@convai/web-sdk 1.9.2 → 2.0.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 (80) hide show
  1. package/README.md +22 -11
  2. package/dist/core/types.d.ts +2 -2
  3. package/dist/react/hooks/index.d.ts +0 -2
  4. package/dist/react/hooks/index.js +0 -3
  5. package/dist/react/hooks/useConvaiClient.js +0 -16
  6. package/dist/react/index.d.ts +0 -3
  7. package/dist/react/index.js +3 -10
  8. package/dist/vanilla/index.d.ts +6 -18
  9. package/dist/vanilla/index.js +7 -19
  10. package/dist/version.d.ts +1 -1
  11. package/dist/version.js +1 -1
  12. package/package.json +9 -8
  13. package/dist/react/components/ConvaiWidget.d.ts +0 -86
  14. package/dist/react/components/ConvaiWidget.js +0 -610
  15. package/dist/react/components/index.d.ts +0 -1
  16. package/dist/react/components/index.js +0 -2
  17. package/dist/react/components/rtc-widget/components/AudioSettingsPanel.d.ts +0 -9
  18. package/dist/react/components/rtc-widget/components/AudioSettingsPanel.js +0 -315
  19. package/dist/react/components/rtc-widget/components/AudioVisualizer.d.ts +0 -35
  20. package/dist/react/components/rtc-widget/components/AudioVisualizer.js +0 -285
  21. package/dist/react/components/rtc-widget/components/ConviMessage.d.ts +0 -12
  22. package/dist/react/components/rtc-widget/components/ConviMessage.js +0 -13
  23. package/dist/react/components/rtc-widget/components/FloatingVideo.d.ts +0 -8
  24. package/dist/react/components/rtc-widget/components/FloatingVideo.js +0 -120
  25. package/dist/react/components/rtc-widget/components/MarkdownRenderer.d.ts +0 -31
  26. package/dist/react/components/rtc-widget/components/MarkdownRenderer.js +0 -140
  27. package/dist/react/components/rtc-widget/components/MessageBubble.d.ts +0 -9
  28. package/dist/react/components/rtc-widget/components/MessageBubble.js +0 -22
  29. package/dist/react/components/rtc-widget/components/MessageList.d.ts +0 -13
  30. package/dist/react/components/rtc-widget/components/MessageList.js +0 -88
  31. package/dist/react/components/rtc-widget/components/SiteCard.d.ts +0 -14
  32. package/dist/react/components/rtc-widget/components/SiteCard.js +0 -34
  33. package/dist/react/components/rtc-widget/components/UserMessage.d.ts +0 -8
  34. package/dist/react/components/rtc-widget/components/UserMessage.js +0 -14
  35. package/dist/react/components/rtc-widget/components/conviComponents/ConviButton.d.ts +0 -5
  36. package/dist/react/components/rtc-widget/components/conviComponents/ConviButton.js +0 -14
  37. package/dist/react/components/rtc-widget/components/conviComponents/ConviFooter.d.ts +0 -24
  38. package/dist/react/components/rtc-widget/components/conviComponents/ConviFooter.js +0 -170
  39. package/dist/react/components/rtc-widget/components/conviComponents/ConviHeader.d.ts +0 -16
  40. package/dist/react/components/rtc-widget/components/conviComponents/ConviHeader.js +0 -64
  41. package/dist/react/components/rtc-widget/components/conviComponents/SettingsTray.d.ts +0 -11
  42. package/dist/react/components/rtc-widget/components/conviComponents/SettingsTray.js +0 -65
  43. package/dist/react/components/rtc-widget/components/conviComponents/VoiceModeOverlay.d.ts +0 -13
  44. package/dist/react/components/rtc-widget/components/conviComponents/VoiceModeOverlay.js +0 -298
  45. package/dist/react/components/rtc-widget/components/conviComponents/index.d.ts +0 -5
  46. package/dist/react/components/rtc-widget/components/conviComponents/index.js +0 -5
  47. package/dist/react/components/rtc-widget/components/index.d.ts +0 -8
  48. package/dist/react/components/rtc-widget/components/index.js +0 -14
  49. package/dist/react/components/rtc-widget/index.d.ts +0 -5
  50. package/dist/react/components/rtc-widget/index.js +0 -8
  51. package/dist/react/components/rtc-widget/styles/framerConfig.d.ts +0 -115
  52. package/dist/react/components/rtc-widget/styles/framerConfig.js +0 -72
  53. package/dist/react/components/rtc-widget/styles/icons.d.ts +0 -27
  54. package/dist/react/components/rtc-widget/styles/icons.js +0 -256
  55. package/dist/react/components/rtc-widget/styles/index.d.ts +0 -5
  56. package/dist/react/components/rtc-widget/styles/index.js +0 -8
  57. package/dist/react/components/rtc-widget/styles/styledComponents.d.ts +0 -89
  58. package/dist/react/components/rtc-widget/styles/styledComponents.js +0 -662
  59. package/dist/react/components/rtc-widget/styles/theme.d.ts +0 -187
  60. package/dist/react/components/rtc-widget/styles/theme.js +0 -289
  61. package/dist/react/components/rtc-widget/types/index.d.ts +0 -59
  62. package/dist/react/components/rtc-widget/types/index.js +0 -1
  63. package/dist/react/hooks/useCharacterInfo.d.ts +0 -18
  64. package/dist/react/hooks/useCharacterInfo.js +0 -65
  65. package/dist/react/hooks/useLocalCameraTrack.d.ts +0 -21
  66. package/dist/react/hooks/useLocalCameraTrack.js +0 -33
  67. package/dist/react/icons.d.ts +0 -37
  68. package/dist/react/icons.js +0 -53
  69. package/dist/utils/lightbox.d.ts +0 -15
  70. package/dist/utils/lightbox.js +0 -94
  71. package/dist/vanilla/ConvaiWidget.d.ts +0 -46
  72. package/dist/vanilla/ConvaiWidget.js +0 -2866
  73. package/dist/vanilla/WidgetEventSubscriptions.d.ts +0 -14
  74. package/dist/vanilla/WidgetEventSubscriptions.js +0 -36
  75. package/dist/vanilla/icons.d.ts +0 -34
  76. package/dist/vanilla/icons.js +0 -268
  77. package/dist/vanilla/styles.d.ts +0 -168
  78. package/dist/vanilla/styles.js +0 -407
  79. package/dist/vanilla/types.d.ts +0 -170
  80. package/dist/vanilla/types.js +0 -1
