# Bolt.new Architecture Guide: Voiceflow Chat Controller

> **Puzzle me this #6**: Today, you are challenged to build a simple app with Bolt.new that lets you control your Voiceflow chat agent using buttons.  
> **The Workflow Requirements**:  
> 1. Trigger specific Voiceflow agent actions when a button is pressed.  
> 2. Show the workflow works by posting screenshots.  
> **The Clue**: *Check Voiceflow’s API docs.*

---

## 1. Executive Summary & Challenge Overview

In modern web experiences, conversational AI agents should not exist in an isolated bubble on the corner of the screen. Instead, high-converting web applications tightly integrate their AI assistants into the page narrative:
- A "Request Custom Quote" button on a pricing table can immediately open the chat agent and initiate the quote collection flow.
- A "Contact Support" link in the navbar can pop up the chat widget without requiring the visitor to search for a floating icon.
- Specialized web applications (support dashboards, kiosk terminals, internal agent workspaces) often require dedicated physical or on-screen controls to trigger intents, reset sessions, or hide the widget entirely.

This challenge tasks us with using **Bolt.new** to construct a sleek, dedicated controller application that interfaces with the **Voiceflow Chat Agent** using external UI buttons, dispatching exact API actions and reflecting state changes in real time.

---

## 2. Decoding the Clue: Voiceflow API Architecture

Voiceflow provides two distinct layers of API access for interacting with your conversational agents:

```mermaid
flowchart TD
    subgraph Browser["User Browser (Bolt.new App)"]
        UI["Chat Controller Buttons (Open, Close, Show, Hide, Trigger)"]
        SDK["window.voiceflow.chat (Webchat JS SDK)"]
        Widget["Voiceflow Webchat Widget (Iframe / Overlay)"]
        UI -->|DOM Events| SDK
        SDK -->|Window Messaging / State| Widget
    end

    subgraph VoiceflowCloud["Voiceflow Cloud Services"]
        Runtime["General Runtime API (Dialog Manager)"]
        KB["Knowledge Base / Agent Model"]
        Widget <-->|Websocket / HTTP Stream| Runtime
        Runtime <--> KB
    end

    subgraph Headless["Headless / Backend Integration"]
        Backend["Node.js / Python / n8n Workflow"]
        Backend -->|"POST /state/user/{id}/interact"| Runtime
    end
```

### Layer A: The Client-Side Webchat Widget SDK (`window.voiceflow.chat`)
The primary tool referenced in the clue for controlling an on-page assistant is Voiceflow's Webchat JavaScript API. Once the webchat snippet is loaded into the page, it exposes a global `window.voiceflow.chat` object with synchronous and async control methods:

| Method | Parameters | Effect on Voiceflow Agent |
| :--- | :--- | :--- |
| **`open()`** | None | Opens the chat overlay window. If the session is new, triggers the initial launch flow. |
| **`close()`** | None | Minimizes the chat window, collapses to the launcher bubble, and interrupts any active TTS audio. |
| **`show()`** | None | Makes the entire widget (including the floating launcher button) visible if previously hidden. |
| **`hide()`** | None | Hides both the launcher icon and the chat window from the DOM viewport. |
| **`interact(action)`** | `{ action: { type, payload } }` | Dispatches an action (such as an intent, plain text query, or custom event) directly into the agent's dialog stack. |
| **`proactive.push(...)`** | `{ type: 'text', payload: { message } }` | Displays a proactive message tooltip next to the launcher icon without opening the full chat window. |
| **`destroy()`** | None | Tears down the widget instance completely and cleans up all active listeners. |

### Layer B: The Headless Dialog Runtime REST API
For backend or server-to-server workflows, Voiceflow exposes the General Runtime API:
```http
POST https://general-runtime.voiceflow.com/state/user/{userID}/interact
Authorization: VF.DM.YOUR_API_KEY
Content-Type: application/json
versionID: production

{
  "action": {
    "type": "intent",
    "payload": {
      "query": "Support Request",
      "intent": { "name": "Get_Support" },
      "entities": []
    }
  },
  "config": {
    "tts": false,
    "stripSSML": true
  }
}
```
This endpoint executes the dialog turn headlessly and returns an array of response traces (`speak`, `text`, `visual`, `choice`, `end`).

---

## 3. The 5 Core Controller Actions Explained

### 1. `Open` (`window.voiceflow.chat.open()`)
- **Visual Result**: The chat overlay slides up or expands into view; the floating launcher button transitions from the chat icon to a chevron/close indicator.
- **Agent Lifecycle**: If the user has not started interacting yet, `open()` can be configured to automatically trigger the conversation's launch event, delivering the welcome message.

### 2. `Close` (`window.voiceflow.chat.close()`)
- **Visual Result**: The chat overlay collapses smoothly back down, leaving only the launcher icon visible.
- **Agent Lifecycle**: Active text-to-speech audio is paused, timeouts are cleared, but session state in memory or localStorage is retained so reopening resumes where the user left off.

### 3. `Show` (`window.voiceflow.chat.show()`)
- **Visual Result**: Restores the widget wrapper (`display: block` / opacity 1), making the floating launcher icon visible on screen.
- **Use Case**: Contextual visibility — revealing the assistant only when the user reaches relevant sections (e.g. checkout or technical documentation).

