@chatterfly/widget 0.3.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]);
@@ -497,9 +689,17 @@ var widget_default = {
497
689
  activeInputSubmit: "widget_activeInputSubmit",
498
690
  inlineError: "widget_inlineError",
499
691
  resumingBanner: "widget_resumingBanner",
692
+ reconnectingPill: "widget_reconnectingPill",
500
693
  terminalBanner: "widget_terminalBanner",
501
694
  terminalCompleted: "widget_terminalBanner widget_terminalCompleted",
502
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",
503
703
  typingIndicator: "widget_typingIndicator",
504
704
  typingDot: "widget_typingDot",
505
705
  cfTyping: "widget_cfTyping",
@@ -2668,29 +2868,6 @@ function FormRenderer({
2668
2868
  ) })
2669
2869
  ] });
2670
2870
  }
2671
-
2672
- // src/strings.ts
2673
- var defaultStrings = {
2674
- statusInitialising: "Initialising\u2026",
2675
- statusConnecting: "Connecting\u2026",
2676
- statusRunning: "Running\u2026",
2677
- statusCompletedTitle: "Completed",
2678
- statusCompletedBody: "This workflow run has finished.",
2679
- statusErrorTitle: "Something went wrong",
2680
- statusOfflineTitle: "Connection lost",
2681
- statusOfflineBody: "Unable to reach the server. Please check your connection and refresh.",
2682
- statusListening: "Listening\u2026",
2683
- resumingConversation: "Resuming conversation\u2026",
2684
- conversationCompleted: "Conversation completed.",
2685
- somethingWentWrong: "Something went wrong",
2686
- chatInputPlaceholder: "Type a message\u2026",
2687
- sendButton: "Send",
2688
- handBackButton: "Hand Back",
2689
- converseDoneButton: "I'm done"
2690
- };
2691
- function resolveStrings(overrides) {
2692
- return overrides ? { ...defaultStrings, ...overrides } : defaultStrings;
2693
- }
2694
2871
  function StatusDisplay({ status, error, strings }) {
2695
2872
  const t = strings ? { ...defaultStrings, ...strings } : defaultStrings;
2696
2873
  switch (status) {
@@ -2720,6 +2897,11 @@ function StatusDisplay({ status, error, strings }) {
2720
2897
  /* @__PURE__ */ jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: t.statusOfflineTitle }),
2721
2898
  /* @__PURE__ */ jsx("div", { className: `${widget_default.statusLabel} ${widget_default.statusError}`, children: t.statusOfflineBody })
2722
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
+ ] });
2723
2905
  case "awaiting_voice":
