# Configuration

> Every option by group, with examples.

Every option you can pass to `init(...)` / `mount(...)` / set via
`data-*` attributes / set via web-component attributes.

Group-by-group walkthrough with realistic examples. For an at-a-glance
lookup, see [API reference](/sdk/api-reference).

---

## How options arrive

Options resolve in this order (highest priority wins):

1. **Options you pass to `init()`** — always win.
2. **Server-pushed settings** — your Help AI dashboard settings for this
   deployment. Fill in anything you left unset.
3. **Built-in defaults** — sensible fallbacks shipped with the widget.

This means you can:

- Hardcode `publicKey` in code, tune the rest from the dashboard.
- Ship all config in `init()` and ignore the dashboard.
- Override a specific field (e.g., force `theme: "dark"`) while letting
  the dashboard control everything else.

### Canonical option shape

Embed identity, routing, context, endpoint overrides, storage, and callbacks stay
at the top level. Serializable widget settings are grouped by ownership:

| Section        | Fields described in this guide                                                       |
| -------------- | ------------------------------------------------------------------------------------ |
| `presentation` | `mode`, `iframe`, `position`, `size`                                                 |
| `behavior`     | `startMinimized`, `responseMode`, transcript visibility, feedback, suggestion policy |
| `header`       | `actions`                                                                            |
| `composer`     | `sendButton`, `attachments`                                                          |
| `feedback`     | `sound`, `haptics`                                                                   |
| `i18n`         | `locale`, `defaultLocale`, `availableLocales`, `strings`                             |
| `footer`       | `composerDisclaimer`, `poweredBy`                                                    |

The flat HTML attributes remain intentionally short (`data-mode`, `data-actions`,
and so on); the attribute parser maps them into this nested JavaScript shape.

---

## Required

### `publicKey`

`string` · required for authenticated browser deployments

Your deployment's public key from the Help AI dashboard. Looks like
`agent_pk_...`.

```ts
init({ publicKey: 'agent_pk_abc123...', aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000' });
```

