@chatterfly/widget 0.3.0 → 0.5.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.
package/dist/index.js CHANGED
@@ -15,11 +15,68 @@ var WidgetError = class {
15
15
  return this.message;
16
16
  }
17
17
  };
18
- var RECONNECT_DELAY_MS = 2e3;
18
+
19
+ // src/strings.ts
20
+ var defaultStrings = {
21
+ statusInitialising: "Initialising\u2026",
22
+ statusConnecting: "Connecting\u2026",
23
+ statusRunning: "Running\u2026",
24
+ statusCompletedTitle: "Completed",
25
+ statusCompletedBody: "This workflow run has finished.",
26
+ statusErrorTitle: "Something went wrong",
27
+ statusOfflineTitle: "Connection lost",
28
+ statusOfflineBody: "Unable to reach the server. Please check your connection and refresh.",
29
+ statusExpiredTitle: "Session expired",
30
+ statusExpiredBody: "This conversation's session has expired. Start a new one to continue.",
31
+ statusListening: "Listening\u2026",
32
+ resumingConversation: "Resuming conversation\u2026",
33
+ reconnecting: "Reconnecting\u2026",
34
+ conversationCompleted: "Conversation completed.",
35
+ somethingWentWrong: "Something went wrong",
36
+ chatInputPlaceholder: "Type a message\u2026",
37
+ sendButton: "Send",
38
+ handBackButton: "Hand Back",
39
+ converseDoneButton: "I'm done",
40
+ startConversation: "Start conversation",
41
+ clickToStartDescription: "Click below to begin.",
42
+ resumeTitle: "Continue where you left off?",
43
+ resumeContinue: "Continue",
44
+ resumeRestart: "Start fresh",
45
+ startNewConversation: "Start new conversation",
46
+ conversationEnded: "This conversation has ended."
47
+ };
48
+ function resolveStrings(overrides) {
49
+ return overrides ? { ...defaultStrings, ...overrides } : defaultStrings;
50
+ }
51
+ var RECONNECT_BASE_DELAY_MS = 2e3;
52
+ var RECONNECT_MAX_DELAY_MS = 3e4;
19
53
  var MAX_RECONNECT_ATTEMPTS = 5;
