@convai/web-sdk 1.8.0 → 1.9.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +213 -45
  2. package/dist/core/CharacterRoster.d.ts +84 -0
  3. package/dist/core/CharacterRoster.d.ts.map +1 -0
  4. package/dist/core/CharacterRoster.js +348 -0
  5. package/dist/core/CharacterRoster.js.map +1 -0
  6. package/dist/core/CharacterVersionManager.d.ts +100 -0
  7. package/dist/core/CharacterVersionManager.d.ts.map +1 -0
  8. package/dist/core/CharacterVersionManager.js +227 -0
  9. package/dist/core/CharacterVersionManager.js.map +1 -0
  10. package/dist/core/ConvaiClient.d.ts +190 -1
  11. package/dist/core/ConvaiClient.d.ts.map +1 -1
  12. package/dist/core/ConvaiClient.js +1328 -289
  13. package/dist/core/ConvaiClient.js.map +1 -1
  14. package/dist/core/ConvaiRoomError.d.ts +48 -0
  15. package/dist/core/ConvaiRoomError.d.ts.map +1 -0
  16. package/dist/core/ConvaiRoomError.js +111 -0
  17. package/dist/core/ConvaiRoomError.js.map +1 -0
  18. package/dist/core/MessageHandler.d.ts +26 -2
  19. package/dist/core/MessageHandler.d.ts.map +1 -1
  20. package/dist/core/MessageHandler.js +397 -32
  21. package/dist/core/MessageHandler.js.map +1 -1
  22. package/dist/core/SSESession.d.ts +74 -0
  23. package/dist/core/SSESession.d.ts.map +1 -0
  24. package/dist/core/SSESession.js +499 -0
  25. package/dist/core/SSESession.js.map +1 -0
  26. package/dist/core/characterReference.d.ts +40 -0
  27. package/dist/core/characterReference.d.ts.map +1 -0
  28. package/dist/core/characterReference.js +72 -0
  29. package/dist/core/characterReference.js.map +1 -0
  30. package/dist/core/connectRequest.d.ts +17 -4
  31. package/dist/core/connectRequest.d.ts.map +1 -1
  32. package/dist/core/connectRequest.js +28 -17
  33. package/dist/core/connectRequest.js.map +1 -1
  34. package/dist/core/index.d.ts +8 -1
  35. package/dist/core/index.d.ts.map +1 -1
  36. package/dist/core/index.js +13 -1
  37. package/dist/core/index.js.map +1 -1
  38. package/dist/core/logicalTurn.d.ts +4 -6
  39. package/dist/core/logicalTurn.d.ts.map +1 -1
  40. package/dist/core/logicalTurn.js +29 -4
  41. package/dist/core/logicalTurn.js.map +1 -1
  42. package/dist/core/modelOutput.d.ts.map +1 -1
  43. package/dist/core/modelOutput.js +2 -2
  44. package/dist/core/modelOutput.js.map +1 -1
  45. package/dist/core/rosterRequest.d.ts +57 -0
  46. package/dist/core/rosterRequest.d.ts.map +1 -0
  47. package/dist/core/rosterRequest.js +210 -0
  48. package/dist/core/rosterRequest.js.map +1 -0
  49. package/dist/core/types.d.ts +869 -22
  50. package/dist/core/types.d.ts.map +1 -1
  51. package/dist/core/types.js.map +1 -1
  52. package/dist/embed/ConvaiChatElement.d.ts +77 -1
  53. package/dist/embed/ConvaiChatElement.d.ts.map +1 -1
  54. package/dist/embed/ConvaiChatElement.js +433 -54
  55. package/dist/embed/ConvaiChatElement.js.map +1 -1
  56. package/dist/embed/chat-embed-v1.js +136 -35
  57. package/dist/embed/chat-embed-v1.js.map +4 -4
  58. package/dist/react/components/ConvaiWidget.d.ts.map +1 -1
  59. package/dist/react/components/ConvaiWidget.js +6 -1
  60. package/dist/react/components/ConvaiWidget.js.map +1 -1
  61. package/dist/react/components/rtc-widget/components/AudioVisualizer.d.ts.map +1 -1
  62. package/dist/react/components/rtc-widget/components/AudioVisualizer.js +28 -1
  63. package/dist/react/components/rtc-widget/components/AudioVisualizer.js.map +1 -1
  64. package/dist/react/components/rtc-widget/components/MarkdownRenderer.d.ts +7 -0
  65. package/dist/react/components/rtc-widget/components/MarkdownRenderer.d.ts.map +1 -1
  66. package/dist/react/components/rtc-widget/components/MarkdownRenderer.js +135 -46
  67. package/dist/react/components/rtc-widget/components/MarkdownRenderer.js.map +1 -1
  68. package/dist/react/components/rtc-widget/components/UserMessage.js +1 -1
  69. package/dist/react/components/rtc-widget/components/UserMessage.js.map +1 -1
  70. package/dist/react/components/rtc-widget/components/conviComponents/VoiceModeOverlay.d.ts.map +1 -1
  71. package/dist/react/components/rtc-widget/components/conviComponents/VoiceModeOverlay.js +93 -49
  72. package/dist/react/components/rtc-widget/components/conviComponents/VoiceModeOverlay.js.map +1 -1
  73. package/dist/react/hooks/useConvaiClient.d.ts.map +1 -1
  74. package/dist/react/hooks/useConvaiClient.js +17 -2
  75. package/dist/react/hooks/useConvaiClient.js.map +1 -1
  76. package/dist/react/index.d.ts +4 -1
  77. package/dist/react/index.d.ts.map +1 -1
  78. package/dist/react/index.js +8 -1
  79. package/dist/react/index.js.map +1 -1
  80. package/dist/utils/inlineMarkdown.d.ts +60 -0
  81. package/dist/utils/inlineMarkdown.d.ts.map +1 -0
  82. package/dist/utils/inlineMarkdown.js +183 -0
  83. package/dist/utils/inlineMarkdown.js.map +1 -0
  84. package/dist/vanilla/AudioRenderer.d.ts +3 -1
  85. package/dist/vanilla/AudioRenderer.d.ts.map +1 -1
  86. package/dist/vanilla/AudioRenderer.js +8 -2
  87. package/dist/vanilla/AudioRenderer.js.map +1 -1
  88. package/dist/vanilla/ConvaiWidget.d.ts.map +1 -1
  89. package/dist/vanilla/ConvaiWidget.js +1122 -302
  90. package/dist/vanilla/ConvaiWidget.js.map +1 -1
  91. package/dist/vanilla/WidgetEventSubscriptions.d.ts +1 -1
  92. package/dist/vanilla/WidgetEventSubscriptions.d.ts.map +1 -1
  93. package/dist/vanilla/WidgetEventSubscriptions.js +5 -0
  94. package/dist/vanilla/WidgetEventSubscriptions.js.map +1 -1
  95. package/dist/vanilla/icons.d.ts.map +1 -1
  96. package/dist/vanilla/icons.js +62 -15
  97. package/dist/vanilla/icons.js.map +1 -1
  98. package/dist/vanilla/index.d.ts +6 -2
  99. package/dist/vanilla/index.d.ts.map +1 -1
  100. package/dist/vanilla/index.js +5 -1
  101. package/dist/vanilla/index.js.map +1 -1
  102. package/dist/vanilla/styles.d.ts +18 -1
  103. package/dist/vanilla/styles.d.ts.map +1 -1
  104. package/dist/vanilla/styles.js +141 -29
  105. package/dist/vanilla/styles.js.map +1 -1
  106. package/dist/vanilla/types.d.ts +74 -0
  107. package/dist/vanilla/types.d.ts.map +1 -1
  108. package/dist/vanilla/types.js.map +1 -1
  109. package/dist/version.d.ts +1 -1
  110. package/dist/version.d.ts.map +1 -1
  111. package/dist/version.js +1 -1
  112. package/dist/version.js.map +1 -1
  113. package/package.json +45 -18
@@ -3,11 +3,107 @@
3
3
  * Ports the React ConvaiWidget to vanilla TypeScript with DOM manipulation
4
4
  */
5
5
  import { AudioRenderer } from "./AudioRenderer.js";
6
- import { aeroTheme, injectGlobalStyles } from "./styles.js";
6
+ import { aeroTheme, injectGlobalStyles, injectKeyframes, } from "./styles.js";
7
7
  import { Icons } from "./icons.js";
8
8
  import { WidgetEventSubscriptions } from "./WidgetEventSubscriptions.js";
9
9
  import { ConvaiClient } from "../core/ConvaiClient.js";
10
+ import { parseInlineMarkdown, compactUrl } from "../utils/inlineMarkdown.js";
10
11
  import { freshPublicationGrantOptions } from "../core/publishedChat.js";
12
+ /**
13
+ * Positioning declarations for the widget root, keyed by `placement`. The
14
+ * `bottom-right` entry must stay byte-identical to the literals it replaces --
15
+ * the inline-style parity suite snapshots the resolved `cssText` and compares
16
+ * it to a committed fixture.
17
+ */
18
+ /** Gap between a fixed-placement widget and the viewport edge it anchors to. */
19
+ const PLACEMENT_INSET_PX = 24;
20
+ const PLACEMENT_CSS = {
21
+ "bottom-right": `position: fixed; bottom: ${PLACEMENT_INSET_PX}px; right: ${PLACEMENT_INSET_PX}px;`,
22
+ "bottom-left": `position: fixed; bottom: ${PLACEMENT_INSET_PX}px; left: ${PLACEMENT_INSET_PX}px;`,
23
+ "top-right": `position: fixed; top: ${PLACEMENT_INSET_PX}px; right: ${PLACEMENT_INSET_PX}px;`,
24
+ "top-left": `position: fixed; top: ${PLACEMENT_INSET_PX}px; left: ${PLACEMENT_INSET_PX}px;`,
25
+ inline: "position: relative;",
26
+ };
27
+ /** The open panel's preferred size. Capped by `PANEL_MAX_*` — see below. */
28
+ const PANEL_W_PX = 400;
29
+ const PANEL_H_PX = 600;
30
+ /**
31
+ * A ceiling on the open panel, so it can never be clipped by the viewport.
32
+ *
33
+ * The panel used to be a flat 400x600. The widget is `position: fixed`
34
+ * anchored `PLACEMENT_INSET_PX` from one edge, so on any viewport narrower
35
+ * than 448px — or shorter than 648px — the panel ran past the opposite edge
36
+ * and was silently cut off, with no scrollbar to reveal it, because fixed
37
+ * elements do not contribute to scrollable overflow. That is most phones: at
38
+ * 393px (iPhone 15 Pro) 30px of the panel sat off-screen, at 360px 63px did,
39
+ * and in landscape 233px of it — the entire header, including the close
40
+ * button — sat above the viewport, leaving nothing on screen to dismiss it.
41
+ *
42
+ * Expressed as `max-width`/`max-height` rather than folding the cap into the
43
+ * width with `min()`. Both compute the same thing, but they fail differently:
44
+ * a parser that does not know `min()` drops the whole declaration and the
45
+ * panel is left with no width at all, which is worse than the bug. An unknown
46
+ * `max-width` drops only the ceiling and leaves the previous behaviour intact.
47
+ * (Not hypothetical — happy-dom, which this package's own tests run in, parses
48
+ * the `max-width` form and discards the `min()` one.)
49
+ *
50
+ * Dynamic viewport units so mobile browser chrome is accounted for as it shows
51
+ * and hides, rather than sizing against a viewport the user cannot fully see.
52
+ * Applied to the container permanently rather than per state: the collapsed
53
+ * bubble is far below the ceiling, so it is unaffected.
54
+ */
55
+ const PANEL_MAX_W = `calc(100dvw - ${PLACEMENT_INSET_PX * 2}px)`;
56
+ const PANEL_MAX_H = `calc(100dvh - ${PLACEMENT_INSET_PX * 2}px)`;
57
+ /** `convai-error{code:'mic-permission'}` per the embed's error-handling contract. */
58
+ const MIC_PERMISSION_ERROR_CODE = "mic-permission";
59
+ /**
60
+ * Distinguishes a microphone-permission denial from any other audio failure.
61
+ *
62
+ * Traced (not assumed): `client.audioControls.unmuteAudio()` delegates to
63
+ * `AudioManager.enableAudio()`, which calls
64
+ * `room.localParticipant.setMicrophoneEnabled(true)`. That's LiveKit's
65
+ * `setTrackEnabled()`, which on failure does `throw e` unchanged, from a
66
+ * `catch` around `createLocalTracks()`, which itself does `throw e` unchanged
67
+ * around `navigator.mediaDevices.getUserMedia()`. `AudioManager.enableAudio()`
68
+ * also just does `throw error` in its own catch. Nothing on that path wraps or
69
+ * replaces the error, so a user's permission denial reaches here as the exact
70
+ * `DOMException` `getUserMedia()` produced, with `.name === 'NotAllowedError'`
71
+ * (`'PermissionDeniedError'` is the old pre-spec name some browsers used).
72
+ */
73
+ function isMicPermissionDenial(error) {
74
+ const name = error?.name;
75
+ return name === "NotAllowedError" || name === "PermissionDeniedError";
76
+ }
77
+ /**
78
+ * Wraps a mic-permission denial so a consumer of the client's `error`
79
+ * channel can tell it apart from a generic failure without knowing anything
80
+ * about `DOMException` internals -- it only has to check `error.code`. The
81
+ * original error is preserved on `.cause` for anyone who wants the detail.
82
+ */
83
+ function toMicPermissionError(cause) {
84
+ const err = new Error("Microphone access was denied. Continuing in text-only mode.");
85
+ err.name = "ConvaiMicPermissionError";
86
+ err.code = MIC_PERMISSION_ERROR_CODE;
87
+ err.cause = cause;
88
+ return err;
89
+ }
90
+ /**
91
+ * Routes a failed `enableAudio()`/`unmuteAudio()` call onto the client's
92
+ * *existing* `error` channel -- the same one `ConvaiClient` already uses --
93
+ * instead of letting it become an unhandled rejection (the click-handler
94
+ * site) or vanish into a bare `console.error` (the auto-voice-mode sites).
95
+ * `console.error` is kept alongside for local debugging; this just adds the
96
+ * event emission next to it. `client.emit` is called defensively since it
97
+ * isn't part of the public `IConvaiClient` surface -- see the `emit?` field
98
+ * on `VanillaWidgetOptions.convaiClient` in `./types.ts`.
99
+ */
100
+ function reportMicFailure(client, logLabel, error) {
101
+ console.error(logLabel, error);
102
+ const payload = isMicPermissionDenial(error)
103
+ ? toMicPermissionError(error)
104
+ : error;
105
+ client.emit?.("error", payload);
106
+ }
11
107
  /**
12
108
  * Create a Convai chat widget in the specified container
13
109
  *
@@ -44,6 +140,21 @@ import { freshPublicationGrantOptions } from "../core/publishedChat.js";
44
140
  * ```
45
141
  */