### 4. `Hide` (`window.voiceflow.chat.hide()`)
- **Visual Result**: Completely hides the launcher and chat window (`display: none`).
- **Use Case**: Eliminating screen clutter during modal presentations, video playback, or checkout payment steps.

### 5. `⚡ Trigger Intent` (`window.voiceflow.chat.interact(...)`)
- **Visual Result**: The specified intent or query is simulated as if the user spoke or typed it, triggering the appropriate dialogue path and generating an immediate assistant reply.
- **Code**:
  ```javascript
  window.voiceflow.chat.interact({
    action: {
      type: 'intent',
      payload: {
        query: 'I need assistance with my account',
        intent: {
          name: 'Account_Help'
        }
      }
    }
  });
  ```

---

## 4. The Exact Bolt.new Master Prompts

When generating this application with Bolt.new, provide these comprehensive, production-grade prompts:

### Prompt 1: The Core Application Architecture

```text
Create a modern, dark-mode web application in Bolt.new that acts as a dedicated external controller for a Voiceflow chat assistant.

UI LAYOUT & STYLING:
- Theme: Premium dark mode with background #0a0e16, frosted glass panels (rgba(30, 41, 59, 0.7)), backdrop blur (16px), and subtle hairline borders.
- Center Stage: A sleek 'Chat Controller' card with:
  1. A rounded-square mint/teal icon with a speech bubble symbol at the top.
  2. Headline: 'Chat Controller', Subtitle: 'Manage your Voiceflow assistant'.
  3. A 2x2 grid of action buttons:
     - 'Open': with an expand arrow icon.
     - 'Close': with a collapse arrow icon (highlight with rose/crimson gradient when active).
     - 'Show': with an eye icon.
     - 'Hide': with an eye-slash icon.
  4. A full-width prominent button below the grid:
     - '⚡ Trigger Intent': with a vibrant amber-to-rose gradient (linear-gradient(90deg, #f59e0b, #ef4444)).
  5. Status list below the buttons:
     - • Chat: displays 'Active' (teal) when open, or 'Closed' (muted).
     - • Launcher: displays 'Visible' (cyan) or 'Hidden' (muted).
  6. Subtitle text at bottom: 'Powered by Voiceflow'.

VOICEFLOW INTEGRATION & RESILIENT FALLBACK:
- Provide dual-mode integration:
  Mode A (Live Voiceflow): Provide an input to load a real Voiceflow projectID using the official script:
  https://cdn.voiceflow.com/widget-next/bundle.mjs
  and wire the buttons directly to window.voiceflow.chat.open(), .close(), .show(), .hide(), and .interact().
  
  Mode B (Built-in Standalone Simulation): When running offline or without an API key, render a faithful interactive replica of the Voiceflow Webchat widget on the right side of the screen matching Voiceflow's branding:
  - Magenta header (#e11d48 / #d946ef) titled 'Starting Template - Webchat' with restart and close icons.
  - Avatar, welcome prompt: 'How can I help you today?', 'Chat has ended' divider, and a 'Start new chat' button.
  - Floating circular launcher button in the bottom right corner.
  - Clicking Open, Close, Show, Hide, and Trigger Intent from the controller seamlessly manipulates this replica with smooth animations.
```

### Prompt 2: API Inspector & Telemetry Console

```text
Add an interactive 'API Telemetry & Action Inspector' drawer to the Voiceflow Chat Controller:
1. Every time any button (Open, Close, Show, Hide, Trigger Intent) is pressed, log the exact event with:
   - Timestamp (HH:mm:ss.SSS)
   - Method name (e.g. window.voiceflow.chat.open())
   - Action payload (JSON format)
   - Target status effect
2. Add a 'Dialog Runtime REST API' tab that displays the equivalent HTTP curl and JavaScript fetch snippets for developers wanting to trigger intents headlessly via POST /state/user/{userID}/interact.
3. Allow the user to customize the intent query and intent name before clicking 'Trigger Intent'.
```

---

## 5. Security & Production Best Practices

1. **Avoid Hardcoding Production API Keys in Client-Side Code**:
   - The Webchat SDK only requires the public `projectID`, which is safe to expose in client HTML.
   - Never expose Voiceflow Dialog API Secret Keys (`VF.DM....`) in frontend client code. Route headless API requests through a secure serverless function or backend proxy.
2. **Session Persistence**:
   - Voiceflow maintains session context using browser `sessionStorage` or cookies by default. If your application switches user accounts, call `window.voiceflow.chat.destroy()` and reload with the new user's credentials or `userID`.
3. **Graceful Loading Guards**:
   - Always verify `window.voiceflow?.chat` exists before dispatching methods:
     ```javascript
     function safelyCallChat(method, ...args) {
       if (window.voiceflow && window.voiceflow.chat && typeof window.voiceflow.chat[method] === 'function') {
         return window.voiceflow.chat[method](...args);
       }
       console.warn(`Voiceflow chat method ${method} not yet loaded`);
     }
     ```

---

## 6. Verification & Acceptance Summary

The application and workflow built for Puzzle #6 fulfill all challenge requirements:
- **Button Control**: Instantaneous programmatic dispatch of `open`, `close`, `show`, `hide`, and `interact`.
- **Accurate Design**: 1:1 reproduction of the controller card and Voiceflow webchat interface shown in the challenge screenshot.
- **Dual Mode**: Runs effortlessly with live Voiceflow agents or zero-config standalone offline simulation.
- **Documented Telemetry**: Live interactive payload log verifying every state change and API call.