20
- var TERMINAL_STATUSES = ["completed", "error", "offline"];
54
+ var TERMINAL_STATUSES = ["completed", "error", "offline", "expired"];
55
+ var PARKED_STATUSES = [
56
+ "awaiting_input",
57
+ "awaiting_voice",
58
+ "awaiting_form",
59
+ "awaiting_chat",
60
+ "awaiting_editor"
61
+ ];
62
+ var DEFAULT_IDLE_DISCONNECT_MS = 5 * 6e4;
63
+ var DEFAULT_POLL_INTERVAL_MS = 45e3;
64
+ var DEFAULT_HIBERNATE_AFTER_MS = 60 * 6e4;
65
+ function computeReconnectDelay(attempt) {
66
+ const cap = Math.min(
67
+ RECONNECT_MAX_DELAY_MS,
68
+ RECONNECT_BASE_DELAY_MS * 2 ** attempt
69
+ );
70
+ return Math.random() * cap;
71
+ }
21
72
  function useRunStream(config, onEvent) {
73
+ var _a, _b, _c;
22
74
  const { runId, participantToken, apiBase } = config;
75
+ const policyConfig = config.connectionPolicy;
76
+ const dormancyDisabled = policyConfig === "always-on";
77
+ const idleDisconnectMs = (_a = !dormancyDisabled && typeof policyConfig === "object" ? policyConfig == null ? void 0 : policyConfig.idleDisconnectMs : void 0) != null ? _a : DEFAULT_IDLE_DISCONNECT_MS;
78
+ const pollIntervalMs = (_b = !dormancyDisabled && typeof policyConfig === "object" ? policyConfig == null ? void 0 : policyConfig.pollIntervalMs : void 0) != null ? _b : DEFAULT_POLL_INTERVAL_MS;
79
+ const hibernateAfterMs = (_c = !dormancyDisabled && typeof policyConfig === "object" ? policyConfig == null ? void 0 : policyConfig.hibernateAfterMs : void 0) != null ? _c : DEFAULT_HIBERNATE_AFTER_MS;
23
80
  const [status, setStatus] = react.useState("idle");
24
81
  const [activeSession, setActiveSession] = react.useState(null);
25
82
  const [messages, setMessages] = react.useState([]);
@@ -28,11 +85,19 @@ function useRunStream(config, onEvent) {
28
85
  const [output, setOutput] = react.useState(null);
29
86
  const lastSeqRef = react.useRef(0);
30
87
  const [lastSeq, setLastSeq] = react.useState(0);
88
+ const [currentToken, setCurrentToken] = react.useState(participantToken);
89
+ const currentTokenRef = react.useRef(currentToken);
90
+ currentTokenRef.current = currentToken;
91
+ react.useEffect(() => setCurrentToken(participantToken), [participantToken]);
31
92
  const wsRef = react.useRef(null);
32
93
  const statusRef = react.useRef("idle");
33
94
  const reconnectTimerRef = react.useRef(null);
34
95
  const replayTimeoutRef = react.useRef(null);
35
96
  const mountedRef = react.useRef(true);
97
+ const connectionStateRef = react.useRef("active");
98
+ const idleTimerRef = react.useRef(null);
99
+ const hibernateTimerRef = react.useRef(null);
100
+ const pollTimerRef = react.useRef(null);
36
101
  const reconnectAttemptsRef = react.useRef(0);
37
102
  const manualDisconnectRef = react.useRef(false);
38
103
  const onEventRef = react.useRef(onEvent);
@@ -42,8 +107,8 @@ function useRunStream(config, onEvent) {
42
107
  setStatus(next);
43
108
  }, []);
44
109
  const authHeaders = react.useCallback(
45
- () => ({ Authorization: `Bearer ${participantToken}` }),
46
- [participantToken]
110
+ () => ({ Authorization: `Bearer ${currentTokenRef.current}` }),
111
+ []
47
112
  );
48
113
  const mergeTimeline = react.useCallback(
49
114
  (incoming) => {
@@ -65,9 +130,18 @@ function useRunStream(config, onEvent) {
65
130
  if (!mountedRef.current) return;
66
131
  if (!runId || !apiBase) return;
67
132
  manualDisconnectRef.current = false;
133
+ connectionStateRef.current = "active";
134
+ if (pollTimerRef.current) {
135
+ clearInterval(pollTimerRef.current);
136
+ pollTimerRef.current = null;
137
+ }
138
+ if (hibernateTimerRef.current) {
139
+ clearTimeout(hibernateTimerRef.current);
140
+ hibernateTimerRef.current = null;
141
+ }
68
142
  updateStatus("connecting");
69
143
  const wsUrl = apiBase.replace(/^http/, "ws") + `/api/participant/runs/${runId}/stream`;
70
- const params = new URLSearchParams({ token: participantToken });
144
+ const params = new URLSearchParams({ token: currentTokenRef.current });
71
145
  const ws = new WebSocket(`${wsUrl}?${params}`);
72
146
  wsRef.current = ws;
73
147
  ws.onopen = () => {
@@ -105,15 +179,128 @@ function useRunStream(config, onEvent) {
105
179
  if (isOffline) {
106
180
  updateStatus("offline");
107
181
  } else {
182
+ const attempt = reconnectAttemptsRef.current;
108
183
  reconnectAttemptsRef.current += 1;
109
- reconnectTimerRef.current = setTimeout(connect, RECONNECT_DELAY_MS);
184
+ reconnectTimerRef.current = setTimeout(
185
+ connect,
186
+ computeReconnectDelay(attempt)
187
+ );
110
188
  }
111
189
  }
112
190
  };
113
191
  }, [runId, participantToken, apiBase]);
192
+ const remintToken = react.useCallback(async () => {
193
+ try {
194
+ const res = await fetch(`${apiBase}/api/public/runs/${runId}/token`, {
195
+ method: "POST",
196
+ headers: { "Content-Type": "application/json" },
197
+ body: JSON.stringify({ participant_token: currentTokenRef.current })
198
+ });
199
+ if (!res.ok) return null;
200
+ const data = await res.json();
201
+ if (!data.participant_token) return null;
202
+ setCurrentToken(data.participant_token);
203
+ return data.participant_token;
204
+ } catch {
205
+ return null;
206
+ }
207
+ }, [apiBase, runId]);
208
+ const stopPolling = react.useCallback(() => {
209
+ if (pollTimerRef.current) {
210
+ clearInterval(pollTimerRef.current);
211
+ pollTimerRef.current = null;
212
+ }
213
+ if (hibernateTimerRef.current) {
214
+ clearTimeout(hibernateTimerRef.current);
215
+ hibernateTimerRef.current = null;
216
+ }
217
+ }, []);
218
+ const wake = react.useCallback(() => {
219
+ if (!mountedRef.current) return;
220
+ if (connectionStateRef.current === "active") return;
221
+ stopPolling();
222
+ reconnectAttemptsRef.current = 0;
223
+ connect();
224
+ }, [connect, stopPolling]);
225
+ const startPolling = react.useCallback(() => {
226
+ if (pollTimerRef.current) return;
227
+ pollTimerRef.current = setInterval(async () => {
228
+ if (!mountedRef.current) return;
229
+ try {
230
+ const res = await fetch(
231
+ `${apiBase}/api/participant/runs/${runId}/timeline?since_seq=${lastSeqRef.current}`,
232
+ { headers: { Authorization: `Bearer ${currentTokenRef.current}` } }
233
+ );
234
+ if (res.status === 401) {
235
+ const fresh = await remintToken();
236
+ if (!fresh) {
237
+ stopPolling();
238
+ updateStatus("expired");
239
+ }
240
+ return;
241
+ }
242
+ if (!res.ok) return;
243
+ const entries = await res.json();
244
+ if (Array.isArray(entries) && entries.length > 0) {
245
+ wake();
246
+ }
247
+ } catch {
248
+ }
249
+ }, pollIntervalMs);
250
+ hibernateTimerRef.current = setTimeout(() => {
251
+ connectionStateRef.current = "hibernating";
252
+ if (pollTimerRef.current) {
253
+ clearInterval(pollTimerRef.current);
254
+ pollTimerRef.current = null;
255
+ }
256
+ }, hibernateAfterMs);
257
+ }, [apiBase, runId, pollIntervalMs, hibernateAfterMs, remintToken, stopPolling, updateStatus, wake]);
258
+ const goDormant = react.useCallback(() => {
259
+ var _a2;
260
+ if (connectionStateRef.current !== "active") return;
261
+ connectionStateRef.current = "dormant";
262
+ manualDisconnectRef.current = true;
263
+ (_a2 = wsRef.current) == null ? void 0 : _a2.close();
264
+ wsRef.current = null;
265
+ startPolling();
266
+ }, [startPolling]);
267
+ react.useEffect(() => {
268
+ if (dormancyDisabled) return;
269
+ if (idleTimerRef.current) {
270
+ clearTimeout(idleTimerRef.current);
271
+ idleTimerRef.current = null;
272
+ }
273
+ if (PARKED_STATUSES.includes(status) && connectionStateRef.current === "active") {
274
+ idleTimerRef.current = setTimeout(goDormant, idleDisconnectMs);
275
+ }
276
+ return () => {
277
+ if (idleTimerRef.current) {
278
+ clearTimeout(idleTimerRef.current);
279
+ idleTimerRef.current = null;
280
+ }
281
+ };
282
+ }, [status, dormancyDisabled, idleDisconnectMs, goDormant]);
283
+ react.useEffect(() => {
284
+ if (dormancyDisabled) return;
285
+ const handleVisibility = () => {
286
+ if (document.visibilityState === "visible") wake();
287
+ };
288
+ document.addEventListener("visibilitychange", handleVisibility);
289
+ window.addEventListener("online", wake);
290
+ window.addEventListener("focus", wake);
291
+ window.addEventListener("pointerdown", wake);
292
+ window.addEventListener("keydown", wake);
293
+ return () => {
294
+ document.removeEventListener("visibilitychange", handleVisibility);
295
+ window.removeEventListener("online", wake);
296
+ window.removeEventListener("focus", wake);
297
+ window.removeEventListener("pointerdown", wake);
298
+ window.removeEventListener("keydown", wake);
299
+ };
300
+ }, [dormancyDisabled, wake]);
114
301
  function handleEvent(event) {
115
- var _a, _b, _c, _d, _e;
116
- (_a = onEventRef.current) == null ? void 0 : _a.call(onEventRef, event);
302
+ var _a2, _b2, _c2, _d, _e;
303
+ (_a2 = onEventRef.current) == null ? void 0 : _a2.call(onEventRef, event);
117
304
  switch (event.type) {
118
305
  case "timeline.replay": {
119
306
  mergeTimeline(event.payload);
@@ -150,7 +337,7 @@ function useRunStream(config, onEvent) {
150
337
  entry_context: event.entry_context,
151
338
  status: "open",
152
339
  messages: replayedMessages,
153
- document_content: (_b = event.document_content) != null ? _b : null
340
+ document_content: (_b2 = event.document_content) != null ? _b2 : null
154
341
  };
155
342
  setActiveSession(session);
156
343
  if (replayedMessages.length > 0) {
@@ -163,7 +350,7 @@ function useRunStream(config, onEvent) {
163
350
  } else if (event.layout === "form") {
164
351
  updateStatus("awaiting_form");
165
352
  } else {
166
- const surface = (_c = event.entry_context) == null ? void 0 : _c.surface;
353
+ const surface = (_c2 = event.entry_context) == null ? void 0 : _c2.surface;
167
354
  const isVoice = typeof surface === "string" && (surface === "widget/voice" || surface === "phone" || surface === "phone/outbound");
168
355
  if (isVoice) {
169
356
  updateStatus("awaiting_voice");
@@ -185,6 +372,9 @@ function useRunStream(config, onEvent) {
185
372
  ]);
186
373
  break;
187
374
  }
375
+ case "run_complete":
376
+ case "run_error":
377
+ break;
188
378
  case "run.completed":
189
379
  case "run.cancelled":
190
380
  setStreamingText("");
@@ -203,17 +393,21 @@ function useRunStream(config, onEvent) {
203
393
  mountedRef.current = true;
204
394
  reconnectTimerRef.current = setTimeout(connect, 0);
205
395
  return () => {
206
- var _a;
396
+ var _a2;
207
397
  mountedRef.current = false;
208
398
  if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
209
399
  if (replayTimeoutRef.current) clearTimeout(replayTimeoutRef.current);
210
- (_a = wsRef.current) == null ? void 0 : _a.close();
400
+ if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
401
+ if (pollTimerRef.current) clearInterval(pollTimerRef.current);
402
+ if (hibernateTimerRef.current) clearTimeout(hibernateTimerRef.current);
403
+ (_a2 = wsRef.current) == null ? void 0 : _a2.close();
211
404
  wsRef.current = null;
212
405
  };
213
406
  }, [connect]);
214
407
  const sendMessage = react.useCallback(
215
408
  async (content) => {
216
409
  if (!activeSession) return;
410
+ wake();
217
411
  setMessages((prev) => [
218
412
  ...prev,
219
413
  { role: "human", content }
@@ -240,12 +434,13 @@ function useRunStream(config, onEvent) {
240
434
  throw new Error(`sendMessage failed: ${res.status} ${text}`);
241
435
  }
242
436
  },
243
- [activeSession, apiBase, authHeaders, updateStatus]
437
+ [activeSession, apiBase, authHeaders, updateStatus, wake]
244
438
  );
245
439
  const submitHandback = react.useCallback(
246
440
  async (output2, idempotencyKey) => {
247
- var _a;
441
+ var _a2;
248
442
  if (!activeSession) return null;
443
+ wake();
249
444
  const body = { output: output2 };
250
445
  if (idempotencyKey) body.idempotency_key = idempotencyKey;
251
446
  let res;
@@ -267,7 +462,7 @@ function useRunStream(config, onEvent) {
267
462
  }
268
463
  if (res.status === 422) {
269
464
  const data = await res.json();
270
- return (_a = data.errors) != null ? _a : [{ field: "_", message: "Validation failed" }];
465
+ return (_a2 = data.errors) != null ? _a2 : [{ field: "_", message: "Validation failed" }];
271
466
  }
272
467
  if (!res.ok) {
273
468
  const text = await res.text();
@@ -278,13 +473,13 @@ function useRunStream(config, onEvent) {
278
473
  updateStatus("running");
279
474
  return null;
280
475
  },
281
- [activeSession, apiBase, authHeaders, updateStatus]
476
+ [activeSession, apiBase, authHeaders, updateStatus, wake]
282
477
  );
283
478
  const disconnect = react.useCallback(() => {
284
- var _a;
479
+ var _a2;
285
480
  manualDisconnectRef.current = true;
286
481
  if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
287
- (_a = wsRef.current) == null ? void 0 : _a.close();
482
+ (_a2 = wsRef.current) == null ? void 0 : _a2.close();
288
483
  wsRef.current = null;
289
484
  updateStatus("offline");
290
485
  }, [updateStatus]);
@@ -486,6 +681,7 @@ var widget_default = {
486
681
  formKvValue: "widget_formKvValue",
487
682
  formKvNested: "widget_formKvNested",
488
683
  activeInputArea: "widget_activeInputArea",
684
+ activeInputAreaVoice: "widget_activeInputAreaVoice",
489
685
  formTimelineWrapper: "widget_formTimelineWrapper",
490
686
  formScrollArea: "widget_formScrollArea",
491
687
  activeInputPrompt: "widget_activeInputPrompt",
@@ -499,9 +695,17 @@ var widget_default = {
499
695
  activeInputSubmit: "widget_activeInputSubmit",
500
696
  inlineError: "widget_inlineError",
501
697
  resumingBanner: "widget_resumingBanner",
698
+ reconnectingPill: "widget_reconnectingPill",
502
699
  terminalBanner: "widget_terminalBanner",
503
700
  terminalCompleted: "widget_terminalBanner widget_terminalCompleted",
504
701
  terminalError: "widget_terminalBanner widget_terminalError",
702
+ startNewConversationButton: "widget_startNewConversationButton",
703
+ gateCard: "widget_gateCard",
704
+ gateTitle: "widget_gateTitle",
705
+ gateDescription: "widget_gateDescription",
706
+ gateActions: "widget_gateActions",
707
+ gateButtonPrimary: "widget_gateButtonPrimary",
708
+ gateButtonSecondary: "widget_gateButtonSecondary",
505
709
  typingIndicator: "widget_typingIndicator",
506
710
  typingDot: "widget_typingDot",
507
711
  cfTyping: "widget_cfTyping",
@@ -525,13 +729,17 @@ var widget_default = {
525
729
  voiceRatingMatched: "widget_voiceRatingMatched",
526
730
  voiceRatingLabels: "widget_voiceRatingLabels",
527
731
  voiceTranscript: "widget_voiceTranscript",
528
- voiceTranscriptLabel: "widget_voiceTranscriptLabel",
732
+ voiceLiveLog: "widget_voiceLiveLog",
733
+ voiceLiveLogUser: "widget_voiceLiveLogUser",
734
+ voiceLiveLogAssistant: "widget_voiceLiveLogAssistant",
529
735
  voiceTranscriptText: "widget_voiceTranscriptText",
736
+ voiceTranscriptLabel: "widget_voiceTranscriptLabel",
530
737
  voiceError: "widget_voiceError",
531
738
  cfVoiceShake: "widget_cfVoiceShake",
532
739
  voiceOrbContainer: "widget_voiceOrbContainer",
533
- voiceOrbContainerSticky: "widget_voiceOrbContainerSticky",
740
+ voiceOrbRow: "widget_voiceOrbRow",
534
741
  voiceOrbHint: "widget_voiceOrbHint",
742
+ voiceAssistantStatus: "widget_voiceAssistantStatus",
535
743
  voiceOrb: "widget_voiceOrb",
536
744
  cfVoiceBreathe: "widget_cfVoiceBreathe",
537
745
  voiceOrbDisabled: "widget_voiceOrbDisabled",
@@ -540,12 +748,12 @@ var widget_default = {
540
748
  voiceOrbRing2: "widget_voiceOrbRing2",
541
749
  voiceOrb_idle: "widget_voiceOrb_idle",
542
750
  voiceOrb_listening: "widget_voiceOrb_listening",
543
- cfVoicePulse: "widget_cfVoicePulse",
544
751
  voiceOrb_speaking: "widget_voiceOrb_speaking",
545
- cfVoiceWave: "widget_cfVoiceWave",
546
752
  voiceOrb_processing: "widget_voiceOrb_processing",
547
753
  voiceOrb_confirming: "widget_voiceOrb_confirming",
548
754
  voiceOrb_error: "widget_voiceOrb_error",
755
+ cfVoicePulse: "widget_cfVoicePulse",
756
+ cfVoiceWave: "widget_cfVoiceWave",
549
757
  voiceAudioLevelBar: "widget_voiceAudioLevelBar",
550
758
  voiceMuteButton: "widget_voiceMuteButton",
551
759
  voiceConfirmation: "widget_voiceConfirmation",
@@ -2670,29 +2878,6 @@ function FormRenderer({
2670
2878
  ) })
2671
2879
  ] });
2672
2880
  }
2673
-
2674
- // src/strings.ts
2675
- var defaultStrings = {
2676
- statusInitialising: "Initialising\u2026",
2677
- statusConnecting: "Connecting\u2026",
2678
- statusRunning: "Running\u2026",
2679
- statusCompletedTitle: "Completed",
2680
- statusCompletedBody: "This workflow run has finished.",
2681
- statusErrorTitle: "Something went wrong",
2682
- statusOfflineTitle: "Connection lost",
2683
- statusOfflineBody: "Unable to reach the server. Please check your connection and refresh.",
2684
- statusListening: "Listening\u2026",
2685
- resumingConversation: "Resuming conversation\u2026",
2686
- conversationCompleted: "Conversation completed.",
2687
- somethingWentWrong: "Something went wrong",
2688
- chatInputPlaceholder: "Type a message\u2026",
2689
- sendButton: "Send",
2690
- handBackButton: "Hand Back",
2691
- converseDoneButton: "I'm done"
2692
- };
2693
- function resolveStrings(overrides) {
2694
- return overrides ? { ...defaultStrings, ...overrides } : defaultStrings;
2695
- }
2696
2881
  function StatusDisplay({ status, error, strings }) {
2697
2882
  const t = strings ? { ...defaultStrings, ...strings } : defaultStrings;
2698
2883
  switch (status) {
@@ -2722,6 +2907,11 @@ function StatusDisplay({ status, error, strings }) {
2722
2907
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: t.statusOfflineTitle }),
2723
2908
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.statusLabel} ${widget_default.statusError}`, children: t.statusOfflineBody })
2724
2909
  ] });
2910
+ case "expired":
2911
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.statusWrapper, children: [
2912
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: t.statusExpiredTitle }),
2913
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.statusLabel} ${widget_default.statusError}`, children: t.statusExpiredBody })
2914
+ ] });
2725
2915
  case "awaiting_voice":
2726
2916
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.statusWrapper, children: [
2727
2917
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.spinner, "aria-hidden": true }),
@@ -2733,6 +2923,7 @@ function StatusDisplay({ status, error, strings }) {
2733
2923
  }
2734
2924
  function VoiceOrb({
2735
2925
  state,
2926
+ inputLevel = 0,
2736
2927
  onPress,
2737
2928
  onRelease,
2738
2929
  disabled
@@ -2758,6 +2949,7 @@ function VoiceOrb({
2758
2949
  },
2759
2950
  [disabled, onRelease]
2760
2951
  );
2952
+ const level = Math.min(1, Math.max(0, inputLevel));
2761
2953
  return /* @__PURE__ */ jsxRuntime.jsxs(
2762
2954
  "button",
2763
2955
  {
@@ -2770,8 +2962,26 @@ function VoiceOrb({
2770
2962
  disabled,
2771
2963
  "aria-label": ariaForState(state),
2772
2964
  children: [
2773
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.voiceOrbRing1 }),
2774
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.voiceOrbRing2 }),
2965
+ /* @__PURE__ */ jsxRuntime.jsx(
2966
+ "span",
2967
+ {
2968
+ className: widget_default.voiceOrbRing1,
2969
+ style: {
2970
+ opacity: 0.18 + level * 0.42,
2971
+ transform: `scale(${1.08 + level * 0.24})`
2972
+ }
2973
+ }
2974
+ ),
2975
+ /* @__PURE__ */ jsxRuntime.jsx(
2976
+ "span",
2977
+ {
2978
+ className: widget_default.voiceOrbRing2,
2979
+ style: {
2980
+ opacity: 0.1 + level * 0.32,
2981
+ transform: `scale(${1.18 + level * 0.42})`
2982
+ }
2983
+ }
2984
+ ),
2775
2985
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.voiceOrbIcon, children: state === "listening" ? micIcon : state === "speaking" ? speakerIcon : micIcon })
2776
2986
  ]
2777
2987
  }
@@ -4144,13 +4354,29 @@ function VoiceContinuousRenderer({
4144
4354
  /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: () => handleConfirmation(false), children: "No, retry" })
4145
4355
  ] }),