46
142
  export function createConvaiWidget(container, options) {
143
+ /**
144
+ * Where global styles and `@keyframes` are injected.
145
+ *
146
+ * An explicit `options.styleTarget` wins and is used verbatim. Otherwise we
147
+ * fall back to deriving it from the container's current root — which is what
148
+ * every existing caller relies on, but only works when the container is
149
+ * already attached to its final root. A caller that builds a detached
150
+ * subtree and appends it to a shadow root afterwards must pass
151
+ * `styleTarget` explicitly, or the styles land in `document.head` and the
152
+ * shadow tree renders unstyled with no error.
153
+ */
154
+ const styleTarget = options.styleTarget ??
155
+ (container.getRootNode() instanceof ShadowRoot
156
+ ? container.getRootNode()
157
+ : document);
47
158
  // Create client if not provided - guarantee it's defined
48
159
  const client = options.convaiClient ||
49
160
  (() => {
@@ -63,8 +174,18 @@ export function createConvaiWidget(container, options) {
63
174
  });
64
175
  })();
65
176
  const { showVideo = true, showScreenShare = true, defaultVoiceMode = true, requestPublicationGrant, publishedChatConnectOptions, publishedChatDescriptor, onConnect, onDisconnect, onMessage, } = options;
177
+ // Unknown/typo'd values fall back to the default rather than throwing --
178
+ // a bad `placement` attribute on a customer's page must not blank the
179
+ // widget.
180
+ const placement = options.placement && options.placement in PLACEMENT_CSS
181
+ ? options.placement
182
+ : "bottom-right";
66
183
  // Inject global styles
67
- injectGlobalStyles();
184
+ injectGlobalStyles(styleTarget);
185
+ // Keyframes were injected lazily by the connecting overlay and the settings
186
+ // tray, but a link-preview skeleton can render before either exists — a
187
+ // replayed transcript paints message bubbles immediately. Idempotent.
188
+ injectKeyframes(styleTarget);
68
189
  // State
69
190
  let isOpen = false;
70
191
  let isSettingsOpen = false;
