@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.js CHANGED
@@ -15,11 +15,68 @@ var WidgetError = class {
15
15
  return this.message;
16
16
  }
17
17
  };
18
- var RECONNECT_DELAY_MS = 2e3;
18
+
19
+ // src/strings.ts
20
+ var defaultStrings = {
21
+ statusInitialising: "Initialising\u2026",
22
+ statusConnecting: "Connecting\u2026",
23
+ statusRunning: "Running\u2026",
24
+ statusCompletedTitle: "Completed",
25
+ statusCompletedBody: "This workflow run has finished.",
26
+ statusErrorTitle: "Something went wrong",
27
+ statusOfflineTitle: "Connection lost",
28
+ statusOfflineBody: "Unable to reach the server. Please check your connection and refresh.",
29
+ statusExpiredTitle: "Session expired",
30
+ statusExpiredBody: "This conversation's session has expired. Start a new one to continue.",
31
+ statusListening: "Listening\u2026",
32
+ resumingConversation: "Resuming conversation\u2026",
33
+ reconnecting: "Reconnecting\u2026",
34
+ conversationCompleted: "Conversation completed.",
35
+ somethingWentWrong: "Something went wrong",
36
+ chatInputPlaceholder: "Type a message\u2026",
37
+ sendButton: "Send",
38
+ handBackButton: "Hand Back",
39
+ converseDoneButton: "I'm done",
40
+ startConversation: "Start conversation",
41
+ clickToStartDescription: "Click below to begin.",
42
+ resumeTitle: "Continue where you left off?",
43
+ resumeContinue: "Continue",
44
+ resumeRestart: "Start fresh",
45
+ startNewConversation: "Start new conversation",
46
+ conversationEnded: "This conversation has ended."
47
+ };
48
+ function resolveStrings(overrides) {
49
+ return overrides ? { ...defaultStrings, ...overrides } : defaultStrings;
50
+ }
51
+ var RECONNECT_BASE_DELAY_MS = 2e3;
52
+ var RECONNECT_MAX_DELAY_MS = 3e4;
19
53
  var MAX_RECONNECT_ATTEMPTS = 5;