4146
4356
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.voiceOrbContainer, children: [
4147
- /* @__PURE__ */ jsxRuntime.jsx(
4148
- VoiceOrb,
4149
- {
4150
- state: getOrbState(),
4151
- disabled: disabled || voiceState === "processing" || transcribing
4152
- }
4153
- ),
4357
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.voiceOrbRow, children: [
4358
+ /* @__PURE__ */ jsxRuntime.jsx(
4359
+ VoiceOrb,
4360
+ {
4361
+ state: getOrbState(),
4362
+ disabled: disabled || voiceState === "processing" || transcribing
4363
+ }
4364
+ ),
4365
+ /* @__PURE__ */ jsxRuntime.jsx(
4366
+ "button",
4367
+ {
4368
+ type: "button",
4369
+ "data-cf-voice-mute": "true",
4370
+ className: `${widget_default.voiceMuteButton}${isMuted ? " " + widget_default.voiceMuteButtonMuted : ""}`,
4371
+ onClick: handleMuteToggle,
4372
+ title: isMuted ? "Unmute microphone (Spacebar)" : "Mute microphone (Spacebar)",
4373
+ "aria-label": isMuted ? "Unmute microphone" : "Mute microphone",
4374
+ "aria-pressed": isMuted,
4375
+ "aria-keyshortcuts": "Space",
4376
+ children: isMuted ? "\u{1F507}" : "\u{1F3A4}"
4377
+ }
4378
+ )
4379
+ ] }),
4154
4380
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.voiceOrbStats, children: [
4155
4381
  /* @__PURE__ */ jsxRuntime.jsxs("span", { className: widget_default.voiceOrbHint, children: [
4156
4382
  isMuted && "\u{1F507} Muted",
@@ -4173,21 +4399,7 @@ function VoiceContinuousRenderer({
4173
4399
  Math.round(confidence * 100),
4174
4400
  "% confident"
4175
4401
  ] })
4176
- ] }),
4177
- /* @__PURE__ */ jsxRuntime.jsx(
4178
- "button",
4179
- {
4180
- type: "button",
4181
- "data-cf-voice-mute": "true",
4182
- className: `${widget_default.voiceMuteButton}${isMuted ? " " + widget_default.voiceMuteButtonMuted : ""}`,
4183
- onClick: handleMuteToggle,
4184
- title: isMuted ? "Unmute microphone (Spacebar)" : "Mute microphone (Spacebar)",
4185
- "aria-label": isMuted ? "Unmute microphone" : "Mute microphone",
4186
- "aria-pressed": isMuted,
4187
- "aria-keyshortcuts": "Space",
4188
- children: isMuted ? "\u{1F507}" : "\u{1F3A4}"
4189
- }
4190
- )
4402
+ ] })
4191
4403
  ] }),
4192
4404
  retryCount >= 3 && /* @__PURE__ */ jsxRuntime.jsx("a", { href: "#", className: widget_default.voiceTypeFallback, children: "Switch to typing mode" })
4193
4405
  ] });
@@ -4237,7 +4449,7 @@ class PcmCaptureProcessor extends AudioWorkletProcessor {
4237
4449
  this._buf = new Int16Array(this.frameSamples);
4238
4450
  this._pos = 0;
4239
4451
  this._acc = 0;
4240
- this._accCount = 0;
4452
+ this._accWeight = 0;
4241
4453
  }
4242
4454
 
