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