> ## Documentation Index
> Fetch the complete documentation index at: https://docs.waniwani.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Chat embed

> Drop-in chat for any website. The dashboard generates the snippet — you paste it.

The chat embed is a self-contained IIFE bundle that drops the Waniwani chat into any website. It talks directly to `app.waniwani.ai`, so no backend proxy is required on your side.

> [!NOTE]
>
> **Platform feature.** The dashboard generates the embed snippet for your project. [Open app.waniwani.ai](https://app.waniwani.ai) to get yours, or read more about the [Platform](https://docs.waniwani.ai/sdk/platform/overview.md).

## Quick start

1. Open your project on [app.waniwani.ai](https://app.waniwani.ai) and copy the chat embed snippet from the project settings.
2. Paste it into your site's HTML, alongside a mount point where you want the chat to appear:

```html theme={null}
<!-- Where the chat appears, sized by your CSS -->
<div data-waniwani-embed style="height: 600px; max-width: 480px;"></div>

<!-- The <script> tag you copied from the dashboard goes here. -->
```

That's it. The chat mounts inside your marker div via Shadow DOM (so its styles never leak into your page).

The snippet carries identifiers only — your project token, the channel ID, and the API URL. Title, welcome message, placeholder, suggestions, thread history and tool-call display are never baked in: the embed fetches them from your channel at runtime, so changing them in the dashboard updates live sites with no redeploy. Theming is the exception — it has no dashboard equivalent and is set on the tag (`data-theme`) or in CSS. **Don't hand-author the snippet** — the channel ID is issued by the Platform and required for the embed to route correctly.

## Modes

The embed renders in one of four modes, set with `data-mode` on the `<script>` tag:

| Mode | What it does |
| - | - |
| `inline` (default) | Mounts the chat into a `<div data-waniwani-embed></div>` marker on the page. You control the size with CSS or `data-height`. If no marker exists, one is created in front of the `<script>` tag, so a bare snippet works with no markup changes — note that a container we create renders as a centered card (max-width `28rem`, rounded, bordered), while one you place is styled entirely by you. |
| `floating` | Docks a compact composer bar at the bottom center of the viewport. Clicking it expands the bar, and starting a conversation opens the full chat panel — bottom-anchored and width-capped on desktop, full-screen on mobile. No marker element needed. |
| `composer` | Mounts just the input, plus the channel's suggestion pills, into your `<div data-waniwani-embed></div>` marker. Sending the first message (Enter, the send button, or a pill) opens the same panel `floating` uses, over the page. The box is content-height and as wide as its container, so you place it like any other page element. |
| `off` | Mounts no chat at all: no dock, no marker box, no panel. The tag still publishes your site's MCP tools to a browsing agent standing on the page, and `WaniWani.chat.track` / `.identify` still work, so a site can carry the script without showing a widget to its visitors. With the `app.waniwani.ai/embed.js` loader and no `data-agent-beacon`, a browser without WebMCP gets no bundle in this mode, so `track` and `identify` don't exist for that visitor (see [Publish tools without showing the chat](https://docs.waniwani.ai/sdk/chat/webmcp.md#publish-tools-without-showing-the-chat)). The chat methods (`open()`, `sendMessage()`, …) become no-ops and no `page.viewed` event fires. |

Use `inline` when the chat is the page section. Use `floating` when it should be available everywhere without taking up layout space. Use `composer` for a search-box entry point inside your own layout (a hero, a help-center header, a row under a pricing table), where a full chat panel takes too much room and a corner bubble is too easy to miss. Use `off` when you want the tag's non-chat behavior on a page that should look untouched: publishing tools to browsing agents, or host-page tracking, with nothing on screen.

```html theme={null}
<!-- Inline: the chat lives in your layout -->
<script src="…/embed.js" data-token="wwp_..." data-channel-id="..." defer></script>

<!-- Floating: a docked composer bar at the bottom of the viewport -->
<script src="…/embed.js" data-token="wwp_..." data-channel-id="..." data-mode="floating" defer></script>

<!-- Composer: an input in your layout that opens the panel on send -->
<div data-waniwani-embed style="max-width: 560px; margin: 0 auto;"></div>
<script src="…/embed.js" data-token="wwp_..." data-channel-id="..." data-mode="composer" defer></script>

<!-- Off: the script runs, the page shows nothing -->
<script src="…/embed.js" data-token="wwp_..." data-channel-id="..." data-mode="off" defer></script>
```

In `composer` mode the panel is appended to `<body>` rather than nested in your marker, so a `transform` or `filter` on an ancestor of the marker can't drag the fixed panel out of position. Give the marker whatever width and margins your layout needs; `data-height` and the `500px` inline default don't apply. The conversation survives closing the panel: clicking the box again reopens it with the history intact.

### Modal or sidebar

In `floating` and `composer` mode, the first message opens the chat panel. `data-panel-layout` sets its shape. On the channel's Integrate tab, the **Chat panel** field writes it into the snippet for you.

| Layout | What opens |
| - | - |
| `modal` (default) | A card centered over the page, up to `--ww-panel-width` wide and `--ww-panel-height` tall. |
| `sidebar` | A full-height column on the right edge of the window, `--ww-sidebar-width` wide (`440px` by default). It slides in over the page, and your layout does not move. |

```html theme={null}
<!-- The floating bar opens a sidebar -->
<script src="…/embed.js" data-token="wwp_..." data-channel-id="..." data-mode="floating" data-panel-layout="sidebar" defer></script>

<!-- The in-page box opens a sidebar -->
<div data-waniwani-embed style="max-width: 560px; margin: 0 auto;"></div>
<script src="…/embed.js" data-token="wwp_..." data-channel-id="..." data-mode="composer" data-panel-layout="sidebar" defer></script>
```

The sidebar opens on send, the same as the modal, and the close button slides it out again. Below 640px both layouts open the full-screen sheet. `inline` and `off` mode open no panel, so they ignore the attribute.

Give the sidebar a different width in CSS:

```css theme={null}
:root {
  --ww-sidebar-width: 480px;
}
```

### Let visitors dock the panel

`data-panel-dockable="true"` adds a button to the panel header that moves the open panel between the modal and the sidebar. The visitor chooses; `data-panel-layout` is only where it starts. The choice holds for as long as the page is open, so closing and reopening the panel brings it back where the visitor left it. Below 640px both layouts are the full-screen sheet, so the button changes nothing visible there until the window widens. Off by default: without the attribute the header is unchanged.

```html theme={null}
<!-- Opens centered, the visitor can park it on the right -->
<script src="…/embed.js" data-token="wwp_..." data-channel-id="..." data-mode="floating" data-panel-dockable="true" defer></script>
```

The button is the `.ww-layout-toggle` part and carries `data-layout="modal"` or `"sidebar"`, so your `data-css` file can swap its icon per state. Its labels are the `launcher.toSidebar` and `launcher.toModal` wording keys. A click emits the `panel.layout.changed` event on `onEvent`. To turn the docked state into a smaller card instead of a full-height column, restyle it:

```css theme={null}
@media (min-width: 640px) {
  .ww-panel[data-layout="sidebar"] {
    top: auto;
    bottom: var(--ww-panel-offset);
    right: var(--ww-panel-offset);
    height: var(--ww-panel-height);
    max-height: calc(100dvh - var(--ww-panel-offset) * 2);
    border-radius: var(--ww-panel-radius);
    border-width: 1px;
  }
}
```

If you want React-component-level control over the inline mount, see [Chat in React](https://docs.waniwani.ai/sdk/chat/react.md).

## Sizing

Inline mode only. In `floating` mode the panel sizes itself, and in `composer` mode the box is content-height inside a container you size.

The embed fills its container. Give the `<div data-waniwani-embed>` a definite size via CSS, or set `data-height` on the script tag:

```html theme={null}
<!-- Fixed height -->
<div data-waniwani-embed style="height: 600px;"></div>

<!-- Bounded by max-height -->
<div data-waniwani-embed style="max-height: 80vh;"></div>

<!-- Flex column child -->
<div style="display: flex; flex-direction: column; max-height: 800px;">
  <div data-waniwani-embed style="flex: 1 1 auto; min-height: 0;"></div>
</div>
```

A container you leave unstyled is `500px` tall. That default is written with `:where()`, so it carries no specificity and any rule you write beats it — including `height: auto` to let the chat grow with its content. A `ResizeObserver` mirrors the container's `max-height` onto the embed so padding and borders are respected.

## Overriding attributes

You can edit `data-*` attributes on the `<script>` tag to tweak behavior. Do it sparingly: an attribute set here permanently outranks the channel config the embed fetches from the dashboard (resolution order is dashboard → `data-*` → `init()`), so a title pinned on the tag can no longer be changed by whoever owns the channel.

| Attribute | Type | Notes |
| - | - | - |
| `data-mode` | string | `"inline"` (default), `"floating"`, `"composer"`, or `"off"`. See [Modes](#modes). |
| `data-height` | string | Height of the inline container. Any CSS length (`"500px"`, `"80vh"`) or a bare number treated as px. Defaults to `500px`. Ignored in `floating` and `composer` mode. |
| `data-title` | string | Header title. No default — with no title (and no thread history) the chat renders headerless. |
| `data-hide-header` | boolean | Force-hide the sticky header when your page already provides its own chrome. |
| `data-welcome-message` | string | Greeting shown before the first message. |
| `data-placeholder` | string | Input field placeholder. |
| `data-suggestions` | string (comma-separated) | Initial suggestion chips. |
| `data-suggestion-origins` | string (comma-separated) | Which providers may fill the per-turn pill row: any of `"channel"`, `"page"`, `"flow"`, `"followup"`. Defaults to `"channel,page,followup"` — include `"flow"` to render pills from a flow's `interrupt({ suggestions })`. An empty value renders none. Initial chips (`data-suggestions`) show either way. |
| `data-enable-thread-history` | boolean | Persist threads in IndexedDB. Defaults to `false`. |
| `data-locale` | string | UI language for built-in labels: `"en"`, `"fr"`, `"es"`. Defaults to detecting from `<html lang>` / `navigator.language`, falling back to English. |
| `data-disclaimer` | string \| `"false"` | AI transparency notice under the input (EU AI Act). A string overrides the default wording; `"false"` (or `"0"`) hides it. A `[label](https://…)` in the string renders as a link that opens in a new tab. |
| `data-css` | string | URL to a custom stylesheet loaded into the shadow root. Targets the stable `.ww-*` classes — see [Theming](https://docs.waniwani.ai/sdk/chat/theming.md). |
| `data-theme` | string | `"light"` (default), `"dark"`, or `"auto"` (follows `prefers-color-scheme`). |
| `data-assistant-bubble` | boolean | Render assistant replies in a filled, themeable bubble. Defaults to `false` (plain text). |
| `data-visitor-id` | string | Override the anonymous visitor id with one you already track (a PostHog / Amplitude / Segment distinct id, your own cookie). See [Link visitors to your analytics](#link-visitors-to-your-analytics). |
| `data-show-tool-calls` | boolean \| `"titles-only"` | `true` (default) makes each step expandable to its request/response JSON, `"titles-only"` shows step labels, `false` hides the chain and reasoning trace. |
| `data-disable-page-view` | boolean | Opt out of the `page.viewed` event fired once on mount. Set on surfaces where a page view would pollute the funnel (internal tools, previews, authenticated app shells). |
| `data-agent-beacon` | boolean | Report page views that show browser automation to your site's agent traffic. Off by default; `"on"`, `"true"`, `"1"` or the bare attribute turns it on. See [Agent traffic beacon](#agent-traffic-beacon). |

Look and feel. Each one is covered in depth in [Theming & customization](https://docs.waniwani.ai/sdk/chat/theming.md):

| Attribute | Type | Notes |
| - | - | - |
| `data-messages` | JSON | Replaces built-in strings: the loader text, menu entries, the restart dialog, the toast. Flat, or keyed by locale (`{"fr": {…}}`). Single-quote the attribute. See [Wording](https://docs.waniwani.ai/sdk/chat/theming.md#wording). |
| `data-messages-url` | string | URL of a JSON file with the same shape as `data-messages`. Fetched without credentials, so a file on another origin needs CORS headers. The chat waits up to 600 ms for it before it shows. Inline `data-messages` wins key by key. |
| `data-avatar` | string | URL of the assistant's avatar image. An animated SVG or GIF works, since it renders as an `<img>`. |
| `data-avatar-slots` | string (comma-separated) | Where the avatar shows: any of `welcome`, `header`, `message`, `composer`, `dock`. Defaults to `welcome,header` when `data-avatar` is set. |
| `data-avatar-intro` | string | URL of an animated image (GIF, animated WebP, APNG) that plays in place of the avatar once per slot and page load, then gives way to `data-avatar`. Never plays in the `message` slot, nor under `prefers-reduced-motion: reduce`. The image carries `data-intro="true"` while it plays. |
| `data-avatar-intro-duration` | number | How long `data-avatar-intro` plays, in milliseconds from the moment it loads. Defaults to `7000`. Match it to the animation's length, since a looping GIF or WebP cannot signal its end. |
| `data-welcome-title` | string | Shows the structured welcome (avatar, title, subtitle, the channel's suggestions as chips) in place of the `data-welcome-message` bubble while the conversation is empty. A `\|` starts a new line. |
| `data-welcome-subtitle` | string (`\|`-separated) | Subtitle under the welcome title. Give several to rotate them. |
| `data-welcome-subtitle-rotate` | number | Milliseconds between two subtitles. Unset or `0` keeps the first one. |
| `data-suggestions-layout` | string | `"wrap"` (default) or `"single-row"`, which keeps the pill row on one line and clips the rest. |
| `data-suggestions-position` | string | `"above-input"` (default) or `"after-message"`, which shows the follow-up pills under the last answer, inside the thread. |
| `data-send-icon` | string | Arrow on the send button: `"up"` (default) or `"right"`. Swap it for any other icon in CSS on `.ww-send`. |
| `data-menu` | string (comma-separated) | Header menu entries, in order: any of `new-chat`, `restart`, `copy-conversation`, `history`, `delete`. When set, one menu replaces the New chat and thread history buttons. `history` and `delete` act on stored threads, so they only do something with `data-enable-thread-history`. |
| `data-restart-confirm` | boolean | Ask before the menu's `restart` clears the conversation. With `copy-conversation` in the menu, the dialog offers "Copy and clear" and "Clear without copying". Defaults to `false`. |
| `data-show-table-toolbar` | boolean | `false` hides the copy and download toolbar above tables in answers. Defaults to `true`. |

Floating and composer modes:

| Attribute | Type | Notes |
| - | - | - |
| `data-launcher-text` | string | Placeholder for the entry input: the docked bar in `floating` mode, the in-page box in `composer` mode (e.g. `"Ask anything…"`). Falls back to `data-placeholder`, then to a localized prompt. The in-panel input keeps `data-placeholder`. |
| `data-panel-layout` | string | Shape of the panel that the first message opens: `"modal"` (default) or `"sidebar"`. See [Modal or sidebar](#modal-or-sidebar). |
| `data-panel-dockable` | boolean | Adds a header button that lets the visitor move the panel between the modal and the sidebar. Off by default. See [Let visitors dock the panel](#let-visitors-dock-the-panel). |
| `data-appear-delay` | number | Floating only. Milliseconds before the dock animates in, letting the page settle first. Defaults to `2000`. `0` shows it immediately. A `composer` box is page content and renders with the page. |

Floating mode only. These shape the docked bar:

| Attribute | Type | Notes |
| - | - | - |
| `data-dock-chips-trigger` | string (comma-separated) | When the bar's suggestion chips show. `hover` (default) expands them a second after the bar appears, and on focus. `scroll` shows them after the visitor scrolls down and pauses in a page section, once per section. `always` keeps them out from the start. Combine triggers with a list such as `hover,scroll`: the first to fire wins. See [Section prompts](#section-prompts-on-the-floating-bar). |
| `data-dock-click` | string | What a click on the bar's input does before any conversation exists. `"expand"` (default) widens the bar and shows the chips; `"open"` opens the panel straight away. |
| `data-dock-pointer-vars` | boolean | Writes `--ww-pointer-x` and `--ww-pointer-y` (px, relative to the bar) on `.ww-dock` while the pointer moves over it, for a light that follows the cursor in your CSS. Defaults to `false`. |
| `data-dock-glow` | boolean | `false` renders the field without its animated border glow. Defaults to `true`. |
| `data-dock-readonly-mobile` | boolean | On phones, the bar's input is read-only, so a tap opens the panel without raising the keyboard. Defaults to `false`. See [On phones](#floating-mode-on-phones). |
| `data-panel-history` | boolean | On phones, holds one browser history entry while the panel is open, so the back gesture closes the panel instead of leaving the page. Defaults to `false`. See [On phones](#floating-mode-on-phones). |

Composer mode only. The box sits in your layout, so its chrome is adjustable:

| Attribute | Type | Notes |
| - | - | - |
| `data-composer-variant` | string | `"glow"` (default) or `"outline"`. See [Composer variants](#composer-variants). |
| `data-composer-size` | string | `"sm"`, `"md"` (default), or `"lg"`. Moves padding, type scale, and the send button together. |
| `data-composer-suggestions` | boolean | Render the channel's suggestion pills under the box. Defaults to `true`. |
| `data-composer-align` | string | `"start"` (default) or `"center"`. Centers the pills, and the label when the composer renders as a trigger. |
| `data-composer-trigger` | boolean | Render the box as a tap target instead of a live input, at every width. Defaults to `false`. See [Trigger instead of an input](#trigger-instead-of-an-input). |
| `data-composer-mobile-trigger` | boolean | On phone-width viewports, render the box as a tap target instead of a live input. Defaults to `true`. See [On mobile](#on-mobile). |

### Composer variants

Every variant behaves the same: the first message opens the panel. Only the chrome differs.

| Variant | Looks like | Reach for it when |
| - | - | - |
| `glow` | Filled box on a card shadow, with a one-off colored border sweep once the config resolves. | The composer is the page's main call to action and should pull the eye. |
| `outline` | The same box without the sweep. | It sits inside a card or a form that already has its own chrome. |

Two, because a variant is a starting point rather than the ceiling. Radius, fill, border, shadow and the send button are CSS custom properties, so a fully rounded search bar is one declaration rather than a third variant. See [Restyling with CSS](#restyling-with-css).

### Trigger instead of an input

`data-composer-trigger="true"` renders the box as a tap target: nothing is typed in the page, and a click opens the panel where the caret lands. For a host that wants one tap into the full chat and no in-page composing.

The box keeps its variant and whatever CSS you set on it — only the textarea is swapped for the trigger. It is the same swap [On mobile](#on-mobile) applies automatically below 640px; this option applies it at every width.

```html theme={null}
<script
  src="…/embed.js"
  data-token="wwp_..."
  data-channel-id="..."
  data-mode="composer"
  data-composer-variant="outline"
  data-composer-size="lg"
  defer
></script>
```

### Restyling with CSS

The box reads its fill, border, radius, shadow and send button from `--ww-composer-*` custom properties. Set them wherever you set the rest of the widget's variables (`[data-waniwani-embed]` works, and so does `:root`); they inherit through the widget's Shadow DOM. Anything you leave alone keeps the variant's own value.

| Variable | Default | Controls |
| - | - | - |
| `--ww-composer-bg` | `var(--ww-color-input)` | Box fill. |
| `--ww-composer-radius` | 12 / 16 / 20px by size | Corner radius. |
| `--ww-composer-border-color` | `var(--ww-color-border)` | Border color. |
| `--ww-composer-border-width` | `1px` | Border width. Takes the full `border-width` shorthand, so `0 0 1px 0` leaves only a rule underneath. |
| `--ww-composer-shadow` | the theme's `--ww-shadow` | Box shadow. |
| `--ww-composer-send-bg` | `var(--ww-color-foreground)` | Send button fill. |
| `--ww-composer-send-fg` | `var(--ww-color-background)` | Send arrow. |

A flat box with a single rule under it:

```css theme={null}
[data-waniwani-embed] {
  --ww-composer-bg: transparent;
  --ww-composer-radius: 0;
  --ww-composer-shadow: none;
  --ww-composer-border-width: 0 0 1px 0;
}
```

A fully rounded search bar:

```css theme={null}
[data-waniwani-embed] {
  --ww-composer-radius: 9999px;
  --ww-composer-shadow: none;
}
```

A tinted box with a branded send button:

```css theme={null}
[data-waniwani-embed] {
  --ww-composer-bg: #eef2ff;
  --ww-composer-border-color: #c7d2fe;
  --ww-composer-send-bg: #4f46e5;
  --ww-composer-send-fg: #ffffff;
  --ww-composer-shadow: none;
}
```

Text color, placeholder color, and the font come from the widget-wide variables in [Theming & customization](https://docs.waniwani.ai/sdk/chat/theming.md), not from a composer-specific one.

### On mobile

Below 640px the composer renders as a tap target rather than a live input, whatever variant you picked. One tap opens the panel, which is already a full-screen sheet at that width, and the visitor types there.

This is the default because in-page typing on a phone is the worse half of the handoff: the soft keyboard covers the box, the first message opens a full-screen panel over it, and focus has to move mid-sentence. Going straight to the panel skips all of it.

The box keeps its variant and whatever CSS you set on it; only the textarea is swapped out. Set `data-composer-mobile-trigger="false"` to keep a real input at every width.

### Section prompts on the floating bar

With `data-dock-chips-trigger="scroll"` (alone or in a list), the bar can show different chips for each part of a long page. The prompts come from your channel's per-page prompts in the dashboard:

* An entry whose URL ends in a `#fragment`, such as `https://your.site/#pricing`, belongs to the section with that `id`.
* When the visitor scrolls down and pauses, the bar reads the section at the centre of the viewport (the closest `<section>` or element with an `id`) and shows the matching entry's chips, once per section.
* Anywhere else on the page, the bar uses the page's entry without a fragment, else the first entry for the page, else the channel's general suggestions.

The pause lasts one second on desktop and two and a half on phones, where a pause is often a thumb lifting between two flicks.

### Floating mode on phones

Below 640px the panel is a full-screen sheet. It fills the space above the soft keyboard and follows it as it opens and closes, so the header and the input stay in view. While the sheet is open your page can't scroll behind it, and the visitor's scroll position comes back when it closes. On a touch keyboard, Return adds a line and the send button sends. While the keyboard is up, the line under the input (the powered-by mark and `data-disclaimer`) is hidden, so the input sits right on the keyboard. The line comes back when the keyboard closes.

Two behaviours can be switched on there:

* **No keyboard on the first tap** (`data-dock-readonly-mobile="true"`). The bar's input is read-only, so a tap opens the panel and the visitor types in it. By default the visitor types in the bar itself.
* **The back gesture closes the panel** (`data-panel-history="true"`). While the panel is open the widget holds one entry in the browser history, so back closes the panel instead of leaving the page. Closing the panel any other way removes the entry, and your page's own history state is kept.

Programmatic callers pass the same options as an object:

```js theme={null}
WaniWani.chat.init({
  mode: "composer",
  panelLayout: "sidebar",
  composer: { variant: "outline", size: "lg", showSuggestions: false },
});
```

Per-URL show/hide rules are configured in the dashboard, not on the script tag. They gate every mode; in `inline` and `composer` mode the marker div collapses too, so a hidden page shows no empty box. In `off` mode there is nothing to gate.

Leave the wiring attributes (`data-token`, `data-channel-id`, `data-api`, the script `src`) as the dashboard generated them.

Beyond the attributes above, individual colors, fonts, sizes and shapes have no `data-*` equivalent: set `--ww-*` CSS variables instead, and restyle elements through their `ww-*` part classes in a `data-css` file. They inherit through the widget's Shadow DOM, so declare them on `[data-waniwani-embed]` in inline or composer mode, or anywhere on the host page (`:root` works) in floating mode, where there is no container of your own. See [Theming & customization](https://docs.waniwani.ai/sdk/chat/theming.md) for the full variable list and deep-customization recipes.

Full type definitions: [`EmbedConfig`](https://github.com/WaniWani-AI/sdk/blob/main/packages/chat/src/embed/config.ts) and [`ChatTheme`](https://github.com/WaniWani-AI/sdk/blob/main/packages/chat/src/%40types.ts).

## Programmatic init

For runtime control (computing options dynamically, mounting on demand), drop the `data-token` attribute from the script tag and call `init()` manually. You still need the wiring attributes from a dashboard-issued snippet:

```html theme={null}
<div data-waniwani-embed></div>

<!-- Load the bundle itself, so window.WaniWani exists on DOMContentLoaded.
     Keep data-channel-id from the dashboard snippet, and leave out
     data-token so the embed doesn't auto-init. -->
<script
  src="https://cdn.jsdelivr.net/npm/@waniwani/chat@1/dist/embed.js"
  data-channel-id="..."
  defer
></script>
<script>
  window.addEventListener("DOMContentLoaded", () => {
    window.WaniWani.chat.init({
      token: "wwp_...", // from the dashboard snippet
      welcomeMessage: computeGreetingForUser(),
    });
  });
</script>
```

`init()` returns an instance that carries the same methods as the `window.WaniWani.chat` global, listed in [Control the chat from your page](#control-the-chat-from-your-page).

`init()` also accepts an `onEvent` callback that mirrors chat lifecycle events (opens, messages, errors, link clicks) into your own analytics — Amplitude, Segment, gtag — with your page's identity attached automatically. See [Widget events (onEvent)](https://docs.waniwani.ai/sdk/chat/widget-events.md).

## Control the chat from your page

Once the script has loaded, `window.WaniWani.chat` drives the chat from anywhere on your page. Call it from your own buttons, links or router events to open the panel without going through the chat bar, or to ask a question on the visitor's behalf.

```html theme={null}
<button type="button" id="open-chat">Talk to an advisor</button>
<button type="button" id="ask-rate">What rate can I get?</button>

<script>
  document.getElementById("open-chat").addEventListener("click", () => {
    window.WaniWani?.chat?.open();
  });

  document.getElementById("ask-rate").addEventListener("click", () => {
    // Opens the panel, then sends the question as the visitor's message
    window.WaniWani?.chat?.sendMessage("What rate can I get?");
  });
</script>
```

The embed script loads with `defer`, so the optional chaining (`?.`) keeps a click that lands before it has run from throwing.

| Method | What it does |
| - | - |
| `open()` | Opens the full chat panel. No-op in `inline` mode, where the chat is already on screen. |
| `close()` | Closes the panel, back to the docked bar in `floating` mode or the in-page box in `composer` mode. The conversation is kept. |
| `toggle()` | Opens the panel when it's closed and closes it when it's open. |
| `sendMessage(text)` | Sends `text` as the visitor's message. In `floating` and `composer` mode it opens the panel first. |
| `sendMessageAndWait(text)` | Same as `sendMessage`, and returns a promise that resolves with the assistant's final message once it has finished streaming. |
| `focus()` | Puts the caret in the chat input. In `floating` mode it opens the panel first. In `composer` mode it focuses the in-page box while the panel is closed. |
| `reset()` | Clears the conversation and starts a new one. |
| `restart()` | Clears the conversation without the confirmation dialog, and fires `conversation.restarted`. |
| `copyConversation()` | Copies the conversation to the clipboard as plain text: a header line with the date and your site, then "You:" and "Assistant:" blocks. Resolves `true` on success and fires `conversation.copied`, `false` when the browser refuses. |
| `getMessages()` | The conversation so far. Empty until the chat has loaded. |
| `getSessionId()` | The chat session id, `undefined` until the first message. |
| `track` / `identify` | Host-page tracking with the chat session attached. See [Widgets & chat](https://docs.waniwani.ai/sdk/tracking/widgets.md). |
| `setVisitorId(id)` / `getVisitorId()` | See [Link visitors to your analytics](#link-visitors-to-your-analytics). |
| `init(options)` / `destroy()` | Mount and unmount the chat. See [Programmatic init](#programmatic-init). |

> [!NOTE]
>
> Calling these methods doesn't bypass the per-URL show/hide rules set in the dashboard. On a page the rules hide, `open()` and `sendMessage()` show nothing, so the rules have to show the chat on every page that carries one of your buttons.

A message sent before the chat has loaded its channel config is dropped. Wire `sendMessage()` to a visitor's click, which lands after the load, rather than calling it from a page-load script.

To react when the visitor opens or closes the panel themselves (hiding your own button while the panel is up, say), listen for `chat.opened` and `chat.closed` in the `onEvent` callback. See [Widget events (onEvent)](https://docs.waniwani.ai/sdk/chat/widget-events.md).

`restart()` and `copyConversation()` let you wire your own "Start over" and "Copy" buttons, with the same effect as the header menu's entries (`data-menu`). The menu fires the same `conversation.restarted` and `conversation.copied` events.

```js theme={null}
document.getElementById("copy-chat").addEventListener("click", async () => {
  const copied = await window.WaniWani?.chat?.copyConversation();
  if (!copied) showMyOwnError();
});
```

## The page the visitor is on

From SDK 0.24.1, the chat sends the address of the page the visitor is on with every message, and Waniwani tells your agent about it. Someone who asks "how much would this cost me?" on your pricing page gets an answer about that page without having to say where they are.

There is nothing to switch on. If you load a pinned SDK bundle yourself, use `@waniwani/sdk` 0.24.1 or later.

The agent gets the address and nothing else from the page. It doesn't see the page's text, its forms, or what the visitor typed into them. So tell the agent what your pages are: a line in its system prompt such as "`/simulator` is the loan simulator, `/rates` lists today's rates", or the pages' content in its knowledge base.

* **The full address is sent**, including everything after `?` and `#`. Keep personal data such as email addresses out of your URLs.
* **Only web pages count.** An address that doesn't start with `http://` or `https://`, or is longer than 2,048 characters, is dropped, and the agent is told nothing about the page.
* **It follows single-page apps.** The address is read when each message is sent, so it stays right after in-app navigation.

## Link visitors to your analytics

By default the embed mints its own anonymous **visitor id**, a stable opaque value persisted in the browser's `localStorage`. It rides on every chat request and tracking event, so a visit is attributable before the first message mints a session (see [Sessions](https://docs.waniwani.ai/sdk/tracking/sessions.md)).

If your site already tracks visitors with PostHog, Amplitude, Segment, or a first-party cookie, override that id with your own. Waniwani then correlates its sessions and events to the same visitor you see in your analytics, and your server-side MCP tools and flows read the id back as `context.waniwani.visitorId`, so they can send events straight to the same analytics tool the id came from.

There are three ways to set it. Pick the one that matches when your id is available.

### If you know the id up front

Set it declaratively on the script tag:

```html theme={null}
<script
  src="https://app.waniwani.ai/embed.js"
  data-token="wwp_..."
  data-channel-id="..."
  data-visitor-id="the-id-from-your-system"
  defer
></script>
```

Or pass it to `init()` when you initialize programmatically. `init()` accepts a string or a resolver (sync or async), so you can read the id inline:

```js theme={null}
window.WaniWani.chat.init({
  token: "wwp_...",
  visitorId: "the-id-from-your-system",
  // or a resolver: visitorId: () => posthog.get_distinct_id(),
});
```

### If the id resolves asynchronously (the common case)

Analytics SDKs usually assign a distinct id only after they bootstrap, so read it when it's ready and hand it to the widget. `setVisitorId()` is safe to call at any time, before or after `init()`, and the new id applies to the next chat request and tracking event:

```js theme={null}
// PostHog
posthog.onFeatureFlags(() => {
  window.WaniWani.chat.setVisitorId(posthog.get_distinct_id());
});

// Amplitude
const amplitudeId = amplitude.getDeviceId();
if (amplitudeId) {
  window.WaniWani.chat.setVisitorId(amplitudeId);
}
```

A blank value is ignored, so an id that isn't ready yet never wipes a good one. Read the id the widget will send with `window.WaniWani.chat.getVisitorId()`.

> [!NOTE]
>
> The visitor id identifies a **device / browser**, not a signed-in account. When a visitor logs in, keep the visitor id and additionally call [`identify()`](https://docs.waniwani.ai/sdk/tracking/identify) with your account id, so anonymous and known activity stitch together.

## Agent traffic beacon

The embed can tell your site's agent traffic when an AI agent drives a browser on the page. It is off by default while we measure it; turn it on with `data-agent-beacon="on"` or `init({ agentBeacon: true })`. It runs in every mode, `off` included, so you can use it with no chat on the page.

The beacon watches for signs of automation: the WebDriver flag, a headless browser, the globals that Playwright, Selenium and ChromeDriver leave, and input no person makes (script-made events, a click with no mouse movement, a pointer that jumps to its target). Only when one of these fires, it sends one small report to Waniwani with:

* the names of the signals it saw
* the page URL without its query string, and the referrer's origin and path
* the time since the page started loading

It sends no cookie, stores nothing in the browser, and reads no device details. The request goes out with credentials omitted, so it cannot be tied to anyone signed in to Waniwani. When your site also sends its request logs to Waniwani (for example the Vercel log drain), the report joins the logged request, so a page view counts once.

## Self-hosting the JS bundle

If you'd rather not load from a CDN, pin a specific `@waniwani/chat` version and serve the bundled file yourself. The `data-*` attributes still come from the dashboard snippet — you're only swapping where `embed.js` is served from:

```bash theme={null}
bun add @waniwani/chat
cp node_modules/@waniwani/chat/dist/embed.js public/waniwani-embed.js
```

Then point the dashboard-issued snippet at your local copy:

```html theme={null}
<div data-waniwani-embed></div>
<script
  src="/waniwani-embed.js"
  data-token="wwp_..."
  data-channel-id="..."
  defer
></script>
```

## How it works

1. The script reads its own `data-*` attributes (token, channel ID, mode, theming, content overrides).
2. On `DOMContentLoaded` (or immediately, if the DOM is already ready), it mounts the chat via Shadow DOM — inside `[data-waniwani-embed]` in `inline` and `composer` mode, or in its own anchored container in `floating` mode. `composer` mode adds a second, `<body>`-level container for the panel.
3. The chat calls `app.waniwani.ai/api/mcp/chat` with the project token and streams responses back through Server-Sent Events.
4. Conversation history lives only in memory by default; set `data-enable-thread-history` to persist threads in IndexedDB on the user's device.

No server-side integration on your side.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.