2724
2906
  return /* @__PURE__ */ jsxs("div", { className: widget_default.statusWrapper, children: [
2725
2907
  /* @__PURE__ */ jsx("div", { className: widget_default.spinner, "aria-hidden": true }),
@@ -5817,6 +5999,7 @@ var ChatAdapter = forwardRef(
5817
5999
  runId,
5818
6000
  participantToken,
5819
6001
  apiBase,
6002
+ connectionPolicy,
5820
6003
  className,
5821
6004
  onCompleted,
5822
6005
  onError,
@@ -5872,7 +6055,7 @@ var ChatAdapter = forwardRef(
5872
6055
  output,
5873
6056
  disconnect,
5874
6057
  reconnect
5875
- } = useRunStream({ runId, participantToken, apiBase }, onEventFirehose);
6058
+ } = useRunStream({ runId, participantToken, apiBase, connectionPolicy }, onEventFirehose);
5876
6059
  useImperativeHandle(
5877
6060
  ref,
5878
6061
  () => ({
@@ -5994,6 +6177,7 @@ var ChatAdapter = forwardRef(
5994
6177
  }, [timeline, isVoiceSurface, enqueueSpeak]);
5995
6178
  const completedFiredRef = useRef(false);
5996
6179
  const errorFiredRef = useRef(false);
6180
+ const expiredFiredRef = useRef(false);
5997
6181
  const inputAreaRef = useRef(null);
5998
6182
  const lastFocusedSessionRef = useRef(null);
5999
6183
  const activeSessionId = (_c = activeSession == null ? void 0 : activeSession.id) != null ? _c : null;
@@ -6020,6 +6204,12 @@ var ChatAdapter = forwardRef(
6020
6204
  errorFiredRef.current = true;
6021
6205
  onError == null ? void 0 : onError(new WidgetError("run_failed", "The run encountered an error."));
6022
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
+ }
6023
6213
  }, [status, output, onCompleted, onError]);
6024
6214
  const colorSchemeClass = colorScheme === "dark" ? widget_default.cfDark : colorScheme === "auto" ? widget_default.cfAuto : void 0;
6025
6215
  const cls = [widget_default.widget, colorSchemeClass, className].filter(Boolean).join(" ");
@@ -6066,10 +6256,11 @@ var ChatAdapter = forwardRef(
6066
6256
  },
6067
6257
  [handleSubmit]
6068
6258
  );
6069
- if (status === "idle" || status === "connecting") {
6259
+ const isSilentReconnect = (status === "connecting" || status === "replaying") && timeline.length > 0;
6260
+ if (status === "idle" || status === "connecting" && !isSilentReconnect) {
6070
6261
  return /* @__PURE__ */ jsx("div", { className: cls, style: rootStyle, children: loadingFallback != null ? loadingFallback : /* @__PURE__ */ jsx(StatusDisplay, { status, strings }) });
6071
6262
  }
6072
- if (status === "replaying") {
6263
+ if (status === "replaying" && !isSilentReconnect) {
6073
6264
  return /* @__PURE__ */ jsxs("div", { className: cls, style: rootStyle, children: [
6074
6265
  header,
6075
6266
  /* @__PURE__ */ jsxs("div", { className: widget_default.resumingBanner, children: [
@@ -6302,6 +6493,10 @@ var ChatAdapter = forwardRef(
6302
6493
  ) });
6303
6494
  }
6304
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
+ ] }),
6305
6500
  header,
6306
6501
  /* @__PURE__ */ jsx(ChatTimeline, { entries: timeline, showTyping, streamingText, components }),
6307
6502
  activeSession && field && InputComponent && /* @__PURE__ */ jsxs("form", { ref: inputAreaRef, className: widget_default.activeInputArea, onSubmit: handleSubmit, children: [
@@ -6499,15 +6694,44 @@ function clearPersistedSession(config, target) {
6499
6694
  } catch {
6500
6695
  }
6501
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
+ }
6502
6718
  var ChatterflyWidget = forwardRef(
6503
6719
  function ChatterflyWidget2(props, ref) {
6504
- 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;
6505
6721
  const [resolved, setResolved] = useState(null);
6506
6722
  const [configError, setConfigError] = useState(null);
6507
6723
  const [restartNonce, setRestartNonce] = useState(0);
6508
6724
  const adapterRef = useRef(null);
6509
6725
  const autoStarting = Boolean(!props.runId && (props.deploymentId || props.workflowId));
6510
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
+ });
6511
6735
  useEffect(() => {
6512
6736
  var _a2;
6513
6737
  if (props.runId) return;
@@ -6522,52 +6746,109 @@ var ChatterflyWidget = forwardRef(
6522
6746
  return;
6523
6747
  }
6524
6748
  setConfigError(null);
6525
- if (restartNonce === 0) {
6526
- const persisted = loadPersistedSession(props.persistSession, persistTarget);
6527
- if (persisted) {
6528
- setResolved({ runId: persisted.runId, participantToken: persisted.participantToken });
6529
- 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);
6530
6792
  }
6793
+ return;
6531
6794
  }
6532
- const base = props.apiBase;
6533
- const startUrl = props.workflowId ? `${base}/api/public/workflows/${props.workflowId}/start` : `${base}/api/public/surveys/${props.deploymentId}/start`;
6534
- const body = props.initialInput ? JSON.stringify({ input: props.initialInput }) : void 0;
6535
- fetch(startUrl, {
6536
- method: "POST",
6537
- headers: body ? { "Content-Type": "application/json" } : void 0,
6538
- body
6539
- }).then(async (r) => {
6540
- if (!r.ok) {
6541
- const code = r.status === 404 ? "no_live_deployment" : "workflow_not_public";
6542
- const detail = await r.text().catch(() => "");
6543
- throw new WidgetError(
6544
- code,
6545
- `Failed to start run (HTTP ${r.status})${detail ? `: ${detail}` : ""}`
6546
- );
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
+ }
6547
6814
  }
6548
- return r.json();
6549
- }).then(({ run_id, participant_token }) => {
6550
- setResolved({ runId: run_id, participantToken: participant_token });
6551
- savePersistedSession(props.persistSession, persistTarget, {
6552
- runId: run_id,
6553
- participantToken: participant_token
6554
- });
6555
- }).catch((err) => {
6556
- var _a3;
6557
- const widgetErr = err instanceof WidgetError ? err : new WidgetError("network", err instanceof Error ? err.message : String(err));
6558
- (_a3 = props.onError) == null ? void 0 : _a3.call(props, widgetErr);
6559
- });
6815
+ );
6816
+ return () => {
6817
+ cancelled = true;
6818
+ };
6560
6819
  }, [props.deploymentId, props.workflowId, props.apiBase, restartNonce]);
6561
6820
  const restart = useCallback(() => {
6562
6821
  var _a2;
6563
6822
  if (autoStarting) {
6564
- clearPersistedSession(props.persistSession, persistTarget);
6823
+ clearPersistedSession(effectivePersistSession, persistTarget);
6565
6824
  setResolved(null);
6825
+ setTerminalReplayActive(false);
6826
+ setGate("idle");
6566
6827
  setRestartNonce((n) => n + 1);
6567
6828
  } else {
6568
6829
  (_a2 = adapterRef.current) == null ? void 0 : _a2.restart();
6569
6830
  }
6570
- }, [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]);
6571
6852
  const disconnect = useCallback(() => {
6572
6853
  var _a2;
6573
6854
  (_a2 = adapterRef.current) == null ? void 0 : _a2.disconnect();
@@ -6581,10 +6862,10 @@ var ChatterflyWidget = forwardRef(
6581
6862
  disconnect,
6582
6863
  sendMessage
6583
6864
  ]);
6584
- const runId = (_b = resolved == null ? void 0 : resolved.runId) != null ? _b : props.runId;
6585
- const participantToken = (_c = resolved == null ? void 0 : resolved.participantToken) != null ? _c : props.participantToken;
6586
- const mode = (_d = props.mode) != null ? _d : "inline";
6587
- 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);
6588
6869
  const [unreadCount, setUnreadCount] = useState(0);
6589
6870
  const toggleOpen = useCallback(() => {
6590
6871
  setOpen((prev) => {
@@ -6606,10 +6887,62 @@ var ChatterflyWidget = forwardRef(
6606
6887
  );
6607
6888
  let content;
6608
6889
  if (configError) {
6609
- 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
+ ] });
6610
6931
  } else if (!runId || !participantToken) {
6611
- 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" });
6612
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;
6613
6946
  content = /* @__PURE__ */ jsx(
6614
6947
  ChatAdapter,
6615
6948
  {
@@ -6617,14 +6950,16 @@ var ChatterflyWidget = forwardRef(
6617
6950
  ref: adapterRef,
6618
6951
  runId,
6619
6952
  participantToken,
6620
- onMessage: handleMessage
6953
+ onMessage: handleMessage,
6954
+ completedState: (_o = props.completedState) != null ? _o : replayCompletedState,
6955
+ errorState: (_p = props.errorState) != null ? _p : replayCompletedState
6621
6956
  }
6622
6957
  );
6623
6958
  }
6624
6959
  if (mode !== "floating") {
6625
6960
  return content;
6626
6961
  }
6627
- const position = (_h = props.position) != null ? _h : "bottom-right";
6962
+ const position = (_q = props.position) != null ? _q : "bottom-right";
6628
6963
  return /* @__PURE__ */ jsx(
6629
6964
  FloatingLauncherChrome,
6630
6965
  {
@@ -6682,7 +7017,8 @@ function FloatingLauncherChrome({
6682
7017
  }
6683
7018
  function useChatterflyRun(options) {
6684
7019
  var _a, _b;
6685
- 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;
6686
7022
  const [resolved, setResolved] = useState(null);
6687
7023
  const [error, setError] = useState(null);
6688
7024
  const [restartNonce, setRestartNonce] = useState(0);
@@ -6701,7 +7037,7 @@ function useChatterflyRun(options) {
6701
7037
  }
6702
7038
  setError(null);
6703
7039
  if (restartNonce === 0) {
6704
- const persisted = loadPersistedSession(persistSession, persistTarget);
7040
+ const persisted = loadPersistedSession(effectivePersistSession, persistTarget);
6705
7041
  if (persisted) {
6706
7042
  setResolved({ runId: persisted.runId, participantToken: persisted.participantToken });
6707
7043
  return;
@@ -6725,7 +7061,7 @@ function useChatterflyRun(options) {
6725
7061
  return r.json();
6726
7062
  }).then(({ run_id, participant_token }) => {
6727
7063
  setResolved({ runId: run_id, participantToken: participant_token });
6728
- savePersistedSession(persistSession, persistTarget, {
7064
+ savePersistedSession(effectivePersistSession, persistTarget, {
6729
7065
  runId: run_id,
6730
7066
  participantToken: participant_token
6731
7067
  });
@@ -6741,19 +7077,29 @@ function useChatterflyRun(options) {
6741
7077
  {
6742
7078
  runId: effectiveRunId != null ? effectiveRunId : "",
6743
7079
  participantToken: effectiveToken != null ? effectiveToken : "",
6744
- apiBase: apiBase != null ? apiBase : ""
7080
+ apiBase: apiBase != null ? apiBase : "",
7081
+ connectionPolicy
6745
7082
  },
6746
7083
  onEvent
6747
7084
  );
6748
7085
  const restart = useCallback(() => {
6749
7086
  if (autoStarting) {
6750
- clearPersistedSession(persistSession, persistTarget);
7087
+ clearPersistedSession(effectivePersistSession, persistTarget);
6751
7088
  setResolved(null);
6752
7089
  setRestartNonce((n) => n + 1);
6753
7090
  } else {
6754
7091
  stream.reconnect();
6755
7092
  }
6756
- }, [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]);
6757
7103
  const connecting = autoStarting && !resolved && !error;
6758
7104
  return {
6759
7105
  ...stream,