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

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