@runtypelabs/persona 4.24.0 → 4.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (237) hide show
  1. package/dist/animations/glyph-cycle.d.cts +1 -1
  2. package/dist/animations/glyph-cycle.d.ts +1 -1
  3. package/dist/animations/{types-Db61aI9J.d.cts → types-BwKTZhg9.d.cts} +14 -0
  4. package/dist/animations/{types-Db61aI9J.d.ts → types-BwKTZhg9.d.ts} +14 -0
  5. package/dist/animations/wipe.d.cts +1 -1
  6. package/dist/animations/wipe.d.ts +1 -1
  7. package/dist/animations-extra.d.cts +14 -0
  8. package/dist/animations-extra.d.ts +14 -0
  9. package/dist/approval-ui-QAKWNFNM.js +1 -0
  10. package/dist/approval-ui.cjs +2 -2
  11. package/dist/approval-ui.d.cts +243 -8
  12. package/dist/approval-ui.d.ts +243 -8
  13. package/dist/approval-ui.js +2 -2
  14. package/dist/{artifacts-ui-IGB5YKLO.js → artifacts-ui-NJGMM27I.js} +1 -1
  15. package/dist/artifacts-ui.cjs +4 -4
  16. package/dist/artifacts-ui.d.cts +243 -8
  17. package/dist/artifacts-ui.d.ts +243 -8
  18. package/dist/artifacts-ui.js +5 -5
  19. package/dist/chunk-2ANTRKTV.js +1 -0
  20. package/dist/chunk-4HPTPUC6.js +1 -0
  21. package/dist/chunk-6V3MNEKB.js +1 -0
  22. package/dist/chunk-HGUCGM3K.js +9 -0
  23. package/dist/chunk-IO5VVUKP.js +3 -0
  24. package/dist/chunk-J4J3Y2P2.js +1 -0
  25. package/dist/chunk-K6HKIP5K.js +1 -0
  26. package/dist/chunk-K7NA7G7J.js +1 -0
  27. package/dist/chunk-MXUTS3LB.js +1 -0
  28. package/dist/chunk-PDPVORUF.js +1 -0
  29. package/dist/chunk-QPPJUSZH.js +1 -0
  30. package/dist/chunk-QRKGQPU7.js +1 -0
  31. package/dist/chunk-S6PBWE75.js +1 -0
  32. package/dist/chunk-T7QM7YMF.js +1 -0
  33. package/dist/chunk-TR2H475E.js +1 -0
  34. package/dist/chunk-UPO4GUFC.js +1 -0
  35. package/dist/chunk-ZC66NAIR.js +1 -0
  36. package/dist/client-history-YPEG45Q4.js +1 -0
  37. package/dist/client-history.js +1 -0
  38. package/dist/client-stream-42FOI3EC.js +4 -0
  39. package/dist/client-stream.js +5 -0
  40. package/dist/codegen.cjs +1 -1
  41. package/dist/codegen.js +1 -1
  42. package/dist/context-mentions-E7HJYWO6.js +161 -0
  43. package/dist/{context-mentions-inline-I2RDEBAK.js → context-mentions-inline-QVESLW55.js} +1 -1
  44. package/dist/context-mentions.cjs +7 -7
  45. package/dist/context-mentions.d.cts +243 -8
  46. package/dist/context-mentions.d.ts +243 -8
  47. package/dist/context-mentions.js +8 -8
  48. package/dist/event-stream-view-FOIJHFQO.js +1 -0
  49. package/dist/event-stream-view.cjs +1 -1
  50. package/dist/event-stream-view.d.cts +246 -31
  51. package/dist/event-stream-view.d.ts +246 -31
  52. package/dist/event-stream-view.js +1 -1
  53. package/dist/forms-ui.d.cts +295 -667
  54. package/dist/forms-ui.d.ts +295 -667
  55. package/dist/history-shell-QDQ44PSE.js +3 -0
  56. package/dist/history-shell.js +3 -0
  57. package/dist/{history-view-BD6OXLNA.js → history-view-NCFBI5GR.js} +2 -2
  58. package/dist/history-view.cjs +2 -2
  59. package/dist/history-view.d.cts +35 -1
  60. package/dist/history-view.d.ts +35 -1
  61. package/dist/history-view.js +2 -2
  62. package/dist/index.cjs +80 -74
  63. package/dist/index.cjs.map +1 -1
  64. package/dist/index.d.cts +301 -738
  65. package/dist/index.d.ts +301 -738
  66. package/dist/index.global.js +3 -215
  67. package/dist/index.global.js.map +1 -1
  68. package/dist/index.js +81 -75
  69. package/dist/index.js.map +1 -1
  70. package/dist/install.global.js +1 -1
  71. package/dist/install.global.js.map +1 -1
  72. package/dist/launcher.global.js +3 -67
  73. package/dist/launcher.global.js.map +1 -1
  74. package/dist/markdown-parsers.js +22 -22
  75. package/dist/runtype-tts-entry-NFBVWR7N.js +1 -0
  76. package/dist/runtype-tts.js +1 -1
  77. package/dist/session-actions-ISSKSI66.js +1 -0
  78. package/dist/session-actions.js +1 -0
  79. package/dist/session-reconnect.d.cts +243 -8
  80. package/dist/session-reconnect.d.ts +243 -8
  81. package/dist/smart-dom-reader.cjs +13 -13
  82. package/dist/smart-dom-reader.d.cts +243 -8
  83. package/dist/smart-dom-reader.d.ts +243 -8
  84. package/dist/smart-dom-reader.js +11 -11
  85. package/dist/theme-editor-preview.cjs +116 -98
  86. package/dist/theme-editor-preview.d.cts +245 -8
  87. package/dist/theme-editor-preview.d.ts +245 -8
  88. package/dist/theme-editor-preview.js +49 -54
  89. package/dist/theme-editor.cjs +2 -2
  90. package/dist/theme-editor.d.cts +244 -23
  91. package/dist/theme-editor.d.ts +244 -23
  92. package/dist/theme-editor.js +2 -2
  93. package/dist/theme-reference.d.cts +14 -0
  94. package/dist/theme-reference.d.ts +14 -0
  95. package/dist/ui-extras-entry-WAYFKVNW.js +3 -0
  96. package/dist/ui-extras.js +72 -0
  97. package/dist/voice-runtime-UOQOFAFY.js +17 -0
  98. package/dist/voice-runtime.cjs +17 -1
  99. package/dist/voice-runtime.d.cts +11643 -192
  100. package/dist/voice-runtime.d.ts +11643 -192
  101. package/dist/voice-runtime.js +17 -1
  102. package/dist/voice-worklet-player.cjs +19 -4
  103. package/dist/voice-worklet-player.d.cts +9 -10
  104. package/dist/voice-worklet-player.d.ts +9 -10
  105. package/dist/voice-worklet-player.js +19 -4
  106. package/dist/webmcp-polyfill.js +1 -1
  107. package/dist/webmcp-runtime-V6ZWW3PI.js +6 -0
  108. package/dist/webmcp-runtime.cjs +2 -2
  109. package/dist/webmcp-runtime.d.cts +1 -33
  110. package/dist/webmcp-runtime.d.ts +1 -33
  111. package/dist/webmcp-runtime.js +2 -2
  112. package/dist/widget.css +1 -1
  113. package/package.json +11 -5
  114. package/src/approval-paused-tool-settle.test.ts +221 -0
  115. package/src/client-approve.test.ts +311 -0
  116. package/src/client-history-eager.ts +9 -0
  117. package/src/client-history-loader.ts +23 -0
  118. package/src/client-history.ts +579 -0
  119. package/src/client-resume.ts +177 -0
  120. package/src/client-stream-eager.ts +12 -0
  121. package/src/client-stream-loader.ts +25 -0
  122. package/src/client-stream.ts +1880 -0
  123. package/src/client.test.ts +31 -1
  124. package/src/client.ts +293 -2607
  125. package/src/components/approval-actions.test.ts +27 -0
  126. package/src/components/approval-actions.ts +27 -3
  127. package/src/components/message-bubble.test.ts +19 -0
  128. package/src/components/message-bubble.ts +2 -0
  129. package/src/components/registry.ts +6 -6
  130. package/src/components/tool-bubble.test.ts +9 -0
  131. package/src/components/tool-bubble.ts +1 -0
  132. package/src/history-shell-bundle.test.ts +54 -0
  133. package/src/history-shell-eager.ts +12 -0
  134. package/src/history-shell-loader.ts +27 -0
  135. package/src/history-shell.ts +2362 -0
  136. package/src/history-view-loader.ts +2 -0
  137. package/src/history-view.ts +3 -0
  138. package/src/index-core.ts +8 -0
  139. package/src/index-global.ts +90 -248
  140. package/src/index.ts +13 -0
  141. package/src/install.ts +6 -4
  142. package/src/internal/runtype-history-provider.test.ts +1 -0
  143. package/src/internal/runtype-history-provider.ts +28 -13
  144. package/src/plugins/registry.ts +8 -8
  145. package/src/session-actions-chunk.test.ts +55 -0
  146. package/src/session-actions-eager.ts +11 -0
  147. package/src/session-actions-loader.ts +37 -0
  148. package/src/session-actions.ts +909 -0
  149. package/src/session-history.test.ts +3 -1
  150. package/src/session.ts +875 -1530
  151. package/src/session.voice.test.ts +1241 -5
  152. package/src/styles/widget.css +58 -0
  153. package/src/theme-editor/state.ts +91 -91
  154. package/src/types.ts +269 -5
  155. package/src/ui-ask-user-sheet.ts +382 -0
  156. package/src/ui-extras-eager.ts +10 -0
  157. package/src/ui-extras-entry.ts +9 -0
  158. package/src/ui-extras-loader.ts +26 -0
  159. package/src/ui.artifact-rail-resize.test.ts +2 -1
  160. package/src/ui.ask-user-chunk.test.ts +93 -0
  161. package/src/ui.history-chunk.test.ts +2 -1
  162. package/src/ui.history-config-provider.test.ts +2 -1
  163. package/src/ui.history-confirm-fallback.test.ts +142 -0
  164. package/src/ui.history-controller.test.ts +2 -1
  165. package/src/ui.history-lifecycle.test.ts +2 -1
  166. package/src/ui.history-render-hooks.test.ts +2 -1
  167. package/src/ui.history-shell.test.ts +2 -1
  168. package/src/ui.rail-overlay.test.ts +2 -1
  169. package/src/ui.rail-resize.test.ts +2 -1
  170. package/src/ui.rail-trigger-pending.test.ts +2 -1
  171. package/src/ui.ts +399 -2770
  172. package/src/ui.voice-prewarm.test.ts +222 -0
  173. package/src/utils/attachment-manager.ts +67 -67
  174. package/src/utils/constants.ts +3 -0
  175. package/src/utils/context-mention-controller.ts +323 -323
  176. package/src/utils/context-mention-manager.ts +40 -40
  177. package/src/utils/context-mention-orchestrator.ts +28 -0
  178. package/src/utils/event-stream-buffer.ts +50 -50
  179. package/src/utils/event-stream-store.ts +43 -43
  180. package/src/utils/throughput-tracker.ts +34 -34
  181. package/src/utils/virtual-scroller.ts +67 -67
  182. package/src/utils/visitor-store.test.ts +50 -0
  183. package/src/utils/visitor-store.ts +23 -5
  184. package/src/voice/__fixtures__/voice-wire/README.md +1 -0
  185. package/src/voice/__fixtures__/voice-wire/client/cancel.json +3 -0
  186. package/src/voice/__fixtures__/voice-wire/client/context.json +4 -0
  187. package/src/voice/__fixtures__/voice-wire/client/delegation_result.json +6 -0
  188. package/src/voice/__fixtures__/voice-wire/client/delegation_update.json +6 -0
  189. package/src/voice/__fixtures__/voice-wire/client/ping.json +3 -0
  190. package/src/voice/__fixtures__/voice-wire/client/playback_progress.json +5 -0
  191. package/src/voice/__fixtures__/voice-wire/client/start.json +3 -0
  192. package/src/voice/__fixtures__/voice-wire/server/artifact.json +11 -0
  193. package/src/voice/__fixtures__/voice-wire/server/attached.json +4 -0
  194. package/src/voice/__fixtures__/voice-wire/server/audio_clear.json +4 -0
  195. package/src/voice/__fixtures__/voice-wire/server/audio_end.json +3 -0
  196. package/src/voice/__fixtures__/voice-wire/server/delegation_cancelled.json +5 -0
  197. package/src/voice/__fixtures__/voice-wire/server/delegation_completed.json +8 -0
  198. package/src/voice/__fixtures__/voice-wire/server/delegation_started.json +15 -0
  199. package/src/voice/__fixtures__/voice-wire/server/error.json +6 -0
  200. package/src/voice/__fixtures__/voice-wire/server/metrics.json +10 -0
  201. package/src/voice/__fixtures__/voice-wire/server/pong.json +3 -0
  202. package/src/voice/__fixtures__/voice-wire/server/session_config.json +16 -0
  203. package/src/voice/__fixtures__/voice-wire/server/transcript_final.json +7 -0
  204. package/src/voice/__fixtures__/voice-wire/server/transcript_interim.json +4 -0
  205. package/src/voice/__fixtures__/voice-wire/server/transcript_partial.json +6 -0
  206. package/src/voice/__fixtures__/voice-wire/server/transcript_update.json +10 -0
  207. package/src/voice/__fixtures__/voice-wire/server/warning.json +5 -0
  208. package/src/voice/audio-playback-manager.test.ts +57 -0
  209. package/src/voice/audio-playback-manager.ts +120 -98
  210. package/src/voice/browser-voice-provider.ts +37 -37
  211. package/src/voice/fallback-speech-engine.ts +22 -16
  212. package/src/voice/keyed-voice-transcript.ts +314 -0
  213. package/src/voice/mic-state-styles.ts +182 -0
  214. package/src/voice/read-aloud-controller.ts +46 -44
  215. package/src/voice/runtype-speech-engine.ts +35 -33
  216. package/src/voice/runtype-voice-provider.ts +856 -164
  217. package/src/voice/session-voice-wiring.ts +266 -0
  218. package/src/voice/voice-delegation.test.ts +71 -0
  219. package/src/voice/voice-delegation.ts +364 -0
  220. package/src/voice/voice-turn-tracker.ts +6 -6
  221. package/src/voice/voice.test.ts +1250 -7
  222. package/src/voice/worklet-playback-engine.test.ts +81 -0
  223. package/src/voice/worklet-playback-engine.ts +21 -3
  224. package/src/voice-runtime-loader.ts +4 -1
  225. package/src/voice-runtime.ts +7 -0
  226. package/src/webmcp-runtime-entry.ts +41 -39
  227. package/dist/approval-ui-3NMYNXBD.js +0 -1
  228. package/dist/chunk-5EIIHQLQ.js +0 -1
  229. package/dist/chunk-7CO4T5KB.js +0 -1
  230. package/dist/chunk-EFJBUH5F.js +0 -1
  231. package/dist/chunk-R2TMIMDI.js +0 -3
  232. package/dist/chunk-UTVLOTWB.js +0 -9
  233. package/dist/context-mentions-45MODWOY.js +0 -161
  234. package/dist/event-stream-view-GL3ADRY2.js +0 -1
  235. package/dist/runtype-tts-entry-UJAEF7NZ.js +0 -1
  236. package/dist/voice-runtime-EFR3R5ES.js +0 -1
  237. package/dist/webmcp-runtime-JI7T4QYF.js +0 -6
package/src/ui.ts CHANGED
@@ -6,6 +6,11 @@ import { resolveSanitizer } from "./utils/sanitize";
6
6
  import { stabilizeStreamingTables } from "./utils/streaming-table";
7
7
  import { wrapScrollableTables, refreshTableScrollFades } from "./utils/table-scroll-fade";
8
8
  import { onMarkdownParsersReady, getMarkdownParsersSync, loadMarkdownParsers } from "./markdown-parsers-loader";