20
- var TERMINAL_STATUSES = ["completed", "error", "offline"];
54
+ var TERMINAL_STATUSES = ["completed", "error", "offline", "expired"];
55
+ var PARKED_STATUSES = [
56
+ "awaiting_input",
57
+ "awaiting_voice",
58
+ "awaiting_form",
59
+ "awaiting_chat",
60
+ "awaiting_editor"
61
+ ];
62
+ var DEFAULT_IDLE_DISCONNECT_MS = 5 * 6e4;
63
+ var DEFAULT_POLL_INTERVAL_MS = 45e3;
64
+ var DEFAULT_HIBERNATE_AFTER_MS = 60 * 6e4;
65
+ function computeReconnectDelay(attempt) {
66
+ const cap = Math.min(
67
+ RECONNECT_MAX_DELAY_MS,
68
+ RECONNECT_BASE_DELAY_MS * 2 ** attempt
69
+ );
70
+ return Math.random() * cap;
71
+ }
21
72
  function useRunStream(config, onEvent) {
73
+ var _a, _b, _c;
22
74
  const { runId, participantToken, apiBase } = config;
75
+ const policyConfig = config.connectionPolicy;
76
+ const dormancyDisabled = policyConfig === "always-on";
77
+ const idleDisconnectMs = (_a = !dormancyDisabled && typeof policyConfig === "object" ? policyConfig == null ? void 0 : policyConfig.idleDisconnectMs : void 0) != null ? _a : DEFAULT_IDLE_DISCONNECT_MS;
78
+ const pollIntervalMs = (_b = !dormancyDisabled && typeof policyConfig === "object" ? policyConfig == null ? void 0 : policyConfig.pollIntervalMs : void 0) != null ? _b : DEFAULT_POLL_INTERVAL_MS;
79
+ const hibernateAfterMs = (_c = !dormancyDisabled && typeof policyConfig === "object" ? policyConfig == null ? void 0 : policyConfig.hibernateAfterMs : void 0) != null ? _c : DEFAULT_HIBERNATE_AFTER_MS;
23
80
  const [status, setStatus] = react.useState("idle");
24
81
  const [activeSession, setActiveSession] = react.useState(null);
25
82
  const [messages, setMessages] = react.useState([]);
@@ -28,11 +85,19 @@ function useRunStream(config, onEvent) {
28
85
  const [output, setOutput] = react.useState(null);
29
86
  const lastSeqRef = react.useRef(0);
30
87
  const [lastSeq, setLastSeq] = react.useState(0);
88
+ const [currentToken, setCurrentToken] = react.useState(participantToken);
89
+ const currentTokenRef = react.useRef(currentToken);
90
+ currentTokenRef.current = currentToken;
91
+ react.useEffect(() => setCurrentToken(participantToken), [participantToken]);
31
92
  const wsRef = react.useRef(null);
32
93
  const statusRef = react.useRef("idle");
33
94
  const reconnectTimerRef = react.useRef(null);
34
95
  const replayTimeoutRef = react.useRef(null);
35
96
  const mountedRef = react.useRef(true);
97
+ const connectionStateRef = react.useRef("active");
98
+ const idleTimerRef = react.useRef(null);
99
+ const hibernateTimerRef = react.useRef(null);
100
+ const pollTimerRef = react.useRef(null);
36
101
  const reconnectAttemptsRef = react.useRef(0);
37
102
  const manualDisconnectRef = react.useRef(false);
38
103
  const onEventRef = react.useRef(onEvent);
@@ -42,8 +107,8 @@ function useRunStream(config, onEvent) {
42
107
  setStatus(next);
43
108
  }, []);
44
109
  const authHeaders = react.useCallback(
45
- () => ({ Authorization: `Bearer ${participantToken}` }),
46
- [participantToken]
110
+ () => ({ Authorization: `Bearer ${currentTokenRef.current}` }),
111
+ []
47
112
  );
48
113
  const mergeTimeline = react.useCallback(
49
114
  (incoming) => {
@@ -65,9 +130,18 @@ function useRunStream(config, onEvent) {
65
130
  if (!mountedRef.current) return;
66
131
  if (!runId || !apiBase) return;
67
132
  manualDisconnectRef.current = false;
133
+ connectionStateRef.current = "active";
134
+ if (pollTimerRef.current) {
135
+ clearInterval(pollTimerRef.current);
136
+ pollTimerRef.current = null;
137
+ }
138
+ if (hibernateTimerRef.current) {
139
+ clearTimeout(hibernateTimerRef.current);
140
+ hibernateTimerRef.current = null;
141
+ }
68
142
  updateStatus("connecting");
69
143
  const wsUrl = apiBase.replace(/^http/, "ws") + `/api/participant/runs/${runId}/stream`;
70
- const params = new URLSearchParams({ token: participantToken });
144
+ const params = new URLSearchParams({ token: currentTokenRef.current });
71
145
  const ws = new WebSocket(`${wsUrl}?${params}`);
72
146
  wsRef.current = ws;
73
147
  ws.onopen = () => {
@@ -105,15 +179,128 @@ function useRunStream(config, onEvent) {
105
179
  if (isOffline) {
106
180
  updateStatus("offline");
107
181
  } else {
182
+ const attempt = reconnectAttemptsRef.current;
108
183
  reconnectAttemptsRef.current += 1;
109
- reconnectTimerRef.current = setTimeout(connect, RECONNECT_DELAY_MS);
184
+ reconnectTimerRef.current = setTimeout(
185
+ connect,
186
+ computeReconnectDelay(attempt)
187
+ );
110
188
  }
111
189
  }
112
190
  };
113
191
  }, [runId, participantToken, apiBase]);
192
+ const remintToken = react.useCallback(async () => {
193
+ try {
194
+ const res = await fetch(`${apiBase}/api/public/runs/${runId}/token`, {
195
+ method: "POST",
196
+ headers: { "Content-Type": "application/json" },
197
+ body: JSON.stringify({ participant_token: currentTokenRef.current })
198
+ });
199
+ if (!res.ok) return null;
200
+ const data = await res.json();
201
+ if (!data.participant_token) return null;
202
+ setCurrentToken(data.participant_token);
203
+ return data.participant_token;
204
+ } catch {
205
+ return null;
206
+ }
207
+ }, [apiBase, runId]);
208
+ const stopPolling = react.useCallback(() => {
209
+ if (pollTimerRef.current) {
210
+ clearInterval(pollTimerRef.current);
211
+ pollTimerRef.current = null;
212
+ }
213
+ if (hibernateTimerRef.current) {
214
+ clearTimeout(hibernateTimerRef.current);
215
+ hibernateTimerRef.current = null;
216
+ }
217
+ }, []);
218
+ const wake = react.useCallback(() => {
219
+ if (!mountedRef.current) return;
220
+ if (connectionStateRef.current === "active") return;
221
+ stopPolling();
222
+ reconnectAttemptsRef.current = 0;
223
+ connect();
224
+ }, [connect, stopPolling]);
225
+ const startPolling = react.useCallback(() => {
226
+ if (pollTimerRef.current) return;
227
+ pollTimerRef.current = setInterval(async () => {
228
+ if (!mountedRef.current) return;
229
+ try {
230
+ const res = await fetch(
231
+ `${apiBase}/api/participant/runs/${runId}/timeline?since_seq=${lastSeqRef.current}`,
232
+ { headers: { Authorization: `Bearer ${currentTokenRef.current}` } }
233
+ );
234
+ if (res.status === 401) {
235
+ const fresh = await remintToken();
236
+ if (!fresh) {
237
+ stopPolling();
238
+ updateStatus("expired");
239
+ }
240
+ return;
241
+ }
242
+ if (!res.ok) return;
243
+ const entries = await res.json();
244
+ if (Array.isArray(entries) && entries.length > 0) {
245
+ wake();
246
+ }
247
+ } catch {
248
+ }
249
+ }, pollIntervalMs);
250
+ hibernateTimerRef.current = setTimeout(() => {
251
+ connectionStateRef.current = "hibernating";
252
+ if (pollTimerRef.current) {
253
+ clearInterval(pollTimerRef.current);
254
+ pollTimerRef.current = null;
255
+ }
256
+ }, hibernateAfterMs);
257
+ }, [apiBase, runId, pollIntervalMs, hibernateAfterMs, remintToken, stopPolling, updateStatus, wake]);
258
+ const goDormant = react.useCallback(() => {
259
+ var _a2;
260
+ if (connectionStateRef.current !== "active") return;
261
+ connectionStateRef.current = "dormant";
262
+ manualDisconnectRef.current = true;
263
+ (_a2 = wsRef.current) == null ? void 0 : _a2.close();
264
+ wsRef.current = null;
265
+ startPolling();
266
+ }, [startPolling]);
267
+ react.useEffect(() => {
268
+ if (dormancyDisabled) return;
269
+ if (idleTimerRef.current) {
270
+ clearTimeout(idleTimerRef.current);
271
+ idleTimerRef.current = null;
272
+ }
273
+ if (PARKED_STATUSES.includes(status) && connectionStateRef.current === "active") {
274
+ idleTimerRef.current = setTimeout(goDormant, idleDisconnectMs);
275
+ }
276
+ return () => {
277
+ if (idleTimerRef.current) {
278
+ clearTimeout(idleTimerRef.current);
279
+ idleTimerRef.current = null;
280
+ }
281
+ };
282
+ }, [status, dormancyDisabled, idleDisconnectMs, goDormant]);
283
+ react.useEffect(() => {
284
+ if (dormancyDisabled) return;
285
+ const handleVisibility = () => {
286
+ if (document.visibilityState === "visible") wake();
287
+ };
288
+ document.addEventListener("visibilitychange", handleVisibility);
289
+ window.addEventListener("online", wake);
290
+ window.addEventListener("focus", wake);
291
+ window.addEventListener("pointerdown", wake);
292
+ window.addEventListener("keydown", wake);
293
+ return () => {
294
+ document.removeEventListener("visibilitychange", handleVisibility);
295
+ window.removeEventListener("online", wake);
296
+ window.removeEventListener("focus", wake);
297
+ window.removeEventListener("pointerdown", wake);
298
+ window.removeEventListener("keydown", wake);
299
+ };
300
+ }, [dormancyDisabled, wake]);
114
301
  function handleEvent(event) {
115
- var _a, _b, _c, _d, _e;
116
- (_a = onEventRef.current) == null ? void 0 : _a.call(onEventRef, event);
302
+ var _a2, _b2, _c2, _d, _e;
303
+ (_a2 = onEventRef.current) == null ? void 0 : _a2.call(onEventRef, event);
117
304
  switch (event.type) {
118
305
  case "timeline.replay": {
119
306
  mergeTimeline(event.payload);
@@ -150,7 +337,7 @@ function useRunStream(config, onEvent) {
150
337
  entry_context: event.entry_context,
151
338
  status: "open",
152
339
  messages: replayedMessages,
153
- document_content: (_b = event.document_content) != null ? _b : null
340
+ document_content: (_b2 = event.document_content) != null ? _b2 : null
154
341
  };
155
342
  setActiveSession(session);
156
343
  if (replayedMessages.length > 0) {
@@ -163,7 +350,7 @@ function useRunStream(config, onEvent) {
163
350
  } else if (event.layout === "form") {
164
351
  updateStatus("awaiting_form");
165
352
  } else {
166
- const surface = (_c = event.entry_context) == null ? void 0 : _c.surface;
353
+ const surface = (_c2 = event.entry_context) == null ? void 0 : _c2.surface;
167
354
  const isVoice = typeof surface === "string" && (surface === "widget/voice" || surface === "phone" || surface === "phone/outbound");
168
355
  if (isVoice) {
169
356
  updateStatus("awaiting_voice");
@@ -203,17 +390,21 @@ function useRunStream(config, onEvent) {
203
390
  mountedRef.current = true;
204
391
  reconnectTimerRef.current = setTimeout(connect, 0);
205
392
  return () => {
206
- var _a;
393
+ var _a2;
207
394
  mountedRef.current = false;
208
395
  if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
209
396
  if (replayTimeoutRef.current) clearTimeout(replayTimeoutRef.current);
210
- (_a = wsRef.current) == null ? void 0 : _a.close();
397
+ if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
398
+ if (pollTimerRef.current) clearInterval(pollTimerRef.current);
399
+ if (hibernateTimerRef.current) clearTimeout(hibernateTimerRef.current);
400
+ (_a2 = wsRef.current) == null ? void 0 : _a2.close();
211
401
  wsRef.current = null;
212
402
  };
213
403
  }, [connect]);
214
404
  const sendMessage = react.useCallback(
215
405
  async (content) => {
216
406
  if (!activeSession) return;
407
+ wake();
217
408
  setMessages((prev) => [
218
409
  ...prev,
219
410
  { role: "human", content }
@@ -240,12 +431,13 @@ function useRunStream(config, onEvent) {
240
431
  throw new Error(`sendMessage failed: ${res.status} ${text}`);
241
432
  }
242
433
  },
243
- [activeSession, apiBase, authHeaders, updateStatus]
434
+ [activeSession, apiBase, authHeaders, updateStatus, wake]
244
435
  );
245
436
  const submitHandback = react.useCallback(
246
437
  async (output2, idempotencyKey) => {
247
- var _a;
438
+ var _a2;
248
439
  if (!activeSession) return null;
440
+ wake();
249
441
  const body = { output: output2 };
250
442
  if (idempotencyKey) body.idempotency_key = idempotencyKey;
251
443
  let res;
@@ -267,7 +459,7 @@ function useRunStream(config, onEvent) {
267
459
  }
268
460
  if (res.status === 422) {
269
461
  const data = await res.json();
270
- return (_a = data.errors) != null ? _a : [{ field: "_", message: "Validation failed" }];
462
+ return (_a2 = data.errors) != null ? _a2 : [{ field: "_", message: "Validation failed" }];
271
463
  }
272
464
  if (!res.ok) {
273
465
  const text = await res.text();
@@ -278,13 +470,13 @@ function useRunStream(config, onEvent) {
278
470
  updateStatus("running");
279
471
  return null;
280
472
  },
281
- [activeSession, apiBase, authHeaders, updateStatus]
473
+ [activeSession, apiBase, authHeaders, updateStatus, wake]
282
474
  );
283
475
  const disconnect = react.useCallback(() => {
284
- var _a;
476
+ var _a2;
285
477
  manualDisconnectRef.current = true;
286
478
  if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
287
- (_a = wsRef.current) == null ? void 0 : _a.close();
479
+ (_a2 = wsRef.current) == null ? void 0 : _a2.close();
288
480
  wsRef.current = null;
289
481
  updateStatus("offline");
290
482
  }, [updateStatus]);
@@ -499,9 +691,17 @@ var widget_default = {
499
691
  activeInputSubmit: "widget_activeInputSubmit",
500
692
  inlineError: "widget_inlineError",
501
693
  resumingBanner: "widget_resumingBanner",
694
+ reconnectingPill: "widget_reconnectingPill",
502
695
  terminalBanner: "widget_terminalBanner",
503
696
  terminalCompleted: "widget_terminalBanner widget_terminalCompleted",
504
697
  terminalError: "widget_terminalBanner widget_terminalError",
698
+ startNewConversationButton: "widget_startNewConversationButton",
699
+ gateCard: "widget_gateCard",
700
+ gateTitle: "widget_gateTitle",
701
+ gateDescription: "widget_gateDescription",
702
+ gateActions: "widget_gateActions",
703
+ gateButtonPrimary: "widget_gateButtonPrimary",
704
+ gateButtonSecondary: "widget_gateButtonSecondary",
505
705
  typingIndicator: "widget_typingIndicator",
506
706
  typingDot: "widget_typingDot",
507
707
  cfTyping: "widget_cfTyping",
@@ -2670,29 +2870,6 @@ function FormRenderer({
2670
2870
  ) })
2671
2871
  ] });
2672
2872
  }
2673
-
2674
- // src/strings.ts
2675
- var defaultStrings = {
2676
- statusInitialising: "Initialising\u2026",
2677
- statusConnecting: "Connecting\u2026",
2678
- statusRunning: "Running\u2026",
2679
- statusCompletedTitle: "Completed",
2680
- statusCompletedBody: "This workflow run has finished.",
2681
- statusErrorTitle: "Something went wrong",
2682
- statusOfflineTitle: "Connection lost",
2683
- statusOfflineBody: "Unable to reach the server. Please check your connection and refresh.",
2684
- statusListening: "Listening\u2026",
2685
- resumingConversation: "Resuming conversation\u2026",
2686
- conversationCompleted: "Conversation completed.",
2687
- somethingWentWrong: "Something went wrong",
2688
- chatInputPlaceholder: "Type a message\u2026",
2689
- sendButton: "Send",
2690
- handBackButton: "Hand Back",
2691
- converseDoneButton: "I'm done"
2692
- };
2693
- function resolveStrings(overrides) {
2694
- return overrides ? { ...defaultStrings, ...overrides } : defaultStrings;
2695
- }
2696
2873
  function StatusDisplay({ status, error, strings }) {
2697
2874
  const t = strings ? { ...defaultStrings, ...strings } : defaultStrings;
2698
2875
  switch (status) {
@@ -2722,6 +2899,11 @@ function StatusDisplay({ status, error, strings }) {
2722
2899
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: t.statusOfflineTitle }),
2723
2900
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.statusLabel} ${widget_default.statusError}`, children: t.statusOfflineBody })
2724
2901
  ] });
2902
+ case "expired":
2903
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.statusWrapper, children: [
2904
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: t.statusExpiredTitle }),
2905
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.statusLabel} ${widget_default.statusError}`, children: t.statusExpiredBody })
2906
+ ] });
2725
2907
  case "awaiting_voice":
2726
2908
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.statusWrapper, children: [
2727
2909
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.spinner, "aria-hidden": true }),
@@ -5819,6 +6001,7 @@ var ChatAdapter = react.forwardRef(
5819
6001
  runId,
5820
6002
  participantToken,
5821
6003
  apiBase,
6004
+ connectionPolicy,
5822
6005
  className,
5823
6006
  onCompleted,
5824
6007
  onError,
@@ -5874,7 +6057,7 @@ var ChatAdapter = react.forwardRef(
5874
6057
  output,
5875
6058
  disconnect,
5876
6059
  reconnect
5877
- } = useRunStream({ runId, participantToken, apiBase }, onEventFirehose);
6060
+ } = useRunStream({ runId, participantToken, apiBase, connectionPolicy }, onEventFirehose);
5878
6061
  react.useImperativeHandle(
5879
6062
  ref,
5880
6063
  () => ({
@@ -5996,6 +6179,7 @@ var ChatAdapter = react.forwardRef(
5996
6179
  }, [timeline, isVoiceSurface, enqueueSpeak]);
5997
6180
  const completedFiredRef = react.useRef(false);
5998
6181
  const errorFiredRef = react.useRef(false);
6182
+ const expiredFiredRef = react.useRef(false);
5999
6183
  const inputAreaRef = react.useRef(null);
6000
6184
  const lastFocusedSessionRef = react.useRef(null);
6001
6185
  const activeSessionId = (_c = activeSession == null ? void 0 : activeSession.id) != null ? _c : null;
@@ -6022,6 +6206,12 @@ var ChatAdapter = react.forwardRef(
6022
6206
  errorFiredRef.current = true;
6023
6207
  onError == null ? void 0 : onError(new WidgetError("run_failed", "The run encountered an error."));
6024
6208
  }
6209
+ if (status === "expired" && !expiredFiredRef.current) {
6210
+ expiredFiredRef.current = true;
6211
+ onError == null ? void 0 : onError(
6212
+ new WidgetError("token_expired", "The participant token expired and could not be renewed.")
6213
+ );
6214
+ }
6025
6215
  }, [status, output, onCompleted, onError]);
6026
6216
  const colorSchemeClass = colorScheme === "dark" ? widget_default.cfDark : colorScheme === "auto" ? widget_default.cfAuto : void 0;
6027
6217
  const cls = [widget_default.widget, colorSchemeClass, className].filter(Boolean).join(" ");
@@ -6068,10 +6258,11 @@ var ChatAdapter = react.forwardRef(
6068
6258
  },
6069
6259
  [handleSubmit]
6070
6260
  );