@@ -80,8 +201,22 @@ export function createConvaiWidget(container, options) {
80
201
  let hasEnteredDefaultVoiceMode = false;
81
202
  /** True after we have connected at least once; used to call reconnect() instead of connect() when opening after disconnect */
82
203
  let hasConnectedBefore = false;
83
- /** Prevent repeated open clicks from minting multiple one-time publication grants. */
84
- let isStartingConnection = false;
204
+ /**
205
+ * True from the moment an open is requested on a *disconnected* client
206
+ * until that open either completes or is cancelled.
207
+ *
208
+ * `isOpen` alone cannot express this: the first open awaits a real
209
+ * `connect()` (0.5-3s in production) and only flips `isOpen` afterwards, so
210
+ * for that whole window the widget is neither open nor idle. Without this
211
+ * flag `close()` sees `isOpen === false` and no-ops -- and the connect then
212
+ * pops the panel open behind the user -- while `toggle()` sees the same
213
+ * `false`, starts a *second* open, and lands on the already-connecting
214
+ * branch that opens immediately. Every entry point below treats
215
+ * `pendingOpen` as "open" for the purpose of deciding what a close/toggle
216
+ * means, and `handleToggle` re-checks it before committing `setIsOpen(true)`
217
+ * so a cancellation during the await is honoured.
218
+ */
219
+ let pendingOpen = false;
85
220
  /** Prevent an in-flight publication grant request from connecting after teardown. */
86
221
  let isDestroyed = false;
87
222
  const eventSubscriptions = new WidgetEventSubscriptions(() => isDestroyed);
@@ -98,6 +233,13 @@ export function createConvaiWidget(container, options) {
98
233
  let settingsTray;
99
234
  let floatingVideo;
100
235
  let voiceModeOverlay;
236
+ let connectingOverlay;
237
+ /**
238
+ * Elements captured at creation. IDs are scoped per DOM tree, so
239
+ * document.getElementById() returns null when the widget is mounted
240
+ * inside a shadow root. Every element here is created in this file.
241
+ */
242
+ const refs = {};
101
243
  // Audio Analysis State
102
244
  let audioContext = null;
103
245
  let analyzer = null;
@@ -108,15 +250,31 @@ export function createConvaiWidget(container, options) {
108
250
  const fetchCharacterInfo = async () => {
109
251
  if (publishedChatDescriptor)
110
252
  return;
111
- if (!client.apiKey || !client.characterId)
253
+ // Prefer authToken over apiKey, matching the precedence ConvaiClient
254
+ // uses when building /connect headers -- a client carrying both must
255
+ // behave identically in both places.
256
+ //
257
+ // The two credentials travel in *different* headers: api.convai.com reads
258
+ // an auth token from API-AUTH-TOKEN and an API key from X-API-Key, and
259
+ // answers an API key sent as API-AUTH-TOKEN with `400 Your session has
260
+ // expired.` Because the failure is swallowed below, sending the wrong one
261
+ // showed up only as a header stuck on the fallback name.
262
+ const credential = client.authToken ?? client.apiKey;
263
+ if (!credential || !client.characterId)
112
264
  return;
265
+ const headers = {
266
+ "Content-Type": "application/json",
267
+ };
268
+ if (client.authToken) {
269
+ headers["API-AUTH-TOKEN"] = client.authToken;
270
+ }
271
+ else {
272
+ headers["X-API-Key"] = credential;
273
+ }
113
274
  try {
114
275
  const response = await fetch("https://api.convai.com/character/get", {
115
276
  method: "POST",
116
- headers: {
117
- "Content-Type": "application/json",
118
- "API-AUTH-TOKEN": client.apiKey,
119
- },
277
+ headers,
120
278
  body: JSON.stringify({ charID: client.characterId }),
121
279
  });
122
280
  if (response.ok) {
@@ -140,23 +298,34 @@ export function createConvaiWidget(container, options) {
140
298
  rootElement = document.createElement("div");
141
299
  rootElement.className = "convai-widget";
142
300
  rootElement.style.cssText = `
143
- position: fixed;
144
- bottom: 1.5rem;
145
- right: 1.5rem;
146
- z-index: ${aeroTheme.zIndex.modal};
147
- font-family: ${aeroTheme.typography.fontFamily.primary};
301
+ ${PLACEMENT_CSS[placement]}
302
+ z-index: var(--convai-z-index, ${aeroTheme.zIndex.modal});
303
+ font-family: var(--convai-font, ${aeroTheme.typography.fontFamily.primary});
148
304
  `;
149
305
  // Morphing container
150
306
  morphingContainer = document.createElement("div");
307
+ // `part="launcher"` is precise only while collapsed: this same element
308
+ // morphs into the open panel (400x600, capped to the viewport — see PANEL_MAX_W)
309
+ // and carries that panel's background,
310
+ // radius and shadow. See the `part="panel"` call site below for the full
311
+ // semantics a host needs to know.
312
+ morphingContainer.setAttribute("part", "launcher");
313
+ // NOTE on border-radius: deliberately NOT themable. `--convai-radius`
314
+ // drives the open panel only. One token cannot serve both geometries --
315
+ // `--convai-radius: 8px` would squircle the circular launcher, and `50%`
316
+ // would turn the panel into an ellipse. A dedicated
317
+ // `--convai-launcher-radius` can be added additively later if wanted.
151
318
  morphingContainer.style.cssText = `
152
319
  position: relative;
153
- width: 4rem;
154
- height: 4rem;
155
- background: ${aeroTheme.colors.glass.backdrop};
320
+ width: var(--convai-launcher-size, 64px);
321
+ height: var(--convai-launcher-size, 64px);
322
+ max-width: ${PANEL_MAX_W};
323
+ max-height: ${PANEL_MAX_H};
324
+ background: var(--convai-panel-bg, ${aeroTheme.colors.glass.backdrop});
156
325
  backdrop-filter: ${aeroTheme.glass.backdrop};
157
326
  border: ${aeroTheme.glass.border};
158
327
  border-radius: 50%;
159
- box-shadow: ${aeroTheme.shadows.glass};
328
+ box-shadow: var(--convai-shadow, ${aeroTheme.shadows.glass});
160
329
  transition: all 0.3s ease-in-out;
161
330
  overflow: hidden;
162
331
  display: flex;
@@ -177,10 +346,39 @@ export function createConvaiWidget(container, options) {
177
346
  transform: scale(1);
178
347
  `;
179
348
  const convaiLogo = Icons.ConvaiLogo("xl", "idle");
180
- convaiLogo.style.color = aeroTheme.colors.convai.light;
349
+ convaiLogo.style.color = `var(--convai-accent, ${aeroTheme.colors.convai.light})`;
181
350
  buttonContent.appendChild(convaiLogo);
182
351
  // Chat content
183
352
  chatContent = document.createElement("div");
353
+ // ----------------------------------------------------------------------
354
+ // `launcher` / `panel` part semantics. Read before writing theming docs.
355
+ //
356
+ // This widget morphs rather than swapping trees: `morphingContainer` IS
357
+ // the 64px circle AND the open panel, animating between them (see
358
+ // setIsOpen). It therefore owns every painted surface property of both
359
+ // states -- background, border, border-radius, box-shadow. `buttonContent`
360
+ // and `chatContent` are transparent `inset: 0` overlays that only
361
+ // cross-fade their contents.
362
+ //
363
+ // So, precisely:
364
+ // ::part(launcher) -> morphingContainer. Paints the collapsed circle
365
+ // AND the open panel; there is no rule that hits
366
+ // only one. This is the surface part.
367
+ // ::part(panel) -> chatContent. The open state's *content layer*:
368
+ // useful for padding, colour, font, opacity. It has
369
+ // no background, no border and no radius of its
370
+ // own, so `::part(panel){border-radius}` does
371
+ // nothing -- set radius via ::part(launcher) or
372
+ // `--convai-radius` (which is panel-scoped).
373
+ //
374
+ // Assessed and deliberately not "fixed": moving `launcher` onto
375
+ // buttonContent would make `::part(launcher){background}` state-specific
376
+ // but would silently break `border-radius` and `box-shadow` on it, since
377
+ // buttonContent is clipped by the container's own radius + overflow:
378
+ // hidden. Correcting this properly needs a separate launcher element
379
+ // instead of a morph -- a rendering change, out of scope here.
380
+ // ----------------------------------------------------------------------
381
+ chatContent.setAttribute("part", "panel");
184
382
  chatContent.style.cssText = `
185
383
  position: absolute;
186
384
  inset: 0;
@@ -201,11 +399,19 @@ export function createConvaiWidget(container, options) {
201
399
  contentElement.style.cssText = `
202
400
  flex: 1;
203
401
  overflow-y: auto;
204
- padding: 1rem;
402
+ padding: 16px;
205
403
  background: transparent;
404
+ position: relative;
206
405
  `;
207
406
  messageListElement = createMessageList();
208
407
  contentElement.appendChild(messageListElement);
408
+ // Connecting overlay -- shown until the bot is ready. Appended last, not
409
+ // to match DOM order (position: absolute + z-index: 100, set inside
410
+ // createConnectingOverlay, is what keeps it on top regardless of source
411
+ // order) but so inserting it doesn't shift every existing sibling's
412
+ // index-based path in the inline-style-parity fixture.
413
+ connectingOverlay = createConnectingOverlay();
414
+ contentElement.appendChild(connectingOverlay);
209
415
  // Footer
210
416
  footerElement = createFooter();
211
417
  chatContent.appendChild(headerElement);
@@ -222,9 +428,31 @@ export function createConvaiWidget(container, options) {
222
428
  container.appendChild(floatingVideo);
223
429
  container.appendChild(rootElement);
224
430
  // Event listeners
225
- morphingContainer.addEventListener("click", handleToggle);
431
+ morphingContainer.addEventListener("click", handleLauncherClick);
226
432
  };
227
433
  // Create Voice Mode Overlay
434
+ /**
435
+ * Voice mode, matched to the React overlay (VoiceModeOverlay.tsx) rather
436
+ * than to what this file used to draw.
437
+ *
438
+ * The two had diverged badly: React centres the character's avatar inside
439
+ * two counter-rotating liquid-gradient layers and paints the user's
440
+ * microphone as three overlapping sine waves on a canvas, while this file
441
+ * drew forty grey vertical bars and no avatar at all. Same product, two
442
+ * unrelated screens.
443
+ *
444
+ * What is reproduced here, value for value: the 120px avatar with its 3px
445
+ * rgba(255,255,255,0.2) ring and letter fallback, the 126px conic and
446
+ * radial gradient layers (20s clockwise / 15s anticlockwise, blurred 8px
447
+ * and 6px), the 250x80 canvas carrying three waves, and the status text at
448
+ * 16px/600 over 13px with React's wording.
449
+ *
450
+ * The one deliberate omission is the `AudioVisualizer` ring that React
451
+ * fades in behind the avatar while the character speaks: it is a 364-line
452
+ * component wired directly to a LiveKit `Room`, and porting it is its own
453
+ * change. The avatar still breathes while the character speaks, so the
454
+ * speaking state reads without it.
455
+ */
228
456
  const createVoiceModeOverlay = () => {
229
457
  const overlay = document.createElement("div");
230
458
  overlay.style.cssText = `
@@ -233,171 +461,383 @@ export function createConvaiWidget(container, options) {
233
461
  left: 50%;
234
462
  transform: translate(-50%, -50%);
235
463
  text-align: center;
236
- padding: 1rem;
464
+ padding: 16px;
237
465
  z-index: 10;
238
466
  pointer-events: auto;
239
467
  display: none;
240
468
  flex-direction: column;
241
469
  align-items: center;
242
- gap: 1.5rem;
470
+ gap: 32px;
243
471
  `;
244
- // Bars Container
245
- const barsContainer = document.createElement("div");
246
- barsContainer.id = "voice-bars-container";
247
- barsContainer.style.cssText = `
472
+ // --- Avatar, with the two rotating gradient layers behind it ----------
473
+ const avatarWrap = document.createElement("div");
474
+ avatarWrap.style.cssText = `
475
+ position: relative;
248
476
  display: flex;
249
477
  align-items: center;
250
478
  justify-content: center;
251
- gap: 2px;
252
- height: 80px;
253
- max-width: 300px;
479
+ isolation: isolate;
254
480
  `;
255
- // Create 40 bars
256
- for (let i = 0; i < 40; i++) {
257
- const bar = document.createElement("div");
258
- bar.className = "voice-bar";
259
- bar.style.cssText = `
260
- width: 3px;
261
- height: 15px;
262
- background-color: ${aeroTheme.colors.neutral[400]};
263
- border-radius: 1.5px;
264
- transition: height 0.08s ease-out, background-color 0.2s;
265
- transform-origin: center;
266
- `;
267
- barsContainer.appendChild(bar);
268
- }
269
- overlay.appendChild(barsContainer);
270
- // Status Text
481
+ const avatarStack = document.createElement("div");
482
+ avatarStack.className = "convai-voice-avatar";
483
+ refs.voiceModeAvatar = avatarStack;
484
+ avatarStack.style.cssText = `
485
+ position: relative;
486
+ z-index: 10;
487
+ border-radius: 50%;
488
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
489
+ background: white;
490
+ display: flex;
491
+ align-items: center;
492
+ justify-content: center;
493
+ `;
494
+ const accent = `var(--convai-accent, ${aeroTheme.colors.convai.light})`;
495
+ const layer1 = document.createElement("div");
496
+ layer1.className = "convai-voice-gradient";
497
+ layer1.style.cssText = `
498
+ position: absolute;
499
+ width: 126px;
500
+ height: 126px;
501
+ border-radius: 50%;
502
+ background: conic-gradient(
503
+ from 0deg,
504
+ ${aeroTheme.colors.convai.light}00 0%,
505
+ ${aeroTheme.colors.convai.light}40 25%,
506
+ ${aeroTheme.colors.convai.dark}60 50%,
507
+ ${aeroTheme.colors.convai.light}40 75%,
508
+ ${aeroTheme.colors.convai.light}00 100%
509
+ );
510
+ opacity: 0.8;
511
+ filter: blur(8px);
512
+ z-index: -2;
513
+ animation: convaiVoiceSpin 20s linear infinite;
514
+ `;
515
+ const layer2 = document.createElement("div");
516
+ layer2.className = "convai-voice-gradient";
517
+ layer2.style.cssText = `
518
+ position: absolute;
519
+ width: 126px;
520
+ height: 126px;
521
+ border-radius: 50%;
522
+ background:
523
+ radial-gradient(ellipse 80% 100% at 30% 40%,
524
+ ${aeroTheme.colors.convai.light}50,
525
+ ${aeroTheme.colors.convai.light}30 40%,
526
+ transparent 70%),
527
+ radial-gradient(ellipse 80% 100% at 70% 60%,
528
+ ${aeroTheme.colors.convai.dark}50,
529
+ ${aeroTheme.colors.convai.dark}30 40%,
530
+ transparent 70%);
531
+ opacity: 0.9;
532
+ filter: blur(6px);
533
+ z-index: -1;
534
+ animation: convaiVoiceSpinReverse 15s linear infinite;
535
+ `;
536
+ // The image is clipped by its own container so the gradients above stay
537
+ // visible outside it — React nests it the same way for the same reason.
538
+ const avatarClip = document.createElement("div");
539
+ avatarClip.style.cssText = `
540
+ position: relative;
541
+ border-radius: 50%;
542
+ overflow: hidden;
543
+ border: 3px solid rgba(255, 255, 255, 0.2);
544
+ width: 120px;
545
+ height: 120px;
546
+ display: flex;
547
+ align-items: center;
548
+ justify-content: center;
549
+ `;
550
+ refs.voiceModeAvatarClip = avatarClip;
551
+ avatarStack.append(layer1, layer2, avatarClip);
552
+ avatarWrap.appendChild(avatarStack);
553
+ overlay.appendChild(avatarWrap);
554
+ // --- The user's microphone, as three waves on a canvas ----------------
555
+ const canvas = document.createElement("canvas");
556
+ canvas.className = "convai-voice-wave";
557
+ canvas.style.cssText = `width: 250px; height: 80px;`;
558
+ refs.voiceModeCanvas = canvas;
559
+ overlay.appendChild(canvas);
560
+ // --- Status text ------------------------------------------------------
271
561
  const statusContainer = document.createElement("div");
272
562
  const statusTitle = document.createElement("div");
273
563
  statusTitle.id = "voice-mode-title";
564
+ refs.voiceModeTitle = statusTitle;
274
565
  statusTitle.style.cssText = `
275
- font-size: 14px;
276
- font-weight: 500;
277
- color: ${aeroTheme.colors.text.primary};
278
- margin-bottom: 0.5rem;
566
+ font-size: 16px;
567
+ font-weight: 600;
568
+ color: var(--convai-panel-fg, ${aeroTheme.colors.text.primary});
569
+ margin-bottom: 8px;
279
570
  `;
280
- statusTitle.textContent = "Voice Only Mode";
571
+ statusTitle.textContent = "Voice Mode";
281
572
  const statusSubtitle = document.createElement("div");
282
573
  statusSubtitle.id = "voice-mode-subtitle";
574
+ refs.voiceModeSubtitle = statusSubtitle;
283
575
  statusSubtitle.style.cssText = `
284
- font-size: 12px;
576
+ font-size: 13px;
285
577
  color: ${aeroTheme.colors.text.secondary};
286
578
  `;
287
- statusSubtitle.textContent = "Press and hold the microphone to talk";
288
- statusContainer.appendChild(statusTitle);
289
- statusContainer.appendChild(statusSubtitle);
579
+ statusSubtitle.textContent = "Tap microphone to talk";
580
+ statusContainer.append(statusTitle, statusSubtitle);
290
581
  overlay.appendChild(statusContainer);
582
+ void accent;
291
583
  return overlay;
292
584
  };
585
+ /**
586
+ * Fills the voice-mode avatar from the character info fetch, or falls back
587
+ * to the character's initial the way React does. Called from
588
+ * updateHeader(), so it tracks a late `fetchCharacterInfo()` rather than
589
+ * being fixed at construction.
590
+ */
591
+ const updateVoiceModeAvatar = () => {
592
+ const clip = refs.voiceModeAvatarClip;
593
+ if (!clip)
594
+ return;
595
+ const wanted = characterImage || `letter:${characterName}`;
596
+ if (clip.dataset.filledWith === wanted)
597
+ return;
598
+ clip.dataset.filledWith = wanted;
599
+ clip.replaceChildren();
600
+ if (characterImage) {
601
+ const img = document.createElement("img");
602
+ img.src = characterImage;
603
+ img.alt = characterName;
604
+ img.style.cssText = `width: 120px; height: 120px; object-fit: cover; display: block;`;
605
+ clip.appendChild(img);
606
+ return;
607
+ }
608
+ const letter = document.createElement("div");
609
+ letter.style.cssText = `
610
+ width: 120px;
611
+ height: 120px;
612
+ background-color: ${aeroTheme.colors.convai.light}20;
613
+ display: flex;
614
+ align-items: center;
615
+ justify-content: center;
616
+ font-size: 48px;
617
+ font-weight: 600;
618
+ color: var(--convai-accent, ${aeroTheme.colors.convai.light});
619
+ `;
620
+ letter.textContent = characterName[0]?.toUpperCase() || "C";
621
+ clip.appendChild(letter);
622
+ };
623
+ // Create Connecting Overlay -- matches React's inline AnimatePresence
624
+ // block exactly (ConvaiWidget.tsx:681-737): shown whenever
625
+ // `isConnected && !isBotReady`, covering just the content area (not the
626
+ // header/footer) so the chrome stays interactive while the character
627
+ // joins. Persistent in the DOM like voiceModeOverlay above -- toggled via
628
+ // opacity/pointer-events rather than mounted/unmounted, since this file has
629
+ // no AnimatePresence-style exit-animation machinery. Visibility is driven
630
+ // by updateConnectingOverlay().
631
+ const createConnectingOverlay = () => {
632
+ const overlay = document.createElement("div");
633
+ overlay.id = "convai-connecting-overlay";
634
+ overlay.style.cssText = `
635
+ position: absolute;
636
+ inset: 0;
637
+ z-index: 100;
638
+ display: flex;
639
+ flex-direction: column;
640
+ align-items: center;
641
+ justify-content: center;
642
+ gap: 16px;
643
+ background: rgba(255, 255, 255, 0.95);
644
+ opacity: 0;
645
+ pointer-events: none;
646
+ transition: opacity 0.3s;
647
+ `;
648
+ // Keyframes live in the shadow-safe injector (styles.ts), not
649
+ // document.head -- @keyframes defined there do not resolve for shadow
650
+ // content. Idempotent; also called from createSettingsTray().
651
+ injectKeyframes(styleTarget);
652
+ // Spinning logo: a full turn every 2s, linear, infinite.
653
+ const spinWrapper = document.createElement("div");
654
+ spinWrapper.className = "convai-connecting-spin";
655
+ spinWrapper.style.cssText = `
656
+ display: inline-flex;
657
+ animation: convaiConnectingSpin 2s linear infinite;
658
+ `;
659
+ const logo = Icons.ConvaiLogo("xl", "connecting");
660
+ // Themable, like every other accent usage in this file (see
661
+ // theming.test.ts) -- var() with the exact literal React passes
662
+ // (`aeroTheme.colors.convai.light`) as the fallback, so an unset
663
+ // --convai-accent renders identically to the React value.
664
+ logo.style.color = `var(--convai-accent, ${aeroTheme.colors.convai.light})`;
665
+ spinWrapper.appendChild(logo);
666
+ overlay.appendChild(spinWrapper);
667
+ // Pulsing "Connecting to {characterName}..." label.
668
+ const label = document.createElement("div");
669
+ label.id = "convai-connecting-text";
670
+ label.className = "convai-connecting-pulse";
671
+ label.style.cssText = `
672
+ font-size: 14px;
673
+ font-weight: 500;
674
+ color: ${aeroTheme.colors.text.secondary};
675
+ animation: convaiConnectingPulse 2s ease-in-out infinite;
676
+ `;
677
+ refs.connectingLabel = label;
678
+ overlay.appendChild(label);
679
+ return overlay;
680
+ };
681
+ /** Shows/hides the connecting overlay and refreshes its label. Called
682
+ * from updateHeader() so every existing call site (stateChange, botReady,
683
+ * connect/disconnect via stateChange, character-info fetch, ...) stays in
684
+ * sync automatically. */
685
+ const updateConnectingOverlay = () => {
686
+ if (!connectingOverlay)
687
+ return;
688
+ const label = refs.connectingLabel;
689
+ if (label) {
690
+ label.textContent = `Connecting to ${characterName}...`;
691
+ }
692
+ // `isConnecting` matters as much as `isConnected` here. The panel opens
693
+ // on the click that *starts* the connect, so between that click and the
694
+ // transport coming up (a real network round trip — ~3s against the live
695
+ // service) `isConnected` is still false. Gating on it alone left the
696
+ // whole of that window with no overlay at all: an empty message area and
697
+ // a nameless header, i.e. the widget looked broken for exactly as long as
698
+ // it was doing the one thing the user asked for. Then the label appeared
699
+ // *after* the transport was already up, which reads backwards.
700
+ //
701
+ // The embed makes this the normal path rather than an edge case: its
702
+ // launcher click opens the panel immediately by design, so the pre-connect
703
+ // window is always visible to the user.
704
+ const shouldShow = (client.state.isConnected || client.state.isConnecting) && !client.isBotReady;
705
+ connectingOverlay.style.opacity = shouldShow ? "1" : "0";
706
+ connectingOverlay.style.pointerEvents = shouldShow ? "auto" : "none";
707
+ };
293
708
  // Audio Analysis State for Voice Mode
294
709
  let audioLevels = Array(40).fill(0);
295
- let targetLevels = Array(40).fill(0.05);
296
- let currentLevels = Array(40).fill(0.05);
297
710
  let startTime = 0;
298
- // Audio Analysis Logic
711
+ /**
712
+ * Paints the three overlapping sine waves React draws for the user's
713
+ * microphone (VoiceModeOverlay.tsx's `drawWaves`), including its two
714
+ * performance guards, which matter more here than there: this canvas sits
715
+ * over whatever the host page is rendering, and every repaint forces the
716
+ * compositor to re-blend the whole panel. So it runs at 30fps rather than
717
+ * 60, and stops entirely while the input is silent — the static line is
718
+ * already on the canvas at that point.
719
+ */
720
+ let waveFrameParity = 0;
721
+ let waveWasSilent = false;
722
+ const drawWaves = () => {
723
+ const canvas = refs.voiceModeCanvas;
724
+ if (!canvas)
725
+ return;
726
+ waveFrameParity ^= 1;
727
+ if (waveFrameParity)
728
+ return;
729
+ let sum = 0;
730
+ for (let i = 0; i < audioLevels.length; i++)
731
+ sum += audioLevels[i];
732
+ const silent = sum / audioLevels.length < 0.012;
733
+ if (silent && waveWasSilent)
734
+ return;
735
+ waveWasSilent = silent;
736
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
737
+ if (canvas.width !== 250 * dpr) {
738
+ canvas.width = 250 * dpr;
739
+ canvas.height = 80 * dpr;
740
+ }
741
+ const ctx = canvas.getContext("2d");
742
+ if (!ctx)
743
+ return;
744
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
745
+ ctx.clearRect(0, 0, 250, 80);
746
+ const centerY = 40;
747
+ const waveWidth = 250;
748
+ const segments = 40;
749
+ const avgLevel = sum / audioLevels.length;
750
+ const waveColors = [
751
+ aeroTheme.colors.convai.light,
752
+ aeroTheme.colors.convai.light,
753
+ "#34d399",
754
+ ];
755
+ ctx.lineCap = "round";
756
+ ctx.lineJoin = "round";
757
+ for (let waveIndex = 2; waveIndex >= 0; waveIndex--) {
758
+ ctx.beginPath();
759
+ for (let i = 0; i <= segments; i++) {
760
+ const x = (i / segments) * waveWidth;
761
+ const levelIndex = Math.floor((i / segments) * (audioLevels.length - 1));
762
+ const level = audioLevels[levelIndex] || 0;
763
+ const phase = (Date.now() / 500 + i * 0.2 + waveIndex * 1.5) % (Math.PI * 2);
764
+ const baseAmplitude = avgLevel > 0.05 ? 2 + waveIndex * 1.5 : 0;
765
+ const amplitude = baseAmplitude + level * (25 - baseAmplitude);
766
+ const y = centerY + Math.sin(phase) * amplitude;
767
+ if (i === 0)
768
+ ctx.moveTo(x, y);
769
+ else
770
+ ctx.lineTo(x, y);
771
+ }
772
+ ctx.strokeStyle = waveColors[waveIndex];
773
+ ctx.globalAlpha = 0.18 * (0.3 + avgLevel);
774
+ ctx.lineWidth = 2.5 - waveIndex * 0.4 + 8 * avgLevel + 3;
775
+ ctx.stroke();
776
+ ctx.globalAlpha = 0.95 - waveIndex * 0.15;
777
+ ctx.lineWidth = 2.5 - waveIndex * 0.4;
778
+ ctx.stroke();
779
+ }
780
+ ctx.globalAlpha = 1;
781
+ };
782
+ /**
783
+ * The voice-mode frame loop. Keeps the name `updateAudioBars` because
784
+ * every call site refers to it; what it drives is now the avatar, the
785
+ * canvas and the status text rather than forty bars.
786
+ */
299
787
  const updateAudioBars = () => {
300
788
  if (!voiceModeOverlay)
301
789
  return;
302
- const bars = voiceModeOverlay.querySelectorAll(".voice-bar");
303
790
  const isTalking = client.state.isSpeaking;
304
- const isListening = client.state.isListening; // User is speaking (from user-started-speaking)
305
- const isAnimating = isListening || isTalking;
306
- // Update colors based on state
307
- bars.forEach((bar) => {
308
- bar.style.backgroundColor = isTalking
309
- ? aeroTheme.colors.convai.light
310
- : isListening
311
- ? aeroTheme.colors.text.primary
312
- : aeroTheme.colors.neutral[400];
313
- });
314
- // Update Text
315
- const title = document.getElementById("voice-mode-title");
316
- const subtitle = document.getElementById("voice-mode-subtitle");
791
+ const isListening = client.state.isListening;
792
+ const micOpen = !client.audioControls.isAudioMuted;
793
+ // The avatar breathes while the character speaks — React drives the same
794
+ // thing with a framer-motion scale keyframe.
795
+ const avatar = refs.voiceModeAvatar;
796
+ if (avatar) {
797
+ const wanted = isTalking ? "convaiVoiceBreathe 3s ease-in-out infinite" : "";
798
+ if (avatar.style.animation !== wanted)
799
+ avatar.style.animation = wanted;
800
+ }
801
+ // React's exact wording, including "Voice Mode" rather than the
802
+ // "Voice Only Mode" this file used to show.
803
+ const title = refs.voiceModeTitle;
804
+ const subtitle = refs.voiceModeSubtitle;
317
805
  if (title) {
318
806
  title.textContent = isTalking
319
- ? "Character Speaking..."
320
- : isListening
807
+ ? `${characterName} Speaking...`
808
+ : isListening || micOpen
321
809
  ? "Listening..."
322
- : "Voice Only Mode";
810
+ : "Voice Mode";
323
811
  }
324
812
  if (subtitle) {
325
813
  subtitle.textContent =
326
- isListening || isTalking
327
- ? "Audio active"
328
- : "Press and hold the microphone to talk";
814
+ isListening || micOpen || isTalking ? "Audio active" : "Tap microphone to talk";
329
815
  }
330
- // Animation Logic - Matches React version (animate when user or bot is active)
331
- if ((isListening || !client.audioControls.isAudioMuted) && analyzer && dataArray) {
332
- // Use time domain data (waveform) instead of frequency
816
+ if ((isListening || micOpen) && analyzer && dataArray) {
333
817
  // @ts-ignore - TypeScript strict mode issue with Uint8Array type
334
818
  analyzer.getByteTimeDomainData(dataArray);
335
- // Calculate RMS (Root Mean Square) for volume
336
819
  let sum = 0;
337
820
  for (let i = 0; i < dataArray.length; i++) {
338
- const normalized = (dataArray[i] - 128) / 128; // Center around 0
821
+ const normalized = (dataArray[i] - 128) / 128;
339
822
  sum += normalized * normalized;
340
823
  }
341
824
  const rms = Math.sqrt(sum / dataArray.length);
342
- // Apply some scaling and clamping
343
- const volume = Math.min(1, rms * 3); // Boost sensitivity
344
- // Create left-to-right wave effect
345
- const minHeight = 8;
346
- const maxHeight = 70;
347
- bars.forEach((bar, i) => {
348
- // Progressive wave from left to right
349
- const position = i / 40; // 0 to 1 from left to right
825
+ const volume = Math.min(1, rms * 3);
826
+ for (let i = 0; i < audioLevels.length; i++) {
827
+ const position = i / audioLevels.length;
350
828
  const wavePhase = Date.now() / 300 + position * Math.PI * 2;
351
- const waveVariation = Math.sin(wavePhase) * 0.15 + 0.85; // 0.7 to 1.0
352
- const level = volume * waveVariation;
353
- const height = minHeight + level * (maxHeight - minHeight);
354
- bar.style.height = `${Math.max(minHeight, height)}px`;
355
- });
356
- }
357
- else if (isTalking) {
358
- // Simulate speaking bars with natural speech patterns
359
- const elapsed = (Date.now() - startTime) / 1000; // seconds
360
- // Generate new random target levels occasionally (simulating syllables/words)
361
- if (Math.random() < 0.08) {
362
- // 8% chance per frame = ~5 times per second
363
- targetLevels = Array(40)
364
- .fill(0)
365
- .map((_, i) => {
366
- // More variation in the middle bars, less on edges for natural spread
367
- const position = i / 40;
368
- const centerWeight = 1 - Math.abs(position - 0.5) * 0.5;
369
- // Random peaks and valleys like speech patterns
370
- const randomPeak = 0.2 + Math.random() * 0.7; // 0.2 to 0.9
371
- // Add some neighbor correlation so bars don't jump independently
372
- const prevTarget = targetLevels[i] || 0.3;
373
- const correlation = prevTarget * 0.4 + randomPeak * 0.6;
374
- return correlation * centerWeight;
375
- });
829
+ const waveVariation = Math.sin(wavePhase) * 0.15 + 0.85;
830
+ audioLevels[i] = volume * waveVariation;
376
831
  }
377
- // Smoothly interpolate current levels toward targets (organic movement)
378
- currentLevels = currentLevels.map((current, i) => {
379
- const target = targetLevels[i];
380
- const speed = 0.2; // Smooth but responsive
381
- return current + (target - current) * speed;
382
- });
383
- // Apply a gentle fade-in for the first 0.3 seconds
384
- const fadeIn = Math.min(1, elapsed / 0.3);
385
- const minHeight = 8;
386
- const maxHeight = 70;
387
- bars.forEach((bar, i) => {
388
- // Small random jitter for micro-variation
389
- const microJitter = 0.95 + Math.random() * 0.1; // 0.95 to 1.05
390
- const level = Math.max(0.05, Math.min(1, currentLevels[i] * fadeIn * microJitter));
391
- const height = minHeight + level * (maxHeight - minHeight);
392
- bar.style.height = `${Math.max(minHeight, height)}px`;
393
- });
394
832
  }
395
833
  else {
396
- // Reset to idle state
397
- bars.forEach((bar) => {
398
- bar.style.height = "15px";
399
- });
834
+ // The waves settle to a flat line rather than animating on the
835
+ // character's behalf: React paints this canvas from the microphone
836
+ // only, and the character's own speech is the avatar's job.
837
+ for (let i = 0; i < audioLevels.length; i++)
838
+ audioLevels[i] = 0;
400
839
  }
840
+ drawWaves();
401
841
  rafId = requestAnimationFrame(updateAudioBars);
402
842
  };
403
843
  const startAudioAnalysis = async () => {
@@ -419,7 +859,15 @@ export function createConvaiWidget(container, options) {
419
859
  updateAudioBars();
420
860
  }
421
861
  catch (e) {
422
- console.error("Audio analysis setup failed:", e);
862
+ // Fourth mic-acquiring call site: this getUserMedia() is independent
863
+ // of client.audioControls (it's a separate analyser-only stream, not
864
+ // routed through AudioManager), but a denial here is the identical
865
+ // failure mode -- most commonly a mid-session permission revocation,
866
+ // since by the time voice mode is entered the mic has usually already
867
+ // been granted via unmuteAudio(). Same helper, same channel, so a
868
+ // consumer sees one consistent signal regardless of which internal
869
+ // path acquired the mic.
870
+ reportMicFailure(client, "Audio analysis setup failed:", e);
423
871
  }
424
872
  };
425
873
  const stopAudioAnalysis = () => {
@@ -436,13 +884,14 @@ export function createConvaiWidget(container, options) {
436
884
  // Create header
437
885
  const createHeader = () => {
438
886
  const header = document.createElement("div");
887
+ header.setAttribute("part", "header");
439
888
  header.style.cssText = `
440
889
  display: flex;
441
890
  align-items: center;
442
891
  justify-content: space-between;
443
- padding: 1rem;
892
+ padding: 16px;
444
893
  border-bottom: 1px solid ${aeroTheme.colors.neutral[200]};
445
- background: white;
894
+ background: var(--convai-panel-bg, white);
446
895
  position: relative;
447
896
  `;
448
897
  // Close button on the left
@@ -450,10 +899,10 @@ export function createConvaiWidget(container, options) {
450
899
  const chevronIcon = Icons.ChevronDown("md");
451
900
  closeButton.appendChild(chevronIcon);
452
901
  closeButton.style.cssText = `
453
- font-size: 1.25rem;
902
+ font-size: 20px;
454
903
  color: ${aeroTheme.colors.text.secondary};
455
904
  cursor: pointer;
456
- padding: 0.25rem;
905
+ padding: 4px;
457
906
  transition: ${aeroTheme.transitions.fast};
458
907
  background: transparent;
459
908
  border: none;
@@ -470,21 +919,22 @@ export function createConvaiWidget(container, options) {
470
919
  transform: translateX(-50%);
471
920
  display: flex;
472
921
  align-items: center;
473
- gap: 0.5rem;
922
+ gap: 8px;
474
923
  font-size: ${aeroTheme.typography.fontSize.base};
475
924
  font-weight: ${aeroTheme.typography.fontWeight.semibold};
476
- color: ${aeroTheme.colors.text.primary};
925
+ color: var(--convai-panel-fg, ${aeroTheme.colors.text.primary});
477
926
  `;
478
927
  titleSection.id = "convai-widget-title";
928
+ refs.widgetTitle = titleSection;
479
929
  // Settings button on the right
480
930
  const settingsButton = document.createElement("button");
481
931
  const moreIcon = Icons.MoreVertical("md");
482
932
  settingsButton.appendChild(moreIcon);
483
933
  settingsButton.style.cssText = `
484
- font-size: 1.5rem;
934
+ font-size: 24px;
485
935
  color: ${aeroTheme.colors.text.secondary};
486
936
  cursor: pointer;
487
- padding: 0.25rem;
937
+ padding: 4px;
488
938
  transition: ${aeroTheme.transitions.fast};
489
939
  background: transparent;
490
940
  border: none;
@@ -501,7 +951,7 @@ export function createConvaiWidget(container, options) {
501
951
  };
502
952
  // Update header with character info
503
953
  const updateHeader = () => {
504
- const titleSection = document.getElementById("convai-widget-title");
954
+ const titleSection = refs.widgetTitle;
505
955
  if (!titleSection)
506
956
  return;
507
957
  titleSection.innerHTML = "";
@@ -510,8 +960,8 @@ export function createConvaiWidget(container, options) {
510
960
  img.src = characterImage;
511
961
  img.alt = characterName;
512
962
  img.style.cssText = `
513
- width: 1.5rem;
514
- height: 1.5rem;
963
+ width: 24px;
964
+ height: 24px;
515
965
  border-radius: 50%;
516
966
  object-fit: cover;
517
967
  border: 1.5px solid ${getBotStatusColor().color};
@@ -541,7 +991,7 @@ export function createConvaiWidget(container, options) {
541
991
  padding: 0;
542
992
  display: inline-flex;
543
993
  align-items: center;
544
- margin-left: 0.5rem;
994
+ margin-left: 8px;
545
995
  outline: none;
546
996
  transition: transform 0.1s ease-out;
547
997
  `;
@@ -562,7 +1012,7 @@ export function createConvaiWidget(container, options) {
562
1012
  voiceBadge.textContent = "VOICE";
563
1013
  voiceBadge.style.cssText = `
564
1014
  font-size: 10px;
565
- color: ${aeroTheme.colors.convai.light};
1015
+ color: var(--convai-accent, ${aeroTheme.colors.convai.light});
566
1016
  font-weight: 500;
567
1017
  margin-left: 8px;
568
1018
  padding: 2px 6px;
@@ -627,15 +1077,22 @@ export function createConvaiWidget(container, options) {
627
1077
  listeningTag.insertBefore(dot, listeningTag.firstChild);
628
1078
  titleSection.appendChild(listeningTag);
629
1079
  }
1080
+ // Every call site that refreshes the header (stateChange, botReady,
1081
+ // connect/disconnect via stateChange, character-info fetch, ...) also
1082
+ // needs the connecting overlay re-evaluated -- it depends on the same
1083
+ // `isConnected`/`isBotReady`/`characterName` inputs.
1084
+ updateConnectingOverlay();
1085
+ updateVoiceModeAvatar();
630
1086
  };
631
1087
  // Create message list
632
1088
  const createMessageList = () => {
633
1089
  const list = document.createElement("div");
634
1090
  list.id = "convai-message-list";
1091
+ list.setAttribute("part", "messages");
635
1092
  list.style.cssText = `
636
1093
  display: flex;
637
1094
  flex-direction: column;
638
- gap: 0.75rem;
1095
+ gap: 12px;
639
1096
  min-height: 100%;
640
1097
  `;
641
1098
  return list;
@@ -644,22 +1101,23 @@ export function createConvaiWidget(container, options) {
644
1101
  const createFooter = () => {
645
1102
  const footer = document.createElement("div");
646
1103
  footer.style.cssText = `
647
- padding: 1rem;
1104
+ padding: 16px;
648
1105
  border-top: 1px solid ${aeroTheme.colors.neutral[200]};
649
- background: white;
1106
+ background: var(--convai-panel-bg, white);
650
1107
  display: flex;
651
- gap: 0.5rem;
1108
+ gap: 8px;
652
1109
  align-items: center;
653
1110
  position: relative;
654
1111
  `;
655
1112
  // Voice Mode Exit Button (Initially hidden)
656
1113
  const voiceExitButton = document.createElement("button");
657
1114
  voiceExitButton.id = "convai-voice-exit-btn";
1115
+ refs.voiceExitBtn = voiceExitButton;
658
1116
  const exitIcon = Icons.PhoneOff("md");
659
1117
  voiceExitButton.appendChild(exitIcon);
660
1118
  voiceExitButton.style.cssText = `
661
- width: 2.25rem;
662
- height: 2.25rem;
1119
+ width: 36px;
1120
+ height: 36px;
663
1121
  border-radius: 50%;
664
1122
  background: ${aeroTheme.colors.error[500]};
665
1123
  color: white;
@@ -670,19 +1128,31 @@ export function createConvaiWidget(container, options) {
670
1128
  margin: 0 auto;
671
1129
  border: none;
672
1130
  `;
673
- voiceExitButton.addEventListener("click", async () => {
1131
+ voiceExitButton.addEventListener("click", () => {
1132
+ // Deliberately a *sync* listener. It used to be `async` with a bare
1133
+ // `await client.audioControls.muteAudio()` and no try/catch: on the
1134
+ // LiveKit path that call rethrows when the room has dropped, so a
1135
+ // network blip mid-call plus a tap on exit leaked an unhandled
1136
+ // rejection onto the host page *and* skipped the two lines below,
1137
+ // stranding the user in the voice overlay with no way out.
1138
+ //
1139
+ // The mute is not dropped -- `applyVoiceMode()` -> `updateVoiceMode()`
1140
+ // performs it (conditionally, if the mic is live) inside the exit
1141
+ // branch, where a failure is now reported rather than fatal. Exiting
1142
+ // the UI is unconditional either way: the overlay must never outlive
1143
+ // the user's decision to leave it.
674
1144
  client.sendInterruptMessage();
675
- await client.audioControls.muteAudio(); // Mute on exit
676
1145
  isVoiceMode = false;
677
- updateVoiceMode();
1146
+ applyVoiceMode();
678
1147
  });
679
1148
  footer.appendChild(voiceExitButton);
680
1149
  // Standard Footer Content (Mic + Input)
681
1150
  const standardContent = document.createElement("div");
682
1151
  standardContent.id = "convai-footer-standard";
1152
+ refs.footerStandard = standardContent;
683
1153
  standardContent.style.cssText = `
684
1154
  display: flex;
685
- gap: 0.5rem;
1155
+ gap: 8px;
686
1156
  align-items: center;
687
1157
  width: 100%;
688
1158
  `;
@@ -695,15 +1165,16 @@ export function createConvaiWidget(container, options) {
695
1165
  align-items: center;
696
1166
  `;
697
1167
  inputElement = document.createElement("input");
1168
+ inputElement.setAttribute("part", "input");
698
1169
  inputElement.type = "text";
699
1170
  inputElement.placeholder = "Conversation";
700
1171
  inputElement.style.cssText = `
701
1172
  width: 100%;
702
- padding: 0.75rem 2.75rem 0.75rem 1rem;
1173
+ padding: 12px 44px 12px 16px;
703
1174
  border-radius: ${aeroTheme.borderRadius.full};
704
1175
  border: 1px solid ${aeroTheme.colors.neutral[300]};
705
1176
  background: ${aeroTheme.colors.glass.medium};
706
- color: ${aeroTheme.colors.text.primary};
1177
+ color: var(--convai-panel-fg, ${aeroTheme.colors.text.primary});
707
1178
  font-size: ${aeroTheme.typography.fontSize.sm};
708
1179
  transition: ${aeroTheme.transitions.fast};
709
1180
  outline: none;
@@ -719,16 +1190,22 @@ export function createConvaiWidget(container, options) {
719
1190
  // Send button
720
1191
  const sendButton = document.createElement("button");
721
1192
  sendButton.id = "convai-send-button";
1193
+ // This button is dual-role -- it sends text when the input has a draft,
1194
+ // and toggles voice mode when empty -- but there is no separate mic
1195
+ // element, so only the send-button part applies. `mic-button` is
1196
+ // reserved for a future version that splits the two; see parts.test.ts.
1197
+ sendButton.setAttribute("part", "send-button");
1198
+ refs.sendButton = sendButton;
722
1199
  const sendIcon = Icons.Send("md");
723
1200
  sendButton.appendChild(sendIcon);
724
1201
  sendButton.style.cssText = `
725
1202
  position: absolute;
726
- right: 0.375rem;
727
- width: 2.25rem;
728
- height: 2.25rem;
1203
+ right: 6px;
1204
+ width: 36px;
1205
+ height: 36px;
729
1206
  border-radius: 50%;
730
1207
  background: transparent; /* Initial transparent for voice toggle */
731
- color: ${aeroTheme.colors.text.primary};
1208
+ color: var(--convai-panel-fg, ${aeroTheme.colors.text.primary});
732
1209
  display: flex;
733
1210
  align-items: center;
734
1211
  justify-content: center;
@@ -744,9 +1221,19 @@ export function createConvaiWidget(container, options) {
744
1221
  client.connectionType !== "text") {
745
1222
  // Toggle Voice Mode
746
1223
  client.sendInterruptMessage();
747
- await client.audioControls.unmuteAudio(); // Unmute on enter
748
- isVoiceMode = true;
749
- updateVoiceMode();
1224
+ try {
1225
+ await client.audioControls.unmuteAudio(); // Unmute on enter
1226
+ isVoiceMode = true;
1227
+ // Awaited so this try/catch actually covers it -- bare, the promise
1228
+ // escaped the block it looks like it belongs to.
1229
+ await updateVoiceMode();
1230
+ }
1231
+ catch (error) {
1232
+ // isVoiceMode is only flipped after a successful unmute, so a
1233
+ // denial here leaves the widget in text mode, not stranded
1234
+ // mid-transition into voice mode.
1235
+ reportMicFailure(client, "Failed to enable microphone:", error);
1236
+ }
750
1237
  }
751
1238
  });
752
1239
  inputContainer.appendChild(inputElement);
@@ -763,7 +1250,7 @@ export function createConvaiWidget(container, options) {
763
1250
  position: absolute;
764
1251
  top: 60px;
765
1252
  right: 16px;
766
- background: white;
1253
+ background: var(--convai-panel-bg, white);
767
1254
  border-radius: ${aeroTheme.borderRadius.xl};
768
1255
  box-shadow: ${aeroTheme.shadows.xl};
769
1256
  padding: 0;
@@ -778,17 +1265,7 @@ export function createConvaiWidget(container, options) {
778
1265
  overflow: hidden;
779
1266
  `;
780
1267
  // Add animation keyframes if not present
781
- if (!document.getElementById("convai-widget-keyframes")) {
782
- const style = document.createElement("style");
783
- style.id = "convai-widget-keyframes";
784
- style.textContent = `
785
- @keyframes popIn {
786
- from { opacity: 0; transform: scale(0.95) translateY(-10px); }
787
- to { opacity: 1; transform: scale(1) translateY(0); }
788
- }
789
- `;
790
- document.head.appendChild(style);
791
- }
1268
+ injectKeyframes(styleTarget);
792
1269
  // Horizontal Settings Row Container
793
1270
  const settingsRow = document.createElement("div");
794
1271
  settingsRow.style.cssText = `
@@ -817,7 +1294,7 @@ export function createConvaiWidget(container, options) {
817
1294
  ? "#10b981"
818
1295
  : isDestructive
819
1296
  ? "#ef4444"
820
- : aeroTheme.colors.text.primary};
1297
+ : `var(--convai-panel-fg, ${aeroTheme.colors.text.primary})`};
821
1298
  transition: ${aeroTheme.transitions.fast};
822
1299
  min-width: 50px;
823
1300
  `;
@@ -869,6 +1346,7 @@ export function createConvaiWidget(container, options) {
869
1346
  videoIcon.style.height = "18px";
870
1347
  const videoBtn = createOption(videoIcon, "Video", handleToggleVideo, isVideoVisible);
871
1348
  videoBtn.id = "convai-settings-video-btn";
1349
+ refs.settingsVideoBtn = videoBtn;
872
1350
  settingsRow.appendChild(videoBtn);
873
1351
  }
874
1352
  // Screen Share - only show if connection type is video
@@ -881,6 +1359,7 @@ export function createConvaiWidget(container, options) {
881
1359
  shareIcon.style.height = "18px";
882
1360
  const shareBtn = createOption(shareIcon, "Screen", handleToggleScreenShare, isSharing);
883
1361
  shareBtn.id = "convai-settings-share-btn";
1362
+ refs.settingsShareBtn = shareBtn;
884
1363
  settingsRow.appendChild(shareBtn);
885
1364
  }
886
1365
  // Disconnect
@@ -919,7 +1398,7 @@ export function createConvaiWidget(container, options) {
919
1398
  ? "#10b981"
920
1399
  : isDestructive
921
1400
  ? "#ef4444"
922
- : aeroTheme.colors.text.primary};
1401
+ : `var(--convai-panel-fg, ${aeroTheme.colors.text.primary})`};
923
1402
  transition: ${aeroTheme.transitions.fast};
924
1403
  min-width: 50px;
925
1404
  `;
@@ -971,6 +1450,7 @@ export function createConvaiWidget(container, options) {
971
1450
  videoIcon.style.height = "18px";
972
1451
  const videoBtn = createOption(videoIcon, "Video", handleToggleVideo, isVideoVisible);
973
1452
  videoBtn.id = "convai-settings-video-btn";
1453
+ refs.settingsVideoBtn = videoBtn;
974
1454
  settingsRow.appendChild(videoBtn);
975
1455
  }
976
1456
  // Screen Share - Always show if showScreenShare is true and connection type is video
@@ -983,6 +1463,7 @@ export function createConvaiWidget(container, options) {
983
1463
  shareIcon.style.height = "18px";
984
1464
  const shareBtn = createOption(shareIcon, "Screen", handleToggleScreenShare, isSharing);
985
1465
  shareBtn.id = "convai-settings-share-btn";
1466
+ refs.settingsShareBtn = shareBtn;
986
1467
  settingsRow.appendChild(shareBtn);
987
1468
  }
988
1469
  // Disconnect
@@ -997,6 +1478,12 @@ export function createConvaiWidget(container, options) {
997
1478
  const createFloatingVideo = () => {
998
1479
  const container = document.createElement("div");
999
1480
  container.id = "floating-video-container";
1481
+ // NOTE on z-index: deliberately NOT themable. `--convai-z-index` drives the
1482
+ // widget root only. Both elements are `position: fixed` and this one is
1483
+ // appended *before* the widget root, so on a tie the widget paints on top:
1484
+ // a host raising the token to clear their nav bar would hide the user's own
1485
+ // camera preview behind the panel. Video/screen share are also out of scope
1486
+ // for the embed, which is chat-only.
1000
1487
  container.style.cssText = `
1001
1488
  position: fixed;
1002
1489
  left: 20px;
@@ -1178,16 +1665,18 @@ export function createConvaiWidget(container, options) {
1178
1665
  };
1179
1666
  // Event handlers
1180
1667
  const handleToggle = async () => {
1181
- if (isDestroyed || isStartingConnection) {
1668
+ if (isDestroyed)
1182
1669
  return;
1183
- }
1184
- if (isOpen) {
1185
- // Just close if already open
1670
+ if (isOpen || pendingOpen) {
1671
+ // Already open, or an open is already in flight: nothing to do. The
1672
+ // `pendingOpen` half is what keeps a repeat call from falling through
1673
+ // to the `isConnecting` branch below and opening the panel *before* the
1674
+ // connect it is waiting on has finished.
1186
1675
  return;
1187
1676
  }
1188
1677
  // Connect on first click if not already connected/connecting
1189
1678
  if (!client.state.isConnected && !client.state.isConnecting) {
1190
- isStartingConnection = true;
1679
+ pendingOpen = true;
1191
1680
  try {
1192
1681
  if (requestPublicationGrant || client.isPublishedChatSession) {
1193
1682
  if (!requestPublicationGrant) {
@@ -1217,6 +1706,20 @@ export function createConvaiWidget(container, options) {
1217
1706
  await client.disconnect();
1218
1707
  return;
1219
1708
  }
1709
+ // Re-checked *after* the await: a close()/toggle()/launcher click
1710
+ // during the connect clears the flag, and that cancellation has to
1711
+ // win. The client stays connected either way -- only the panel is
1712
+ // held back -- so a later open() takes the already-connected branch
1713
+ // and opens instantly.
1714
+ if (isDestroyed) {
1715
+ // destroy() can also run after the grant is exchanged but before
1716
+ // Core or LiveKit finishes connecting. Disconnect that late session
1717
+ // instead of leaving an invisible room alive.
1718
+ await client.disconnect();
1719
+ return;
1720
+ }
1721
+ if (!pendingOpen)
1722
+ return;
1220
1723
  setIsOpen(true);
1221
1724
  }
1222
1725
  catch (error) {
@@ -1225,7 +1728,7 @@ export function createConvaiWidget(container, options) {
1225
1728
  }
1226
1729
  }
1227
1730
  finally {
1228
- isStartingConnection = false;
1731
+ pendingOpen = false;
1229
1732
  }
1230
1733
  }
1231
1734
  else {
@@ -1233,11 +1736,29 @@ export function createConvaiWidget(container, options) {
1233
1736
  setIsOpen(!isOpen);
1234
1737
  }
1235
1738
  };
1739
+ /** A launcher click while an open is pending means "cancel", same as `toggle()`. */
1740
+ const handleLauncherClick = () => {
1741
+ if (pendingOpen) {
1742
+ handleClose();
1743
+ return;
1744
+ }
1745
+ void handleToggle();
1746
+ };
1236
1747
  const handleClose = () => {
1748
+ // Cancels an in-flight open as well as closing an open panel; see
1749
+ // `pendingOpen`. `setIsOpen(false)` on an already-closed widget just
1750
+ // re-applies the collapsed styles, so this is safe in both cases.
1751
+ pendingOpen = false;
1237
1752
  setIsOpen(false);
1238
1753
  };
1754
+ // Published sessions must wait for Core's bot-ready handshake. A normal
1755
+ // authenticated text session still gets the text-only UI, but can send as
1756
+ // soon as it connects.
1757
+ const requiresBotReadyForText = () => Boolean(requestPublicationGrant) || Boolean(client.isPublishedChatSession);
1758
+ const isTextInputReady = () => client.state.isConnected &&
1759
+ (!requiresBotReadyForText() || client.isBotReady);
1239
1760
  const handleSend = () => {
1240
- if (inputValue.trim() && client.state.isConnected && client.isBotReady) {
1761
+ if (inputValue.trim() && isTextInputReady()) {
1241
1762
  client.sendUserTextMessage(inputValue);
1242
1763
  inputValue = "";
1243
1764
  inputElement.value = "";
@@ -1268,7 +1789,7 @@ export function createConvaiWidget(container, options) {
1268
1789
  isVoiceMode = false;
1269
1790
  hasEnteredDefaultVoiceMode = false;
1270
1791
  updateHeader();
1271
- updateVoiceMode();
1792
+ await updateVoiceMode();
1272
1793
  updateSendButton();
1273
1794
  }
1274
1795
  catch (error) {
@@ -1282,7 +1803,11 @@ export function createConvaiWidget(container, options) {
1282
1803
  isVoiceMode = false;
1283
1804
  hasEnteredDefaultVoiceMode = false;
1284
1805
  updateHeader();
1285
- updateVoiceMode();
1806
+ // Not awaited: this function has no try/catch of its own and is wired
1807
+ // straight to a click, so awaiting would only move a rejection from one
1808
+ // unguarded place to another. See the note on `handleDisconnect`'s own
1809
+ // `await client.disconnect()` in the fix report.
1810
+ applyVoiceMode();
1286
1811
  updateSendButton();
1287
1812
  };
1288
1813
  const handleToggleVideo = async () => {
@@ -1321,10 +1846,17 @@ export function createConvaiWidget(container, options) {
1321
1846
  const setIsOpen = async (open) => {
1322
1847
  isOpen = open;
1323
1848
  if (open) {
1324
- morphingContainer.style.width = "400px";
1325
- morphingContainer.style.height = "600px";
1326
- morphingContainer.style.borderRadius = aeroTheme.borderRadius.xl;
1849
+ morphingContainer.style.width = `${PANEL_W_PX}px`;
1850
+ morphingContainer.style.height = `${PANEL_H_PX}px`;
1851
+ morphingContainer.style.borderRadius = `var(--convai-radius, ${aeroTheme.borderRadius.xl})`;
1327
1852
  morphingContainer.style.cursor = "default";
1853
+ // The open panel is a *different* glass treatment from the launcher
1854
+ // bubble, matching the React widget: near-opaque and saturated, so the
1855
+ // host page does not bleed through. At the bubble's 0.8 alpha a dark
1856
+ // host page shows through the panel and reads as grey.
1857
+ morphingContainer.style.background =
1858
+ "var(--convai-panel-bg, rgba(252, 252, 253, 0.95))";
1859
+ morphingContainer.style.backdropFilter = "blur(20px) saturate(180%)";
1328
1860
  buttonContent.style.opacity = "0";
1329
1861
  buttonContent.style.transform = "scale(0.8)";
1330
1862
  buttonContent.style.pointerEvents = "none";
@@ -1342,19 +1874,24 @@ export function createConvaiWidget(container, options) {
1342
1874
  await client.audioControls.unmuteAudio();
1343
1875
  isVoiceMode = true;
1344
1876
  hasEnteredDefaultVoiceMode = true;
1345
- updateVoiceMode();
1877
+ await updateVoiceMode();
1346
1878
  }
1347
1879
  catch (error) {
1348
- console.error("Failed to enter voice mode on open:", error);
1880
+ reportMicFailure(client, "Failed to enter voice mode on open:", error);
1349
1881
  }
1350
1882
  }, 100);
1351
1883
  }
1352
1884
  }
1353
1885
  else {
1354
- morphingContainer.style.width = "4rem";
1355
- morphingContainer.style.height = "4rem";
1886
+ morphingContainer.style.width = "var(--convai-launcher-size, 64px)";
1887
+ morphingContainer.style.height = "var(--convai-launcher-size, 64px)";
1888
+ // Literal, not `--convai-radius` — see the creation site: that token is
1889
+ // the *panel* radius, and reusing it here would squircle the launcher.
1356
1890
  morphingContainer.style.borderRadius = "50%";
1357
1891
  morphingContainer.style.cursor = "pointer";
1892
+ // Back to the launcher bubble's lighter glass — see the open branch.
1893
+ morphingContainer.style.background = `var(--convai-panel-bg, ${aeroTheme.colors.glass.backdrop})`;
1894
+ morphingContainer.style.backdropFilter = aeroTheme.glass.backdrop;
1358
1895
  buttonContent.style.opacity = "1";
1359
1896
  buttonContent.style.transform = "scale(1)";
1360
1897
  buttonContent.style.pointerEvents = "auto";
@@ -1368,35 +1905,52 @@ export function createConvaiWidget(container, options) {
1368
1905
  settingsTray.style.display = open ? "flex" : "none";
1369
1906
  };
1370
1907
  const updateSendButton = () => {
1371
- const sendButton = document.getElementById("convai-send-button");
1908
+ const sendButton = refs.sendButton;
1372
1909
  if (!sendButton)
1373
1910
  return;
1374
1911
  // Clear previous content
1375
1912
  sendButton.innerHTML = "";
1376
- const canSendText = client.state.isConnected && client.isBotReady;
1377
- inputElement.disabled = !canSendText;
1913
+ // A published session must wait for Core's bot-ready handshake before
1914
+ // accepting text. Preserve the established interactive-widget behavior
1915
+ // for authenticated voice/video sessions.
1916
+ const isPublishedTextChat = requiresBotReadyForText();
1917
+ const textInputReady = isTextInputReady();
1918
+ inputElement.disabled = isPublishedTextChat && !textInputReady;
1378
1919
  if (inputValue.length > 0 ||
1379
1920
  requestPublicationGrant ||
1380
1921
  client.connectionType === "text") {
1381
1922
  // Show Send Button
1382
1923
  sendButton.appendChild(Icons.Send("md"));
1383
- sendButton.style.background = aeroTheme.colors.text.primary;
1384
- sendButton.style.color = "white";
1924
+ sendButton.style.background = `var(--convai-accent, ${aeroTheme.colors.text.primary})`;
1925
+ // The label sits *on* the accent fill, so it must follow the panel
1926
+ // surface colour rather than stay a hardcoded "white" -- a host setting
1927
+ // a pale --convai-accent would otherwise get white-on-white. `white` is
1928
+ // byte-identical to the fallback --convai-panel-bg already carries at
1929
+ // its three other sites, so the default rendering is unchanged.
1930
+ // Pairing requirement for hosts: --convai-accent and --convai-panel-bg
1931
+ // must contrast with each other, since this is the one place they meet.
1932
+ sendButton.style.color = "var(--convai-panel-bg, white)";
1385
1933
  sendButton.style.border = "none";
1386
- sendButton.disabled = inputValue.length === 0 || !canSendText;
1387
- sendButton.style.opacity =
1388
- inputValue.length > 0 && canSendText ? "1" : "0.5";
1389
- sendButton.title = canSendText
1390
- ? inputValue.length > 0
1391
- ? "Send"
1392
- : "Type a message"
1393
- : "Waiting for character";
1934
+ sendButton.disabled =
1935
+ isPublishedTextChat && (inputValue.length === 0 || !textInputReady);
1936
+ if (isPublishedTextChat) {
1937
+ sendButton.style.opacity =
1938
+ inputValue.length > 0 && textInputReady ? "1" : "0.5";
1939
+ sendButton.title = textInputReady
1940
+ ? inputValue.length > 0
1941
+ ? "Send"
1942
+ : "Type a message"
1943
+ : "Waiting for character";
1944
+ }
1945
+ else {
1946
+ sendButton.title = "Send";
1947
+ }
1394
1948
  }
1395
1949
  else {
1396
1950
  // Show Voice Mode Toggle
1397
1951
  sendButton.appendChild(Icons.Waveform("md"));
1398
1952
  sendButton.style.background = "transparent";
1399
- sendButton.style.color = aeroTheme.colors.text.primary;
1953
+ sendButton.style.color = `var(--convai-panel-fg, ${aeroTheme.colors.text.primary})`;
1400
1954
  sendButton.style.border = `1px solid ${aeroTheme.colors.neutral[300]}`;
1401
1955
  sendButton.style.opacity = "1";
1402
1956
  sendButton.disabled = false;
@@ -1429,8 +1983,8 @@ export function createConvaiWidget(container, options) {
1429
1983
  }
1430
1984
  };
1431
1985
  const updateVoiceMode = async () => {
1432
- const standardFooter = document.getElementById("convai-footer-standard");
1433
- const voiceExitBtn = document.getElementById("convai-voice-exit-btn");
1986
+ const standardFooter = refs.footerStandard;
1987
+ const voiceExitBtn = refs.voiceExitBtn;
1434
1988
  if (isVoiceMode) {
1435
1989
  // Show Voice Overlay
1436
1990
  if (voiceModeOverlay)
@@ -1450,15 +2004,26 @@ export function createConvaiWidget(container, options) {
1450
2004
  updateHeader();
1451
2005
  // Reset animation state for voice mode
1452
2006
  startTime = Date.now();
1453
- currentLevels = Array(40).fill(0.05);
1454
- targetLevels = Array(40).fill(0.05);
1455
2007
  // Start Audio Analysis
1456
2008
  startAudioAnalysis();
1457
2009
  }
1458
2010
  else {
1459
- // Ensure microphone is muted when not in voice mode
2011
+ // Ensure microphone is muted when not in voice mode.
2012
+ //
2013
+ // This await is the only one in this function that can reject, and
2014
+ // everything below it -- hiding the overlay, restoring the standard
2015
+ // footer, updating the header, stopping the analyser -- is the only
2016
+ // route out of the voice UI. So a failed mute must never short-circuit
2017
+ // it: report it and carry on tearing the overlay down. (LiveKit's
2018
+ // setMicrophoneEnabled(false) rethrows on a dropped room, which is
2019
+ // exactly when the user is most likely to be hitting exit.)
1460
2020
  if (!client.audioControls.isAudioMuted) {
1461
- await client.audioControls.muteAudio();
2021
+ try {
2022
+ await client.audioControls.muteAudio();
2023
+ }
2024
+ catch (error) {
2025
+ reportMicFailure(client, "Failed to mute microphone:", error);
2026
+ }
1462
2027
  }
1463
2028
  // Hide Overlay
1464
2029
  if (voiceModeOverlay)
@@ -1490,9 +2055,31 @@ export function createConvaiWidget(container, options) {
1490
2055
  stopAudioAnalysis();
1491
2056
  }
1492
2057
  };
2058
+ /**
2059
+ * Fire-and-forget `updateVoiceMode()` for the call sites that are
2060
+ * synchronous (DOM listeners, the constructor tail) and therefore have no
2061
+ * caller to catch anything it rejects with.
2062
+ *
2063
+ * `updateVoiceMode()` is `async`, so a bare call there would put a floating
2064
+ * promise on the host page. Its one rejecting await is now guarded
2065
+ * internally, which makes this belt-and-braces -- but it is the guarantee
2066
+ * that keeps a future await added inside `updateVoiceMode()` from silently
2067
+ * reintroducing the unhandled rejection this replaces. Routed through
2068
+ * `reportMicFailure` so a failure is observable on the client's `error`
2069
+ * channel rather than console-only.
2070
+ */
2071
+ const applyVoiceMode = () => {
2072
+ void updateVoiceMode().catch((error) => {
2073
+ reportMicFailure(client, "Failed to apply voice mode:", error);
2074
+ });
2075
+ };
1493
2076
  // Microphone button removed - only controlled via voice mode now
1494
2077
  // Helper for Markdown - matches React MarkdownRenderer.tsx
1495
- const renderMarkdown = (text, container) => {
2078
+ // `media` renders inline image/video previews under a media link. Bot messages
2079
+ // want them; the user's own bubble does not — you already know what you typed,
2080
+ // and a preview there would let a URL a user pasted embed remote media into
2081
+ // the transcript. Links stay clickable either way.
2082
+ const renderMarkdown = (text, container, { media = true } = {}) => {
1496
2083
  if (!text)
1497
2084
  return;
1498
2085
  // Handle both actual newlines and \n escape sequences
@@ -1500,59 +2087,183 @@ export function createConvaiWidget(container, options) {
1500
2087
  const lines = normalizedText.split("\n");
1501
2088
  lines.forEach((line, lineIndex) => {
1502
2089
  // Process markdown within each line
2090
+ // Bold, italic, links, images and bare URLs — see utils/inlineMarkdown.
2091
+ // `cdn.example.com/a/b/c.png` -> `cdn.example.com · c.png`
2092
+ const describeUrl = (url) => {
2093
+ try {
2094
+ const { host, pathname } = new URL(url);
2095
+ const file = pathname.split("/").filter(Boolean).pop();
2096
+ return file ? `${host} · ${file}` : host;
2097
+ }
2098
+ catch {
2099
+ return url;
2100
+ }
2101
+ };
2102
+ /**
2103
+ * A preview card that reserves its space before the media arrives, so the
2104
+ * bubble does not jump when an image decodes, and collapses to one muted
2105
+ * line if the URL does not resolve — a character can easily invent one,
2106
+ * and an empty player in the transcript reads as a broken widget.
2107
+ *
2108
+ * Chrome is derived from the inherited text colour: the widget is embedded
2109
+ * in someone else's page, on a background this code cannot know.
2110
+ */
2111
+ const mediaPreview = (src, alt, media) => {
2112
+ const card = document.createElement("span");
2113
+ card.setAttribute("part", "message-media-card");
2114
+ card.style.cssText = `
2115
+ display: block;
2116
+ position: relative;
2117
+ margin-top: 6px;
2118
+ max-width: 320px;
2119
+ aspect-ratio: 16 / 10;
2120
+ border-radius: 8px;
2121
+ overflow: hidden;
2122
+ background: color-mix(in srgb, currentColor 6%, transparent);
2123
+ box-shadow: inset 0 0 0 1px color-mix(in srgb, currentColor 10%, transparent);
2124
+ `;
2125
+ const el = media === "image"
2126
+ ? Object.assign(document.createElement("img"), { src, alt, loading: "lazy" })
2127
+ : Object.assign(document.createElement("video"), { src, controls: true, preload: "metadata" });
2128
+ el.setAttribute("part", "message-media");
2129
+ el.style.cssText = `
2130
+ display: block;
2131
+ width: 100%;
2132
+ height: 100%;
2133
+ object-fit: ${media === "image" ? "cover" : "contain"};
2134
+ border-radius: 8px;
2135
+ opacity: 0;
2136
+ transition: opacity .18s ease;
2137
+ `;
2138
+ const skeleton = document.createElement("span");
2139
+ skeleton.setAttribute("part", "message-media-skeleton");
2140
+ skeleton.setAttribute("aria-hidden", "true");
2141
+ skeleton.dataset.convaiSkeleton = "";
2142
+ skeleton.style.cssText = `
2143
+ position: absolute;
2144
+ inset: 0;
2145
+ border-radius: 8px;
2146
+ background: color-mix(in srgb, currentColor 8%, transparent);
2147
+ background-image: linear-gradient(90deg, transparent, color-mix(in srgb, currentColor 12%, transparent), transparent);
2148
+ background-size: 200% 100%;
2149
+ animation: convai-preview-shimmer 1.4s ease-in-out infinite;
2150
+ `;
2151
+ const caption = document.createElement("span");
2152
+ caption.setAttribute("part", "message-media-caption");
2153
+ caption.textContent = describeUrl(src);
2154
+ caption.style.cssText = `
2155
+ display: block;
2156
+ margin-top: 4px;
2157
+ font-size: 11px;
2158
+ opacity: .7;
2159
+ white-space: nowrap;
2160
+ overflow: hidden;
2161
+ text-overflow: ellipsis;
2162
+ `;
2163
+ const settled = () => {
2164
+ el.style.opacity = "1";
2165
+ skeleton.remove();
2166
+ };
2167
+ el.addEventListener(media === "image" ? "load" : "loadedmetadata", settled);
2168
+ el.addEventListener("error", () => {
2169
+ const dead = document.createElement("span");
2170
+ dead.setAttribute("part", "message-media-unavailable");
2171
+ dead.textContent = `Preview unavailable — ${describeUrl(src)}`;
2172
+ dead.style.cssText = `
2173
+ display: block;
2174
+ margin-top: 6px;
2175
+ font-size: 11px;
2176
+ opacity: .55;
2177
+ font-style: italic;
2178
+ white-space: nowrap;
2179
+ overflow: hidden;
2180
+ text-overflow: ellipsis;
2181
+ `;
2182
+ card.replaceWith(dead);
2183
+ caption.remove();
2184
+ });
2185
+ card.appendChild(el);
2186
+ card.appendChild(skeleton);
2187
+ const frag = document.createDocumentFragment();
2188
+ frag.appendChild(card);
2189
+ frag.appendChild(caption);
2190
+ return frag;
2191
+ };
1503
2192
  const processLine = (text) => {
1504
2193
  const parts = [];
1505
- let remaining = text;
1506
- // Process bold and italic markdown
1507
- // Bold: **text** or __text__
1508
- // Italic: *text* or _text_
1509
- const markdownRegex = /(\*\*|__)(.*?)\1|\*([^*]+)\*|_([^_]+)_/g;
1510
- let lastIndex = 0;
1511
- let match;
1512
- while ((match = markdownRegex.exec(remaining)) !== null) {
1513
- // Add text before the match
1514
- if (match.index > lastIndex) {
1515
- const textBefore = remaining.substring(lastIndex, match.index);
1516
- if (textBefore) {
1517
- parts.push(document.createTextNode(textBefore));
2194
+ for (const node of parseInlineMarkdown(text)) {
2195
+ switch (node.kind) {
2196
+ case "strong": {
2197
+ // matches React UserBubble styling
2198
+ const strong = document.createElement("strong");
2199
+ strong.textContent = node.text;
2200
+ strong.style.cssText = `
2201
+ font-weight: 600;
2202
+ color: var(--convai-panel-fg, ${aeroTheme.colors.text.primary});
2203
+ `;
2204
+ parts.push(strong);
2205
+ break;
1518
2206
  }
1519
- }
1520
- // Determine if it's bold or italic
1521
- if (match[1] && match[2]) {
1522
- // Bold text (** or __) - matches React UserBubble styling
1523
- const strong = document.createElement("strong");
1524
- strong.textContent = match[2];
1525
- strong.style.cssText = `
1526
- font-weight: 600;
1527
- color: ${aeroTheme.colors.text.primary};
1528
- `;
1529
- parts.push(strong);
1530
- }
1531
- else if (match[3]) {
1532
- // Italic text (*) - matches React UserBubble styling
1533
- const em = document.createElement("em");
1534
- em.textContent = match[3];
1535
- em.style.cssText = `
1536
- font-style: italic;
1537
- `;
1538
- parts.push(em);
1539
- }
1540
- else if (match[4]) {
1541
- // Italic text (_) - matches React UserBubble styling
1542
- const em = document.createElement("em");
1543
- em.textContent = match[4];
1544
- em.style.cssText = `
1545
- font-style: italic;
1546
- `;
1547
- parts.push(em);
1548
- }
1549
- lastIndex = match.index + match[0].length;
1550
- }
1551
- // Add remaining text
1552
- if (lastIndex < remaining.length) {
1553
- const textAfter = remaining.substring(lastIndex);
1554
- if (textAfter) {
1555
- parts.push(document.createTextNode(textAfter));
2207
+ case "em": {
2208
+ const em = document.createElement("em");
2209
+ em.textContent = node.text;
2210
+ em.style.cssText = `font-style: italic;`;
2211
+ parts.push(em);
2212
+ break;
2213
+ }
2214
+ case "link": {
2215
+ const a = document.createElement("a");
2216
+ a.href = node.href;
2217
+ a.textContent = node.label === node.href ? compactUrl(node.label) : node.label;
2218
+ a.target = "_blank";
2219
+ a.rel = "noopener noreferrer";
2220
+ a.setAttribute("part", "message-link");
2221
+ a.style.cssText = `
2222
+ color: #10b981;
2223
+ text-decoration: underline;
2224
+ word-break: break-all;
2225
+ `;
2226
+ parts.push(a);
2227
+ if (media && node.media)
2228
+ parts.push(mediaPreview(node.href, node.label, node.media));
2229
+ break;
2230
+ }
2231
+ case "blocked": {
2232
+ const blocked = document.createElement("span");
2233
+ blocked.setAttribute("part", "message-link-blocked");
2234
+ blocked.textContent = node.label;
2235
+ blocked.title = `Link blocked: ${node.href}`;
2236
+ blocked.style.cssText = `
2237
+ opacity: .75;
2238
+ text-decoration: underline dotted;
2239
+ cursor: help;
2240
+ `;
2241
+ parts.push(blocked);
2242
+ break;
2243
+ }
2244
+ case "image": {
2245
+ if (media) {
2246
+ parts.push(mediaPreview(node.src, node.alt, "image"));
2247
+ break;
2248
+ }
2249
+ // With previews off, an image still has to say what it pointed at,
2250
+ // so it degrades to the same anchor a plain link would render.
2251
+ const imgLink = document.createElement("a");
2252
+ imgLink.href = node.src;
2253
+ imgLink.textContent = node.alt || node.src;
2254
+ imgLink.target = "_blank";
2255
+ imgLink.rel = "noopener noreferrer";
2256
+ imgLink.setAttribute("part", "message-link");
2257
+ imgLink.style.cssText = `
2258
+ color: #10b981;
2259
+ text-decoration: underline;
2260
+ word-break: break-all;
2261
+ `;
2262
+ parts.push(imgLink);
2263
+ break;
2264
+ }
2265
+ default:
2266
+ parts.push(document.createTextNode(node.text));
1556
2267
  }
1557
2268
  }
1558
2269
  return parts;
@@ -1591,7 +2302,7 @@ export function createConvaiWidget(container, options) {
1591
2302
  height: 100%;
1592
2303
  color: ${aeroTheme.colors.text.secondary};
1593
2304
  text-align: center;
1594
- padding: 2rem;
2305
+ padding: 32px;
1595
2306
  `;
1596
2307
  emptyState.innerHTML = `
1597
2308
  <p style="font-weight: 500; margin-bottom: 8px;">Start a conversation</p>
@@ -1613,6 +2324,7 @@ export function createConvaiWidget(container, options) {
1613
2324
  contain: layout style paint;
1614
2325
  `;
1615
2326
  const bubble = document.createElement("div");
2327
+ bubble.setAttribute("part", msg.isUser ? "message message-user" : "message message-bot");
1616
2328
  // Add data attribute to identify user messages for debugging/styling
1617
2329
  if (msg.isUser) {
1618
2330
  bubble.setAttribute("data-message-type", "user");
@@ -1620,6 +2332,10 @@ export function createConvaiWidget(container, options) {
1620
2332
  // Set base styles first - explicitly set background to match React UserBubble exactly
1621
2333
  // CRITICAL: Use the exact same background for both user and bot messages
1622
2334
  const backgroundColor = "rgba(252, 252, 253, 0.95)";
2335
+ // NOTE on border-radius: deliberately NOT themable. `--convai-radius` is
2336
+ // the open panel's radius; a bubble's asymmetric tail corner is a
2337
+ // different geometry (`50%` would make ellipses of these). A dedicated
2338
+ // `--convai-bubble-radius` can be added additively later if wanted.
1623
2339
  bubble.style.cssText = `
1624
2340
  padding: 12px;
1625
2341
  border-radius: ${msg.isUser ? "12px 12px 4px 12px" : "12px 12px 12px 4px"};
@@ -1628,8 +2344,8 @@ export function createConvaiWidget(container, options) {
1628
2344
  backdrop-filter: blur(20px) saturate(180%);
1629
2345
  border: 1px solid rgba(0, 0, 0, 0.06);
1630
2346
  box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.8) inset, 0 2px 8px rgba(0, 0, 0, 0.08);
1631
- color: ${aeroTheme.colors.text.primary};
1632
- font-family: ${aeroTheme.typography.fontFamily.body};
2347
+ color: var(--convai-panel-fg, ${aeroTheme.colors.text.primary});
2348
+ font-family: var(--convai-font, ${aeroTheme.typography.fontFamily.body});
1633
2349
  font-size: 14px;
1634
2350
  line-height: 1.5;
1635
2351
  word-wrap: break-word;
@@ -1661,8 +2377,8 @@ export function createConvaiWidget(container, options) {
1661
2377
  // Logo/Icon - matches React LogoWrapper
1662
2378
  const logoContainer = document.createElement("div");
1663
2379
  logoContainer.style.cssText = `
1664
- width: 1rem;
1665
- height: 1rem;
2380
+ width: 16px;
2381
+ height: 16px;
1666
2382
  display: flex;
1667
2383
  align-items: center;
1668
2384
  justify-content: center;
@@ -1689,10 +2405,10 @@ export function createConvaiWidget(container, options) {
1689
2405
  const nameLabel = document.createElement("span");
1690
2406
  nameLabel.textContent = msg.sender === "User" ? "You" : msg.sender;
1691
2407
  nameLabel.style.cssText = `
1692
- font-size: 0.75rem;
2408
+ font-size: 12px;
1693
2409
  color: ${msg.isUser ? aeroTheme.colors.convai.dark : "#10b981"};
1694
2410
  font-weight: 500;
1695
- font-family: ${aeroTheme.typography.fontFamily.body};
2411
+ font-family: var(--convai-font, ${aeroTheme.typography.fontFamily.body});
1696
2412
  isolation: isolate;
1697
2413
  contain: layout style paint;
1698
2414
  `;
@@ -1706,7 +2422,7 @@ export function createConvaiWidget(container, options) {
1706
2422
  white-space: pre-wrap;
1707
2423
  word-wrap: break-word;
1708
2424
  `;
1709
- renderMarkdown(msg.text, contentDiv);
2425
+ renderMarkdown(msg.text, contentDiv, { media: !msg.isUser });
1710
2426
  bubble.appendChild(contentDiv);
1711
2427
  messageWrapper.appendChild(bubble);
1712
2428
  // Timestamp - matches React exactly
@@ -1714,11 +2430,11 @@ export function createConvaiWidget(container, options) {
1714
2430
  const timestamp = document.createElement("span");
1715
2431
  timestamp.textContent = msg.timestamp;
1716
2432
  timestamp.style.cssText = `
1717
- font-size: 0.75rem;
2433
+ font-size: 12px;
1718
2434
  color: ${aeroTheme.colors.text.secondary};
1719
2435
  margin-top: 4px;
1720
2436
  align-self: ${msg.isUser ? "flex-end" : "flex-start"};
1721
- font-family: ${aeroTheme.typography.fontFamily.body};
2437
+ font-family: var(--convai-font, ${aeroTheme.typography.fontFamily.body});
1722
2438
  `;
1723
2439
  messageWrapper.appendChild(timestamp);
1724
2440
  }
@@ -1762,6 +2478,8 @@ export function createConvaiWidget(container, options) {
1762
2478
  // Setup event listeners for client state changes
1763
2479
  const setupClientListeners = () => {
1764
2480
  eventSubscriptions.register((listener) => client.on("stateChange", listener), () => {
2481
+ // Published chat (connectionType "text") has no microphone: never let
2482
+ // a voice-mode transition leave the panel in a mode it cannot honour.
1765
2483
  if (client.connectionType === "text") {
1766
2484
  if (isVoiceMode) {
1767
2485
  isVoiceMode = false;
@@ -1789,8 +2507,6 @@ export function createConvaiWidget(container, options) {
1789
2507
  // Reset when not speaking
1790
2508
  if (startTime && !client.state.isSpeaking) {
1791
2509
  startTime = 0;
1792
- currentLevels = Array(40).fill(0.05);
1793
- targetLevels = Array(40).fill(0.05);
1794
2510
  }
1795
2511
  }
1796
2512
  // Auto-collapse when disconnected
@@ -1803,12 +2519,14 @@ export function createConvaiWidget(container, options) {
1803
2519
  isVideoVisible = false;
1804
2520
  hasEnteredDefaultVoiceMode = false;
1805
2521
  updateHeader();
1806
- updateVoiceMode();
2522
+ // Synchronous listener: nothing here can catch a rejection, and the
2523
+ // mute inside is the one most likely to fail (the room has just
2524
+ // dropped -- that is why we are collapsing).
2525
+ applyVoiceMode();
1807
2526
  }
1808
2527
  // Auto-enter voice mode on first connection if defaultVoiceMode is true
1809
2528
  if (client.state.isConnected &&
1810
2529
  defaultVoiceMode &&
1811
- client.connectionType !== "text" &&
1812
2530
  isOpen &&
1813
2531
  !hasEnteredDefaultVoiceMode &&
1814
2532
  !isVoiceMode) {
@@ -1817,10 +2535,10 @@ export function createConvaiWidget(container, options) {
1817
2535
  await client.audioControls.unmuteAudio();
1818
2536
  isVoiceMode = true;
1819
2537
  hasEnteredDefaultVoiceMode = true;
1820
- updateVoiceMode();
2538
+ await updateVoiceMode();
1821
2539
  }
1822
2540
  catch (error) {
1823
- console.error("Failed to enter voice mode:", error);
2541
+ reportMicFailure(client, "Failed to enter voice mode:", error);
1824
2542
  }
1825
2543
  }, 100);
1826
2544
  }
@@ -1830,9 +2548,9 @@ export function createConvaiWidget(container, options) {
1830
2548
  eventSubscriptions.register((listener) => client.videoControls.on("videoStateChange", listener), (videoState) => {
1831
2549
  if (videoState.isVideoEnabled !== undefined) {
1832
2550
  isVideoVisible = videoState.isVideoEnabled;
1833
- updateVoiceMode();
2551
+ applyVoiceMode(); // synchronous listener; see applyVoiceMode()
1834
2552
  // Update tray button state
1835
- const videoBtn = document.getElementById("convai-settings-video-btn");
2553
+ const videoBtn = refs.settingsVideoBtn;
1836
2554
  if (videoBtn) {
1837
2555
  const isActive = isVideoVisible;
1838
2556
  videoBtn.style.backgroundColor = isActive
@@ -1840,7 +2558,7 @@ export function createConvaiWidget(container, options) {
1840
2558
  : "transparent";
1841
2559
  videoBtn.style.color = isActive
1842
2560
  ? "#10b981"
1843
- : aeroTheme.colors.text.primary;
2561
+ : `var(--convai-panel-fg, ${aeroTheme.colors.text.primary})`;
1844
2562
  // Update Icon - first child is icon container
1845
2563
  const iconContainer = videoBtn.querySelector("div");
1846
2564
  if (iconContainer) {
@@ -1854,10 +2572,10 @@ export function createConvaiWidget(container, options) {
1854
2572
  }
1855
2573
  });
1856
2574
  // Screen share state change listener
1857
- eventSubscriptions.register((listener) => client.screenShareControls.on("screenShareStateChange", listener), (screenShareState) => {
2575
+ client.screenShareControls.on("screenShareStateChange", (screenShareState) => {
1858
2576
  if (screenShareState.isScreenShareActive !== undefined) {
1859
2577
  const isSharing = screenShareState.isScreenShareActive;
1860
- const shareBtn = document.getElementById("convai-settings-share-btn");
2578
+ const shareBtn = refs.settingsShareBtn;
1861
2579
  if (shareBtn) {
1862
2580
  const isActive = isSharing;
1863
2581
  shareBtn.style.backgroundColor = isActive
@@ -1865,7 +2583,7 @@ export function createConvaiWidget(container, options) {
1865
2583
  : "transparent";
1866
2584
  shareBtn.style.color = isActive
1867
2585
  ? "#10b981"
1868
- : aeroTheme.colors.text.primary;
2586
+ : `var(--convai-panel-fg, ${aeroTheme.colors.text.primary})`;
1869
2587
  // Update Icon - first child is icon container
1870
2588
  const iconContainer = shareBtn.querySelector("div");
1871
2589
  if (iconContainer) {
@@ -1882,11 +2600,6 @@ export function createConvaiWidget(container, options) {
1882
2600
  });
1883
2601
  eventSubscriptions.register((listener) => client.on("messagesChange", listener), () => {
1884
2602
  updateMessageList();
1885
- // Call onMessage callback if provided
1886
- if (onMessage && client.chatMessages.length > 0) {
1887
- const lastMessage = client.chatMessages[client.chatMessages.length - 1];
1888
- onMessage(lastMessage);
1889
- }
1890
2603
  });
1891
2604
  // Bot ready listener - updates UI when bot becomes ready
1892
2605
  eventSubscriptions.register((listener) => client.on("botReady", listener), () => {
@@ -1896,8 +2609,13 @@ export function createConvaiWidget(container, options) {
1896
2609
  eventSubscriptions.register((listener) => client.on("connect", listener), () => {
1897
2610
  hasConnectedBefore = true;
1898
2611
  // Initialize audio renderer on connection
2612
+ // NOTE: the audio elements live under rootElement, so playback ends if
2613
+ // the host *removes or re-parents* its mount container mid-call. Merely
2614
+ // hiding it (display: none / visibility: hidden) does NOT stop
2615
+ // HTMLMediaElement playback in any browser — an earlier version of this
2616
+ // comment claimed otherwise and was wrong.
1899
2617
  if (client.room && !audioRenderer) {
1900
- audioRenderer = new AudioRenderer(client.room);
2618
+ audioRenderer = new AudioRenderer(client.room, { container: rootElement });
1901
2619
  }
1902
2620
  // Fetch character info
1903
2621
  fetchCharacterInfo();
@@ -1918,25 +2636,127 @@ export function createConvaiWidget(container, options) {
1918
2636
  onDisconnect();
1919
2637
  }
1920
2638
  });
2639
+ // `message` carries the row actually updated. That can differ from the
2640
+ // list tail when correlated v2 streams interleave, which is why onMessage
2641
+ // no longer reads the last element of chatMessages.
2642
+ eventSubscriptions.register((listener) => client.on("message", listener), (message) => {
2643
+ const row = message;
2644
+ if (onMessage && row) {
2645
+ onMessage(row);
2646
+ }
2647
+ });
2648
+ // Screen share state change listener
2649
+ eventSubscriptions.register((listener) => client.screenShareControls.on("screenShareStateChange", listener), (screenShareState) => {
2650
+ if (screenShareState.isScreenShareActive !== undefined) {
2651
+ const isSharing = screenShareState.isScreenShareActive;
2652
+ const shareBtn = document.getElementById("convai-settings-share-btn");
2653
+ if (shareBtn) {
2654
+ const isActive = isSharing;
2655
+ shareBtn.style.backgroundColor = isActive
2656
+ ? "rgba(16, 185, 129, 0.15)"
2657
+ : "transparent";
2658
+ shareBtn.style.color = isActive
2659
+ ? "#10b981"
2660
+ : aeroTheme.colors.text.primary;
2661
+ // Update Icon - first child is icon container
2662
+ const iconContainer = shareBtn.querySelector("div");
2663
+ if (iconContainer) {
2664
+ iconContainer.innerHTML = "";
2665
+ const icon = isActive
2666
+ ? Icons.StopScreenShare("md")
2667
+ : Icons.ScreenShare("md");
2668
+ icon.style.width = "18px";
2669
+ icon.style.height = "18px";
2670
+ iconContainer.appendChild(icon);
2671
+ }
2672
+ }
2673
+ }
2674
+ });
1921
2675
  };
1922
2676
  // Initialize
1923
2677
  createDOM();
1924
2678
  setupClientListeners();
2679
+ // Paint the connecting overlay's initial state. updateHeader() (which also
2680
+ // calls updateConnectingOverlay()) is otherwise only reached via a client
2681
+ // event or a successful character-info fetch, so a widget constructed
2682
+ // already connected-but-not-ready would show nothing until one of those
2683
+ // fires without this.
2684
+ updateConnectingOverlay();
1925
2685
  // Set initial button state
1926
2686
  updateSendButton(); // Show voice mode button initially since input is empty
1927
2687
  // Set initial voice mode UI if defaultVoiceMode is true
1928
2688
  if (defaultVoiceMode) {
1929
- updateVoiceMode();
2689
+ applyVoiceMode(); // synchronous constructor tail; see applyVoiceMode()
1930
2690
  }
1931
2691
  // If already connected, initialize audio renderer and fetch character info
2692
+ // NOTE: same lifetime caveat as the "connect" handler above — the audio
2693
+ // elements are torn down with rootElement if the host detaches it.
1932
2694
  if (client.state.isConnected && client.room) {
1933
- audioRenderer = new AudioRenderer(client.room);
2695
+ audioRenderer = new AudioRenderer(client.room, { container: rootElement });
1934
2696
  fetchCharacterInfo();
1935
2697
  }
1936
2698
  // Return widget instance
1937
2699
  const widget = {
1938
2700
  element: rootElement,
1939
2701
  client: client,
2702
+ // `isOpen` reports *requested* state, which on a warm client is the same
2703
+ // thing as rendered state: `setIsOpen()` runs synchronously. The one case
2704
+ // where they differ is the first open on a disconnected client, where the
2705
+ // panel is committed only after `connect()` resolves; reporting `false`
2706
+ // for those seconds would tell an embed reconciling its own
2707
+ // convai-open/convai-close events that a widget it just opened is closed.
2708
+ // `pendingOpen` is cleared by every cancellation path, so this never
2709
+ // reports open for a request that was called off.
2710
+ get isOpen() {
2711
+ return isOpen || pendingOpen;
2712
+ },
2713
+ // Drives the exact same path the launcher click does: `handleToggle`
2714
+ // (connect-on-first-open, then `setIsOpen(true)`). Idempotent against an
2715
+ // in-flight open as well as an open panel, so repeat calls never start a
2716
+ // second connect.
2717
+ open: () => {
2718
+ if (isOpen || pendingOpen)
2719
+ return;
2720
+ void handleToggle();
2721
+ },
2722
+ // Drives the same path the header's close button does: `handleClose` ->
2723
+ // `setIsOpen(false)`. Also cancels an open that is still waiting on
2724
+ // `connect()`; a redundant `close()` is a no-op.
2725
+ close: () => {
2726
+ if (!isOpen && !pendingOpen)
2727
+ return;
2728
+ handleClose();
2729
+ },
2730
+ toggle: () => {
2731
+ if (isOpen || pendingOpen) {
2732
+ handleClose();
2733
+ }
2734
+ else {
2735
+ void handleToggle();
2736
+ }
2737
+ },
2738
+ // Pushes a synthetic ChatMessage straight onto `client.chatMessages` and
2739
+ // re-renders via the widget's existing `updateMessageList()`. It never
2740
+ // calls a client send method (e.g. `sendUserTextMessage`), so the
2741
+ // message never reaches the character and is never billed as an LLM
2742
+ // turn. The `local-` id keeps it from colliding with a server-issued id.
2743
+ appendMessage: (message) => {
2744
+ // Shared core path, so React and vanilla insert identically. A
2745
+ // hand-rolled IConvaiClient without it falls back to the old local push.
2746
+ if (typeof client.appendMessage === "function") {
2747
+ client.appendMessage(message);
2748
+ }
2749
+ else {
2750
+ const chatMessage = {
2751
+ id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`,
2752
+ type: message.sender === "user" ? "user-llm-text" : "bot-llm-text",
2753
+ content: message.content,
2754
+ timestamp: new Date().toISOString(),
2755
+ };
2756
+ client.chatMessages.push(chatMessage);
2757
+ }
2758
+ updateMessageList();
2759
+ },
1940
2760
  destroy: () => {
1941
2761
  isDestroyed = true;
1942
2762
  // Cleanup audio renderer
@@ -1945,7 +2765,7 @@ export function createConvaiWidget(container, options) {
1945
2765
  audioRenderer = null;
1946
2766
  }
1947
2767
  // Remove event listeners
1948
- morphingContainer.removeEventListener("click", handleToggle);
2768
+ morphingContainer.removeEventListener("click", handleLauncherClick);
1949
2769
  // Remove DOM elements
1950
2770
  if (rootElement.parentElement) {
1951
2771
  rootElement.remove();