4243
4455
  _emit() {
@@ -4252,18 +4464,24 @@ class PcmCaptureProcessor extends AudioWorkletProcessor {
4252
4464
  if (!input || !input[0]) return true;
4253
4465
  const ch = input[0];
4254
4466
  for (let i = 0; i < ch.length; i++) {
4255
- this._acc += ch[i];
4256
- this._accCount++;
4257
- if (this._accCount >= this.ratio) {
4258
- const avg = this._acc / this._accCount;
4259
- // Clamp to [-1, 1] then quantize to int16.
4260
- let s = avg;
4261
- if (s > 1) s = 1;
4262
- else if (s < -1) s = -1;
4263
- this._buf[this._pos++] = s < 0 ? s * 0x8000 : s * 0x7fff;
4264
- this._acc = 0;
4265
- this._accCount = 0;
4266
- if (this._pos >= this.frameSamples) this._emit();
4467
+ let sourceWeight = 1;
4468
+ while (sourceWeight > 0) {
4469
+ const weight = Math.min(sourceWeight, this.ratio - this._accWeight);
4470
+ this._acc += ch[i] * weight;
4471
+ this._accWeight += weight;
4472
+ sourceWeight -= weight;
4473
+
4474
+ if (this._accWeight + 1e-10 >= this.ratio) {
4475
+ const avg = this._acc / this._accWeight;
4476
+ // Clamp to [-1, 1] then quantize to int16.
4477
+ let s = avg;
4478
+ if (s > 1) s = 1;
4479
+ else if (s < -1) s = -1;
4480
+ this._buf[this._pos++] = s < 0 ? s * 0x8000 : s * 0x7fff;
4481
+ this._acc = 0;
4482
+ this._accWeight = 0;
4483
+ if (this._pos >= this.frameSamples) this._emit();
4484
+ }
4267
4485
  }
4268
4486
  }
4269
4487
  return true;
@@ -4299,7 +4517,10 @@ function useGeminiLiveSession(cfg, onValue) {
4299
4517
  const [transcripts, setTranscripts] = react.useState([]);
4300
4518
  const [assistantText, setAssistantText] = react.useState("");
4301
4519
  const [activeFieldId, setActiveFieldId] = react.useState(null);
4520
+ const [askedFieldId, setAskedFieldId] = react.useState(null);
4521
+ const [playbackComplete, setPlaybackComplete] = react.useState(false);
4302
4522
  const [lastValue, setLastValue] = react.useState(null);
4523
+ const [inputLevel, setInputLevel] = react.useState(0);
4303
4524
  const [isMuted, setIsMuted] = react.useState(false);
4304
4525
  const [error, setError] = react.useState(null);
4305
4526
  const wsRef = react.useRef(null);
@@ -4308,17 +4529,55 @@ function useGeminiLiveSession(cfg, onValue) {
4308
4529
  const workletRef = react.useRef(null);
4309
4530
  const sourceRef = react.useRef(null);
4310
4531
  const playbackQueueTimeRef = react.useRef(0);
4532
+ const playbackNodesRef = react.useRef(/* @__PURE__ */ new Set());
4311
4533
  const isMutedRef = react.useRef(false);
4312
4534
  const onValueRef = react.useRef(onValue);
4313
4535
  const disposedRef = react.useRef(false);
4536
+ const smoothedInputLevelRef = react.useRef(0);
4537
+ const inputLevelFrameRef = react.useRef(0);
4538
+ const terminalReceivedRef = react.useRef(false);
4539
+ const currentPlaybackTurnRef = react.useRef(null);
4540
+ const playbackTurnsRef = react.useRef(/* @__PURE__ */ new Map());
4541
+ const socketSessionIdRef = react.useRef(null);
4542
+ if (sessionId && socketSessionIdRef.current === null) {
4543
+ socketSessionIdRef.current = sessionId;
4544
+ }
4545
+ const socketSessionId = socketSessionIdRef.current;
4314
4546
  react.useEffect(() => {
4315
4547
  onValueRef.current = onValue;
4316
4548
  }, [onValue]);
4317
4549
  react.useEffect(() => {
4318
4550
  isMutedRef.current = isMuted;
4319
4551
  }, [isMuted]);
4552
+ const maybeCompletePlayback = react.useCallback(() => {
4553
+ if (terminalReceivedRef.current && playbackNodesRef.current.size === 0) {
4554
+ setPlaybackComplete(true);
4555
+ }
4556
+ }, []);
4557
+ const maybeFinishPlaybackTurn = react.useCallback(
4558
+ (turnId) => {
4559
+ const turn = playbackTurnsRef.current.get(turnId);
4560
+ if (!turn || !turn.serverEnded || turn.nodes.size > 0) return;
4561
+ playbackTurnsRef.current.delete(turnId);
4562
+ if (turn.purpose === "field" && turn.fieldId !== null) {
4563
+ setAskedFieldId(turn.fieldId);
4564
+ }
4565
+ const ws = wsRef.current;
4566
+ if ((ws == null ? void 0 : ws.readyState) === WebSocket.OPEN) {
4567
+ ws.send(
4568
+ JSON.stringify({
4569
+ type: "playback_turn_complete",
4570
+ turnId
4571
+ })
4572
+ );
4573
+ }
4574
+ maybeCompletePlayback();
4575
+ },
4576
+ [maybeCompletePlayback]
4577
+ );
4320
4578
  const enqueuePlayback = react.useCallback(
4321
4579
  (pcm) => {
4580
+ var _a;
4322
4581
  const ctx = ctxRef.current;
4323
4582
  if (!ctx) return;
4324
4583
  const samples = new Int16Array(pcm);
@@ -4335,70 +4594,208 @@ function useGeminiLiveSession(cfg, onValue) {
4335
4594
  const startAt = Math.max(now, playbackQueueTimeRef.current);
4336
4595
  node.start(startAt);
4337
4596
  playbackQueueTimeRef.current = startAt + buf.duration;
4597
+ const scheduled = playbackNodesRef.current;
4598
+ scheduled.add(node);
4599
+ const turnId = currentPlaybackTurnRef.current;
4600
+ if (turnId !== null) {
4601
+ (_a = playbackTurnsRef.current.get(turnId)) == null ? void 0 : _a.nodes.add(node);
4602
+ }
4603
+ node.onended = () => {
4604
+ var _a2;
4605
+ scheduled.delete(node);
4606
+ let turnEnded = false;
4607
+ if (turnId !== null) {
4608
+ const turn = playbackTurnsRef.current.get(turnId);
4609
+ turnEnded = (_a2 = turn == null ? void 0 : turn.serverEnded) != null ? _a2 : false;
4610
+ turn == null ? void 0 : turn.nodes.delete(node);
4611
+ maybeFinishPlaybackTurn(turnId);
4612
+ }
4613
+ if (scheduled.size === 0) {
4614
+ setState(
4615
+ (prev) => prev === "speaking" ? turnEnded ? "listening" : "processing" : prev
4616
+ );
4617
+ maybeCompletePlayback();
4618
+ }
4619
+ };
4620
+ setState(
4621
+ (prev) => prev === "listening" || prev === "processing" ? "speaking" : prev
4622
+ );
4338
4623
  },
4339
- [outputSampleRate]
4624
+ [maybeCompletePlayback, maybeFinishPlaybackTurn, outputSampleRate]
4340
4625
  );
4341
- const handleInbound = react.useCallback((msg) => {
4342
- var _a, _b, _c, _d, _e;
4343
- switch (msg.type) {
4344
- case "state": {
4345
- const next = msg.value || "";
4346
- if (next === "listening" || next === "speaking" || next === "idle") {
4347
- setState(next);
4348
- }
4349
- break;
4626
+ const noteMicLevel = react.useCallback((pcm) => {
4627
+ const samples = new Int16Array(pcm);
4628
+ if (samples.length === 0) return;
4629
+ let sum = 0;
4630
+ for (let i = 0; i < samples.length; i++) sum += samples[i] * samples[i];
4631
+ const rms = Math.sqrt(sum / samples.length);
4632
+ const normalized = Math.min(1, Math.max(0, (rms - 80) / 2400));
4633
+ const previous = smoothedInputLevelRef.current;
4634
+ const smoothing = normalized > previous ? 0.45 : 0.16;
4635
+ const next = previous + (normalized - previous) * smoothing;
4636
+ smoothedInputLevelRef.current = next;
4637
+ inputLevelFrameRef.current += 1;
4638
+ if (inputLevelFrameRef.current % 3 === 0) setInputLevel(next);
4639
+ }, []);
4640
+ const flushPlayback = react.useCallback(() => {
4641
+ const ws = wsRef.current;
4642
+ if ((ws == null ? void 0 : ws.readyState) === WebSocket.OPEN) {
4643
+ for (const turnId of playbackTurnsRef.current.keys()) {
4644
+ ws.send(
4645
+ JSON.stringify({
4646
+ type: "playback_turn_cancelled",
4647
+ turnId
4648
+ })
4649
+ );
4350
4650
  }
4351
- case "transcript": {
4352
- const who = (_a = msg.who) != null ? _a : "user";
4353
- const text = String((_b = msg.text) != null ? _b : "");
4354
- const final = Boolean(msg.final);
4355
- setTranscripts((prev) => {
4356
- if (!final) {
4651
+ }
4652
+ const scheduled = playbackNodesRef.current;
4653
+ scheduled.forEach((node) => {
4654
+ try {
4655
+ node.onended = null;
4656
+ node.stop();
4657
+ node.disconnect();
4658
+ } catch {
4659
+ }
4660
+ });
4661
+ scheduled.clear();
4662
+ playbackTurnsRef.current.clear();
4663
+ currentPlaybackTurnRef.current = null;
4664
+ playbackQueueTimeRef.current = 0;
4665
+ }, []);
4666
+ const handleInbound = react.useCallback(
4667
+ (msg) => {
4668
+ var _a, _b, _c, _d, _e, _f, _g, _h;
4669
+ switch (msg.type) {
4670
+ case "state": {
4671
+ const next = String((_a = msg.state) != null ? _a : "");
4672
+ if (next === "listening" || next === "speaking" || next === "idle" || next === "connecting") {
4673
+ setState(next);
4674
+ } else if (next === "processing") {
4675
+ setState("connecting");
4676
+ }
4677
+ break;
4678
+ }
4679
+ case "interrupt": {
4680
+ flushPlayback();
4681
+ setState("listening");
4682
+ break;
4683
+ }
4684
+ case "transcript": {
4685
+ const text = String((_b = msg.text) != null ? _b : "");
4686
+ const final = msg.partial !== true;
4687
+ if (text.length === 0) break;
4688
+ setState((prev) => prev === "listening" ? "processing" : prev);
4689
+ setTranscripts((prev) => {
4357
4690
  const next = prev.slice();
4358
- const lastIdx = next.length - 1;
4359
- if (lastIdx >= 0 && next[lastIdx].who === who && !next[lastIdx].final) {
4360
- next[lastIdx] = { who, text, final };
4691
+ const last = next[next.length - 1];
4692
+ if (last && last.who === "user" && !last.final) {
4693
+ next[next.length - 1] = {
4694
+ who: "user",
4695
+ text: last.text + text,
4696
+ final
4697
+ };
4361
4698
  return next;
4362
4699
  }
4363
- return [...next, { who, text, final }];
4700
+ return [...next, { who: "user", text, final }];
4701
+ });
4702
+ break;
4703
+ }
4704
+ case "assistant_text": {
4705
+ const text = String((_c = msg.text) != null ? _c : "");
4706
+ if (text.length === 0) break;
4707
+ setAssistantText(text);
4708
+ setTranscripts((prev) => {
4709
+ const next = prev.slice();
4710
+ const last = next[next.length - 1];
4711
+ if (last && last.who === "assistant" && !last.final) {
4712
+ next[next.length - 1] = {
4713
+ who: "assistant",
4714
+ text: last.text + text,
4715
+ final: false
4716
+ };
4717
+ return next;
4718
+ }
4719
+ return [...next, { who: "assistant", text, final: false }];
4720
+ });
4721
+ break;
4722
+ }
4723
+ case "audio_turn_start": {
4724
+ const turnId = String((_d = msg.turnId) != null ? _d : "");
4725
+ if (turnId.length === 0) break;
4726
+ currentPlaybackTurnRef.current = turnId;
4727
+ playbackTurnsRef.current.set(turnId, {
4728
+ purpose: String((_e = msg.purpose) != null ? _e : ""),
4729
+ fieldId: typeof msg.fieldId === "string" && msg.fieldId.length > 0 ? msg.fieldId : null,
4730
+ nodes: /* @__PURE__ */ new Set(),
4731
+ serverEnded: false
4732
+ });
4733
+ setState(
4734
+ (prev) => prev === "speaking" || prev === "completed" || prev === "error" ? prev : "processing"
4735
+ );
4736
+ break;
4737
+ }
4738
+ case "audio_turn_end": {
4739
+ const turnId = String((_f = msg.turnId) != null ? _f : "");
4740
+ if (turnId.length === 0) break;
4741
+ const turn = playbackTurnsRef.current.get(turnId);
4742
+ if (turn) turn.serverEnded = true;
4743
+ if (currentPlaybackTurnRef.current === turnId) {
4744
+ currentPlaybackTurnRef.current = null;
4364
4745
  }
4365
- return [...prev, { who, text, final }];
4366
- });
4367
- break;
4368
- }
4369
- case "assistant_text": {
4370
- setAssistantText(String((_c = msg.text) != null ? _c : ""));
4371
- break;
4372
- }
4373
- case "field_change": {
4374
- setActiveFieldId(String((_d = msg.field_id) != null ? _d : ""));
4375
- playbackQueueTimeRef.current = 0;
4376
- break;
4377
- }
4378
- case "value": {
4379
- const v = msg.value;
4380
- setLastValue(v);
4381
- try {
4382
- onValueRef.current(v);
4383
- } catch {
4746
+ setTranscripts((prev) => {
4747
+ const last = prev[prev.length - 1];
4748
+ if (!last || last.who !== "assistant" || last.final) return prev;
4749
+ const next = prev.slice();
4750
+ next[next.length - 1] = { ...last, final: true };
4751
+ return next;
4752
+ });
4753
+ maybeFinishPlaybackTurn(turnId);
4754
+ break;
4755
+ }
4756
+ case "field_change": {
4757
+ const fieldId = String((_g = msg.fieldId) != null ? _g : "");
4758
+ setActiveFieldId(fieldId);
4759
+ setState(
4760
+ (prev) => prev === "speaking" || prev === "error" ? prev : "processing"
4761
+ );
4762
+ break;
4763
+ }
4764
+ case "value": {
4765
+ const v = msg.value;
4766
+ setLastValue(v);
4767
+ setState(
4768
+ (prev) => prev === "speaking" || prev === "error" ? prev : "processing"
4769
+ );
4770
+ try {
4771
+ onValueRef.current(v);
4772
+ } catch {
4773
+ }
4774
+ break;
4775
+ }
4776
+ case "completed": {
4777
+ terminalReceivedRef.current = true;
4778
+ setState("completed");
4779
+ maybeCompletePlayback();
4780
+ break;
4781
+ }
4782
+ case "error": {
4783
+ setError(String((_h = msg.message) != null ? _h : "voice session error"));
4784
+ setState("error");
4785
+ break;
4384
4786
  }
4385
- break;
4386
- }
4387
- case "completed": {
4388
- setState("completed");
4389
- break;
4390
- }
4391
- case "error": {
4392
- setError(String((_e = msg.message) != null ? _e : "voice session error"));
4393
- setState("error");
4394
- break;
4395
4787
  }
4396
- }
4397
- }, []);
4788
+ },
4789
+ [flushPlayback, maybeCompletePlayback, maybeFinishPlaybackTurn]
4790
+ );
4398
4791
  react.useEffect(() => {
4399
- if (!sessionId || !participantToken) return;
4792
+ if (!socketSessionId || !participantToken) return;
4400
4793
  let cancelled = false;
4401
4794
  disposedRef.current = false;
4795
+ terminalReceivedRef.current = false;
4796
+ currentPlaybackTurnRef.current = null;
4797
+ playbackTurnsRef.current.clear();
4798
+ setPlaybackComplete(false);
4402
4799
  const start = async () => {
4403
4800
  try {
4404
4801
  setState("connecting");
@@ -4430,7 +4827,7 @@ function useGeminiLiveSession(cfg, onValue) {
4430
4827
  });
4431
4828
  workletRef.current = worklet;
4432
4829
  source.connect(worklet);
4433
- const wsUrl = apiBase.replace(/^http/, "ws") + `/api/participant/inbox/${encodeURIComponent(sessionId)}/voice-stream?token=${encodeURIComponent(participantToken)}`;
4830
+ const wsUrl = apiBase.replace(/^http/, "ws") + `/api/participant/inbox/${encodeURIComponent(socketSessionId)}/voice-stream?token=${encodeURIComponent(participantToken)}`;
4434
4831
  const ws = new WebSocket(wsUrl, SUBPROTOCOL);
4435
4832
  ws.binaryType = "arraybuffer";
4436
4833
  wsRef.current = ws;
@@ -4470,7 +4867,9 @@ function useGeminiLiveSession(cfg, onValue) {
4470
4867
  worklet.port.onmessage = (ev) => {
4471
4868
  if (isMutedRef.current) return;
4472
4869
  if (ws.readyState !== WebSocket.OPEN) return;
4473
- ws.send(ev.data);
4870
+ const pcm = ev.data;
4871
+ noteMicLevel(pcm);
4872
+ ws.send(pcm);
4474
4873
  };
4475
4874
  } catch (err) {
4476
4875
  if (cancelled) return;
@@ -4511,11 +4910,12 @@ function useGeminiLiveSession(cfg, onValue) {
4511
4910
  }, [
4512
4911
  apiBase,
4513
4912
  participantToken,
4514
- sessionId,
4913
+ socketSessionId,
4515
4914
  inputSampleRate,
4516
4915
  outputSampleRate,
4517
4916
  enqueuePlayback,
4518
- handleInbound
4917
+ handleInbound,
4918
+ noteMicLevel
4519
4919
  ]);
4520
4920
  const toggleMute = react.useCallback(() => {
4521
4921
  setIsMuted((prev) => {
@@ -4533,7 +4933,10 @@ function useGeminiLiveSession(cfg, onValue) {
4533
4933
  transcripts,
4534
4934
  assistantText,
4535
4935
  activeFieldId,
4936
+ askedFieldId,
4937
+ playbackComplete,
4536
4938
  lastValue,
4939
+ inputLevel: isMuted ? 0 : inputLevel,
4537
4940
  isMuted,
4538
4941
  toggleMute,
4539
4942
  error
@@ -4544,11 +4947,13 @@ function VoiceLiveRenderer({
4544
4947
  apiBase,
4545
4948
  participantToken,
4546
4949
  sessionId,
4950
+ fieldSessionId,
4547
4951
  liveConfig,
4548
4952
  onValue,
4953
+ onPlaybackComplete,
4954
+ onFieldRevealed,
4549
4955
  disabled
4550
4956
  }) {
4551
- var _a;
4552
4957
  const session = useGeminiLiveSession(
4553
4958
  {
4554
4959
  apiBase,
@@ -4559,13 +4964,20 @@ function VoiceLiveRenderer({
4559
4964
  },
4560
4965
  onValue
4561
4966
  );
4967
+ react.useEffect(() => {
4968
+ if (session.playbackComplete) onPlaybackComplete == null ? void 0 : onPlaybackComplete();
4969
+ }, [session.playbackComplete, onPlaybackComplete]);
4562
4970
  react.useEffect(() => {
4563
4971
  }, [session.activeFieldId]);
4972
+ const fieldRevealed = session.askedFieldId === field.id;
4973
+ react.useEffect(() => {
4974
+ if (fieldRevealed) onFieldRevealed == null ? void 0 : onFieldRevealed(fieldSessionId);
4975
+ }, [fieldRevealed, fieldSessionId, onFieldRevealed]);
4564
4976
  const promptRef = react.useRef(null);
4565
4977
  react.useEffect(() => {
4566
- var _a2;
4567
- (_a2 = promptRef.current) == null ? void 0 : _a2.scrollIntoView({ behavior: "smooth", block: "nearest" });
4568
- }, [field]);
4978
+ var _a;
4979
+ (_a = promptRef.current) == null ? void 0 : _a.scrollIntoView({ behavior: "smooth", block: "nearest" });
4980
+ }, [field, fieldRevealed]);
4569
4981
  const orbState = (() => {
4570
4982
  if (session.error) return "error";
4571
4983
  if (session.isMuted) return "idle";
@@ -4575,8 +4987,10 @@ function VoiceLiveRenderer({
4575
4987
  return "idle";
4576
4988
  case "listening":
4577
4989
  return "listening";
4578
- case "speaking":
4990
+ case "processing":
4579
4991
  return "processing";
4992
+ case "speaking":
4993
+ return "speaking";
4580
4994
  case "completed":
4581
4995
  return "idle";
4582
4996
  case "error":
@@ -4585,12 +4999,17 @@ function VoiceLiveRenderer({
4585
4999
  return "idle";
4586
5000
  }
4587
5001
  })();
4588
- const lastUserTranscript = [...session.transcripts].reverse().find((t) => t.who === "user");
5002
+ const logRef = react.useRef(null);
5003
+ react.useEffect(() => {
5004
+ const el = logRef.current;
5005
+ if (el) el.scrollTop = el.scrollHeight;
5006
+ }, [session.transcripts]);
4589
5007
  const announcement = (() => {
4590
5008
  if (session.error) return session.error;
4591
5009
  if (session.isMuted) return "Microphone muted.";
4592
5010
  if (session.state === "connecting") return "Connecting to voice service.";
4593
- if (session.state === "listening") return "Listening.";
5011
+ if (session.state === "listening") return "Microphone listening.";
5012
+ if (session.state === "processing") return "Preparing the next step.";
4594
5013
  if (session.state === "speaking") return "Assistant speaking.";
4595
5014
  return "";
4596
5015
  })();
@@ -4605,42 +5024,49 @@ function VoiceLiveRenderer({
4605
5024
  children: announcement
4606
5025
  }
4607
5026
  ),
4608
- /* @__PURE__ */ jsxRuntime.jsx("div", { ref: promptRef, children: /* @__PURE__ */ jsxRuntime.jsx(
4609
- VoicePromptCard,
4610
- {
4611
- field,
4612
- transcript: (_a = lastUserTranscript == null ? void 0 : lastUserTranscript.text) != null ? _a : ""
4613
- }
4614
- ) }),
4615
- session.error && /* @__PURE__ */ jsxRuntime.jsx("p", { className: widget_default.voiceError, children: session.error }),
4616
- /* @__PURE__ */ jsxRuntime.jsxs(
5027
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.voiceOrbContainer, children: [
5028
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.voiceOrbRow, children: [
5029
+ /* @__PURE__ */ jsxRuntime.jsx(
5030
+ VoiceOrb,
5031
+ {
5032
+ state: orbState,
5033
+ inputLevel: session.isMuted ? 0 : session.inputLevel,
5034
+ disabled
5035
+ }
5036
+ ),
5037
+ /* @__PURE__ */ jsxRuntime.jsx(
5038
+ "button",
5039
+ {
5040
+ type: "button",
5041
+ "data-cf-voice-mute": "true",
5042
+ className: `${widget_default.voiceMuteButton}${session.isMuted ? " " + widget_default.voiceMuteButtonMuted : ""}`,
5043
+ onClick: session.toggleMute,
5044
+ "aria-label": session.isMuted ? "Unmute microphone" : "Mute microphone",
5045
+ "aria-pressed": session.isMuted,
5046
+ children: session.isMuted ? "Muted" : "Mute"
5047
+ }
5048
+ )
5049
+ ] }),
5050
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.voiceOrbStats, children: [
5051
+ session.isMuted && /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.voiceOrbHint, "aria-hidden": "true", children: "Microphone muted" }),
5052
+ !session.isMuted && session.state === "connecting" && /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.voiceAssistantStatus, children: "Connecting\u2026" }),
5053
+ !session.isMuted && session.state === "processing" && /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.voiceAssistantStatus, children: "Preparing the next step\u2026" }),
5054
+ !session.isMuted && session.state === "speaking" && /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.voiceAssistantStatus, children: "Assistant speaking\u2026" })
5055
+ ] })
5056
+ ] }),
5057
+ session.transcripts.length > 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { ref: logRef, className: widget_default.voiceLiveLog, children: session.transcripts.map((t, i) => /* @__PURE__ */ jsxRuntime.jsxs(
4617
5058
  "div",
4618
5059
  {
4619
- className: `${widget_default.voiceOrbContainer} ${widget_default.voiceOrbContainerSticky}`,
5060
+ className: t.who === "user" ? widget_default.voiceLiveLogUser : widget_default.voiceLiveLogAssistant,
4620
5061
  children: [
4621
- /* @__PURE__ */ jsxRuntime.jsx(VoiceOrb, { state: orbState, disabled }),
4622
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.voiceOrbStats, children: /* @__PURE__ */ jsxRuntime.jsxs("span", { className: widget_default.voiceOrbHint, children: [
4623
- session.isMuted && "\u{1F507} Muted",
4624
- !session.isMuted && session.state === "connecting" && "Connecting\u2026",
4625
- !session.isMuted && session.state === "listening" && "Listening\u2026",
4626
- !session.isMuted && session.state === "speaking" && "Assistant speaking\u2026",
4627
- !session.isMuted && session.state === "idle" && "Ready"
4628
- ] }) }),
4629
- /* @__PURE__ */ jsxRuntime.jsx(
4630
- "button",
4631
- {
4632
- type: "button",
4633
- "data-cf-voice-mute": "true",
4634
- className: `${widget_default.voiceMuteButton}${session.isMuted ? " " + widget_default.voiceMuteButtonMuted : ""}`,
4635
- onClick: session.toggleMute,
4636
- "aria-label": session.isMuted ? "Unmute microphone" : "Mute microphone",
4637
- "aria-pressed": session.isMuted,
4638
- children: session.isMuted ? "\u{1F507}" : "\u{1F3A4}"
4639
- }
4640
- )
5062
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.voiceTranscriptLabel, children: t.who === "user" ? "You" : "Assistant" }),
5063
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.voiceTranscriptText, children: t.text })
4641
5064
  ]
4642
- }
4643
- )
5065
+ },
5066
+ i
5067
+ )) }),
5068
+ fieldRevealed && /* @__PURE__ */ jsxRuntime.jsx("div", { ref: promptRef, children: /* @__PURE__ */ jsxRuntime.jsx(VoicePromptCard, { field }) }),
5069
+ session.error && /* @__PURE__ */ jsxRuntime.jsx("p", { className: widget_default.voiceError, children: session.error })
4644
5070
  ] });