9
+ import { loadClientStream } from "./client-stream-loader";
10
+ import { HistoryClientError } from "./client";
11
+ import { HistoryProviderError } from "./internal/history-provider";
12
+ import { getUiExtrasSync, loadUiExtras, type UiExtrasModule } from "./ui-extras-loader";
13
+ import type { AskUserSheetContext, AskUserSheetHandlers } from "./ui-ask-user-sheet";
9
14
  import {
10
15
  AgentWidgetSession,
11
16
  AgentWidgetSessionStatus,
@@ -16,6 +21,7 @@ import {
16
21
  AgentWidgetConfig,
17
22
  AgentWidgetConfigPatch,
18
23
  AgentWidgetSessionInitHook,
24
+ AgentWidgetVoicePrewarmHook,
19
25
  AgentWidgetApprovalDecisionOptions,
20
26
  AgentWidgetMessage,
21
27
  AgentWidgetEvent,
@@ -36,7 +42,6 @@ import {
36
42
  InjectSystemMessageOptions,
37
43
  InjectComponentDirectiveOptions,
38
44
  LoadingIndicatorRenderContext,
39
- AgentWidgetRenderHistoryOpenErrorContext,
40
45
  IdleIndicatorRenderContext,
41
46
  VoiceStatus,
42
47
  ReadAloudState,
@@ -50,7 +55,6 @@ import {
50
55
  AgentWidgetSuggestion,
51
56
  AgentWidgetSuggestionSource,
52
57
  AgentWidgetWelcomeIcon,
53
- HistoryConversationPatch,
54
58
  HistoryConversationSummary,
55
59
  HistoryIdentityStatus,
56
60
  HistoryReturnSurface,
@@ -144,10 +148,10 @@ import {
144
148
  type BeforeSendOutcome,
145
149
  type InternalSubmissionSnapshot,
146
150
  } from "./utils/composer-submission";
147
- import {
148
- createContextMentionOrchestrator,
149
- type ContextMentionOrchestrator,
150
- } from "./utils/context-mention-orchestrator";
151
+ import type { ContextMentionOrchestrator } from "./utils/context-mention-orchestrator";
152
+ import { loadContextMentions } from "./context-mentions-loader";
153
+ import { loadContextMentionsInline } from "./context-mentions-inline-loader";
154
+ import { createMentionButton } from "./components/context-mention-button";
151
155
  import type { MentionSubmitBundle } from "./utils/context-mention-manager";
152
156
  import { createTextPart, ALL_SUPPORTED_MIME_TYPES } from "./utils/content";
153
157
  import { applyThemeVariables, createThemeObserver, getActiveTheme, getColorScheme } from "./utils/theme";
@@ -156,7 +160,7 @@ import { deepMerge } from "./utils/deep-merge";
156
160
  import { Activity, Check, Copy } from "lucide";
157
161
  import { renderLucideIcon, onExtraIconsReady } from "./utils/icons";
158
162
  import { renderIconNode } from "./utils/icon-node";
159
- import { createElement, createNode, cx } from "./utils/dom";
163
+ import { createElement } from "./utils/dom";
160
164
  import { resolveContentMaxWidth } from "./utils/content-width";
161
165
  import {
162
166
  computeComposerLift,
@@ -170,16 +174,13 @@ import {
170
174
  DEFAULT_TOOLTIP_DELAY_MS,
171
175
  DEFAULT_TOOLTIP_SKIP_DELAY_MS,
172
176
  } from "./utils/tooltip-timing";
173
- import {
174
- ariaCombo,
175
- createShortcutRegistry,
176
- formatCombo,
177
- parseCombo,
178
- } from "./utils/shortcuts";
177
+ import { createShortcutRegistry } from "./utils/shortcuts";
179
178
  // The artifact download/copy helpers live in the lazy artifacts-ui chunk;
180
179
  // reached via getArtifactsUiSync() in the delegated click handlers (which can
181
180
  // only fire on DOM the adopted chunk rendered).
182
181
  import { morphMessages } from "./utils/morph";
182
+ import { getVoiceRuntimeSync, loadVoiceRuntime, type VoiceRuntimeModule } from "./voice-runtime-loader";
183
+ import type { MicStateStyles, OriginalMicStyles } from "./voice/mic-state-styles";
183
184
  import { normalizeCopiedSelectionText } from "./utils/copy-selection";
184
185
  import {
185
186
  navigateComposerHistory,
@@ -201,7 +202,6 @@ import {
201
202
  import {
202
203
  statusCopy,
203
204
  DEFAULT_OVERLAY_Z_INDEX,
204
- PORTALED_OVERLAY_Z_INDEX,
205
205
  } from "./utils/constants";
206
206
  import {
207
207
  applyStreamBuffer,
@@ -272,18 +272,10 @@ import { createReasoningBubble, updateReasoningBubbleUI } from "./components/rea
272
272
  import { copyToolDetail } from "./components/tool-details";
273
273
  import { createToolBubble, updateToolBubbleUI } from "./components/tool-bubble";
274
274
  import {
275
- buildStructuredAnswers,
276
275
  ensureAskUserQuestionSheet,
277
- getCurrentIndex,
278
- getQuestionCount,
279
- getSelectedLabels,
280
276
  isAskUserQuestionMessage,
281
- isGroupedSheet,
282
- navigateToPage,
283
277
  parseAskUserQuestionPayload,
284
- readAnswersFromSheet,
285
278
  removeAskUserQuestionSheet,
286
- setCurrentAnswer,
287
279
  } from "./components/ask-user-question-bubble";
288
280
  import {
289
281
  isSuggestRepliesMessage,
@@ -342,27 +334,9 @@ import {
342
334
  import { createLocalStorageAdapter } from "./utils/storage";
343
335
  import { createVisitorStore, type VisitorStore } from "./utils/visitor-store";
344
336
  import { loadHistoryView } from "./history-view-loader";
345
- import type {
346
- HistoryHeaderPlacement,
347
- HistoryRailSection,
348
- HistoryViewHandle,
349
- HistoryViewOptions,
350
- } from "./history-view-entry";
351
- import {
352
- createHistoryRenderSurface,
353
- type HistoryRenderSurface,
354
- } from "./history-render";
337
+ import { getHistoryShellSync, loadHistoryShell, type HistoryShellModule } from "./history-shell-loader";
338
+ import type { HistoryShell, HistoryShellContext } from "./history-shell";
355
339
  import { getHistoryProviderFactory } from "./internal/history-provider-registry";
356
- import type {
357
- HistoryOperationContext,
358
- HistoryProvider,
359
- } from "./internal/history-provider";
360
- import { createRuntypeHistoryProvider } from "./internal/runtype-history-provider";
361
- import {
362
- resolveHistoryShellCopy,
363
- type ResolvedHistoryShellCopy,
364
- } from "./components/history-shell-copy";
365
- import { showHistoryConfirm } from "./components/history-confirm-dialog";
366
340
  import { componentRegistry } from "./components/registry";
367
341
  import {
368
342
  renderComponentDirective,
@@ -1099,6 +1073,13 @@ export const createAgentExperience = (
1099
1073
  const historyBootstrapReady = new Promise<void>((resolve) => {
1100
1074
  resolveHistoryBootstrap = resolve;
1101
1075
  });
1076
+ // With history enabled at mount, history-capable init also waits for the
1077
+ // shell, which installs the provider. Only the IIFE build loads it async
1078
+ // (always resolves, even when the chunk fails).
1079
+ let resolveHistoryShellGate: () => void = () => {};
1080
+ const historyShellGate = new Promise<void>((resolve) => {
1081
+ resolveHistoryShellGate = resolve;
1082
+ });
1102
1083
  /** Synchronously loaded draft, replayed into the composer after it mounts. */
1103
1084
  let loadedStoredDraft: AgentWidgetStoredDraft | undefined;
1104
1085
 
@@ -2334,6 +2315,20 @@ export const createAgentExperience = (
2334
2315
  */
2335
2316
  const setupMentionOrchestrator = () => {
2336
2317
  if (!config.contextMentions?.enabled || !textarea) return;
2318
+ // The orchestrator rides the lazy ui-extras chunk on the CDN: mount it (and
2319
+ // re-collect the composer actions for its affordance buttons) once the
2320
+ // chunk lands, unless a composer rebuild replaced this textarea meanwhile
2321
+ // (the rebuild re-runs this function) or the widget was destroyed.
2322
+ const extras = getUiExtrasSync();
2323
+ if (!extras) {
2324
+ const forTextarea = textarea;
2325
+ loadUiExtras().then(() => {
2326
+ if (mentionOrchestrator || textarea !== forTextarea || !forTextarea.isConnected) return;
2327
+ setupMentionOrchestrator();
2328
+ composerActionRenderer?.resolve();
2329
+ }, () => {});
2330
+ return;
2331
+ }
2337
2332
  // Slash-command dispatch (prompt macros write text / submit; client actions
2338
2333
  // read/replace the value) and submission are owned by the composer input
2339
2334
  // surface itself — the mention runtime builds a textarea (chip) or
@@ -2345,7 +2340,9 @@ export const createAgentExperience = (
2345
2340
  const header = composerBindings?.header ?? null;
2346
2341
  const chipRow = header ? ensureComposerChipRow(header) : undefined;
2347
2342
 
2348
- mentionOrchestrator = createContextMentionOrchestrator({
2343
+ mentionOrchestrator = extras.createContextMentionOrchestrator({
2344
+ // Core's stateful collaborators, not the chunk's copies.
2345
+ deps: { loadContextMentions, loadContextMentionsInline, renderLucideIcon, createMentionButton },
2349
2346
  config,
2350
2347
  textarea,
2351
2348
  anchor: composerForm ?? textarea,
@@ -3327,345 +3324,63 @@ export const createAgentExperience = (
3327
3324
  // user message via session.sendMessage so the agent resumes on the next turn.
3328
3325
  const askUserOverlay = panelElements.composerOverlay;
3329
3326
 
3330
- const submitAskUserAnswer = (
3331
- sheet: HTMLElement,
3332
- text: string,
3333
- meta: {
3334
- source: "pick" | "multi" | "free-text" | "submit-all";
3335
- values?: string[];
3336
- structured?: Record<string, string | string[]>;
3337
- }
3338
- ): void => {
3339
- const trimmed = text.trim();
3340
- if (!trimmed || !sessionRef.current) return;
3341
- const toolCallId = sheet.getAttribute("data-tool-call-id") ?? "";
3342
- const isFreeText = meta.source === "free-text";
3343
-
3344
- // Dispatch before removing the sheet so listeners can still query DOM state.
3345
- mount.dispatchEvent(
3346
- new CustomEvent("persona:askUserQuestion:answered", {
3347
- detail: {
3348
- toolUseId: toolCallId,
3349
- answer: trimmed,
3350
- answers: meta.structured,
3351
- values: meta.values ?? (meta.source === "multi" ? trimmed.split(", ") : [trimmed]),
3352
- isFreeText,
3353
- source: meta.source,
3354
- },
3355
- bubbles: true,
3356
- composed: true,
3357
- })
3358
- );
3359
-
3360
- removeAskUserQuestionSheet(askUserOverlay, toolCallId);
3361
-
3362
- // Branch: LOCAL-tool pause (await) resumes via /resume with structured
3363
- // toolOutputs; legacy path sends as a plain user message.
3364
- const sourceMessage = sessionRef.current
3365
- .getMessages()
3366
- .find((m) => m.toolCall?.id === toolCallId);
3367
- if (sourceMessage?.agentMetadata?.awaitingLocalTool) {
3368
- sessionRef.current.resolveAskUserQuestion(sourceMessage, meta.structured ?? trimmed);
3369
- } else {
3370
- sessionRef.current.sendMessage(trimmed);
3371
- }
3372
- };
3373
-
3374
- /**
3375
- * Persist in-progress grouped-question answers + page index back to the
3376
- * source message so a refresh restores the user's spot.
3377
- */
3378
- const persistGroupedProgress = (sheet: HTMLElement): void => {
3379
- const session = sessionRef.current;
3380
- if (!session) return;
3381
- const toolCallId = sheet.getAttribute("data-tool-call-id") ?? "";
3382
- const sourceMessage = session.getMessages().find((m) => m.toolCall?.id === toolCallId);
3383
- if (!sourceMessage) return;
3384
- session.persistAskUserQuestionProgress(sourceMessage, {
3385
- answers: buildStructuredAnswers(sheet, sourceMessage),
3386
- currentIndex: getCurrentIndex(sheet),
3387
- });
3388
- };
3389
-
3390
- /**
3391
- * Build a one-line summary string for the legacy `answer` field on the
3392
- * answered event when submit-all fires from a grouped sheet.
3393
- */
3394
- const stringifyStructured = (answers: Record<string, string | string[]>): string => {
3395
- return Object.entries(answers)
3396
- .map(([q, v]) => `${q}: ${Array.isArray(v) ? v.join(", ") : v}`)
3397
- .join(" | ");
3398
- };
3399
-
3400
- /**
3401
- * If `groupedAutoAdvance` is enabled (default) and we're not on the final
3402
- * page, advance one step. The final page never auto-submits: users always
3403
- * confirm with an explicit Submit-all click so they can review.
3404
- */
3405
- const maybeAutoAdvance = (sheet: HTMLElement): void => {
3406
- if (config.features?.askUserQuestion?.groupedAutoAdvance === false) return;
3407
- const idx = getCurrentIndex(sheet);
3408
- const count = getQuestionCount(sheet);
3409
- if (idx >= count - 1) return;
3410
- const sourceMessage = sessionRef.current
3411
- ?.getMessages()
3412
- .find((m) => m.toolCall?.id === sheet.getAttribute("data-tool-call-id"));
3413
- if (!sourceMessage) return;
3414
- navigateToPage(sheet, sourceMessage, config, idx + 1);
3415
- persistGroupedProgress(sheet);
3416
- };
3417
-
3418
- askUserOverlay.addEventListener("click", (event) => {
3419
- const target = event.target as HTMLElement;
3420
- const trigger = target.closest<HTMLElement>("[data-ask-user-action]");
3421
- if (!trigger) return;
3422
- const sheet = trigger.closest<HTMLElement>("[data-persona-ask-sheet-for]");
3423
- if (!sheet) return;
3424
-
3425
- const action = trigger.getAttribute("data-ask-user-action");
3426
- event.preventDefault();
3427
- event.stopPropagation();
3428
-
3429
- if (action === "dismiss") {
3430
- const toolCallId = sheet.getAttribute("data-tool-call-id") ?? "";
3431
- mount.dispatchEvent(
3432
- new CustomEvent("persona:askUserQuestion:dismissed", {
3433
- detail: { toolUseId: toolCallId },
3434
- bubbles: true,
3435
- composed: true,
3436
- })
3437
- );
3438
- removeAskUserQuestionSheet(askUserOverlay, toolCallId);
3439
-
3440
- // Best-effort: if this sheet corresponds to a LOCAL-awaiting tool,
3441
- // unblock the paused execution with a sentinel answer so the server
3442
- // doesn't sit in waiting_for_local forever. Fire-and-forget: errors
3443
- // are surfaced to the onError callback. Flip the answered flag first
3444
- // so a racing render pass doesn't re-mount the sheet mid-dismissal.
3445
- const sourceMessage = sessionRef.current
3446
- ?.getMessages()
3447
- .find((m) => m.toolCall?.id === toolCallId);
3448
- if (sourceMessage?.agentMetadata?.awaitingLocalTool) {
3449
- sessionRef.current?.markAskUserQuestionResolved(sourceMessage);
3450
- sessionRef.current?.resolveAskUserQuestion(sourceMessage, "(dismissed)");
3451
- }
3452
- return;
3453
- }
3454
-
3455
- if (action === "pick") {
3456
- const label = trigger.getAttribute("data-option-label");
3457
- if (!label) return;
3458
- const multiSelect = sheet.getAttribute("data-multi-select") === "true";
3459
- const grouped = isGroupedSheet(sheet);
3460
-
3461
- if (grouped && multiSelect) {
3462
- const stored = readAnswersFromSheet(sheet)[getCurrentIndex(sheet)];
3463
- const set = new Set<string>(Array.isArray(stored) ? stored : []);
3464
- if (set.has(label)) set.delete(label);
3465
- else set.add(label);
3466
- setCurrentAnswer(sheet, Array.from(set));
3467
- persistGroupedProgress(sheet);
3468
- return;
3469
- }
3470
-
3471
- if (grouped) {
3472
- setCurrentAnswer(sheet, label);
3473
- persistGroupedProgress(sheet);
3474
- maybeAutoAdvance(sheet);
3475
- return;
3476
- }
3477
-
3478
- // 1-question modes: preserve original UX.
3479
- if (multiSelect) {
3480
- const pressed = trigger.getAttribute("aria-pressed") === "true";
3481
- trigger.setAttribute("aria-pressed", pressed ? "false" : "true");
3482
- trigger.classList.toggle("persona-ask-pill-selected", !pressed);
3483
- const submitBtn = sheet.querySelector<HTMLButtonElement>(
3484
- '[data-ask-user-action="submit-multi"]'
3485
- );
3486
- if (submitBtn) {
3487
- submitBtn.disabled = getSelectedLabels(sheet).length === 0;
3488
- }
3489
- return;
3490
- }
3491
- submitAskUserAnswer(sheet, label, { source: "pick", values: [label] });
3492
- return;
3493
- }
3494
-
3495
- if (action === "submit-multi") {
3496
- const labels = getSelectedLabels(sheet);
3497
- if (labels.length === 0) return;
3498
- submitAskUserAnswer(sheet, labels.join(", "), {
3499
- source: "multi",
3500
- values: labels,
3501
- });
3502
- return;
3503
- }
3504
-
3505
- if (action === "open-free-text") {
3506
- const row = sheet.querySelector<HTMLElement>('[data-ask-free-text-row="true"]');
3507
- if (row) {
3508
- row.classList.remove("persona-hidden");
3509
- const input = row.querySelector<HTMLInputElement>('[data-ask-free-text-input="true"]');
3510
- input?.focus();
3511
- }
3512
- return;
3513
- }
3514
-
3515
- if (action === "focus-free-text") {
3516
- // Rows-layout Other row: input lives inside the row container itself.
3517
- // Native click on the input already focuses it; this branch handles
3518
- // clicks on the badge or row chrome AND digit-shortcut activations.
3519
- const input = sheet.querySelector<HTMLInputElement>('[data-ask-free-text-input="true"]');
3520
- input?.focus();
3521
- return;
3522
- }
3523
-
3524
- if (action === "submit-free-text") {
3525
- const input = sheet.querySelector<HTMLInputElement>('[data-ask-free-text-input="true"]');
3526
- const text = input?.value ?? "";
3527
- if (!text.trim()) return;
3528
- if (isGroupedSheet(sheet)) {
3529
- setCurrentAnswer(sheet, text.trim());
3530
- persistGroupedProgress(sheet);
3531
- maybeAutoAdvance(sheet);
3327
+ // Warm the handler chunk as the sheet mounts so it is ready before any pick.
3328
+ const mountAskUserSheet = (message: AgentWidgetMessage): void => {
3329
+ loadUiExtras().catch(() => {});
3330
+ ensureAskUserQuestionSheet(message, config, askUserOverlay);
3331
+ };
3332
+
3333
+ // Handlers live in the lazy ui-extras chunk (warmed when a sheet mounts).
3334
+ // Only events from inside a mounted sheet need them.
3335
+ let askUserHandlers: AskUserSheetHandlers | null = null;
3336
+ const askUserCtx: AskUserSheetContext = {
3337
+ mount,
3338
+ overlay: askUserOverlay,
3339
+ sessionRef,
3340
+ config: () => config,
3341
+ };
3342
+ // At most one interaction waits on the chunk: later ones (a double click)
3343
+ // are dropped, and the queued one is dropped too if its sheet was removed
3344
+ // meanwhile, so an answer can never be submitted twice.
3345
+ let askUserEventPending = false;
3346
+ const routeAskUserEvent =
3347
+ (kind: keyof AskUserSheetHandlers) =>
3348
+ (event: Event): void => {
3349
+ const target = event.target as HTMLElement | null;
3350
+ const sheet = target?.closest?.("[data-persona-ask-sheet-for]");
3351
+ if (!sheet) return;
3352
+ // Only events the handlers act on (an action control click, Enter in the
3353
+ // free-text input) may claim the pending slot; ordinary typing must not
3354
+ // block the answer that follows it.
3355
+ const actionable =
3356
+ kind === "click"
3357
+ ? !!target?.closest("[data-ask-user-action]")
3358
+ : (event as KeyboardEvent).key === "Enter" &&
3359
+ !!target?.matches?.('[data-ask-free-text-input="true"]');
3360
+ if (!actionable) return;
3361
+ const run = (m: UiExtrasModule) => {
3362
+ askUserHandlers ??= m.createAskUserSheetHandlers(askUserCtx);
3363
+ (askUserHandlers[kind] as (e: Event) => void)(event);
3364
+ };
3365
+ const loaded = getUiExtrasSync();
3366
+ if (loaded) {
3367
+ run(loaded);
3532
3368
  return;
3533
3369
  }
3534
- submitAskUserAnswer(sheet, text, { source: "free-text" });
3535
- return;
3536
- }
3537
-
3538
- if (action === "next" || action === "back") {
3539
- if (!sessionRef.current) return;
3540
- const toolCallId = sheet.getAttribute("data-tool-call-id") ?? "";
3541
- const sourceMessage = sessionRef.current
3542
- .getMessages()
3543
- .find((m) => m.toolCall?.id === toolCallId);
3544
- if (!sourceMessage) return;
3545
- // Flush any unsubmitted free-text input as the current answer.
3546
- const freeInput = sheet.querySelector<HTMLInputElement>('[data-ask-free-text-input="true"]');
3547
- const pending = freeInput?.value?.trim() ?? "";
3548
- if (pending) {
3549
- const stored = readAnswersFromSheet(sheet)[getCurrentIndex(sheet)];
3550
- if (typeof stored !== "string" || stored !== pending) {
3551
- setCurrentAnswer(sheet, pending);
3552
- }
3553
- }
3554
- const direction = action === "next" ? 1 : -1;
3555
- const nextIdx = getCurrentIndex(sheet) + direction;
3556
- navigateToPage(sheet, sourceMessage, config, nextIdx);
3557
- persistGroupedProgress(sheet);
3558
- return;
3559
- }
3560
-
3561
- if (action === "submit-all") {
3562
- if (!sessionRef.current) return;
3563
- const toolCallId = sheet.getAttribute("data-tool-call-id") ?? "";
3564
- const sourceMessage = sessionRef.current
3565
- .getMessages()
3566
- .find((m) => m.toolCall?.id === toolCallId);
3567
- if (!sourceMessage) return;
3568
- // Flush any pending free-text on the final page first.
3569
- const freeInput = sheet.querySelector<HTMLInputElement>('[data-ask-free-text-input="true"]');
3570
- const pending = freeInput?.value?.trim() ?? "";
3571
- if (pending) setCurrentAnswer(sheet, pending);
3572
-
3573
- const structured = buildStructuredAnswers(sheet, sourceMessage);
3574
- // Persist final answers to message metadata BEFORE resolving so the
3575
- // answered-state review card (which reads `agentMetadata
3576
- // .askUserQuestionAnswers`) shows the user's actual picks instead of
3577
- // "(skipped)" placeholders. Without this, any answer set only via the
3578
- // pending-flush above (or via paths that bypassed the per-pick persist
3579
- // hook) would be missing from the transcript review even though it
3580
- // landed in the structured payload sent to the agent.
3581
- sessionRef.current.persistAskUserQuestionProgress(sourceMessage, {
3582
- answers: structured,
3583
- currentIndex: getCurrentIndex(sheet),
3584
- });
3585
- const summary = stringifyStructured(structured);
3586
- submitAskUserAnswer(sheet, summary || "(submitted)", {
3587
- source: "submit-all",
3588
- structured,
3589
- });
3590
- return;
3591
- }
3592
-
3593
- if (action === "skip") {
3594
- if (!sessionRef.current) return;
3595
- const toolCallId = sheet.getAttribute("data-tool-call-id") ?? "";
3596
- const sourceMessage = sessionRef.current
3597
- .getMessages()
3598
- .find((m) => m.toolCall?.id === toolCallId);
3599
- if (!sourceMessage) return;
3600
-
3601
- const grouped = isGroupedSheet(sheet);
3602
- const idx = getCurrentIndex(sheet);
3603
- const count = getQuestionCount(sheet);
3604
- const isFinal = idx >= count - 1;
3605
-
3606
- // Single-question payloads behave like dismiss.
3607
- if (!grouped) {
3608
- mount.dispatchEvent(
3609
- new CustomEvent("persona:askUserQuestion:dismissed", {
3610
- detail: { toolUseId: toolCallId },
3611
- bubbles: true,
3612
- composed: true,
3613
- })
3614
- );
3615
- removeAskUserQuestionSheet(askUserOverlay, toolCallId);
3616
- if (sourceMessage.agentMetadata?.awaitingLocalTool) {
3617
- sessionRef.current.markAskUserQuestionResolved(sourceMessage);
3618
- sessionRef.current.resolveAskUserQuestion(sourceMessage, "(dismissed)");
3370
+ if (askUserEventPending) return;
3371
+ askUserEventPending = true;
3372
+ loadUiExtras().then(
3373
+ (m) => {
3374
+ askUserEventPending = false;
3375
+ if (sheet.isConnected) run(m);
3376
+ },
3377
+ () => {
3378
+ askUserEventPending = false;
3619
3379
  }
3620
- return;
3621
- }
3622
-
3623
- // Drop the current question's answer (if any) so it's absent from the
3624
- // resolved Record. setCurrentAnswer with an empty string deletes the
3625
- // index from the in-memory map.
3626
- setCurrentAnswer(sheet, "");
3627
- // Also clear any unsubmitted free-text on this page.
3628
- const freeInput = sheet.querySelector<HTMLInputElement>('[data-ask-free-text-input="true"]');
3629
- if (freeInput) freeInput.value = "";
3630
-
3631
- if (isFinal) {
3632
- // Submit with whatever has been recorded so far.
3633
- const structured = buildStructuredAnswers(sheet, sourceMessage);
3634
- const summary = stringifyStructured(structured);
3635
- submitAskUserAnswer(sheet, summary || "(skipped)", {
3636
- source: "submit-all",
3637
- structured,
3638
- });
3639
- return;
3640
- }
3641
-
3642
- // Intermediate page: advance one step without recording.
3643
- navigateToPage(sheet, sourceMessage, config, idx + 1);
3644
- persistGroupedProgress(sheet);
3645
- return;
3646
- }
3647
- });
3648
-
3649
- // Enter on the free-text input → submit. Stays on the overlay because the
3650
- // event target IS the input, which lives inside the overlay subtree.
3651
- askUserOverlay.addEventListener("keydown", (event) => {
3652
- if (event.key !== "Enter") return;
3653
- const target = event.target as HTMLElement;
3654
- const input = target as HTMLInputElement;
3655
- if (!input.matches?.('[data-ask-free-text-input="true"]')) return;
3656
- const sheet = input.closest<HTMLElement>("[data-persona-ask-sheet-for]");
3657
- if (!sheet) return;
3658
- event.preventDefault();
3659
- const text = input.value;
3660
- if (!text.trim()) return;
3661
- if (isGroupedSheet(sheet)) {
3662
- setCurrentAnswer(sheet, text.trim());
3663
- persistGroupedProgress(sheet);
3664
- maybeAutoAdvance(sheet);
3665
- return;
3666
- }
3667
- submitAskUserAnswer(sheet, text, { source: "free-text" });
3668
- });
3380
+ );
3381
+ };
3382
+ askUserOverlay.addEventListener("click", routeAskUserEvent("click"));
3383
+ askUserOverlay.addEventListener("keydown", routeAskUserEvent("keydown"));
3669
3384
 
3670
3385
  // Digit 1–9 → pick option N on the current rows-layout single-select page.
3671
3386
  // Listens on `document` so the shortcut fires regardless of where focus
@@ -3725,7 +3440,8 @@ export const createAgentExperience = (
3725
3440
  * to cover expanded, collapsed, and dragged widths alike.
3726
3441
  */
3727
3442
  const railedChatMinPx = (): number => {
3728
- const host = railShell && railHost?.isConnected ? railHost : null;
3443
+ const railHost = historyShell?.railShell ? historyShell.railHost : null;
3444
+ const host = railHost?.isConnected ? railHost : null;
3729
3445
  const railPx = host ? host.getBoundingClientRect().width : 0;
3730
3446
  if (railPx <= 0) return ARTIFACT_RESIZE_CHAT_MIN_PX;
3731
3447
  return railPx + ARTIFACT_RESIZE_RAILED_TRANSCRIPT_MIN_PX;
@@ -5353,6 +5069,10 @@ export const createAgentExperience = (
5353
5069
  string,
5354
5070
  { streaming?: boolean; role: AgentWidgetMessage["role"] }
5355
5071
  >();
5072
+ // The live call already showed its AI-disclosure notice; in the composer bar
5073
+ // (no status line) it holds the input placeholder, restored at hang-up.
5074
+ let voiceDisclosed = false;
5075
+ let placeholderBeforeDisclosure: string | null = null;
5356
5076
  const voiceState = {
5357
5077
  active: false,
5358
5078
  manuallyDeactivated: false,
@@ -6580,7 +6300,7 @@ export const createAgentExperience = (
6580
6300
  !message.agentMetadata?.askUserQuestionAnswered
6581
6301
  ) {
6582
6302
  liveAskToolIds.add(message.toolCall.id);
6583
- ensureAskUserQuestionSheet(message, config, panelElements.composerOverlay);
6303
+ mountAskUserSheet(message);
6584
6304
  }
6585
6305
  return;
6586
6306
  }
@@ -6693,7 +6413,7 @@ export const createAgentExperience = (
6693
6413
  !message.agentMetadata?.askUserQuestionAnswered
6694
6414
  ) {
6695
6415
  liveAskToolIds.add(message.toolCall!.id);
6696
- ensureAskUserQuestionSheet(message, config, panelElements.composerOverlay);
6416
+ mountAskUserSheet(message);
6697
6417
  }
6698
6418
  return;
6699
6419
  }
@@ -6716,7 +6436,7 @@ export const createAgentExperience = (
6716
6436
  !message.agentMetadata?.askUserQuestionAnswered
6717
6437
  ) {
6718
6438
  liveAskToolIds.add(message.toolCall!.id);
6719
- ensureAskUserQuestionSheet(message, config, panelElements.composerOverlay);
6439
+ mountAskUserSheet(message);
6720
6440
  }
6721
6441
  return;
6722
6442
  }
@@ -7478,6 +7198,8 @@ export const createAgentExperience = (
7478
7198
  const warmMarkdownParsers = () => {
7479
7199
  if (markdownParsersWarmed) return;
7480
7200
  markdownParsersWarmed = true;
7201
+ // The stream processor is needed for the first reply; warm it too.
7202
+ loadClientStream().catch(() => {});
7481
7203
  loadMarkdownParsers().catch(() => {
7482
7204
  // Failed fetch (ad blocker, offline): allow the next visibility change
7483
7205
  // or render to retry; the chunk loader resets its cached promise on
@@ -8698,7 +8420,10 @@ export const createAgentExperience = (
8698
8420
  };
8699
8421
  let historyInternals: WidgetHistoryInternals = {
8700
8422
  ...(visitorStore ? { visitorStore } : {}),
8701
- historyBootstrapReady,
8423
+ historyBootstrapReady:
8424
+ config.features?.history?.enabled === true && !getHistoryShellSync()
8425
+ ? Promise.all([historyBootstrapReady, historyShellGate]).then(() => {})
8426
+ : historyBootstrapReady,
8702
8427
  getStoredMessageCursor: () => readMetadataString('historyMessageCursor'),
8703
8428
  setStoredMessageCursor: (cursor: string | null) => {
8704
8429
  if (cursor === null) {
@@ -9081,6 +8806,20 @@ export const createAgentExperience = (
9081
8806
 
9082
8807
  switch (status) {
9083
8808
  case 'listening':
8809
+ // A speech-to-speech call discloses that it's an AI, once per call.
8810
+ if (!voiceDisclosed) {
8811
+ const notice = session.getVoiceDisclosure();
8812
+ if (notice) {
8813
+ voiceDisclosed = true;
8814
+ if (isComposerBar()) {
8815
+ placeholderBeforeDisclosure = textarea.placeholder;
8816
+ textarea.placeholder = notice;
8817
+ announce(notice);
8818
+ } else {
8819
+ showComposerNotice(notice, 10_000);
8820
+ }
8821
+ }
8822
+ }
9084
8823
  // A continuous realtime call re-enters `listening` after every spoken
9085
8824
  // reply, so reassert the recording styles here (they were replaced by
9086
8825
  // the `processing`/`speaking` states during the turn). The initial
@@ -9106,6 +8845,11 @@ export const createAgentExperience = (
9106
8845
  micButton?.setAttribute("aria-label", "End voice session");
9107
8846
  } else {
9108
8847
  voiceState.active = false;
8848
+ voiceDisclosed = false;
8849
+ if (placeholderBeforeDisclosure !== null) {
8850
+ textarea.placeholder = placeholderBeforeDisclosure;
8851
+ placeholderBeforeDisclosure = null;
8852
+ }
9109
8853
  removeRuntypeMicStateStyles();
9110
8854
  emitVoiceState("system");
9111
8855
  persistVoiceMetadata();
@@ -9221,71 +8965,13 @@ export const createAgentExperience = (
9221
8965
  // mutation. The lazily loaded Messages view owns the list itself.
9222
8966
  // ==========================================================================
9223
8967
 
9224
- /** Rail needs this much HOST width; below it, rail collapses to panel. */
9225
- const RAIL_MIN_CONTAINER_WIDTH = 720;
9226
- /** Ceiling on the view's ~160ms exit before the close proceeds regardless. */
9227
- const HISTORY_EXIT_TIMEOUT_MS = 250;
9228
-
9229
- let historyShellCopy: ResolvedHistoryShellCopy = resolveHistoryShellCopy(
9230
- config.features?.history?.copy
9231
- );
9232
- let historyProvider: HistoryProvider | null = null;
9233
- let historyUnavailable = false;
9234
- /** Default view + plugin render-hook arbitration. Null while closed. */
9235
- let historySurface: HistoryRenderSurface | null = null;
9236
- let historyOperationContext: HistoryOperationContext | null = null;
9237
- let historyReturnSurface: HistoryReturnSurface = "conversation";
9238
- let historyInvoker: HTMLElement | null = null;
9239
- let historyButton: HTMLButtonElement | null = null;
9240
- /** The inserted node: removing the button alone would orphan its wrapper. */
9241
- let historyButtonWrapper: HTMLElement | null = null;
8968
+ let historyShell: HistoryShell | null = null;
8969
+ let historyShellLoad: Promise<HistoryShell | null> | null = null;
8970
+ let historyShellTornDown = false;
9242
8971
  let historySessionState: SessionHistoryState = session.getHistoryState();
9243
- let historyIdentityKey: string | null = null;
9244
- let historyOpenToken = 0;
9245
- let clearChatDefaultLabel: string | null = null;
9246
- let unsubscribeHistoryAvailability: (() => void) | null = null;
9247
- let unsubscribeHistoryIdentity: (() => void) | null = null;
9248
- const historyRegionId = `persona-history-${Math.random().toString(36).slice(2, 8)}`;
9249
8972
 
9250
8973
  const historyFeatureEnabled = (): boolean =>
9251
8974
  config.features?.history?.enabled === true;
9252
- const historyAvailable = (): boolean =>
9253
- historyFeatureEnabled() && !!historyProvider && !historyUnavailable;
9254
- /** Switching conversations mid-turn would abandon a live answer. */
9255
- const historyTurnBusy = (): boolean => {
9256
- const status = session.getStatus();
9257
- return isStreaming || status === "paused" || status === "resuming";
9258
- };
9259
- const historyScope = (): HistoryScope => {
9260
- const configured = config.features?.history?.scope;
9261
- if (configured) return configured;
9262
- // Derived, not requested: narrow to what the provider advertises rather
9263
- // than asking it for a scope it will reject.
9264
- const derived: HistoryScope = config.getIdentityProof
9265
- ? "verified-user"
9266
- : "browser";
9267
- const scopes = historyProvider?.capabilities.scopes;
9268
- if (!scopes || scopes.includes(derived)) return derived;
9269
- return scopes[0] ?? derived;
9270
- };
9271
- const historyOperationScope = (): HistoryScope =>
9272
- historyOperationContext?.scope ?? historyScope();
9273
- const activeHistoryTargetId = (): string | null =>
9274
- session.getClientSession()?.targetId ?? null;
9275
-
9276
- const identityStatusKey = (status: HistoryIdentityStatus): string =>
9277
- `${status.state}:${"reason" in status ? status.reason : ""}`;
9278
-
9279
- /** Instance-scoped only: authentication state is never broadcast page-wide. */
9280
- const emitHistoryIdentityStatus = (status: HistoryIdentityStatus): void => {
9281
- const key = identityStatusKey(status);
9282
- if (key === historyIdentityKey) return;
9283
- historyIdentityKey = key;
9284
- eventBus.emit("history:identityStatusChanged", {
9285
- status,
9286
- timestamp: Date.now(),
9287
- });
9288
- };
9289
8975
 
9290
8976
  /** Unconditional: `announce()` is gated on an unrelated scroll opt-in. */
9291
8977
  const announceHistory = (message: string): void => {
@@ -9294,529 +8980,6 @@ export const createAgentExperience = (
9294
8980
  liveRegion.textContent = message;
9295
8981
  };
9296
8982
 
9297
- // --- provider ------------------------------------------------------------
9298
-
9299
- /** One provider build per widget instance; a new factory identity rebuilds. */
9300
- let configuredProviderFactory: (() => HistoryProvider) | null = null;
9301
- let configuredProviderInstance: HistoryProvider | null = null;
9302
-
9303
- const buildHistoryProvider = (): HistoryProvider | null => {
9304
- if (!historyFeatureEnabled()) return null;
9305
- // Demo/test override first, then the host's own provider; production
9306
- // without one builds the Runtype provider from client-token config.
9307
- const override = getHistoryProviderFactory();
9308
- if (override) return override();
9309
- const configured = config.features?.history?.provider;
9310
- if (configured) {
9311
- if (typeof configured !== "function") return configured;
9312
- if (configuredProviderFactory !== configured) {
9313
- configuredProviderFactory = configured;
9314
- configuredProviderInstance = configured();
9315
- }
9316
- return configuredProviderInstance;
9317
- }
9318
- if (!session.isClientTokenMode()) return null;
9319
- return createRuntypeHistoryProvider({
9320
- client: session.getClient(),
9321
- getIdentityProofConfigured: () =>
9322
- typeof config.getIdentityProof === "function",
9323
- onActivationCommitted: (clientSession) =>
9324
- session.bindActivatedSession(clientSession),
9325
- // Connection-config rebuilds replace the client under the provider.
9326
- getClient: () => session.getClient(),
9327
- });
9328
- };
9329
-
9330
- const installHistoryProvider = (): void => {
9331
- unsubscribeHistoryAvailability?.();
9332
- unsubscribeHistoryAvailability = null;
9333
- unsubscribeHistoryIdentity?.();
9334
- unsubscribeHistoryIdentity = null;
9335
- historyUnavailable = false;
9336
- historyProvider = buildHistoryProvider();
9337
- const next: WidgetHistoryInternals = { ...historyInternals };
9338
- if (historyProvider) next.historyProvider = historyProvider;
9339
- else delete next.historyProvider;
9340
- historyInternals = next;
9341
- session.setHistoryInternals(historyInternals);
9342
- if (!historyProvider) return;
9343
- unsubscribeHistoryAvailability =
9344
- historyProvider.subscribeAvailability?.((available) => {
9345
- historyUnavailable = !available;
9346
- // A degrade must remove an ALREADY-rendered surface, not just a flag.
9347
- if (!available) closeHistory({ restoreFocus: false });
9348
- syncHistoryChromeImpl();
9349
- }) ?? null;
9350
- unsubscribeHistoryIdentity = historyProvider.subscribeIdentityStatus(
9351
- (status) => emitHistoryIdentityStatus(status)
9352
- );
9353
- historyIdentityKey = identityStatusKey(historyProvider.getIdentityStatus());
9354
- };
9355
-
9356
- // --- presentation hosts --------------------------------------------------
9357
-
9358
- /**
9359
- * Resolved against the history HOST width, never the viewport. With the
9360
- * artifact split mounted the split root is that host, not the container:
9361
- * width the artifact pane borrows from the chat column is still the widget's,
9362
- * so a drag on the split must never read as a narrow host and re-mode the
9363
- * rail. A real window/host narrowing shrinks the split root too, and still
9364
- * flips.
9365
- */
9366
- const resolveHistoryPresentation = (): ResolvedHistoryPresentation => {
9367
- const configured = config.features?.history?.presentation ?? "panel";
9368
- if (configured === "panel") return "panel";
9369
- if (configured === "auto") {
9370
- // Floating launchers stay panel-based at every width.
9371
- const inlineOrDocked = !launcherEnabled || isDockedMountMode(config);
9372
- if (!inlineOrDocked) return "panel";
9373
- }
9374
- const host = artifactSplitRoot ?? container;
9375
- const width = host.getBoundingClientRect().width || host.clientWidth;
9376
- return width >= RAIL_MIN_CONTAINER_WIDTH ? "rail" : "panel";
9377
- };
9378
-
9379
- const setHistoryHostInert = (element: HTMLElement, inert: boolean): void => {
9380
- if (inert) {
9381
- element.setAttribute("aria-hidden", "true");
9382
- element.setAttribute("inert", "");
9383
- } else {
9384
- element.removeAttribute("aria-hidden");
9385
- element.removeAttribute("inert");
9386
- }
9387
- };
9388
-
9389
- /** Suppression of the shell header's own children while Messages owns the bar. */
9390
- const HISTORY_SUPPRESSED_ATTR = "data-persona-history-suppressed";
9391
- /** Shell-owned wrapper for the view's bar contents. Null while not hosting. */
9392
- let historyHeaderHost: HTMLElement | null = null;
9393
- /** Header carrying the swap-time min-height pin. Null while not hosting. */
9394
- let historyPinnedHeader: HTMLElement | null = null;
9395
- /** Handle + arbitrated element, tracked from before `historySurface` is assigned. */
9396
- let historyViewHandle: HistoryViewHandle | null = null;
9397
- let historyMountedElement: HTMLElement | null = null;
9398
- let capturedPanelHeader: HTMLElement | null = null;
9399
- let capturedPanelHeaderDisplay = "";
9400
-
9401
- /** The display the shell header returns to; "none" means there is no bar. */
9402
- const shownHeaderDisplay = (): string =>
9403
- header === capturedPanelHeader
9404
- ? capturedPanelHeaderDisplay
9405
- : config.layout?.showHeader === false
9406
- ? "none"
9407
- : "";
9408
-
9409
- /**
9410
- * One persistent bar: the shell header hosts the view's bar contents whenever
9411
- * the default view owns a panel and there is a visible header to host them in.
9412
- * A plugin's full custom surface owns everything, so it falls back to hiding.
9413
- */
9414
- const historyHeaderExternal = (): boolean =>
9415
- historyPresentation === "panel" &&
9416
- !!historyViewHandle &&
9417
- historyMountedElement === historyViewHandle.element &&
9418
- config.layout?.showHeader !== false &&
9419
- shownHeaderDisplay() !== "none";
9420
-
9421
- const suppressHeaderChildren = (): void => {
9422
- for (const child of Array.from(header.children)) {
9423
- if (child === historyHeaderHost) continue;
9424
- child.setAttribute(HISTORY_SUPPRESSED_ATTR, "");
9425
- }
9426
- };
9427
-
9428
- /** By attribute, not by captured list: the header may have been rebuilt. */
9429
- const unsuppressHeaderChildren = (): void => {
9430
- for (const node of Array.from(
9431
- container.querySelectorAll(`[${HISTORY_SUPPRESSED_ATTR}]`)
9432
- )) {
9433
- node.removeAttribute(HISTORY_SUPPRESSED_ATTR);
9434
- }
9435
- };
9436
-
9437
- const hostHistoryHeaderContent = (): void => {
9438
- const view = historyViewHandle;
9439
- if (!view) return;
9440
- // Pin the pre-swap height so the contents swap never moves the chrome: the
9441
- // hosted bar is usually shorter than the title cluster it replaces, and
9442
- // constant-height chrome is what keeps the switch from reading as layout
9443
- // shift. Measurable only while the original contents are still visible; a
9444
- // re-entry on an already-hosted header keeps the standing pin, and a
9445
- // rebuilt header re-measures before its own suppression below.
9446
- const originalsVisible = Array.from(header.children).some(
9447
- (child) =>
9448
- child !== historyHeaderHost &&
9449
- !child.hasAttribute(HISTORY_SUPPRESSED_ATTR)
9450
- );
9451
- if (originalsVisible) {
9452
- if (historyPinnedHeader && historyPinnedHeader !== header) {
9453
- historyPinnedHeader.style.removeProperty("min-height");
9454
- historyPinnedHeader = null;
9455
- }
9456
- const measured = header.offsetHeight;
9457
- if (measured > 0) {
9458
- header.style.minHeight = `${measured}px`;
9459
- historyPinnedHeader = header;
9460
- }
9461
- }
9462
- if (!historyHeaderHost) {
9463
- historyHeaderHost = createElement("div", "persona-history-header-host");
9464
- }
9465
- view.setHeaderPlacement("external");
9466
- const content = view.getHeaderElement();
9467
- if (content.parentNode !== historyHeaderHost) {
9468
- historyHeaderHost.replaceChildren(content);
9469
- }
9470
- // The wrapper follows a rebuilt header binding; focus inside it survives.
9471
- if (historyHeaderHost.parentNode !== header) {
9472
- header.appendChild(historyHeaderHost);
9473
- }
9474
- suppressHeaderChildren();
9475
- };
9476
-
9477
- const releaseHistoryHeaderContent = (): void => {
9478
- if (historyPinnedHeader) {
9479
- historyPinnedHeader.style.removeProperty("min-height");
9480
- historyPinnedHeader = null;
9481
- }
9482
- if (!historyHeaderHost) return;
9483
- // The view re-adopts its bar; the wrapper never owns the content's lifetime.
9484
- historyViewHandle?.setHeaderPlacement("inline");
9485
- historyHeaderHost.remove();
9486
- historyHeaderHost = null;
9487
- unsuppressHeaderChildren();
9488
- };
9489
-
9490
- /**
9491
- * Panel presentation obscures the conversation, so the transcript AND the
9492
- * composer must be unreachable: a visitor must never send into a conversation
9493
- * they cannot see. The header bar itself stays: only its contents swap, which
9494
- * is also why it is never inert here (rail changes nothing at all: the
9495
- * conversation stays primary).
9496
- *
9497
- * The widget's close (×) usually lives inside that header, but no trap
9498
- * results: the view's back control is the initial focus target, Escape exits,
9499
- * and both restore the header contents before focus lands. `top-right` close
9500
- * placement parents the × to the container, so it stays reachable either way.
9501
- *
9502
- * Restores exactly what it captured.
9503
- */
9504
- let restorePanelHost: (() => void) | null = null;
9505
- const enforcePanelHost = (): void => {
9506
- if (!restorePanelHost) return;
9507
- body.style.display = "none";
9508
- setHistoryHostInert(body, true);
9509
- // Live `footer` / `header` bindings: a composer-plugin rebuild or a
9510
- // header-layout rebuild swaps them and re-enters here for the replacement.
9511
- footer.hidden = true;
9512
- setHistoryHostInert(footer, true);
9513
- if (historyHeaderExternal()) {
9514
- hostHistoryHeaderContent();
9515
- header.style.display = shownHeaderDisplay();
9516
- setHistoryHostInert(header, false);
9517
- return;
9518
- }
9519
- // No bar to host in: hide the header the way the surface used to.
9520
- releaseHistoryHeaderContent();
9521
- header.style.display = "none";
9522
- setHistoryHostInert(header, true);
9523
- };
9524
- reapplyHistoryHostChrome = enforcePanelHost;
9525
-
9526
- const mountPanelHost = (element: HTMLElement): void => {
9527
- const previousDisplay = body.style.display;
9528
- const previousFooterHidden = footer.hidden;
9529
- const capturedFooter = footer;
9530
- const capturedHeader = header;
9531
- const previousHeaderDisplay = header.style.display;
9532
- capturedPanelHeader = capturedHeader;
9533
- capturedPanelHeaderDisplay = previousHeaderDisplay;
9534
- restorePanelHost = () => {
9535
- restorePanelHost = null;
9536
- releaseHistoryHeaderContent();
9537
- capturedPanelHeader = null;
9538
- body.style.display = previousDisplay;
9539
- setHistoryHostInert(body, false);
9540
- capturedFooter.hidden = previousFooterHidden;
9541
- setHistoryHostInert(capturedFooter, false);
9542
- if (footer !== capturedFooter) {
9543
- footer.hidden = false;
9544
- setHistoryHostInert(footer, false);
9545
- }
9546
- capturedHeader.style.display = previousHeaderDisplay;
9547
- setHistoryHostInert(capturedHeader, false);
9548
- if (header !== capturedHeader) {
9549
- // A replacement carries no captured state; only config decides it.
9550
- header.style.display = config.layout?.showHeader === false ? "none" : "";
9551
- setHistoryHostInert(header, false);
9552
- }
9553
- };
9554
- footer.parentNode?.insertBefore(element, footer);
9555
- enforcePanelHost();
9556
- };
9557
-
9558
- let railShell: HTMLElement | null = null;
9559
- let railHost: HTMLElement | null = null;
9560
- let railColumn: HTMLElement | null = null;
9561
- /** Stand-in element holding the docked column while the chunk loads. */
9562
- let railPlaceholder: HTMLElement | null = null;
9563
- /** Container order the rail borrows from and hands back, header first. */
9564
- const railBorrowed = (): Array<HTMLElement | null> => [
9565
- header,
9566
- panelElements.closeButtonWrapper,
9567
- panelElements.clearChatButtonWrapper,
9568
- body,
9569
- // Composer-bar mode keeps the footer outside the container; the parent
9570
- // checks below then never adopt it.
9571
- footer,
9572
- ];
9573
-
9574
- /** Collapsed icon rail, measured from the reference sidebar. */
9575
- const RAIL_COLLAPSED_WIDTH = 52;
9576
- const railCollapsible = (): boolean =>
9577
- config.features?.history?.rail?.collapsible !== false;
9578
- const railSide = (): "left" | "right" =>
9579
- config.features?.history?.rail?.side === "right" ? "right" : "left";
9580
- /** The band a rail width may take, by config or by drag. */
9581
- const RAIL_MIN_WIDTH = 200;
9582
- const RAIL_MAX_WIDTH = 400;
9583
- const clampRailWidth = (value: number): number =>
9584
- Math.min(RAIL_MAX_WIDTH, Math.max(RAIL_MIN_WIDTH, Math.round(value)));
9585
-
9586
- const railResizable = (): boolean =>
9587
- config.features?.history?.rail?.resizable === true;
9588
- /** Resolved once per widget: storage, else nothing. */
9589
- let railWidthChoice: number | null | undefined;
9590
-
9591
- // Same teaser pattern as the collapsed state: blocked storage throws rather
9592
- // than fails, so the resolved value is also the in-memory fallback.
9593
- const storedRailWidth = (): number | null => {
9594
- if (railWidthChoice === undefined) {
9595
- railWidthChoice = null;
9596
- if (config.persistState !== false) {
9597
- try {
9598
- const stored = Number(
9599
- window.localStorage.getItem(`${currentKeyPrefix()}rail-width`)
9600
- );
9601
- if (stored) railWidthChoice = stored;
9602
- } catch {
9603
- /* blocked storage: the config width stands */
9604
- }
9605
- }
9606
- }
9607
- return railWidthChoice;
9608
- };
9609
-
9610
- /**
9611
- * Expanded rail width, shared by the column and the floating overlay. A
9612
- * dragged width outranks config, the way the collapsed state does: a live
9613
- * `update()` must not undo what the visitor chose.
9614
- */
9615
- const railWidth = (): number =>
9616
- clampRailWidth(
9617
- storedRailWidth() ?? config.features?.history?.rail?.width ?? 260
9618
- );
9619
-
9620
- const setStoredRailWidth = (next: number): void => {
9621
- railWidthChoice = next;
9622
- if (config.persistState === false) return;
9623
- try {
9624
- window.localStorage.setItem(`${currentKeyPrefix()}rail-width`, String(next));
9625
- } catch {
9626
- /* blocked storage: the in-memory value above is the fallback */
9627
- }
9628
- };
9629
- /**
9630
- * Overlay mode: the collapsed rail is a trigger in the conversation header
9631
- * plus a floating host, so there is no icon column and no mounted view at
9632
- * rest. `collapsed` then means "not pinned".
9633
- */
9634
- const railOverlayMode = (): boolean =>
9635
- railCollapsible() &&
9636
- config.features?.history?.rail?.collapsedBehavior === "overlay";
9637
- /** True while the view is mounted in the floating host, not a rail column. */
9638
- let railOverlayOpen = false;
9639
-
9640
- /** Decorative image for a config-supplied rail icon or brand URL. */
9641
- const railIconImage = (src: string): HTMLImageElement => {
9642
- const image = createElement("img");
9643
- image.src = src;
9644
- image.alt = "";
9645
- image.setAttribute("aria-hidden", "true");
9646
- return image;
9647
- };
9648
-
9649
- /**
9650
- * One brand declaration, resolved here where the lucide registry lives, into
9651
- * the callback both rail placements call: the expanded heading and the
9652
- * collapsed toggle's rest face. Precedence render > iconUrl > icon; the
9653
- * icon cases resolve once (so an unknown name warns once) and each caller
9654
- * gets its own copy, since both faces can be in the DOM at once.
9655
- */
9656
- const railBrandNode = ():
9657
- | ((collapsed: boolean) => Element | null)
9658
- | undefined => {
9659
- const brand = config.features?.history?.rail?.brand;
9660
- if (!brand) return undefined;
9661
- let warned = false;
9662
- let mark: Element | null | undefined;
9663
- return (collapsed) => {
9664
- if (brand.render) {
9665
- try {
9666
- return brand.render({ collapsed }) ?? null;
9667
- } catch (error) {
9668
- if (!warned) {
9669
- warned = true;
9670
- console.warn("[persona] history rail brand threw", error);
9671
- }
9672
- return null;
9673
- }
9674
- }
9675
- if (mark === undefined) {
9676
- if (brand.iconUrl) mark = railIconImage(brand.iconUrl);
9677
- else mark = brand.icon ? renderLucideIcon(brand.icon, 20) : null;
9678
- }
9679
- return mark ? (mark.cloneNode(true) as Element) : null;
9680
- };
9681
- };
9682
-
9683
- /**
9684
- * Config nav sections, normalized for the size-capped chunk: icon precedence
9685
- * (renderIcon > iconUrl > icon) collapses to one memoized thunk resolved
9686
- * here, where the lucide registry already lives, and every host callback gets
9687
- * a warn-once-per-section guard.
9688
- */
9689
- const configNavSections = (): HistoryRailSection[] =>
9690
- config.features?.history?.rail?.sections?.map((section) => {
9691
- let warned = false;
9692
- const warn = (error: unknown): void => {
9693
- if (warned) return;
9694
- warned = true;
9695
- console.warn("[persona] history rail section threw", section.id, error);
9696
- };
9697
- return {
9698
- id: section.id,
9699
- title: section.title,
9700
- placement: section.placement ?? "above-conversations",
9701
- items: section.items.map((item) => {
9702
- // Built on first paint and cached: an unknown lucide name warns once,
9703
- // and a presentation flip reuses the node it made.
9704
- let node: Element | null | undefined;
9705
- return {
9706
- id: item.id,
9707
- label: item.label,
9708
- badge: item.badge,
9709
- iconNode: (): Element | null => {
9710
- if (node !== undefined) return node;
9711
- try {
9712
- if (item.renderIcon) node = item.renderIcon() ?? null;
9713
- else if (item.iconUrl) node = railIconImage(item.iconUrl);
9714
- else node = item.icon ? renderLucideIcon(item.icon, 20) : null;
9715
- } catch (error) {
9716
- warn(error);
9717
- node = null;
9718
- }
9719
- return node;
9720
- },
9721
- onSelect: () => {
9722
- try {
9723
- item.onSelect();
9724
- } catch (error) {
9725
- warn(error);
9726
- }
9727
- },
9728
- };
9729
- }),
9730
- };
9731
- }) ?? [];
9732
-
9733
- /** One array for the chunk: config sections first in each placement bucket. */
9734
- const railNavSections = (
9735
- pluginSections: HistoryRailSection[]
9736
- ): HistoryRailSection[] | undefined => {
9737
- const sections = configNavSections();
9738
- for (const section of pluginSections) {
9739
- // Config owns the id space; a colliding plugin section is dropped.
9740
- if (sections.some((existing) => existing.id === section.id)) {
9741
- console.warn("[persona] duplicate history rail section id", section.id);
9742
- } else sections.push(section);
9743
- }
9744
- return sections.length ? sections : undefined;
9745
- };
9746
-
9747
- /** Resolved once per widget: storage, else the configured default. */
9748
- let railCollapsed: boolean | null = null;
9749
-
9750
- const railCollapseKey = (): string => `${currentKeyPrefix()}rail-collapsed`;
9751
-
9752
- // localStorage access throws (not just fails) in Safari private mode and
9753
- // partitioned iframes, so the resolved value is also the in-memory fallback.
9754
- const isRailCollapsed = (): boolean => {
9755
- if (railCollapsed === null) {
9756
- railCollapsed = config.features?.history?.rail?.defaultCollapsed === true;
9757
- if (config.persistState !== false) {
9758
- try {
9759
- const stored = window.localStorage.getItem(railCollapseKey());
9760
- if (stored) railCollapsed = stored === "1";
9761
- } catch {
9762
- /* blocked storage: the resolved default stands */
9763
- }
9764
- }
9765
- }
9766
- return railCollapsed;
9767
- };
9768
-
9769
- const setRailCollapsed = (next: boolean): void => {
9770
- railCollapsed = next;
9771
- if (config.persistState === false) return;
9772
- try {
9773
- window.localStorage.setItem(railCollapseKey(), next ? "1" : "0");
9774
- } catch {
9775
- /* blocked storage: the in-memory value above is the fallback */
9776
- }
9777
- };
9778
-
9779
- /**
9780
- * Collapsed only ever applies to a collapsible rail presentation, and never
9781
- * in overlay mode, where a mounted rail is always the expanded one.
9782
- */
9783
- const railShowsCollapsed = (): boolean =>
9784
- historyPresentation === "rail" &&
9785
- railCollapsible() &&
9786
- !railOverlayMode() &&
9787
- isRailCollapsed();
9788
-
9789
- /** Overlay-mode counterpart, assigned with the overlay controller below. */
9790
- let toggleRailPinned: () => void = () => {};
9791
-
9792
- const toggleRailCollapsed = (): void => {
9793
- // The rail's own toggle sits where the trigger does, so in overlay mode it
9794
- // is that control: it pins a floating rail and unpins a docked one.
9795
- if (railOverlayMode()) {
9796
- toggleRailPinned();
9797
- return;
9798
- }
9799
- setRailCollapsed(!isRailCollapsed());
9800
- historySurface?.view.setCollapsed(railShowsCollapsed());
9801
- applyRailChrome();
9802
- // The transcript column resizes beside the anchor; a clamp would bounce it.
9803
- repinAnchoredMessage();
9804
- };
9805
-
9806
- /**
9807
- * One declaration, three artifacts: the binding below, the toggle's tooltip
9808
- * hint chip, and its `aria-keyshortcuts`. Null when unset or unparseable.
9809
- */
9810
- const railCollapseShortcut = (): {
9811
- combo: string;
9812
- hint: string;
9813
- aria: string;
9814
- } | null => {
9815
- const combo = config.features?.history?.rail?.collapseShortcut;
9816
- if (!combo || !parseCombo(combo)) return null;
9817
- return { combo, hint: formatCombo(combo), aria: ariaCombo(combo) };
9818
- };
9819
-
9820
8983
  /**
9821
8984
  * Every binding this instance owns, re-derived so a live `update()` of the
9822
8985
  * config or the plugin list lands. Config registers before plugins, so a
@@ -9825,8 +8988,10 @@ export const createAgentExperience = (
9825
8988
  const syncShortcuts = (): void => {
9826
8989
  releaseShortcuts.forEach((release) => release());
9827
8990
  releaseShortcuts = [];
9828
- const shortcut = railCollapseShortcut();
9829
- if (shortcut) {
8991
+ // The rail collapse combo belongs to the (lazy) history shell.
8992
+ const shell = historyShell;
8993
+ const shortcut = shell?.railCollapseShortcut();
8994
+ if (shell && shortcut) {
9830
8995
  releaseShortcuts.push(
9831
8996
  shortcuts.register({
9832
8997
  id: "history-rail-collapse",
@@ -9840,10 +9005,12 @@ export const createAgentExperience = (
9840
9005
  when: () =>
9841
9006
  (historyVisible &&
9842
9007
  historyPresentation === "rail" &&
9843
- railCollapsible()) ||
9844
- railTriggerApplies(),
9008
+ shell.railCollapsible()) ||
9009
+ shell.railTriggerApplies(),
9845
9010
  run: () =>
9846
- railOverlayMode() ? toggleRailPinned() : toggleRailCollapsed(),
9011
+ shell.railOverlayMode()
9012
+ ? shell.toggleRailPinned()
9013
+ : shell.toggleRailCollapsed(),
9847
9014
  })
9848
9015
  );
9849
9016
  }
@@ -9875,946 +9042,6 @@ export const createAgentExperience = (
9875
9042
  };
9876
9043
  syncShortcuts();
9877
9044
 
9878
- // --- collapsed rail as a floating overlay --------------------------------
9879
- //
9880
- // Rest state is a trigger at the leading edge of the conversation header and
9881
- // nothing else: no column, no mounted view, and the history chunk unloaded
9882
- // until a hover warms it. The pointer entering floats the expanded rail over
9883
- // the conversation; clicking pins it back into the full-height column.
9884
-
9885
- /** Grace before a pointer that left both surfaces dismisses the rail. */
9886
- const RAIL_OVERLAY_GRACE_MS = 300;
9887
- /**
9888
- * Gap from the trigger, the docked edge and the bottom. A var reference, not
9889
- * a number, so a live theme update reaches an open overlay unaided.
9890
- */
9891
- const RAIL_OVERLAY_MARGIN = "var(--persona-history-overlay-margin,8px)";
9892
-
9893
- let railTriggerButton: HTMLButtonElement | null = null;
9894
- let railTriggerWrapper: HTMLElement | null = null;
9895
- /** Docking opens awaiting the history chunk; the trigger hides for them. */
9896
- let railPinPendingOpens = 0;
9897
- let railOverlayHost: HTMLElement | null = null;
9898
- let railGraceTimer: ReturnType<typeof setTimeout> | null = null;
9899
- /** Pointer is over the trigger or over the floating rail. */
9900
- let railPointerInside = false;
9901
- /**
9902
- * Uncovering the trigger re-enters it with no pointer movement at all, which
9903
- * would undo the dismissal that just uncovered it. That synthetic enter
9904
- * arrives within a frame or two of the unmount.
9905
- */
9906
- let railUncoveredUntil = 0;
9907
-
9908
- /** Touch has no hover to open with, so it taps the overlay open instead. */
9909
- const coarsePointer = (): boolean =>
9910
- window.matchMedia?.("(pointer: coarse)").matches === true;
9911
-
9912
- /** The trigger stands in for the collapsed rail, so it needs a rail width. */
9913
- const railTriggerApplies = (): boolean =>
9914
- historyAvailable() &&
9915
- railOverlayMode() &&
9916
- (historyPresentation ?? resolveHistoryPresentation()) === "rail";
9917
-
9918
- /** Docked in its own column rather than floating over the conversation. */
9919
- const railPinned = (): boolean => historyVisible && !railOverlayOpen;
9920
-
9921
- const cancelRailGrace = (): void => {
9922
- if (railGraceTimer !== null) clearTimeout(railGraceTimer);
9923
- railGraceTimer = null;
9924
- };
9925
-
9926
- /** Keyboard focus warms without opening; Enter and Space commit. */
9927
- const warmHistoryChunk = (): void => {
9928
- // A failed load just leaves the overlay closed; the loader retries later.
9929
- void loadHistoryView().catch(() => {});
9930
- };
9931
-
9932
- /** Leaving both surfaces dismisses, but only after a grace to come back in. */
9933
- const scheduleRailOverlayClose = (): void => {
9934
- cancelRailGrace();
9935
- if (!railOverlayOpen) return;
9936
- railGraceTimer = setTimeout(() => {
9937
- railGraceTimer = null;
9938
- if (railPointerInside || !railOverlayOpen) return;
9939
- // A keyboard visitor inside the floating rail never loses it to a stray
9940
- // pointer leaving the widget.
9941
- if (railOverlayHost?.contains(document.activeElement)) return;
9942
- // A pointer dismissal moves focus no more than a pointer open does.
9943
- closeHistory({ restoreFocus: false });
9944
- }, RAIL_OVERLAY_GRACE_MS);
9945
- };
9946
-
9947
- /**
9948
- * Hover keep-alive is geometric, not element-based: a pointer travelling
9949
- * from the trigger to the rail crosses the conversation header, which is
9950
- * neither. The safe zone is the trigger, the rail, and the bridge between
9951
- * them: the rail's own horizontal extent, from the trigger's row down to the
9952
- * rail's top edge. Derived from the live rects, so a right-docked rail needs
9953
- * no separate case.
9954
- */
9955
- const inRailSafeZone = (x: number, y: number): boolean => {
9956
- const rail = railOverlayHost?.getBoundingClientRect();
9957
- if (!rail) return false;
9958
- const row = railTriggerButton?.getBoundingClientRect();
9959
- // The rail and the bridge are one band: the rail's own width, from the
9960
- // trigger's row down to the rail's bottom. The trigger is its own rect.
9961
- const top = row ? Math.min(row.top, rail.top) : rail.top;
9962
- return (
9963
- (x >= rail.left && x <= rail.right && y >= top && y <= rail.bottom) ||
9964
- (!!row && x >= row.left && x <= row.right && y >= row.top && y <= row.bottom)
9965
- );
9966
- };
9967
-
9968
- const handleRailPointerMove = (event: PointerEvent): void => {
9969
- if (!railOverlayOpen) return;
9970
- railPointerInside = inRailSafeZone(event.clientX, event.clientY);
9971
- if (railPointerInside) cancelRailGrace();
9972
- // Re-arming on every outside move would restart the countdown forever.
9973
- else if (railGraceTimer === null) scheduleRailOverlayClose();
9974
- };
9975
-
9976
- /**
9977
- * No dwell: the rail answers the pointer the moment it arrives, as fast as
9978
- * the chunk allows (already loaded, that is the same frame). The 300ms leave
9979
- * grace is what an accidental pass over the trigger costs.
9980
- */
9981
- const openRailOverlay = (opts?: { keyboard?: boolean }): void => {
9982
- if (historyVisible || !railTriggerApplies()) return;
9983
- railOverlayOpen = true;
9984
- void openHistory({
9985
- invoker: railTriggerButton,
9986
- keyboard: opts?.keyboard === true,
9987
- }).then(() => {
9988
- // The chunk can resolve after the pointer left, or not resolve at all.
9989
- if (!historyVisible) railOverlayOpen = false;
9990
- else if (!railPointerInside && document.activeElement !== railTriggerButton) {
9991
- closeHistory();
9992
- }
9993
- });
9994
- };
9995
-
9996
- /**
9997
- * Floating, the rail's own toggle pins instead of collapsing, so it wears
9998
- * the expand label; docked, it says collapse again.
9999
- */
10000
- const syncRailToggleLabel = (): void => {
10001
- // The mounted element, not the surface: the first mount happens inside the
10002
- // surface constructor, before `historySurface` is assigned.
10003
- const toggle = historyMountedElement?.querySelector(
10004
- '[data-persona-history-focus="collapse"]'
10005
- );
10006
- if (!toggle) return;
10007
- toggle.setAttribute(
10008
- "aria-label",
10009
- railOverlayOpen
10010
- ? historyShellCopy.expandLabel
10011
- : historyShellCopy.collapseLabel
10012
- );
10013
- toggle.setAttribute("aria-expanded", railOverlayOpen ? "false" : "true");
10014
- };
10015
-
10016
- /**
10017
- * Pin: the floating rail gives way to the full-height column, moving the
10018
- * SAME view element when one is already open.
10019
- */
10020
- const pinRail = (): void => {
10021
- setRailCollapsed(false);
10022
- const surface = historySurface;
10023
- if (!railOverlayOpen || !surface) {
10024
- void openHistory({ invoker: railTriggerButton });
10025
- return;
10026
- }
10027
- const refocus = document.activeElement === railTriggerButton;
10028
- railOverlayOpen = false;
10029
- unmountHistoryHosts();
10030
- // Detach before re-hosting, exactly as the panel/rail move does.
10031
- surface.element.remove();
10032
- mountHistoryElement(surface.element);
10033
- syncRailToggleLabel();
10034
- // The trigger stands down beside the rail's own toggle, so keyboard focus
10035
- // has to follow the control there.
10036
- if (refocus) focusHistoryEntry();
10037
- repinAnchoredMessage();
10038
- syncHistoryChromeImpl();
10039
- };
10040
-
10041
- /** Unpin: the column closes and the trigger takes the control back. */
10042
- const unpinRail = (): void => {
10043
- setRailCollapsed(true);
10044
- closeHistory();
10045
- };
10046
-
10047
- toggleRailPinned = (): void => {
10048
- if (!historyVisible || railOverlayOpen) pinRail();
10049
- else unpinRail();
10050
- };
10051
-
10052
- /**
10053
- * The sidebar glyph, plainly. `rail.brand` belongs to the icon column, which
10054
- * has no other identity, and to the rail's own header; this control sits in
10055
- * a conversation header that already carries the agent's.
10056
- */
10057
- const buildRailTrigger = (): void => {
10058
- const shortcut = railCollapseShortcut();
10059
- const parts = createHeaderIconButton({
10060
- ariaLabel: historyShellCopy.expandLabel,
10061
- iconName: "panel-left",
10062
- wrapperClassName:
10063
- "persona-relative persona-inline-flex persona-items-center persona-justify-center",
10064
- extraClassName: "persona-rail-trigger",
10065
- // Hovering answers with the rail itself; a bubble would race the flyover.
10066
- // The combo stays discoverable on the floating rail's own toggle.
10067
- tooltip: false,
10068
- attrs: {
10069
- "data-persona-rail-trigger": "",
10070
- "aria-controls": historyRegionId,
10071
- ...(shortcut ? { "aria-keyshortcuts": shortcut.aria } : {}),
10072
- },
10073
- });
10074
- const button = parts.button;
10075
- button.addEventListener("mouseenter", () => {
10076
- railPointerInside = true;
10077
- cancelRailGrace();
10078
- if (coarsePointer() || Date.now() < railUncoveredUntil) return;
10079
- openRailOverlay();
10080
- });
10081
- button.addEventListener("mouseleave", () => {
10082
- railPointerInside = false;
10083
- // A real departure ends the hold-off: the next enter is intent.
10084
- railUncoveredUntil = 0;
10085
- scheduleRailOverlayClose();
10086
- });
10087
- // Focus only warms: Enter and Space are how a keyboard visitor commits.
10088
- button.addEventListener("focus", () => {
10089
- if (!historyVisible) warmHistoryChunk();
10090
- });
10091
- button.addEventListener("click", (event) => {
10092
- if (!historyAvailable()) return;
10093
- // Touch taps the overlay open first and pins on a second tap. A pointer
10094
- // that can hover is already looking at the rail, and Enter/Space (a click
10095
- // with detail 0) is a commitment either way, so both pin outright.
10096
- if (event.detail !== 0 && coarsePointer() && !historyVisible) {
10097
- openRailOverlay();
10098
- } else pinRail();
10099
- });
10100
- railTriggerButton = button;
10101
- railTriggerWrapper = parts.wrapper;
10102
- };
10103
-
10104
- /**
10105
- * The trigger is chrome, not surface state: it exists whenever a collapsed
10106
- * overlay rail could be opened, and stands down only while the rail is
10107
- * docked, where the rail's own header toggle is the same control.
10108
- */
10109
- const syncRailOverlayTrigger = (): void => {
10110
- // A header rebuild detaches it; a stale ref must not block recreation.
10111
- if (railTriggerWrapper && !railTriggerWrapper.isConnected) {
10112
- railTriggerWrapper = null;
10113
- railTriggerButton = null;
10114
- }
10115
- if (!railTriggerApplies()) {
10116
- railTriggerWrapper?.remove();
10117
- railTriggerWrapper = null;
10118
- railTriggerButton = null;
10119
- return;
10120
- }
10121
- if (!railTriggerButton) buildRailTrigger();
10122
- const wrapper = railTriggerWrapper;
10123
- const button = railTriggerButton;
10124
- if (!wrapper || !button) return;
10125
- // Leading edge of the conversation header, mirrored for a right rail.
10126
- const lead = railSide() !== "right" ? header.firstChild : null;
10127
- if ((lead ?? header.lastChild) !== wrapper) header.insertBefore(wrapper, lead);
10128
- wrapper.style.display =
10129
- railPinned() || railPinPendingOpens > 0 ? "none" : "";
10130
- button.setAttribute("aria-label", historyShellCopy.expandLabel);
10131
- button.setAttribute("aria-expanded", historyVisible ? "true" : "false");
10132
- // The floating rail hangs from this control, so a rebuild or a resize that
10133
- // moved it re-anchors what is already open.
10134
- if (railOverlayHost) applyRailChrome();
10135
- };
10136
-
10137
- /**
10138
- * Click outside dismisses the floating rail. Portaled surfaces it opened
10139
- * itself (row menus, confirmations) are not "outside" it.
10140
- */
10141
- const handleRailOverlayPointerDown = (event: Event): void => {
10142
- if (!railOverlayOpen) return;
10143
- const target = event.target;
10144
- if (!(target instanceof Node)) return;
10145
- if (railOverlayHost?.contains(target) || railTriggerWrapper?.contains(target)) {
10146
- return;
10147
- }
10148
- if (
10149
- target instanceof Element &&
10150
- target.closest('.persona-dropdown-menu,[role="alertdialog"]')
10151
- ) {
10152
- return;
10153
- }
10154
- closeHistory({ restoreFocus: false });
10155
- };
10156
- document.addEventListener("pointerdown", handleRailOverlayPointerDown, true);
10157
- destroyCallbacks.push(() => {
10158
- document.removeEventListener("pointerdown", handleRailOverlayPointerDown, true);
10159
- // Attached only while the rail floats; removing an unattached one is free.
10160
- document.removeEventListener("pointermove", handleRailPointerMove);
10161
- railResizeRelease?.();
10162
- cancelRailGrace();
10163
- });
10164
-
10165
- // --- drag-resize of the docked rail --------------------------------------
10166
-
10167
- let railResizeHandle: HTMLElement | null = null;
10168
- /** Ends an in-flight drag: its listeners are on the document, not the handle. */
10169
- let railResizeRelease: (() => void) | null = null;
10170
- /** Arrow-key step, matching the reference sidebar's coarse nudge. */
10171
- const RAIL_RESIZE_STEP = 16;
10172
-
10173
- const commitRailWidth = (next: number): void => {
10174
- setStoredRailWidth(clampRailWidth(next));
10175
- applyRailChrome();
10176
- // The transcript resized beside the anchor; a clamp would bounce it.
10177
- repinAnchoredMessage();
10178
- };
10179
-
10180
- /** Mirrors the artifact split handle: pointer capture, document-level drag. */
10181
- const buildRailResizeHandle = (): HTMLElement => {
10182
- const handle = createElement("div", "persona-rail-resizer");
10183
- handle.tabIndex = 0;
10184
- handle.setAttribute("role", "separator");
10185
- handle.setAttribute("aria-orientation", "vertical");
10186
- handle.setAttribute("aria-valuemin", String(RAIL_MIN_WIDTH));
10187
- handle.setAttribute("aria-valuemax", String(RAIL_MAX_WIDTH));
10188
-
10189
- handle.addEventListener("pointerdown", (event) => {
10190
- const host = railHost;
10191
- if (!host || event.button !== 0) return;
10192
- event.preventDefault();
10193
- railResizeRelease?.();
10194
- const startX = event.clientX;
10195
- const startWidth = host.getBoundingClientRect().width || railWidth();
10196
- // A leading rail widens as the pointer travels right; a trailing one
10197
- // mirrors that.
10198
- const direction = railSide() === "right" ? -1 : 1;
10199
- let width = startWidth;
10200
- const doc = mount.ownerDocument;
10201
- // The collapse animation is a transition on this very basis; left on, it
10202
- // would trail the pointer for the whole drag.
10203
- host.style.transition = "none";
10204
- const onMove = (move: PointerEvent): void => {
10205
- width = clampRailWidth(startWidth + direction * (move.clientX - startX));
10206
- // Straight onto the basis: a chrome pass per pointer move is waste.
10207
- host.style.flex = `0 0 ${width}px`;
10208
- handle.setAttribute("aria-valuenow", String(width));
10209
- };
10210
- const onUp = (): void => {
10211
- railResizeRelease = null;
10212
- doc.removeEventListener("pointermove", onMove);
10213
- doc.removeEventListener("pointerup", onUp);
10214
- doc.removeEventListener("pointercancel", onUp);
10215
- host.style.removeProperty("transition");
10216
- try {
10217
- handle.releasePointerCapture(event.pointerId);
10218
- } catch {
10219
- /* the capture may already be gone */
10220
- }
10221
- commitRailWidth(width);
10222
- };
10223
- railResizeRelease = onUp;
10224
- doc.addEventListener("pointermove", onMove);
10225
- doc.addEventListener("pointerup", onUp);
10226
- doc.addEventListener("pointercancel", onUp);
10227
- try {
10228
- handle.setPointerCapture(event.pointerId);
10229
- } catch {
10230
- /* pointer capture is an enhancement, not the mechanism */
10231
- }
10232
- });
10233
-
10234
- handle.addEventListener("keydown", (event) => {
10235
- // Arrows track the visual direction, so a trailing rail inverts them.
10236
- const step = railSide() === "right" ? -RAIL_RESIZE_STEP : RAIL_RESIZE_STEP;
10237
- const width = railWidth();
10238
- const next =
10239
- event.key === "ArrowRight"
10240
- ? width + step
10241
- : event.key === "ArrowLeft"
10242
- ? width - step
10243
- : event.key === "Home"
10244
- ? RAIL_MIN_WIDTH
10245
- : event.key === "End"
10246
- ? RAIL_MAX_WIDTH
10247
- : null;
10248
- if (next === null) return;
10249
- event.preventDefault();
10250
- commitRailWidth(next);
10251
- });
10252
- return handle;
10253
- };
10254
-
10255
- /** Docked and expanded only: the floating rail and the icon column never resize. */
10256
- const syncRailResizeHandle = (
10257
- shell: HTMLElement,
10258
- before: HTMLElement
10259
- ): void => {
10260
- if (!railResizable() || railShowsCollapsed()) {
10261
- railResizeRelease?.();
10262
- railResizeHandle?.remove();
10263
- return;
10264
- }
10265
- const handle = railResizeHandle ?? buildRailResizeHandle();
10266
- railResizeHandle = handle;
10267
- handle.setAttribute("aria-label", historyShellCopy.resizeLabel);
10268
- handle.setAttribute("aria-valuenow", String(railWidth()));
10269
- // Between the two, on the edge the divider already faces.
10270
- if (handle.nextElementSibling !== before) shell.insertBefore(handle, before);
10271
- };
10272
-
10273
- /**
10274
- * Rail geometry is config-derived, so it must be re-derivable: a live
10275
- * `update()` of `rail.width` / `rail.side` lands here, not only at mount.
10276
- */
10277
- applyRailChrome = (): void => {
10278
- // The bar mirrors the docked edge, so the view hears about a side flip even
10279
- // while it is presenting as a panel.
10280
- historySurface?.view.setRailSide(railSide());
10281
- const trailing = railSide() === "right";
10282
- const overlay = railOverlayHost;
10283
- if (overlay) {
10284
- // Hangs from the trigger's row rather than the widget's top edge, so the
10285
- // trigger stays visible and clickable above it. Measured, since a header
10286
- // rebuild or a resize can move the trigger.
10287
- const below = railTriggerButton
10288
- ? railTriggerButton.getBoundingClientRect().bottom -
10289
- container.getBoundingClientRect().top
10290
- : 0;
10291
- overlay.style.top = `calc(${Math.max(0, Math.round(below))}px + ${RAIL_OVERLAY_MARGIN})`;
10292
- overlay.style.width = `${railWidth()}px`;
10293
- overlay.style.left = trailing ? "" : RAIL_OVERLAY_MARGIN;
10294
- overlay.style.right = trailing ? RAIL_OVERLAY_MARGIN : "";
10295
- }
10296
- const host = railHost;
10297
- const shell = railShell;
10298
- const column = railColumn;
10299
- if (!host || !shell || !column) return;
10300
- host.style.flex = `0 0 ${
10301
- railShowsCollapsed() ? RAIL_COLLAPSED_WIDTH : railWidth()
10302
- }px`;
10303
- // The divider always faces the conversation, whichever edge the rail took.
10304
- const divider = "1px solid var(--persona-divider,#e5e7eb)";
10305
- host.style.borderRight = trailing ? "" : divider;
10306
- host.style.borderLeft = trailing ? divider : "";
10307
- const leading = trailing ? column : host;
10308
- // Reorder only on an actual side flip: re-parenting blurs what it moves.
10309
- if (shell.firstElementChild !== leading) {
10310
- shell.append(leading, trailing ? host : column);
10311
- }
10312
- syncRailResizeHandle(shell, trailing ? host : column);
10313
- };
10314
-
10315
- /**
10316
- * Rail is a shell-owned navigation column running the FULL widget height
10317
- * beside a still-operable conversation: the shell header, `body`, the
10318
- * in-container composer and any top-right action wrappers move into a column
10319
- * next to the host, and the shell takes the header's old container slot.
10320
- */
10321
- const mountRailHost = (element: HTMLElement): void => {
10322
- // A pending docking open already built the shell around a placeholder;
10323
- // the arriving view takes its slot with no reflow around it.
10324
- if (railPlaceholder && railHost) {
10325
- railPlaceholder.replaceWith(element);
10326
- railPlaceholder = null;
10327
- applyRailChrome();
10328
- return;
10329
- }
10330
- const shell = createElement("div", "persona-history-rail-shell");
10331
- shell.style.cssText = "display:flex;flex-direction:row;flex:1 1 auto;min-height:0";
10332
- const column = createElement("div", "persona-history-rail-conversation");
10333
- // position: top-right close/clear wrappers anchor here instead of the
10334
- // container, or they would float over the rail.
10335
- column.style.cssText =
10336
- "display:flex;flex-direction:column;flex:1 1 auto;min-width:0;min-height:0;position:relative";
10337
- // The collapse transition is a rule in the history chunk's stylesheet: an
10338
- // inline one could not carry the reduced-motion query.
10339
- const host = createElement("div", "persona-history-rail-host");
10340
- host.style.cssText = "display:flex;min-height:0;overflow:hidden";
10341
-
10342
- container.insertBefore(shell, header.parentNode === container ? header : body);
10343
- for (const node of railBorrowed()) {
10344
- if (node?.parentNode === container) column.appendChild(node);
10345
- }
10346
- shell.append(host, column);
10347
- host.appendChild(element);
10348
- railShell = shell;
10349
- railHost = host;
10350
- railColumn = column;
10351
- applyRailChrome();
10352
- };
10353
-
10354
- /**
10355
- * Space reservation for a docking open that still awaits the chunk: the full
10356
- * rail shell mounts around an empty stand-in at the final width, so the
10357
- * conversation and its header paint at their docked geometry from the first
10358
- * frame instead of being pushed over when the view lands.
10359
- */
10360
- const mountRailPlaceholder = (): void => {
10361
- if (railShell) return;
10362
- const placeholder = createElement(
10363
- "div",
10364
- "persona-history-rail-placeholder"
10365
- );
10366
- placeholder.style.cssText = "flex:1 1 auto;min-height:0";
10367
- railPlaceholder = placeholder;
10368
- mountRailHost(placeholder);
10369
- repinAnchoredMessage();
10370
- };
10371
-
10372
- /** Hands the reserved column back (failed or re-presented open). */
10373
- const clearRailPlaceholder = (): void => {
10374
- if (!railPlaceholder) return;
10375
- unmountHistoryHosts();
10376
- repinAnchoredMessage();
10377
- };
10378
-
10379
- /**
10380
- * Floating host for the collapsed overlay rail: the expanded view elevated
10381
- * over a conversation that keeps its own layout, so nothing is borrowed and
10382
- * nothing reflows around it.
10383
- */
10384
- const mountRailOverlayHost = (element: HTMLElement): void => {
10385
- const host = createElement("div", "persona-history-rail-overlay");
10386
- // Every themeable value is a var() reference with its default in the
10387
- // fallback, so an unset token costs nothing and a live one lands at once.
10388
- host.style.cssText =
10389
- `position:absolute;bottom:${RAIL_OVERLAY_MARGIN};` +
10390
- `display:flex;overflow:hidden;z-index:${PORTALED_OVERLAY_Z_INDEX - 1};` +
10391
- "border-radius:var(--persona-history-overlay-radius,16px);" +
10392
- "background:var(--persona-history-overlay-bg,var(--persona-container,#f7f7f8));" +
10393
- "box-shadow:var(--persona-history-overlay-shadow,0 12px 40px rgba(0,0,0,0.25))";
10394
- // The conversation column already relies on a positioned container.
10395
- container.style.position = "relative";
10396
- container.appendChild(host);
10397
- host.appendChild(element);
10398
- // The safe zone spans nodes the rail does not own, so hover is tracked by
10399
- // position for as long as it is open.
10400
- document.addEventListener("pointermove", handleRailPointerMove);
10401
- railOverlayHost = host;
10402
- applyRailChrome();
10403
- syncRailToggleLabel();
10404
- };
10405
-
10406
- const unmountHistoryHosts = (): void => {
10407
- restorePanelHost?.();
10408
- if (railOverlayHost) {
10409
- // Dismissed under the pointer: hold the hover off until the synthetic
10410
- // enter from uncovering the trigger has passed.
10411
- if (railPointerInside) railUncoveredUntil = Date.now() + 150;
10412
- document.removeEventListener("pointermove", handleRailPointerMove);
10413
- railOverlayHost.remove();
10414
- railOverlayHost = null;
10415
- }
10416
- const shell = railShell;
10417
- if (shell) {
10418
- // A drag in flight owns document listeners the host is about to lose.
10419
- railResizeRelease?.();
10420
- // Live bindings, in panel order, before the slot the shell took. A header
10421
- // restored first also takes its inline action wrappers back with it, so
10422
- // the `contains` check skips them.
10423
- for (const node of railBorrowed()) {
10424
- if (node && shell.contains(node)) container.insertBefore(node, shell);
10425
- }
10426
- shell.remove();
10427
- railShell = null;
10428
- railHost = null;
10429
- railColumn = null;
10430
- railPlaceholder = null;
10431
- }
10432
- };
10433
-
10434
- /** Shell-owned chrome applied to whatever element arbitration produced. */
10435
- const prepareHistoryElement = (element: HTMLElement): void => {
10436
- historyMountedElement = element;
10437
- element.id = historyRegionId;
10438
- // Host-side flex sizing: the chunk sizes itself to 100%, the shell decides
10439
- // how it participates in the column/row it was just dropped into.
10440
- element.style.flex = "1 1 auto";
10441
- element.style.minHeight = "0";
10442
- };
10443
-
10444
- /** The chunk owns its own classes/labels; the shell only picks the host. */
10445
- const mountHistoryElement = (element: HTMLElement): void => {
10446
- prepareHistoryElement(element);
10447
- // The open that reserved the column can resolve to another host (a width
10448
- // change mid-load re-presents as panel); the stand-in must not outlive it.
10449
- if (historyPresentation !== "rail" || railOverlayOpen) {
10450
- clearRailPlaceholder();
10451
- }
10452
- if (historyPresentation !== "rail") mountPanelHost(element);
10453
- else if (railOverlayOpen) mountRailOverlayHost(element);
10454
- else mountRailHost(element);
10455
- };
10456
-
10457
- /**
10458
- * Live rail <-> panel transition. ONE view instance survives the move, so the
10459
- * list, its fixed operation context, and any pending work are preserved. A
10460
- * custom full view is re-invoked with the new presentation value.
10461
- */
10462
- const syncHistoryPresentation = (): void => {
10463
- // The trigger belongs to a rail-capable width, so it resolves here too, and
10464
- // the header toggle stands down beside whatever it resolved to.
10465
- syncRailOverlayTrigger();
10466
- syncHistoryButton();
10467
- if (!historyVisible || !historySurface) return;
10468
- const next = resolveHistoryPresentation();
10469
- if (next === historyPresentation) return;
10470
- const focusKey = document.activeElement;
10471
- // The bar's contents may be focused inside the shell header, not the view.
10472
- const refocus =
10473
- focusKey instanceof HTMLElement &&
10474
- (historySurface.element.contains(focusKey) ||
10475
- historyHeaderHost?.contains(focusKey) === true)
10476
- ? focusKey
10477
- : null;
10478
- unmountHistoryHosts();
10479
- // Detach before re-hosting so a mid-move re-arbitration cannot re-insert
10480
- // the surface into the host it is being moved out of.
10481
- historySurface.element.remove();
10482
- // Rail is always inline; the panel host re-externalizes on mount.
10483
- historySurface.view.setHeaderPlacement("inline");
10484
- historyPresentation = next;
10485
- historySurface.view.setPresentation(next);
10486
- // Panel always shows the whole list; returning to rail restores the state.
10487
- historySurface.view.setCollapsed(railShowsCollapsed());
10488
- historySurface.requestRender();
10489
- if (!historySurface.element.isConnected) {
10490
- mountHistoryElement(historySurface.element);
10491
- }
10492
- if (refocus?.isConnected) refocus.focus();
10493
- else focusHistoryEntry();
10494
- syncScrollToBottomButton();
10495
- // A one-frame layout removal above the anchored message clamps scrollTop.
10496
- repinAnchoredMessage();
10497
- syncHistoryChromeImpl();
10498
- };
10499
-
10500
- // --- open / close --------------------------------------------------------
10501
-
10502
- /** The bar lives in the shell header while it is hosted there. */
10503
- const queryHistoryOwned = <T extends HTMLElement>(
10504
- element: HTMLElement,
10505
- selector: string
10506
- ): T | null =>
10507
- historyHeaderHost?.querySelector<T>(selector) ??
10508
- element.querySelector<T>(selector);
10509
-
10510
- const focusHistoryEntry = (): void => {
10511
- const element = historySurface?.element ?? historyMountedElement;
10512
- if (!element) return;
10513
- const close = queryHistoryOwned(
10514
- element,
10515
- // The rail's leading control is a collapse toggle, not a close.
10516
- '[data-persona-history-focus="close"],[data-persona-history-focus="collapse"]'
10517
- );
10518
- if (close) {
10519
- close.focus();
10520
- return;
10521
- }
10522
- const heading =
10523
- queryHistoryOwned<HTMLElement>(element, ".persona-history-title") ??
10524
- // Custom contents may expose neither: the region itself is the fallback.
10525
- element;
10526
- heading.tabIndex = -1;
10527
- heading.focus();
10528
- };
10529
-
10530
- const openHistory = async (opts?: {
10531
- returnSurface?: HistoryReturnSurface;
10532
- invoker?: HTMLElement | null;
10533
- /** Rail only: an open with no keyboard behind it must not move focus. */
10534
- keyboard?: boolean;
10535
- /** `false` skips the entry focus entirely (programmatic/preview opens). */
10536
- focus?: boolean;
10537
- }): Promise<void> => {
10538
- if (!historyAvailable() || historyVisible) return;
10539
- const provider = historyProvider;
10540
- if (!provider) return;
10541
- // An unpinned overlay rail IS its trigger, so restoring that state must
10542
- // render chrome only: no surface, and no chunk fetched for it.
10543
- if (!railOverlayOpen && railTriggerApplies() && isRailCollapsed()) {
10544
- syncRailOverlayTrigger();
10545
- return;
10546
- }
10547
- // A reopen mid-exit finishes the outgoing teardown first: never two
10548
- // surfaces, never a restore that lands after this one mounts.
10549
- settleHistoryExit();
10550
- const token = ++historyOpenToken;
10551
- historyReturnSurface = opts?.returnSurface ?? "conversation";
10552
- historyInvoker = opts?.invoker ?? historyButton;
10553
-
10554
- // An open that will dock the rail takes its final geometry for the chunk
10555
- // load: the trigger hides (painted, the glyph flashes at the header's
10556
- // leading edge and then jumps to the mounted rail's own toggle) and the
10557
- // column is reserved (unreserved, the conversation header paints at the
10558
- // widget edge and is pushed over when the rail lands).
10559
- const pinPending = railTriggerApplies() && !railOverlayOpen;
10560
- if (pinPending) {
10561
- railPinPendingOpens += 1;
10562
- syncRailOverlayTrigger();
10563
- mountRailPlaceholder();
10564
- }
10565
- let module: Awaited<ReturnType<typeof loadHistoryView>>;
10566
- try {
10567
- module = await loadHistoryView();
10568
- } catch {
10569
- // Lazy-chunk failure keeps the invoking surface interactive and retryable.
10570
- announceHistory(historyShellCopy.openHistoryLabel);
10571
- if (pinPending) {
10572
- railPinPendingOpens -= 1;
10573
- // A superseded open leaves the shared chrome to its successor.
10574
- if (token === historyOpenToken) {
10575
- clearRailPlaceholder();
10576
- syncRailOverlayTrigger();
10577
- }
10578
- }
10579
- return;
10580
- }
10581
- if (pinPending) railPinPendingOpens -= 1;
10582
- if (token !== historyOpenToken || historyVisible) return;
10583
-
10584
- // One scope for the whole opened view; every operation reuses it.
10585
- historyOperationContext = { scope: historyScope() };
10586
- historyPresentation = resolveHistoryPresentation();
10587
- historyVisible = true;
10588
-
10589
- // Built externally when there is a shell header to host it in; the panel
10590
- // host re-decides on mount, so this only avoids a needless first insert.
10591
- const initialHeaderPlacement: HistoryHeaderPlacement =
10592
- historyPresentation === "panel" &&
10593
- config.layout?.showHeader !== false &&
10594
- header.style.display !== "none"
10595
- ? "external"
10596
- : "inline";
10597
-
10598
- const rowAvatar = config.features?.history?.rowAvatar;
10599
- const shortcut = railCollapseShortcut();
10600
- const collapseShortcutStrings = shortcut
10601
- ? { hint: shortcut.hint, aria: shortcut.aria }
10602
- : null;
10603
-
10604
- const baseViewOptions: HistoryViewOptions = {
10605
- provider,
10606
- context: historyOperationContext,
10607
- targetId: activeHistoryTargetId(),
10608
- presentation: historyPresentation,
10609
- collapsible: railCollapsible(),
10610
- collapsed: railShowsCollapsed(),
10611
- railSide: railSide(),
10612
- renderRailHeader: config.features?.history?.rail?.renderHeader,
10613
- railBrand: railBrandNode(),
10614
- onToggleCollapse: toggleRailCollapsed,
10615
- // Formatted strings only: the size-capped chunk never imports shortcuts.
10616
- ...(collapseShortcutStrings
10617
- ? { collapseShortcut: collapseShortcutStrings }
10618
- : {}),
10619
- headerPlacement: initialHeaderPlacement,
10620
- showScopeStatus: config.features?.history?.showScopeStatus !== false,
10621
- showDelete: config.features?.history?.showDelete !== false,
10622
- showDeleteAll: config.features?.history?.showDeleteAll !== false,
10623
- ...(config.features?.history?.listActions?.length
10624
- ? { listActions: config.features.history.listActions }
10625
- : {}),
10626
- // Rows borrow the launcher's IMAGE mark only: agentIconText carries the
10627
- // merged 💬 default, which would put a placeholder glyph on every row.
10628
- // No mark at all means text-only rows, the assistant-list default.
10629
- rowAvatar:
10630
- rowAvatar === false
10631
- ? false
10632
- : typeof rowAvatar === "string"
10633
- ? rowAvatar
10634
- : config.launcher?.iconUrl,
10635
- activeConversationId: session.getActiveConversationId(),
10636
- ...(config.features?.history?.grouping
10637
- ? { grouping: config.features.history.grouping }
10638
- : {}),
10639
- ...(config.features?.history?.copy
10640
- ? { copy: config.features.history.copy }
10641
- : {}),
10642
- ...(config.features?.history?.pageSize !== undefined
10643
- ? { pageSize: config.features.history.pageSize }
10644
- : {}),
10645
- // The pending/error surface owns failures (optimistic open), so the
10646
- // row must not double-report them.
10647
- onSelect: (conversationId) =>
10648
- openHistoryConversation(conversationId, { focusComposer: true }).catch(
10649
- () => {}
10650
- ),
10651
- onActiveConversationChange: (summary) =>
10652
- setActiveConversationSummary(summary),
10653
- // The chunk is size-capped, so it borrows the shell's tooltip module.
10654
- attachTooltip,
10655
- onStartNew: () => startNewConversation({ focusComposer: true }),
10656
- onClose: () => closeHistory(),
10657
- onRequestDeleteConversation: (conversationId) =>
10658
- requestDeleteConversation(conversationId),
10659
- onRequestClearHistory: () => requestClearConversationHistory(),
10660
- ...(provider.resetDevice
10661
- ? { onRequestResetIdentity: () => requestResetHistoryIdentity() }
10662
- : {}),
10663
- };
10664
-
10665
- // Plugin hooks arbitrate around the default view; the shell keeps placement,
10666
- // open/close, Escape, confirmations, announcements, and focus.
10667
- historySurface = createHistoryRenderSurface({
10668
- plugins,
10669
- config,
10670
- getPresentation: () => historyPresentation ?? "panel",
10671
- getReturnSurface: () => historyReturnSurface,
10672
- close: () => closeHistory(),
10673
- createView: ({ slots, renderDom, onModelChange, railSections }) => {
10674
- // Tracked before `historySurface` is assigned: the first mount happens
10675
- // inside this constructor and already needs the handle.
10676
- historyViewHandle = module.createHistoryView({
10677
- ...baseViewOptions,
10678
- railSections: railNavSections(railSections),
10679
- slots,
10680
- renderDom,
10681
- onModelChange,
10682
- onAnnounce: announceHistory,
10683
- });
10684
- return historyViewHandle;
10685
- },
10686
- onElementChanged: (next, previous) => {
10687
- if (!previous?.isConnected) return mountHistoryElement(next);
10688
- prepareHistoryElement(next);
10689
- previous.replaceWith(next);
10690
- // Default <-> custom re-arbitration changes who owns the bar.
10691
- enforcePanelHost();
10692
- },
10693
- });
10694
- historySurface.view.setNewConversationRequired(
10695
- historySessionState.recovery === "new_conversation_required"
10696
- );
10697
- // The panel makes the conversation inert behind it, so it always takes
10698
- // focus. The rail leaves it operable: a pointer or programmatic open would
10699
- // only leave a keyboard ring on the toggle, so it keeps focus where it is.
10700
- // `focus: false` opts out entirely: the caller owns focus (preview replay).
10701
- if (
10702
- opts?.focus !== false &&
10703
- (historyPresentation !== "rail" || opts?.keyboard === true)
10704
- ) {
10705
- focusHistoryEntry();
10706
- }
10707
- syncScrollToBottomButton();
10708
- repinAnchoredMessage();
10709
- syncHistoryChromeImpl();
10710
- eventBus.emit("history:opened", {
10711
- presentation: historyPresentation,
10712
- returnSurface: historyReturnSurface,
10713
- timestamp: Date.now(),
10714
- });
10715
- };
10716
-
10717
- /**
10718
- * Close is: exit animation -> unmount and restore the hidden chrome ->
10719
- * restore focus. The teardown half is deferred behind the view's `playExit()`
10720
- * promise, so it is exposed here for whoever preempts it (a reopen, a widget
10721
- * teardown). Idempotent, and a no-op while nothing is leaving.
10722
- */
10723
- let settleHistoryExit: () => void = () => {};
10724
-
10725
- const closeHistory = (opts?: { restoreFocus?: boolean }): void => {
10726
- if (!historyVisible) return;
10727
- historyOpenToken += 1;
10728
- const returnSurface = historyReturnSurface;
10729
- const invoker = historyInvoker;
10730
- const surface = historySurface;
10731
- const restoreInvokerFocus = opts?.restoreFocus !== false;
10732
- // Flipped before the animation: a second close is a no-op and a reopen
10733
- // mounts fresh rather than re-entering the surface that is leaving.
10734
- historyVisible = false;
10735
-
10736
- let done = false;
10737
- let timer: ReturnType<typeof setTimeout> | null = null;
10738
- const finish = (): void => {
10739
- if (done) return;
10740
- done = true;
10741
- settleHistoryExit = () => {};
10742
- if (timer !== null) clearTimeout(timer);
10743
- // The floating rail is torn down with the surface it hosted.
10744
- railOverlayOpen = false;
10745
- cancelRailGrace();
10746
- // Before focus restoration below: the invoker lives in the shell header,
10747
- // which is inert until this restores it.
10748
- unmountHistoryHosts();
10749
- // Dispose before destroy: cleanups belong to the render being torn down.
10750
- surface?.dispose();
10751
- surface?.view.destroy();
10752
- surface?.element.remove();
10753
- // A reopen that preempted this exit already owns the shell state.
10754
- if (historySurface === surface) {
10755
- historySurface = null;
10756
- historyViewHandle = null;
10757
- historyMountedElement = null;
10758
- historyPresentation = null;
10759
- historyOperationContext = null;
10760
- historyInvoker = null;
10761
- }
10762
- syncScrollToBottomButton();
10763
- // Removing a full-height host above the anchored message clamps scrollTop.
10764
- repinAnchoredMessage();
10765
- syncHistoryChromeImpl();
10766
- if (restoreInvokerFocus) {
10767
- const target = invoker ?? historyButton;
10768
- if (target?.isConnected) target.focus();
10769
- else maybeFocusInput();
10770
- }
10771
- eventBus.emit("history:closed", { returnSurface, timestamp: Date.now() });
10772
- };
10773
-
10774
- // Only the arbitrated default view animates: a plugin full view owns its
10775
- // own element and never got an entrance either.
10776
- const exit =
10777
- surface && surface.element === surface.view.element
10778
- ? surface.view.playExit()
10779
- : null;
10780
- if (!exit) {
10781
- finish();
10782
- return;
10783
- }
10784
- settleHistoryExit = finish;
10785
- // A cancelled or never-settling animation must never wedge the close.
10786
- timer = setTimeout(finish, HISTORY_EXIT_TIMEOUT_MS);
10787
- void exit.then(finish);
10788
- };
10789
-
10790
- /** Escape returns to the recorded invoking surface, like the back control. */
10791
- const handleHistoryKeydown = (event: KeyboardEvent): void => {
10792
- if (event.key !== "Escape" || !historyVisible || !historySurface) return;
10793
- // Rail leaves the conversation operable: only its own focus closes it, and
10794
- // the floating rail's scope includes the trigger it hangs from.
10795
- if (historyPresentation === "rail") {
10796
- const target = event.target;
10797
- if (
10798
- !(target instanceof Node) ||
10799
- !(
10800
- historySurface.element.contains(target) ||
10801
- (railOverlayOpen && railTriggerWrapper?.contains(target) === true)
10802
- )
10803
- ) {
10804
- return;
10805
- }
10806
- }
10807
- event.preventDefault();
10808
- event.stopPropagation();
10809
- closeHistory();
10810
- };
10811
- container.addEventListener("keydown", handleHistoryKeydown);
10812
- destroyCallbacks.push(() =>
10813
- container.removeEventListener("keydown", handleHistoryKeydown)
10814
- );
10815
-
10816
- // --- session operations --------------------------------------------------
10817
-
10818
9045
  // ---- header title binding (layout.header.titleSource: "conversation") ----
10819
9046
  // The history view reports the active conversation's list summary through
10820
9047
  // onActiveConversationChange; the shell owns the fallback and the write, so
@@ -10873,696 +9100,26 @@ export const createAgentExperience = (
10873
9100
  const activeId = session.getActiveConversationId();
10874
9101
  if (!activeId) return;
10875
9102
  if (actionId === "delete") {
10876
- void requestDeleteConversation(activeId);
9103
+ void withHistoryShell((shell) => shell.requestDeleteConversation(activeId));
10877
9104
  } else if (actionId === "star" && session.canUpdateConversations()) {
10878
- void updateHistoryConversation(activeId, {
10879
- starred: !activeConversationStarred,
10880
- }).catch(() => {});
10881
- }
10882
- });
10883
-
10884
- // --- optimistic conversation open ---------------------------------------
10885
- // Selection acknowledges within a frame: the composer gates immediately, the
10886
- // stand-in takes the surface only if the fetch outlasts the show delay, and
10887
- // the transcript hydrates when the fetch lands. The token invalidates a stale
10888
- // resolution after a newer open, a new conversation, or a failure the visitor
10889
- // navigated away from.
10890
- let conversationOpenToken = 0;
10891
- // Show delay: opens that land inside it swap straight from the welcome or the
10892
- // previous conversation to the loaded transcript, so no skeleton ever flashes.
10893
- const CONVERSATION_OPEN_TAKEOVER_DELAY_MS = 250;
10894
- let conversationOpenTakeoverTimer: ReturnType<typeof setTimeout> | null = null;
10895
-
10896
- const cancelConversationOpenTakeover = (): void => {
10897
- if (conversationOpenTakeoverTimer) clearTimeout(conversationOpenTakeoverTimer);
10898
- conversationOpenTakeoverTimer = null;
10899
- };
10900
- destroyCallbacks.push(cancelConversationOpenTakeover);
10901
-
10902
- /** Hands the surface to the mounted stand-in. Idempotent by re-application. */
10903
- const engageConversationOpenTakeover = (): void => {
10904
- cancelConversationOpenTakeover();
10905
- const element = conversationOpenPendingEl;
10906
- if (!element) return;
10907
- conversationOpenTakeover = true;
10908
- element.hidden = false;
10909
- messagesWrapper.style.display = "none";
10910
- // The welcome is a sibling of the transcript, so hiding the wrapper alone
10911
- // would leave it painted above the stand-in.
10912
- updateWelcome();
10913
- };
10914
-
10915
- const clearConversationOpenPending = (): void => {
10916
- conversationOpenToken += 1;
10917
- cancelConversationOpenTakeover();
10918
- if (!conversationOpenPendingEl) return;
10919
- conversationOpenPendingEl.remove();
10920
- conversationOpenPendingEl = null;
10921
- conversationOpenTakeover = false;
10922
- messagesWrapper.style.removeProperty("display");
10923
- setHistoryHostInert(footer, false);
10924
- // Restores the welcome when navigation lands back on an empty transcript.
10925
- updateWelcome();
10926
- };
10927
-
10928
- /**
10929
- * Commit fade for the reopened transcript. WAAPI, not a CSS transition: the
10930
- * wrapper is the morph target, and post-render inline state is stripped by
10931
- * every render inside the completion window.
10932
- */
10933
- const fadeInTranscript = (): void => {
10934
- try {
10935
- if (window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches) {
10936
- return;
10937
- }
10938
- messagesWrapper.animate([{ opacity: 0 }, { opacity: 1 }], {
10939
- duration: 150,
10940
- easing: "ease-out",
10941
- });
10942
- } catch {
10943
- /* environments without WAAPI land the transcript without motion */
10944
- }
10945
- };
10946
-
10947
- // The stand-in surfaces get the transcript's centered column from their
10948
- // container classes, so the hydrated messages land exactly where they stood.
10949
- const skeletonBubble = (width: string, trailing: boolean): HTMLElement =>
10950
- createNode("div", {
10951
- className: cx(
10952
- "persona-conversation-loading-bubble",
10953
- trailing && "persona-conversation-loading-bubble--trailing"
10954
- ),
10955
- attrs: { "aria-hidden": "true" },
10956
- style: { width },
10957
- });
10958
-
10959
- const buildConversationOpenSkeleton = (): HTMLElement =>
10960
- createNode(
10961
- "div",
10962
- { className: "persona-conversation-loading-body" },
10963
- skeletonBubble("58%", false),
10964
- skeletonBubble("72%", true),
10965
- skeletonBubble("44%", false)
10966
- );
10967
-
10968
- const mountConversationOpenState = (element: HTMLElement): void => {
10969
- conversationOpenPendingEl?.remove();
10970
- conversationOpenPendingEl = element;
10971
- // The takeover is deferred, so the stand-in mounts hidden; one that replaces
10972
- // an already-engaged stand-in keeps the surface instead of blanking it.
10973
- element.hidden = !conversationOpenTakeover;
10974
- body.insertBefore(element, messagesWrapper);
10975
- cancelConversationOpenTakeover();
10976
- if (!conversationOpenTakeover) {
10977
- conversationOpenTakeoverTimer = setTimeout(
10978
- engageConversationOpenTakeover,
10979
- CONVERSATION_OPEN_TAKEOVER_DELAY_MS
10980
- );
10981
- }
10982
- // The composer must not send into the conversation being replaced. The
10983
- // panel exit restores the footer after its animation, so the close path
10984
- // re-asserts this gate (see the history:closed re-assert below).
10985
- setHistoryHostInert(footer, true);
10986
- };
10987
-
10988
- const showConversationOpenPending = (): void => {
10989
- // Same plugin -> config -> default chain as the streaming indicator. The
10990
- // hook replaces the skeleton only; the container keeps the centered
10991
- // column, the status role, and the composer gate.
10992
- const context: LoadingIndicatorRenderContext = {
10993
- config,
10994
- streaming: false,
10995
- location: "conversation-open",
10996
- defaultRenderer: buildConversationOpenSkeleton,
10997
- };
10998
- let content: HTMLElement | null = null;
10999
- const loadingPlugin = plugins.find((p) => p.renderLoadingIndicator);
11000
- if (loadingPlugin?.renderLoadingIndicator) {
11001
- content = loadingPlugin.renderLoadingIndicator(context);
11002
- }
11003
- if (content === null && config.loadingIndicator?.render) {
11004
- content = config.loadingIndicator.render(context);
11005
- }
11006
- mountConversationOpenState(
11007
- createNode(
11008
- "div",
11009
- {
11010
- className: "persona-conversation-loading",
11011
- attrs: {
11012
- role: "status",
11013
- "aria-label": historyShellCopy.openConversationLoadingLabel,
11014
- },
11015
- },
11016
- content ?? buildConversationOpenSkeleton()
11017
- )
11018
- );
11019
- };
11020
-
11021
- const showConversationOpenError = (conversationId: string): void => {
11022
- const retry = (): void => {
11023
- void openHistoryConversation(conversationId, {
11024
- focusComposer: true,
11025
- }).catch(() => {});
11026
- };
11027
- const back = historyAvailable()
11028
- ? (): void => {
11029
- clearConversationOpenPending();
11030
- void openHistory();
11031
- }
11032
- : undefined;
11033
- const actionButton = (label: string, onClick: () => void): HTMLElement => {
11034
- const button = createNode("button", {
11035
- className: "persona-conversation-loading-error-action",
11036
- attrs: { type: "button" },
11037
- text: label,
11038
- });
11039
- button.addEventListener("click", onClick);
11040
- return button;
11041
- };
11042
- const buildDefaultBlock = (): HTMLElement =>
11043
- createNode(
11044
- "div",
11045
- { className: "persona-conversation-loading-error-body" },
11046
- createNode("p", {
11047
- className: "persona-conversation-loading-error-title",
11048
- text: historyShellCopy.openConversationErrorTitle,
11049
- }),
11050
- createNode(
11051
- "div",
11052
- { className: "persona-conversation-loading-error-actions" },
11053
- actionButton(historyShellCopy.openConversationRetryLabel, retry),
11054
- back
11055
- ? actionButton(historyShellCopy.openConversationBackLabel, back)
11056
- : null
11057
- )
11058
- );
11059
- // First non-null plugin hook wins (plugins are priority-sorted); a throw
11060
- // is reported and skipped. The container keeps the centered column, the
11061
- // alert role, and the composer gate around whatever the hook returns.
11062
- const context: AgentWidgetRenderHistoryOpenErrorContext = Object.freeze({
11063
- conversationId,
11064
- config,
11065
- copy: Object.freeze({
11066
- title: historyShellCopy.openConversationErrorTitle,
11067
- retryLabel: historyShellCopy.openConversationRetryLabel,
11068
- backLabel: historyShellCopy.openConversationBackLabel,
11069
- }),
11070
- retry,
11071
- ...(back ? { back } : {}),
11072
- defaultRenderer: buildDefaultBlock,
11073
- });
11074
- let content: HTMLElement | null = null;
11075
- for (const plugin of plugins) {
11076
- if (!plugin.renderHistoryOpenError) continue;
11077
- try {
11078
- content = plugin.renderHistoryOpenError(context);
11079
- } catch (error) {
11080
- console.warn("[persona] renderHistoryOpenError threw", error);
11081
- content = null;
11082
- }
11083
- if (content) break;
11084
- }
11085
- mountConversationOpenState(
11086
- createNode(
11087
- "div",
11088
- {
11089
- className: "persona-conversation-loading-error",
11090
- attrs: { role: "alert" },
11091
- },
11092
- content ?? buildDefaultBlock()
11093
- )
11094
- );
11095
- // A failure must never sit hidden behind the surface it replaces, so the
11096
- // error skips the stand-in's show delay.
11097
- engageConversationOpenTakeover();
11098
- };
11099
-
11100
- // The panel exit's deferred teardown restores the footer it captured, which
11101
- // would lift the composer gate mid-fetch; re-assert it while an open is
11102
- // still pending.
11103
- eventBus.on("history:closed", () => {
11104
- if (conversationOpenPendingEl) setHistoryHostInert(footer, true);
11105
- });
11106
-
11107
- /**
11108
- * Optimistic reopen: navigate on the click, hydrate on the fetch. The
11109
- * returned promise keeps the transactional contract (resolves once the
11110
- * transcript is live, rejects on failure) for `controller.openConversation`.
11111
- * `suppressScrollSend` covers the hydration: otherwise the last restored
11112
- * user message triggers the anchor-top send scroll.
11113
- */
11114
- const openHistoryConversation = async (
11115
- conversationId: string,
11116
- { focusComposer = false }: { focusComposer?: boolean } = {}
11117
- ): Promise<void> => {
11118
- const scope = historyOperationScope();
11119
- // Seeds the header title binding from the list row before the list leaves.
11120
- // The surface is usually gone by hydration time (the exit outruns the
11121
- // fetch), so this is the only moment the title can be read from the list.
11122
- const seededFromList = !!historySurface;
11123
- historySurface?.view.setActiveConversationId(conversationId);
11124
- clearConversationOpenPending();
11125
- const token = conversationOpenToken;
11126
- showConversationOpenPending();
11127
- if (historyVisible && (historyPresentation === "panel" || railOverlayOpen)) {
11128
- closeHistory({ restoreFocus: false });
11129
- }
11130
- suppressScrollSend = true;
11131
- try {
11132
- await session.openConversation(conversationId, { scope });
11133
- } catch (error) {
11134
- if (token === conversationOpenToken) {
11135
- showConversationOpenError(conversationId);
11136
- }
11137
- throw error;
11138
- } finally {
11139
- suppressScrollSend = false;
11140
- }
11141
- if (token !== conversationOpenToken) return;
11142
- clearConversationOpenPending();
11143
- messageCache.clear();
11144
- resetAnchorState();
11145
- resumeAutoScroll();
11146
- if (!restoreScrollPosition()) jumpToBottomInstant();
11147
- // Fades only after the scroll settles, so the motion covers the final frame.
11148
- fadeInTranscript();
11149
- syncEarlierMessagesPill();
11150
- // Without a list at selection time there was no title to seed.
11151
- if (!seededFromList) setActiveConversationSummary(null);
11152
- eventBus.emit("history:conversationOpened", {
11153
- conversationId,
11154
- title: activeConversationTitle,
11155
- scope,
11156
- timestamp: Date.now(),
11157
- });
11158
- // Only interaction paths focus: focusing a programmatic open scrolls the
11159
- // host page to the widget (same-origin iframes included).
11160
- if (focusComposer) maybeFocusInput();
11161
- };
11162
-
11163
- /**
11164
- * The single commit path behind the header action, the view's `onStartNew`,
11165
- * and `controller.startNewConversation()`, so one emit covers all three.
11166
- */
11167
- const startNewConversation = async ({
11168
- focusComposer = false,
11169
- }: { focusComposer?: boolean } = {}): Promise<void> => {
11170
- // A new conversation supersedes any transcript fetch still in flight.
11171
- clearConversationOpenPending();
11172
- await session.startNewConversation({ scope: historyOperationScope() });
11173
- setActiveConversationSummary(null);
11174
- messageCache.clear();
11175
- resetAnchorState();
11176
- resumeAutoScroll();
11177
- jumpToBottomInstant();
11178
- syncEarlierMessagesPill();
11179
- const conversationId = session.getActiveConversationId();
11180
- historySurface?.view.setActiveConversationId(conversationId);
11181
- // Emitted before the close so a host can tell a commit from a plain close.
11182
- eventBus.emit("history:conversationStarted", {
11183
- conversationId,
11184
- timestamp: Date.now(),
11185
- });
11186
- if (historyVisible && (historyPresentation === "panel" || railOverlayOpen)) {
11187
- closeHistory({ restoreFocus: false });
11188
- }
11189
- if (focusComposer) maybeFocusInput();
11190
- };
11191
-
11192
- /** Shared rename/star path: provider update, then view + header binding. */
11193
- const updateHistoryConversation = async (
11194
- conversationId: string,
11195
- patch: HistoryConversationPatch
11196
- ): Promise<HistoryConversationSummary> => {
11197
- const summary = await session.updateConversation(conversationId, {
11198
- ...patch,
11199
- ...(patch.title !== undefined ? { title: patch.title.trim() } : {}),
11200
- });
11201
- // The view re-renders and reports the active title through the reporter;
11202
- // without a mounted view, keep the header binding fresh directly.
11203
- historySurface?.view.applyConversationSummary(summary);
11204
- if (!historySurface && conversationId === session.getActiveConversationId()) {
11205
- setActiveConversationSummary(summary);
11206
- }
11207
- return summary;
11208
- };
11209
-
11210
- const deleteHistoryConversation = async (
11211
- conversationId: string
11212
- ): Promise<void> => {
11213
- const scope = historyOperationScope();
11214
- const wasActive = session.getActiveConversationId() === conversationId;
11215
- await session.deleteConversation(conversationId, { scope });
11216
- // Prune the open list too: the view's own delete flow removes its row
11217
- // after this resolves, but built-in/headless deletes have no view caller.
11218
- historySurface?.view.removeConversationSummary(conversationId);
11219
- if (wasActive) {
11220
- setActiveConversationSummary(null);
11221
- messageCache.clear();
11222
- resetAnchorState();
11223
- resumeAutoScroll();
11224
- syncEarlierMessagesPill();
11225
- }
11226
- eventBus.emit("history:conversationDeleted", {
11227
- conversationId,
11228
- scope,
11229
- wasActive,
11230
- timestamp: Date.now(),
11231
- });
11232
- };
11233
-
11234
- const clearConversationHistory = async (opts?: {
11235
- targetId?: string;
11236
- /** Deliberate headless opt-in to the whole authorized client-token scope. */
11237
- allTargets?: boolean;
11238
- scope?: HistoryScope;
11239
- }): Promise<{ deleted: number }> => {
11240
- const scope = opts?.scope ?? historyOperationScope();
11241
- // Default to the same filter the visible list uses; only an explicit
11242
- // headless opt-in deletes conversations the visitor was never shown.
11243
- const targetId = opts?.allTargets
11244
- ? null
11245
- : (opts?.targetId ?? activeHistoryTargetId());
11246
- const result = await session.clearConversationHistory({
11247
- ...(targetId ? { targetId } : {}),
11248
- scope,
11249
- });
11250
- setActiveConversationSummary(null);
11251
- messageCache.clear();
11252
- resetAnchorState();
11253
- resumeAutoScroll();
11254
- syncEarlierMessagesPill();
11255
- eventBus.emit("history:cleared", {
11256
- deleted: result.deleted,
11257
- scope,
11258
- targetId,
11259
- timestamp: Date.now(),
11260
- });
11261
- return result;
11262
- };
11263
-
11264
- /**
11265
- * D6: the local wipe is UNCONDITIONAL. Records survive on the server; this
11266
- * browser is detached from them whether or not revocation was confirmed.
11267
- */
11268
- const resetHistoryIdentity = async (): Promise<{
11269
- remoteRevocationConfirmed: boolean;
11270
- }> => {
11271
- // Rejection is reserved for misuse; remote failure resolves false.
11272
- if (!historyProvider?.resetDevice) {
11273
- throw new Error(
11274
- "[Persona] resetHistoryIdentity() requires a history provider that can reset this device"
11275
- );
11276
- }
11277
- let remoteRevocationConfirmed = false;
11278
- try {
11279
- const result = await session.resetHistoryDevice();
11280
- remoteRevocationConfirmed = result.remoteRevocationConfirmed;
11281
- } finally {
11282
- setActiveConversationSummary(null);
11283
- session.clearArtifacts();
11284
- messageCache.clear();
11285
- lastAppliedMessages = null;
11286
- config.clearStoredSessionId?.();
11287
- config.clearStoredConversationId?.();
11288
- persistentMetadata = {};
11289
- actionManager.syncFromMetadata();
11290
- if (storageAdapter?.clear) {
11291
- runStorageMutation(
11292
- () => storageAdapter.clear!(),
11293
- "[AgentWidget] Failed to clear storage adapter:"
11294
- );
11295
- }
11296
- resetAnchorState();
11297
- resumeAutoScroll();
11298
- syncEarlierMessagesPill();
11299
- closeHistory({ restoreFocus: false });
11300
- maybeFocusInput();
11301
- if (!open) launcherSurfaceInstance?.launcher.element.focus();
11302
- }
11303
- announceHistory(
11304
- remoteRevocationConfirmed
11305
- ? historyShellCopy.identityResetNotice
11306
- : historyShellCopy.identityResetUnconfirmedNotice
11307
- );
11308
- eventBus.emit("history:identityReset", {
11309
- remoteRevocationConfirmed,
11310
- timestamp: Date.now(),
11311
- });
11312
- return { remoteRevocationConfirmed };
11313
- };
11314
-
11315
- // --- confirmations (shell-owned alert dialogs) ---------------------------
11316
-
11317
- // With the artifact split, `container` is only the chat column, so an
11318
- // inset:0 overlay there would leave the artifact pane undimmed. The panel
11319
- // wraps the whole split and is already position:relative on that path;
11320
- // forcing `relative` onto it elsewhere would not survive the chrome
11321
- // passes' cssText resets, so plain layouts keep the container host.
11322
- const historyConfirmHost = (): HTMLElement =>
11323
- artifactSplitRoot ? panel : container;
11324
-
11325
- const requestDeleteConversation = async (
11326
- conversationId: string
11327
- ): Promise<"deleted" | "cancelled"> => {
11328
- const confirmed = await showHistoryConfirm({
11329
- host: historyConfirmHost(),
11330
- title: historyShellCopy.deleteConversationConfirmTitle,
11331
- description: historyShellCopy.deleteConversationConfirm,
11332
- confirmLabel: historyShellCopy.deleteConversationConfirmLabel,
11333
- cancelLabel: historyShellCopy.confirmCancelLabel,
11334
- });
11335
- if (!confirmed) return "cancelled";
11336
- await deleteHistoryConversation(conversationId);
11337
- return "deleted";
11338
- };
11339
-
11340
- const requestClearConversationHistory = async (): Promise<
11341
- "cleared" | "cancelled"
11342
- > => {
11343
- // Scope-aware copy: never imply the delete is limited to the rendered page.
11344
- const verified = historyOperationScope() === "verified-user";
11345
- const confirmed = await showHistoryConfirm({
11346
- host: historyConfirmHost(),
11347
- title: historyShellCopy.clearHistoryConfirmTitle,
11348
- description: verified
11349
- ? historyShellCopy.clearHistoryVerifiedConfirm
11350
- : historyShellCopy.clearHistoryConfirm,
11351
- confirmLabel: historyShellCopy.clearHistoryConfirmLabel,
11352
- cancelLabel: historyShellCopy.confirmCancelLabel,
11353
- });
11354
- if (!confirmed) return "cancelled";
11355
- await clearConversationHistory();
11356
- return "cleared";
11357
- };
11358
-
11359
- const requestResetHistoryIdentity = async (): Promise<
11360
- { outcome: "cancelled" } | { outcome: "reset"; remoteRevocationConfirmed: boolean }
11361
- > => {
11362
- const confirmed = await showHistoryConfirm({
11363
- host: historyConfirmHost(),
11364
- title: historyShellCopy.resetIdentityConfirmTitle,
11365
- description: historyShellCopy.resetIdentityConfirm,
11366
- confirmLabel: historyShellCopy.resetIdentityConfirmLabel,
11367
- cancelLabel: historyShellCopy.confirmCancelLabel,
11368
- });
11369
- if (!confirmed) return { outcome: "cancelled" };
11370
- const { remoteRevocationConfirmed } = await resetHistoryIdentity();
11371
- return { outcome: "reset", remoteRevocationConfirmed };
11372
- };
11373
-
11374
- // --- "show earlier messages" prepend -------------------------------------
11375
-
11376
- const earlierMessagesButton = createElement(
11377
- "button",
11378
- "persona-history-earlier"
11379
- ) as HTMLButtonElement;
11380
- earlierMessagesButton.type = "button";
11381
- earlierMessagesButton.textContent = historyShellCopy.showEarlierMessagesLabel;
11382
- earlierMessagesButton.setAttribute("data-persona-history-earlier", "");
11383
- Object.assign(earlierMessagesButton.style, {
11384
- alignSelf: "center",
11385
- minHeight: "44px",
11386
- padding: "0 16px",
11387
- borderRadius: "999px",
11388
- border: "1px solid var(--persona-border, rgba(0,0,0,0.12))",
11389
- background: "transparent",
11390
- color: "inherit",
11391
- font: "inherit",
11392
- cursor: "pointer",
11393
- flexShrink: "0",
11394
- } satisfies Partial<CSSStyleDeclaration>);
11395
-
11396
- const syncEarlierMessagesPill = (): void => {
11397
- const show =
11398
- historyAvailable() &&
11399
- !!historySessionState.nextMessageCursor &&
11400
- !!session.getActiveConversationId();
11401
- if (!show) {
11402
- earlierMessagesButton.remove();
11403
- return;
11404
- }
11405
- earlierMessagesButton.textContent = historyShellCopy.showEarlierMessagesLabel;
11406
- if (earlierMessagesButton.parentNode !== body) {
11407
- body.insertBefore(earlierMessagesButton, body.firstChild);
9105
+ void withHistoryShell((shell) =>
9106
+ shell.updateHistoryConversation(activeId, {
9107
+ starred: !activeConversationStarred,
9108
+ })
9109
+ ).catch(() => {});
11408
9110
  }
11409
- };
11410
-
11411
- earlierMessagesButton.addEventListener("click", () => {
11412
- const conversationId = session.getActiveConversationId();
11413
- const cursor = historySessionState.nextMessageCursor;
11414
- if (!conversationId || !cursor || earlierMessagesButton.disabled) return;
11415
- earlierMessagesButton.disabled = true;
11416
- // Capture before the prepend so the reader's viewport stays put.
11417
- const previousHeight = body.scrollHeight;
11418
- const previousTop = body.scrollTop;
11419
- void session
11420
- .loadOlderMessages(conversationId, cursor, { scope: historyOperationScope() })
11421
- .then(() => {
11422
- body.scrollTop = previousTop + (body.scrollHeight - previousHeight);
11423
- // Prepending shifts everything below the anchor.
11424
- repinAnchoredMessage();
11425
- })
11426
- .catch(() => {})
11427
- .finally(() => {
11428
- earlierMessagesButton.disabled = false;
11429
- syncEarlierMessagesPill();
11430
- });
11431
9111
  });
11432
9112
 
11433
- // --- header chrome -------------------------------------------------------
11434
-
11435
- // Shares the header control chrome (box + glyph from the header tokens) with
11436
- // the close and clear-chat buttons beside it.
11437
- const buildHistoryButton = (): {
11438
- button: HTMLButtonElement;
11439
- wrapper: HTMLElement;
11440
- } => {
11441
- const parts = createHeaderIconButton({
11442
- ariaLabel: historyShellCopy.openHistoryLabel,
11443
- iconName: "history",
11444
- wrapperClassName:
11445
- "persona-relative persona-inline-flex persona-items-center persona-justify-center",
11446
- extraClassName: "persona-history-toggle",
11447
- attrs: { "data-persona-history-toggle": "" },
11448
- });
11449
- parts.button.addEventListener("click", (event) => {
11450
- if (!historyAvailable() || historyTurnBusy()) return;
11451
- if (historyVisible) {
11452
- closeHistory();
11453
- return;
11454
- }
11455
- // Enter/Space synthesize a click with detail 0; a pointer press reports > 0.
11456
- void openHistory({ invoker: parts.button, keyboard: event.detail === 0 });
11457
- });
11458
- return parts;
11459
- };
11460
-
11461
- const syncHistoryButton = (): void => {
11462
- if (!historyAvailable()) {
11463
- historyButtonWrapper?.remove();
11464
- historyButton = null;
11465
- historyButtonWrapper = null;
11466
- return;
11467
- }
11468
- // A header rebuild detaches the old button; a stale ref must not block
11469
- // recreation into the replacement header.
11470
- if (historyButtonWrapper && !historyButtonWrapper.isConnected) {
11471
- historyButton = null;
11472
- historyButtonWrapper = null;
11473
- }
11474
- if (!historyButton && header) {
11475
- const parts = buildHistoryButton();
11476
- historyButton = parts.button;
11477
- historyButtonWrapper = parts.wrapper;
11478
- const insertBefore =
11479
- panelElements.clearChatButtonWrapper || panelElements.closeButtonWrapper;
11480
- // Layouts may parent these wrappers in a trailing cluster rather than
11481
- // the header itself; insert wherever they live so close stays outermost.
11482
- if (insertBefore?.parentNode && header.contains(insertBefore)) {
11483
- insertBefore.parentNode.insertBefore(historyButtonWrapper, insertBefore);
11484
- } else {
11485
- header.appendChild(historyButtonWrapper);
11486
- }
11487
- }
11488
- if (!historyButton || !historyButtonWrapper) return;
11489
- // Every rail surface carries its own toggle, and so does the trigger that
11490
- // summons one: the header keeps a control only when neither is on screen.
11491
- const railed =
11492
- railTriggerApplies() || (historyVisible && historyPresentation === "rail");
11493
- historyButtonWrapper.style.display = railed ? "none" : "";
11494
- if (railed) {
11495
- // Hiding the control under focus would drop it to the body; the rail's
11496
- // own toggle is the same control, so focus follows it there.
11497
- if (document.activeElement === historyButton) focusHistoryEntry();
11498
- return;
11499
- }
11500
- const busy = historyTurnBusy();
11501
- historyButton.disabled = busy;
11502
- historyButton.setAttribute("aria-disabled", busy ? "true" : "false");
11503
- const label = busy
11504
- ? historyShellCopy.openHistoryBusyLabel
11505
- : historyShellCopy.openHistoryLabel;
11506
- // The factory tooltip reads the live aria-label; a title would double it.
11507
- historyButton.setAttribute("aria-label", label);
11508
- // Rail/auto toggles a navigation region; panel navigates to a surface.
11509
- if ((config.features?.history?.presentation ?? "panel") === "panel") {
11510
- historyButton.removeAttribute("aria-expanded");
11511
- historyButton.removeAttribute("aria-controls");
11512
- } else {
11513
- historyButton.setAttribute("aria-expanded", historyVisible ? "true" : "false");
11514
- historyButton.setAttribute("aria-controls", historyRegionId);
11515
- }
11516
- };
11517
-
11518
- /**
11519
- * With history available the visible start-over affordance becomes
11520
- * "New conversation" (`clearChat()` stays programmatic-only).
11521
- */
11522
- let clearChatRelabelled = false;
11523
- const syncClearChatAffordance = (): void => {
11524
- const button = panelElements.clearChatButton;
11525
- if (!button) return;
11526
- if (historyAvailable()) {
11527
- if (!clearChatRelabelled) {
11528
- clearChatDefaultLabel = button.getAttribute("aria-label") ?? "";
11529
- clearChatRelabelled = true;
11530
- }
11531
- // aria-label only: the styled tooltip reads it live, and a title would
11532
- // render a second native tooltip on top.
11533
- button.setAttribute("aria-label", historyShellCopy.newConversationLabel);
11534
- button.removeAttribute("title");
11535
- // No touch-target pin: the shared header control class owns the box, and
11536
- // a 44px floor here would desync this control from its neighbours.
11537
- return;
11538
- }
11539
- // Only undo a relabel we performed; never clobber host-configured copy.
11540
- if (!clearChatRelabelled) return;
11541
- clearChatRelabelled = false;
11542
- if (clearChatDefaultLabel) {
11543
- button.setAttribute("aria-label", clearChatDefaultLabel);
11544
- }
11545
- };
11546
-
11547
- const syncHistoryChromeImpl = (): void => {
11548
- historyShellCopy = resolveHistoryShellCopy(config.features?.history?.copy);
11549
- syncHistoryButton();
11550
- syncRailOverlayTrigger();
11551
- syncClearChatAffordance();
11552
- syncEarlierMessagesPill();
11553
- };
11554
- historyChromeSync = syncHistoryChromeImpl;
11555
-
11556
9113
  // --- session-driven state ------------------------------------------------
11557
9114
 
11558
9115
  historyStateHandler = (state) => {
11559
9116
  historySessionState = state;
11560
- historySurface?.view.setNewConversationRequired(
9117
+ historyShell?.historySurface?.view.setNewConversationRequired(
11561
9118
  state.recovery === "new_conversation_required"
11562
9119
  );
11563
9120
  // Sending stays blocked through a destructive/continuity transition.
11564
9121
  setComposerDisabled(state.sendBlocked || isStreaming);
11565
- syncEarlierMessagesPill();
9122
+ historyShell?.syncEarlierMessagesPill();
11566
9123
  };
11567
9124
 
11568
9125
  historyNoticeHandler = (notice) => {
@@ -11575,22 +9132,124 @@ export const createAgentExperience = (
11575
9132
  resumeAutoScroll();
11576
9133
  }
11577
9134
  announceHistory(notice.message);
11578
- historySurface?.view.refresh();
9135
+ historyShell?.historySurface?.view.refresh();
9136
+ };
9137
+
9138
+ // --- lazy shell ----------------------------------------------------------
9139
+ // Placement, the rail, open/close and the conversation operations live in
9140
+ // `history-shell.ts`: inlined for npm builds, the lazy `history-shell.js`
9141
+ // chunk in the IIFE/CDN bundle. The shell is created when
9142
+ // `features.history` is enabled (at mount or by a later `update()`), or on
9143
+ // the first history API call. Until then history is simply unavailable.
9144
+ const historyShellContext: HistoryShellContext = {
9145
+ get actionManager() { return actionManager; },
9146
+ get activeConversationTitle() { return activeConversationTitle; },
9147
+ announceHistory,
9148
+ get applyRailChrome() { return applyRailChrome; },
9149
+ set applyRailChrome(value) { applyRailChrome = value; },
9150
+ get artifactSplitRoot() { return artifactSplitRoot; },
9151
+ get body() { return body; },
9152
+ get config() { return config; },
9153
+ get container() { return container; },
9154
+ get conversationOpenPendingEl() { return conversationOpenPendingEl; },
9155
+ set conversationOpenPendingEl(value) { conversationOpenPendingEl = value; },
9156
+ get conversationOpenTakeover() { return conversationOpenTakeover; },
9157
+ set conversationOpenTakeover(value) { conversationOpenTakeover = value; },
9158
+ currentKeyPrefix,
9159
+ destroyCallbacks,
9160
+ eventBus,
9161
+ get footer() { return footer; },
9162
+ get header() { return header; },
9163
+ get historyChromeSync() { return historyChromeSync; },
9164
+ set historyChromeSync(value) { historyChromeSync = value; },
9165
+ historyFeatureEnabled,
9166
+ get historyInternals() { return historyInternals; },
9167
+ set historyInternals(value) { historyInternals = value; },
9168
+ get historyPresentation() { return historyPresentation; },
9169
+ set historyPresentation(value) { historyPresentation = value; },
9170
+ get historySessionState() { return historySessionState; },
9171
+ get historyVisible() { return historyVisible; },
9172
+ set historyVisible(value) { historyVisible = value; },
9173
+ get isStreaming() { return isStreaming; },
9174
+ jumpToBottomInstant,
9175
+ get lastAppliedMessages() { return lastAppliedMessages; },
9176
+ set lastAppliedMessages(value) { lastAppliedMessages = value; },
9177
+ get launcherEnabled() { return launcherEnabled; },
9178
+ get launcherSurfaceInstance() { return launcherSurfaceInstance; },
9179
+ maybeFocusInput,
9180
+ messageCache,
9181
+ get messagesWrapper() { return messagesWrapper; },
9182
+ mount,
9183
+ get open() { return open; },
9184
+ panel,
9185
+ panelElements,
9186
+ get persistentMetadata() { return persistentMetadata; },
9187
+ set persistentMetadata(value) { persistentMetadata = value; },
9188
+ plugins,
9189
+ get reapplyHistoryHostChrome() { return reapplyHistoryHostChrome; },
9190
+ set reapplyHistoryHostChrome(value) { reapplyHistoryHostChrome = value; },
9191
+ repinAnchoredMessage,
9192
+ resetAnchorState,
9193
+ restoreScrollPosition,
9194
+ resumeAutoScroll,
9195
+ runStorageMutation,
9196
+ get session() { return session; },
9197
+ setActiveConversationSummary,
9198
+ storageAdapter,
9199
+ get suppressScrollSend() { return suppressScrollSend; },
9200
+ set suppressScrollSend(value) { suppressScrollSend = value; },
9201
+ syncScrollToBottomButton,
9202
+ updateWelcome,
9203
+ getHistoryProviderFactory,
9204
+ historyErrors: { HistoryClientError, HistoryProviderError },
9205
+ isDockedMountMode,
9206
+ renderLucideIcon,
9207
+ loadHistoryView,
9208
+ createHeaderIconButton,
9209
+ attachTooltip,
9210
+ };
9211
+
9212
+ const startHistoryShell = (module: HistoryShellModule): HistoryShell | null => {
9213
+ if (!historyShell && !historyShellTornDown) {
9214
+ historyShell = module.createHistoryShell(historyShellContext);
9215
+ // The rail collapse combo registers through the shell that owns the rail.
9216
+ if (historyShell.railCollapseShortcut()) syncShortcuts();
9217
+ }
9218
+ return historyShell;
9219
+ };
9220
+ const ensureHistoryShell = (): Promise<HistoryShell | null> => {
9221
+ if (historyShell) return Promise.resolve(historyShell);
9222
+ const ready = getHistoryShellSync();
9223
+ if (ready) return Promise.resolve(startHistoryShell(ready));
9224
+ historyShellLoad ??= loadHistoryShell().then(startHistoryShell, (error) => {
9225
+ historyShellLoad = null;
9226
+ throw error;
9227
+ });
9228
+ return historyShellLoad;
9229
+ };
9230
+ /** Runs a history API call, synchronously once the shell is available. */
9231
+ const withHistoryShell = <T>(
9232
+ run: (shell: HistoryShell) => Promise<T>
9233
+ ): Promise<T> => {
9234
+ const ready = getHistoryShellSync();
9235
+ const shell = historyShell ?? (ready ? startHistoryShell(ready) : null);
9236
+ if (shell) return run(shell);
9237
+ return ensureHistoryShell().then((loaded) => {
9238
+ if (!loaded) throw new Error("[AgentWidget] The widget was destroyed");
9239
+ return run(loaded);
9240
+ });
9241
+ };
9242
+ const syncHistoryPresentation = (): void => {
9243
+ historyShell?.syncHistoryPresentation();
11579
9244
  };
11580
-
11581
- installHistoryProvider();
11582
- syncHistoryChromeImpl();
11583
9245
  destroyCallbacks.push(() => {
11584
- unsubscribeHistoryAvailability?.();
11585
- unsubscribeHistoryIdentity?.();
11586
- // An open in flight (a hover this teardown raced) must not mount after it.
11587
- historyOpenToken += 1;
11588
- // A pending exit still owns a mounted surface and a live timer.
11589
- settleHistoryExit();
11590
- historySurface?.dispose();
11591
- historySurface?.view.destroy();
11592
- historySurface = null;
9246
+ historyShellTornDown = true;
11593
9247
  });
9248
+ if (historyFeatureEnabled()) {
9249
+ void ensureHistoryShell()
9250
+ .catch(() => {})
9251
+ .finally(resolveHistoryShellGate);
9252
+ }
11594
9253
 
11595
9254
  // Client-token init on mount is reserved for widgets that need a session at
11596
9255
  // boot: visitor history (boot reconciliation) and `sessionInit: 'mount'`.
@@ -11606,11 +9265,12 @@ export const createAgentExperience = (
11606
9265
  .then(() => {
11607
9266
  // Boot resume is authoritative only after reconciliation; the client
11608
9267
  // already gated its init on `historyBootstrapReady`.
11609
- if (!historyAvailable()) return undefined;
11610
- return session.reconcileBootConversation({ scope: historyScope() });
9268
+ const shell = historyShell;
9269
+ if (!shell?.historyAvailable()) return undefined;
9270
+ return session.reconcileBootConversation({ scope: shell.historyScope() });
11611
9271
  })
11612
9272
  .then(() => {
11613
- syncEarlierMessagesPill();
9273
+ historyShell?.syncEarlierMessagesPill();
11614
9274
  })
11615
9275
  .catch((err) => {
11616
9276
  if (config.debug) {
@@ -11851,7 +9511,7 @@ export const createAgentExperience = (
11851
9511
  let composerNoticeTimer: ReturnType<typeof setTimeout> | null = null;
11852
9512
 
11853
9513
  /** Transient message in the status region; a lock reason always outranks it. */
11854
- function showComposerNotice(text: string): void {
9514
+ function showComposerNotice(text: string, ms = 4000): void {
11855
9515
  announce(text);
11856
9516
  if (isComposerBar() || !statusText) return;
11857
9517
  if (statusText.hasAttribute(COMPOSER_REASON_ATTR)) return;
@@ -11876,7 +9536,7 @@ export const createAgentExperience = (
11876
9536
  status
11877
9537
  );
11878
9538
  }
11879
- }, 4000);
9539
+ }, ms);
11880
9540
  }
11881
9541
 
11882
9542
  /** Put the deferred submission back in the editable draft and drop the card. */
@@ -12469,13 +10129,7 @@ export const createAgentExperience = (
12469
10129
  let speechRecognition: any = null;
12470
10130
  let isRecording = false;
12471
10131
  let pauseTimer: number | null = null;
12472
- let originalMicStyles: {
12473
- backgroundColor: string;
12474
- color: string;
12475
- borderColor: string;
12476
- iconName: string;
12477
- iconSize: number;
12478
- } | null = null;
10132
+ let originalMicStyles: OriginalMicStyles | null = null;
12479
10133
 
12480
10134
  /**
12481
10135
  * `voiceRecognition.completionBehavior` (roadmap section 14). Default stays
@@ -12772,142 +10426,39 @@ export const createAgentExperience = (
12772
10426
  };
12773
10427
 
12774
10428
 
12775
- // --- Helpers to store/restore original mic button state ---
12776
-
12777
- const storeOriginalMicStyles = () => {
12778
- if (!micButton || originalMicStyles) return; // Already stored
12779
- const voiceConfig = config.voiceRecognition ?? {};
12780
- originalMicStyles = {
12781
- backgroundColor: micButton.style.backgroundColor,
12782
- color: micButton.style.color,
12783
- borderColor: micButton.style.borderColor,
12784
- iconName: voiceConfig.iconName ?? "mic",
12785
- iconSize: parseFloat(voiceConfig.iconSize ?? "") || COMPOSER_CONTROL_ICON_FALLBACK_PX,
10429
+ // --- Session-voice (Runtype / custom) mic state styling ---
10430
+ // The per-state styling ships in the lazy voice-runtime chunk
10431
+ // (`voice/mic-state-styles.ts`). These states only arise from a provider,
10432
+ // which setupVoice builds from that same chunk, so it is already loaded here;
10433
+ // the async fallback only covers a call that races the first load.
10434
+ let micStateStyles: MicStateStyles | null = null;
10435
+ const withMicStateStyles = (run: (styles: MicStateStyles) => void): void => {
10436
+ const apply = (mod: VoiceRuntimeModule) => {
10437
+ micStateStyles ??= mod.createMicStateStyles({
10438
+ mic: () => micButton,
10439
+ config: () => config,
10440
+ session: () => session,
10441
+ get original() {
10442
+ return originalMicStyles;
10443
+ },
10444
+ set original(next) {
10445
+ originalMicStyles = next;
10446
+ },
10447
+ setMicState,
10448
+ renderIcon: renderLucideIcon,
10449
+ iconFallbackPx: COMPOSER_CONTROL_ICON_FALLBACK_PX,
10450
+ });
10451
+ run(micStateStyles);
12786
10452
  };
10453
+ const mod = getVoiceRuntimeSync();
10454
+ if (mod) apply(mod);
10455
+ else loadVoiceRuntime().then(apply, () => {});
12787
10456
  };
12788
-
12789
- /** Swap the mic button's SVG icon */
12790
- const swapMicIcon = (iconName: string, color: string) => {
12791
- if (!micButton) return;
12792
- const existingSvg = micButton.querySelector("svg");
12793
- if (existingSvg) existingSvg.remove();
12794
- const size = originalMicStyles?.iconSize ?? (parseFloat(config.voiceRecognition?.iconSize ?? "") || COMPOSER_CONTROL_ICON_FALLBACK_PX);
12795
- const newSvg = renderLucideIcon(iconName, size, color, 1.5);
12796
- if (newSvg) micButton.appendChild(newSvg);
12797
- };
12798
-
12799
- /** Remove all voice state CSS classes */
12800
- const removeAllVoiceStateClasses = () => {
12801
- if (!micButton) return;
12802
- micButton.classList.remove("persona-voice-recording", "persona-voice-processing", "persona-voice-speaking");
12803
- };
12804
-
12805
- // --- Per-state style application ---
12806
-
12807
- const applyRuntypeMicRecordingStyles = () => {
12808
- if (!micButton) return;
12809
- storeOriginalMicStyles();
12810
- const voiceConfig = config.voiceRecognition ?? {};
12811
- const recordingBackgroundColor = voiceConfig.recordingBackgroundColor;
12812
- const recordingIconColor = voiceConfig.recordingIconColor;
12813
- const recordingBorderColor = voiceConfig.recordingBorderColor;
12814
- removeAllVoiceStateClasses();
12815
- micButton.classList.add("persona-voice-recording");
12816
- setMicState("recording");
12817
- micButton.style.backgroundColor = recordingBackgroundColor ?? "var(--persona-voice-recording-bg, #ef4444)";
12818
- micButton.style.color = recordingIconColor ?? "var(--persona-voice-recording-indicator, #ffffff)";
12819
- if (recordingIconColor) {
12820
- const svg = micButton.querySelector("svg");
12821
- if (svg) svg.setAttribute("stroke", recordingIconColor);
12822
- }
12823
- if (recordingBorderColor) micButton.style.borderColor = recordingBorderColor;
12824
- micButton.setAttribute("aria-label", "Stop voice recognition");
12825
- };
12826
-
12827
- const applyRuntypeMicProcessingStyles = () => {
12828
- if (!micButton) return;
12829
- storeOriginalMicStyles();
12830
- const voiceConfig = config.voiceRecognition ?? {};
12831
- const interruptionMode = session.getVoiceInterruptionMode();
12832
- const iconName = voiceConfig.processingIconName ?? "loader";
12833
- const iconColor = voiceConfig.processingIconColor ?? originalMicStyles?.color ?? "";
12834
- const bgColor = voiceConfig.processingBackgroundColor ?? originalMicStyles?.backgroundColor ?? "";
12835
- const borderColor = voiceConfig.processingBorderColor ?? originalMicStyles?.borderColor ?? "";
12836
-
12837
- removeAllVoiceStateClasses();
12838
- micButton.classList.add("persona-voice-processing");
12839
- setMicState("processing");
12840
- micButton.style.backgroundColor = bgColor;
12841
- micButton.style.borderColor = borderColor;
12842
- const resolvedColor = iconColor || "currentColor";
12843
- micButton.style.color = resolvedColor;
12844
- swapMicIcon(iconName, resolvedColor);
12845
- micButton.setAttribute("aria-label", "Processing voice input");
12846
- // In "none" mode the button is not actionable during processing
12847
- if (interruptionMode === "none") {
12848
- micButton.style.cursor = "default";
12849
- }
12850
- };
12851
-
12852
- const applyRuntypeMicSpeakingStyles = () => {
12853
- if (!micButton) return;
12854
- storeOriginalMicStyles();
12855
- const voiceConfig = config.voiceRecognition ?? {};
12856
- const interruptionMode = session.getVoiceInterruptionMode();
12857
- // Default icon depends on interruption mode:
12858
- // "square" for cancel, "mic" for barge-in (hot mic), "volume-2" otherwise
12859
- const defaultSpeakingIcon = interruptionMode === "cancel" ? "square"
12860
- : interruptionMode === "barge-in" ? "mic"
12861
- : "volume-2";
12862
- const iconName = voiceConfig.speakingIconName ?? defaultSpeakingIcon;
12863
- const iconColor = voiceConfig.speakingIconColor
12864
- ?? (interruptionMode === "barge-in" ? (voiceConfig.recordingIconColor ?? originalMicStyles?.color ?? "") : (originalMicStyles?.color ?? ""));
12865
- const bgColor = voiceConfig.speakingBackgroundColor
12866
- ?? (interruptionMode === "barge-in" ? (voiceConfig.recordingBackgroundColor ?? "var(--persona-voice-recording-bg, #ef4444)") : (originalMicStyles?.backgroundColor ?? ""));
12867
- const borderColor = voiceConfig.speakingBorderColor
12868
- ?? (interruptionMode === "barge-in" ? (voiceConfig.recordingBorderColor ?? "") : (originalMicStyles?.borderColor ?? ""));
12869
-
12870
- removeAllVoiceStateClasses();
12871
- micButton.classList.add("persona-voice-speaking");
12872
- setMicState("speaking");
12873
- micButton.style.backgroundColor = bgColor;
12874
- micButton.style.borderColor = borderColor;
12875
- const resolvedColor = iconColor || "currentColor";
12876
- micButton.style.color = resolvedColor;
12877
- swapMicIcon(iconName, resolvedColor);
12878
-
12879
- // aria-label varies by interruption mode
12880
- const ariaLabel = interruptionMode === "cancel"
12881
- ? "Stop playback and re-record"
12882
- : interruptionMode === "barge-in"
12883
- ? "Speak to interrupt"
12884
- : "Agent is speaking";
12885
- micButton.setAttribute("aria-label", ariaLabel);
12886
- // In "none" mode the button is not actionable during speaking
12887
- if (interruptionMode === "none") {
12888
- micButton.style.cursor = "default";
12889
- }
12890
- // In "barge-in" mode, add recording class to show mic is hot
12891
- if (interruptionMode === "barge-in") {
12892
- micButton.classList.add("persona-voice-recording");
12893
- }
12894
- };
12895
-
10457
+ const applyRuntypeMicRecordingStyles = () => withMicStateStyles((s) => s.recording());
10458
+ const applyRuntypeMicProcessingStyles = () => withMicStateStyles((s) => s.processing());
10459
+ const applyRuntypeMicSpeakingStyles = () => withMicStateStyles((s) => s.speaking());
12896
10460
  /** Restore mic button to idle state (icon, colors, aria-label, cursor) */
12897
- const removeRuntypeMicStateStyles = () => {
12898
- if (!micButton) return;
12899
- removeAllVoiceStateClasses();
12900
- setMicState("idle");
12901
- if (originalMicStyles) {
12902
- micButton.style.backgroundColor = originalMicStyles.backgroundColor ?? "";
12903
- micButton.style.color = originalMicStyles.color ?? "";
12904
- micButton.style.borderColor = originalMicStyles.borderColor ?? "";
12905
- swapMicIcon(originalMicStyles.iconName, originalMicStyles.color || "currentColor");
12906
- originalMicStyles = null;
12907
- }
12908
- micButton.style.cursor = "";
12909
- micButton.setAttribute("aria-label", "Start voice recognition");
12910
- };
10461
+ const removeRuntypeMicStateStyles = () => withMicStateStyles((s) => s.reset());
12911
10462
 
12912
10463
  // Wire up mic button click handler
12913
10464
  const handleMicButtonClick = () => {
@@ -12981,6 +10532,62 @@ export const createAgentExperience = (
12981
10532
 
12982
10533
  composerVoiceBridge = handleMicButtonClick;
12983
10534
 
10535
+ // Voice prewarm on mic intent (`voiceRecognition.prewarm`). Delegated on the
10536
+ // mount so composer rebuilds stay covered, and `config` is read at event time
10537
+ // so `update()` applies without re-wiring. Default: 'hover' in client token
10538
+ // mode, off otherwise.
10539
+ const warmVoice = () => session.prewarmVoice();
10540
+ const voicePrewarmSetting = () => {
10541
+ const voice = config.voiceRecognition;
10542
+ if (voice?.enabled !== true) return false;
10543
+ return voice.prewarm ?? (config.clientToken ? "hover" : false);
10544
+ };
10545
+ // `pointerover` covers mouse hover and precedes a touch's pointer-down;
10546
+ // `focusin` covers keyboard focus.
10547
+ const handleVoicePrewarmIntent = (event: Event) => {
10548
+ if (voicePrewarmSetting() !== "hover") return;
10549
+ if (micButton?.contains(event.target as Node)) warmVoice();
10550
+ };
10551
+ const voicePrewarmEvents = ["pointerover", "pointerdown", "focusin"];
10552
+ voicePrewarmEvents.forEach((type) => mount.addEventListener(type, handleVoicePrewarmIntent));
10553
+ // A custom prewarm hook is bound to one mic button: it re-runs (after its
10554
+ // cleanup) when the button is rebuilt or `update()` swaps the function.
10555
+ let voicePrewarmHook: AgentWidgetVoicePrewarmHook | undefined;
10556
+ let voicePrewarmHookButton: HTMLButtonElement | null = null;
10557
+ let voicePrewarmHookCleanup: ReturnType<AgentWidgetVoicePrewarmHook>;
10558
+ // Host hook code may throw; neither setup nor cleanup may break the widget.
10559
+ const releaseVoicePrewarmHook = () => {
10560
+ const cleanup = voicePrewarmHookCleanup;
10561
+ voicePrewarmHookCleanup = undefined;
10562
+ try {
10563
+ if (typeof cleanup === "function") cleanup();
10564
+ } catch {
10565
+ // ignored, see above
10566
+ }
10567
+ };
10568
+ const syncVoicePrewarmHook = () => {
10569
+ const setting = voicePrewarmSetting();
10570
+ const next = typeof setting === "function" && micButton ? setting : undefined;
10571
+ const button = next ? micButton : null;
10572
+ if (next === voicePrewarmHook && button === voicePrewarmHookButton) return;
10573
+ releaseVoicePrewarmHook();
10574
+ voicePrewarmHook = next;
10575
+ voicePrewarmHookButton = button;
10576
+ if (!next || !button) return;
10577
+ try {
10578
+ voicePrewarmHookCleanup = next({ warm: warmVoice, micButton: button, mount });
10579
+ } catch {
10580
+ // ignored, see above
10581
+ }
10582
+ };
10583
+ syncVoicePrewarmHook();
10584
+ destroyCallbacks.push(() => {
10585
+ voicePrewarmEvents.forEach((type) =>
10586
+ mount.removeEventListener(type, handleVoicePrewarmIntent)
10587
+ );
10588
+ releaseVoicePrewarmHook();
10589
+ });
10590
+
12984
10591
  if (micButton) {
12985
10592
  // The click listener itself is registered by `wireComposerSurface`, so a
12986
10593
  // composer rebuild unwires it with the rest of the surface.
@@ -13453,8 +11060,9 @@ export const createAgentExperience = (
13453
11060
  clearChatButton.addEventListener("click", () => {
13454
11061
  // With history available this affordance is "New conversation": a local
13455
11062
  // view clear would leave the server record open and unreachable.
13456
- if (historyAvailable()) {
13457
- void startNewConversation({ focusComposer: true }).catch((error) => {
11063
+ const shell = historyShell;
11064
+ if (shell?.historyAvailable()) {
11065
+ void shell.startNewConversation({ focusComposer: true }).catch((error) => {
13458
11066
  if (config.debug) {
13459
11067
  // eslint-disable-next-line no-console
13460
11068
  console.warn("[AgentWidget] New conversation failed:", error);
@@ -13578,6 +11186,7 @@ export const createAgentExperience = (
13578
11186
  if (micButton) {
13579
11187
  composerBindings.addListener(micButton, "click", handleMicButtonClick);
13580
11188
  }
11189
+ syncVoicePrewarmHook();
13581
11190
  };
13582
11191
 
13583
11192
  wireComposerSurface();
@@ -14295,7 +11904,7 @@ export const createAgentExperience = (
14295
11904
  closeButtonWrapper.className = "persona-absolute persona-top-4 persona-right-4 persona-z-50";
14296
11905
  // A mounted rail owns the conversation column; anchoring to the
14297
11906
  // container would float the button over the rail.
14298
- const anchor = railColumn ?? container;
11907
+ const anchor = historyShell?.railColumn ?? container;
14299
11908
  anchor.style.position = "relative";
14300
11909
  anchor.appendChild(closeButtonWrapper);
14301
11910
  } else {
@@ -14434,7 +12043,7 @@ export const createAgentExperience = (
14434
12043
  // Position to the left of the close button (which is at right: 1rem/16px)
14435
12044
  // Close button is ~32px wide, plus small gap = 48px from right
14436
12045
  clearChatButtonWrapper.style.right = "48px";
14437
- const anchor = railColumn ?? container;
12046
+ const anchor = historyShell?.railColumn ?? container;
14438
12047
  anchor.style.position = "relative";
14439
12048
  anchor.appendChild(clearChatButtonWrapper);
14440
12049
  } else {
@@ -14584,13 +12193,17 @@ export const createAgentExperience = (
14584
12193
  config.getIdentityProof !== previousIdentityProof ||
14585
12194
  config.clientToken !== previousClientToken
14586
12195
  ) {
14587
- closeHistory({ restoreFocus: false });
14588
- installHistoryProvider();
12196
+ historyShell?.closeHistory({ restoreFocus: false });
12197
+ historyShell?.installHistoryProvider();
14589
12198
  }
14590
- syncHistoryChromeImpl();
12199
+ historyShell?.syncHistoryChromeImpl();
14591
12200
  // Presentation may have flipped between panel and rail; the open view
14592
12201
  // instance moves hosts rather than being recreated.
14593
12202
  syncHistoryPresentation();
12203
+ // Turning history on loads the shell, which installs and syncs itself.
12204
+ if (historyFeatureEnabled() && !historyShell) {
12205
+ void ensureHistoryShell().catch(() => {});
12206
+ }
14594
12207
  renderMessagesWithPlugins(
14595
12208
  messagesWrapper,
14596
12209
  session.getMessages(),
@@ -14764,6 +12377,7 @@ export const createAgentExperience = (
14764
12377
  }
14765
12378
  }
14766
12379
  }
12380
+ syncVoicePrewarmHook();
14767
12381
 
14768
12382
  // Update attachment button visibility based on attachments config
14769
12383
  const attachmentsEnabled = config.attachments?.enabled === true;
@@ -15482,30 +13096,40 @@ export const createAgentExperience = (
15482
13096
  conversationId: string,
15483
13097
  opts?: { focus?: boolean }
15484
13098
  ): Promise<void> {
15485
- return openHistoryConversation(conversationId, {
15486
- focusComposer: opts?.focus === true,
15487
- });
13099
+ return withHistoryShell((shell) =>
13100
+ shell.openHistoryConversation(conversationId, {
13101
+ focusComposer: opts?.focus === true,
13102
+ })
13103
+ );
15488
13104
  },
15489
13105
  startNewConversation(opts?: { focus?: boolean }): Promise<void> {
15490
- return startNewConversation({ focusComposer: opts?.focus === true });
13106
+ return withHistoryShell((shell) =>
13107
+ shell.startNewConversation({ focusComposer: opts?.focus === true })
13108
+ );
15491
13109
  },
15492
13110
  warmSession(): void {
15493
13111
  warmSession();
15494
13112
  },
15495
13113
  deleteConversation(conversationId: string): Promise<void> {
15496
- return deleteHistoryConversation(conversationId);
13114
+ return withHistoryShell((shell) =>
13115
+ shell.deleteHistoryConversation(conversationId)
13116
+ );
15497
13117
  },
15498
13118
  renameConversation(conversationId, title) {
15499
- return updateHistoryConversation(conversationId, { title });
13119
+ return withHistoryShell((shell) =>
13120
+ shell.updateHistoryConversation(conversationId, { title })
13121
+ );
15500
13122
  },
15501
13123
  setConversationStarred(conversationId, starred) {
15502
- return updateHistoryConversation(conversationId, { starred });
13124
+ return withHistoryShell((shell) =>
13125
+ shell.updateHistoryConversation(conversationId, { starred })
13126
+ );
15503
13127
  },
15504
13128
  clearConversationHistory(opts) {
15505
- return clearConversationHistory(opts);
13129
+ return withHistoryShell((shell) => shell.clearConversationHistory(opts));
15506
13130
  },
15507
13131
  resetHistoryIdentity(): Promise<{ remoteRevocationConfirmed: boolean }> {
15508
- return resetHistoryIdentity();
13132
+ return withHistoryShell((shell) => shell.resetHistoryIdentity());
15509
13133
  },
15510
13134
  async getVisitorToken(): Promise<string | null> {
15511
13135
  const store = visitorStore;
@@ -15514,6 +13138,7 @@ export const createAgentExperience = (
15514
13138
  return store === visitorStore ? token : null;
15515
13139
  },
15516
13140
  getHistoryIdentityStatus(): HistoryIdentityStatus {
13141
+ const historyProvider = historyShell?.historyProvider;
15517
13142
  if (!historyProvider) {
15518
13143
  return historyFeatureEnabled()
15519
13144
  ? { state: "unavailable", reason: "ineligible_mode" }
@@ -15522,13 +13147,17 @@ export const createAgentExperience = (
15522
13147
  return historyProvider.getIdentityStatus();
15523
13148
  },
15524
13149
  showHistory(opts): Promise<void> {
15525
- return openHistory({
15526
- ...(opts?.returnSurface ? { returnSurface: opts.returnSurface } : {}),
15527
- ...(opts?.focus !== undefined ? { focus: opts.focus } : {}),
15528
- });
13150
+ // Disabled history never loads the shell just to report unavailable.
13151
+ if (!historyFeatureEnabled()) return Promise.resolve();
13152
+ return withHistoryShell((shell) =>
13153
+ shell.openHistory({
13154
+ ...(opts?.returnSurface ? { returnSurface: opts.returnSurface } : {}),
13155
+ ...(opts?.focus !== undefined ? { focus: opts.focus } : {}),
13156
+ })
13157
+ );
15529
13158
  },
15530
13159
  hideHistory(opts): void {
15531
- closeHistory(
13160
+ historyShell?.closeHistory(
15532
13161
  opts?.restoreFocus !== undefined
15533
13162
  ? { restoreFocus: opts.restoreFocus }
15534
13163
  : undefined