The public key authorizes the public widget surface. Pair it with that same
deployment's `aiAgentDeploymentId`; the backend requires both values to match.
Intentional guest mode omits the key but still supplies the deployment ID.
There is no per-end-user token — see
[`userContext`](#usercontext) below.

### `aiAgentDeploymentId`

`string` · required for browser deployments

The deployment UUID from the same Dashboard → Deployments install panel as the
public key. It selects the exact agent/configuration and acts as a
defense-in-depth match for authenticated mounts. Send it on every browser
mount; also send the public key unless guest mode is intentional.

---

## Identity + routing

### `widgetId`

`string` · default: `"default"`

A name you pick for this widget instance. Matters when you run more
than one widget on a page — each widgetId gets its own chat thread,
settings, and storage.

```ts
init({ widgetId: 'support', publicKey: SUPPORT_KEY, aiAgentDeploymentId: SUPPORT_DEPLOYMENT_ID });
init({ widgetId: 'sales', publicKey: SALES_KEY, aiAgentDeploymentId: SALES_DEPLOYMENT_ID });
```

See [Recipes § Multiple widgets](/sdk/recipes#multiple-widgets-on-one-page).

### `baseUrl`

`string` · default: `https://help.ai`

The MAIN site origin the widget calls — the API modules derive from it
(agent API at `${baseUrl}/api/agent`, data API at `${baseUrl}/api/data`).
Override if you use:

- A custom domain (`your-company.com`).
- A local dev backend.

### `userToken`

`string | () => string | Promise<string>` · default: none (anonymous)

Signs the visitor in as your logged-in user: a JWT your server signs with the deployment's secret key, or a function
returning a fresh one. Their conversations then follow them to any device, and the AI gets their name and email as
verified facts. Runtime-only: not an attribute or `data-*` option, so the token stays out of the page's markup. See
[Security → Verified users](/sdk/security-privacy#verified-users-usertoken) for signing it.

```ts
init({ publicKey: 'agent_pk_...', aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000', userToken: () => fetch('/api/help-ai-token').then((res) => res.text()) });
```

### `tools`

`ModelContextTool[]` · default: none

Tools the AI agent can use on your page, in the WebMCP tool shape: a name, a description, a JSON Schema of its input
and an `execute` function the widget runs in the visitor's browser when the agent calls it
(`annotations: { consequentialHint: true }` asks the visitor first). Runtime-only, like `userToken`;
`chat.update({ tools })` replaces them. `chat.registerTool(tool)` adds one for every widget on the page instead. Full
guide: [Page tools](/sdk/page-tools).

```ts
init({
  publicKey: 'agent_pk_...',
  aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000',
  tools: [{ name: 'open_booking', description: 'Open the booking form. Use it whenever the visitor wants to book a call.', execute: () => (bookingForm.open(), { opened: true }) }],
});
```

### `userContext`

`object | undefined`

Host-asserted information about the end user, passed to the AI as
**context only — never an authentication credential.** The backend does
not register or authenticate these users. Optional — omit it for
anonymous chats. Recommended for logged-in users so the AI has context.

```ts
init({
  publicKey: 'agent_pk_...',
  aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000',
  userContext: {
    id: 'user_42', // your user id
    email: 'jane@help.ai',
    name: 'Jane Doe',
    plan: 'pro',
    role: 'admin',
    phone: '+15551234567',
    seats: 12, // arbitrary custom scalar field
  },
});
```

A flat object. Recognised fields (all optional):

- `id` — your user's stable identifier.
- `email` — for personalization.
- `name` — for personalization (also drives the Home tab greeting,
  e.g. "Hi Jane 👋").
- `plan` — subscription / pricing tier (e.g. `"pro"`).
- `role` — the user's role on your site (e.g. `"admin"`).
- `phone` — phone number.

Plus any arbitrary custom scalar fields (`string | number | boolean`) —
account age, feature flags, etc.

Because this is untrusted external input, it is sanitized client-side
before it leaves the page: non-scalar values are dropped, reserved keys
(`visitorId`, `conversationId`, `conversationId`, `jwt`, `token`, `authorization`,
`password`) are stripped, a malformed `email` is dropped, strings are
trimmed and capped at 1024 chars, max 50 keys. Sanitization warns to the
debug log and never throws.

> **This is YOUR site's logged-in user — not the widget's own visitor.**
> The widget independently mints and persists an anonymous
> `visitorId` / `conversationId` for the device; `userContext` never overrides
> those. Setting `userContext` simply attaches your context to the same
> visitor.

### `pageContext`

`object | undefined`

Host-asserted context about the page/visit (separate from `userContext`),
so the AI can adapt to where the visitor is — a pricing visitor is not a
docs reader is not a help-desk ticket.

```ts
init({
  publicKey: 'agent_pk_...',
  aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000',
  pageContext: {
    area: 'pricing', // host-defined surface
    path: '/pricing/enterprise',
    title: 'Enterprise plans',
    // url auto-filled from location.href when omitted
  },
});
```

Recognised fields (all optional):

- `area` — host-defined surface the visitor is on. Free-form string;
  suggested values: `home`, `docs`, `help-desk`, `support`, `pricing`,
  `checkout`, `orders`, `account`, `blog` (any string accepted).
- `url` — full page URL. Auto-filled from the host page's
  `location.href` when omitted.
- `path` — page path, e.g. `/pricing/enterprise`.
- `title` — page title.

Plus arbitrary custom scalar fields. Sanitized client-side with the same
rules as `userContext`.

> **On the wire:** `userContext` + `pageContext` are bundled into one
> `context` field — `base64url(JSON.stringify({ user, page }))` — sent on
> **every** request (body for POSTs, `?context=` for GETs), so the backend
> always has the visitor's latest context as they navigate. base64url is
> encoding, **not encryption** (the transport is already TLS); it just keeps
> PII out of plaintext access logs / the devtools network tab.

### Setting context after login / on navigation

In a typical SPA the visitor is anonymous on first load and logs in
later. Update context dynamically via the instance handle. The new context
rides the **next** request automatically (no reconnect) — and a
`setUserContext` identity change additionally re-personalizes the greeting,
keeping the **same** visitor/conversation so the conversation is continuous:

```ts
const widget = HelpAI.init({ publicKey: 'agent_pk_...', aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000' });

// after your app authenticates the user:
widget.setUserContext({
  id: 'user_42',
  email: 'jane@help.ai',
  name: 'Jane Doe',
  plan: 'pro',
});

// on SPA navigation:
widget.setPageContext({ area: 'checkout', path: '/checkout' });

// on logout:
widget.clearUserContext();
```

You can also seed context at load time via `data-user-*` /
`data-page-*` tag attributes — see [Installation](/sdk/installation) and
the framework recipes in [`frameworks.md`](/sdk/frameworks).

---

## Rendering

### `presentation.mode`

`"floating" | "inline" | "standalone" | "modal" | "drawer" | "page"` · default: `"floating"`

How the widget renders on the page.

- **`"floating"`** (default) — floating chat bubble in a corner.
  Clicking opens the panel. Best for marketing sites, support chat.
- **`"inline"`** — a block element that fills its parent container. No
  bubble, no popover. Best for in-app assistants, sidebar chats.
- **`"standalone"`** — full viewport. The dedicated chat tab; renders
  the full module surface (no sidebar).
- **`"modal"`** — a centered dialog over a backdrop. The host opens it
  (no launcher); call `open()` from your own trigger.
- **`"drawer"`** — docks to a screen edge; the launcher becomes a
  vertical edge tab.
- **`"page"`** — full-viewport split: a conversation **sidebar** plus
  the module surface in the main area.

`target` controls where every mode's shadow host is inserted. It is most
important for `inline` / `standalone` / `page`; overlay modes remain
viewport-positioned even when their host is inserted under a custom target.
See `../features/modes.md` for the full behavior matrix.

```ts
init({ presentation: { mode: 'inline' }, target: document.getElementById('chat')! });
```

### `target`

`HTMLElement | undefined`

Where to insert the widget's shadow host. Recommended for `inline` /
`standalone` / `page` modes. Floating, drawer, and modal hosts also use
it, while their panels remain viewport-positioned. Defaults to `<body>`.

### `presentation.iframe`

`boolean` · default: `false`

Wrap the widget in a same-origin iframe for strict JS + CSS isolation.
Useful when the host page has aggressive global scripts that mangle
`window.*` or inject hostile CSS.

```ts
init({ presentation: { mode: 'floating', iframe: true }, publicKey: 'agent_pk_...', aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000' });
```

Composes with any `mode`. Default is `false` — shadow DOM alone is
enough for 95% of deployments. [Security § Iframe isolation](/sdk/security-privacy#iframe-isolation).

### `presentation.position`

`"bottom-right" | "bottom-left" | "top-right" | "top-left"` · default: `"bottom-right"`

Launcher corner. Only applies in `floating` mode.

```ts
init({ presentation: { position: 'bottom-left' } });
```

### `behavior.startMinimized`

`boolean` · default: `true`

Whether the floating panel starts closed (showing only the launcher).
Only applies in `floating` mode.

```ts
// Start open on every fresh page load
init({ behavior: { startMinimized: false } });
```

User's last open/close choice is remembered per device — so even with
`behavior.startMinimized: false`, closing the widget and reloading keeps it
closed.

---

## Theming

### `theme`

`"auto" | "light" | "dark" | ThemeOverrides` · default: `"auto"`

Three forms:

**1. Preset mode:**

```ts
init({ theme: 'auto' }); // follows OS prefers-color-scheme
init({ theme: 'light' }); // force light
init({ theme: 'dark' }); // force dark
```

**2. Color overrides (stays in auto mode):**

```ts
init({
  theme: {
    accent: '#ff3e00', // primary brand color
    accentText: '#ffffff', // text on the accent color
    radius: '12px', // corner rounding
    fontFamily: 'Inter, system-ui, sans-serif',
  },
});
```

**3. Both at once** — not supported in one call, but users can pick a
mode via the header picker regardless of palette overrides.

End users can flip the theme via the header picker. Their choice is
persisted per device + synced cross-device.

Full customization guide: [Theming](/sdk/theming).

---

## Sizing

### `presentation.size`

`SizeOptions | undefined`

Control the panel's dimensions across three tiers:

```ts
init({
  presentation: {
    size: {
      // Normal tier (default panel size)
      width: '420px',
      height: '640px',

      // Expanded tier (when user clicks the ⤢ button)
      expanded: { width: '80vw', height: '80vh' },

      // User drag-resize
      resize: {
        enabled: true,
        minWidth: '360px',
        maxWidth: '900px',
        minHeight: '480px',
        maxHeight: '90vh',
      },

      // First-render pick
      initialSize: 'auto', // auto / normal / expanded / fullscreen
      autoSizeBreakpoint: 900, // "auto" → expanded if viewport ≥ 900px
    },
  },
});
```

### Size tiers

- **Normal** — `width`/`height` or mode-specific CSS defaults.
- **Expanded** — ⤢ header button, configurable dimensions.
- **Fullscreen** — ⛶ header button, always 100vw × 100vh.

### Drag-resize

`presentation.size.resize.enabled: true` shows a corner grip on the panel. Users drag
it to resize; dimensions persist per device + sync cross-device.
`presentation.size.resize.minWidth` etc. clamp the drag range.

### `presentation.size.initialSize`

Which tier to open at on the user's **first** mount. After that, user
interactions own the size.

- `"normal"` — force the normal tier.
- `"expanded"` — open roomy.
- `"fullscreen"` — open full-screen.
- `"auto"` (default) — `fullscreen` below 640 px, `normal` from 640 px
  to `autoSizeBreakpoint`, then `expanded` on wider viewports.

---

## Launcher

### `launcher`

`LauncherOptions | undefined` · only applies in `presentation.mode: "floating"`

The FAB and its nudges.

```ts
init({
  launcher: {
    variant: 'pill', // circle / pill / bar / minimal
    size: 'md', // sm / md / lg
    label: 'Ask us anything',
    icon: 'chat', // chat / message / bubbles / spark / wand / bot / help / lifebuoy / headset / search / sparkles / concierge / wave / raw SVG
    hidden: false, // true = no FAB

    // Unified pre-engagement bubble (optional). Same component
    // for greetings, nudges, onboarding tips — pick the
    // visuals + dismissal lifecycle for the use case.
    callout: {
      text: '👋 Hi! Need any help?',
      shape: 'pill', // pill / bubble / callout
      position: 'auto', // auto / horizontal / vertical
      delayMs: 1200,
      autoDismissMs: 0,
      animated: true,
      persistent: true, // true (default) = re-show on every visit
      // false = dismiss-once, hidden across visits
    },
  },
});
```

Variants + callout fully explained in
[Theming § Launcher](/sdk/theming#launcher).

### `launcher.hidden`

Hide the launcher FAB entirely. Use when you want to trigger the widget
from your own UI:

```ts
const chat = init({ launcher: { hidden: true } });
document.getElementById('my-custom-chat-button').onclick = () => chat.open();
```

---

## Header actions

### `header.actions`

`ActionName[]` · per-mode defaults

The list is a flat enabled set. `history` and `close` render as dedicated
buttons; the rest live in the ⋯ menu in a fixed internal order. Unlisted actions
are hidden, so input order does not choose placement.

```ts
init({
  header: {
    actions: ['theme', 'textSize', 'history', 'close', 'clear', 'fullscreen', 'popOut', 'sound', 'language'],
  },
});
```

Available actions:

| Name         | What it does                                                                |
| ------------ | --------------------------------------------------------------------------- |
| `clear`      | Start a new conversation (trash icon)                                       |
| `expand`     | Toggle normal ↔ expanded tier (⤢)                                           |
| `fullscreen` | Toggle normal ↔ fullscreen (⛶)                                              |
| `popOut`     | Open the active conversation in `behavior.popOutUrl`                        |
| `sound`      | Toggle notification sounds (switch-style)                                   |
| `history`    | Toggle the chat history pane                                                |
| `language`   | Open the language picker (renders as globe icon or inline rows in overflow) |
| `theme`      | Open the theme picker (auto/light/dark)                                     |
| `textSize`   | Cycle the conversation text size                                            |
| `close`      | Close the panel (X)                                                         |

`popOut` renders only when `behavior.popOutUrl` is configured. The new tab
receives `chat`, `widgetId`, `public_key` (when present), and
`ai_agent_deployment_id` query parameters so it can resume the same thread.

Per-mode defaults and visibility rules are maintained in
Header actions.

> `header.actions` is always a complete replacement for the per-mode default;
> arrays are never merged. An explicit client list wins over the server list.

---

## Composer

### `composer.sendButton`

Send-button chrome.

```ts
init({
  composer: {
    sendButton: {
      shape: 'pill', // circle / square / pill
      icon: 'arrowUp', // arrowUp / paperPlane / send / chevron
      variant: 'filled', // filled / outline / ghost
    },
  },
});
```

3 shapes × 4 icons × 3 variants = 36 combinations. Pick what matches
your brand.

---

## Footer

### `footer.composerDisclaimer`

Small grey text below the textarea. Classic "AI can make mistakes"
pattern.

```ts
init({ footer: { composerDisclaimer: 'AI can make mistakes. Check important info.' } });
```

Empty / omitted = no disclaimer shown.

### `footer.poweredBy`

Attribution row below the disclaimer. Defaults to the active
brand: `Powered by <BRAND.displayName>` linking to `BRAND.siteUrl`
(e.g. `Powered by Help AI` → `https://help.ai` for `@helpai/elements`).
Override fields per-deployment when you want different copy or to add a logo;
omit fields to inherit the brand defaults.

```ts
init({
  footer: {
    poweredBy: {
      text: 'Powered by Acme', // overrides brand default
      href: 'https://acme.com', // overrides brand default
      logoUrl: 'https://yoursite.com/helpai-logo.svg',
    },
  },
});
```

To opt out of the attribution entirely, pass an empty `text` (and no
logo): `footer: { poweredBy: { text: "" } }` collapses the element.

---

## Attachments + features

### `composer.attachments`

Client-side limits. Server enforces its own — these are to give users
fast feedback before upload.

```ts
init({
  composer: {
    attachments: {
      maxBytes: 10 * 1024 * 1024, // 10 MB, default
      maxCount: 10, // default
      accept: 'image/*,application/pdf', // comma-separated MIME globs
    },
  },
});
```

### `features.disableFileUpload`

`boolean` · default: `false`

Turn OFF file uploads — hide the paperclip button and reject drag-drop / paste.
Unset/`false` = enabled (default); set `true` to disable attachments entirely.

### `features.enableOperatorRequest`

`boolean` · default: `false`

Opt IN **operator control** — exposes a "Talk to a person" control in the
composer and the connected-to-operator states (a status banner while the conversation
is routed to the operator, and operator reply bubbles). This is a **positive opt-in**
for a new capability (unlike the `disable*` flags): unset/`false` = off (default), `true` = on.

Every deployment holds one long-lived `GET /pai/stream-resume`; this flag does not gate
the stream. It only exposes the visitor's `request-operator` control. AI replies, operator
replies, and control-state changes continue to arrive on the resume channel and deduplicate
by message id whether the request control is visible or not. The composer stays open while
operator-routed so the visitor can keep typing. Operator requests require backend support.

```ts
init({ features: { enableOperatorRequest: true } });
```

### `features.voice`

`"local" | "server" | "disabled"` · default: `"local"`

How voice input works:

- `"local"` — uses the browser's Web Speech API. Zero upload, free,
  quality varies by browser.
- `"server"` — records audio via `MediaRecorder`, uploads to
  `/pai/transcribe-audio`, receives text. Consistent quality, uses your
  upload quota.
- `"disabled"` — hides the mic button entirely.

## Messenger modules

### `modules`

Turns the panel into an Intercom-style **messenger** with a bottom tab
bar. `modules` is an **ordered array of up to 4 tabs**; each tab picks a UI
`layout`, the content collections it shows (`contentCollectionIds`), and a
translatable `label`. The surface renders in
**every** mode (in `page` mode it fills the main area beside the sidebar). With nothing set, just the **chat** shows —
today's single-chat widget, no tab bar.

```ts
init({
  publicKey: 'agent_pk_...',
  aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000',
  modules: [
    { label: 'tabHome', layout: 'home', contentCollectionIds: [GUIDES_ID], greetingText: 'Hi {name} 👋', brandName: 'Acme' }, // "Popular articles" = the collections' pinned items
    { label: 'tabConversations', layout: 'chat' }, // the conversation
    { id: 'help', label: 'tabHelp', layout: 'help', contentCollectionIds: [GUIDES_ID, BILLING_ID] },
    { id: 'news', label: 'tabNews', layout: 'news', contentCollectionIds: [NEWS_ID] },
  ],
});
```

| Field                  | Required | Meaning                                                                                            |
| ---------------------- | -------- | -------------------------------------------------------------------------------------------------- |
| `label`                | yes      | Tab label — an i18n key (e.g. `tabHome`) or literal; translated via `i18n.strings`.                |
| `layout`               | yes      | `chat` (the conversation), `home`, `help`, or `news`.                                              |
| `contentCollectionIds` | no       | Content collection ids (UUIDv7, max 20) this tab shows, in order; Help sections follow this order. |
| `id`                   | no       | Stable id for nav + last-tab memory (defaults to the first `contentCollectionIds`, else `layout`). |
| home extras            | no       | `greetingText` (supports `{name}`), `hideSearchBar`, `brandName`, … (`home` layout only).          |

- **Order is the array order** (left → right). One tab → no tab bar; zero
  tabs (`[]`) → an empty state.
- The first tab is the first-open default; the widget then remembers the
  user's last tab (per device).
- The deployment can also push `modules` from the dashboard via the
  handshake (`config.modules`); your `init({ modules })` wins (replace-whole).

Each tab's content is fetched lazily from `GET /content` (data-api) on first open.
Full behavior + wire contract:
`features/messenger-modules.md`.

---

## Response mode

### `behavior.responseMode`

`"streaming" | "buffered"` · default: `"streaming"`

- `"streaming"` — paint replies token-by-token as they arrive. Default.
- `"buffered"` — show a neutral loading indicator until the reply
  finishes, then render it whole. The backend always streams; this is a
  client-rendering choice. Useful when token-by-token feels stuttery.

### `behavior.disableMessageFeedback`

`boolean` · default: `false`

Turn OFF the 👍/👎 feedback controls under each rateable reply (AI or operator) — unset/`false` shows them (default). While
shown, a choice fires the [`messageFeedback`](/sdk/events-and-hooks) event and is sent to the backend.

```ts
init({ behavior: { disableMessageFeedback: true } }); // hide the controls
```

### `behavior.autoSendSuggestions`

`boolean` · default: `false`

Controls what tapping a suggestion chip does. Unset/`false` (default) **fills the composer** with the chip's
text so the visitor can edit before sending; `true` **sends** it immediately.

```ts
init({ behavior: { autoSendSuggestions: true } }); // send on tap instead of filling
```

---

## Internationalization

### `i18n.locale`

`string | undefined`

Force a specific BCP-47 locale, overriding the visitor's browser
setting.

```ts
init({ i18n: { locale: 'fr-CA' } });
```

### `i18n.defaultLocale`

`"auto" | string` · default: `"auto"`

Initial / fallback locale when the user hasn't picked one.

- `"auto"` — sniff `navigator.language`.
- Explicit tag (e.g., `"es-MX"`) — force that one.

### `i18n.availableLocales`

`string[]` · optional

Locales offered in the language switcher. Omission defaults to the active
locale as a one-entry list; zero or one entries hide the picker.

```ts
init({
  i18n: {
    availableLocales: ['en', 'fr', 'es', 'de'],
    defaultLocale: 'auto',
  },
});
```

### `i18n.strings`

Per-key overrides for any UI string. Two shapes:

**Flat** (applies to active locale):

```ts
init({
  i18n: {
    strings: {
      send: 'Go',
      composerPlaceholder: 'Ask me anything…',
      newConversation: 'Start fresh',
    },
  },
});
```

**Nested** (per-locale):

```ts
init({
  i18n: {
    strings: {
      en: { send: 'Go' },
      fr: { send: 'Envoyer' },
      es: { send: 'Enviar' },
    },
  },
});
```

Full key list: [i18n](/sdk/theming#internationalization) or
`src/i18n/strings.ts` in the source.

---

## Sound + haptics

### `feedback.sound`

Notification sounds.

```ts
init({
  feedback: {
    sound: {
      enabled: true, // default
      volume: 0.3, // 0..1, default 0.3
      events: {
        messageReceived: true, // built-in synth tone
        messageSent: true,
        error: 'https://cdn.your-site.com/error.mp3', // custom audio file
        voiceStart: false, // silence this one
        voiceStop: false,
      },
    },
  },
});
```

Per-event values:

- `true` — use the built-in synthesized tone.
- `false` — silence this event.
- `"url"` — URL to a custom audio file (decoded once + cached).

End users can mute via the sound action in the header. Their choice
is remembered.

### `feedback.haptics`

Tactile feedback on touch devices.

```ts
init({
  feedback: {
    haptics: {
      enabled: true, // default: true on touch devices
      events: {
        messageSent: [6], // single 6ms tap
        error: [10, 50, 10], // two taps with a 50ms pause
      },
    },
  },
});
```

Per-event values:

- `true` — default pattern.
- `false` — silence.
- number — single vibration of N ms.
- number[] — alternating `[vibrate, pause, vibrate, …]`.

iOS: WebKit only supports a single tick; arrays are flattened.

---

## Callbacks (shortcut for events)

Quick inline callbacks for common events. Same as calling `.on(...)`
on the returned instance.

```ts
init({
  publicKey: 'agent_pk_...',
  aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000',
  onMessage: (msg) => console.log(msg),
  onOpen: () => console.log('opened'),
  onClose: () => console.log('closed'),
  onError: (err) => Sentry.captureException(err),
});
```

For richer event handling, see [Events & hooks](/sdk/events-and-hooks).

---

## Storage

### `storage`

`ChatWidgetOptions["storage"]`

Custom synchronous storage adapter. Default is `localStorage`. Swap for:

- `sessionStorage`.
- Encrypted wrapper.
- In-memory shim (for environments without `localStorage`).

```ts
import type { ChatWidgetOptions } from '@helpai/elements';

type StorageAdapter = NonNullable<ChatWidgetOptions['storage']>;

const myStorage: StorageAdapter = {
  get: (key) => sessionStorage.getItem(key),
  set: (key, value) => sessionStorage.setItem(key, value),
  remove: (key) => sessionStorage.removeItem(key),
};

init({ publicKey: 'agent_pk_...', aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000', storage: myStorage });
```

The adapter also receives `draft.<conversationId>` keys containing exact
unsent textarea text and owns their storage, retention, and privacy behavior.
The widget itself does not include drafts in Help AI network requests before
Send. Use an encrypted adapter when same-origin plaintext storage is not
acceptable; an in-memory adapter disables reload restoration.

Full adapter contract: [Security & privacy § custom storage](/sdk/security-privacy#custom-storage).

---

## Runtime changes

You can change most options after mount via `chat.update(...)`:

```ts
const chat = init({ publicKey: 'agent_pk_...', aiAgentDeploymentId: '01900000-0000-7000-8000-000000000000' });

// Later — flip to dark mode
chat.update({ theme: 'dark' });

// Or change the launcher label
chat.update({ launcher: { variant: 'pill', label: 'New message!' } });
```

`update()` is a **shallow merge** at the top level. Nested objects are
replaced, not merged:

```ts
chat.update({ presentation: { size: { expanded: { width: '800px' } } } });
// This replaces the whole `presentation` section — mode, iframe, and the other size fields are gone!

// Keep the current section in your application state and spread each nested level you preserve:
chat.update({
  presentation: {
    ...currentPresentation,
    size: {
      ...currentPresentation.size,
      expanded: { width: '800px' },
    },
  },
});
```

The `publicKey`, `widgetId`, `presentation.mode`, and `presentation.iframe` can't change at runtime
— they require a full remount (`destroy()` + `mount()`).

---

## Putting it all together — full example

```ts
import { init } from '@helpai/elements';

const chat = init({
  // Identity
  publicKey: process.env.NEXT_PUBLIC_HELPAI_KEY!,
  aiAgentDeploymentId: process.env.NEXT_PUBLIC_HELPAI_DEPLOYMENT_ID!,
  widgetId: 'support',
  userContext: { id: currentUser.id, email: currentUser.email, name: currentUser.name },
  pageContext: { area: 'support', path: location.pathname },

  // Presentation + behavior
  presentation: {
    mode: 'floating',
    position: 'bottom-right',
    size: {
      expanded: { width: '720px', height: '85vh' },
      resize: { enabled: true, minWidth: '360px', maxWidth: '900px' },
      initialSize: 'auto',
      autoSizeBreakpoint: 1024,
    },
  },
  behavior: { startMinimized: true },
  theme: { accent: '#ff3e00', radius: '12px' },

  // Launcher
  launcher: {
    variant: 'pill',
    label: 'Ask us anything',
    icon: 'chat',
    callout: { text: 'Hey there 👋', delayMs: 2000 },
  },

  // i18n
  i18n: {
    availableLocales: ['en', 'fr', 'es'],
    defaultLocale: 'auto',
    strings: {
      en: { composerPlaceholder: 'Ask about anything…' },
      fr: { composerPlaceholder: 'Demandez-moi…' },
    },
  },

  // Feedback
  feedback: { sound: { enabled: true, volume: 0.25 } },

  // Footer
  footer: {
    composerDisclaimer: 'AI-generated answers may contain mistakes.',
    poweredBy: { text: 'Powered by Help AI', href: 'https://help.ai' },
  },

  // Events
  onMessage: (m) => analytics.track('chat_message', m),
  onError: (err) => Sentry.captureException(err),
});
```

---

## Not covered here

- **Events** → [Events & hooks](/sdk/events-and-hooks)
- **Theming deep-dive** → [Theming](/sdk/theming)
- **Framework-specific wiring** → [Frameworks](/sdk/frameworks)
- **Backend API** → Backend contract (internal)