4645
5071
  }
4646
5072
  function InputText({
@@ -5819,6 +6245,7 @@ var ChatAdapter = react.forwardRef(
5819
6245
  runId,
5820
6246
  participantToken,
5821
6247
  apiBase,
6248
+ connectionPolicy,
5822
6249
  className,
5823
6250
  onCompleted,
5824
6251
  onError,
@@ -5838,7 +6265,7 @@ var ChatAdapter = react.forwardRef(
5838
6265
  components,
5839
6266
  strings
5840
6267
  }, ref) {
5841
- var _a, _b, _c, _d, _e, _f, _g, _h, _i;
6268
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
5842
6269
  const t = resolveStrings(strings);
5843
6270
  const apiBaseResolved = apiBase;
5844
6271
  const appBaseResolved = typeof window !== "undefined" ? window.location.origin : (_a = process.env.APP_URL) != null ? _a : "http://localhost:3000";
@@ -5874,7 +6301,7 @@ var ChatAdapter = react.forwardRef(
5874
6301
  output,
5875
6302
  disconnect,
5876
6303
  reconnect
5877
- } = useRunStream({ runId, participantToken, apiBase }, onEventFirehose);
6304
+ } = useRunStream({ runId, participantToken, apiBase, connectionPolicy }, onEventFirehose);
5878
6305
  react.useImperativeHandle(
5879
6306
  ref,
5880
6307
  () => ({
@@ -5884,12 +6311,6 @@ var ChatAdapter = react.forwardRef(
5884
6311
  }),
5885
6312
  [reconnect, disconnect, sendMessage]
5886
6313
  );
5887
- const prevStatusRef = react.useRef(null);
5888
- react.useEffect(() => {
5889
- if (prevStatusRef.current === status) return;
5890
- prevStatusRef.current = status;
5891
- onStatusChange == null ? void 0 : onStatusChange(status);
5892
- }, [status, onStatusChange]);
5893
6314
  const {
5894
6315
  connections: requiredConnections,
5895
6316
  allProvided: allConnectionsProvided,
@@ -5973,7 +6394,11 @@ var ChatAdapter = react.forwardRef(
5973
6394
  if (!isVoiceSurface && activeSession && extractSurface(activeSession) === "widget/voice") {
5974
6395
  setIsVoiceSurface(true);
5975
6396
  }
5976
- const voiceSessionId = (_b = activeSession == null ? void 0 : activeSession.id) != null ? _b : null;
6397
+ const [isLiveVoiceSurface, setIsLiveVoiceSurface] = react.useState(false);
6398
+ if (!isLiveVoiceSurface && activeSession && extractSurface(activeSession) === "widget/voice" && ((_b = extractSurfaceConfig(activeSession)) == null ? void 0 : _b.style) === "live") {
6399
+ setIsLiveVoiceSurface(true);
6400
+ }
6401
+ const voiceSessionId = (_c = activeSession == null ? void 0 : activeSession.id) != null ? _c : null;
5977
6402
  const prevVoiceSessionIdRef = react.useRef(null);
5978
6403
  react.useEffect(() => {
5979
6404
  if (!isVoiceSurface) return;
@@ -5983,6 +6408,25 @@ var ChatAdapter = react.forwardRef(
5983
6408
  }
5984
6409
  prevVoiceSessionIdRef.current = voiceSessionId;
5985
6410
  }, [voiceSessionId, isVoiceSurface, clearSpeech]);
6411
+ const liveVoiceRef = react.useRef(null);
6412
+ const [revealedLivePromptSessions, setRevealedLivePromptSessions] = react.useState(
6413
+ () => /* @__PURE__ */ new Set()
6414
+ );
6415
+ const [livePlaybackComplete, setLivePlaybackComplete] = react.useState(false);
6416
+ const livePlaybackSessionRef = react.useRef(null);
6417
+ react.useEffect(() => {
6418
+ if (!activeSession || activeSession.id === livePlaybackSessionRef.current) return;
6419
+ livePlaybackSessionRef.current = activeSession.id;
6420
+ setLivePlaybackComplete(false);
6421
+ }, [activeSession]);
6422
+ const terminalVoiceDraining = (status === "completed" || status === "error") && isLiveVoiceSurface && liveVoiceRef.current !== null && !livePlaybackComplete;
6423
+ const reportedStatus = terminalVoiceDraining ? "running" : status;
6424
+ const prevStatusRef = react.useRef(null);
6425
+ react.useEffect(() => {
6426
+ if (prevStatusRef.current === reportedStatus) return;
6427
+ prevStatusRef.current = reportedStatus;
6428
+ onStatusChange == null ? void 0 : onStatusChange(reportedStatus);
6429
+ }, [reportedStatus, onStatusChange]);
5986
6430
  react.useEffect(() => {
5987
6431
  if (!isVoiceSurface) return;
5988
6432
  for (const entry of timeline) {
@@ -5990,15 +6434,17 @@ var ChatAdapter = react.forwardRef(
5990
6434
  if (entry.sender === "user") continue;
5991
6435
  if (spokenMessageSeqsRef.current.has(entry.seq)) continue;
5992
6436
  spokenMessageSeqsRef.current.add(entry.seq);
6437
+ if (isLiveVoiceSurface) continue;
5993
6438
  const text = entry.payload.voice_hint || entry.payload.content || "";
5994
6439
  void enqueueSpeak(text);
5995
6440
  }
5996
- }, [timeline, isVoiceSurface, enqueueSpeak]);
6441
+ }, [timeline, isVoiceSurface, isLiveVoiceSurface, enqueueSpeak]);
5997
6442
  const completedFiredRef = react.useRef(false);
5998
6443
  const errorFiredRef = react.useRef(false);
6444
+ const expiredFiredRef = react.useRef(false);
5999
6445
  const inputAreaRef = react.useRef(null);
6000
6446
  const lastFocusedSessionRef = react.useRef(null);
6001
- const activeSessionId = (_c = activeSession == null ? void 0 : activeSession.id) != null ? _c : null;
6447
+ const activeSessionId = (_d = activeSession == null ? void 0 : activeSession.id) != null ? _d : null;
6002
6448
  react.useEffect(() => {
6003
6449
  if (!autoFocusInput) return;
6004
6450
  if (!activeSessionId) return;
@@ -6014,15 +6460,21 @@ var ChatAdapter = react.forwardRef(
6014
6460
  }
6015
6461
  }, [autoFocusInput, activeSessionId, status]);
6016
6462
  react.useEffect(() => {
6017
- if (status === "completed" && !completedFiredRef.current) {
6463
+ if (status === "completed" && !terminalVoiceDraining && !completedFiredRef.current) {
6018
6464
  completedFiredRef.current = true;
6019
6465
  onCompleted == null ? void 0 : onCompleted(output != null ? output : void 0);
6020
6466
  }
6021
- if (status === "error" && !errorFiredRef.current) {
6467
+ if (status === "error" && !terminalVoiceDraining && !errorFiredRef.current) {
6022
6468
  errorFiredRef.current = true;
6023
6469
  onError == null ? void 0 : onError(new WidgetError("run_failed", "The run encountered an error."));
6024
6470
  }
6025
- }, [status, output, onCompleted, onError]);
6471
+ if (status === "expired" && !expiredFiredRef.current) {
6472
+ expiredFiredRef.current = true;
6473
+ onError == null ? void 0 : onError(
6474
+ new WidgetError("token_expired", "The participant token expired and could not be renewed.")
6475
+ );
6476
+ }
6477
+ }, [status, terminalVoiceDraining, output, onCompleted, onError]);
6026
6478
  const colorSchemeClass = colorScheme === "dark" ? widget_default.cfDark : colorScheme === "auto" ? widget_default.cfAuto : void 0;
6027
6479
  const cls = [widget_default.widget, colorSchemeClass, className].filter(Boolean).join(" ");
6028
6480
  const rootStyle = react.useMemo(() => themeToStyle(theme), [theme]);
@@ -6068,10 +6520,11 @@ var ChatAdapter = react.forwardRef(
6068
6520
  },
6069
6521
  [handleSubmit]
6070
6522
  );
6071
- if (status === "idle" || status === "connecting") {
6523
+ const isSilentReconnect = (status === "connecting" || status === "replaying") && timeline.length > 0;
6524
+ if (status === "idle" || status === "connecting" && !isSilentReconnect) {
6072
6525
  return /* @__PURE__ */ jsxRuntime.jsx("div", { className: cls, style: rootStyle, children: loadingFallback != null ? loadingFallback : /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status, strings }) });
6073
6526
  }
6074
- if (status === "replaying") {
6527
+ if (status === "replaying" && !isSilentReconnect) {
6075
6528
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cls, style: rootStyle, children: [
6076
6529
  header,
6077
6530
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.resumingBanner, children: [
@@ -6081,7 +6534,8 @@ var ChatAdapter = react.forwardRef(
6081
6534
  /* @__PURE__ */ jsxRuntime.jsx(ChatTimeline, { entries: timeline, streamingText, components })
6082
6535
  ] });
6083
6536
  }
6084
- if (status === "completed" || status === "error") {
6537
+ const awaitingLivePlayback = terminalVoiceDraining;
6538
+ if ((status === "completed" || status === "error") && !awaitingLivePlayback) {
6085
6539
  const hasChatContent = timeline.some(
6086
6540
  (e) => {
6087
6541
  var _a2, _b2;
@@ -6101,7 +6555,7 @@ var ChatAdapter = react.forwardRef(
6101
6555
  FormRenderer,
6102
6556
  {
6103
6557
  fields: formSpec == null ? void 0 : formSpec.fields,
6104
- repeater: (_d = formSpec == null ? void 0 : formSpec.repeaters) == null ? void 0 : _d[0],
6558
+ repeater: (_e = formSpec == null ? void 0 : formSpec.repeaters) == null ? void 0 : _e[0],
6105
6559
  onSubmit: (values) => void submitHandback(values),
6106
6560
  disabled: submitting
6107
6561
  }
@@ -6135,9 +6589,9 @@ var ChatAdapter = react.forwardRef(
6135
6589
  const converseUserCanEnd = (converseCtx == null ? void 0 : converseCtx.converse_user_can_end) === true;
6136
6590
  const field = activeSession ? extractField(activeSession) : null;
6137
6591
  if (status === "awaiting_chat" && activeSession && !(isConverseSession && field)) {
6138
- const hbCtx = (_e = activeSession.entry_context) == null ? void 0 : _e.handback;
6592
+ const hbCtx = (_f = activeSession.entry_context) == null ? void 0 : _f.handback;
6139
6593
  const outputSchema = hbCtx == null ? void 0 : hbCtx.output_schema;
6140
- const requireOutput = (_f = hbCtx == null ? void 0 : hbCtx.require_output) != null ? _f : false;
6594
+ const requireOutput = (_g = hbCtx == null ? void 0 : hbCtx.require_output) != null ? _g : false;
6141
6595
  const handbackReady = !requireOutput || outputSchema != null && Object.keys(outputSchema).every((k) => {
6142
6596
  var _a2;
6143
6597
  return ((_a2 = handbackValues[k]) != null ? _a2 : "").trim() !== "";
@@ -6238,31 +6692,63 @@ var ChatAdapter = react.forwardRef(
6238
6692
  const shouldUseVoice = effectiveVoiceMode !== "off";
6239
6693
  const voiceRenderer = effectiveVoiceMode === "push_to_talk" ? "click" : "continuous";
6240
6694
  const isLiveVoice = surface === "widget/voice" && (surfaceConfig == null ? void 0 : surfaceConfig.style) === "live";
6241
- if (shouldUseVoice && activeSession && field) {
6242
- const spokenHint = (_h = nodeVoice == null ? void 0 : nodeVoice.hint) != null ? _h : (_g = field.voice) == null ? void 0 : _g.hint;
6243
- const handleVoiceValue = (value) => {
6244
- setInputValue(value);
6245
- void submitHandback(value, crypto.randomUUID());
6246
- };
6247
- const handleLiveValue = (value) => {
6248
- setInputValue(value);
6695
+ if (activeSession && !isLiveVoice) {
6696
+ liveVoiceRef.current = null;
6697
+ } else if (isLiveVoice && activeSession && field) {
6698
+ liveVoiceRef.current = {
6699
+ // Pin the FIRST id: it only picks which socket to open, and the proxy
6700
+ // tracks field transitions itself from then on.
6701
+ sessionId: (_i = (_h = liveVoiceRef.current) == null ? void 0 : _h.sessionId) != null ? _i : activeSession.id,
6702
+ fieldSessionId: activeSession.id,
6703
+ field,
6704
+ hint: (_k = nodeVoice == null ? void 0 : nodeVoice.hint) != null ? _k : (_j = field.voice) == null ? void 0 : _j.hint,
6705
+ config: surfaceConfig != null ? surfaceConfig : void 0
6249
6706
  };
6707
+ }
6708
+ const liveVoice = isLiveVoice && activeSession && field || !activeSession && status === "running" || awaitingLivePlayback ? liveVoiceRef.current : null;
6709
+ if (liveVoice) {
6710
+ const respondedSessionIds = new Set(
6711
+ timeline.filter((entry) => entry.event_type === "response" && entry.session_id).map((entry) => entry.session_id)
6712
+ );
6713
+ const visibleLiveTimeline = timeline.filter(
6714
+ (entry) => entry.event_type !== "prompt" || entry.session_id === null || respondedSessionIds.has(entry.session_id) || revealedLivePromptSessions.has(entry.session_id)
6715
+ );
6250
6716
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cls, style: rootStyle, children: [
6251
6717
  header,
6252
- /* @__PURE__ */ jsxRuntime.jsx(ChatTimeline, { entries: timeline, showTyping, streamingText, components }),
6253
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.activeInputArea, children: isLiveVoice ? /* @__PURE__ */ jsxRuntime.jsx(
6718
+ /* @__PURE__ */ jsxRuntime.jsx(ChatTimeline, { entries: visibleLiveTimeline, showTyping, streamingText, components }),
6719
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.activeInputArea} ${widget_default.activeInputAreaVoice}`, children: /* @__PURE__ */ jsxRuntime.jsx(
6254
6720
  VoiceLiveRenderer,
6255
6721
  {
6256
- field,
6257
- voiceHint: spokenHint,
6722
+ field: liveVoice.field,
6723
+ voiceHint: liveVoice.hint,
6258
6724
  apiBase: apiBaseResolved,
6259
6725
  participantToken,
6260
- sessionId: activeSession.id,
6261
- liveConfig: surfaceConfig != null ? surfaceConfig : void 0,
6262
- onValue: handleLiveValue,
6726
+ sessionId: liveVoice.sessionId,
6727
+ fieldSessionId: liveVoice.fieldSessionId,
6728
+ liveConfig: liveVoice.config,
6729
+ onValue: (value) => setInputValue(value),
6730
+ onPlaybackComplete: () => setLivePlaybackComplete(true),
6731
+ onFieldRevealed: (revealedSessionId) => setRevealedLivePromptSessions((prev) => {
6732
+ if (prev.has(revealedSessionId)) return prev;
6733
+ const next = new Set(prev);
6734
+ next.add(revealedSessionId);
6735
+ return next;
6736
+ }),
6263
6737
  disabled: submitting
6264
6738
  }
6265
- ) : voiceRenderer === "continuous" ? /* @__PURE__ */ jsxRuntime.jsx(
6739
+ ) })
6740
+ ] });
6741
+ }
6742
+ if (shouldUseVoice && activeSession && field) {
6743
+ const spokenHint = (_m = nodeVoice == null ? void 0 : nodeVoice.hint) != null ? _m : (_l = field.voice) == null ? void 0 : _l.hint;
6744
+ const handleVoiceValue = (value) => {
6745
+ setInputValue(value);
6746
+ void submitHandback(value, crypto.randomUUID());
6747
+ };
6748
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cls, style: rootStyle, children: [
6749
+ header,
6750
+ /* @__PURE__ */ jsxRuntime.jsx(ChatTimeline, { entries: timeline, showTyping, streamingText, components }),
6751
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.activeInputArea} ${widget_default.activeInputAreaVoice}`, children: voiceRenderer === "continuous" ? /* @__PURE__ */ jsxRuntime.jsx(
6266
6752
  VoiceContinuousRenderer,
6267
6753
  {
6268
6754
  field,
@@ -6271,7 +6757,7 @@ var ChatAdapter = react.forwardRef(
6271
6757
  participantToken,
6272
6758
  onValue: handleVoiceValue,
6273
6759
  autoSubmitMode: "confirm",
6274
- confidenceThreshold: (_i = nodeVoice == null ? void 0 : nodeVoice.confidence_threshold) != null ? _i : typeof (surfaceConfig == null ? void 0 : surfaceConfig.confidence_threshold) === "number" ? surfaceConfig.confidence_threshold : 0.7,
6760
+ confidenceThreshold: (_n = nodeVoice == null ? void 0 : nodeVoice.confidence_threshold) != null ? _n : typeof (surfaceConfig == null ? void 0 : surfaceConfig.confidence_threshold) === "number" ? surfaceConfig.confidence_threshold : 0.7,
6275
6761
  enqueueSpeak,
6276
6762
  isSpeaking,
6277
6763
  disabled: submitting
@@ -6304,6 +6790,10 @@ var ChatAdapter = react.forwardRef(
6304
6790
  ) });
6305
6791
  }
6306
6792
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cls, style: rootStyle, children: [
6793
+ isSilentReconnect && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.reconnectingPill, children: [
6794
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.spinner }),
6795
+ t.reconnecting
6796
+ ] }),
6307
6797
  header,
6308
6798
  /* @__PURE__ */ jsxRuntime.jsx(ChatTimeline, { entries: timeline, showTyping, streamingText, components }),
6309
6799
  activeSession && field && InputComponent && /* @__PURE__ */ jsxRuntime.jsxs("form", { ref: inputAreaRef, className: widget_default.activeInputArea, onSubmit: handleSubmit, children: [
@@ -6501,15 +6991,44 @@ function clearPersistedSession(config, target) {
6501
6991
  } catch {
6502
6992
  }
6503
6993
  }
6994
+ async function fetchPersistedRunTerminalStatus(apiBase, runId, participantToken) {
6995
+ var _a;
6996
+ try {
6997
+ const res = await fetch(`${apiBase}/api/participant/runs/${runId}/timeline`, {
6998
+ headers: { Authorization: `Bearer ${participantToken}` }
6999
+ });
7000
+ if (!res.ok) return null;
7001
+ const entries = await res.json();
7002
+ if (!Array.isArray(entries)) return null;
7003
+ for (let i = entries.length - 1; i >= 0; i--) {
7004
+ const e = entries[i];
7005
+ if (e.event_type === "status_change") {
7006
+ const s = (_a = e.payload) == null ? void 0 : _a.status;
7007
+ if (s === "completed" || s === "failed") return s;
7008
+ }
7009
+ }
7010
+ return null;
7011
+ } catch {
7012
+ return null;
7013
+ }
7014
+ }
6504
7015
  var ChatterflyWidget = react.forwardRef(
6505
7016
  function ChatterflyWidget2(props, ref) {
6506
- var _a, _b, _c, _d, _e, _f, _g, _h;
7017
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
6507
7018
  const [resolved, setResolved] = react.useState(null);
6508
7019
  const [configError, setConfigError] = react.useState(null);
6509
7020
  const [restartNonce, setRestartNonce] = react.useState(0);
6510
7021
  const adapterRef = react.useRef(null);
6511
7022
  const autoStarting = Boolean(!props.runId && (props.deploymentId || props.workflowId));
6512
7023
  const persistTarget = (_a = props.workflowId) != null ? _a : props.deploymentId;
7024
+ const effectivePersistSession = props.persistSession === void 0 ? true : props.persistSession;
7025
+ const showCompletedHistory = (_b = props.showCompletedHistory) != null ? _b : true;
7026
+ const t = { ...defaultStrings, ...props.strings };
7027
+ const [gate, setGate] = react.useState("idle");
7028
+ const [terminalReplayActive, setTerminalReplayActive] = react.useState(false);
7029
+ const pendingPersistedRef = react.useRef(null);
7030
+ const startNewRunRef = react.useRef(() => {
7031
+ });
6513
7032
  react.useEffect(() => {
6514
7033
  var _a2;
6515
7034
  if (props.runId) return;
@@ -6524,52 +7043,109 @@ var ChatterflyWidget = react.forwardRef(
6524
7043
  return;
6525
7044
  }
6526
7045
  setConfigError(null);
6527
- if (restartNonce === 0) {
6528
- const persisted = loadPersistedSession(props.persistSession, persistTarget);
6529
- if (persisted) {
6530
- setResolved({ runId: persisted.runId, participantToken: persisted.participantToken });
6531
- return;
7046
+ const base = props.apiBase;
7047
+ const doStart = (input) => {
7048
+ const startUrl = props.workflowId ? `${base}/api/public/workflows/${props.workflowId}/start` : `${base}/api/public/surveys/${props.deploymentId}/start`;
7049
+ const body = input ? JSON.stringify({ input }) : void 0;
7050
+ fetch(startUrl, {
7051
+ method: "POST",
7052
+ headers: body ? { "Content-Type": "application/json" } : void 0,
7053
+ body
7054
+ }).then(async (r) => {
7055
+ if (!r.ok) {
7056
+ const code = r.status === 404 ? "no_live_deployment" : "workflow_not_public";
7057
+ const detail = await r.text().catch(() => "");
7058
+ throw new WidgetError(
7059
+ code,
7060
+ `Failed to start run (HTTP ${r.status})${detail ? `: ${detail}` : ""}`
7061
+ );
7062
+ }
7063
+ return r.json();
7064
+ }).then(({ run_id, participant_token }) => {
7065
+ setGate("idle");
7066
+ setTerminalReplayActive(false);
7067
+ setResolved({ runId: run_id, participantToken: participant_token });
7068
+ savePersistedSession(effectivePersistSession, persistTarget, {
7069
+ runId: run_id,
7070
+ participantToken: participant_token
7071
+ });
7072
+ }).catch((err) => {
7073
+ var _a3;
7074
+ const widgetErr = err instanceof WidgetError ? err : new WidgetError("network", err instanceof Error ? err.message : String(err));
7075
+ (_a3 = props.onError) == null ? void 0 : _a3.call(props, widgetErr);
7076
+ });
7077
+ };
7078
+ startNewRunRef.current = doStart;
7079
+ if (restartNonce > 0) {
7080
+ doStart(props.initialInput);
7081
+ return;
7082
+ }
7083
+ const persisted = loadPersistedSession(effectivePersistSession, persistTarget);
7084
+ if (!persisted) {
7085
+ if (props.clickToStart) {
7086
+ setGate("click-to-start");
7087
+ } else {
7088
+ doStart(props.initialInput);
6532
7089
  }
7090
+ return;
6533
7091
  }
6534
- const base = props.apiBase;
6535
- const startUrl = props.workflowId ? `${base}/api/public/workflows/${props.workflowId}/start` : `${base}/api/public/surveys/${props.deploymentId}/start`;
6536
- const body = props.initialInput ? JSON.stringify({ input: props.initialInput }) : void 0;
6537
- fetch(startUrl, {
6538
- method: "POST",
6539
- headers: body ? { "Content-Type": "application/json" } : void 0,
6540
- body
6541
- }).then(async (r) => {
6542
- if (!r.ok) {
6543
- const code = r.status === 404 ? "no_live_deployment" : "workflow_not_public";
6544
- const detail = await r.text().catch(() => "");
6545
- throw new WidgetError(
6546
- code,
6547
- `Failed to start run (HTTP ${r.status})${detail ? `: ${detail}` : ""}`
6548
- );
7092
+ let cancelled = false;
7093
+ fetchPersistedRunTerminalStatus(base, persisted.runId, persisted.participantToken).then(
7094
+ (terminal) => {
7095
+ if (cancelled) return;
7096
+ if (terminal) {
7097
+ if (showCompletedHistory) {
7098
+ setTerminalReplayActive(true);
7099
+ setGate("idle");
7100
+ setResolved(persisted);
7101
+ } else {
7102
+ clearPersistedSession(effectivePersistSession, persistTarget);
7103
+ doStart(props.initialInput);
7104
+ }
7105
+ } else if (props.resumePrompt) {
7106
+ pendingPersistedRef.current = persisted;
7107
+ setGate("resume-choice");
7108
+ } else {
7109
+ setResolved(persisted);
7110
+ }
6549
7111
  }
6550
- return r.json();
6551
- }).then(({ run_id, participant_token }) => {
6552
- setResolved({ runId: run_id, participantToken: participant_token });
6553
- savePersistedSession(props.persistSession, persistTarget, {
6554
- runId: run_id,
6555
- participantToken: participant_token
6556
- });
6557
- }).catch((err) => {
6558
- var _a3;
6559
- const widgetErr = err instanceof WidgetError ? err : new WidgetError("network", err instanceof Error ? err.message : String(err));
6560
- (_a3 = props.onError) == null ? void 0 : _a3.call(props, widgetErr);
6561
- });
7112
+ );
7113
+ return () => {
7114
+ cancelled = true;
7115
+ };
6562
7116
  }, [props.deploymentId, props.workflowId, props.apiBase, restartNonce]);
6563
7117
  const restart = react.useCallback(() => {
6564
7118
  var _a2;
6565
7119
  if (autoStarting) {
6566
- clearPersistedSession(props.persistSession, persistTarget);
7120
+ clearPersistedSession(effectivePersistSession, persistTarget);
6567
7121
  setResolved(null);
7122
+ setTerminalReplayActive(false);
7123
+ setGate("idle");
6568
7124
  setRestartNonce((n) => n + 1);
6569
7125
  } else {
6570
7126
  (_a2 = adapterRef.current) == null ? void 0 : _a2.restart();
6571
7127
  }
6572
- }, [autoStarting, props.persistSession, persistTarget]);
7128
+ }, [autoStarting, effectivePersistSession, persistTarget]);
7129
+ const handleClickToStart = react.useCallback(() => {
7130
+ startNewRunRef.current(props.initialInput);
7131
+ }, [props.initialInput]);
7132
+ const handleResumeContinue = react.useCallback(() => {
7133
+ if (pendingPersistedRef.current) {
7134
+ setResolved(pendingPersistedRef.current);
7135
+ setGate("idle");
7136
+ }
7137
+ }, []);
7138
+ const handleResumeRestart = react.useCallback(() => {
7139
+ clearPersistedSession(effectivePersistSession, persistTarget);
7140
+ setGate("idle");
7141
+ startNewRunRef.current(props.initialInput);
7142
+ }, [effectivePersistSession, persistTarget, props.initialInput]);
7143
+ const handleStartNewFromReplay = react.useCallback(() => {
7144
+ clearPersistedSession(effectivePersistSession, persistTarget);
7145
+ setTerminalReplayActive(false);
7146
+ setResolved(null);
7147
+ startNewRunRef.current(props.initialInput);
7148
+ }, [effectivePersistSession, persistTarget, props.initialInput]);
6573
7149
  const disconnect = react.useCallback(() => {
6574
7150
  var _a2;
6575
7151
  (_a2 = adapterRef.current) == null ? void 0 : _a2.disconnect();
@@ -6583,10 +7159,10 @@ var ChatterflyWidget = react.forwardRef(
6583
7159
  disconnect,
6584
7160
  sendMessage
6585
7161
  ]);
6586
- const runId = (_b = resolved == null ? void 0 : resolved.runId) != null ? _b : props.runId;
6587
- const participantToken = (_c = resolved == null ? void 0 : resolved.participantToken) != null ? _c : props.participantToken;
6588
- const mode = (_d = props.mode) != null ? _d : "inline";
6589
- const [open, setOpen] = react.useState((_e = props.defaultOpen) != null ? _e : false);
7162
+ const runId = (_c = resolved == null ? void 0 : resolved.runId) != null ? _c : props.runId;
7163
+ const participantToken = (_d = resolved == null ? void 0 : resolved.participantToken) != null ? _d : props.participantToken;
7164
+ const mode = (_e = props.mode) != null ? _e : "inline";
7165
+ const [open, setOpen] = react.useState((_f = props.defaultOpen) != null ? _f : false);
6590
7166
  const [unreadCount, setUnreadCount] = react.useState(0);
6591
7167
  const toggleOpen = react.useCallback(() => {
6592
7168
  setOpen((prev) => {
@@ -6608,10 +7184,62 @@ var ChatterflyWidget = react.forwardRef(
6608
7184
  );
6609
7185
  let content;
6610
7186
  if (configError) {
6611
- content = (_f = props.loadingFallback) != null ? _f : /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status: "error" });
7187
+ content = (_g = props.loadingFallback) != null ? _g : /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status: "error" });
7188
+ } else if (gate === "click-to-start") {
7189
+ const cfg = typeof props.clickToStart === "object" ? props.clickToStart : void 0;
7190
+ content = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.gateCard, children: [
7191
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.gateTitle, children: (_h = cfg == null ? void 0 : cfg.label) != null ? _h : t.startConversation }),
7192
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.gateDescription, children: (_i = cfg == null ? void 0 : cfg.description) != null ? _i : t.clickToStartDescription }),
7193
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.gateActions, children: /* @__PURE__ */ jsxRuntime.jsx(
7194
+ "button",
7195
+ {
7196
+ type: "button",
7197
+ className: widget_default.gateButtonPrimary,
7198
+ onClick: handleClickToStart,
7199
+ children: (_j = cfg == null ? void 0 : cfg.label) != null ? _j : t.startConversation
7200
+ }
7201
+ ) })
7202
+ ] });
7203
+ } else if (gate === "resume-choice") {
7204
+ const cfg = typeof props.resumePrompt === "object" ? props.resumePrompt : void 0;
7205
+ content = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.gateCard, children: [
7206
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.gateTitle, children: (_k = cfg == null ? void 0 : cfg.title) != null ? _k : t.resumeTitle }),
7207
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.gateActions, children: [
7208
+ /* @__PURE__ */ jsxRuntime.jsx(
7209
+ "button",
7210
+ {
7211
+ type: "button",
7212
+ className: widget_default.gateButtonPrimary,
7213
+ onClick: handleResumeContinue,
7214
+ children: (_l = cfg == null ? void 0 : cfg.continueLabel) != null ? _l : t.resumeContinue
7215
+ }
7216
+ ),
7217
+ /* @__PURE__ */ jsxRuntime.jsx(
7218
+ "button",
7219
+ {
7220
+ type: "button",
7221
+ className: widget_default.gateButtonSecondary,
7222
+ onClick: handleResumeRestart,
7223
+ children: (_m = cfg == null ? void 0 : cfg.restartLabel) != null ? _m : t.resumeRestart
7224
+ }
7225
+ )
7226
+ ] })
7227
+ ] });
6612
7228
  } else if (!runId || !participantToken) {
6613
- content = (_g = props.loadingFallback) != null ? _g : /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status: autoStarting ? "connecting" : "error" });
7229
+ content = (_n = props.loadingFallback) != null ? _n : /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status: autoStarting ? "connecting" : "error" });
6614
7230
  } else {
7231
+ const replayCompletedState = terminalReplayActive ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
7232
+ t.conversationEnded,
7233
+ /* @__PURE__ */ jsxRuntime.jsx(
7234
+ "button",
7235
+ {
7236
+ type: "button",
7237
+ className: widget_default.startNewConversationButton,
7238
+ onClick: handleStartNewFromReplay,
7239
+ children: t.startNewConversation
7240
+ }
7241
+ )
7242
+ ] }) : void 0;
6615
7243
  content = /* @__PURE__ */ jsxRuntime.jsx(
6616
7244
  ChatAdapter,
6617
7245
  {
@@ -6619,14 +7247,16 @@ var ChatterflyWidget = react.forwardRef(
6619
7247
  ref: adapterRef,
6620
7248
  runId,
6621
7249
  participantToken,
6622
- onMessage: handleMessage
7250
+ onMessage: handleMessage,
7251
+ completedState: (_o = props.completedState) != null ? _o : replayCompletedState,
7252
+ errorState: (_p = props.errorState) != null ? _p : replayCompletedState
6623
7253
  }
6624
7254
  );
6625
7255
  }