6071
- if (status === "idle" || status === "connecting") {
6261
+ const isSilentReconnect = (status === "connecting" || status === "replaying") && timeline.length > 0;
6262
+ if (status === "idle" || status === "connecting" && !isSilentReconnect) {
6072
6263
  return /* @__PURE__ */ jsxRuntime.jsx("div", { className: cls, style: rootStyle, children: loadingFallback != null ? loadingFallback : /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status, strings }) });
6073
6264
  }
6074
- if (status === "replaying") {
6265
+ if (status === "replaying" && !isSilentReconnect) {
6075
6266
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cls, style: rootStyle, children: [
6076
6267
  header,
6077
6268
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.resumingBanner, children: [
@@ -6304,6 +6495,10 @@ var ChatAdapter = react.forwardRef(
6304
6495
  ) });
6305
6496
  }
6306
6497
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cls, style: rootStyle, children: [
6498
+ isSilentReconnect && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.reconnectingPill, children: [
6499
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.spinner }),
6500
+ t.reconnecting
6501
+ ] }),
6307
6502
  header,
6308
6503
  /* @__PURE__ */ jsxRuntime.jsx(ChatTimeline, { entries: timeline, showTyping, streamingText, components }),
6309
6504
  activeSession && field && InputComponent && /* @__PURE__ */ jsxRuntime.jsxs("form", { ref: inputAreaRef, className: widget_default.activeInputArea, onSubmit: handleSubmit, children: [
@@ -6501,15 +6696,44 @@ function clearPersistedSession(config, target) {
6501
6696
  } catch {
6502
6697
  }
6503
6698
  }
6699
+ async function fetchPersistedRunTerminalStatus(apiBase, runId, participantToken) {
6700
+ var _a;
6701
+ try {
6702
+ const res = await fetch(`${apiBase}/api/participant/runs/${runId}/timeline`, {
6703
+ headers: { Authorization: `Bearer ${participantToken}` }
6704
+ });
6705
+ if (!res.ok) return null;
6706
+ const entries = await res.json();
6707
+ if (!Array.isArray(entries)) return null;
6708
+ for (let i = entries.length - 1; i >= 0; i--) {
6709
+ const e = entries[i];
6710
+ if (e.event_type === "status_change") {
6711
+ const s = (_a = e.payload) == null ? void 0 : _a.status;
6712
+ if (s === "completed" || s === "failed") return s;
6713
+ }
6714
+ }
6715
+ return null;
6716
+ } catch {
6717
+ return null;
6718
+ }
6719
+ }
6504
6720
  var ChatterflyWidget = react.forwardRef(
6505
6721
  function ChatterflyWidget2(props, ref) {
6506
- var _a, _b, _c, _d, _e, _f, _g, _h;
6722
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
6507
6723
  const [resolved, setResolved] = react.useState(null);
6508
6724
  const [configError, setConfigError] = react.useState(null);
6509
6725
  const [restartNonce, setRestartNonce] = react.useState(0);
6510
6726
  const adapterRef = react.useRef(null);
6511
6727
  const autoStarting = Boolean(!props.runId && (props.deploymentId || props.workflowId));
6512
6728
  const persistTarget = (_a = props.workflowId) != null ? _a : props.deploymentId;
6729
+ const effectivePersistSession = props.persistSession === void 0 ? true : props.persistSession;
6730
+ const showCompletedHistory = (_b = props.showCompletedHistory) != null ? _b : true;
6731
+ const t = { ...defaultStrings, ...props.strings };
6732
+ const [gate, setGate] = react.useState("idle");
6733
+ const [terminalReplayActive, setTerminalReplayActive] = react.useState(false);
6734
+ const pendingPersistedRef = react.useRef(null);
6735
+ const startNewRunRef = react.useRef(() => {
6736
+ });
6513
6737
  react.useEffect(() => {
6514
6738
  var _a2;
6515
6739
  if (props.runId) return;
@@ -6524,52 +6748,109 @@ var ChatterflyWidget = react.forwardRef(
6524
6748
  return;
6525
6749
  }
6526
6750
  setConfigError(null);
6527
- if (restartNonce === 0) {
6528
- const persisted = loadPersistedSession(props.persistSession, persistTarget);
6529
- if (persisted) {
6530
- setResolved({ runId: persisted.runId, participantToken: persisted.participantToken });
6531
- return;
6751
+ const base = props.apiBase;
6752
+ const doStart = (input) => {
6753
+ const startUrl = props.workflowId ? `${base}/api/public/workflows/${props.workflowId}/start` : `${base}/api/public/surveys/${props.deploymentId}/start`;
6754
+ const body = input ? JSON.stringify({ input }) : void 0;
6755
+ fetch(startUrl, {
6756
+ method: "POST",
6757
+ headers: body ? { "Content-Type": "application/json" } : void 0,
6758
+ body
6759
+ }).then(async (r) => {
6760
+ if (!r.ok) {
6761
+ const code = r.status === 404 ? "no_live_deployment" : "workflow_not_public";
6762
+ const detail = await r.text().catch(() => "");
6763
+ throw new WidgetError(
6764
+ code,
6765
+ `Failed to start run (HTTP ${r.status})${detail ? `: ${detail}` : ""}`
6766
+ );
6767
+ }
6768
+ return r.json();
6769
+ }).then(({ run_id, participant_token }) => {
6770
+ setGate("idle");
6771
+ setTerminalReplayActive(false);
6772
+ setResolved({ runId: run_id, participantToken: participant_token });
6773
+ savePersistedSession(effectivePersistSession, persistTarget, {
6774
+ runId: run_id,
6775
+ participantToken: participant_token
6776
+ });
6777
+ }).catch((err) => {
6778
+ var _a3;
6779
+ const widgetErr = err instanceof WidgetError ? err : new WidgetError("network", err instanceof Error ? err.message : String(err));
6780
+ (_a3 = props.onError) == null ? void 0 : _a3.call(props, widgetErr);
6781
+ });
6782
+ };
6783
+ startNewRunRef.current = doStart;
6784
+ if (restartNonce > 0) {
6785
+ doStart(props.initialInput);
6786
+ return;
6787
+ }
6788
+ const persisted = loadPersistedSession(effectivePersistSession, persistTarget);
6789
+ if (!persisted) {
6790
+ if (props.clickToStart) {
6791
+ setGate("click-to-start");
6792
+ } else {
6793
+ doStart(props.initialInput);
6532
6794
  }
6795
+ return;
6533
6796
  }
6534
- const base = props.apiBase;
6535
- const startUrl = props.workflowId ? `${base}/api/public/workflows/${props.workflowId}/start` : `${base}/api/public/surveys/${props.deploymentId}/start`;
6536
- const body = props.initialInput ? JSON.stringify({ input: props.initialInput }) : void 0;
6537
- fetch(startUrl, {
6538
- method: "POST",
6539
- headers: body ? { "Content-Type": "application/json" } : void 0,
6540
- body
6541
- }).then(async (r) => {
6542
- if (!r.ok) {
6543
- const code = r.status === 404 ? "no_live_deployment" : "workflow_not_public";
6544
- const detail = await r.text().catch(() => "");
6545
- throw new WidgetError(
6546
- code,
6547
- `Failed to start run (HTTP ${r.status})${detail ? `: ${detail}` : ""}`
6548
- );
6797
+ let cancelled = false;
6798
+ fetchPersistedRunTerminalStatus(base, persisted.runId, persisted.participantToken).then(
6799
+ (terminal) => {
6800
+ if (cancelled) return;
6801
+ if (terminal) {
6802
+ if (showCompletedHistory) {
6803
+ setTerminalReplayActive(true);
6804
+ setGate("idle");
6805
+ setResolved(persisted);
6806
+ } else {
6807
+ clearPersistedSession(effectivePersistSession, persistTarget);
6808
+ doStart(props.initialInput);
6809
+ }
6810
+ } else if (props.resumePrompt) {
6811
+ pendingPersistedRef.current = persisted;
6812
+ setGate("resume-choice");
6813
+ } else {
6814
+ setResolved(persisted);
6815
+ }
6549
6816
  }
6550
- return r.json();
6551
- }).then(({ run_id, participant_token }) => {
6552
- setResolved({ runId: run_id, participantToken: participant_token });
6553
- savePersistedSession(props.persistSession, persistTarget, {
6554
- runId: run_id,
6555
- participantToken: participant_token
6556
- });
6557
- }).catch((err) => {
6558
- var _a3;
6559
- const widgetErr = err instanceof WidgetError ? err : new WidgetError("network", err instanceof Error ? err.message : String(err));
6560
- (_a3 = props.onError) == null ? void 0 : _a3.call(props, widgetErr);
6561
- });
6817
+ );
6818
+ return () => {
6819
+ cancelled = true;
6820
+ };
6562
6821
  }, [props.deploymentId, props.workflowId, props.apiBase, restartNonce]);
6563
6822
  const restart = react.useCallback(() => {
6564
6823
  var _a2;
6565
6824
  if (autoStarting) {
6566
- clearPersistedSession(props.persistSession, persistTarget);
6825
+ clearPersistedSession(effectivePersistSession, persistTarget);
6567
6826
  setResolved(null);
6827
+ setTerminalReplayActive(false);
6828
+ setGate("idle");
6568
6829
  setRestartNonce((n) => n + 1);
6569
6830
  } else {
6570
6831
  (_a2 = adapterRef.current) == null ? void 0 : _a2.restart();
6571
6832
  }
6572
- }, [autoStarting, props.persistSession, persistTarget]);
6833
+ }, [autoStarting, effectivePersistSession, persistTarget]);
6834
+ const handleClickToStart = react.useCallback(() => {
6835
+ startNewRunRef.current(props.initialInput);
6836
+ }, [props.initialInput]);
6837
+ const handleResumeContinue = react.useCallback(() => {
6838
+ if (pendingPersistedRef.current) {
6839
+ setResolved(pendingPersistedRef.current);
6840
+ setGate("idle");
6841
+ }
6842
+ }, []);
6843
+ const handleResumeRestart = react.useCallback(() => {
6844
+ clearPersistedSession(effectivePersistSession, persistTarget);
6845
+ setGate("idle");
6846
+ startNewRunRef.current(props.initialInput);
6847
+ }, [effectivePersistSession, persistTarget, props.initialInput]);
6848
+ const handleStartNewFromReplay = react.useCallback(() => {
6849
+ clearPersistedSession(effectivePersistSession, persistTarget);
6850
+ setTerminalReplayActive(false);
6851
+ setResolved(null);
6852
+ startNewRunRef.current(props.initialInput);
6853
+ }, [effectivePersistSession, persistTarget, props.initialInput]);
6573
6854
  const disconnect = react.useCallback(() => {
6574
6855
  var _a2;
6575
6856
  (_a2 = adapterRef.current) == null ? void 0 : _a2.disconnect();
@@ -6583,10 +6864,10 @@ var ChatterflyWidget = react.forwardRef(
6583
6864
  disconnect,
6584
6865
  sendMessage
6585
6866
  ]);
6586
- const runId = (_b = resolved == null ? void 0 : resolved.runId) != null ? _b : props.runId;
6587
- const participantToken = (_c = resolved == null ? void 0 : resolved.participantToken) != null ? _c : props.participantToken;
6588
- const mode = (_d = props.mode) != null ? _d : "inline";
6589
- const [open, setOpen] = react.useState((_e = props.defaultOpen) != null ? _e : false);
6867
+ const runId = (_c = resolved == null ? void 0 : resolved.runId) != null ? _c : props.runId;
6868
+ const participantToken = (_d = resolved == null ? void 0 : resolved.participantToken) != null ? _d : props.participantToken;
6869
+ const mode = (_e = props.mode) != null ? _e : "inline";
6870
+ const [open, setOpen] = react.useState((_f = props.defaultOpen) != null ? _f : false);
6590
6871
  const [unreadCount, setUnreadCount] = react.useState(0);
6591
6872
  const toggleOpen = react.useCallback(() => {
6592
6873
  setOpen((prev) => {
@@ -6608,10 +6889,62 @@ var ChatterflyWidget = react.forwardRef(
6608
6889
  );
6609
6890
  let content;
6610
6891
  if (configError) {
6611
- content = (_f = props.loadingFallback) != null ? _f : /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status: "error" });
6892
+ content = (_g = props.loadingFallback) != null ? _g : /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status: "error" });
6893
+ } else if (gate === "click-to-start") {
6894
+ const cfg = typeof props.clickToStart === "object" ? props.clickToStart : void 0;
6895
+ content = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.gateCard, children: [
6896
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.gateTitle, children: (_h = cfg == null ? void 0 : cfg.label) != null ? _h : t.startConversation }),
6897
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.gateDescription, children: (_i = cfg == null ? void 0 : cfg.description) != null ? _i : t.clickToStartDescription }),
6898
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.gateActions, children: /* @__PURE__ */ jsxRuntime.jsx(
6899
+ "button",
6900
+ {
6901
+ type: "button",
6902
+ className: widget_default.gateButtonPrimary,
6903
+ onClick: handleClickToStart,
6904
+ children: (_j = cfg == null ? void 0 : cfg.label) != null ? _j : t.startConversation
6905
+ }
6906
+ ) })
6907
+ ] });
6908
+ } else if (gate === "resume-choice") {
6909
+ const cfg = typeof props.resumePrompt === "object" ? props.resumePrompt : void 0;
6910
+ content = /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.gateCard, children: [
6911
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.gateTitle, children: (_k = cfg == null ? void 0 : cfg.title) != null ? _k : t.resumeTitle }),
6912
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.gateActions, children: [
6913
+ /* @__PURE__ */ jsxRuntime.jsx(
6914
+ "button",
6915
+ {
6916
+ type: "button",
6917
+ className: widget_default.gateButtonPrimary,
6918
+ onClick: handleResumeContinue,
6919
+ children: (_l = cfg == null ? void 0 : cfg.continueLabel) != null ? _l : t.resumeContinue
6920
+ }
6921
+ ),
6922
+ /* @__PURE__ */ jsxRuntime.jsx(
6923
+ "button",
6924
+ {
6925
+ type: "button",
6926
+ className: widget_default.gateButtonSecondary,
6927
+ onClick: handleResumeRestart,
6928
+ children: (_m = cfg == null ? void 0 : cfg.restartLabel) != null ? _m : t.resumeRestart
6929
+ }
6930
+ )
6931
+ ] })
6932
+ ] });
6612
6933
  } else if (!runId || !participantToken) {
6613
- content = (_g = props.loadingFallback) != null ? _g : /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status: autoStarting ? "connecting" : "error" });
6934
+ content = (_n = props.loadingFallback) != null ? _n : /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status: autoStarting ? "connecting" : "error" });
6614
6935
  } else {
6936
+ const replayCompletedState = terminalReplayActive ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
6937
+ t.conversationEnded,
6938
+ /* @__PURE__ */ jsxRuntime.jsx(
6939
+ "button",
6940
+ {
6941
+ type: "button",
6942
+ className: widget_default.startNewConversationButton,
6943
+ onClick: handleStartNewFromReplay,
6944
+ children: t.startNewConversation
6945
+ }
6946
+ )
6947
+ ] }) : void 0;
6615
6948
  content = /* @__PURE__ */ jsxRuntime.jsx(
6616
6949
  ChatAdapter,
6617
6950
  {
@@ -6619,14 +6952,16 @@ var ChatterflyWidget = react.forwardRef(
6619
6952
  ref: adapterRef,
6620
6953
  runId,
6621
6954
  participantToken,
6622
- onMessage: handleMessage
6955
+ onMessage: handleMessage,
6956
+ completedState: (_o = props.completedState) != null ? _o : replayCompletedState,
6957
+ errorState: (_p = props.errorState) != null ? _p : replayCompletedState
6623
6958
  }
6624
6959
  );
6625
6960
  }
