@chatterfly/widget 0.2.0 → 0.4.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
@@ -13,11 +13,68 @@ var WidgetError = class {
13
13
  return this.message;
14
14
  }
15
15
  };
16
- var RECONNECT_DELAY_MS = 2e3;
16
+
17
+ // src/strings.ts
18
+ var defaultStrings = {
19
+ statusInitialising: "Initialising\u2026",
20
+ statusConnecting: "Connecting\u2026",
21
+ statusRunning: "Running\u2026",
22
+ statusCompletedTitle: "Completed",
23
+ statusCompletedBody: "This workflow run has finished.",
24
+ statusErrorTitle: "Something went wrong",
25
+ statusOfflineTitle: "Connection lost",
26
+ statusOfflineBody: "Unable to reach the server. Please check your connection and refresh.",
27
+ statusExpiredTitle: "Session expired",
28
+ statusExpiredBody: "This conversation's session has expired. Start a new one to continue.",
29
+ statusListening: "Listening\u2026",
30
+ resumingConversation: "Resuming conversation\u2026",
31
+ reconnecting: "Reconnecting\u2026",
32
+ conversationCompleted: "Conversation completed.",
33
+ somethingWentWrong: "Something went wrong",
34
+ chatInputPlaceholder: "Type a message\u2026",
35
+ sendButton: "Send",
36
+ handBackButton: "Hand Back",
37
+ converseDoneButton: "I'm done",
38
+ startConversation: "Start conversation",
39
+ clickToStartDescription: "Click below to begin.",
40
+ resumeTitle: "Continue where you left off?",
41
+ resumeContinue: "Continue",
42
+ resumeRestart: "Start fresh",
43
+ startNewConversation: "Start new conversation",
44
+ conversationEnded: "This conversation has ended."
45
+ };
46
+ function resolveStrings(overrides) {
47
+ return overrides ? { ...defaultStrings, ...overrides } : defaultStrings;
48
+ }
49
+ var RECONNECT_BASE_DELAY_MS = 2e3;
50
+ var RECONNECT_MAX_DELAY_MS = 3e4;
17
51
  var MAX_RECONNECT_ATTEMPTS = 5;
