@chatterfly/widget 0.5.0 → 0.6.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.mjs CHANGED
@@ -22,6 +22,8 @@ var defaultStrings = {
22
22
  statusCompletedTitle: "Completed",
23
23
  statusCompletedBody: "This workflow run has finished.",
24
24
  statusErrorTitle: "Something went wrong",
25
+ statusAuthorizationTitle: "Authorization required",
26
+ statusAuthorizationBody: "Reconnect the linked account to continue this workflow.",
25
27
  statusOfflineTitle: "Connection lost",
26
28
  statusOfflineBody: "Unable to reach the server. Please check your connection and refresh.",
27
29
  statusExpiredTitle: "Session expired",
@@ -30,7 +32,9 @@ var defaultStrings = {
30
32
  resumingConversation: "Resuming conversation\u2026",
31
33
  reconnecting: "Reconnecting\u2026",
32
34
  conversationCompleted: "Conversation completed.",
35
+ conversationTimedOut: "This conversation timed out.",
33
36
  somethingWentWrong: "Something went wrong",
37
+ tryAgain: "Try again",
34
38
  chatInputPlaceholder: "Type a message\u2026",
35
39
  sendButton: "Send",
36
40
  handBackButton: "Hand Back",
@@ -76,6 +80,7 @@ function useRunStream(config, onEvent) {
76
80
  const pollIntervalMs = (_b = !dormancyDisabled && typeof policyConfig === "object" ? policyConfig == null ? void 0 : policyConfig.pollIntervalMs : void 0) != null ? _b : DEFAULT_POLL_INTERVAL_MS;
77
81
  const hibernateAfterMs = (_c = !dormancyDisabled && typeof policyConfig === "object" ? policyConfig == null ? void 0 : policyConfig.hibernateAfterMs : void 0) != null ? _c : DEFAULT_HIBERNATE_AFTER_MS;
78
82
  const [status, setStatus] = useState("idle");
83
+ const [failureKind, setFailureKind] = useState(null);
79
84
  const [activeSession, setActiveSession] = useState(null);
80
85
  const [messages, setMessages] = useState([]);
81
86
  const [timeline, setTimeline] = useState([]);
@@ -297,7 +302,7 @@ function useRunStream(config, onEvent) {
297
302
  };
298
303
  }, [dormancyDisabled, wake]);
299
304
  function handleEvent(event) {
300
- var _a2, _b2, _c2, _d, _e;
305
+ var _a2, _b2, _c2, _d, _e, _f;
301
306
  (_a2 = onEventRef.current) == null ? void 0 : _a2.call(onEventRef, event);
302
307
  switch (event.type) {
303
308
  case "timeline.replay": {
@@ -315,11 +320,27 @@ function useRunStream(config, onEvent) {
315
320
  setStreamingText("");
316
321
  break;
317
322
  }
323
+ case "provider_operation": {
324
+ if (event.payload) {
325
+ mergeTimeline([{
326
+ id: `provider-${(_b2 = event.node_id) != null ? _b2 : "operation"}-${Date.now()}`,
327
+ run_id: runId,
328
+ session_id: null,
329
+ seq: Number.MAX_SAFE_INTEGER,
330
+ event_type: "provider_operation",
331
+ sender: "system",
332
+ payload: event.payload,
333
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
334
+ }]);
335
+ }
336
+ break;
337
+ }
318
338
  case "agent.token": {
319
339
  setStreamingText((prev) => prev + event.token);
320
340
  break;
321
341
  }
322
342
  case "run.started":
343
+ setFailureKind(null);
323
344
  updateStatus("running");
324
345
  break;
325
346
  case "run.status_changed":
@@ -335,7 +356,7 @@ function useRunStream(config, onEvent) {
335
356
  entry_context: event.entry_context,
336
357
  status: "open",
337
358
  messages: replayedMessages,
338
- document_content: (_b2 = event.document_content) != null ? _b2 : null
359
+ document_content: (_c2 = event.document_content) != null ? _c2 : null
339
360
  };
340
361
  setActiveSession(session);
341
362
  if (replayedMessages.length > 0) {
@@ -348,7 +369,7 @@ function useRunStream(config, onEvent) {
348
369
  } else if (event.layout === "form") {
349
370
  updateStatus("awaiting_form");
350
371
  } else {
351
- const surface = (_c2 = event.entry_context) == null ? void 0 : _c2.surface;
372
+ const surface = (_d = event.entry_context) == null ? void 0 : _d.surface;
352
373
  const isVoice = typeof surface === "string" && (surface === "widget/voice" || surface === "phone" || surface === "phone/outbound");
353
374
  if (isVoice) {
354
375
  updateStatus("awaiting_voice");
@@ -363,6 +384,11 @@ function useRunStream(config, onEvent) {
363
384
  setMessages([]);
364
385
  updateStatus("running");
365
386
  break;
387
+ case "run.authorization_required":
388
+ setStreamingText("");
389
+ setFailureKind(null);
390
+ updateStatus("awaiting_authorization");
391
+ break;
366
392
  case "message.sent": {
367
393
  setMessages((prev) => [
368
394
  ...prev,
@@ -376,14 +402,16 @@ function useRunStream(config, onEvent) {
376
402
  case "run.completed":
377
403
  case "run.cancelled":
378
404
  setStreamingText("");
405
+ setFailureKind(null);
379
406
  if (event.state) setOutput(event.state);
380
407
  updateStatus("completed");
381
- (_d = wsRef.current) == null ? void 0 : _d.close();
408
+ (_e = wsRef.current) == null ? void 0 : _e.close();
382
409
  break;
383
410
  case "run.failed":
384
411
  setStreamingText("");
412
+ setFailureKind(/timed out/i.test(event.error) ? "timeout" : null);
385
413
  updateStatus("error");
386
- (_e = wsRef.current) == null ? void 0 : _e.close();
414
+ (_f = wsRef.current) == null ? void 0 : _f.close();
387
415
  break;
388
416
  }
389
417
  }
@@ -489,6 +517,8 @@ function useRunStream(config, onEvent) {
489
517
  }, [connect]);
490
518
  return {
491
519
  status,
520
+ failureKind,
521
+ currentParticipantToken: currentToken,
492
522
  activeSession,
493
523
  messages,
494
524
  timeline,
@@ -657,6 +687,10 @@ var widget_default = {
657
687
  messageFeed: "widget_messageFeed",
658
688
  feedMessage: "widget_feedMessage",
659
689
  chatTimeline: "widget_chatTimeline",
690
+ toolActivity: "widget_toolActivity",
691
+ toolActivityPulse: "widget_toolActivityPulse",
692
+ toolActivityDone: "widget_toolActivityDone",
693
+ "cf-tool-pulse": "widget_cf-tool-pulse",
660
694
  bubbleRow: "widget_bubbleRow",
661
695
  bubbleUserRow: "widget_bubbleUserRow",
662
696
  bubble: "widget_bubble",
@@ -734,6 +768,8 @@ var widget_default = {
734
768
  voiceTranscriptLabel: "widget_voiceTranscriptLabel",
735
769
  voiceError: "widget_voiceError",
736
770
  cfVoiceShake: "widget_cfVoiceShake",
771
+ voiceErrorGroup: "widget_voiceErrorGroup",
772
+ voiceRetryButton: "widget_voiceRetryButton",
737
773
  voiceOrbContainer: "widget_voiceOrbContainer",
738
774
  voiceOrbRow: "widget_voiceOrbRow",
739
775
  voiceOrbHint: "widget_voiceOrbHint",
@@ -1200,6 +1236,29 @@ function entryToDisplay(entry) {
1200
1236
  case "delay_resumed":
1201
1237
  return null;
1202
1238
  // no visible bubble
1239
+ case "tool_call": {
1240
+ const tool = typeof payload.callee_agent === "string" ? payload.callee_agent : typeof payload.name === "string" ? payload.name : "Tool";
1241
+ return { text: `${tool} is working`, sender: "system", activity: "running" };
1242
+ }
1243
+ case "tool_result": {
1244
+ const tool = typeof payload.callee_agent === "string" ? payload.callee_agent : typeof payload.name === "string" ? payload.name : "Tool";
1245
+ return { text: `${tool} finished`, sender: "system", activity: "completed" };
1246
+ }
1247
+ case "provider_operation": {
1248
+ const operation = typeof payload.operation === "string" ? payload.operation : "Provider operation";
1249
+ if (payload.outcome === "error") {
1250
+ const code = typeof payload.error_code === "string" ? payload.error_code : "provider_operation_failed";
1251
+ return { text: `${operation} could not be completed (${code}).`, sender: "system" };
1252
+ }
1253
+ const recordID = typeof payload.record_id === "string" ? payload.record_id : "";
1254
+ const recordURL = typeof payload.record_url === "string" && payload.record_url.startsWith("https://") ? payload.record_url : "";
1255
+ return {
1256
+ text: payload.replayed === true ? `${operation} was already completed; the saved result was reused.` : `${operation} completed.`,
1257
+ tags: recordID ? [`Record ${recordID}`] : void 0,
1258
+ sender: "system",
1259
+ link: recordURL ? { href: recordURL, label: "Open record" } : void 0
1260
+ };
1261
+ }
1203
1262
  default:
1204
1263
  return null;
1205
1264
  }
@@ -1268,10 +1327,33 @@ function ChatTimeline({ entries, showTyping, streamingText, components }) {
1268
1327
  }, [streamingText, scheduleScrollToBottom]);
1269
1328
  return /* @__PURE__ */ jsxs("div", { ref: containerRef, className: widget_default.chatTimeline, onScroll: handleScroll, children: [
1270
1329
  entries.map((entry) => {
1330
+ var _a2;
1271
1331
  const display = entryToDisplay(entry);
1272
1332
  if (!display) return null;
1273
1333
  if (display.sender === "system") {
1274
- return /* @__PURE__ */ jsx("div", { className: widget_default.bubbleSystem, children: /* @__PURE__ */ jsx(MarkdownBubble, { content: display.text }) }, entry.id);
1334
+ return /* @__PURE__ */ jsxs(
1335
+ "div",
1336
+ {
1337
+ className: display.activity ? widget_default.toolActivity : widget_default.bubbleSystem,
1338
+ role: display.activity === "running" ? "status" : void 0,
1339
+ children: [
1340
+ display.activity && /* @__PURE__ */ jsx(
1341
+ "span",
1342
+ {
1343
+ className: display.activity === "running" ? widget_default.toolActivityPulse : widget_default.toolActivityDone,
1344
+ "aria-hidden": "true"
1345
+ }
1346
+ ),
1347
+ /* @__PURE__ */ jsx(MarkdownBubble, { content: display.text }),
1348
+ (_a2 = display.tags) == null ? void 0 : _a2.map((tag) => /* @__PURE__ */ jsxs("span", { children: [
1349
+ " ",
1350
+ tag
1351
+ ] }, tag)),
1352
+ display.link && /* @__PURE__ */ jsx("a", { href: display.link.href, target: "_blank", rel: "noopener noreferrer", children: display.link.label })
1353
+ ]
1354
+ },
1355
+ entry.id
1356
+ );
1275
1357
  }
1276
1358
  if (display.sender === "user") {
1277
1359
  if (display.formData) {
@@ -1365,6 +1447,8 @@ function getProviderId(serviceType) {
1365
1447
  return "gmail";
1366
1448
  case "github":
1367
1449
  return "github";
1450
+ case "zoho":
1451
+ return "zoho";
1368
1452
  default:
1369
1453
  return null;
1370
1454
  }
@@ -1375,12 +1459,14 @@ function getServiceLabel(serviceType) {
1375
1459
  return "Gmail";
1376
1460
  case "github":
1377
1461
  return "GitHub";
1462
+ case "zoho":
1463
+ return "Zoho";
1378
1464
  default:
1379
1465
  return serviceType;
1380
1466
  }
1381
1467
  }
1382
1468
  function supportsSwitch(serviceType) {
1383
- return serviceType === "gmail";
1469
+ return serviceType === "gmail" || serviceType === "zoho";
1384
1470
  }
1385
1471
  function ConnectionOnboarding({
1386
1472
  connections,
@@ -2900,6 +2986,11 @@ function StatusDisplay({ status, error, strings }) {
2900
2986
  /* @__PURE__ */ jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: t.statusErrorTitle }),
2901
2987
  error && /* @__PURE__ */ jsx("div", { className: `${widget_default.statusLabel} ${widget_default.statusError}`, children: error })
2902
2988
  ] });
2989
+ case "awaiting_authorization":
2990
+ return /* @__PURE__ */ jsxs("div", { className: widget_default.statusWrapper, children: [
2991
+ /* @__PURE__ */ jsx("div", { className: widget_default.statusTitle, children: t.statusAuthorizationTitle }),
2992
+ /* @__PURE__ */ jsx("div", { className: widget_default.statusLabel, children: t.statusAuthorizationBody })
2993
+ ] });
2903
2994
  case "offline":
2904
2995
  return /* @__PURE__ */ jsxs("div", { className: widget_default.statusWrapper, children: [
2905
2996
  /* @__PURE__ */ jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: t.statusOfflineTitle }),
@@ -4503,6 +4594,7 @@ var PCM_WORKLET_NAME = "cf-pcm-capture";
4503
4594
 
4504
4595
  // src/hooks/useGeminiLiveSession.ts
4505
4596
  var SUBPROTOCOL = "chatterfly.voice.v1";
4597
+ var MAX_RECONNECT_ATTEMPTS2 = 3;
4506
4598
  function useGeminiLiveSession(cfg, onValue) {
4507
4599
  const {
4508
4600
  apiBase,
@@ -4518,9 +4610,12 @@ function useGeminiLiveSession(cfg, onValue) {
4518
4610
  const [askedFieldId, setAskedFieldId] = useState(null);
4519
4611
  const [playbackComplete, setPlaybackComplete] = useState(false);
4520
4612
  const [lastValue, setLastValue] = useState(null);
4613
+ const [checkpoint, setCheckpoint] = useState(null);
4614
+ const [completion, setCompletion] = useState(null);
4521
4615
  const [inputLevel, setInputLevel] = useState(0);
4522
4616
  const [isMuted, setIsMuted] = useState(false);
4523
4617
  const [error, setError] = useState(null);
4618
+ const [errorRecoverable, setErrorRecoverable] = useState(false);
4524
4619
  const wsRef = useRef(null);
4525
4620
  const ctxRef = useRef(null);
4526
4621
  const streamRef = useRef(null);
@@ -4536,6 +4631,8 @@ function useGeminiLiveSession(cfg, onValue) {
4536
4631
  const terminalReceivedRef = useRef(false);
4537
4632
  const currentPlaybackTurnRef = useRef(null);
4538
4633
  const playbackTurnsRef = useRef(/* @__PURE__ */ new Map());
4634
+ const retryAllowedRef = useRef(true);
4635
+ const maxHistorySequenceRef = useRef(0);
4539
4636
  const socketSessionIdRef = useRef(null);
4540
4637
  if (sessionId && socketSessionIdRef.current === null) {
4541
4638
  socketSessionIdRef.current = sessionId;
@@ -4667,13 +4764,72 @@ function useGeminiLiveSession(cfg, onValue) {
4667
4764
  switch (msg.type) {
4668
4765
  case "state": {
4669
4766
  const next = String((_a = msg.state) != null ? _a : "");
4670
- if (next === "listening" || next === "speaking" || next === "idle" || next === "connecting") {
4767
+ if (next === "listening" || next === "speaking" || next === "idle" || next === "connecting" || next === "finalizing") {
4671
4768
  setState(next);
4672
4769
  } else if (next === "processing") {
4673
4770
  setState("connecting");
4674
4771
  }
4675
4772
  break;
4676
4773
  }
4774
+ case "history": {
4775
+ if (!Array.isArray(msg.history)) break;
4776
+ const restored = msg.history.flatMap((item) => {
4777
+ if (typeof item !== "object" || item === null) return [];
4778
+ const who = item.who;
4779
+ const text = item.text;
4780
+ const sequence = item.sequence;
4781
+ if (who !== "user" && who !== "assistant" || typeof text !== "string" || text.length === 0) return [];
4782
+ return [{
4783
+ who,
4784
+ text,
4785
+ final: true,
4786
+ sequence: typeof sequence === "number" ? sequence : void 0
4787
+ }];
4788
+ });
4789
+ const maxSequence = restored.reduce(
4790
+ (max, item) => {
4791
+ var _a2;
4792
+ return Math.max(max, (_a2 = item.sequence) != null ? _a2 : 0);
4793
+ },
4794
+ 0
4795
+ );
4796
+ if (maxSequence > 0 && maxSequence <= maxHistorySequenceRef.current) break;
4797
+ maxHistorySequenceRef.current = maxSequence;
4798
+ setTranscripts(restored);
4799
+ if (typeof msg.fieldId === "string" && msg.fieldId.length > 0) {
4800
+ setActiveFieldId(msg.fieldId);
4801
+ setAskedFieldId(msg.fieldId);
4802
+ }
4803
+ const lastAssistant = [...restored].reverse().find((item) => item.who === "assistant");
4804
+ if (lastAssistant) setAssistantText(lastAssistant.text);
4805
+ break;
4806
+ }
4807
+ case "checkpoint": {
4808
+ const sequence = Number(msg.sequence);
4809
+ const turn = Number(msg.turn);
4810
+ if (!Number.isSafeInteger(sequence) || sequence < 1) break;
4811
+ if (!Number.isSafeInteger(turn) || turn < 0) break;
4812
+ setCheckpoint(
4813
+ (previous) => previous && previous.sequence >= sequence ? previous : {
4814
+ sequence,
4815
+ turn,
4816
+ reconstructed: msg.reconstructed === true
4817
+ }
4818
+ );
4819
+ break;
4820
+ }
4821
+ case "completion": {
4822
+ const status = msg.status;
4823
+ if (status !== "finalizing" && status !== "completed") break;
4824
+ setCompletion({
4825
+ status,
4826
+ reason: typeof msg.completionReason === "string" && msg.completionReason.length > 0 ? msg.completionReason : null
4827
+ });
4828
+ setState(
4829
+ (previous) => previous === "error" || previous === "completed" ? previous : "finalizing"
4830
+ );
4831
+ break;
4832
+ }
4677
4833
  case "interrupt": {
4678
4834
  flushPlayback();
4679
4835
  setState("listening");
@@ -4772,13 +4928,17 @@ function useGeminiLiveSession(cfg, onValue) {
4772
4928
  break;
4773
4929
  }
4774
4930
  case "completed": {
4931
+ retryAllowedRef.current = false;
4775
4932
  terminalReceivedRef.current = true;
4776
4933
  setState("completed");
4777
4934
  maybeCompletePlayback();
4778
4935
  break;
4779
4936
  }
4780
4937
  case "error": {
4938
+ const recoverable = msg.fatal !== true;
4939
+ if (!recoverable) retryAllowedRef.current = false;
4781
4940
  setError(String((_h = msg.message) != null ? _h : "voice session error"));
4941
+ setErrorRecoverable(recoverable);
4782
4942
  setState("error");
4783
4943
  break;
4784
4944
  }
@@ -4790,10 +4950,66 @@ function useGeminiLiveSession(cfg, onValue) {
4790
4950
  if (!socketSessionId || !participantToken) return;
4791
4951
  let cancelled = false;
4792
4952
  disposedRef.current = false;
4953
+ retryAllowedRef.current = true;
4793
4954
  terminalReceivedRef.current = false;
4794
4955
  currentPlaybackTurnRef.current = null;
4795
4956
  playbackTurnsRef.current.clear();
4796
4957
  setPlaybackComplete(false);
4958
+ let reconnectAttempts = 0;
4959
+ let reconnectTimer = null;
4960
+ let stableConnectionTimer = null;
4961
+ const connectSocket = () => {
4962
+ if (cancelled || disposedRef.current) return;
4963
+ setState("connecting");
4964
+ const wsUrl = apiBase.replace(/^http/, "ws") + `/api/participant/inbox/${encodeURIComponent(socketSessionId)}/voice-stream?token=${encodeURIComponent(participantToken)}`;
4965
+ const ws = new WebSocket(wsUrl, SUBPROTOCOL);
4966
+ ws.binaryType = "arraybuffer";
4967
+ wsRef.current = ws;
4968
+ ws.onopen = () => {
4969
+ if (cancelled) return;
4970
+ setError(null);
4971
+ setErrorRecoverable(false);
4972
+ setState("listening");
4973
+ ws.send(
4974
+ JSON.stringify({
4975
+ type: "hello",
4976
+ input_sample_rate: inputSampleRate,
4977
+ output_sample_rate: outputSampleRate
4978
+ })
4979
+ );
4980
+ stableConnectionTimer = setTimeout(() => {
4981
+ reconnectAttempts = 0;
4982
+ }, 1e4);
4983
+ };
4984
+ ws.onmessage = (ev) => {
4985
+ if (typeof ev.data === "string") {
4986
+ try {
4987
+ handleInbound(JSON.parse(ev.data));
4988
+ } catch {
4989
+ }
4990
+ return;
4991
+ }
4992
+ if (ev.data instanceof ArrayBuffer) enqueuePlayback(ev.data);
4993
+ };
4994
+ ws.onerror = () => {
4995
+ };
4996
+ ws.onclose = () => {
4997
+ if (stableConnectionTimer !== null) {
4998
+ clearTimeout(stableConnectionTimer);
4999
+ stableConnectionTimer = null;
5000
+ }
5001
+ if (cancelled || disposedRef.current || !retryAllowedRef.current) return;
5002
+ if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS2) {
5003
+ setError("voice connection lost");
5004
+ setState("error");
5005
+ return;
5006
+ }
5007
+ const delay = 500 * 2 ** reconnectAttempts;
5008
+ reconnectAttempts += 1;
5009
+ setState("connecting");
5010
+ reconnectTimer = setTimeout(connectSocket, delay);
5011
+ };
5012
+ };
4797
5013
  const start = async () => {
4798
5014
  try {
4799
5015
  setState("connecting");
@@ -4825,46 +5041,11 @@ function useGeminiLiveSession(cfg, onValue) {
4825
5041
  });
4826
5042
  workletRef.current = worklet;
4827
5043
  source.connect(worklet);
4828
- const wsUrl = apiBase.replace(/^http/, "ws") + `/api/participant/inbox/${encodeURIComponent(socketSessionId)}/voice-stream?token=${encodeURIComponent(participantToken)}`;
4829
- const ws = new WebSocket(wsUrl, SUBPROTOCOL);
4830
- ws.binaryType = "arraybuffer";
4831
- wsRef.current = ws;
4832
- ws.onopen = () => {
4833
- if (cancelled) return;
4834
- setState("listening");
4835
- ws.send(
4836
- JSON.stringify({
4837
- type: "hello",
4838
- input_sample_rate: inputSampleRate,
4839
- output_sample_rate: outputSampleRate
4840
- })
4841
- );
4842
- };
4843
- ws.onmessage = (ev) => {
4844
- if (typeof ev.data === "string") {
4845
- try {
4846
- const msg = JSON.parse(ev.data);
4847
- handleInbound(msg);
4848
- } catch {
4849
- }
4850
- return;
4851
- }
4852
- if (ev.data instanceof ArrayBuffer) {
4853
- enqueuePlayback(ev.data);
4854
- }
4855
- };
4856
- ws.onerror = () => {
4857
- if (disposedRef.current) return;
4858
- setError("voice connection error");
4859
- setState("error");
4860
- };
4861
- ws.onclose = () => {
4862
- if (disposedRef.current) return;
4863
- setState((prev) => prev === "completed" ? prev : "idle");
4864
- };
5044
+ connectSocket();
4865
5045
  worklet.port.onmessage = (ev) => {
4866
5046
  if (isMutedRef.current) return;
4867
- if (ws.readyState !== WebSocket.OPEN) return;
5047
+ const ws = wsRef.current;
5048
+ if ((ws == null ? void 0 : ws.readyState) !== WebSocket.OPEN) return;
4868
5049
  const pcm = ev.data;
4869
5050
  noteMicLevel(pcm);
4870
5051
  ws.send(pcm);
@@ -4880,6 +5061,8 @@ function useGeminiLiveSession(cfg, onValue) {
4880
5061
  var _a, _b, _c, _d, _e, _f;
4881
5062
  cancelled = true;
4882
5063
  disposedRef.current = true;
5064
+ if (reconnectTimer !== null) clearTimeout(reconnectTimer);
5065
+ if (stableConnectionTimer !== null) clearTimeout(stableConnectionTimer);
4883
5066
  try {
4884
5067
  (_a = wsRef.current) == null ? void 0 : _a.send(JSON.stringify({ type: "bye" }));
4885
5068
  } catch {
@@ -4926,6 +5109,25 @@ function useGeminiLiveSession(cfg, onValue) {
4926
5109
  return next;
4927
5110
  });
4928
5111
  }, []);
5112
+ const retryError = useCallback(() => {
5113
+ if (!errorRecoverable) return;
5114
+ setError(null);
5115
+ setErrorRecoverable(false);
5116
+ setState("listening");
5117
+ }, [errorRecoverable]);
5118
+ const requestEnd = useCallback(() => {
5119
+ const socket = wsRef.current;
5120
+ if (!socket || socket.readyState !== WebSocket.OPEN) {
5121
+ setError("Voice connection is not ready.");
5122
+ setErrorRecoverable(true);
5123
+ setState("error");
5124
+ return;
5125
+ }
5126
+ socket.send(JSON.stringify({ type: "end" }));
5127
+ setError(null);
5128
+ setErrorRecoverable(false);
5129
+ setState("finalizing");
5130
+ }, []);
4929
5131
  return {
4930
5132
  state,
4931
5133
  transcripts,
@@ -4934,10 +5136,15 @@ function useGeminiLiveSession(cfg, onValue) {
4934
5136
  askedFieldId,
4935
5137
  playbackComplete,
4936
5138
  lastValue,
5139
+ checkpoint,
5140
+ completion,
4937
5141
  inputLevel: isMuted ? 0 : inputLevel,
4938
5142
  isMuted,
4939
5143
  toggleMute,
4940
- error
5144
+ error,
5145
+ errorRecoverable,
5146
+ retryError,
5147
+ requestEnd
4941
5148
  };
4942
5149
  }
4943
5150
  function VoiceLiveRenderer({
@@ -4950,8 +5157,14 @@ function VoiceLiveRenderer({
4950
5157
  onValue,
4951
5158
  onPlaybackComplete,
4952
5159
  onFieldRevealed,
5160
+ timedOut = false,
5161
+ timeoutMessage = "This conversation timed out.",
5162
+ retryLabel = "Try again",
5163
+ userCanEnd = false,
5164
+ endLabel = "I'm done",
4953
5165
  disabled
4954
5166
  }) {
5167
+ var _a;
4955
5168
  const session = useGeminiLiveSession(
4956
5169
  {
4957
5170
  apiBase,
@@ -4973,8 +5186,8 @@ function VoiceLiveRenderer({
4973
5186
  }, [fieldRevealed, fieldSessionId, onFieldRevealed]);
4974
5187
  const promptRef = useRef(null);
4975
5188
  useEffect(() => {
4976
- var _a;
4977
- (_a = promptRef.current) == null ? void 0 : _a.scrollIntoView({ behavior: "smooth", block: "nearest" });
5189
+ var _a2;
5190
+ (_a2 = promptRef.current) == null ? void 0 : _a2.scrollIntoView({ behavior: "smooth", block: "nearest" });
4978
5191
  }, [field, fieldRevealed]);
4979
5192
  const orbState = (() => {
4980
5193
  if (session.error) return "error";
@@ -4986,6 +5199,7 @@ function VoiceLiveRenderer({
4986
5199
  case "listening":
4987
5200
  return "listening";
4988
5201
  case "processing":
5202
+ case "finalizing":
4989
5203
  return "processing";
4990
5204
  case "speaking":
4991
5205
  return "speaking";
@@ -5003,11 +5217,16 @@ function VoiceLiveRenderer({
5003
5217
  if (el) el.scrollTop = el.scrollHeight;
5004
5218
  }, [session.transcripts]);
5005
5219
  const announcement = (() => {
5220
+ var _a2;
5221
+ if (timedOut) return timeoutMessage;
5006
5222
  if (session.error) return session.error;
5007
5223
  if (session.isMuted) return "Microphone muted.";
5008
5224
  if (session.state === "connecting") return "Connecting to voice service.";
5009
5225
  if (session.state === "listening") return "Microphone listening.";
5010
5226
  if (session.state === "processing") return "Preparing the next step.";
5227
+ if (session.state === "finalizing") {
5228
+ return ((_a2 = session.completion) == null ? void 0 : _a2.status) === "completed" ? "Conversation complete. Finishing playback." : "Finalizing the conversation.";
5229
+ }
5011
5230
  if (session.state === "speaking") return "Assistant speaking.";
5012
5231
  return "";
5013
5232
  })();
@@ -5049,7 +5268,12 @@ function VoiceLiveRenderer({
5049
5268
  session.isMuted && /* @__PURE__ */ jsx("span", { className: widget_default.voiceOrbHint, "aria-hidden": "true", children: "Microphone muted" }),
5050
5269
  !session.isMuted && session.state === "connecting" && /* @__PURE__ */ jsx("span", { className: widget_default.voiceAssistantStatus, children: "Connecting\u2026" }),
5051
5270
  !session.isMuted && session.state === "processing" && /* @__PURE__ */ jsx("span", { className: widget_default.voiceAssistantStatus, children: "Preparing the next step\u2026" }),
5052
- !session.isMuted && session.state === "speaking" && /* @__PURE__ */ jsx("span", { className: widget_default.voiceAssistantStatus, children: "Assistant speaking\u2026" })
5271
+ !session.isMuted && session.state === "finalizing" && /* @__PURE__ */ jsx("span", { className: widget_default.voiceAssistantStatus, children: ((_a = session.completion) == null ? void 0 : _a.status) === "completed" ? "Conversation complete \xB7 finishing playback\u2026" : "Finalizing\u2026" }),
5272
+ !session.isMuted && session.state === "speaking" && /* @__PURE__ */ jsx("span", { className: widget_default.voiceAssistantStatus, children: "Assistant speaking\u2026" }),
5273
+ !session.isMuted && session.state === "listening" && session.checkpoint && /* @__PURE__ */ jsxs("span", { className: widget_default.voiceOrbHint, children: [
5274
+ "Progress saved \xB7 turn ",
5275
+ session.checkpoint.turn
5276
+ ] })
5053
5277
  ] })
5054
5278
  ] }),
5055
5279
  session.transcripts.length > 0 && /* @__PURE__ */ jsx("div", { ref: logRef, className: widget_default.voiceLiveLog, children: session.transcripts.map((t, i) => /* @__PURE__ */ jsxs(
@@ -5064,7 +5288,29 @@ function VoiceLiveRenderer({
5064
5288
  i
5065
5289
  )) }),
5066
5290
  fieldRevealed && /* @__PURE__ */ jsx("div", { ref: promptRef, children: /* @__PURE__ */ jsx(VoicePromptCard, { field }) }),
5067
- session.error && /* @__PURE__ */ jsx("p", { className: widget_default.voiceError, children: session.error })
5291
+ timedOut && /* @__PURE__ */ jsx("p", { className: widget_default.voiceError, children: timeoutMessage }),
5292
+ !timedOut && session.error && /* @__PURE__ */ jsxs("div", { className: widget_default.voiceErrorGroup, children: [
5293
+ /* @__PURE__ */ jsx("p", { className: widget_default.voiceError, children: session.error }),
5294
+ session.errorRecoverable && /* @__PURE__ */ jsx(
5295
+ "button",
5296
+ {
5297
+ type: "button",
5298
+ className: widget_default.voiceRetryButton,
5299
+ onClick: session.retryError,
5300
+ children: retryLabel
5301
+ }
5302
+ )
5303
+ ] }),
5304
+ userCanEnd && !timedOut && session.state !== "finalizing" && session.state !== "completed" && /* @__PURE__ */ jsx(
5305
+ "button",
5306
+ {
5307
+ type: "button",
5308
+ className: widget_default.converseDoneButton,
5309
+ onClick: session.requestEnd,
5310
+ disabled: disabled || session.state === "connecting",
5311
+ children: endLabel
5312
+ }
5313
+ )
5068
5314
  ] });
5069
5315
  }
5070
5316
  function InputText({
@@ -6263,7 +6509,7 @@ var ChatAdapter = forwardRef(
6263
6509
  components,
6264
6510
  strings
6265
6511
  }, ref) {
6266
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
6512
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
6267
6513
  const t = resolveStrings(strings);
6268
6514
  const apiBaseResolved = apiBase;
6269
6515
  const appBaseResolved = typeof window !== "undefined" ? window.location.origin : (_a = process.env.APP_URL) != null ? _a : "http://localhost:3000";
@@ -6290,6 +6536,8 @@ var ChatAdapter = forwardRef(
6290
6536
  );
6291
6537
  const {
6292
6538
  status,
6539
+ failureKind,
6540
+ currentParticipantToken,
6293
6541
  activeSession,
6294
6542
  timeline,
6295
6543
  submitHandback,
@@ -6543,7 +6791,7 @@ var ChatAdapter = forwardRef(
6543
6791
  return /* @__PURE__ */ jsxs("div", { className: cls, style: rootStyle, children: [
6544
6792
  hasChatContent && /* @__PURE__ */ jsx(ChatTimeline, { entries: timeline, streamingText, components }),
6545
6793
  status === "completed" && /* @__PURE__ */ jsx("div", { className: widget_default.terminalCompleted, children: completedState != null ? completedState : t.conversationCompleted }),
6546
- status === "error" && /* @__PURE__ */ jsx("div", { className: widget_default.terminalError, children: errorState != null ? errorState : t.somethingWentWrong })
6794
+ status === "error" && /* @__PURE__ */ jsx("div", { className: widget_default.terminalError, children: errorState != null ? errorState : failureKind === "timeout" ? t.conversationTimedOut : t.somethingWentWrong })
6547
6795
  ] });
6548
6796
  }
6549
6797
  if (status === "awaiting_form" && activeSession) {
@@ -6585,11 +6833,12 @@ var ChatAdapter = forwardRef(
6585
6833
  const converseCtx = activeSession == null ? void 0 : activeSession.entry_context;
6586
6834
  const isConverseSession = (converseCtx == null ? void 0 : converseCtx.converse_session) === true;
6587
6835
  const converseUserCanEnd = (converseCtx == null ? void 0 : converseCtx.converse_user_can_end) === true;
6836
+ const converseRuntime = (_f = converseCtx == null ? void 0 : converseCtx.converse_runtime) != null ? _f : "turn_based";
6588
6837
  const field = activeSession ? extractField(activeSession) : null;
6589
6838
  if (status === "awaiting_chat" && activeSession && !(isConverseSession && field)) {
6590
- const hbCtx = (_f = activeSession.entry_context) == null ? void 0 : _f.handback;
6839
+ const hbCtx = (_g = activeSession.entry_context) == null ? void 0 : _g.handback;
6591
6840
  const outputSchema = hbCtx == null ? void 0 : hbCtx.output_schema;
6592
- const requireOutput = (_g = hbCtx == null ? void 0 : hbCtx.require_output) != null ? _g : false;
6841
+ const requireOutput = (_h = hbCtx == null ? void 0 : hbCtx.require_output) != null ? _h : false;
6593
6842
  const handbackReady = !requireOutput || outputSchema != null && Object.keys(outputSchema).every((k) => {
6594
6843
  var _a2;
6595
6844
  return ((_a2 = handbackValues[k]) != null ? _a2 : "").trim() !== "";
@@ -6696,10 +6945,10 @@ var ChatAdapter = forwardRef(
6696
6945
  liveVoiceRef.current = {
6697
6946
  // Pin the FIRST id: it only picks which socket to open, and the proxy
6698
6947
  // tracks field transitions itself from then on.
6699
- sessionId: (_i = (_h = liveVoiceRef.current) == null ? void 0 : _h.sessionId) != null ? _i : activeSession.id,
6948
+ sessionId: (_j = (_i = liveVoiceRef.current) == null ? void 0 : _i.sessionId) != null ? _j : activeSession.id,
6700
6949
  fieldSessionId: activeSession.id,
6701
6950
  field,
6702
- hint: (_k = nodeVoice == null ? void 0 : nodeVoice.hint) != null ? _k : (_j = field.voice) == null ? void 0 : _j.hint,
6951
+ hint: (_l = nodeVoice == null ? void 0 : nodeVoice.hint) != null ? _l : (_k = field.voice) == null ? void 0 : _k.hint,
6703
6952
  config: surfaceConfig != null ? surfaceConfig : void 0
6704
6953
  };
6705
6954
  }
@@ -6720,12 +6969,17 @@ var ChatAdapter = forwardRef(
6720
6969
  field: liveVoice.field,
6721
6970
  voiceHint: liveVoice.hint,
6722
6971
  apiBase: apiBaseResolved,
6723
- participantToken,
6972
+ participantToken: currentParticipantToken,
6724
6973
  sessionId: liveVoice.sessionId,
6725
6974
  fieldSessionId: liveVoice.fieldSessionId,
6726
6975
  liveConfig: liveVoice.config,
6727
6976
  onValue: (value) => setInputValue(value),
6728
6977
  onPlaybackComplete: () => setLivePlaybackComplete(true),
6978
+ timedOut: failureKind === "timeout",
6979
+ timeoutMessage: t.conversationTimedOut,
6980
+ retryLabel: t.tryAgain,
6981
+ userCanEnd: converseUserCanEnd,
6982
+ endLabel: t.converseDoneButton,
6729
6983
  onFieldRevealed: (revealedSessionId) => setRevealedLivePromptSessions((prev) => {
6730
6984
  if (prev.has(revealedSessionId)) return prev;
6731
6985
  const next = new Set(prev);
@@ -6738,7 +6992,7 @@ var ChatAdapter = forwardRef(
6738
6992
  ] });
6739
6993
  }
6740
6994
  if (shouldUseVoice && activeSession && field) {
6741
- const spokenHint = (_m = nodeVoice == null ? void 0 : nodeVoice.hint) != null ? _m : (_l = field.voice) == null ? void 0 : _l.hint;
6995
+ const spokenHint = (_n = nodeVoice == null ? void 0 : nodeVoice.hint) != null ? _n : (_m = field.voice) == null ? void 0 : _m.hint;
6742
6996
  const handleVoiceValue = (value) => {
6743
6997
  setInputValue(value);
6744
6998
  void submitHandback(value, crypto.randomUUID());
@@ -6755,7 +7009,7 @@ var ChatAdapter = forwardRef(
6755
7009
  participantToken,
6756
7010
  onValue: handleVoiceValue,
6757
7011
  autoSubmitMode: "confirm",
6758
- 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,
7012
+ confidenceThreshold: (_o = nodeVoice == null ? void 0 : nodeVoice.confidence_threshold) != null ? _o : typeof (surfaceConfig == null ? void 0 : surfaceConfig.confidence_threshold) === "number" ? surfaceConfig.confidence_threshold : 0.7,
6759
7013
  enqueueSpeak,
6760
7014
  isSpeaking,
6761
7015
  disabled: submitting
@@ -6797,7 +7051,7 @@ var ChatAdapter = forwardRef(
6797
7051
  activeSession && field && InputComponent && /* @__PURE__ */ jsxs("form", { ref: inputAreaRef, className: widget_default.activeInputArea, onSubmit: handleSubmit, children: [
6798
7052
  isConverseSession && /* @__PURE__ */ jsxs("div", { className: widget_default.converseHint, children: [
6799
7053
  /* @__PURE__ */ jsx("span", { className: widget_default.converseHintDot }),
6800
- "Collecting your answers\u2026"
7054
+ converseRuntime === "live" ? "Live conversation in progress\u2026" : "Collecting your answers\u2026"
6801
7055
  ] }),
6802
7056
  field.prompt && /* @__PURE__ */ jsx("div", { className: widget_default.activeInputPrompt, children: field.prompt }),
6803
7057
  /* @__PURE__ */ jsxs("div", { className: widget_default.activeInputRow, children: [