6626
6961
  if (mode !== "floating") {
6627
6962
  return content;
6628
6963
  }
6629
- const position = (_h = props.position) != null ? _h : "bottom-right";
6964
+ const position = (_q = props.position) != null ? _q : "bottom-right";
6630
6965
  return /* @__PURE__ */ jsxRuntime.jsx(
6631
6966
  FloatingLauncherChrome,
6632
6967
  {
@@ -6684,7 +7019,8 @@ function FloatingLauncherChrome({
6684
7019
  }
6685
7020
  function useChatterflyRun(options) {
6686
7021
  var _a, _b;
6687
- const { runId, participantToken, apiBase, deploymentId, workflowId, initialInput, persistSession, onEvent } = options;
7022
+ const { runId, participantToken, apiBase, deploymentId, workflowId, initialInput, persistSession, connectionPolicy, onEvent } = options;
7023
+ const effectivePersistSession = persistSession === void 0 ? true : persistSession;
6688
7024
  const [resolved, setResolved] = react.useState(null);
6689
7025
  const [error, setError] = react.useState(null);
6690
7026
  const [restartNonce, setRestartNonce] = react.useState(0);
@@ -6703,7 +7039,7 @@ function useChatterflyRun(options) {
6703
7039
  }
6704
7040
  setError(null);
6705
7041
  if (restartNonce === 0) {
6706
- const persisted = loadPersistedSession(persistSession, persistTarget);
7042
+ const persisted = loadPersistedSession(effectivePersistSession, persistTarget);
6707
7043
  if (persisted) {
6708
7044
  setResolved({ runId: persisted.runId, participantToken: persisted.participantToken });
6709
7045
  return;
@@ -6727,7 +7063,7 @@ function useChatterflyRun(options) {
6727
7063
  return r.json();
6728
7064
  }).then(({ run_id, participant_token }) => {
6729
7065
  setResolved({ runId: run_id, participantToken: participant_token });
6730
- savePersistedSession(persistSession, persistTarget, {
7066
+ savePersistedSession(effectivePersistSession, persistTarget, {
6731
7067
  runId: run_id,
6732
7068
  participantToken: participant_token
6733
7069
  });
@@ -6743,19 +7079,29 @@ function useChatterflyRun(options) {
6743
7079
  {
6744
7080
  runId: effectiveRunId != null ? effectiveRunId : "",
6745
7081
  participantToken: effectiveToken != null ? effectiveToken : "",
6746
- apiBase: apiBase != null ? apiBase : ""
7082
+ apiBase: apiBase != null ? apiBase : "",
7083
+ connectionPolicy
6747
7084
  },
6748
7085
  onEvent
6749
7086
  );
6750
7087
  const restart = react.useCallback(() => {
6751
7088
  if (autoStarting) {
6752
- clearPersistedSession(persistSession, persistTarget);
7089
+ clearPersistedSession(effectivePersistSession, persistTarget);
6753
7090
  setResolved(null);
6754
7091
  setRestartNonce((n) => n + 1);
6755
7092
  } else {
6756
7093
  stream.reconnect();
6757
7094
  }
6758
- }, [autoStarting, persistSession, persistTarget, stream]);
7095
+ }, [autoStarting, effectivePersistSession, persistTarget, stream]);
7096
+ const expiredErrorFiredRef = react.useRef(false);
7097
+ react.useEffect(() => {
7098
+ if (stream.status === "expired" && !expiredErrorFiredRef.current) {
7099
+ expiredErrorFiredRef.current = true;
7100
+ setError(
7101
+ new WidgetError("token_expired", "The participant token expired and could not be renewed.")
7102
+ );
7103
+ }
7104
+ }, [stream.status]);
6759
7105
  const connecting = autoStarting && !resolved && !error;
6760
7106
  return {
6761
7107
  ...stream,