@@ -1,2866 +0,0 @@
1
- /**
2
- * Vanilla ConvaiWidget - Complete UI widget for Convai conversations
3
- * Ports the React ConvaiWidget to vanilla TypeScript with DOM manipulation
4
- */
5
- import { AudioRenderer } from "./AudioRenderer.js";
6
- import { aeroTheme, injectGlobalStyles, injectKeyframes, } from "./styles.js";
7
- import { Icons } from "./icons.js";
8
- import { WidgetEventSubscriptions } from "./WidgetEventSubscriptions.js";
9
- import { ConvaiClient } from "../core/ConvaiClient.js";
10
- import { fetchCharacterInfo as requestCharacterInfo } from "../core/characterInfo.js";
11
- import { parseInlineMarkdown, compactUrl } from "../utils/inlineMarkdown.js";
12
- import { linkKindForUrl, describeUrl, fileNameOf, documentBadge, contactLabel, hoverTitle, isMixedContent, glyph, presentationStyles as S, toCssText, PREVIEW_TIMEOUT_MS, MAX_CARDS_PER_MESSAGE, } from "../utils/linkPresentation.js";
13
- import { openLightbox } from "../utils/lightbox.js";
14
- import { resolveLinkPreviewCached, isCardWorthy, siteNameFor, faviconFor, } from "../utils/linkPreview.js";
15
- import { freshPublicationGrantOptions } from "../core/publishedChat.js";
16
- /**
17
- * Positioning declarations for the widget root, keyed by `placement`. The
18
- * `bottom-right` entry must stay byte-identical to the literals it replaces --
19
- * the inline-style parity suite snapshots the resolved `cssText` and compares
20
- * it to a committed fixture.
21
- */
22
- /** Gap between a fixed-placement widget and the viewport edge it anchors to. */
23
- const PLACEMENT_INSET_PX = 24;
24
- const PLACEMENT_CSS = {
25
- "bottom-right": `position: fixed; bottom: ${PLACEMENT_INSET_PX}px; right: ${PLACEMENT_INSET_PX}px;`,
26
- "bottom-left": `position: fixed; bottom: ${PLACEMENT_INSET_PX}px; left: ${PLACEMENT_INSET_PX}px;`,
27
- "top-right": `position: fixed; top: ${PLACEMENT_INSET_PX}px; right: ${PLACEMENT_INSET_PX}px;`,
28
- "top-left": `position: fixed; top: ${PLACEMENT_INSET_PX}px; left: ${PLACEMENT_INSET_PX}px;`,
29
- inline: "position: relative;",
30
- };
31
- /** The open panel's preferred size. Capped by `PANEL_MAX_*` — see below. */
32
- const PANEL_W_PX = 400;
33
- const PANEL_H_PX = 600;
34
- /**
35
- * A ceiling on the open panel, so it can never be clipped by the viewport.
36
- *
37
- * The panel used to be a flat 400x600. The widget is `position: fixed`
38
- * anchored `PLACEMENT_INSET_PX` from one edge, so on any viewport narrower
39
- * than 448px — or shorter than 648px — the panel ran past the opposite edge
40
- * and was silently cut off, with no scrollbar to reveal it, because fixed
41
- * elements do not contribute to scrollable overflow. That is most phones: at
42
- * 393px (iPhone 15 Pro) 30px of the panel sat off-screen, at 360px 63px did,
43
- * and in landscape 233px of it — the entire header, including the close
44
- * button — sat above the viewport, leaving nothing on screen to dismiss it.
45
- *
46
- * Expressed as `max-width`/`max-height` rather than folding the cap into the
47
- * width with `min()`. Both compute the same thing, but they fail differently:
48
- * a parser that does not know `min()` drops the whole declaration and the
49
- * panel is left with no width at all, which is worse than the bug. An unknown
50
- * `max-width` drops only the ceiling and leaves the previous behaviour intact.
51
- * (Not hypothetical — happy-dom, which this package's own tests run in, parses
52
- * the `max-width` form and discards the `min()` one.)
53
- *
54
- * Dynamic viewport units so mobile browser chrome is accounted for as it shows
55
- * and hides, rather than sizing against a viewport the user cannot fully see.
56
- * Applied to the container permanently rather than per state: the collapsed
57
- * bubble is far below the ceiling, so it is unaffected.
58
- */
59
- const PANEL_MAX_W = `calc(100dvw - ${PLACEMENT_INSET_PX * 2}px)`;
60
- const PANEL_MAX_H = `calc(100dvh - ${PLACEMENT_INSET_PX * 2}px)`;
61
- /** `convai-error{code:'mic-permission'}` per the embed's error-handling contract. */
62
- const MIC_PERMISSION_ERROR_CODE = "mic-permission";
63
- /**
64
- * Distinguishes a microphone-permission denial from any other audio failure.
65
- *
66
- * Traced (not assumed): `client.audioControls.unmuteAudio()` delegates to
67
- * `AudioManager.enableAudio()`, which calls
68
- * `room.localParticipant.setMicrophoneEnabled(true)`. That's LiveKit's
69
- * `setTrackEnabled()`, which on failure does `throw e` unchanged, from a
70
- * `catch` around `createLocalTracks()`, which itself does `throw e` unchanged
71
- * around `navigator.mediaDevices.getUserMedia()`. `AudioManager.enableAudio()`
72
- * also just does `throw error` in its own catch. Nothing on that path wraps or
73
- * replaces the error, so a user's permission denial reaches here as the exact
74
- * `DOMException` `getUserMedia()` produced, with `.name === 'NotAllowedError'`
75
- * (`'PermissionDeniedError'` is the old pre-spec name some browsers used).
76
- */
77
- function isMicPermissionDenial(error) {
78
- const name = error?.name;
79
- return name === "NotAllowedError" || name === "PermissionDeniedError";
80
- }
81
- /**
82
- * Wraps a mic-permission denial so a consumer of the client's `error`
83
- * channel can tell it apart from a generic failure without knowing anything
84
- * about `DOMException` internals -- it only has to check `error.code`. The
85
- * original error is preserved on `.cause` for anyone who wants the detail.
86
- */
87
- function toMicPermissionError(cause) {
88
- const err = new Error("Microphone access was denied. Continuing in text-only mode.");
89
- err.name = "ConvaiMicPermissionError";
90
- err.code = MIC_PERMISSION_ERROR_CODE;
91
- err.cause = cause;
92
- return err;
93
- }
94
- /**
95
- * Routes a failed `enableAudio()`/`unmuteAudio()` call onto the client's
96
- * *existing* `error` channel -- the same one `ConvaiClient` already uses --
97
- * instead of letting it become an unhandled rejection (the click-handler
98
- * site) or vanish into a bare `console.error` (the auto-voice-mode sites).
99
- * `console.error` is kept alongside for local debugging; this just adds the
100
- * event emission next to it. `client.emit` is called defensively since it
101
- * isn't part of the public `IConvaiClient` surface -- see the `emit?` field
102
- * on `VanillaWidgetOptions.convaiClient` in `./types.ts`.
103
- */
104
- function reportMicFailure(client, logLabel, error) {
105
- console.error(logLabel, error);
106
- const payload = isMicPermissionDenial(error)
107
- ? toMicPermissionError(error)
108
- : error;
109
- client.emit?.("error", payload);
110
- }
111
- /**
112
- * Create a Convai chat widget in the specified container
113
- *
114
- * @param container - HTML element to attach the widget to
115
- * @param options - Widget configuration options
116
- * @returns VanillaWidget instance with destroy method
117
- *
118
- * @example Simple usage with config
119
- * ```typescript
120
- * import { createConvaiWidget } from '@convai/web-sdk/vanilla';
121
- *
122
- * const widget = createConvaiWidget(document.body, {
123
- * apiKey: 'your-api-key',
124
- * characterId: 'your-character-id',
125
- * enableVideo: false
126
- * });
127
- * ```
128
- *
129
- * @example Advanced usage with client instance
130
- * ```typescript
131
- * import { ConvaiClient, createConvaiWidget } from '@convai/web-sdk/vanilla';
132
- *
133
- * const client = new ConvaiClient({
134
- * apiKey: 'your-api-key',
135
- * characterId: 'your-character-id'
136
- * });
137
- *
138
- * const widget = createConvaiWidget(document.body, {
139
- * convaiClient: client,
140
- * showVideo: true,
141
- * showScreenShare: true,
142
- * defaultVoiceMode: true
143
- * });
144
- * ```
145
- */
146
- export function createConvaiWidget(container, options) {
147
- /**
148
- * Where global styles and `@keyframes` are injected.
149
- *
150
- * An explicit `options.styleTarget` wins and is used verbatim. Otherwise we
151
- * fall back to deriving it from the container's current root — which is what
152
- * every existing caller relies on, but only works when the container is
153
- * already attached to its final root. A caller that builds a detached
154
- * subtree and appends it to a shadow root afterwards must pass
155
- * `styleTarget` explicitly, or the styles land in `document.head` and the
156
- * shadow tree renders unstyled with no error.
157
- */
158
- const styleTarget = options.styleTarget ??
159
- (container.getRootNode() instanceof ShadowRoot
160
- ? container.getRootNode()
161
- : document);
162
- // Create client if not provided - guarantee it's defined
163
- const client = options.convaiClient ||
164
- (() => {
165
- const hasAuth = Boolean(options.apiKey || options.authToken);
166
- if (!hasAuth || !options.characterId) {
167
- throw new Error("Either convaiClient or (apiKey or authToken) and characterId must be provided");
168
- }
169
- return new ConvaiClient({
170
- apiKey: options?.apiKey || undefined,
171
- authToken: options?.authToken || undefined,
172
- characterId: options.characterId,
173
- enableVideo: options.enableVideo ?? false,
174
- startWithVideoOn: options.startWithVideoOn ?? false,
175
- enableLipsync: options.enableLipsync ?? false,
176
- enableEmotion: options.enableEmotion,
177
- blendshapeConfig: options.blendshapeConfig,
178
- });
179
- })();
180
- const { showVideo = true, showScreenShare = true, defaultVoiceMode = true, requestPublicationGrant, publishedChatConnectOptions, publishedChatDescriptor, onConnect, onDisconnect, onMessage, } = options;
181
- // Unknown/typo'd values fall back to the default rather than throwing --
182
- // a bad `placement` attribute on a customer's page must not blank the
183
- // widget.
184
- const placement = options.placement && options.placement in PLACEMENT_CSS
185
- ? options.placement
186
- : "bottom-right";
187
- // Inject global styles
188
- injectGlobalStyles(styleTarget);
189
- // Keyframes were injected lazily by the connecting overlay and the settings
190
- // tray, but a link-preview skeleton can render before either exists — a
191
- // replayed transcript paints message bubbles immediately. Idempotent.
192
- injectKeyframes(styleTarget);
193
- // State
194
- let isOpen = false;
195
- let isSettingsOpen = false;
196
- let isVoiceMode = defaultVoiceMode &&
197
- !requestPublicationGrant &&
198
- client.connectionType !== "text";
199
- let isMuted = false;
200
- let isVideoVisible = false;
201
- let inputValue = "";
202
- let characterName = publishedChatDescriptor?.display_name || "Character";
203
- let characterImage = publishedChatDescriptor?.image_url || "";
204
- let audioRenderer = null;
205
- let hasEnteredDefaultVoiceMode = false;
206
- /** True after we have connected at least once; used to call reconnect() instead of connect() when opening after disconnect */
207
- let hasConnectedBefore = false;
208
- /**
209
- * True from the moment an open is requested on a *disconnected* client
210
- * until that open either completes or is cancelled.
211
- *
212
- * `isOpen` alone cannot express this: the first open awaits a real
213
- * `connect()` (0.5-3s in production) and only flips `isOpen` afterwards, so
214
- * for that whole window the widget is neither open nor idle. Without this
215
- * flag `close()` sees `isOpen === false` and no-ops -- and the connect then
216
- * pops the panel open behind the user -- while `toggle()` sees the same
217
- * `false`, starts a *second* open, and lands on the already-connecting
218
- * branch that opens immediately. Every entry point below treats
219
- * `pendingOpen` as "open" for the purpose of deciding what a close/toggle
220
- * means, and `handleToggle` re-checks it before committing `setIsOpen(true)`
221
- * so a cancellation during the await is honoured.
222
- */
223
- let pendingOpen = false;
224
- /** Prevent an in-flight publication grant request from connecting after teardown. */
225
- let isDestroyed = false;
226
- const eventSubscriptions = new WidgetEventSubscriptions(() => isDestroyed);
227
- // DOM elements (will be created below)
228
- let rootElement;
229
- let morphingContainer;
230
- let buttonContent;
231
- let chatContent;
232
- let headerElement;
233
- let contentElement;
234
- let footerElement;
235
- let inputElement;
236
- let messageListElement;
237
- let settingsTray;
238
- let floatingVideo;
239
- let voiceModeOverlay;
240
- let connectingOverlay;
241
- /**
242
- * Elements captured at creation. IDs are scoped per DOM tree, so
243
- * document.getElementById() returns null when the widget is mounted
244
- * inside a shadow root. Every element here is created in this file.
245
- */
246
- const refs = {};
247
- // Audio Analysis State
248
- let audioContext = null;
249
- let analyzer = null;
250
- let dataArray = null;
251
- let rafId = null;
252
- let source = null;
253
- // Fetch character info - matches React useCharacterInfo hook
254
- const fetchCharacterInfo = async () => {
255
- if (publishedChatDescriptor)
256
- return;
257
- // Prefer authToken over apiKey, matching the precedence ConvaiClient
258
- // uses when building /connect headers -- a client carrying both must
259
- // behave identically in both places.
260
- //
261
- // The two travel in *different* headers, which requestCharacterInfo
262
- // handles: an auth token goes in API-AUTH-TOKEN, an API key in X-API-Key,
263
- // and the host answers an API key sent as API-AUTH-TOKEN with `400 Your
264
- // session has expired.` The failure is swallowed below, so getting it
265
- // wrong showed up only as a header stuck on the fallback name.
266
- const credential = client.authToken ?? client.apiKey;
267
- if (!credential || !client.characterId)
268
- return;
269
- // Same request as the React hook, because it is literally the same
270
- // function now -- the two used to be hand-synced copies sharing a
271
- // hardcoded host, which is what made this unconfigurable on-prem.
272
- try {
273
- const info = await requestCharacterInfo({
274
- characterId: client.characterId,
275
- apiKey: credential,
276
- authToken: client.authToken,
277
- baseUrl: client.characterInfoUrl,
278
- });
279
- characterName = info.name;
280
- characterImage = info.image ?? "";
281
- updateHeader();
282
- }
283
- catch (error) {
284
- // Cosmetic: keep the fallback header rather than surface this.
285
- console.error("Failed to fetch character info:", error);
286
- }
287
- };
288
- // Create root structure
289
- const createDOM = () => {
290
- rootElement = document.createElement("div");
291
- rootElement.className = "convai-widget";
292
- rootElement.style.cssText = `
293
- ${PLACEMENT_CSS[placement]}
294
- z-index: var(--convai-z-index, ${aeroTheme.zIndex.modal});
295
- font-family: var(--convai-font, ${aeroTheme.typography.fontFamily.primary});
296
- `;
297
- // Morphing container
298
- morphingContainer = document.createElement("div");
299
- // `part="launcher"` is precise only while collapsed: this same element
300
- // morphs into the open panel (400x600, capped to the viewport — see PANEL_MAX_W)
301
- // and carries that panel's background,
302
- // radius and shadow. See the `part="panel"` call site below for the full
303
- // semantics a host needs to know.
304
- morphingContainer.setAttribute("part", "launcher");
305
- // NOTE on border-radius: deliberately NOT themable. `--convai-radius`
306
- // drives the open panel only. One token cannot serve both geometries --
307
- // `--convai-radius: 8px` would squircle the circular launcher, and `50%`
308
- // would turn the panel into an ellipse. A dedicated
309
- // `--convai-launcher-radius` can be added additively later if wanted.
310
- morphingContainer.style.cssText = `
311
- position: relative;
312
- width: var(--convai-launcher-size, 64px);
313
- height: var(--convai-launcher-size, 64px);
314
- max-width: ${PANEL_MAX_W};
315
- max-height: ${PANEL_MAX_H};
316
- background: var(--convai-panel-bg, ${aeroTheme.colors.glass.backdrop});
317
- backdrop-filter: ${aeroTheme.glass.backdrop};
318
- border: ${aeroTheme.glass.border};
319
- border-radius: 50%;
320
- box-shadow: var(--convai-shadow, ${aeroTheme.shadows.glass});
321
- transition: all 0.3s ease-in-out;
322
- overflow: hidden;
323
- display: flex;
324
- align-items: center;
325
- justify-content: center;
326
- cursor: pointer;
327
- `;
328
- // Button content (logo)
329
- buttonContent = document.createElement("div");
330
- buttonContent.style.cssText = `
331
- position: absolute;
332
- inset: 0;
333
- display: flex;
334
- align-items: center;
335
- justify-content: center;
336
- transition: opacity 0.3s, transform 0.3s;
337
- opacity: 1;
338
- transform: scale(1);
339
- `;
340
- const convaiLogo = Icons.ConvaiLogo("xl", "idle");
341
- convaiLogo.style.color = `var(--convai-accent, ${aeroTheme.colors.convai.light})`;
342
- buttonContent.appendChild(convaiLogo);
343
- // Chat content
344
- chatContent = document.createElement("div");
345
- // ----------------------------------------------------------------------
346
- // `launcher` / `panel` part semantics. Read before writing theming docs.
347
- //
348
- // This widget morphs rather than swapping trees: `morphingContainer` IS
349
- // the 64px circle AND the open panel, animating between them (see
350
- // setIsOpen). It therefore owns every painted surface property of both
351
- // states -- background, border, border-radius, box-shadow. `buttonContent`
352
- // and `chatContent` are transparent `inset: 0` overlays that only
353
- // cross-fade their contents.
354
- //
355
- // So, precisely:
356
- // ::part(launcher) -> morphingContainer. Paints the collapsed circle
357
- // AND the open panel; there is no rule that hits
358
- // only one. This is the surface part.
359
- // ::part(panel) -> chatContent. The open state's *content layer*:
360
- // useful for padding, colour, font, opacity. It has
361
- // no background, no border and no radius of its
362
- // own, so `::part(panel){border-radius}` does
363
- // nothing -- set radius via ::part(launcher) or
364
- // `--convai-radius` (which is panel-scoped).
365
- //
366
- // Assessed and deliberately not "fixed": moving `launcher` onto
367
- // buttonContent would make `::part(launcher){background}` state-specific
368
- // but would silently break `border-radius` and `box-shadow` on it, since
369
- // buttonContent is clipped by the container's own radius + overflow:
370
- // hidden. Correcting this properly needs a separate launcher element
371
- // instead of a morph -- a rendering change, out of scope here.
372
- // ----------------------------------------------------------------------
373
- chatContent.setAttribute("part", "panel");
374
- chatContent.style.cssText = `
375
- position: absolute;
376
- inset: 0;
377
- display: flex;
378
- flex-direction: column;
379
- opacity: 0;
380
- transform: scale(0.8);
381
- transition: opacity 0.2s, transform 0.2s;
382
- pointer-events: none;
383
- `;
384
- // Voice Mode Overlay
385
- voiceModeOverlay = createVoiceModeOverlay();
386
- chatContent.appendChild(voiceModeOverlay);
387
- // Header
388
- headerElement = createHeader();
389
- // Content area
390
- contentElement = document.createElement("div");
391
- contentElement.style.cssText = `
392
- flex: 1;
393
- overflow-y: auto;
394
- padding: 16px;
395
- background: transparent;
396
- position: relative;
397
- `;
398
- messageListElement = createMessageList();
399
- contentElement.appendChild(messageListElement);
400
- // Connecting overlay -- shown until the bot is ready. Appended last, not
401
- // to match DOM order (position: absolute + z-index: 100, set inside
402
- // createConnectingOverlay, is what keeps it on top regardless of source
403
- // order) but so inserting it doesn't shift every existing sibling's
404
- // index-based path in the inline-style-parity fixture.
405
- connectingOverlay = createConnectingOverlay();
406
- contentElement.appendChild(connectingOverlay);
407
- // Footer
408
- footerElement = createFooter();
409
- chatContent.appendChild(headerElement);
410
- chatContent.appendChild(contentElement);
411
- chatContent.appendChild(footerElement);
412
- morphingContainer.appendChild(buttonContent);
413
- morphingContainer.appendChild(chatContent);
414
- rootElement.appendChild(morphingContainer);
415
- // Settings tray
416
- settingsTray = createSettingsTray();
417
- rootElement.appendChild(settingsTray);
418
- // Floating video
419
- floatingVideo = createFloatingVideo();
420
- container.appendChild(floatingVideo);
421
- container.appendChild(rootElement);
422
- // Event listeners
423
- morphingContainer.addEventListener("click", handleLauncherClick);
424
- };
425
- // Create Voice Mode Overlay
426
- /**
427
- * Voice mode, matched to the React overlay (VoiceModeOverlay.tsx) rather
428
- * than to what this file used to draw.
429
- *
430
- * The two had diverged badly: React centres the character's avatar inside
431
- * two counter-rotating liquid-gradient layers and paints the user's
432
- * microphone as three overlapping sine waves on a canvas, while this file
433
- * drew forty grey vertical bars and no avatar at all. Same product, two
434
- * unrelated screens.
435
- *
436
- * What is reproduced here, value for value: the 120px avatar with its 3px
437
- * rgba(255,255,255,0.2) ring and letter fallback, the 126px conic and
438
- * radial gradient layers (20s clockwise / 15s anticlockwise, blurred 8px
439
- * and 6px), the 250x80 canvas carrying three waves, and the status text at
440
- * 16px/600 over 13px with React's wording.
441
- *
442
- * The one deliberate omission is the `AudioVisualizer` ring that React
443
- * fades in behind the avatar while the character speaks: it is a 364-line
444
- * component wired directly to a LiveKit `Room`, and porting it is its own
445
- * change. The avatar still breathes while the character speaks, so the
446
- * speaking state reads without it.
447
- */
448
- const createVoiceModeOverlay = () => {
449
- const overlay = document.createElement("div");
450
- overlay.style.cssText = `
451
- position: absolute;
452
- top: 50%;
453
- left: 50%;
454
- transform: translate(-50%, -50%);
455
- text-align: center;
456
- padding: 16px;
457
- z-index: 10;
458
- pointer-events: auto;
459
- display: none;
460
- flex-direction: column;
461
- align-items: center;
462
- gap: 32px;
463
- `;
464
- // --- Avatar, with the two rotating gradient layers behind it ----------
465
- const avatarWrap = document.createElement("div");
466
- avatarWrap.style.cssText = `
467
- position: relative;
468
- display: flex;
469
- align-items: center;
470
- justify-content: center;
471
- isolation: isolate;
472
- `;
473
- const avatarStack = document.createElement("div");
474
- avatarStack.className = "convai-voice-avatar";
475
- refs.voiceModeAvatar = avatarStack;
476
- avatarStack.style.cssText = `
477
- position: relative;
478
- z-index: 10;
479
- border-radius: 50%;
480
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
481
- background: white;
482
- display: flex;
483
- align-items: center;
484
- justify-content: center;
485
- `;
486
- const accent = `var(--convai-accent, ${aeroTheme.colors.convai.light})`;
487
- const layer1 = document.createElement("div");
488
- layer1.className = "convai-voice-gradient";
489
- layer1.style.cssText = `
490
- position: absolute;
491
- width: 126px;
492
- height: 126px;
493
- border-radius: 50%;
494
- background: conic-gradient(
495
- from 0deg,
496
- ${aeroTheme.colors.convai.light}00 0%,
497
- ${aeroTheme.colors.convai.light}40 25%,
498
- ${aeroTheme.colors.convai.dark}60 50%,
499
- ${aeroTheme.colors.convai.light}40 75%,
500
- ${aeroTheme.colors.convai.light}00 100%
501
- );
502
- opacity: 0.8;
503
- filter: blur(8px);
504
- z-index: -2;
505
- animation: convaiVoiceSpin 20s linear infinite;
506
- `;
507
- const layer2 = document.createElement("div");
508
- layer2.className = "convai-voice-gradient";
509
- layer2.style.cssText = `
510
- position: absolute;
511
- width: 126px;
512
- height: 126px;
513
- border-radius: 50%;
514
- background:
515
- radial-gradient(ellipse 80% 100% at 30% 40%,
516
- ${aeroTheme.colors.convai.light}50,
517
- ${aeroTheme.colors.convai.light}30 40%,
518
- transparent 70%),
519
- radial-gradient(ellipse 80% 100% at 70% 60%,
520
- ${aeroTheme.colors.convai.dark}50,
521
- ${aeroTheme.colors.convai.dark}30 40%,
522
- transparent 70%);
523
- opacity: 0.9;
524
- filter: blur(6px);
525
- z-index: -1;
526
- animation: convaiVoiceSpinReverse 15s linear infinite;
527
- `;
528
- // The image is clipped by its own container so the gradients above stay
529
- // visible outside it — React nests it the same way for the same reason.
530
- const avatarClip = document.createElement("div");
531
- avatarClip.style.cssText = `
532
- position: relative;
533
- border-radius: 50%;
534
- overflow: hidden;
535
- border: 3px solid rgba(255, 255, 255, 0.2);
536
- width: 120px;
537
- height: 120px;
538
- display: flex;
539
- align-items: center;
540
- justify-content: center;
541
- `;
542
- refs.voiceModeAvatarClip = avatarClip;
543
- avatarStack.append(layer1, layer2, avatarClip);
544
- avatarWrap.appendChild(avatarStack);
545
- overlay.appendChild(avatarWrap);
546
- // --- The user's microphone, as three waves on a canvas ----------------
547
- const canvas = document.createElement("canvas");
548
- canvas.className = "convai-voice-wave";
549
- canvas.style.cssText = `width: 250px; height: 80px;`;
550
- refs.voiceModeCanvas = canvas;
551
- overlay.appendChild(canvas);
552
- // --- Status text ------------------------------------------------------
553
- const statusContainer = document.createElement("div");
554
- const statusTitle = document.createElement("div");
555
- statusTitle.id = "voice-mode-title";
556
- refs.voiceModeTitle = statusTitle;
557
- statusTitle.style.cssText = `
558
- font-size: 16px;
559
- font-weight: 600;
560
- color: var(--convai-panel-fg, ${aeroTheme.colors.text.primary});
561
- margin-bottom: 8px;
562
- `;
563
- statusTitle.textContent = "Voice Mode";
564
- const statusSubtitle = document.createElement("div");
565
- statusSubtitle.id = "voice-mode-subtitle";
566
- refs.voiceModeSubtitle = statusSubtitle;
567
- statusSubtitle.style.cssText = `
568
- font-size: 13px;
569
- color: ${aeroTheme.colors.text.secondary};
570
- `;
571
- statusSubtitle.textContent = "Tap microphone to talk";
572
- statusContainer.append(statusTitle, statusSubtitle);
573
- overlay.appendChild(statusContainer);
574
- void accent;
575
- return overlay;
576
- };
577
- /**
578
- * Fills the voice-mode avatar from the character info fetch, or falls back
579
- * to the character's initial the way React does. Called from
580
- * updateHeader(), so it tracks a late `fetchCharacterInfo()` rather than
581
- * being fixed at construction.
582
- */
583
- const updateVoiceModeAvatar = () => {
584
- const clip = refs.voiceModeAvatarClip;
585
- if (!clip)
586
- return;
587
- const wanted = characterImage || `letter:${characterName}`;
588
- if (clip.dataset.filledWith === wanted)
589
- return;
590
- clip.dataset.filledWith = wanted;
591
- clip.replaceChildren();
592
- if (characterImage) {
593
- const img = document.createElement("img");
594
- img.src = characterImage;
595
- img.alt = characterName;
596
- img.style.cssText = `width: 120px; height: 120px; object-fit: cover; display: block;`;
597
- clip.appendChild(img);
598
- return;
599
- }
600
- const letter = document.createElement("div");
601
- letter.style.cssText = `
602
- width: 120px;
603
- height: 120px;
604
- background-color: ${aeroTheme.colors.convai.light}20;
605
- display: flex;
606
- align-items: center;
607
- justify-content: center;
608
- font-size: 48px;
609
- font-weight: 600;
610
- color: var(--convai-accent, ${aeroTheme.colors.convai.light});
611
- `;
612
- letter.textContent = characterName[0]?.toUpperCase() || "C";
613
- clip.appendChild(letter);
614
- };
615
- // Create Connecting Overlay -- matches React's inline AnimatePresence
616
- // block exactly (ConvaiWidget.tsx:681-737): shown whenever
617
- // `isConnected && !isBotReady`, covering just the content area (not the
618
- // header/footer) so the chrome stays interactive while the character
619
- // joins. Persistent in the DOM like voiceModeOverlay above -- toggled via
620
- // opacity/pointer-events rather than mounted/unmounted, since this file has
621
- // no AnimatePresence-style exit-animation machinery. Visibility is driven
622
- // by updateConnectingOverlay().
623
- const createConnectingOverlay = () => {
624
- const overlay = document.createElement("div");
625
- overlay.id = "convai-connecting-overlay";
626
- overlay.style.cssText = `
627
- position: absolute;
628
- inset: 0;
629
- z-index: 100;
630
- display: flex;
631
- flex-direction: column;
632
- align-items: center;
633
- justify-content: center;
634
- gap: 16px;
635
- background: rgba(255, 255, 255, 0.95);
636
- opacity: 0;
637
- pointer-events: none;
638
- transition: opacity 0.3s;
639
- `;
640
- // Keyframes live in the shadow-safe injector (styles.ts), not
641
- // document.head -- @keyframes defined there do not resolve for shadow
642
- // content. Idempotent; also called from createSettingsTray().
643
- injectKeyframes(styleTarget);
644
- // Spinning logo: a full turn every 2s, linear, infinite.
645
- const spinWrapper = document.createElement("div");
646
- spinWrapper.className = "convai-connecting-spin";
647
- spinWrapper.style.cssText = `
648
- display: inline-flex;
649
- animation: convaiConnectingSpin 2s linear infinite;
650
- `;
651
- const logo = Icons.ConvaiLogo("xl", "connecting");
652
- // Themable, like every other accent usage in this file (see
653
- // theming.test.ts) -- var() with the exact literal React passes
654
- // (`aeroTheme.colors.convai.light`) as the fallback, so an unset
655
- // --convai-accent renders identically to the React value.
656
- logo.style.color = `var(--convai-accent, ${aeroTheme.colors.convai.light})`;
657
- spinWrapper.appendChild(logo);
658
- overlay.appendChild(spinWrapper);
659
- // Pulsing "Connecting to {characterName}..." label.
660
- const label = document.createElement("div");
661
- label.id = "convai-connecting-text";
662
- label.className = "convai-connecting-pulse";
663
- label.style.cssText = `
664
- font-size: 14px;
665
- font-weight: 500;
666
- color: ${aeroTheme.colors.text.secondary};
667
- animation: convaiConnectingPulse 2s ease-in-out infinite;
668
- `;
669
- refs.connectingLabel = label;
670
- overlay.appendChild(label);
671
- return overlay;
672
- };
673
- /** Shows/hides the connecting overlay and refreshes its label. Called
674
- * from updateHeader() so every existing call site (stateChange, botReady,
675
- * connect/disconnect via stateChange, character-info fetch, ...) stays in
676
- * sync automatically. */
677
- const updateConnectingOverlay = () => {
678
- if (!connectingOverlay)
679
- return;
680
- const label = refs.connectingLabel;
681
- if (label) {
682
- label.textContent = `Connecting to ${characterName}...`;
683
- }
684
- // `isConnecting` matters as much as `isConnected` here. The panel opens
685
- // on the click that *starts* the connect, so between that click and the
686
- // transport coming up (a real network round trip — ~3s against the live
687
- // service) `isConnected` is still false. Gating on it alone left the
688
- // whole of that window with no overlay at all: an empty message area and
689
- // a nameless header, i.e. the widget looked broken for exactly as long as
690
- // it was doing the one thing the user asked for. Then the label appeared
691
- // *after* the transport was already up, which reads backwards.
692
- //
693
- // The embed makes this the normal path rather than an edge case: its
694
- // launcher click opens the panel immediately by design, so the pre-connect
695
- // window is always visible to the user.
696
- const shouldShow = (client.state.isConnected || client.state.isConnecting) && !client.isBotReady;
697
- connectingOverlay.style.opacity = shouldShow ? "1" : "0";
698
- connectingOverlay.style.pointerEvents = shouldShow ? "auto" : "none";
699
- };
700
- // Audio Analysis State for Voice Mode
701
- let audioLevels = Array(40).fill(0);
702
- let startTime = 0;
703
- /**
704
- * Paints the three overlapping sine waves React draws for the user's
705
- * microphone (VoiceModeOverlay.tsx's `drawWaves`), including its two
706
- * performance guards, which matter more here than there: this canvas sits
707
- * over whatever the host page is rendering, and every repaint forces the
708
- * compositor to re-blend the whole panel. So it runs at 30fps rather than
709
- * 60, and stops entirely while the input is silent — the static line is
710
- * already on the canvas at that point.
711
- */
712
- let waveFrameParity = 0;
713
- let waveWasSilent = false;
714
- const drawWaves = () => {
715
- const canvas = refs.voiceModeCanvas;
716
- if (!canvas)
717
- return;
718
- waveFrameParity ^= 1;
719
- if (waveFrameParity)
720
- return;
721
- let sum = 0;
722
- for (let i = 0; i < audioLevels.length; i++)
723
- sum += audioLevels[i];
724
- const silent = sum / audioLevels.length < 0.012;
725
- if (silent && waveWasSilent)
726
- return;
727
- waveWasSilent = silent;
728
- const dpr = Math.min(window.devicePixelRatio || 1, 2);
729
- if (canvas.width !== 250 * dpr) {
730
- canvas.width = 250 * dpr;
731
- canvas.height = 80 * dpr;
732
- }
733
- const ctx = canvas.getContext("2d");
734
- if (!ctx)
735
- return;
736
- ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
737
- ctx.clearRect(0, 0, 250, 80);
738
- const centerY = 40;
739
- const waveWidth = 250;
740
- const segments = 40;
741
- const avgLevel = sum / audioLevels.length;
742
- const waveColors = [
743
- aeroTheme.colors.convai.light,
744
- aeroTheme.colors.convai.light,
745
- "#34d399",
746
- ];
747
- ctx.lineCap = "round";
748
- ctx.lineJoin = "round";
749
- for (let waveIndex = 2; waveIndex >= 0; waveIndex--) {
750
- ctx.beginPath();
751
- for (let i = 0; i <= segments; i++) {
752
- const x = (i / segments) * waveWidth;
753
- const levelIndex = Math.floor((i / segments) * (audioLevels.length - 1));
754
- const level = audioLevels[levelIndex] || 0;
755
- const phase = (Date.now() / 500 + i * 0.2 + waveIndex * 1.5) % (Math.PI * 2);
756
- const baseAmplitude = avgLevel > 0.05 ? 2 + waveIndex * 1.5 : 0;
757
- const amplitude = baseAmplitude + level * (25 - baseAmplitude);
758
- const y = centerY + Math.sin(phase) * amplitude;
759
- if (i === 0)
760
- ctx.moveTo(x, y);
761
- else
762
- ctx.lineTo(x, y);
763
- }
764
- ctx.strokeStyle = waveColors[waveIndex];
765
- ctx.globalAlpha = 0.18 * (0.3 + avgLevel);
766
- ctx.lineWidth = 2.5 - waveIndex * 0.4 + 8 * avgLevel + 3;
767
- ctx.stroke();
768
- ctx.globalAlpha = 0.95 - waveIndex * 0.15;
769
- ctx.lineWidth = 2.5 - waveIndex * 0.4;
770
- ctx.stroke();
771
- }
772
- ctx.globalAlpha = 1;
773
- };
774
- /**
775
- * The voice-mode frame loop. Keeps the name `updateAudioBars` because
776
- * every call site refers to it; what it drives is now the avatar, the
777
- * canvas and the status text rather than forty bars.
778
- */
779
- const updateAudioBars = () => {
780
- if (!voiceModeOverlay)
781
- return;
782
- const isTalking = client.state.isSpeaking;
783
- const isListening = client.state.isListening;
784
- const micOpen = !client.audioControls.isAudioMuted;
785
- // The avatar breathes while the character speaks — React drives the same
786
- // thing with a framer-motion scale keyframe.
787
- const avatar = refs.voiceModeAvatar;
788
- if (avatar) {
789
- const wanted = isTalking ? "convaiVoiceBreathe 3s ease-in-out infinite" : "";
790
- if (avatar.style.animation !== wanted)
791
- avatar.style.animation = wanted;
792
- }
793
- // React's exact wording, including "Voice Mode" rather than the
794
- // "Voice Only Mode" this file used to show.
795
- const title = refs.voiceModeTitle;
796
- const subtitle = refs.voiceModeSubtitle;
797
- if (title) {
798
- title.textContent = isTalking
799
- ? `${characterName} Speaking...`
800
- : isListening || micOpen
801
- ? "Listening..."
802
- : "Voice Mode";
803
- }
804
- if (subtitle) {
805
- subtitle.textContent =
806
- isListening || micOpen || isTalking ? "Audio active" : "Tap microphone to talk";
807
- }
808
- if ((isListening || micOpen) && analyzer && dataArray) {
809
- // @ts-ignore - TypeScript strict mode issue with Uint8Array type
810
- analyzer.getByteTimeDomainData(dataArray);
811
- let sum = 0;
812
- for (let i = 0; i < dataArray.length; i++) {
813
- const normalized = (dataArray[i] - 128) / 128;
814
- sum += normalized * normalized;
815
- }
816
- const rms = Math.sqrt(sum / dataArray.length);
817
- const volume = Math.min(1, rms * 3);
818
- for (let i = 0; i < audioLevels.length; i++) {
819
- const position = i / audioLevels.length;
820
- const wavePhase = Date.now() / 300 + position * Math.PI * 2;
821
- const waveVariation = Math.sin(wavePhase) * 0.15 + 0.85;
822
- audioLevels[i] = volume * waveVariation;
823
- }
824
- }
825
- else {
826
- // The waves settle to a flat line rather than animating on the
827
- // character's behalf: React paints this canvas from the microphone
828
- // only, and the character's own speech is the avatar's job.
829
- for (let i = 0; i < audioLevels.length; i++)
830
- audioLevels[i] = 0;
831
- }
832
- drawWaves();
833
- rafId = requestAnimationFrame(updateAudioBars);
834
- };
835
- const startAudioAnalysis = async () => {
836
- try {
837
- if (!audioContext) {
838
- audioContext = new (window.AudioContext ||
839
- window.webkitAudioContext)();
840
- }
841
- if (audioContext.state === "suspended") {
842
- await audioContext.resume();
843
- }
844
- const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
845
- analyzer = audioContext.createAnalyser();
846
- analyzer.fftSize = 256;
847
- analyzer.smoothingTimeConstant = 0.7;
848
- source = audioContext.createMediaStreamSource(stream);
849
- source.connect(analyzer);
850
- dataArray = new Uint8Array(analyzer.fftSize);
851
- updateAudioBars();
852
- }
853
- catch (e) {
854
- // Fourth mic-acquiring call site: this getUserMedia() is independent
855
- // of client.audioControls (it's a separate analyser-only stream, not
856
- // routed through AudioManager), but a denial here is the identical
857
- // failure mode -- most commonly a mid-session permission revocation,
858
- // since by the time voice mode is entered the mic has usually already
859
- // been granted via unmuteAudio(). Same helper, same channel, so a
860
- // consumer sees one consistent signal regardless of which internal
861
- // path acquired the mic.
862
- reportMicFailure(client, "Audio analysis setup failed:", e);
863
- }
864
- };
865
- const stopAudioAnalysis = () => {
866
- if (rafId)
867
- cancelAnimationFrame(rafId);
868
- if (source) {
869
- source.disconnect();
870
- source.mediaStream.getTracks().forEach((t) => t.stop());
871
- source = null;
872
- }
873
- // Keep context alive if possible, or close it? React component closes it.
874
- // We can keep it for reuse or close. Let's keep it simple.
875
- };
876
- // Create header
877
- const createHeader = () => {
878
- const header = document.createElement("div");
879
- header.setAttribute("part", "header");
880
- header.style.cssText = `
881
- display: flex;
882
- align-items: center;
883
- justify-content: space-between;
884
- padding: 16px;
885
- border-bottom: 1px solid ${aeroTheme.colors.neutral[200]};
886
- background: var(--convai-panel-bg, white);
887
- position: relative;
888
- `;
889
- // Close button on the left
890
- const closeButton = document.createElement("button");
891
- const chevronIcon = Icons.ChevronDown("md");
892
- closeButton.appendChild(chevronIcon);
893
- closeButton.style.cssText = `
894
- font-size: 20px;
895
- color: ${aeroTheme.colors.text.secondary};
896
- cursor: pointer;
897
- padding: 4px;
898
- transition: ${aeroTheme.transitions.fast};
899
- background: transparent;
900
- border: none;
901
- `;
902
- closeButton.addEventListener("click", (e) => {
903
- e.stopPropagation();
904
- handleClose();
905
- });
906
- // Title section centered - matches React version
907
- const titleSection = document.createElement("div");
908
- titleSection.style.cssText = `
909
- position: absolute;
910
- left: 50%;
911
- transform: translateX(-50%);
912
- display: flex;
913
- align-items: center;
914
- gap: 8px;
915
- font-size: ${aeroTheme.typography.fontSize.base};
916
- font-weight: ${aeroTheme.typography.fontWeight.semibold};
917
- color: var(--convai-panel-fg, ${aeroTheme.colors.text.primary});
918
- `;
919
- titleSection.id = "convai-widget-title";
920
- refs.widgetTitle = titleSection;
921
- // Settings button on the right
922
- const settingsButton = document.createElement("button");
923
- const moreIcon = Icons.MoreVertical("md");
924
- settingsButton.appendChild(moreIcon);
925
- settingsButton.style.cssText = `
926
- font-size: 24px;
927
- color: ${aeroTheme.colors.text.secondary};
928
- cursor: pointer;
929
- padding: 4px;
930
- transition: ${aeroTheme.transitions.fast};
931
- background: transparent;
932
- border: none;
933
- margin-left: auto;
934
- `;
935
- settingsButton.addEventListener("click", (e) => {
936
- e.stopPropagation();
937
- handleSettingsToggle();
938
- });
939
- header.appendChild(closeButton);
940
- header.appendChild(titleSection);
941
- header.appendChild(settingsButton);
942
- return header;
943
- };
944
- // Update header with character info
945
- const updateHeader = () => {
946
- const titleSection = refs.widgetTitle;
947
- if (!titleSection)
948
- return;
949
- titleSection.innerHTML = "";
950
- if (characterImage) {
951
- const img = document.createElement("img");
952
- img.src = characterImage;
953
- img.alt = characterName;
954
- img.style.cssText = `
955
- width: 24px;
956
- height: 24px;
957
- border-radius: 50%;
958
- object-fit: cover;
959
- border: 1.5px solid ${getBotStatusColor().color};
960
- box-shadow: 0 0 6px ${getBotStatusColor().color}40;
961
- transition: all 0.3s ease;
962
- `;
963
- titleSection.appendChild(img);
964
- }
965
- const nameSpan = document.createElement("span");
966
- nameSpan.textContent = characterName;
967
- titleSection.appendChild(nameSpan);
968
- // Mute button
969
- const muteButton = document.createElement("button");
970
- muteButton.innerHTML = "";
971
- const volumeIcon = isMuted
972
- ? Icons.VolumeMute("sm")
973
- : Icons.VolumeHigh("sm");
974
- volumeIcon.style.color = isMuted ? "#919EABA6" : "#0E7360";
975
- muteButton.appendChild(volumeIcon);
976
- muteButton.style.cssText = `
977
- cursor: pointer;
978
- background: transparent;
979
- border: none;
980
- box-shadow: none;
981
- width: auto;
982
- height: auto;
983
- padding: 0;
984
- display: inline-flex;
985
- align-items: center;
986
- margin-left: 8px;
987
- outline: none;
988
- transition: transform 0.1s ease-out;
989
- `;
990
- muteButton.addEventListener("click", (e) => {
991
- e.stopPropagation();
992
- handleToggleMute();
993
- });
994
- muteButton.addEventListener("mouseenter", () => {
995
- muteButton.style.transform = "scale(1.1)";
996
- });
997
- muteButton.addEventListener("mouseleave", () => {
998
- muteButton.style.transform = "scale(1)";
999
- });
1000
- titleSection.appendChild(muteButton);
1001
- // Voice Mode Badge
1002
- if (isVoiceMode) {
1003
- const voiceBadge = document.createElement("span");
1004
- voiceBadge.textContent = "VOICE";
1005
- voiceBadge.style.cssText = `
1006
- font-size: 10px;
1007
- color: var(--convai-accent, ${aeroTheme.colors.convai.light});
1008
- font-weight: 500;
1009
- margin-left: 8px;
1010
- padding: 2px 6px;
1011
- border-radius: 4px;
1012
- background-color: ${aeroTheme.colors.convai.light}20;
1013
- `;
1014
- titleSection.appendChild(voiceBadge);
1015
- }
1016
- // Speaking tag (top bar, same style as React)
1017
- if (client.state.isSpeaking) {
1018
- const speakingTag = document.createElement("span");
1019
- speakingTag.textContent = "SPEAKING";
1020
- speakingTag.style.cssText = `
1021
- font-size: 10px;
1022
- color: #10b981;
1023
- font-weight: 600;
1024
- margin-left: 8px;
1025
- padding: 3px 8px;
1026
- border-radius: 6px;
1027
- background-color: #10b98120;
1028
- border: 1px solid #10b98140;
1029
- display: inline-flex;
1030
- align-items: center;
1031
- gap: 4px;
1032
- `;
1033
- const dot = document.createElement("span");
1034
- dot.style.cssText = `
1035
- width: 6px;
1036
- height: 6px;
1037
- border-radius: 50%;
1038
- background-color: #10b981;
1039
- display: inline-block;
1040
- `;
1041
- speakingTag.insertBefore(dot, speakingTag.firstChild);
1042
- titleSection.appendChild(speakingTag);
1043
- }
1044
- // Listening tag (top bar, when user is speaking)
1045
- if (client.state.isListening && !client.state.isSpeaking) {
1046
- const listeningTag = document.createElement("span");
1047
- listeningTag.textContent = "LISTENING";
1048
- listeningTag.style.cssText = `
1049
- font-size: 10px;
1050
- color: #3b82f6;
1051
- font-weight: 600;
1052
- margin-left: 8px;
1053
- padding: 3px 8px;
1054
- border-radius: 6px;
1055
- background-color: #3b82f620;
1056
- border: 1px solid #3b82f640;
1057
- display: inline-flex;
1058
- align-items: center;
1059
- gap: 4px;
1060
- `;
1061
- const dot = document.createElement("span");
1062
- dot.style.cssText = `
1063
- width: 6px;
1064
- height: 6px;
1065
- border-radius: 50%;
1066
- background-color: #3b82f6;
1067
- display: inline-block;
1068
- `;
1069
- listeningTag.insertBefore(dot, listeningTag.firstChild);
1070
- titleSection.appendChild(listeningTag);
1071
- }
1072
- // Every call site that refreshes the header (stateChange, botReady,
1073
- // connect/disconnect via stateChange, character-info fetch, ...) also
1074
- // needs the connecting overlay re-evaluated -- it depends on the same
1075
- // `isConnected`/`isBotReady`/`characterName` inputs.
1076
- updateConnectingOverlay();
1077
- updateVoiceModeAvatar();
1078
- };
1079
- // Create message list
1080
- const createMessageList = () => {
1081
- const list = document.createElement("div");
1082
- list.id = "convai-message-list";
1083
- list.setAttribute("part", "messages");
1084
- list.style.cssText = `
1085
- display: flex;
1086
- flex-direction: column;
1087
- gap: 12px;
1088
- min-height: 100%;
1089
- `;
1090
- return list;
1091
- };
1092
- // Create footer
1093
- const createFooter = () => {
1094
- const footer = document.createElement("div");
1095
- footer.style.cssText = `
1096
- padding: 16px;
1097
- border-top: 1px solid ${aeroTheme.colors.neutral[200]};
1098
- background: var(--convai-panel-bg, white);
1099
- display: flex;
1100
- gap: 8px;
1101
- align-items: center;
1102
- position: relative;
1103
- `;
1104
- // Voice Mode Exit Button (Initially hidden)
1105
- const voiceExitButton = document.createElement("button");
1106
- voiceExitButton.id = "convai-voice-exit-btn";
1107
- refs.voiceExitBtn = voiceExitButton;
1108
- const exitIcon = Icons.PhoneOff("md");
1109
- voiceExitButton.appendChild(exitIcon);
1110
- voiceExitButton.style.cssText = `
1111
- width: 36px;
1112
- height: 36px;
1113
- border-radius: 50%;
1114
- background: ${aeroTheme.colors.error[500]};
1115
- color: white;
1116
- display: none; /* Hidden by default */
1117
- align-items: center;
1118
- justify-content: center;
1119
- cursor: pointer;
1120
- margin: 0 auto;
1121
- border: none;
1122
- `;
1123
- voiceExitButton.addEventListener("click", () => {
1124
- // Deliberately a *sync* listener. It used to be `async` with a bare
1125
- // `await client.audioControls.muteAudio()` and no try/catch: on the
1126
- // LiveKit path that call rethrows when the room has dropped, so a
1127
- // network blip mid-call plus a tap on exit leaked an unhandled
1128
- // rejection onto the host page *and* skipped the two lines below,
1129
- // stranding the user in the voice overlay with no way out.
1130
- //
1131
- // The mute is not dropped -- `applyVoiceMode()` -> `updateVoiceMode()`
1132
- // performs it (conditionally, if the mic is live) inside the exit
1133
- // branch, where a failure is now reported rather than fatal. Exiting
1134
- // the UI is unconditional either way: the overlay must never outlive
1135
- // the user's decision to leave it.
1136
- client.sendInterruptMessage();
1137
- isVoiceMode = false;
1138
- applyVoiceMode();
1139
- });
1140
- footer.appendChild(voiceExitButton);
1141
- // Standard Footer Content (Mic + Input)
1142
- const standardContent = document.createElement("div");
1143
- standardContent.id = "convai-footer-standard";
1144
- refs.footerStandard = standardContent;
1145
- standardContent.style.cssText = `
1146
- display: flex;
1147
- gap: 8px;
1148
- align-items: center;
1149
- width: 100%;
1150
- `;
1151
- // Input container (microphone button removed from text mode)
1152
- const inputContainer = document.createElement("div");
1153
- inputContainer.style.cssText = `
1154
- flex: 1;
1155
- position: relative;
1156
- display: flex;
1157
- align-items: center;
1158
- `;
1159
- inputElement = document.createElement("input");
1160
- inputElement.setAttribute("part", "input");
1161
- inputElement.type = "text";
1162
- inputElement.placeholder = "Conversation";
1163
- inputElement.style.cssText = `
1164
- width: 100%;
1165
- padding: 12px 44px 12px 16px;
1166
- border-radius: ${aeroTheme.borderRadius.full};
1167
- border: 1px solid ${aeroTheme.colors.neutral[300]};
1168
- background: ${aeroTheme.colors.glass.medium};
1169
- color: var(--convai-panel-fg, ${aeroTheme.colors.text.primary});
1170
- font-size: ${aeroTheme.typography.fontSize.sm};
1171
- transition: ${aeroTheme.transitions.fast};
1172
- outline: none;
1173
- `;
1174
- inputElement.addEventListener("input", (e) => {
1175
- inputValue = e.target.value;
1176
- updateSendButton();
1177
- });
1178
- inputElement.addEventListener("keypress", (e) => {
1179
- if (e.key === "Enter")
1180
- handleSend();
1181
- });
1182
- // Send button
1183
- const sendButton = document.createElement("button");
1184
- sendButton.id = "convai-send-button";
1185
- // This button is dual-role -- it sends text when the input has a draft,
1186
- // and toggles voice mode when empty -- but there is no separate mic
1187
- // element, so only the send-button part applies. `mic-button` is
1188
- // reserved for a future version that splits the two; see parts.test.ts.
1189
- sendButton.setAttribute("part", "send-button");
1190
- refs.sendButton = sendButton;
1191
- const sendIcon = Icons.Send("md");
1192
- sendButton.appendChild(sendIcon);
1193
- sendButton.style.cssText = `
1194
- position: absolute;
1195
- right: 6px;
1196
- width: 36px;
1197
- height: 36px;
1198
- border-radius: 50%;
1199
- background: transparent; /* Initial transparent for voice toggle */
1200
- color: var(--convai-panel-fg, ${aeroTheme.colors.text.primary});
1201
- display: flex;
1202
- align-items: center;
1203
- justify-content: center;
1204
- cursor: pointer;
1205
- transition: ${aeroTheme.transitions.fast};
1206
- border: none;
1207
- `;
1208
- sendButton.addEventListener("click", async () => {
1209
- if (inputValue.length > 0) {
1210
- handleSend();
1211
- }
1212
- else if (!requestPublicationGrant &&
1213
- client.connectionType !== "text") {
1214
- // Toggle Voice Mode
1215
- client.sendInterruptMessage();
1216
- try {
1217
- await client.audioControls.unmuteAudio(); // Unmute on enter
1218
- isVoiceMode = true;
1219
- // Awaited so this try/catch actually covers it -- bare, the promise
1220
- // escaped the block it looks like it belongs to.
1221
- await updateVoiceMode();
1222
- }
1223
- catch (error) {
1224
- // isVoiceMode is only flipped after a successful unmute, so a
1225
- // denial here leaves the widget in text mode, not stranded
1226
- // mid-transition into voice mode.
1227
- reportMicFailure(client, "Failed to enable microphone:", error);
1228
- }
1229
- }
1230
- });
1231
- inputContainer.appendChild(inputElement);
1232
- inputContainer.appendChild(sendButton);
1233
- standardContent.appendChild(inputContainer);
1234
- footer.appendChild(standardContent);
1235
- return footer;
1236
- };
1237
- // Create settings tray - Matches React SettingsTray component exactly
1238
- const createSettingsTray = () => {
1239
- const tray = document.createElement("div");
1240
- tray.setAttribute("data-settings-tray", "true");
1241
- tray.style.cssText = `
1242
- position: absolute;
1243
- top: 60px;
1244
- right: 16px;
1245
- background: var(--convai-panel-bg, white);
1246
- border-radius: ${aeroTheme.borderRadius.xl};
1247
- box-shadow: ${aeroTheme.shadows.xl};
1248
- padding: 0;
1249
- display: none;
1250
- flex-direction: row;
1251
- align-items: center;
1252
- gap: 0;
1253
- z-index: 9999;
1254
- min-width: auto;
1255
- transform-origin: top right;
1256
- animation: popIn 0.2s cubic-bezier(0.175, 0.885, 0.32, 1.275);
1257
- overflow: hidden;
1258
- `;
1259
- // Add animation keyframes if not present
1260
- injectKeyframes(styleTarget);
1261
- // Horizontal Settings Row Container
1262
- const settingsRow = document.createElement("div");
1263
- settingsRow.style.cssText = `
1264
- display: flex;
1265
- flex-direction: row;
1266
- align-items: center;
1267
- padding: 8px;
1268
- gap: 4px;
1269
- `;
1270
- const createOption = (icon, label, onClick, isActive = false, isDestructive = false) => {
1271
- const btn = document.createElement("div");
1272
- btn.style.cssText = `
1273
- display: flex;
1274
- flex-direction: column;
1275
- align-items: center;
1276
- gap: 4px;
1277
- padding: 8px 12px;
1278
- cursor: pointer;
1279
- border-radius: ${aeroTheme.borderRadius.md};
1280
- background-color: ${isActive
1281
- ? "rgba(16, 185, 129, 0.15)"
1282
- : isDestructive
1283
- ? "rgba(239, 68, 68, 0.1)"
1284
- : "transparent"};
1285
- color: ${isActive
1286
- ? "#10b981"
1287
- : isDestructive
1288
- ? "#ef4444"
1289
- : `var(--convai-panel-fg, ${aeroTheme.colors.text.primary})`};
1290
- transition: ${aeroTheme.transitions.fast};
1291
- min-width: 50px;
1292
- `;
1293
- // Icon container
1294
- const iconContainer = document.createElement("div");
1295
- iconContainer.appendChild(icon);
1296
- btn.appendChild(iconContainer);
1297
- const span = document.createElement("span");
1298
- span.textContent = label;
1299
- span.style.cssText = `
1300
- font-size: 10px;
1301
- font-weight: 500;
1302
- `;
1303
- btn.appendChild(span);
1304
- btn.addEventListener("click", (e) => {
1305
- e.stopPropagation();
1306
- onClick();
1307
- });
1308
- btn.addEventListener("mouseover", () => {
1309
- btn.style.transform = "scale(1.02)";
1310
- if (!isActive && !isDestructive) {
1311
- btn.style.backgroundColor = aeroTheme.colors.neutral[100];
1312
- }
1313
- });
1314
- btn.addEventListener("mouseout", () => {
1315
- btn.style.transform = "scale(1)";
1316
- btn.style.backgroundColor = isActive
1317
- ? "rgba(16, 185, 129, 0.15)"
1318
- : isDestructive
1319
- ? "rgba(239, 68, 68, 0.1)"
1320
- : "transparent";
1321
- });
1322
- return btn;
1323
- };
1324
- // Reset
1325
- const resetIcon = Icons.Redo("md");
1326
- resetIcon.style.width = "18px";
1327
- resetIcon.style.height = "18px";
1328
- if (!client.isPublishedChatSession || requestPublicationGrant) {
1329
- settingsRow.appendChild(createOption(resetIcon, "Reset", handleReset));
1330
- }
1331
- // Video - only show if connection type is video
1332
- const connectionType = client.connectionType;
1333
- if (connectionType === "video" && showVideo) {
1334
- const videoIcon = isVideoVisible
1335
- ? Icons.Video("md")
1336
- : Icons.VideoOff("md");
1337
- videoIcon.style.width = "18px";
1338
- videoIcon.style.height = "18px";
1339
- const videoBtn = createOption(videoIcon, "Video", handleToggleVideo, isVideoVisible);
1340
- videoBtn.id = "convai-settings-video-btn";
1341
- refs.settingsVideoBtn = videoBtn;
1342
- settingsRow.appendChild(videoBtn);
1343
- }
1344
- // Screen Share - only show if connection type is video
1345
- if (connectionType === "video" && showScreenShare) {
1346
- const isSharing = client.screenShareControls.isScreenShareActive;
1347
- const shareIcon = isSharing
1348
- ? Icons.StopScreenShare("md")
1349
- : Icons.ScreenShare("md");
1350
- shareIcon.style.width = "18px";
1351
- shareIcon.style.height = "18px";
1352
- const shareBtn = createOption(shareIcon, "Screen", handleToggleScreenShare, isSharing);
1353
- shareBtn.id = "convai-settings-share-btn";
1354
- refs.settingsShareBtn = shareBtn;
1355
- settingsRow.appendChild(shareBtn);
1356
- }
1357
- // Disconnect
1358
- const disconnectIcon = document.createElement("span");
1359
- disconnectIcon.innerHTML = "⏻";
1360
- disconnectIcon.style.fontSize = "18px";
1361
- if (!client.isPublishedChatSession || requestPublicationGrant) {
1362
- settingsRow.appendChild(createOption(disconnectIcon, "Disconnect", handleDisconnect, false, true));
1363
- }
1364
- tray.appendChild(settingsRow);
1365
- return tray;
1366
- };
1367
- // Update settings tray content to reflect current connection state
1368
- const updateSettingsTray = () => {
1369
- const settingsRow = settingsTray.querySelector("div");
1370
- if (!settingsRow)
1371
- return;
1372
- // Clear existing content
1373
- settingsRow.innerHTML = "";
1374
- const createOption = (icon, label, onClick, isActive = false, isDestructive = false) => {
1375
- const btn = document.createElement("div");
1376
- btn.style.cssText = `
1377
- display: flex;
1378
- flex-direction: column;
1379
- align-items: center;
1380
- gap: 4px;
1381
- padding: 8px 12px;
1382
- cursor: pointer;
1383
- border-radius: ${aeroTheme.borderRadius.md};
1384
- background-color: ${isActive
1385
- ? "rgba(16, 185, 129, 0.15)"
1386
- : isDestructive
1387
- ? "rgba(239, 68, 68, 0.1)"
1388
- : "transparent"};
1389
- color: ${isActive
1390
- ? "#10b981"
1391
- : isDestructive
1392
- ? "#ef4444"
1393
- : `var(--convai-panel-fg, ${aeroTheme.colors.text.primary})`};
1394
- transition: ${aeroTheme.transitions.fast};
1395
- min-width: 50px;
1396
- `;
1397
- // Icon container
1398
- const iconContainer = document.createElement("div");
1399
- iconContainer.appendChild(icon);
1400
- btn.appendChild(iconContainer);
1401
- const span = document.createElement("span");
1402
- span.textContent = label;
1403
- span.style.cssText = `
1404
- font-size: 10px;
1405
- font-weight: 500;
1406
- `;
1407
- btn.appendChild(span);
1408
- btn.addEventListener("click", (e) => {
1409
- e.stopPropagation();
1410
- onClick();
1411
- });
1412
- btn.addEventListener("mouseover", () => {
1413
- btn.style.transform = "scale(1.02)";
1414
- if (!isActive && !isDestructive) {
1415
- btn.style.backgroundColor = aeroTheme.colors.neutral[100];
1416
- }
1417
- });
1418
- btn.addEventListener("mouseout", () => {
1419
- btn.style.transform = "scale(1)";
1420
- btn.style.backgroundColor = isActive
1421
- ? "rgba(16, 185, 129, 0.15)"
1422
- : isDestructive
1423
- ? "rgba(239, 68, 68, 0.1)"
1424
- : "transparent";
1425
- });
1426
- return btn;
1427
- };
1428
- // Reset
1429
- const resetIcon = Icons.Redo("md");
1430
- resetIcon.style.width = "18px";
1431
- resetIcon.style.height = "18px";
1432
- if (!client.isPublishedChatSession || requestPublicationGrant) {
1433
- settingsRow.appendChild(createOption(resetIcon, "Reset", handleReset));
1434
- }
1435
- // Video - Always show if showVideo is true and connection type is video
1436
- const connectionType = client.connectionType;
1437
- if (connectionType === "video" && showVideo) {
1438
- const videoIcon = isVideoVisible
1439
- ? Icons.Video("md")
1440
- : Icons.VideoOff("md");
1441
- videoIcon.style.width = "18px";
1442
- videoIcon.style.height = "18px";
1443
- const videoBtn = createOption(videoIcon, "Video", handleToggleVideo, isVideoVisible);
1444
- videoBtn.id = "convai-settings-video-btn";
1445
- refs.settingsVideoBtn = videoBtn;
1446
- settingsRow.appendChild(videoBtn);
1447
- }
1448
- // Screen Share - Always show if showScreenShare is true and connection type is video
1449
- if (connectionType === "video" && showScreenShare) {
1450
- const isSharing = client.screenShareControls.isScreenShareActive;
1451
- const shareIcon = isSharing
1452
- ? Icons.StopScreenShare("md")
1453
- : Icons.ScreenShare("md");
1454
- shareIcon.style.width = "18px";
1455
- shareIcon.style.height = "18px";
1456
- const shareBtn = createOption(shareIcon, "Screen", handleToggleScreenShare, isSharing);
1457
- shareBtn.id = "convai-settings-share-btn";
1458
- refs.settingsShareBtn = shareBtn;
1459
- settingsRow.appendChild(shareBtn);
1460
- }
1461
- // Disconnect
1462
- const disconnectIcon = document.createElement("span");
1463
- disconnectIcon.innerHTML = "⏻";
1464
- disconnectIcon.style.fontSize = "18px";
1465
- if (!client.isPublishedChatSession || requestPublicationGrant) {
1466
- settingsRow.appendChild(createOption(disconnectIcon, "Disconnect", handleDisconnect, false, true));
1467
- }
1468
- };
1469
- // Create floating video - Matches React FloatingVideo component
1470
- const createFloatingVideo = () => {
1471
- const container = document.createElement("div");
1472
- container.id = "floating-video-container";
1473
- // NOTE on z-index: deliberately NOT themable. `--convai-z-index` drives the
1474
- // widget root only. Both elements are `position: fixed` and this one is
1475
- // appended *before* the widget root, so on a tie the widget paints on top:
1476
- // a host raising the token to clear their nav bar would hide the user's own
1477
- // camera preview behind the panel. Video/screen share are also out of scope
1478
- // for the embed, which is chat-only.
1479
- container.style.cssText = `
1480
- position: fixed;
1481
- left: 20px;
1482
- top: 20px;
1483
- z-index: 10000;
1484
- width: 320px;
1485
- border-radius: ${aeroTheme.borderRadius.lg};
1486
- overflow: hidden;
1487
- box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
1488
- cursor: grab;
1489
- display: none;
1490
- transition: opacity 0.4s cubic-bezier(0.4, 0, 0.2, 1), transform 0.4s cubic-bezier(0.4, 0, 0.2, 1);
1491
- `;
1492
- const wrapper = document.createElement("div");
1493
- wrapper.style.cssText = `
1494
- background: rgba(15, 23, 42, 0.95);
1495
- backdrop-filter: blur(20px);
1496
- border: 1px solid ${aeroTheme.colors.neutral[700]};
1497
- border-radius: ${aeroTheme.borderRadius.lg};
1498
- overflow: hidden;
1499
- `;
1500
- // Header
1501
- const header = document.createElement("div");
1502
- header.style.cssText = `
1503
- display: flex;
1504
- align-items: center;
1505
- justify-content: space-between;
1506
- padding: 8px 12px;
1507
- background: rgba(0, 0, 0, 0.3);
1508
- border-bottom: 1px solid ${aeroTheme.colors.neutral[700]};
1509
- `;
1510
- const headerLeft = document.createElement("div");
1511
- headerLeft.style.cssText = `
1512
- display: flex;
1513
- align-items: center;
1514
- gap: 8px;
1515
- color: ${aeroTheme.colors.neutral[300]};
1516
- font-size: 12px;
1517
- font-weight: 500;
1518
- `;
1519
- const dragIcon = Icons.DragIndicator("sm");
1520
- dragIcon.style.width = "16px";
1521
- dragIcon.style.height = "16px";
1522
- headerLeft.appendChild(dragIcon);
1523
- const label = document.createElement("span");
1524
- label.textContent = "Your Camera";
1525
- headerLeft.appendChild(label);
1526
- const closeButton = document.createElement("button");
1527
- closeButton.innerHTML = "";
1528
- const closeIcon = Icons.Close("md");
1529
- closeIcon.style.width = "20px";
1530
- closeIcon.style.height = "20px";
1531
- closeButton.appendChild(closeIcon);
1532
- closeButton.style.cssText = `
1533
- background: transparent;
1534
- border: none;
1535
- color: ${aeroTheme.colors.neutral[400]};
1536
- cursor: pointer;
1537
- display: flex;
1538
- align-items: center;
1539
- justify-content: center;
1540
- padding: 4px;
1541
- transition: transform 0.1s ease-out;
1542
- `;
1543
- closeButton.addEventListener("click", (e) => {
1544
- e.stopPropagation();
1545
- client.videoControls.disableVideo();
1546
- });
1547
- closeButton.addEventListener("mouseenter", () => {
1548
- closeButton.style.transform = "scale(1.1)";
1549
- });
1550
- closeButton.addEventListener("mouseleave", () => {
1551
- closeButton.style.transform = "scale(1)";
1552
- });
1553
- header.appendChild(headerLeft);
1554
- header.appendChild(closeButton);
1555
- // Video Container
1556
- const videoContainer = document.createElement("div");
1557
- videoContainer.style.cssText = `
1558
- position: relative;
1559
- width: 100%;
1560
- padding-bottom: 75%;
1561
- background: #000;
1562
- `;
1563
- const videoWrapper = document.createElement("div");
1564
- videoWrapper.id = "floating-video-wrapper";
1565
- videoWrapper.style.cssText = `
1566
- position: absolute;
1567
- top: 0;
1568
- left: 0;
1569
- width: 100%;
1570
- height: 100%;
1571
- `;
1572
- const videoElement = document.createElement("video");
1573
- videoElement.id = "floating-video-element";
1574
- videoElement.autoplay = true;
1575
- videoElement.playsInline = true;
1576
- videoElement.muted = true;
1577
- videoElement.style.cssText = `
1578
- width: 100%;
1579
- height: 100%;
1580
- object-fit: cover;
1581
- transform: scaleX(-1);
1582
- `;
1583
- // Camera off placeholder
1584
- const cameraOffPlaceholder = document.createElement("div");
1585
- cameraOffPlaceholder.id = "camera-off-placeholder";
1586
- cameraOffPlaceholder.style.cssText = `
1587
- width: 100%;
1588
- height: 100%;
1589
- display: flex;
1590
- flex-direction: column;
1591
- align-items: center;
1592
- justify-content: center;
1593
- color: ${aeroTheme.colors.neutral[400]};
1594
- gap: 12px;
1595
- background: #000;
1596
- `;
1597
- const cameraOffIcon = Icons.VideoOff("lg");
1598
- cameraOffIcon.style.width = "48px";
1599
- cameraOffIcon.style.height = "48px";
1600
- cameraOffPlaceholder.appendChild(cameraOffIcon);
1601
- const cameraOffText = document.createElement("span");
1602
- cameraOffText.textContent = "Camera is off";
1603
- cameraOffText.style.cssText = `
1604
- font-size: 14px;
1605
- text-align: center;
1606
- `;
1607
- cameraOffPlaceholder.appendChild(cameraOffText);
1608
- videoWrapper.appendChild(videoElement);
1609
- videoWrapper.appendChild(cameraOffPlaceholder);
1610
- videoContainer.appendChild(videoWrapper);
1611
- wrapper.appendChild(header);
1612
- wrapper.appendChild(videoContainer);
1613
- container.appendChild(wrapper);
1614
- // Add drag functionality
1615
- let isDragging = false;
1616
- let startX = 0;
1617
- let startY = 0;
1618
- let startLeft = 20;
1619
- let startTop = 20;
1620
- const handleMouseDown = (e) => {
1621
- if (e.target.closest("button"))
1622
- return;
1623
- isDragging = true;
1624
- startX = e.clientX;
1625
- startY = e.clientY;
1626
- const style = window.getComputedStyle(container);
1627
- startLeft = parseInt(style.left);
1628
- startTop = parseInt(style.top);
1629
- container.style.cursor = "grabbing";
1630
- e.preventDefault();
1631
- };
1632
- const handleMouseMove = (e) => {
1633
- if (!isDragging)
1634
- return;
1635
- const deltaX = e.clientX - startX;
1636
- const deltaY = e.clientY - startY;
1637
- const newLeft = startLeft + deltaX;
1638
- const newTop = startTop + deltaY;
1639
- // Keep within bounds
1640
- const maxX = window.innerWidth - 320;
1641
- const maxY = window.innerHeight - 240;
1642
- const boundedLeft = Math.max(0, Math.min(newLeft, maxX));
1643
- const boundedTop = Math.max(0, Math.min(newTop, maxY));
1644
- container.style.left = `${boundedLeft}px`;
1645
- container.style.top = `${boundedTop}px`;
1646
- };
1647
- const handleMouseUp = () => {
1648
- if (isDragging) {
1649
- isDragging = false;
1650
- container.style.cursor = "grab";
1651
- }
1652
- };
1653
- container.addEventListener("mousedown", handleMouseDown);
1654
- document.addEventListener("mousemove", handleMouseMove);
1655
- document.addEventListener("mouseup", handleMouseUp);
1656
- return container;
1657
- };
1658
- // Event handlers
1659
- const handleToggle = async () => {
1660
- if (isDestroyed)
1661
- return;
1662
- if (isOpen || pendingOpen) {
1663
- // Already open, or an open is already in flight: nothing to do. The
1664
- // `pendingOpen` half is what keeps a repeat call from falling through
1665
- // to the `isConnecting` branch below and opening the panel *before* the
1666
- // connect it is waiting on has finished.
1667
- return;
1668
- }
1669
- // Connect on first click if not already connected/connecting
1670
- if (!client.state.isConnected && !client.state.isConnecting) {
1671
- pendingOpen = true;
1672
- try {
1673
- if (requestPublicationGrant || client.isPublishedChatSession) {
1674
- if (!requestPublicationGrant) {
1675
- throw new Error("Published chat widgets require requestPublicationGrant to start a new session");
1676
- }
1677
- if (!client.connectWithPublicationGrant) {
1678
- throw new Error("This Convai client does not support published chat connections");
1679
- }
1680
- const launchToken = await requestPublicationGrant();
1681
- // destroy() can run while the grant endpoint is in flight. A one-time
1682
- // grant must not start a session for a widget which no longer exists.
1683
- if (isDestroyed) {
1684
- return;
1685
- }
1686
- await client.connectWithPublicationGrant(launchToken, freshPublicationGrantOptions(publishedChatConnectOptions));
1687
- }
1688
- else if (hasConnectedBefore && typeof client.reconnect === "function") {
1689
- await client.reconnect();
1690
- }
1691
- else {
1692
- await client.connect();
1693
- }
1694
- if (isDestroyed) {
1695
- // destroy() can also run after the grant is exchanged but before
1696
- // Core or LiveKit finishes connecting. Disconnect that late session
1697
- // instead of leaving an invisible room alive.
1698
- await client.disconnect();
1699
- return;
1700
- }
1701
- // Re-checked *after* the await: a close()/toggle()/launcher click
1702
- // during the connect clears the flag, and that cancellation has to
1703
- // win. The client stays connected either way -- only the panel is
1704
- // held back -- so a later open() takes the already-connected branch
1705
- // and opens instantly.
1706
- if (isDestroyed) {
1707
- // destroy() can also run after the grant is exchanged but before
1708
- // Core or LiveKit finishes connecting. Disconnect that late session
1709
- // instead of leaving an invisible room alive.
1710
- await client.disconnect();
1711
- return;
1712
- }
1713
- if (!pendingOpen)
1714
- return;
1715
- setIsOpen(true);
1716
- }
1717
- catch (error) {
1718
- if (!isDestroyed) {
1719
- console.error("Failed to connect:", error);
1720
- }
1721
- }
1722
- finally {
1723
- pendingOpen = false;
1724
- }
1725
- }
1726
- else {
1727
- // Just toggle open/close if already connected
1728
- setIsOpen(!isOpen);
1729
- }
1730
- };
1731
- /** A launcher click while an open is pending means "cancel", same as `toggle()`. */
1732
- const handleLauncherClick = () => {
1733
- if (pendingOpen) {
1734
- handleClose();
1735
- return;
1736
- }
1737
- void handleToggle();
1738
- };
1739
- const handleClose = () => {
1740
- // Cancels an in-flight open as well as closing an open panel; see
1741
- // `pendingOpen`. `setIsOpen(false)` on an already-closed widget just
1742
- // re-applies the collapsed styles, so this is safe in both cases.
1743
- pendingOpen = false;
1744
- setIsOpen(false);
1745
- };
1746
- // Published sessions must wait for Core's bot-ready handshake. A normal
1747
- // authenticated text session still gets the text-only UI, but can send as
1748
- // soon as it connects.
1749
- const requiresBotReadyForText = () => Boolean(requestPublicationGrant) || Boolean(client.isPublishedChatSession);
1750
- const isTextInputReady = () => client.state.isConnected &&
1751
- (!requiresBotReadyForText() || client.isBotReady);
1752
- const handleSend = () => {
1753
- if (inputValue.trim() && isTextInputReady()) {
1754
- client.sendUserTextMessage(inputValue);
1755
- inputValue = "";
1756
- inputElement.value = "";
1757
- updateSendButton();
1758
- }
1759
- };
1760
- // Microphone toggle removed - only controlled via voice mode now
1761
- const handleToggleMute = () => {
1762
- isMuted = !isMuted;
1763
- // The client owns this now: it covers the WebSocket transport, which this
1764
- // handler never did, and it holds the state so a reconnect or a joining
1765
- // roster member does not come back audible.
1766
- client.setCharacterMuted(isMuted);
1767
- updateHeader();
1768
- };
1769
- const handleReset = async () => {
1770
- setIsSettingsOpen(false);
1771
- try {
1772
- await client.disconnect();
1773
- client.resetSession();
1774
- isMuted = false;
1775
- isVoiceMode = false;
1776
- hasEnteredDefaultVoiceMode = false;
1777
- updateHeader();
1778
- await updateVoiceMode();
1779
- updateSendButton();
1780
- }
1781
- catch (error) {
1782
- console.error("Failed to reset:", error);
1783
- }
1784
- };
1785
- const handleDisconnect = async () => {
1786
- setIsSettingsOpen(false);
1787
- await client.disconnect();
1788
- isMuted = false;
1789
- isVoiceMode = false;
1790
- hasEnteredDefaultVoiceMode = false;
1791
- updateHeader();
1792
- // Not awaited: this function has no try/catch of its own and is wired
1793
- // straight to a click, so awaiting would only move a rejection from one
1794
- // unguarded place to another. See the note on `handleDisconnect`'s own
1795
- // `await client.disconnect()` in the fix report.
1796
- applyVoiceMode();
1797
- updateSendButton();
1798
- };
1799
- const handleToggleVideo = async () => {
1800
- if (client.connectionType !== "video")
1801
- return;
1802
- try {
1803
- if (isVideoVisible) {
1804
- await client.videoControls.disableVideo();
1805
- }
1806
- else {
1807
- await client.videoControls.enableVideo();
1808
- }
1809
- // State will be updated via event listener below
1810
- }
1811
- catch (e) {
1812
- console.error("Failed to toggle video:", e);
1813
- }
1814
- };
1815
- const handleToggleScreenShare = async () => {
1816
- try {
1817
- await client.screenShareControls.toggleScreenShare();
1818
- // State will be updated via event listener above
1819
- }
1820
- catch (e) {
1821
- console.error("Failed to toggle screen share:", e);
1822
- }
1823
- };
1824
- const handleSettingsToggle = () => {
1825
- // Regenerate settings tray content BEFORE opening to reflect current connection type
1826
- if (!isSettingsOpen) {
1827
- updateSettingsTray();
1828
- }
1829
- setIsSettingsOpen(!isSettingsOpen);
1830
- };
1831
- // Update functions
1832
- const setIsOpen = async (open) => {
1833
- isOpen = open;
1834
- if (open) {
1835
- morphingContainer.style.width = `${PANEL_W_PX}px`;
1836
- morphingContainer.style.height = `${PANEL_H_PX}px`;
1837
- morphingContainer.style.borderRadius = `var(--convai-radius, ${aeroTheme.borderRadius.xl})`;
1838
- morphingContainer.style.cursor = "default";
1839
- // The open panel is a *different* glass treatment from the launcher
1840
- // bubble, matching the React widget: near-opaque and saturated, so the
1841
- // host page does not bleed through. At the bubble's 0.8 alpha a dark
1842
- // host page shows through the panel and reads as grey.
1843
- morphingContainer.style.background =
1844
- "var(--convai-panel-bg, rgba(252, 252, 253, 0.95))";
1845
- morphingContainer.style.backdropFilter = "blur(20px) saturate(180%)";
1846
- buttonContent.style.opacity = "0";
1847
- buttonContent.style.transform = "scale(0.8)";
1848
- buttonContent.style.pointerEvents = "none";
1849
- chatContent.style.opacity = "1";
1850
- chatContent.style.transform = "scale(1)";
1851
- chatContent.style.pointerEvents = "auto";
1852
- // Auto-enter voice mode if defaultVoiceMode is true and not already entered
1853
- if (defaultVoiceMode &&
1854
- !requestPublicationGrant &&
1855
- client.connectionType !== "text" &&
1856
- !hasEnteredDefaultVoiceMode &&
1857
- client.state.isConnected) {
1858
- setTimeout(async () => {
1859
- try {
1860
- await client.audioControls.unmuteAudio();
1861
- isVoiceMode = true;
1862
- hasEnteredDefaultVoiceMode = true;
1863
- await updateVoiceMode();
1864
- }
1865
- catch (error) {
1866
- reportMicFailure(client, "Failed to enter voice mode on open:", error);
1867
- }
1868
- }, 100);
1869
- }
1870
- }
1871
- else {
1872
- morphingContainer.style.width = "var(--convai-launcher-size, 64px)";
1873
- morphingContainer.style.height = "var(--convai-launcher-size, 64px)";
1874
- // Literal, not `--convai-radius` — see the creation site: that token is
1875
- // the *panel* radius, and reusing it here would squircle the launcher.
1876
- morphingContainer.style.borderRadius = "50%";
1877
- morphingContainer.style.cursor = "pointer";
1878
- // Back to the launcher bubble's lighter glass — see the open branch.
1879
- morphingContainer.style.background = `var(--convai-panel-bg, ${aeroTheme.colors.glass.backdrop})`;
1880
- morphingContainer.style.backdropFilter = aeroTheme.glass.backdrop;
1881
- buttonContent.style.opacity = "1";
1882
- buttonContent.style.transform = "scale(1)";
1883
- buttonContent.style.pointerEvents = "auto";
1884
- chatContent.style.opacity = "0";
1885
- chatContent.style.transform = "scale(0.8)";
1886
- chatContent.style.pointerEvents = "none";
1887
- }
1888
- };
1889
- const setIsSettingsOpen = (open) => {
1890
- isSettingsOpen = open;
1891
- settingsTray.style.display = open ? "flex" : "none";
1892
- };
1893
- const updateSendButton = () => {
1894
- const sendButton = refs.sendButton;
1895
- if (!sendButton)
1896
- return;
1897
- // Clear previous content
1898
- sendButton.innerHTML = "";
1899
- // A published session must wait for Core's bot-ready handshake before
1900
- // accepting text. Preserve the established interactive-widget behavior
1901
- // for authenticated voice/video sessions.
1902
- const isPublishedTextChat = requiresBotReadyForText();
1903
- const textInputReady = isTextInputReady();
1904
- inputElement.disabled = isPublishedTextChat && !textInputReady;
1905
- if (inputValue.length > 0 ||
1906
- requestPublicationGrant ||
1907
- client.connectionType === "text") {
1908
- // Show Send Button
1909
- sendButton.appendChild(Icons.Send("md"));
1910
- sendButton.style.background = `var(--convai-accent, ${aeroTheme.colors.text.primary})`;
1911
- // The label sits *on* the accent fill, so it must follow the panel
1912
- // surface colour rather than stay a hardcoded "white" -- a host setting
1913
- // a pale --convai-accent would otherwise get white-on-white. `white` is
1914
- // byte-identical to the fallback --convai-panel-bg already carries at
1915
- // its three other sites, so the default rendering is unchanged.
1916
- // Pairing requirement for hosts: --convai-accent and --convai-panel-bg
1917
- // must contrast with each other, since this is the one place they meet.
1918
- sendButton.style.color = "var(--convai-panel-bg, white)";
1919
- sendButton.style.border = "none";
1920
- sendButton.disabled =
1921
- isPublishedTextChat && (inputValue.length === 0 || !textInputReady);
1922
- if (isPublishedTextChat) {
1923
- sendButton.style.opacity =
1924
- inputValue.length > 0 && textInputReady ? "1" : "0.5";
1925
- sendButton.title = textInputReady
1926
- ? inputValue.length > 0
1927
- ? "Send"
1928
- : "Type a message"
1929
- : "Waiting for character";
1930
- }
1931
- else {
1932
- sendButton.title = "Send";
1933
- }
1934
- }
1935
- else {
1936
- // Show Voice Mode Toggle
1937
- sendButton.appendChild(Icons.Waveform("md"));
1938
- sendButton.style.background = "transparent";
1939
- sendButton.style.color = `var(--convai-panel-fg, ${aeroTheme.colors.text.primary})`;
1940
- sendButton.style.border = `1px solid ${aeroTheme.colors.neutral[300]}`;
1941
- sendButton.style.opacity = "1";
1942
- sendButton.disabled = false;
1943
- sendButton.title = "Voice Mode";
1944
- }
1945
- };
1946
- const updateVideoTrack = () => {
1947
- if (!floatingVideo || !client.room || !client.room.localParticipant)
1948
- return;
1949
- const videoEl = floatingVideo.querySelector("#floating-video-element");
1950
- const placeholder = floatingVideo.querySelector("#camera-off-placeholder");
1951
- if (!videoEl || !placeholder)
1952
- return;
1953
- if (isVideoVisible && !isVoiceMode) {
1954
- const tracks = Array.from(client.room.localParticipant.videoTrackPublications.values());
1955
- const videoPub = tracks.find((t) => t.kind === "video");
1956
- if (videoPub && videoPub.track) {
1957
- videoPub.track.attach(videoEl);
1958
- videoEl.style.display = "block";
1959
- placeholder.style.display = "none";
1960
- }
1961
- else {
1962
- videoEl.style.display = "none";
1963
- placeholder.style.display = "flex";
1964
- }
1965
- }
1966
- else {
1967
- videoEl.style.display = "none";
1968
- placeholder.style.display = "flex";
1969
- }
1970
- };
1971
- const updateVoiceMode = async () => {
1972
- const standardFooter = refs.footerStandard;
1973
- const voiceExitBtn = refs.voiceExitBtn;
1974
- if (isVoiceMode) {
1975
- // Show Voice Overlay
1976
- if (voiceModeOverlay)
1977
- voiceModeOverlay.style.display = "flex";
1978
- if (messageListElement)
1979
- messageListElement.style.display = "none";
1980
- if (floatingVideo)
1981
- floatingVideo.style.display = "none";
1982
- // Footer: Show Exit Button, Hide Standard
1983
- if (standardFooter)
1984
- standardFooter.style.display = "none";
1985
- if (voiceExitBtn)
1986
- voiceExitBtn.style.display = "flex";
1987
- if (footerElement)
1988
- footerElement.style.justifyContent = "center";
1989
- // Update header to show VOICE badge
1990
- updateHeader();
1991
- // Reset animation state for voice mode
1992
- startTime = Date.now();
1993
- // Start Audio Analysis
1994
- startAudioAnalysis();
1995
- }
1996
- else {
1997
- // Ensure microphone is muted when not in voice mode.
1998
- //
1999
- // This await is the only one in this function that can reject, and
2000
- // everything below it -- hiding the overlay, restoring the standard
2001
- // footer, updating the header, stopping the analyser -- is the only
2002
- // route out of the voice UI. So a failed mute must never short-circuit
2003
- // it: report it and carry on tearing the overlay down. (LiveKit's
2004
- // setMicrophoneEnabled(false) rethrows on a dropped room, which is
2005
- // exactly when the user is most likely to be hitting exit.)
2006
- if (!client.audioControls.isAudioMuted) {
2007
- try {
2008
- await client.audioControls.muteAudio();
2009
- }
2010
- catch (error) {
2011
- reportMicFailure(client, "Failed to mute microphone:", error);
2012
- }
2013
- }
2014
- // Hide Overlay
2015
- if (voiceModeOverlay)
2016
- voiceModeOverlay.style.display = "none";
2017
- // Show Video or Message List
2018
- if (isVideoVisible) {
2019
- if (messageListElement)
2020
- messageListElement.style.display = "none";
2021
- if (floatingVideo)
2022
- floatingVideo.style.display = "block";
2023
- updateVideoTrack();
2024
- }
2025
- else {
2026
- if (messageListElement)
2027
- messageListElement.style.display = "flex";
2028
- if (floatingVideo)
2029
- floatingVideo.style.display = "none";
2030
- }
2031
- // Footer: Show Standard, Hide Exit
2032
- if (standardFooter)
2033
- standardFooter.style.display = "flex";
2034
- if (voiceExitBtn)
2035
- voiceExitBtn.style.display = "none";
2036
- if (footerElement)
2037
- footerElement.style.justifyContent = "flex-start";
2038
- // Update header to hide VOICE badge
2039
- updateHeader();
2040
- // Stop Audio Analysis
2041
- stopAudioAnalysis();
2042
- }
2043
- };
2044
- /**
2045
- * Fire-and-forget `updateVoiceMode()` for the call sites that are
2046
- * synchronous (DOM listeners, the constructor tail) and therefore have no
2047
- * caller to catch anything it rejects with.
2048
- *
2049
- * `updateVoiceMode()` is `async`, so a bare call there would put a floating
2050
- * promise on the host page. Its one rejecting await is now guarded
2051
- * internally, which makes this belt-and-braces -- but it is the guarantee
2052
- * that keeps a future await added inside `updateVoiceMode()` from silently
2053
- * reintroducing the unhandled rejection this replaces. Routed through
2054
- * `reportMicFailure` so a failure is observable on the client's `error`
2055
- * channel rather than console-only.
2056
- */
2057
- const applyVoiceMode = () => {
2058
- void updateVoiceMode().catch((error) => {
2059
- reportMicFailure(client, "Failed to apply voice mode:", error);
2060
- });
2061
- };
2062
- // Microphone button removed - only controlled via voice mode now
2063
- // The bubble renderer. Everything visual comes from utils/linkPresentation
2064
- // so this and the React MarkdownRenderer cannot drift; this only maps
2065
- // tokenizer nodes onto DOM. `media` gates cards and chips: bot bubbles get
2066
- // them, the user's own bubble keeps anchors only, so a pasted URL never
2067
- // pulls remote media into the transcript.
2068
- const renderMarkdown = (text, container, { media = true } = {}) => {
2069
- if (!text)
2070
- return;
2071
- // Handle both actual newlines and literal "\n" sequences.
2072
- const lines = text.replace(/\\n/g, "\n").split("\n");
2073
- // Cards drawn so far in this message, against MAX_CARDS_PER_MESSAGE.
2074
- const budget = { cards: 0 };
2075
- const make = (tag, part, ...styles) => {
2076
- const node = document.createElement(tag);
2077
- node.setAttribute("part", part);
2078
- node.style.cssText = toCssText(Object.assign({}, ...styles));
2079
- return node;
2080
- };
2081
- // Inline styles cannot express :focus-visible, so the ring is toggled by hand.
2082
- const focusRing = (node) => {
2083
- const base = node.style.cssText;
2084
- node.addEventListener("focus", () => {
2085
- if (node.matches(":focus-visible"))
2086
- node.style.cssText = `${base} ${toCssText(S.linkFocus)}`;
2087
- });
2088
- node.addEventListener("blur", () => {
2089
- node.style.cssText = base;
2090
- });
2091
- };
2092
- const anchor = (href, kind, label) => {
2093
- const a = make("a", "message-link", S.link);
2094
- a.href = href;
2095
- a.target = "_blank";
2096
- a.rel = "noopener noreferrer";
2097
- // A bare URL is its own label and may be elided for display; the title
2098
- // compares against what is shown so the full target is one hover away.
2099
- const display = label === href ? compactUrl(label) : label;
2100
- a.textContent = display;
2101
- const title = hoverTitle(kind, href, display);
2102
- if (title)
2103
- a.title = title;
2104
- if (kind === "ftp") {
2105
- const badge = make("span", "message-link-badge", S.badge);
2106
- badge.textContent = "FTP";
2107
- a.appendChild(badge);
2108
- }
2109
- focusRing(a);
2110
- return a;
2111
- };
2112
- const contactChip = (href, kind) => {
2113
- const a = make("a", "message-contact", S.contact);
2114
- a.href = href;
2115
- a.title = hoverTitle(kind, href, href);
2116
- const g = make("span", "message-contact-glyph", S.contactGlyph);
2117
- g.innerHTML = glyph(kind);
2118
- const t = document.createElement("span");
2119
- t.textContent = contactLabel(href);
2120
- a.append(g, t);
2121
- focusRing(a);
2122
- return a;
2123
- };
2124
- const documentCard = (href) => {
2125
- let host = "";
2126
- try {
2127
- host = new URL(href).host;
2128
- }
2129
- catch {
2130
- /* keep empty */
2131
- }
2132
- const a = make("a", "message-file-card", S.fileCard);
2133
- a.href = href;
2134
- a.target = "_blank";
2135
- a.rel = "noopener noreferrer";
2136
- a.title = href;
2137
- const icon = make("span", "message-file-icon", S.fileIcon);
2138
- icon.textContent = documentBadge(href);
2139
- const body = document.createElement("span");
2140
- body.style.cssText = toCssText(S.fileBody);
2141
- const name = make("span", "message-file-name", S.fileName);
2142
- name.textContent = fileNameOf(href);
2143
- const meta = make("span", "message-file-meta", S.fileMeta);
2144
- meta.textContent = `${host} · Opens in a new tab`;
2145
- body.append(name, meta);
2146
- a.append(icon, body);
2147
- focusRing(a);
2148
- return a;
2149
- };
2150
- /**
2151
- * Open Graph card under a plain web link. A comment node holds the place
2152
- * until the host's resolver settles; it is replaced only when the result
2153
- * has a title or an image, so nothing flashes for the many links that
2154
- * resolve to nothing card-worthy. Resolver text becomes text nodes only.
2155
- */
2156
- const siteCard = (href) => {
2157
- const resolver = options.linkPreviewResolver;
2158
- const slot = document.createComment("site-card");
2159
- if (!resolver)
2160
- return slot;
2161
- resolveLinkPreviewCached(resolver, href).then((meta) => {
2162
- if (!isCardWorthy(meta) || !slot.parentNode)
2163
- return;
2164
- const a = make("a", "message-site-card", S.siteCard);
2165
- a.href = href;
2166
- a.target = "_blank";
2167
- a.rel = "noopener noreferrer";
2168
- const header = document.createElement("span");
2169
- header.style.cssText = toCssText(S.siteHeader);
2170
- const favicon = faviconFor(meta, href);
2171
- if (favicon) {
2172
- const icon = make("img", "message-site-favicon", S.siteFavicon);
2173
- icon.src = favicon;
2174
- icon.alt = "";
2175
- icon.addEventListener("error", () => icon.remove());
2176
- header.appendChild(icon);
2177
- }
2178
- const name = make("span", "message-site-name", S.siteName);
2179
- name.textContent = siteNameFor(meta, href);
2180
- header.appendChild(name);
2181
- a.appendChild(header);
2182
- if (meta.title) {
2183
- const t = make("span", "message-site-title", S.siteTitle);
2184
- t.textContent = meta.title;
2185
- a.appendChild(t);
2186
- }
2187
- if (meta.description) {
2188
- const d = make("span", "message-site-description", S.siteDescription);
2189
- d.textContent = meta.description;
2190
- a.appendChild(d);
2191
- }
2192
- if (meta.image) {
2193
- const img = make("img", "message-site-image", S.siteImage);
2194
- img.src = meta.image;
2195
- img.alt = "";
2196
- img.loading = "lazy";
2197
- img.addEventListener("error", () => img.remove());
2198
- a.appendChild(img);
2199
- }
2200
- focusRing(a);
2201
- slot.replaceWith(a);
2202
- });
2203
- return slot;
2204
- };
2205
- const unavailable = (src, insecure) => {
2206
- const dead = make("span", "message-media-unavailable", S.unavailable);
2207
- dead.textContent = `Preview unavailable — ${describeUrl(src)}${insecure ? " (insecure URL)" : ""}`;
2208
- return dead;
2209
- };
2210
- /**
2211
- * Image or video card. The element is created up front so the fetch starts
2212
- * immediately; a skeleton covers it until it decodes. Error, timeout, or an
2213
- * insecure URL collapse the card to one muted line — a character can
2214
- * invent a URL, and an empty player in the transcript reads as a broken
2215
- * widget.
2216
- */
2217
- const mediaPreview = (src, alt, kind) => {
2218
- const frag = document.createDocumentFragment();
2219
- if (isMixedContent(src)) {
2220
- frag.appendChild(unavailable(src, true));
2221
- return frag;
2222
- }
2223
- const card = make("span", "message-media-card", S.card, kind === "image" ? S.cardButton : {});
2224
- const el = kind === "image"
2225
- ? Object.assign(document.createElement("img"), { src, alt, loading: "lazy" })
2226
- : Object.assign(document.createElement("video"), { src, controls: true, preload: "metadata" });
2227
- el.setAttribute("part", "message-media");
2228
- el.style.cssText = toCssText(Object.assign({}, S.media, kind === "video" ? S.videoMedia : {}, { opacity: 0 }));
2229
- const skeleton = make("span", "message-media-skeleton", S.skeleton);
2230
- skeleton.setAttribute("aria-hidden", "true");
2231
- skeleton.dataset.convaiSkeleton = "";
2232
- const caption = make("span", "message-media-caption", S.caption);
2233
- caption.textContent = describeUrl(src);
2234
- const fail = () => {
2235
- clearTimeout(timer);
2236
- card.replaceWith(unavailable(src, false));
2237
- caption.remove();
2238
- };
2239
- const settled = () => {
2240
- clearTimeout(timer);
2241
- el.style.opacity = "1";
2242
- skeleton.remove();
2243
- if (kind === "image") {
2244
- const zoom = make("span", "message-media-zoom", S.zoom);
2245
- zoom.innerHTML = glyph("zoom");
2246
- card.appendChild(zoom);
2247
- }
2248
- };
2249
- const timer = setTimeout(fail, PREVIEW_TIMEOUT_MS);
2250
- el.addEventListener(kind === "image" ? "load" : "loadedmetadata", settled);
2251
- el.addEventListener("error", fail);
2252
- if (kind === "image") {
2253
- card.setAttribute("role", "button");
2254
- card.tabIndex = 0;
2255
- card.setAttribute("aria-label", `Open image: ${fileNameOf(src)}`);
2256
- const open = () => openLightbox({
2257
- src,
2258
- alt,
2259
- caption: describeUrl(src),
2260
- href: src,
2261
- root: styleTarget,
2262
- returnFocusTo: card,
2263
- });
2264
- card.addEventListener("click", open);
2265
- card.addEventListener("keydown", (e) => {
2266
- if (e.key === "Enter" || e.key === " ") {
2267
- e.preventDefault();
2268
- open();
2269
- }
2270
- });
2271
- }
2272
- card.append(el, skeleton);
2273
- frag.append(card, caption);
2274
- return frag;
2275
- };
2276
- const processLine = (line) => {
2277
- const parts = [];
2278
- for (const node of parseInlineMarkdown(line)) {
2279
- switch (node.kind) {
2280
- case "strong": {
2281
- // matches React UserBubble styling
2282
- const strong = document.createElement("strong");
2283
- strong.textContent = node.text;
2284
- strong.style.cssText = `
2285
- font-weight: 600;
2286
- color: var(--convai-panel-fg, ${aeroTheme.colors.text.primary});
2287
- `;
2288
- parts.push(strong);
2289
- break;
2290
- }
2291
- case "em": {
2292
- const em = document.createElement("em");
2293
- em.textContent = node.text;
2294
- em.style.cssText = `font-style: italic;`;
2295
- parts.push(em);
2296
- break;
2297
- }
2298
- case "blocked": {
2299
- // Not an anchor, ever. The label reads as the character wrote it;
2300
- // the target is only revealed on hover.
2301
- const blocked = make("span", "message-link-blocked", S.blocked);
2302
- blocked.textContent = node.label;
2303
- blocked.title = `Link blocked: ${node.href}`;
2304
- parts.push(blocked);
2305
- break;
2306
- }
2307
- case "image": {
2308
- if (media && budget.cards < MAX_CARDS_PER_MESSAGE) {
2309
- budget.cards++;
2310
- parts.push(mediaPreview(node.src, node.alt, "image"));
2311
- }
2312
- else {
2313
- // With previews off (or the budget spent), an image still has to
2314
- // say what it pointed at, so it degrades to a plain anchor.
2315
- parts.push(anchor(node.src, "image", node.alt || node.src));
2316
- }
2317
- break;
2318
- }
2319
- case "link": {
2320
- const kind = linkKindForUrl(node.href);
2321
- if (kind === "email" || kind === "phone" || kind === "sms") {
2322
- parts.push(media ? contactChip(node.href, kind) : anchor(node.href, kind, node.label));
2323
- break;
2324
- }
2325
- parts.push(anchor(node.href, kind, node.label));
2326
- // The budget is spent when the card mounts, not when it resolves,
2327
- // so the cap stays deterministic for a message naming twenty pages.
2328
- const wantsSiteCard = media &&
2329
- kind === "web" &&
2330
- !!options.linkPreviewResolver &&
2331
- budget.cards < MAX_CARDS_PER_MESSAGE;
2332
- if (wantsSiteCard) {
2333
- budget.cards++;
2334
- parts.push(siteCard(node.href));
2335
- break;
2336
- }
2337
- const wantsCard = media &&
2338
- (kind === "image" || kind === "video" || kind === "document") &&
2339
- budget.cards < MAX_CARDS_PER_MESSAGE;
2340
- if (!wantsCard)
2341
- break;
2342
- budget.cards++;
2343
- parts.push(kind === "document" ? documentCard(node.href) : mediaPreview(node.href, node.label, kind));
2344
- break;
2345
- }
2346
- default:
2347
- parts.push(document.createTextNode(node.text));
2348
- }
2349
- }
2350
- return parts;
2351
- };
2352
- lines.forEach((line, lineIndex) => {
2353
- // An empty line is paragraph spacing.
2354
- if (line.trim() === "" && lineIndex > 0) {
2355
- container.appendChild(document.createElement("br"));
2356
- return;
2357
- }
2358
- const processed = processLine(line);
2359
- if (processed.length > 0)
2360
- processed.forEach((p) => container.appendChild(p));
2361
- else
2362
- container.appendChild(document.createTextNode(line));
2363
- if (lineIndex < lines.length - 1)
2364
- container.appendChild(document.createElement("br"));
2365
- });
2366
- };
2367
- const updateMessageList = () => {
2368
- if (!messageListElement)
2369
- return;
2370
- const messages = formatMessages();
2371
- messageListElement.innerHTML = "";
2372
- if (messages.length === 0) {
2373
- const emptyState = document.createElement("div");
2374
- emptyState.style.cssText = `
2375
- display: flex;
2376
- flex-direction: column;
2377
- align-items: center;
2378
- justify-content: center;
2379
- height: 100%;
2380
- color: ${aeroTheme.colors.text.secondary};
2381
- text-align: center;
2382
- padding: 32px;
2383
- `;
2384
- emptyState.innerHTML = `
2385
- <p style="font-weight: 500; margin-bottom: 8px;">Start a conversation</p>
2386
- <p style="font-size: 12px;">Type a message below to begin chatting</p>
2387
- `;
2388
- messageListElement.appendChild(emptyState);
2389
- return;
2390
- }
2391
- messages.forEach((msg) => {
2392
- // MessageWrapper - matches React UserMessageContainer
2393
- const messageWrapper = document.createElement("div");
2394
- messageWrapper.style.cssText = `
2395
- display: flex;
2396
- flex-direction: column;
2397
- max-width: ${msg.isUser ? "70%" : "70%"};
2398
- margin-left: ${msg.isUser ? "auto" : "0"};
2399
- width: 100%;
2400
- isolation: isolate;
2401
- contain: layout style paint;
2402
- `;
2403
- const bubble = document.createElement("div");
2404
- bubble.setAttribute("part", msg.isUser ? "message message-user" : "message message-bot");
2405
- // Add data attribute to identify user messages for debugging/styling
2406
- if (msg.isUser) {
2407
- bubble.setAttribute("data-message-type", "user");
2408
- }
2409
- // Set base styles first - explicitly set background to match React UserBubble exactly
2410
- // CRITICAL: Use the exact same background for both user and bot messages
2411
- const backgroundColor = "rgba(252, 252, 253, 0.95)";
2412
- // NOTE on border-radius: deliberately NOT themable. `--convai-radius` is
2413
- // the open panel's radius; a bubble's asymmetric tail corner is a
2414
- // different geometry (`50%` would make ellipses of these). A dedicated
2415
- // `--convai-bubble-radius` can be added additively later if wanted.
2416
- bubble.style.cssText = `
2417
- padding: 12px;
2418
- border-radius: ${msg.isUser ? "12px 12px 4px 12px" : "12px 12px 12px 4px"};
2419
- background: ${backgroundColor};
2420
- background-color: ${backgroundColor};
2421
- backdrop-filter: blur(20px) saturate(180%);
2422
- border: 1px solid rgba(0, 0, 0, 0.06);
2423
- box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.8) inset, 0 2px 8px rgba(0, 0, 0, 0.08);
2424
- color: var(--convai-panel-fg, ${aeroTheme.colors.text.primary});
2425
- font-family: var(--convai-font, ${aeroTheme.typography.fontFamily.body});
2426
- font-size: 14px;
2427
- line-height: 1.5;
2428
- word-wrap: break-word;
2429
- max-width: 100%;
2430
- display: flex;
2431
- flex-direction: column;
2432
- font-synthesis: none;
2433
- text-rendering: optimizeLegibility;
2434
- -webkit-font-smoothing: antialiased;
2435
- -moz-osx-font-smoothing: grayscale;
2436
- -webkit-text-size-adjust: 100%;
2437
- isolation: isolate;
2438
- contain: layout style paint;
2439
- `;
2440
- // Set background with !important to override any other styles (this is critical)
2441
- bubble.style.setProperty("background", backgroundColor, "important");
2442
- bubble.style.setProperty("background-color", backgroundColor, "important");
2443
- // Header (Logo/Icon + Name) inside bubble - matches React MessageHeader
2444
- if (msg.sender) {
2445
- const header = document.createElement("div");
2446
- header.style.cssText = `
2447
- display: flex;
2448
- align-items: center;
2449
- gap: ${aeroTheme.spacing.xs};
2450
- margin-bottom: ${aeroTheme.spacing.xs};
2451
- isolation: isolate;
2452
- contain: layout style paint;
2453
- `;
2454
- // Logo/Icon - matches React LogoWrapper
2455
- const logoContainer = document.createElement("div");
2456
- logoContainer.style.cssText = `
2457
- width: 16px;
2458
- height: 16px;
2459
- display: flex;
2460
- align-items: center;
2461
- justify-content: center;
2462
- isolation: isolate;
2463
- contain: layout style paint;
2464
- `;
2465
- if (msg.isUser) {
2466
- // User Icon - FaUser from react-icons/fa, matches React exactly
2467
- const userIcon = Icons.User("sm");
2468
- userIcon.style.width = "16px";
2469
- userIcon.style.height = "16px";
2470
- userIcon.style.color = aeroTheme.colors.convai.dark;
2471
- logoContainer.appendChild(userIcon);
2472
- }
2473
- else {
2474
- // Bot Logo - ConvaiLogo sm size with connected state
2475
- const botLogo = Icons.ConvaiLogo("sm", "connected");
2476
- botLogo.style.width = "16px";
2477
- botLogo.style.height = "16px";
2478
- botLogo.style.color = "#10b981";
2479
- logoContainer.appendChild(botLogo);
2480
- }
2481
- // Name Label - matches React UserLabel exactly
2482
- const nameLabel = document.createElement("span");
2483
- nameLabel.textContent = msg.sender === "User" ? "You" : msg.sender;
2484
- nameLabel.style.cssText = `
2485
- font-size: 12px;
2486
- color: ${msg.isUser ? aeroTheme.colors.convai.dark : "#10b981"};
2487
- font-weight: 500;
2488
- font-family: var(--convai-font, ${aeroTheme.typography.fontFamily.body});
2489
- isolation: isolate;
2490
- contain: layout style paint;
2491
- `;
2492
- header.appendChild(logoContainer);
2493
- header.appendChild(nameLabel);
2494
- bubble.appendChild(header);
2495
- }
2496
- // Message Content
2497
- const contentDiv = document.createElement("div");
2498
- contentDiv.style.cssText = `
2499
- white-space: pre-wrap;
2500
- word-wrap: break-word;
2501
- `;
2502
- renderMarkdown(msg.text, contentDiv, { media: !msg.isUser });
2503
- bubble.appendChild(contentDiv);
2504
- messageWrapper.appendChild(bubble);
2505
- // Timestamp - matches React exactly
2506
- if (msg.timestamp) {
2507
- const timestamp = document.createElement("span");
2508
- timestamp.textContent = msg.timestamp;
2509
- timestamp.style.cssText = `
2510
- font-size: 12px;
2511
- color: ${aeroTheme.colors.text.secondary};
2512
- margin-top: 4px;
2513
- align-self: ${msg.isUser ? "flex-end" : "flex-start"};
2514
- font-family: var(--convai-font, ${aeroTheme.typography.fontFamily.body});
2515
- `;
2516
- messageWrapper.appendChild(timestamp);
2517
- }
2518
- messageListElement.appendChild(messageWrapper);
2519
- });
2520
- // Scroll to bottom
2521
- messageListElement.scrollTop = messageListElement.scrollHeight;
2522
- };
2523
- const getBotStatusColor = () => {
2524
- if (!client.state.isConnected) {
2525
- return { color: "#ef4444", label: "Disconnected" };
2526
- }
2527
- if (client.state.isConnecting || !client.isBotReady) {
2528
- return { color: "#f59e0b", label: "Connecting" };
2529
- }
2530
- if (client.state.isListening) {
2531
- return { color: "#3b82f6", label: "Listening" };
2532
- }
2533
- return { color: "#10b981", label: "Connected" };
2534
- };
2535
- const formatMessages = () => {
2536
- const filteredMessages = client.chatMessages.filter((msg) => (msg.type === "user-transcription" ||
2537
- msg.type === "user-llm-text" ||
2538
- msg.type === "bot-llm-text" ||
2539
- msg.type === "bot-output" ||
2540
- msg.type === "bot-emotion") &&
2541
- msg.content &&
2542
- msg.content.trim().length > 0);
2543
- return filteredMessages.map((msg) => ({
2544
- id: msg.id,
2545
- text: msg.content,
2546
- isUser: msg.type.includes("user"),
2547
- timestamp: new Date(msg.timestamp).toLocaleTimeString([], {
2548
- hour: "2-digit",
2549
- minute: "2-digit",
2550
- }),
2551
- sender: msg.type.includes("user") ? "You" : characterName,
2552
- showLogo: msg.type.includes("bot"),
2553
- }));
2554
- };
2555
- // Setup event listeners for client state changes
2556
- const setupClientListeners = () => {
2557
- eventSubscriptions.register((listener) => client.on("stateChange", listener), () => {
2558
- // Published chat (connectionType "text") has no microphone: never let
2559
- // a voice-mode transition leave the panel in a mode it cannot honour.
2560
- if (client.connectionType === "text") {
2561
- if (isVoiceMode) {
2562
- isVoiceMode = false;
2563
- hasEnteredDefaultVoiceMode = true;
2564
- void updateVoiceMode();
2565
- }
2566
- updateSendButton();
2567
- }
2568
- updateHeader();
2569
- // Update pulse animation based on connecting state
2570
- if (client.state.isConnecting) {
2571
- morphingContainer.style.animation =
2572
- "convai-pulse 2s ease-in-out infinite";
2573
- }
2574
- else {
2575
- morphingContainer.style.animation = "none";
2576
- }
2577
- // Update speaking animation state
2578
- if (client.state.isSpeaking) {
2579
- if (!startTime) {
2580
- startTime = Date.now();
2581
- }
2582
- }
2583
- else {
2584
- // Reset when not speaking
2585
- if (startTime && !client.state.isSpeaking) {
2586
- startTime = 0;
2587
- }
2588
- }
2589
- // Auto-collapse when disconnected
2590
- if (!client.state.isConnected && !client.state.isConnecting) {
2591
- if (isOpen) {
2592
- setIsOpen(false);
2593
- }
2594
- isMuted = false;
2595
- isVoiceMode = false;
2596
- isVideoVisible = false;
2597
- hasEnteredDefaultVoiceMode = false;
2598
- updateHeader();
2599
- // Synchronous listener: nothing here can catch a rejection, and the
2600
- // mute inside is the one most likely to fail (the room has just
2601
- // dropped -- that is why we are collapsing).
2602
- applyVoiceMode();
2603
- }
2604
- // Auto-enter voice mode on first connection if defaultVoiceMode is true
2605
- if (client.state.isConnected &&
2606
- defaultVoiceMode &&
2607
- isOpen &&
2608
- !hasEnteredDefaultVoiceMode &&
2609
- !isVoiceMode) {
2610
- setTimeout(async () => {
2611
- try {
2612
- await client.audioControls.unmuteAudio();
2613
- isVoiceMode = true;
2614
- hasEnteredDefaultVoiceMode = true;
2615
- await updateVoiceMode();
2616
- }
2617
- catch (error) {
2618
- reportMicFailure(client, "Failed to enter voice mode:", error);
2619
- }
2620
- }, 100);
2621
- }
2622
- });
2623
- // Audio state changes now only affect voice mode (microphone button removed)
2624
- // Video state change listener
2625
- eventSubscriptions.register((listener) => client.videoControls.on("videoStateChange", listener), (videoState) => {
2626
- if (videoState.isVideoEnabled !== undefined) {
2627
- isVideoVisible = videoState.isVideoEnabled;
2628
- applyVoiceMode(); // synchronous listener; see applyVoiceMode()
2629
- // Update tray button state
2630
- const videoBtn = refs.settingsVideoBtn;
2631
- if (videoBtn) {
2632
- const isActive = isVideoVisible;
2633
- videoBtn.style.backgroundColor = isActive
2634
- ? "rgba(16, 185, 129, 0.15)"
2635
- : "transparent";
2636
- videoBtn.style.color = isActive
2637
- ? "#10b981"
2638
- : `var(--convai-panel-fg, ${aeroTheme.colors.text.primary})`;
2639
- // Update Icon - first child is icon container
2640
- const iconContainer = videoBtn.querySelector("div");
2641
- if (iconContainer) {
2642
- iconContainer.innerHTML = "";
2643
- const icon = isActive ? Icons.Video("md") : Icons.VideoOff("md");
2644
- icon.style.width = "18px";
2645
- icon.style.height = "18px";
2646
- iconContainer.appendChild(icon);
2647
- }
2648
- }
2649
- }
2650
- });
2651
- // Screen share state change listener
2652
- client.screenShareControls.on("screenShareStateChange", (screenShareState) => {
2653
- if (screenShareState.isScreenShareActive !== undefined) {
2654
- const isSharing = screenShareState.isScreenShareActive;
2655
- const shareBtn = refs.settingsShareBtn;
2656
- if (shareBtn) {
2657
- const isActive = isSharing;
2658
- shareBtn.style.backgroundColor = isActive
2659
- ? "rgba(16, 185, 129, 0.15)"
2660
- : "transparent";
2661
- shareBtn.style.color = isActive
2662
- ? "#10b981"
2663
- : `var(--convai-panel-fg, ${aeroTheme.colors.text.primary})`;
2664
- // Update Icon - first child is icon container
2665
- const iconContainer = shareBtn.querySelector("div");
2666
- if (iconContainer) {
2667
- iconContainer.innerHTML = "";
2668
- const icon = isActive
2669
- ? Icons.StopScreenShare("md")
2670
- : Icons.ScreenShare("md");
2671
- icon.style.width = "18px";
2672
- icon.style.height = "18px";
2673
- iconContainer.appendChild(icon);
2674
- }
2675
- }
2676
- }
2677
- });
2678
- eventSubscriptions.register((listener) => client.on("messagesChange", listener), () => {
2679
- updateMessageList();
2680
- });
2681
- // Bot ready listener - updates UI when bot becomes ready
2682
- eventSubscriptions.register((listener) => client.on("botReady", listener), () => {
2683
- updateHeader(); // Update header to show green status
2684
- updateSendButton();
2685
- });
2686
- eventSubscriptions.register((listener) => client.on("connect", listener), () => {
2687
- hasConnectedBefore = true;
2688
- // Initialize audio renderer on connection
2689
- // NOTE: the audio elements live under rootElement, so playback ends if
2690
- // the host *removes or re-parents* its mount container mid-call. Merely
2691
- // hiding it (display: none / visibility: hidden) does NOT stop
2692
- // HTMLMediaElement playback in any browser — an earlier version of this
2693
- // comment claimed otherwise and was wrong.
2694
- if (client.room && !audioRenderer) {
2695
- audioRenderer = new AudioRenderer(client.room, { container: rootElement });
2696
- }
2697
- // Fetch character info
2698
- fetchCharacterInfo();
2699
- // Call onConnect callback if provided
2700
- if (onConnect) {
2701
- onConnect();
2702
- }
2703
- });
2704
- eventSubscriptions.register((listener) => client.on("disconnect", listener), () => {
2705
- // Cleanup audio renderer
2706
- if (audioRenderer) {
2707
- audioRenderer.destroy();
2708
- audioRenderer = null;
2709
- }
2710
- updateMessageList();
2711
- // Call onDisconnect callback if provided
2712
- if (onDisconnect) {
2713
- onDisconnect();
2714
- }
2715
- });
2716
- // `message` carries the row actually updated. That can differ from the
2717
- // list tail when correlated v2 streams interleave, which is why onMessage
2718
- // no longer reads the last element of chatMessages.
2719
- eventSubscriptions.register((listener) => client.on("message", listener), (message) => {
2720
- const row = message;
2721
- if (onMessage && row) {
2722
- onMessage(row);
2723
- }
2724
- });
2725
- // Screen share state change listener
2726
- eventSubscriptions.register((listener) => client.screenShareControls.on("screenShareStateChange", listener), (screenShareState) => {
2727
- if (screenShareState.isScreenShareActive !== undefined) {
2728
- const isSharing = screenShareState.isScreenShareActive;
2729
- const shareBtn = document.getElementById("convai-settings-share-btn");
2730
- if (shareBtn) {
2731
- const isActive = isSharing;
2732
- shareBtn.style.backgroundColor = isActive
2733
- ? "rgba(16, 185, 129, 0.15)"
2734
- : "transparent";
2735
- shareBtn.style.color = isActive
2736
- ? "#10b981"
2737
- : aeroTheme.colors.text.primary;
2738
- // Update Icon - first child is icon container
2739
- const iconContainer = shareBtn.querySelector("div");
2740
- if (iconContainer) {
2741
- iconContainer.innerHTML = "";
2742
- const icon = isActive
2743
- ? Icons.StopScreenShare("md")
2744
- : Icons.ScreenShare("md");
2745
- icon.style.width = "18px";
2746
- icon.style.height = "18px";
2747
- iconContainer.appendChild(icon);
2748
- }
2749
- }
2750
- }
2751
- });
2752
- };
2753
- // Initialize
2754
- createDOM();
2755
- setupClientListeners();
2756
- // Paint the connecting overlay's initial state. updateHeader() (which also
2757
- // calls updateConnectingOverlay()) is otherwise only reached via a client
2758
- // event or a successful character-info fetch, so a widget constructed
2759
- // already connected-but-not-ready would show nothing until one of those
2760
- // fires without this.
2761
- updateConnectingOverlay();
2762
- // Set initial button state
2763
- updateSendButton(); // Show voice mode button initially since input is empty
2764
- // Set initial voice mode UI if defaultVoiceMode is true
2765
- if (defaultVoiceMode) {
2766
- applyVoiceMode(); // synchronous constructor tail; see applyVoiceMode()
2767
- }
2768
- // If already connected, initialize audio renderer and fetch character info
2769
- // NOTE: same lifetime caveat as the "connect" handler above — the audio
2770
- // elements are torn down with rootElement if the host detaches it.
2771
- if (client.state.isConnected && client.room) {
2772
- audioRenderer = new AudioRenderer(client.room, { container: rootElement });
2773
- fetchCharacterInfo();
2774
- }
2775
- // Return widget instance
2776
- const widget = {
2777
- element: rootElement,
2778
- client: client,
2779
- // `isOpen` reports *requested* state, which on a warm client is the same
2780
- // thing as rendered state: `setIsOpen()` runs synchronously. The one case
2781
- // where they differ is the first open on a disconnected client, where the
2782
- // panel is committed only after `connect()` resolves; reporting `false`
2783
- // for those seconds would tell an embed reconciling its own
2784
- // convai-open/convai-close events that a widget it just opened is closed.
2785
- // `pendingOpen` is cleared by every cancellation path, so this never
2786
- // reports open for a request that was called off.
2787
- get isOpen() {
2788
- return isOpen || pendingOpen;
2789
- },
2790
- // Drives the exact same path the launcher click does: `handleToggle`
2791
- // (connect-on-first-open, then `setIsOpen(true)`). Idempotent against an
2792
- // in-flight open as well as an open panel, so repeat calls never start a
2793
- // second connect.
2794
- open: () => {
2795
- if (isOpen || pendingOpen)
2796
- return;
2797
- void handleToggle();
2798
- },
2799
- // Drives the same path the header's close button does: `handleClose` ->
2800
- // `setIsOpen(false)`. Also cancels an open that is still waiting on
2801
- // `connect()`; a redundant `close()` is a no-op.
2802
- close: () => {
2803
- if (!isOpen && !pendingOpen)
2804
- return;
2805
- handleClose();
2806
- },
2807
- toggle: () => {
2808
- if (isOpen || pendingOpen) {
2809
- handleClose();
2810
- }
2811
- else {
2812
- void handleToggle();
2813
- }
2814
- },
2815
- // Pushes a synthetic ChatMessage straight onto `client.chatMessages` and
2816
- // re-renders via the widget's existing `updateMessageList()`. It never
2817
- // calls a client send method (e.g. `sendUserTextMessage`), so the
2818
- // message never reaches the character and is never billed as an LLM
2819
- // turn. The `local-` id keeps it from colliding with a server-issued id.
2820
- appendMessage: (message) => {
2821
- // Shared core path, so React and vanilla insert identically. A
2822
- // hand-rolled IConvaiClient without it falls back to the old local push.
2823
- if (typeof client.appendMessage === "function") {
2824
- client.appendMessage(message);
2825
- }
2826
- else {
2827
- const chatMessage = {
2828
- id: `local-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`,
2829
- type: message.sender === "user" ? "user-llm-text" : "bot-llm-text",
2830
- content: message.content,
2831
- timestamp: new Date().toISOString(),
2832
- };
2833
- client.chatMessages.push(chatMessage);
2834
- }
2835
- updateMessageList();
2836
- },
2837
- destroy: () => {
2838
- isDestroyed = true;
2839
- // Cleanup audio renderer
2840
- if (audioRenderer) {
2841
- audioRenderer.destroy();
2842
- audioRenderer = null;
2843
- }
2844
- // Remove event listeners
2845
- morphingContainer.removeEventListener("click", handleLauncherClick);
2846
- // Remove DOM elements
2847
- if (rootElement.parentElement) {
2848
- rootElement.remove();
2849
- }
2850
- if (floatingVideo.parentElement) {
2851
- floatingVideo.remove();
2852
- }
2853
- // Unsubscribe using the exact callbacks registered above. The guards
2854
- // also suppress an event that was queued just before teardown.
2855
- eventSubscriptions.unsubscribeAll();
2856
- },
2857
- };
2858
- return widget;
2859
- }
2860
- /**
2861
- * Destroy a Convai widget instance
2862
- * @param widget - Widget instance to destroy
2863
- */
2864
- export function destroyConvaiWidget(widget) {
2865
- widget.destroy();
2866
- }