6626
7256
  if (mode !== "floating") {
6627
7257
  return content;
6628
7258
  }
6629
- const position = (_h = props.position) != null ? _h : "bottom-right";
7259
+ const position = (_q = props.position) != null ? _q : "bottom-right";
6630
7260
  return /* @__PURE__ */ jsxRuntime.jsx(
6631
7261
  FloatingLauncherChrome,
6632
7262
  {
@@ -6684,7 +7314,8 @@ function FloatingLauncherChrome({
6684
7314
  }
6685
7315
  function useChatterflyRun(options) {
6686
7316
  var _a, _b;
6687
- const { runId, participantToken, apiBase, deploymentId, workflowId, initialInput, persistSession, onEvent } = options;
7317
+ const { runId, participantToken, apiBase, deploymentId, workflowId, initialInput, persistSession, connectionPolicy, onEvent } = options;
7318
+ const effectivePersistSession = persistSession === void 0 ? true : persistSession;
6688
7319
  const [resolved, setResolved] = react.useState(null);
6689
7320
  const [error, setError] = react.useState(null);
6690
7321
  const [restartNonce, setRestartNonce] = react.useState(0);
@@ -6703,7 +7334,7 @@ function useChatterflyRun(options) {
6703
7334
  }
6704
7335
  setError(null);
6705
7336
  if (restartNonce === 0) {
6706
- const persisted = loadPersistedSession(persistSession, persistTarget);
7337
+ const persisted = loadPersistedSession(effectivePersistSession, persistTarget);
6707
7338
  if (persisted) {
6708
7339
  setResolved({ runId: persisted.runId, participantToken: persisted.participantToken });
6709
7340
  return;
@@ -6727,7 +7358,7 @@ function useChatterflyRun(options) {
6727
7358
  return r.json();
6728
7359
  }).then(({ run_id, participant_token }) => {
6729
7360
  setResolved({ runId: run_id, participantToken: participant_token });
6730
- savePersistedSession(persistSession, persistTarget, {
7361
+ savePersistedSession(effectivePersistSession, persistTarget, {
6731
7362
  runId: run_id,
6732
7363
  participantToken: participant_token
6733
7364
  });
@@ -6743,19 +7374,29 @@ function useChatterflyRun(options) {
6743
7374
  {
6744
7375
  runId: effectiveRunId != null ? effectiveRunId : "",
6745
7376
  participantToken: effectiveToken != null ? effectiveToken : "",
6746
- apiBase: apiBase != null ? apiBase : ""
7377
+ apiBase: apiBase != null ? apiBase : "",
7378
+ connectionPolicy
6747
7379
  },
6748
7380
  onEvent
6749
7381
  );
6750
7382
  const restart = react.useCallback(() => {
6751
7383
  if (autoStarting) {
6752
- clearPersistedSession(persistSession, persistTarget);
7384
+ clearPersistedSession(effectivePersistSession, persistTarget);
6753
7385
  setResolved(null);
6754
7386
  setRestartNonce((n) => n + 1);
6755
7387
  } else {
6756
7388
  stream.reconnect();
6757
7389
  }
6758
- }, [autoStarting, persistSession, persistTarget, stream]);
7390
+ }, [autoStarting, effectivePersistSession, persistTarget, stream]);
7391
+ const expiredErrorFiredRef = react.useRef(false);
7392
+ react.useEffect(() => {
7393
+ if (stream.status === "expired" && !expiredErrorFiredRef.current) {
7394
+ expiredErrorFiredRef.current = true;
7395
+ setError(
7396
+ new WidgetError("token_expired", "The participant token expired and could not be renewed.")
7397
+ );
7398
+ }
7399
+ }, [stream.status]);
6759
7400
  const connecting = autoStarting && !resolved && !error;
6760
7401
  return {
6761
7402
  ...stream,