18
- var TERMINAL_STATUSES = ["completed", "error", "offline"];
52
+ var TERMINAL_STATUSES = ["completed", "error", "offline", "expired"];
53
+ var PARKED_STATUSES = [
54
+ "awaiting_input",
55
+ "awaiting_voice",
56
+ "awaiting_form",
57
+ "awaiting_chat",
58
+ "awaiting_editor"
59
+ ];
60
+ var DEFAULT_IDLE_DISCONNECT_MS = 5 * 6e4;
61
+ var DEFAULT_POLL_INTERVAL_MS = 45e3;
62
+ var DEFAULT_HIBERNATE_AFTER_MS = 60 * 6e4;
63
+ function computeReconnectDelay(attempt) {
64
+ const cap = Math.min(
65
+ RECONNECT_MAX_DELAY_MS,
66
+ RECONNECT_BASE_DELAY_MS * 2 ** attempt
67
+ );
68
+ return Math.random() * cap;
69
+ }
19
70
  function useRunStream(config, onEvent) {
71
+ var _a, _b, _c;
20
72
  const { runId, participantToken, apiBase } = config;
73
+ const policyConfig = config.connectionPolicy;
74
+ const dormancyDisabled = policyConfig === "always-on";
75
+ const idleDisconnectMs = (_a = !dormancyDisabled && typeof policyConfig === "object" ? policyConfig == null ? void 0 : policyConfig.idleDisconnectMs : void 0) != null ? _a : DEFAULT_IDLE_DISCONNECT_MS;
76
+ const pollIntervalMs = (_b = !dormancyDisabled && typeof policyConfig === "object" ? policyConfig == null ? void 0 : policyConfig.pollIntervalMs : void 0) != null ? _b : DEFAULT_POLL_INTERVAL_MS;
77
+ const hibernateAfterMs = (_c = !dormancyDisabled && typeof policyConfig === "object" ? policyConfig == null ? void 0 : policyConfig.hibernateAfterMs : void 0) != null ? _c : DEFAULT_HIBERNATE_AFTER_MS;
21
78
  const [status, setStatus] = useState("idle");
22
79
  const [activeSession, setActiveSession] = useState(null);
23
80
  const [messages, setMessages] = useState([]);
@@ -26,11 +83,19 @@ function useRunStream(config, onEvent) {
26
83
  const [output, setOutput] = useState(null);
27
84
  const lastSeqRef = useRef(0);
28
85
  const [lastSeq, setLastSeq] = useState(0);
86
+ const [currentToken, setCurrentToken] = useState(participantToken);
87
+ const currentTokenRef = useRef(currentToken);
88
+ currentTokenRef.current = currentToken;
89
+ useEffect(() => setCurrentToken(participantToken), [participantToken]);
29
90
  const wsRef = useRef(null);
30
91
  const statusRef = useRef("idle");
31
92
  const reconnectTimerRef = useRef(null);
32
93
  const replayTimeoutRef = useRef(null);
33
94
  const mountedRef = useRef(true);
95
+ const connectionStateRef = useRef("active");
96
+ const idleTimerRef = useRef(null);
97
+ const hibernateTimerRef = useRef(null);
98
+ const pollTimerRef = useRef(null);
34
99
  const reconnectAttemptsRef = useRef(0);
35
100
  const manualDisconnectRef = useRef(false);
36
101
  const onEventRef = useRef(onEvent);
@@ -40,8 +105,8 @@ function useRunStream(config, onEvent) {
40
105
  setStatus(next);
41
106
  }, []);
42
107
  const authHeaders = useCallback(
43
- () => ({ Authorization: `Bearer ${participantToken}` }),
44
- [participantToken]
108
+ () => ({ Authorization: `Bearer ${currentTokenRef.current}` }),
109
+ []
45
110
  );
46
111
  const mergeTimeline = useCallback(
47
112
  (incoming) => {
@@ -63,9 +128,18 @@ function useRunStream(config, onEvent) {
63
128
  if (!mountedRef.current) return;
64
129
  if (!runId || !apiBase) return;
65
130
  manualDisconnectRef.current = false;
131
+ connectionStateRef.current = "active";
132
+ if (pollTimerRef.current) {
133
+ clearInterval(pollTimerRef.current);
134
+ pollTimerRef.current = null;
135
+ }
136
+ if (hibernateTimerRef.current) {
137
+ clearTimeout(hibernateTimerRef.current);
138
+ hibernateTimerRef.current = null;
139
+ }
66
140
  updateStatus("connecting");
67
141
  const wsUrl = apiBase.replace(/^http/, "ws") + `/api/participant/runs/${runId}/stream`;
68
- const params = new URLSearchParams({ token: participantToken });
142
+ const params = new URLSearchParams({ token: currentTokenRef.current });
69
143
  const ws = new WebSocket(`${wsUrl}?${params}`);
70
144
  wsRef.current = ws;
71
145
  ws.onopen = () => {
@@ -103,15 +177,128 @@ function useRunStream(config, onEvent) {
103
177
  if (isOffline) {
104
178
  updateStatus("offline");
105
179
  } else {
180
+ const attempt = reconnectAttemptsRef.current;
106
181
  reconnectAttemptsRef.current += 1;
107
- reconnectTimerRef.current = setTimeout(connect, RECONNECT_DELAY_MS);
182
+ reconnectTimerRef.current = setTimeout(
183
+ connect,
184
+ computeReconnectDelay(attempt)
185
+ );
108
186
  }
109
187
  }
110
188
  };
111
189
  }, [runId, participantToken, apiBase]);
190
+ const remintToken = useCallback(async () => {
191
+ try {
192
+ const res = await fetch(`${apiBase}/api/public/runs/${runId}/token`, {
193
+ method: "POST",
194
+ headers: { "Content-Type": "application/json" },
195
+ body: JSON.stringify({ participant_token: currentTokenRef.current })
196
+ });
197
+ if (!res.ok) return null;
198
+ const data = await res.json();
199
+ if (!data.participant_token) return null;
200
+ setCurrentToken(data.participant_token);
201
+ return data.participant_token;
202
+ } catch {
203
+ return null;
204
+ }
205
+ }, [apiBase, runId]);
206
+ const stopPolling = useCallback(() => {
207
+ if (pollTimerRef.current) {
208
+ clearInterval(pollTimerRef.current);
209
+ pollTimerRef.current = null;
210
+ }
211
+ if (hibernateTimerRef.current) {
212
+ clearTimeout(hibernateTimerRef.current);
213
+ hibernateTimerRef.current = null;
214
+ }
215
+ }, []);
216
+ const wake = useCallback(() => {
217
+ if (!mountedRef.current) return;
218
+ if (connectionStateRef.current === "active") return;
219
+ stopPolling();
220
+ reconnectAttemptsRef.current = 0;
221
+ connect();
222
+ }, [connect, stopPolling]);
223
+ const startPolling = useCallback(() => {
224
+ if (pollTimerRef.current) return;
225
+ pollTimerRef.current = setInterval(async () => {
226
+ if (!mountedRef.current) return;
227
+ try {
228
+ const res = await fetch(
229
+ `${apiBase}/api/participant/runs/${runId}/timeline?since_seq=${lastSeqRef.current}`,
230
+ { headers: { Authorization: `Bearer ${currentTokenRef.current}` } }
231
+ );
232
+ if (res.status === 401) {
233
+ const fresh = await remintToken();
234
+ if (!fresh) {
235
+ stopPolling();
236
+ updateStatus("expired");
237
+ }
238
+ return;
239
+ }
240
+ if (!res.ok) return;
241
+ const entries = await res.json();
242
+ if (Array.isArray(entries) && entries.length > 0) {
243
+ wake();
244
+ }
245
+ } catch {
246
+ }
247
+ }, pollIntervalMs);
248
+ hibernateTimerRef.current = setTimeout(() => {
249
+ connectionStateRef.current = "hibernating";
250
+ if (pollTimerRef.current) {
251
+ clearInterval(pollTimerRef.current);
252
+ pollTimerRef.current = null;
253
+ }
254
+ }, hibernateAfterMs);
255
+ }, [apiBase, runId, pollIntervalMs, hibernateAfterMs, remintToken, stopPolling, updateStatus, wake]);
256
+ const goDormant = useCallback(() => {
257
+ var _a2;
258
+ if (connectionStateRef.current !== "active") return;
259
+ connectionStateRef.current = "dormant";
260
+ manualDisconnectRef.current = true;
261
+ (_a2 = wsRef.current) == null ? void 0 : _a2.close();
262
+ wsRef.current = null;
263
+ startPolling();
264
+ }, [startPolling]);
265
+ useEffect(() => {
266
+ if (dormancyDisabled) return;
267
+ if (idleTimerRef.current) {
268
+ clearTimeout(idleTimerRef.current);
269
+ idleTimerRef.current = null;
270
+ }
271
+ if (PARKED_STATUSES.includes(status) && connectionStateRef.current === "active") {
272
+ idleTimerRef.current = setTimeout(goDormant, idleDisconnectMs);
273
+ }
274
+ return () => {
275
+ if (idleTimerRef.current) {
276
+ clearTimeout(idleTimerRef.current);
277
+ idleTimerRef.current = null;
278
+ }
279
+ };
280
+ }, [status, dormancyDisabled, idleDisconnectMs, goDormant]);
281
+ useEffect(() => {
282
+ if (dormancyDisabled) return;
283
+ const handleVisibility = () => {
284
+ if (document.visibilityState === "visible") wake();
285
+ };
286
+ document.addEventListener("visibilitychange", handleVisibility);
287
+ window.addEventListener("online", wake);
288
+ window.addEventListener("focus", wake);
289
+ window.addEventListener("pointerdown", wake);
290
+ window.addEventListener("keydown", wake);
291
+ return () => {
292
+ document.removeEventListener("visibilitychange", handleVisibility);
293
+ window.removeEventListener("online", wake);
294
+ window.removeEventListener("focus", wake);
295
+ window.removeEventListener("pointerdown", wake);
296
+ window.removeEventListener("keydown", wake);
297
+ };
298
+ }, [dormancyDisabled, wake]);
112
299
  function handleEvent(event) {
113
- var _a, _b, _c, _d, _e;
114
- (_a = onEventRef.current) == null ? void 0 : _a.call(onEventRef, event);
300
+ var _a2, _b2, _c2, _d, _e;
301
+ (_a2 = onEventRef.current) == null ? void 0 : _a2.call(onEventRef, event);
115
302
  switch (event.type) {
116
303
  case "timeline.replay": {
117
304
  mergeTimeline(event.payload);
@@ -148,7 +335,7 @@ function useRunStream(config, onEvent) {
148
335
  entry_context: event.entry_context,
149
336
  status: "open",
150
337
  messages: replayedMessages,
151
- document_content: (_b = event.document_content) != null ? _b : null
338
+ document_content: (_b2 = event.document_content) != null ? _b2 : null
152
339
  };
153
340
  setActiveSession(session);
154
341
  if (replayedMessages.length > 0) {
@@ -161,7 +348,7 @@ function useRunStream(config, onEvent) {
161
348
  } else if (event.layout === "form") {
162
349
  updateStatus("awaiting_form");
163
350
  } else {
164
- const surface = (_c = event.entry_context) == null ? void 0 : _c.surface;
351
+ const surface = (_c2 = event.entry_context) == null ? void 0 : _c2.surface;
165
352
  const isVoice = typeof surface === "string" && (surface === "widget/voice" || surface === "phone" || surface === "phone/outbound");
166
353
  if (isVoice) {
167
354
  updateStatus("awaiting_voice");
@@ -201,17 +388,21 @@ function useRunStream(config, onEvent) {
201
388
  mountedRef.current = true;
202
389
  reconnectTimerRef.current = setTimeout(connect, 0);
203
390
  return () => {
204
- var _a;
391
+ var _a2;
205
392
  mountedRef.current = false;
206
393
  if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
207
394
  if (replayTimeoutRef.current) clearTimeout(replayTimeoutRef.current);
208
- (_a = wsRef.current) == null ? void 0 : _a.close();
395
+ if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
396
+ if (pollTimerRef.current) clearInterval(pollTimerRef.current);
397
+ if (hibernateTimerRef.current) clearTimeout(hibernateTimerRef.current);
398
+ (_a2 = wsRef.current) == null ? void 0 : _a2.close();
209
399
  wsRef.current = null;
210
400
  };
211
401
  }, [connect]);
212
402
  const sendMessage = useCallback(
213
403
  async (content) => {
214
404
  if (!activeSession) return;
405
+ wake();
215
406
  setMessages((prev) => [
216
407
  ...prev,
217
408
  { role: "human", content }
@@ -238,12 +429,13 @@ function useRunStream(config, onEvent) {
238
429
  throw new Error(`sendMessage failed: ${res.status} ${text}`);
239
430
  }
240
431
  },
241
- [activeSession, apiBase, authHeaders, updateStatus]
432
+ [activeSession, apiBase, authHeaders, updateStatus, wake]
242
433
  );
243
434
  const submitHandback = useCallback(
244
435
  async (output2, idempotencyKey) => {
245
- var _a;
436
+ var _a2;
246
437
  if (!activeSession) return null;
438
+ wake();
247
439
  const body = { output: output2 };
248
440
  if (idempotencyKey) body.idempotency_key = idempotencyKey;
249
441
  let res;
@@ -265,7 +457,7 @@ function useRunStream(config, onEvent) {
265
457
  }
266
458
  if (res.status === 422) {
267
459
  const data = await res.json();
268
- return (_a = data.errors) != null ? _a : [{ field: "_", message: "Validation failed" }];
460
+ return (_a2 = data.errors) != null ? _a2 : [{ field: "_", message: "Validation failed" }];
269
461
  }
270
462
  if (!res.ok) {
271
463
  const text = await res.text();
@@ -276,13 +468,13 @@ function useRunStream(config, onEvent) {
276
468
  updateStatus("running");
277
469
  return null;
278
470
  },
279
- [activeSession, apiBase, authHeaders, updateStatus]
471
+ [activeSession, apiBase, authHeaders, updateStatus, wake]
280
472
  );
281
473
  const disconnect = useCallback(() => {
282
- var _a;
474
+ var _a2;
283
475
  manualDisconnectRef.current = true;
284
476
  if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
285
- (_a = wsRef.current) == null ? void 0 : _a.close();
477
+ (_a2 = wsRef.current) == null ? void 0 : _a2.close();
286
478
  wsRef.current = null;
287
479
  updateStatus("offline");
288
480
  }, [updateStatus]);
@@ -490,15 +682,24 @@ var widget_default = {
490
682
  converseHint: "widget_converseHint",
491
683
  converseHintDot: "widget_converseHintDot",
492
684
  "cf-converse-pulse": "widget_cf-converse-pulse",
685
+ converseDoneButton: "widget_converseDoneButton",
493
686
  newMessageChip: "widget_newMessageChip",
494
687
  activeInputRow: "widget_activeInputRow",
495
688
  activeInputField: "widget_activeInputField",
496
689
  activeInputSubmit: "widget_activeInputSubmit",
497
690
  inlineError: "widget_inlineError",
498
691
  resumingBanner: "widget_resumingBanner",
692
+ reconnectingPill: "widget_reconnectingPill",
499
693
  terminalBanner: "widget_terminalBanner",
500
694
  terminalCompleted: "widget_terminalBanner widget_terminalCompleted",
501
695
  terminalError: "widget_terminalBanner widget_terminalError",
696
+ startNewConversationButton: "widget_startNewConversationButton",
697
+ gateCard: "widget_gateCard",
698
+ gateTitle: "widget_gateTitle",
699
+ gateDescription: "widget_gateDescription",
700
+ gateActions: "widget_gateActions",
701
+ gateButtonPrimary: "widget_gateButtonPrimary",
702
+ gateButtonSecondary: "widget_gateButtonSecondary",
502
703
  typingIndicator: "widget_typingIndicator",
503
704
  typingDot: "widget_typingDot",
504
705
  cfTyping: "widget_cfTyping",
@@ -2667,28 +2868,6 @@ function FormRenderer({
2667
2868
  ) })
2668
2869
  ] });
2669
2870
  }
2670
-
2671
- // src/strings.ts
2672
- var defaultStrings = {
2673
- statusInitialising: "Initialising\u2026",
2674
- statusConnecting: "Connecting\u2026",
2675
- statusRunning: "Running\u2026",
2676
- statusCompletedTitle: "Completed",
2677
- statusCompletedBody: "This workflow run has finished.",
2678
- statusErrorTitle: "Something went wrong",
2679
- statusOfflineTitle: "Connection lost",
2680
- statusOfflineBody: "Unable to reach the server. Please check your connection and refresh.",
2681
- statusListening: "Listening\u2026",
2682
- resumingConversation: "Resuming conversation\u2026",
2683
- conversationCompleted: "Conversation completed.",
2684
- somethingWentWrong: "Something went wrong",
2685
- chatInputPlaceholder: "Type a message\u2026",
2686
- sendButton: "Send",
2687
- handBackButton: "Hand Back"
2688
- };
2689
- function resolveStrings(overrides) {
2690
- return overrides ? { ...defaultStrings, ...overrides } : defaultStrings;
2691
- }
2692
2871
  function StatusDisplay({ status, error, strings }) {
2693
2872
  const t = strings ? { ...defaultStrings, ...strings } : defaultStrings;
2694
2873
  switch (status) {
@@ -2718,6 +2897,11 @@ function StatusDisplay({ status, error, strings }) {
2718
2897
  /* @__PURE__ */ jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: t.statusOfflineTitle }),
2719
2898
  /* @__PURE__ */ jsx("div", { className: `${widget_default.statusLabel} ${widget_default.statusError}`, children: t.statusOfflineBody })
2720
2899
  ] });
2900
+ case "expired":
2901
+ return /* @__PURE__ */ jsxs("div", { className: widget_default.statusWrapper, children: [
2902
+ /* @__PURE__ */ jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: t.statusExpiredTitle }),
2903
+ /* @__PURE__ */ jsx("div", { className: `${widget_default.statusLabel} ${widget_default.statusError}`, children: t.statusExpiredBody })
2904
+ ] });
2721
2905
  case "awaiting_voice":
2722
2906
  return /* @__PURE__ */ jsxs("div", { className: widget_default.statusWrapper, children: [
2723
2907
  /* @__PURE__ */ jsx("div", { className: widget_default.spinner, "aria-hidden": true }),
@@ -5815,6 +5999,7 @@ var ChatAdapter = forwardRef(
5815
5999
  runId,
5816
6000
  participantToken,
5817
6001
  apiBase,
6002
+ connectionPolicy,
5818
6003
  className,
5819
6004
  onCompleted,
5820
6005
  onError,
@@ -5834,7 +6019,7 @@ var ChatAdapter = forwardRef(
5834
6019
  components,
5835
6020
  strings
5836
6021
  }, ref) {
5837
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
6022
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
5838
6023
  const t = resolveStrings(strings);
5839
6024
  const apiBaseResolved = apiBase;
5840
6025
  const appBaseResolved = typeof window !== "undefined" ? window.location.origin : (_a = process.env.APP_URL) != null ? _a : "http://localhost:3000";
@@ -5870,7 +6055,7 @@ var ChatAdapter = forwardRef(
5870
6055
  output,
5871
6056
  disconnect,
5872
6057
  reconnect
5873
- } = useRunStream({ runId, participantToken, apiBase }, onEventFirehose);
6058
+ } = useRunStream({ runId, participantToken, apiBase, connectionPolicy }, onEventFirehose);
5874
6059
  useImperativeHandle(
5875
6060
  ref,
5876
6061
  () => ({
@@ -5992,6 +6177,7 @@ var ChatAdapter = forwardRef(
5992
6177
  }, [timeline, isVoiceSurface, enqueueSpeak]);
5993
6178
  const completedFiredRef = useRef(false);
5994
6179
  const errorFiredRef = useRef(false);
6180
+ const expiredFiredRef = useRef(false);
5995
6181
  const inputAreaRef = useRef(null);
5996
6182
  const lastFocusedSessionRef = useRef(null);
5997
6183
  const activeSessionId = (_c = activeSession == null ? void 0 : activeSession.id) != null ? _c : null;
@@ -6018,6 +6204,12 @@ var ChatAdapter = forwardRef(
6018
6204
  errorFiredRef.current = true;
6019
6205
  onError == null ? void 0 : onError(new WidgetError("run_failed", "The run encountered an error."));
6020
6206
  }
6207
+ if (status === "expired" && !expiredFiredRef.current) {
6208
+ expiredFiredRef.current = true;
6209
+ onError == null ? void 0 : onError(
6210
+ new WidgetError("token_expired", "The participant token expired and could not be renewed.")
6211
+ );
6212
+ }
6021
6213
  }, [status, output, onCompleted, onError]);
6022
6214
  const colorSchemeClass = colorScheme === "dark" ? widget_default.cfDark : colorScheme === "auto" ? widget_default.cfAuto : void 0;
6023
6215
  const cls = [widget_default.widget, colorSchemeClass, className].filter(Boolean).join(" ");
@@ -6064,10 +6256,11 @@ var ChatAdapter = forwardRef(
6064
6256
  },
6065
6257
  [handleSubmit]
6066
6258
  );
6067
- if (status === "idle" || status === "connecting") {
6259
+ const isSilentReconnect = (status === "connecting" || status === "replaying") && timeline.length > 0;
6260
+ if (status === "idle" || status === "connecting" && !isSilentReconnect) {
6068
6261
  return /* @__PURE__ */ jsx("div", { className: cls, style: rootStyle, children: loadingFallback != null ? loadingFallback : /* @__PURE__ */ jsx(StatusDisplay, { status, strings }) });
6069
6262
  }
6070
- if (status === "replaying") {
6263
+ if (status === "replaying" && !isSilentReconnect) {
6071
6264
  return /* @__PURE__ */ jsxs("div", { className: cls, style: rootStyle, children: [
6072
6265
  header,
6073
6266
  /* @__PURE__ */ jsxs("div", { className: widget_default.resumingBanner, children: [
@@ -6126,7 +6319,11 @@ var ChatAdapter = forwardRef(
6126
6319
  }
6127
6320
  ) });
6128
6321
  }
6129
- if (status === "awaiting_chat" && activeSession) {
6322
+ const converseCtx = activeSession == null ? void 0 : activeSession.entry_context;
6323
+ const isConverseSession = (converseCtx == null ? void 0 : converseCtx.converse_session) === true;
6324
+ const converseUserCanEnd = (converseCtx == null ? void 0 : converseCtx.converse_user_can_end) === true;
6325
+ const field = activeSession ? extractField(activeSession) : null;
6326
+ if (status === "awaiting_chat" && activeSession && !(isConverseSession && field)) {
6130
6327
  const hbCtx = (_e = activeSession.entry_context) == null ? void 0 : _e.handback;
6131
6328
  const outputSchema = hbCtx == null ? void 0 : hbCtx.output_schema;
6132
6329
  const requireOutput = (_f = hbCtx == null ? void 0 : hbCtx.require_output) != null ? _f : false;
@@ -6222,18 +6419,16 @@ var ChatAdapter = forwardRef(
6222
6419
  ] })
6223
6420
  ] });
6224
6421
  }
6225
- const field = activeSession ? extractField(activeSession) : null;
6226
6422
  const surface = activeSession ? extractSurface(activeSession) : null;
6227
6423
  const surfaceConfig = activeSession ? extractSurfaceConfig(activeSession) : null;
6228
6424
  const nodeVoice = activeSession ? extractNodeVoice(activeSession) : null;
6229
6425
  const InputComponent = field ? getInputComponent(field.input_type) : null;
6230
- const isConverseSession = ((_g = activeSession == null ? void 0 : activeSession.entry_context) == null ? void 0 : _g.converse_session) === true;
6231
6426
  const effectiveVoiceMode = resolveVoiceMode(surface, surfaceConfig, nodeVoice);
6232
6427
  const shouldUseVoice = effectiveVoiceMode !== "off";
6233
6428
  const voiceRenderer = effectiveVoiceMode === "push_to_talk" ? "click" : "continuous";
6234
6429
  const isLiveVoice = surface === "widget/voice" && (surfaceConfig == null ? void 0 : surfaceConfig.style) === "live";
6235
6430
  if (shouldUseVoice && activeSession && field) {
6236
- const spokenHint = (_i = nodeVoice == null ? void 0 : nodeVoice.hint) != null ? _i : (_h = field.voice) == null ? void 0 : _h.hint;
6431
+ const spokenHint = (_h = nodeVoice == null ? void 0 : nodeVoice.hint) != null ? _h : (_g = field.voice) == null ? void 0 : _g.hint;
6237
6432
  const handleVoiceValue = (value) => {
6238
6433
  setInputValue(value);
6239
6434
  void submitHandback(value, crypto.randomUUID());
@@ -6265,7 +6460,7 @@ var ChatAdapter = forwardRef(
6265
6460
  participantToken,
6266
6461
  onValue: handleVoiceValue,
6267
6462
  autoSubmitMode: "confirm",
6268
- confidenceThreshold: (_j = nodeVoice == null ? void 0 : nodeVoice.confidence_threshold) != null ? _j : typeof (surfaceConfig == null ? void 0 : surfaceConfig.confidence_threshold) === "number" ? surfaceConfig.confidence_threshold : 0.7,
6463
+ 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,
6269
6464
  enqueueSpeak,
6270
6465
  isSpeaking,
6271
6466
  disabled: submitting
@@ -6298,6 +6493,10 @@ var ChatAdapter = forwardRef(
6298
6493
  ) });
6299
6494
  }
6300
6495
  return /* @__PURE__ */ jsxs("div", { className: cls, style: rootStyle, children: [
6496
+ isSilentReconnect && /* @__PURE__ */ jsxs("div", { className: widget_default.reconnectingPill, children: [
6497
+ /* @__PURE__ */ jsx("span", { className: widget_default.spinner }),
6498
+ t.reconnecting
6499
+ ] }),
6301
6500
  header,
6302
6501
  /* @__PURE__ */ jsx(ChatTimeline, { entries: timeline, showTyping, streamingText, components }),
6303
6502
  activeSession && field && InputComponent && /* @__PURE__ */ jsxs("form", { ref: inputAreaRef, className: widget_default.activeInputArea, onSubmit: handleSubmit, children: [
@@ -6340,7 +6539,17 @@ var ChatAdapter = forwardRef(
6340
6539
  serverErrors.length > 1 && serverErrors.slice(1).map((e, i) => /* @__PURE__ */ jsxs("div", { className: widget_default.inlineError, children: [
6341
6540
  e.field !== "_" ? `${e.field}: ` : "",
6342
6541
  e.message
6343
- ] }, i))
6542
+ ] }, i)),
6543
+ isConverseSession && converseUserCanEnd && /* @__PURE__ */ jsx(
6544
+ "button",
6545
+ {
6546
+ type: "button",
6547
+ className: widget_default.converseDoneButton,
6548
+ onClick: () => void submitHandback({ _done: true }),
6549
+ disabled: submitting,
6550
+ children: t.converseDoneButton
6551
+ }
6552
+ )
6344
6553
  ] }),
6345
6554
  !activeSession && status === "running" && timeline.length === 0 && (emptyState != null ? emptyState : /* @__PURE__ */ jsx(StatusDisplay, { status: "running", strings })),
6346
6555
  footer
@@ -6485,15 +6694,44 @@ function clearPersistedSession(config, target) {
6485
6694
  } catch {
6486
6695
  }
6487
6696
  }
6697
+ async function fetchPersistedRunTerminalStatus(apiBase, runId, participantToken) {
6698
+ var _a;
6699
+ try {
6700
+ const res = await fetch(`${apiBase}/api/participant/runs/${runId}/timeline`, {
6701
+ headers: { Authorization: `Bearer ${participantToken}` }
6702
+ });
6703
+ if (!res.ok) return null;
6704
+ const entries = await res.json();
6705
+ if (!Array.isArray(entries)) return null;
6706
+ for (let i = entries.length - 1; i >= 0; i--) {
6707
+ const e = entries[i];
6708
+ if (e.event_type === "status_change") {
6709
+ const s = (_a = e.payload) == null ? void 0 : _a.status;
6710
+ if (s === "completed" || s === "failed") return s;
6711
+ }
6712
+ }
6713
+ return null;
6714
+ } catch {
6715
+ return null;
6716
+ }
6717
+ }
6488
6718
  var ChatterflyWidget = forwardRef(
6489
6719
  function ChatterflyWidget2(props, ref) {
6490
- var _a, _b, _c, _d, _e, _f, _g, _h;
6720
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
6491
6721
  const [resolved, setResolved] = useState(null);
6492
6722
  const [configError, setConfigError] = useState(null);
6493
6723
  const [restartNonce, setRestartNonce] = useState(0);
6494
6724
  const adapterRef = useRef(null);
6495
6725
  const autoStarting = Boolean(!props.runId && (props.deploymentId || props.workflowId));
6496
6726
  const persistTarget = (_a = props.workflowId) != null ? _a : props.deploymentId;
6727
+ const effectivePersistSession = props.persistSession === void 0 ? true : props.persistSession;
6728
+ const showCompletedHistory = (_b = props.showCompletedHistory) != null ? _b : true;
6729
+ const t = { ...defaultStrings, ...props.strings };
6730
+ const [gate, setGate] = useState("idle");
6731
+ const [terminalReplayActive, setTerminalReplayActive] = useState(false);
6732
+ const pendingPersistedRef = useRef(null);
6733
+ const startNewRunRef = useRef(() => {
6734
+ });
6497
6735
  useEffect(() => {
6498
6736
  var _a2;
6499
6737
  if (props.runId) return;
@@ -6508,52 +6746,109 @@ var ChatterflyWidget = forwardRef(
6508
6746
  return;
6509
6747
  }
6510
6748
  setConfigError(null);
6511
- if (restartNonce === 0) {
6512
- const persisted = loadPersistedSession(props.persistSession, persistTarget);
6513
- if (persisted) {
6514
- setResolved({ runId: persisted.runId, participantToken: persisted.participantToken });
6515
- return;
6749
+ const base = props.apiBase;
6750
+ const doStart = (input) => {
6751
+ const startUrl = props.workflowId ? `${base}/api/public/workflows/${props.workflowId}/start` : `${base}/api/public/surveys/${props.deploymentId}/start`;
6752
+ const body = input ? JSON.stringify({ input }) : void 0;
6753
+ fetch(startUrl, {
6754
+ method: "POST",
6755
+ headers: body ? { "Content-Type": "application/json" } : void 0,
6756
+ body
6757
+ }).then(async (r) => {
6758
+ if (!r.ok) {
6759
+ const code = r.status === 404 ? "no_live_deployment" : "workflow_not_public";
6760
+ const detail = await r.text().catch(() => "");
6761
+ throw new WidgetError(
6762
+ code,
6763
+ `Failed to start run (HTTP ${r.status})${detail ? `: ${detail}` : ""}`
6764
+ );
6765
+ }
6766
+ return r.json();
6767
+ }).then(({ run_id, participant_token }) => {
6768
+ setGate("idle");
6769
+ setTerminalReplayActive(false);
6770
+ setResolved({ runId: run_id, participantToken: participant_token });
6771
+ savePersistedSession(effectivePersistSession, persistTarget, {
6772
+ runId: run_id,
6773
+ participantToken: participant_token
6774
+ });
6775
+ }).catch((err) => {
6776
+ var _a3;
6777
+ const widgetErr = err instanceof WidgetError ? err : new WidgetError("network", err instanceof Error ? err.message : String(err));
6778
+ (_a3 = props.onError) == null ? void 0 : _a3.call(props, widgetErr);
6779
+ });
6780
+ };
6781
+ startNewRunRef.current = doStart;
6782
+ if (restartNonce > 0) {
6783
+ doStart(props.initialInput);
6784
+ return;
6785
+ }
6786
+ const persisted = loadPersistedSession(effectivePersistSession, persistTarget);
6787
+ if (!persisted) {
6788
+ if (props.clickToStart) {
6789
+ setGate("click-to-start");
6790
+ } else {
6791
+ doStart(props.initialInput);
6516
6792
  }
6793
+ return;
6517
6794
  }
6518
- const base = props.apiBase;
6519
- const startUrl = props.workflowId ? `${base}/api/public/workflows/${props.workflowId}/start` : `${base}/api/public/surveys/${props.deploymentId}/start`;
6520
- const body = props.initialInput ? JSON.stringify({ input: props.initialInput }) : void 0;
6521
- fetch(startUrl, {
6522
- method: "POST",
6523
- headers: body ? { "Content-Type": "application/json" } : void 0,
6524
- body
6525
- }).then(async (r) => {
6526
- if (!r.ok) {
6527
- const code = r.status === 404 ? "no_live_deployment" : "workflow_not_public";
6528
- const detail = await r.text().catch(() => "");
6529
- throw new WidgetError(
6530
- code,
6531
- `Failed to start run (HTTP ${r.status})${detail ? `: ${detail}` : ""}`
6532
- );
6795
+ let cancelled = false;
6796
+ fetchPersistedRunTerminalStatus(base, persisted.runId, persisted.participantToken).then(
6797
+ (terminal) => {
6798
+ if (cancelled) return;
6799
+ if (terminal) {
6800
+ if (showCompletedHistory) {
6801
+ setTerminalReplayActive(true);
6802
+ setGate("idle");
6803
+ setResolved(persisted);
6804
+ } else {
6805
+ clearPersistedSession(effectivePersistSession, persistTarget);
6806
+ doStart(props.initialInput);
6807
+ }
6808
+ } else if (props.resumePrompt) {
6809
+ pendingPersistedRef.current = persisted;
6810
+ setGate("resume-choice");
6811
+ } else {
6812
+ setResolved(persisted);
6813
+ }
6533
6814
  }
6534
- return r.json();
6535
- }).then(({ run_id, participant_token }) => {
6536
- setResolved({ runId: run_id, participantToken: participant_token });
6537
- savePersistedSession(props.persistSession, persistTarget, {
6538
- runId: run_id,
6539
- participantToken: participant_token
6540
- });
6541
- }).catch((err) => {
6542
- var _a3;
6543
- const widgetErr = err instanceof WidgetError ? err : new WidgetError("network", err instanceof Error ? err.message : String(err));
6544
- (_a3 = props.onError) == null ? void 0 : _a3.call(props, widgetErr);
6545
- });
6815
+ );
6816
+ return () => {
6817
+ cancelled = true;
6818
+ };
6546
6819
  }, [props.deploymentId, props.workflowId, props.apiBase, restartNonce]);
6547
6820
  const restart = useCallback(() => {
6548
6821
  var _a2;
6549
6822
  if (autoStarting) {
6550
- clearPersistedSession(props.persistSession, persistTarget);
6823
+ clearPersistedSession(effectivePersistSession, persistTarget);
6551
6824
  setResolved(null);
6825
+ setTerminalReplayActive(false);
6826
+ setGate("idle");
6552
6827
  setRestartNonce((n) => n + 1);
6553
6828
  } else {
6554
6829
  (_a2 = adapterRef.current) == null ? void 0 : _a2.restart();
6555
6830
  }
6556
- }, [autoStarting, props.persistSession, persistTarget]);
6831
+ }, [autoStarting, effectivePersistSession, persistTarget]);
6832
+ const handleClickToStart = useCallback(() => {
6833
+ startNewRunRef.current(props.initialInput);
6834
+ }, [props.initialInput]);
6835
+ const handleResumeContinue = useCallback(() => {
6836
+ if (pendingPersistedRef.current) {
6837
+ setResolved(pendingPersistedRef.current);
6838
+ setGate("idle");
6839
+ }
6840
+ }, []);
6841
+ const handleResumeRestart = useCallback(() => {
6842
+ clearPersistedSession(effectivePersistSession, persistTarget);
6843
+ setGate("idle");
6844
+ startNewRunRef.current(props.initialInput);
6845
+ }, [effectivePersistSession, persistTarget, props.initialInput]);
6846
+ const handleStartNewFromReplay = useCallback(() => {
6847
+ clearPersistedSession(effectivePersistSession, persistTarget);
6848
+ setTerminalReplayActive(false);
6849
+ setResolved(null);
6850
+ startNewRunRef.current(props.initialInput);
6851
+ }, [effectivePersistSession, persistTarget, props.initialInput]);
6557
6852
  const disconnect = useCallback(() => {
6558
6853
  var _a2;
6559
6854
  (_a2 = adapterRef.current) == null ? void 0 : _a2.disconnect();
@@ -6567,10 +6862,10 @@ var ChatterflyWidget = forwardRef(
6567
6862
  disconnect,
6568
6863
  sendMessage
6569
6864
  ]);
6570
- const runId = (_b = resolved == null ? void 0 : resolved.runId) != null ? _b : props.runId;
6571
- const participantToken = (_c = resolved == null ? void 0 : resolved.participantToken) != null ? _c : props.participantToken;
6572
- const mode = (_d = props.mode) != null ? _d : "inline";
6573
- const [open, setOpen] = useState((_e = props.defaultOpen) != null ? _e : false);
6865
+ const runId = (_c = resolved == null ? void 0 : resolved.runId) != null ? _c : props.runId;
6866
+ const participantToken = (_d = resolved == null ? void 0 : resolved.participantToken) != null ? _d : props.participantToken;
6867
+ const mode = (_e = props.mode) != null ? _e : "inline";
6868
+ const [open, setOpen] = useState((_f = props.defaultOpen) != null ? _f : false);
6574
6869
  const [unreadCount, setUnreadCount] = useState(0);
6575
6870
  const toggleOpen = useCallback(() => {
6576
6871
  setOpen((prev) => {
@@ -6592,10 +6887,62 @@ var ChatterflyWidget = forwardRef(
6592
6887
  );
6593
6888
  let content;
6594
6889
  if (configError) {
6595
- content = (_f = props.loadingFallback) != null ? _f : /* @__PURE__ */ jsx(StatusDisplay, { status: "error" });
6890
+ content = (_g = props.loadingFallback) != null ? _g : /* @__PURE__ */ jsx(StatusDisplay, { status: "error" });
6891
+ } else if (gate === "click-to-start") {
6892
+ const cfg = typeof props.clickToStart === "object" ? props.clickToStart : void 0;
6893
+ content = /* @__PURE__ */ jsxs("div", { className: widget_default.gateCard, children: [
6894
+ /* @__PURE__ */ jsx("div", { className: widget_default.gateTitle, children: (_h = cfg == null ? void 0 : cfg.label) != null ? _h : t.startConversation }),
6895
+ /* @__PURE__ */ jsx("div", { className: widget_default.gateDescription, children: (_i = cfg == null ? void 0 : cfg.description) != null ? _i : t.clickToStartDescription }),
6896
+ /* @__PURE__ */ jsx("div", { className: widget_default.gateActions, children: /* @__PURE__ */ jsx(
6897
+ "button",
6898
+ {
6899
+ type: "button",
6900
+ className: widget_default.gateButtonPrimary,
6901
+ onClick: handleClickToStart,
6902
+ children: (_j = cfg == null ? void 0 : cfg.label) != null ? _j : t.startConversation
6903
+ }
6904
+ ) })
6905
+ ] });
6906
+ } else if (gate === "resume-choice") {
6907
+ const cfg = typeof props.resumePrompt === "object" ? props.resumePrompt : void 0;
6908
+ content = /* @__PURE__ */ jsxs("div", { className: widget_default.gateCard, children: [
6909
+ /* @__PURE__ */ jsx("div", { className: widget_default.gateTitle, children: (_k = cfg == null ? void 0 : cfg.title) != null ? _k : t.resumeTitle }),
6910
+ /* @__PURE__ */ jsxs("div", { className: widget_default.gateActions, children: [
6911
+ /* @__PURE__ */ jsx(
6912
+ "button",
6913
+ {
6914
+ type: "button",
6915
+ className: widget_default.gateButtonPrimary,
6916
+ onClick: handleResumeContinue,
6917
+ children: (_l = cfg == null ? void 0 : cfg.continueLabel) != null ? _l : t.resumeContinue
6918
+ }
6919
+ ),
6920
+ /* @__PURE__ */ jsx(
6921
+ "button",
6922
+ {
6923
+ type: "button",
6924
+ className: widget_default.gateButtonSecondary,
6925
+ onClick: handleResumeRestart,
6926
+ children: (_m = cfg == null ? void 0 : cfg.restartLabel) != null ? _m : t.resumeRestart
6927
+ }
6928
+ )
6929
+ ] })
6930
+ ] });
6596
6931
  } else if (!runId || !participantToken) {
6597
- content = (_g = props.loadingFallback) != null ? _g : /* @__PURE__ */ jsx(StatusDisplay, { status: autoStarting ? "connecting" : "error" });
6932
+ content = (_n = props.loadingFallback) != null ? _n : /* @__PURE__ */ jsx(StatusDisplay, { status: autoStarting ? "connecting" : "error" });
6598
6933
  } else {
6934
+ const replayCompletedState = terminalReplayActive ? /* @__PURE__ */ jsxs(Fragment, { children: [
6935
+ t.conversationEnded,
6936
+ /* @__PURE__ */ jsx(
6937
+ "button",
6938
+ {
6939
+ type: "button",
6940
+ className: widget_default.startNewConversationButton,
6941
+ onClick: handleStartNewFromReplay,
6942
+ children: t.startNewConversation
6943
+ }
6944
+ )
6945
+ ] }) : void 0;
6599
6946
  content = /* @__PURE__ */ jsx(
6600
6947
  ChatAdapter,
6601
6948
  {
@@ -6603,14 +6950,16 @@ var ChatterflyWidget = forwardRef(
6603
6950
  ref: adapterRef,
6604
6951
  runId,
6605
6952
  participantToken,
6606
- onMessage: handleMessage
6953
+ onMessage: handleMessage,
6954
+ completedState: (_o = props.completedState) != null ? _o : replayCompletedState,
6955
+ errorState: (_p = props.errorState) != null ? _p : replayCompletedState
6607
6956
  }
6608
6957
  );
6609
6958
  }
6610
6959
  if (mode !== "floating") {
6611
6960
  return content;
6612
6961
  }
6613
- const position = (_h = props.position) != null ? _h : "bottom-right";
6962
+ const position = (_q = props.position) != null ? _q : "bottom-right";
6614
6963
  return /* @__PURE__ */ jsx(
6615
6964
  FloatingLauncherChrome,
6616
6965
  {
@@ -6668,7 +7017,8 @@ function FloatingLauncherChrome({
6668
7017
  }
6669
7018
  function useChatterflyRun(options) {
6670
7019
  var _a, _b;
6671
- const { runId, participantToken, apiBase, deploymentId, workflowId, initialInput, persistSession, onEvent } = options;
7020
+ const { runId, participantToken, apiBase, deploymentId, workflowId, initialInput, persistSession, connectionPolicy, onEvent } = options;
7021
+ const effectivePersistSession = persistSession === void 0 ? true : persistSession;
6672
7022
  const [resolved, setResolved] = useState(null);
6673
7023
  const [error, setError] = useState(null);
6674
7024
  const [restartNonce, setRestartNonce] = useState(0);
@@ -6687,7 +7037,7 @@ function useChatterflyRun(options) {
6687
7037
  }
6688
7038
  setError(null);
6689
7039
  if (restartNonce === 0) {
6690
- const persisted = loadPersistedSession(persistSession, persistTarget);
7040
+ const persisted = loadPersistedSession(effectivePersistSession, persistTarget);
6691
7041
  if (persisted) {
6692
7042
  setResolved({ runId: persisted.runId, participantToken: persisted.participantToken });
6693
7043
  return;
@@ -6711,7 +7061,7 @@ function useChatterflyRun(options) {
6711
7061
  return r.json();
6712
7062
  }).then(({ run_id, participant_token }) => {
6713
7063
  setResolved({ runId: run_id, participantToken: participant_token });
6714
- savePersistedSession(persistSession, persistTarget, {
7064
+ savePersistedSession(effectivePersistSession, persistTarget, {
6715
7065
  runId: run_id,
6716
7066
  participantToken: participant_token
6717
7067
  });
@@ -6727,19 +7077,29 @@ function useChatterflyRun(options) {
6727
7077
  {
6728
7078
  runId: effectiveRunId != null ? effectiveRunId : "",
6729
7079
  participantToken: effectiveToken != null ? effectiveToken : "",
6730
- apiBase: apiBase != null ? apiBase : ""
7080
+ apiBase: apiBase != null ? apiBase : "",
7081
+ connectionPolicy
6731
7082
  },
6732
7083
  onEvent
6733
7084
  );
6734
7085
  const restart = useCallback(() => {
6735
7086
  if (autoStarting) {
6736
- clearPersistedSession(persistSession, persistTarget);
7087
+ clearPersistedSession(effectivePersistSession, persistTarget);
6737
7088
  setResolved(null);
6738
7089
  setRestartNonce((n) => n + 1);
6739
7090
  } else {
6740
7091
  stream.reconnect();
6741
7092
  }
6742
- }, [autoStarting, persistSession, persistTarget, stream]);
7093
+ }, [autoStarting, effectivePersistSession, persistTarget, stream]);
7094
+ const expiredErrorFiredRef = useRef(false);
7095
+ useEffect(() => {
7096
+ if (stream.status === "expired" && !expiredErrorFiredRef.current) {
7097
+ expiredErrorFiredRef.current = true;
7098
+ setError(
7099
+ new WidgetError("token_expired", "The participant token expired and could not be renewed.")
7100
+ );
7101
+ }
7102
+ }, [stream.status]);
6743
7103
  const connecting = autoStarting && !resolved && !error;
6744
7104
  return {
6745
7105
  ...stream,