@chatterfly/widget 0.1.0 → 0.3.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
@@ -4,16 +4,28 @@ var react = require('react');
4
4
  var jsxRuntime = require('react/jsx-runtime');
5
5
 
6
6
  // src/components/ChatterflyWidget.tsx
7
+
8
+ // src/types.ts
9
+ var WidgetError = class {
10
+ constructor(code, message) {
11
+ this.code = code;
12
+ this.message = message;
13
+ }
14
+ toString() {
15
+ return this.message;
16
+ }
17
+ };
7
18
  var RECONNECT_DELAY_MS = 2e3;
8
19
  var MAX_RECONNECT_ATTEMPTS = 5;
9
20
  var TERMINAL_STATUSES = ["completed", "error", "offline"];
10
- function useRunStream(config) {
11
- const { runId, participantToken, apiBase = "http://localhost:8080" } = config;
21
+ function useRunStream(config, onEvent) {
22
+ const { runId, participantToken, apiBase } = config;
12
23
  const [status, setStatus] = react.useState("idle");
13
24
  const [activeSession, setActiveSession] = react.useState(null);
14
25
  const [messages, setMessages] = react.useState([]);
15
26
  const [timeline, setTimeline] = react.useState([]);
16
27
  const [streamingText, setStreamingText] = react.useState("");
28
+ const [output, setOutput] = react.useState(null);
17
29
  const lastSeqRef = react.useRef(0);
18
30
  const [lastSeq, setLastSeq] = react.useState(0);
19
31
  const wsRef = react.useRef(null);
@@ -22,6 +34,9 @@ function useRunStream(config) {
22
34
  const replayTimeoutRef = react.useRef(null);
23
35
  const mountedRef = react.useRef(true);
24
36
  const reconnectAttemptsRef = react.useRef(0);
37
+ const manualDisconnectRef = react.useRef(false);
38
+ const onEventRef = react.useRef(onEvent);
39
+ onEventRef.current = onEvent;
25
40
  const updateStatus = react.useCallback((next) => {
26
41
  statusRef.current = next;
27
42
  setStatus(next);
@@ -48,6 +63,8 @@ function useRunStream(config) {
48
63
  );
49
64
  const connect = react.useCallback(() => {
50
65
  if (!mountedRef.current) return;
66
+ if (!runId || !apiBase) return;
67
+ manualDisconnectRef.current = false;
51
68
  updateStatus("connecting");
52
69
  const wsUrl = apiBase.replace(/^http/, "ws") + `/api/participant/runs/${runId}/stream`;
53
70
  const params = new URLSearchParams({ token: participantToken });
@@ -82,6 +99,7 @@ function useRunStream(config) {
82
99
  ws.onclose = () => {
83
100
  if (!mountedRef.current) return;
84
101
  wsRef.current = null;
102
+ if (manualDisconnectRef.current) return;
85
103
  if (!TERMINAL_STATUSES.includes(statusRef.current)) {
86
104
  const isOffline = typeof navigator !== "undefined" && !navigator.onLine || reconnectAttemptsRef.current >= MAX_RECONNECT_ATTEMPTS;
87
105
  if (isOffline) {
@@ -94,7 +112,8 @@ function useRunStream(config) {
94
112
  };
95
113
  }, [runId, participantToken, apiBase]);
96
114
  function handleEvent(event) {
97
- var _a, _b, _c, _d;
115
+ var _a, _b, _c, _d, _e;
116
+ (_a = onEventRef.current) == null ? void 0 : _a.call(onEventRef, event);
98
117
  switch (event.type) {
99
118
  case "timeline.replay": {
100
119
  mergeTimeline(event.payload);
@@ -131,7 +150,7 @@ function useRunStream(config) {
131
150
  entry_context: event.entry_context,
132
151
  status: "open",
133
152
  messages: replayedMessages,
134
- document_content: (_a = event.document_content) != null ? _a : null
153
+ document_content: (_b = event.document_content) != null ? _b : null
135
154
  };
136
155
  setActiveSession(session);
137
156
  if (replayedMessages.length > 0) {
@@ -144,7 +163,7 @@ function useRunStream(config) {
144
163
  } else if (event.layout === "form") {
145
164
  updateStatus("awaiting_form");
146
165
  } else {
147
- const surface = (_b = event.entry_context) == null ? void 0 : _b.surface;
166
+ const surface = (_c = event.entry_context) == null ? void 0 : _c.surface;
148
167
  const isVoice = typeof surface === "string" && (surface === "widget/voice" || surface === "phone" || surface === "phone/outbound");
149
168
  if (isVoice) {
150
169
  updateStatus("awaiting_voice");
@@ -169,13 +188,14 @@ function useRunStream(config) {
169
188
  case "run.completed":
170
189
  case "run.cancelled":
171
190
  setStreamingText("");
191
+ if (event.state) setOutput(event.state);
172
192
  updateStatus("completed");
173
- (_c = wsRef.current) == null ? void 0 : _c.close();
193
+ (_d = wsRef.current) == null ? void 0 : _d.close();
174
194
  break;
175
195
  case "run.failed":
176
196
  setStreamingText("");
177
197
  updateStatus("error");
178
- (_d = wsRef.current) == null ? void 0 : _d.close();
198
+ (_e = wsRef.current) == null ? void 0 : _e.close();
179
199
  break;
180
200
  }
181
201
  }
@@ -223,10 +243,10 @@ function useRunStream(config) {
223
243
  [activeSession, apiBase, authHeaders, updateStatus]
224
244
  );
225
245
  const submitHandback = react.useCallback(
226
- async (output, idempotencyKey) => {
246
+ async (output2, idempotencyKey) => {
227
247
  var _a;
228
248
  if (!activeSession) return null;
229
- const body = { output };
249
+ const body = { output: output2 };
230
250
  if (idempotencyKey) body.idempotency_key = idempotencyKey;
231
251
  let res;
232
252
  try {
@@ -260,6 +280,20 @@ function useRunStream(config) {
260
280
  },
261
281
  [activeSession, apiBase, authHeaders, updateStatus]
262
282
  );
283
+ const disconnect = react.useCallback(() => {
284
+ var _a;
285
+ manualDisconnectRef.current = true;
286
+ if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
287
+ (_a = wsRef.current) == null ? void 0 : _a.close();
288
+ wsRef.current = null;
289
+ updateStatus("offline");
290
+ }, [updateStatus]);
291
+ const reconnect = react.useCallback(() => {
292
+ if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
293
+ reconnectAttemptsRef.current = 0;
294
+ manualDisconnectRef.current = false;
295
+ connect();
296
+ }, [connect]);
263
297
  return {
264
298
  status,
265
299
  activeSession,
@@ -267,8 +301,11 @@ function useRunStream(config) {
267
301
  timeline,
268
302
  lastSeq,
269
303
  streamingText,
304
+ output,
270
305
  sendMessage,
271
- submitHandback
306
+ submitHandback,
307
+ disconnect,
308
+ reconnect
272
309
  };
273
310
  }
274
311
  function useParticipantConnections(runId, participantToken, apiBase = "http://localhost:8080") {
@@ -340,7 +377,16 @@ function useParticipantConnections(runId, participantToken, apiBase = "http://lo
340
377
 
341
378
  // src/styles/widget.module.css
342
379
  var widget_default = {
380
+ cfDark: "widget_cfDark",
381
+ cfAuto: "widget_cfAuto",
343
382
  widget: "widget_widget",
383
+ launcherRoot: "widget_launcherRoot",
384
+ launcherRootRight: "widget_launcherRootRight",
385
+ launcherRootLeft: "widget_launcherRootLeft",
386
+ launcherButton: "widget_launcherButton",
387
+ launcherIcon: "widget_launcherIcon",
388
+ launcherBadge: "widget_launcherBadge",
389
+ launcherPanel: "widget_launcherPanel",
344
390
  statusWrapper: "widget_statusWrapper",
345
391
  statusLabel: "widget_statusLabel",
346
392
  statusTitle: "widget_statusTitle",
@@ -446,6 +492,7 @@ var widget_default = {
446
492
  converseHint: "widget_converseHint",
447
493
  converseHintDot: "widget_converseHintDot",
448
494
  "cf-converse-pulse": "widget_cf-converse-pulse",
495
+ converseDoneButton: "widget_converseDoneButton",
449
496
  newMessageChip: "widget_newMessageChip",
450
497
  activeInputRow: "widget_activeInputRow",
451
498
  activeInputField: "widget_activeInputField",
@@ -806,6 +853,12 @@ function DocumentCard({ content, descriptor }) {
806
853
  )) })
807
854
  ] });
808
855
  }
856
+ function DefaultBotBubble({ children }) {
857
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.bubbleBot, children });
858
+ }
859
+ function DefaultUserBubble({ children }) {
860
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.bubbleUser, children });
861
+ }
809
862
  function FormDataView({
810
863
  data,
811
864
  depth = 0
@@ -945,7 +998,10 @@ function entryToDisplay(entry) {
945
998
  return null;
946
999
  }
947
1000
  }
948
- function ChatTimeline({ entries, showTyping, streamingText }) {
1001
+ function ChatTimeline({ entries, showTyping, streamingText, components }) {
1002
+ var _a, _b;
1003
+ const BotBubble = (_a = components == null ? void 0 : components.BotBubble) != null ? _a : DefaultBotBubble;
1004
+ const UserBubble = (_b = components == null ? void 0 : components.UserBubble) != null ? _b : DefaultUserBubble;
949
1005
  const containerRef = react.useRef(null);
950
1006
  const prevLengthRef = react.useRef(0);
951
1007
  const prevShowTypingRef = react.useRef(false);
@@ -1061,7 +1117,7 @@ function ChatTimeline({ entries, showTyping, streamingText }) {
1061
1117
  )
1062
1118
  ] }, t)) }) : /* @__PURE__ */ jsxRuntime.jsx(MarkdownBubble, { content: display.text });
1063
1119
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.bubbleUserRow, children: [
1064
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.bubbleUser, children: userContent }),
1120
+ /* @__PURE__ */ jsxRuntime.jsx(UserBubble, { children: userContent }),
1065
1121
  /* @__PURE__ */ jsxRuntime.jsx(
1066
1122
  "div",
1067
1123
  {
@@ -1074,7 +1130,7 @@ function ChatTimeline({ entries, showTyping, streamingText }) {
1074
1130
  }
1075
1131
  const content = display.format !== "text" ? /* @__PURE__ */ jsxRuntime.jsx(MarkdownBubble, { content: display.text }) : display.text;
1076
1132
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.bubbleRow, children: [
1077
- display.document ? /* @__PURE__ */ jsxRuntime.jsx(DocumentCard, { content: display.text, descriptor: display.document }) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.bubbleBot, children: content }),
1133
+ display.document ? /* @__PURE__ */ jsxRuntime.jsx(DocumentCard, { content: display.text, descriptor: display.document }) : /* @__PURE__ */ jsxRuntime.jsx(BotBubble, { children: content }),
1078
1134
  /* @__PURE__ */ jsxRuntime.jsx(
1079
1135
  "div",
1080
1136
  {
@@ -2614,38 +2670,62 @@ function FormRenderer({
2614
2670
  ) })
2615
2671
  ] });
2616
2672
  }
2617
- function StatusDisplay({ status, error }) {
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
+ function StatusDisplay({ status, error, strings }) {
2697
+ const t = strings ? { ...defaultStrings, ...strings } : defaultStrings;
2618
2698
  switch (status) {
2619
2699
  case "idle":
2620
2700
  case "connecting":
2621
2701
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.statusWrapper, children: [
2622
2702
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.spinner }),
2623
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.statusLabel, children: status === "idle" ? "Initialising\u2026" : "Connecting\u2026" })
2703
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.statusLabel, children: status === "idle" ? t.statusInitialising : t.statusConnecting })
2624
2704
  ] });
2625
2705
  case "running":
2626
2706
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.statusWrapper, children: [
2627
2707
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.progressBar, children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.progressBarFill }) }),
2628
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.statusLabel, children: "Running\u2026" })
2708
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.statusLabel, children: t.statusRunning })
2629
2709
  ] });
2630
2710
  case "completed":
2631
2711
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.statusWrapper, children: [
2632
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.statusTitle, children: "Completed" }),
2633
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.statusLabel, children: "This workflow run has finished." })
2712
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.statusTitle, children: t.statusCompletedTitle }),
2713
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.statusLabel, children: t.statusCompletedBody })
2634
2714
  ] });
2635
2715
  case "error":
2636
2716
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.statusWrapper, children: [
2637
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: "Something went wrong" }),
2717
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: t.statusErrorTitle }),
2638
2718
  error && /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.statusLabel} ${widget_default.statusError}`, children: error })
2639
2719
  ] });
2640
2720
  case "offline":
2641
2721
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.statusWrapper, children: [
2642
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: "Connection lost" }),
2643
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.statusLabel} ${widget_default.statusError}`, children: "Unable to reach the server. Please check your connection and refresh." })
2722
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: t.statusOfflineTitle }),
2723
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: `${widget_default.statusLabel} ${widget_default.statusError}`, children: t.statusOfflineBody })
2644
2724
  ] });
2645
2725
  case "awaiting_voice":
2646
2726
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.statusWrapper, children: [
2647
2727
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.spinner, "aria-hidden": true }),
2648
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.statusLabel, children: "Listening\u2026" })
2728
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.statusLabel, children: t.statusListening })
2649
2729
  ] });
2650
2730
  default:
2651
2731
  return null;
@@ -5701,480 +5781,588 @@ function stripForSpeech(text) {
5701
5781
  return text.replace(/[\p{Emoji_Presentation}\p{Extended_Pictographic}]/gu, "").replace(/\s+/g, " ").trim();
5702
5782
  }
5703
5783
  var SPEECH_SETTLE_MS = 300;
5704
- function ChatAdapter({
5705
- runId,
5706
- participantToken,
5707
- apiBase,
5708
- className,
5709
- onCompleted,
5710
- onError,
5711
- autoFocusInput
5712
- }) {
5713
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
5714
- const apiBaseResolved = apiBase != null ? apiBase : "http://localhost:8080";
5715
- const appBaseResolved = typeof window !== "undefined" ? window.location.origin : (_a = process.env.APP_URL) != null ? _a : "http://localhost:3000";
5716
- const {
5717
- status,
5718
- activeSession,
5719
- timeline,
5720
- submitHandback,
5721
- sendMessage,
5722
- messages,
5723
- streamingText
5724
- } = useRunStream({ runId, participantToken, apiBase });
5725
- const {
5726
- connections: requiredConnections,
5727
- allProvided: allConnectionsProvided,
5728
- loading: connectionsLoading,
5729
- refresh: refreshConnections,
5730
- disconnect: disconnectConnection
5731
- } = useParticipantConnections(runId, participantToken, apiBaseResolved);
5732
- const [connectionOnboardingDismissed, setConnectionOnboardingDismissed] = react.useState(false);
5733
- react.useEffect(() => {
5734
- const params = new URLSearchParams(window.location.search);
5735
- if (params.has("connected") || params.has("connect_error")) {
5736
- refreshConnections();
5737
- const url = new URL(window.location.href);
5738
- url.searchParams.delete("connected");
5739
- url.searchParams.delete("connect_error");
5740
- window.history.replaceState({}, "", url.toString());
5741
- }
5742
- }, [refreshConnections]);
5743
- const [inputValue, setInputValue] = react.useState(void 0);
5744
- const [inputError, setInputError] = react.useState(null);
5745
- const [serverErrors, setServerErrors] = react.useState([]);
5746
- const [submitting, setSubmitting] = react.useState(false);
5747
- const [handbackValues, setHandbackValues] = react.useState({});
5748
- const voiceServerCfg = react.useMemo(() => {
5749
- var _a2;
5750
- if (!activeSession) return void 0;
5751
- if (extractSurface(activeSession) === "widget/voice" && ((_a2 = extractSurfaceConfig(activeSession)) == null ? void 0 : _a2.tts) === "server") {
5752
- return { apiBase: apiBaseResolved, participantToken };
5753
- }
5754
- return void 0;
5755
- }, [activeSession, apiBaseResolved, participantToken]);
5756
- const { speak: rawSpeak, cancel: rawCancel } = useSpeechSynthesis(voiceServerCfg);
5757
- const [isSpeaking, setIsSpeaking] = react.useState(false);
5758
- const speechQueueRef = react.useRef([]);
5759
- const drainingRef = react.useRef(false);
5760
- const speechGenRef = react.useRef(0);
5761
- const drainSpeech = react.useCallback(async () => {
5762
- if (drainingRef.current) return;
5763
- drainingRef.current = true;
5764
- const myGen = speechGenRef.current;
5765
- setIsSpeaking(true);
5766
- while (true) {
5767
- if (speechGenRef.current !== myGen) return;
5768
- const item = speechQueueRef.current.shift();
5769
- if (item) {
5770
- try {
5771
- await rawSpeak(item.text);
5772
- } catch {
5773
- }
5774
- item.resolve();
5775
- continue;
5776
- }
5777
- await new Promise((r) => setTimeout(r, SPEECH_SETTLE_MS));
5778
- if (speechGenRef.current !== myGen) return;
5779
- if (speechQueueRef.current.length === 0) break;
5780
- }
5781
- drainingRef.current = false;
5782
- setIsSpeaking(false);
5783
- }, [rawSpeak]);
5784
- const enqueueSpeak = react.useCallback(
5785
- (text) => {
5786
- const t = stripForSpeech(text != null ? text : "");
5787
- if (!t) return Promise.resolve();
5788
- return new Promise((resolve) => {
5789
- speechQueueRef.current.push({ text: t, resolve });
5790
- void drainSpeech();
5791
- });
5792
- },
5793
- [drainSpeech]
5794
- );
5795
- const clearSpeech = react.useCallback(() => {
5796
- speechGenRef.current += 1;
5797
- for (const item of speechQueueRef.current) item.resolve();
5798
- speechQueueRef.current = [];
5799
- rawCancel();
5800
- drainingRef.current = false;
5801
- setIsSpeaking(false);
5802
- }, [rawCancel]);
5803
- const spokenMessageSeqsRef = react.useRef(/* @__PURE__ */ new Set());
5804
- const [isVoiceSurface, setIsVoiceSurface] = react.useState(false);
5805
- if (!isVoiceSurface && activeSession && extractSurface(activeSession) === "widget/voice") {
5806
- setIsVoiceSurface(true);
5784
+ function themeToStyle(theme) {
5785
+ if (!theme) return {};
5786
+ const map = {
5787
+ primary: "--cf-primary",
5788
+ accent: "--cf-accent",
5789
+ info: "--cf-info",
5790
+ bg: "--cf-bg",
5791
+ fg: "--cf-fg",
5792
+ muted: "--cf-muted",
5793
+ border: "--cf-border",
5794
+ surface: "--cf-surface",
5795
+ error: "--cf-error",
5796
+ radius: "--cf-radius",
5797
+ font: "--cf-font",
5798
+ height: "--cf-height",
5799
+ bubbleBotBg: "--cf-bubble-bot-bg",
5800
+ bubbleBotFg: "--cf-bubble-bot-fg",
5801
+ bubbleUserBg: "--cf-bubble-user-bg",
5802
+ bubbleUserFg: "--cf-bubble-user-fg",
5803
+ headerBg: "--cf-header-bg",
5804
+ headerFg: "--cf-header-fg",
5805
+ inputBg: "--cf-input-bg",
5806
+ shadow: "--cf-shadow",
5807
+ spacing: "--cf-spacing",
5808
+ avatarSize: "--cf-avatar-size"
5809
+ };
5810
+ const style = {};
5811
+ for (const key of Object.keys(map)) {
5812
+ const value = theme[key];
5813
+ if (value !== void 0) style[map[key]] = value;
5807
5814
  }
5808
- const voiceSessionId = (_b = activeSession == null ? void 0 : activeSession.id) != null ? _b : null;
5809
- const prevVoiceSessionIdRef = react.useRef(null);
5810
- react.useEffect(() => {
5811
- if (!isVoiceSurface) return;
5812
- const prev = prevVoiceSessionIdRef.current;
5813
- if (prev && voiceSessionId && prev !== voiceSessionId) {
5814
- clearSpeech();
5815
- }
5816
- prevVoiceSessionIdRef.current = voiceSessionId;
5817
- }, [voiceSessionId, isVoiceSurface, clearSpeech]);
5818
- react.useEffect(() => {
5819
- if (!isVoiceSurface) return;
5820
- for (const entry of timeline) {
5821
- if (entry.event_type !== "message") continue;
5822
- if (entry.sender === "user") continue;
5823
- if (spokenMessageSeqsRef.current.has(entry.seq)) continue;
5824
- spokenMessageSeqsRef.current.add(entry.seq);
5825
- const text = entry.payload.voice_hint || entry.payload.content || "";
5826
- void enqueueSpeak(text);
5827
- }
5828
- }, [timeline, isVoiceSurface, enqueueSpeak]);
5829
- const completedFiredRef = react.useRef(false);
5830
- const errorFiredRef = react.useRef(false);
5831
- const inputAreaRef = react.useRef(null);
5832
- const lastFocusedSessionRef = react.useRef(null);
5833
- const activeSessionId = (_c = activeSession == null ? void 0 : activeSession.id) != null ? _c : null;
5834
- react.useEffect(() => {
5835
- if (!autoFocusInput) return;
5836
- if (!activeSessionId) return;
5837
- if (lastFocusedSessionRef.current === activeSessionId) return;
5838
- const root = inputAreaRef.current;
5839
- if (!root) return;
5840
- const focusable = root.querySelector(
5841
- "input:not([type=hidden]):not([disabled]), textarea:not([disabled]), select:not([disabled]), [contenteditable=true]"
5842
- );
5843
- if (focusable) {
5844
- focusable.focus({ preventScroll: true });
5845
- lastFocusedSessionRef.current = activeSessionId;
5846
- }
5847
- }, [autoFocusInput, activeSessionId, status]);
5848
- react.useEffect(() => {
5849
- if (status === "completed" && !completedFiredRef.current) {
5850
- completedFiredRef.current = true;
5851
- onCompleted == null ? void 0 : onCompleted();
5852
- }
5853
- if (status === "error" && !errorFiredRef.current) {
5854
- errorFiredRef.current = true;
5855
- onError == null ? void 0 : onError("The run encountered an error.");
5856
- }
5857
- }, [status, onCompleted, onError]);
5858
- const cls = [widget_default.widget, className].filter(Boolean).join(" ");
5859
- const showTyping = status === "running" && timeline.length > 0 && !streamingText;
5860
- const handleSubmit = react.useCallback(
5861
- async (e, valueOverride) => {
5862
- e == null ? void 0 : e.preventDefault();
5863
- if (!activeSession) return;
5864
- const valueToSubmit = valueOverride !== void 0 ? valueOverride : inputValue;
5865
- const field2 = extractField(activeSession);
5866
- if (field2) {
5867
- const clientErr = validate(valueToSubmit, field2.validation);
5868
- if (clientErr) {
5869
- setInputError(clientErr);
5870
- return;
5815
+ return style;
5816
+ }
5817
+ var ChatAdapter = react.forwardRef(
5818
+ function ChatAdapter2({
5819
+ runId,
5820
+ participantToken,
5821
+ apiBase,
5822
+ className,
5823
+ onCompleted,
5824
+ onError,
5825
+ onEvent,
5826
+ onStatusChange,
5827
+ onSessionOpened,
5828
+ onMessage,
5829
+ autoFocusInput,
5830
+ loadingFallback,
5831
+ theme,
5832
+ colorScheme,
5833
+ header,
5834
+ footer,
5835
+ emptyState,
5836
+ completedState,
5837
+ errorState,
5838
+ components,
5839
+ strings
5840
+ }, ref) {
5841
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
5842
+ const t = resolveStrings(strings);
5843
+ const apiBaseResolved = apiBase;
5844
+ const appBaseResolved = typeof window !== "undefined" ? window.location.origin : (_a = process.env.APP_URL) != null ? _a : "http://localhost:3000";
5845
+ const onEventFirehose = react.useCallback(
5846
+ (event) => {
5847
+ var _a2;
5848
+ onEvent == null ? void 0 : onEvent(event);
5849
+ if (event.type === "hitl.session_opened") {
5850
+ onSessionOpened == null ? void 0 : onSessionOpened({
5851
+ id: event.session_id,
5852
+ step_id: event.step_id,
5853
+ counterparty: event.counterparty,
5854
+ layout: event.layout,
5855
+ entry_context: event.entry_context,
5856
+ status: "open",
5857
+ messages: Array.isArray(event.messages) ? event.messages : [],
5858
+ document_content: (_a2 = event.document_content) != null ? _a2 : null
5859
+ });
5860
+ } else if (event.type === "message.sent") {
5861
+ onMessage == null ? void 0 : onMessage({ role: "assistant", content: event.content });
5871
5862
  }
5863
+ },
5864
+ [onEvent, onSessionOpened, onMessage]
5865
+ );
5866
+ const {
5867
+ status,
5868
+ activeSession,
5869
+ timeline,
5870
+ submitHandback,
5871
+ sendMessage,
5872
+ messages,
5873
+ streamingText,
5874
+ output,
5875
+ disconnect,
5876
+ reconnect
5877
+ } = useRunStream({ runId, participantToken, apiBase }, onEventFirehose);
5878
+ react.useImperativeHandle(
5879
+ ref,
5880
+ () => ({
5881
+ restart: reconnect,
5882
+ disconnect,
5883
+ sendMessage: (text) => void sendMessage(text)
5884
+ }),
5885
+ [reconnect, disconnect, sendMessage]
5886
+ );
5887
+ const prevStatusRef = react.useRef(null);
5888
+ react.useEffect(() => {
5889
+ if (prevStatusRef.current === status) return;
5890
+ prevStatusRef.current = status;
5891
+ onStatusChange == null ? void 0 : onStatusChange(status);
5892
+ }, [status, onStatusChange]);
5893
+ const {
5894
+ connections: requiredConnections,
5895
+ allProvided: allConnectionsProvided,
5896
+ loading: connectionsLoading,
5897
+ refresh: refreshConnections,
5898
+ disconnect: disconnectConnection
5899
+ } = useParticipantConnections(runId, participantToken, apiBaseResolved);
5900
+ const [connectionOnboardingDismissed, setConnectionOnboardingDismissed] = react.useState(false);
5901
+ react.useEffect(() => {
5902
+ const params = new URLSearchParams(window.location.search);
5903
+ if (params.has("connected") || params.has("connect_error")) {
5904
+ refreshConnections();
5905
+ const url = new URL(window.location.href);
5906
+ url.searchParams.delete("connected");
5907
+ url.searchParams.delete("connect_error");
5908
+ window.history.replaceState({}, "", url.toString());
5872
5909
  }
5873
- setSubmitting(true);
5874
- setInputError(null);
5875
- setServerErrors([]);
5876
- try {
5877
- const idempotencyKey = crypto.randomUUID();
5878
- const errors = await submitHandback(valueToSubmit, idempotencyKey);
5879
- if (errors) {
5880
- setServerErrors(errors);
5881
- if (errors.length > 0) {
5882
- setInputError(errors[0].message);
5910
+ }, [refreshConnections]);
5911
+ const [inputValue, setInputValue] = react.useState(void 0);
5912
+ const [inputError, setInputError] = react.useState(null);
5913
+ const [serverErrors, setServerErrors] = react.useState([]);
5914
+ const [submitting, setSubmitting] = react.useState(false);
5915
+ const [handbackValues, setHandbackValues] = react.useState({});
5916
+ const voiceServerCfg = react.useMemo(() => {
5917
+ var _a2;
5918
+ if (!activeSession) return void 0;
5919
+ if (extractSurface(activeSession) === "widget/voice" && ((_a2 = extractSurfaceConfig(activeSession)) == null ? void 0 : _a2.tts) === "server") {
5920
+ return { apiBase: apiBaseResolved, participantToken };
5921
+ }
5922
+ return void 0;
5923
+ }, [activeSession, apiBaseResolved, participantToken]);
5924
+ const { speak: rawSpeak, cancel: rawCancel } = useSpeechSynthesis(voiceServerCfg);
5925
+ const [isSpeaking, setIsSpeaking] = react.useState(false);
5926
+ const speechQueueRef = react.useRef([]);
5927
+ const drainingRef = react.useRef(false);
5928
+ const speechGenRef = react.useRef(0);
5929
+ const drainSpeech = react.useCallback(async () => {
5930
+ if (drainingRef.current) return;
5931
+ drainingRef.current = true;
5932
+ const myGen = speechGenRef.current;
5933
+ setIsSpeaking(true);
5934
+ while (true) {
5935
+ if (speechGenRef.current !== myGen) return;
5936
+ const item = speechQueueRef.current.shift();
5937
+ if (item) {
5938
+ try {
5939
+ await rawSpeak(item.text);
5940
+ } catch {
5883
5941
  }
5884
- } else {
5885
- setInputValue(void 0);
5886
- setInputError(null);
5887
- setServerErrors([]);
5942
+ item.resolve();
5943
+ continue;
5888
5944
  }
5889
- } finally {
5890
- setSubmitting(false);
5891
- }
5892
- },
5893
- [activeSession, inputValue, submitHandback]
5894
- );
5895
- const handleAutoSubmit = react.useCallback(
5896
- (autoValue) => {
5897
- void handleSubmit(void 0, autoValue);
5898
- },
5899
- [handleSubmit]
5900
- );
5901
- if (status === "idle" || status === "connecting") {
5902
- return /* @__PURE__ */ jsxRuntime.jsx("div", { className: cls, children: /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status }) });
5903
- }
5904
- if (status === "replaying") {
5905
- return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cls, children: [
5906
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.resumingBanner, children: [
5907
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.spinner }),
5908
- "Resuming conversation\u2026"
5909
- ] }),
5910
- /* @__PURE__ */ jsxRuntime.jsx(ChatTimeline, { entries: timeline, streamingText })
5911
- ] });
5912
- }
5913
- if (status === "completed" || status === "error") {
5914
- const hasChatContent = timeline.some(
5915
- (e) => {
5916
- var _a2, _b2;
5917
- return e.event_type === "message" || e.event_type === "prompt" && ((_a2 = e.payload) == null ? void 0 : _a2.layout) !== "form" || e.event_type === "response" && ((_b2 = e.payload) == null ? void 0 : _b2.layout) !== "form";
5945
+ await new Promise((r) => setTimeout(r, SPEECH_SETTLE_MS));
5946
+ if (speechGenRef.current !== myGen) return;
5947
+ if (speechQueueRef.current.length === 0) break;
5918
5948
  }
5949
+ drainingRef.current = false;
5950
+ setIsSpeaking(false);
5951
+ }, [rawSpeak]);
5952
+ const enqueueSpeak = react.useCallback(
5953
+ (text) => {
5954
+ const t2 = stripForSpeech(text != null ? text : "");
5955
+ if (!t2) return Promise.resolve();
5956
+ return new Promise((resolve) => {
5957
+ speechQueueRef.current.push({ text: t2, resolve });
5958
+ void drainSpeech();
5959
+ });
5960
+ },
5961
+ [drainSpeech]
5919
5962
  );
5920
- return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cls, children: [
5921
- hasChatContent && /* @__PURE__ */ jsxRuntime.jsx(ChatTimeline, { entries: timeline, streamingText }),
5922
- status === "completed" && /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.terminalCompleted, children: "Conversation completed." }),
5923
- status === "error" && /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.terminalError, children: "Something went wrong" })
5924
- ] });
5925
- }
5926
- if (status === "awaiting_form" && activeSession) {
5927
- const ctx = activeSession.entry_context;
5928
- const formSpec = ctx.form_spec;
5929
- return /* @__PURE__ */ jsxRuntime.jsx("div", { className: cls, children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.formScrollArea, children: /* @__PURE__ */ jsxRuntime.jsx(
5930
- FormRenderer,
5931
- {
5932
- fields: formSpec == null ? void 0 : formSpec.fields,
5933
- repeater: (_d = formSpec == null ? void 0 : formSpec.repeaters) == null ? void 0 : _d[0],
5934
- onSubmit: (values) => void submitHandback(values),
5935
- disabled: submitting
5963
+ const clearSpeech = react.useCallback(() => {
5964
+ speechGenRef.current += 1;
5965
+ for (const item of speechQueueRef.current) item.resolve();
5966
+ speechQueueRef.current = [];
5967
+ rawCancel();
5968
+ drainingRef.current = false;
5969
+ setIsSpeaking(false);
5970
+ }, [rawCancel]);
5971
+ const spokenMessageSeqsRef = react.useRef(/* @__PURE__ */ new Set());
5972
+ const [isVoiceSurface, setIsVoiceSurface] = react.useState(false);
5973
+ if (!isVoiceSurface && activeSession && extractSurface(activeSession) === "widget/voice") {
5974
+ setIsVoiceSurface(true);
5975
+ }
5976
+ const voiceSessionId = (_b = activeSession == null ? void 0 : activeSession.id) != null ? _b : null;
5977
+ const prevVoiceSessionIdRef = react.useRef(null);
5978
+ react.useEffect(() => {
5979
+ if (!isVoiceSurface) return;
5980
+ const prev = prevVoiceSessionIdRef.current;
5981
+ if (prev && voiceSessionId && prev !== voiceSessionId) {
5982
+ clearSpeech();
5936
5983
  }
5937
- ) }) });
5938
- }
5939
- if (status === "awaiting_editor" && activeSession) {
5940
- const editorCtx = activeSession.entry_context;
5941
- const isImageSession = (editorCtx == null ? void 0 : editorCtx.document_type) === "image";
5942
- return /* @__PURE__ */ jsxRuntime.jsx("div", { className: cls, children: isImageSession ? /* @__PURE__ */ jsxRuntime.jsx(
5943
- ImageEditorRenderer,
5944
- {
5945
- session: activeSession,
5946
- onHandback: (output) => submitHandback(output).then(() => void 0),
5947
- apiBase: apiBaseResolved,
5948
- participantToken,
5949
- disabled: submitting
5984
+ prevVoiceSessionIdRef.current = voiceSessionId;
5985
+ }, [voiceSessionId, isVoiceSurface, clearSpeech]);
5986
+ react.useEffect(() => {
5987
+ if (!isVoiceSurface) return;
5988
+ for (const entry of timeline) {
5989
+ if (entry.event_type !== "message") continue;
5990
+ if (entry.sender === "user") continue;
5991
+ if (spokenMessageSeqsRef.current.has(entry.seq)) continue;
5992
+ spokenMessageSeqsRef.current.add(entry.seq);
5993
+ const text = entry.payload.voice_hint || entry.payload.content || "";
5994
+ void enqueueSpeak(text);
5950
5995
  }
5951
- ) : /* @__PURE__ */ jsxRuntime.jsx(
5952
- EditorRenderer,
5953
- {
5954
- session: activeSession,
5955
- onHandback: (output) => submitHandback(output).then(() => void 0),
5956
- apiBase: apiBaseResolved,
5957
- participantToken,
5958
- disabled: submitting
5996
+ }, [timeline, isVoiceSurface, enqueueSpeak]);
5997
+ const completedFiredRef = react.useRef(false);
5998
+ const errorFiredRef = react.useRef(false);
5999
+ const inputAreaRef = react.useRef(null);
6000
+ const lastFocusedSessionRef = react.useRef(null);
6001
+ const activeSessionId = (_c = activeSession == null ? void 0 : activeSession.id) != null ? _c : null;
6002
+ react.useEffect(() => {
6003
+ if (!autoFocusInput) return;
6004
+ if (!activeSessionId) return;
6005
+ if (lastFocusedSessionRef.current === activeSessionId) return;
6006
+ const root = inputAreaRef.current;
6007
+ if (!root) return;
6008
+ const focusable = root.querySelector(
6009
+ "input:not([type=hidden]):not([disabled]), textarea:not([disabled]), select:not([disabled]), [contenteditable=true]"
6010
+ );
6011
+ if (focusable) {
6012
+ focusable.focus({ preventScroll: true });
6013
+ lastFocusedSessionRef.current = activeSessionId;
5959
6014
  }
5960
- ) });
5961
- }
5962
- if (status === "awaiting_chat" && activeSession) {
5963
- const hbCtx = (_e = activeSession.entry_context) == null ? void 0 : _e.handback;
5964
- const outputSchema = hbCtx == null ? void 0 : hbCtx.output_schema;
5965
- const requireOutput = (_f = hbCtx == null ? void 0 : hbCtx.require_output) != null ? _f : false;
5966
- const handbackReady = !requireOutput || outputSchema != null && Object.keys(outputSchema).every((k) => {
5967
- var _a2;
5968
- return ((_a2 = handbackValues[k]) != null ? _a2 : "").trim() !== "";
5969
- });
5970
- return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cls, children: [
5971
- /* @__PURE__ */ jsxRuntime.jsx(ChatTimeline, { entries: timeline, streamingText }),
5972
- /* @__PURE__ */ jsxRuntime.jsxs("div", { ref: inputAreaRef, className: widget_default.chatInputRow, children: [
5973
- /* @__PURE__ */ jsxRuntime.jsx(
5974
- "textarea",
5975
- {
5976
- className: widget_default.chatInput,
5977
- placeholder: "Type a message\u2026",
5978
- value: inputValue != null ? inputValue : "",
5979
- onChange: (e) => {
5980
- setInputValue(e.target.value);
5981
- setInputError(null);
5982
- },
5983
- onKeyDown: (e) => {
5984
- if (e.key === "Enter" && !e.shiftKey) {
5985
- e.preventDefault();
5986
- if (inputValue) {
5987
- void sendMessage(inputValue);
5988
- setInputValue(void 0);
5989
- }
5990
- }
5991
- },
5992
- disabled: submitting,
5993
- rows: 1
6015
+ }, [autoFocusInput, activeSessionId, status]);
6016
+ react.useEffect(() => {
6017
+ if (status === "completed" && !completedFiredRef.current) {
6018
+ completedFiredRef.current = true;
6019
+ onCompleted == null ? void 0 : onCompleted(output != null ? output : void 0);
6020
+ }
6021
+ if (status === "error" && !errorFiredRef.current) {
6022
+ errorFiredRef.current = true;
6023
+ onError == null ? void 0 : onError(new WidgetError("run_failed", "The run encountered an error."));
6024
+ }
6025
+ }, [status, output, onCompleted, onError]);
6026
+ const colorSchemeClass = colorScheme === "dark" ? widget_default.cfDark : colorScheme === "auto" ? widget_default.cfAuto : void 0;
6027
+ const cls = [widget_default.widget, colorSchemeClass, className].filter(Boolean).join(" ");
6028
+ const rootStyle = react.useMemo(() => themeToStyle(theme), [theme]);
6029
+ const showTyping = status === "running" && timeline.length > 0 && !streamingText;
6030
+ const handleSubmit = react.useCallback(
6031
+ async (e, valueOverride) => {
6032
+ e == null ? void 0 : e.preventDefault();
6033
+ if (!activeSession) return;
6034
+ const valueToSubmit = valueOverride !== void 0 ? valueOverride : inputValue;
6035
+ const field2 = extractField(activeSession);
6036
+ if (field2) {
6037
+ const clientErr = validate(valueToSubmit, field2.validation);
6038
+ if (clientErr) {
6039
+ setInputError(clientErr);
6040
+ return;
5994
6041
  }
5995
- ),
5996
- /* @__PURE__ */ jsxRuntime.jsx(
5997
- "button",
5998
- {
5999
- className: widget_default.chatSendButton,
6000
- disabled: submitting || !inputValue,
6001
- onClick: () => {
6002
- if (inputValue) {
6003
- void sendMessage(inputValue);
6004
- setInputValue(void 0);
6005
- }
6006
- },
6007
- children: "Send"
6042
+ }
6043
+ setSubmitting(true);
6044
+ setInputError(null);
6045
+ setServerErrors([]);
6046
+ try {
6047
+ const idempotencyKey = crypto.randomUUID();
6048
+ const errors = await submitHandback(valueToSubmit, idempotencyKey);
6049
+ if (errors) {
6050
+ setServerErrors(errors);
6051
+ if (errors.length > 0) {
6052
+ setInputError(errors[0].message);
6053
+ }
6054
+ } else {
6055
+ setInputValue(void 0);
6056
+ setInputError(null);
6057
+ setServerErrors([]);
6008
6058
  }
6009
- )
6010
- ] }),
6011
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.handbackSection, children: [
6012
- outputSchema != null && /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.handbackForm, children: Object.entries(outputSchema).map(([key, typeStr]) => {
6059
+ } finally {
6060
+ setSubmitting(false);
6061
+ }
6062
+ },
6063
+ [activeSession, inputValue, submitHandback]
6064
+ );
6065
+ const handleAutoSubmit = react.useCallback(
6066
+ (autoValue) => {
6067
+ void handleSubmit(void 0, autoValue);
6068
+ },
6069
+ [handleSubmit]
6070
+ );
6071
+ if (status === "idle" || status === "connecting") {
6072
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: cls, style: rootStyle, children: loadingFallback != null ? loadingFallback : /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status, strings }) });
6073
+ }
6074
+ if (status === "replaying") {
6075
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cls, style: rootStyle, children: [
6076
+ header,
6077
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.resumingBanner, children: [
6078
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.spinner }),
6079
+ t.resumingConversation
6080
+ ] }),
6081
+ /* @__PURE__ */ jsxRuntime.jsx(ChatTimeline, { entries: timeline, streamingText, components })
6082
+ ] });
6083
+ }
6084
+ if (status === "completed" || status === "error") {
6085
+ const hasChatContent = timeline.some(
6086
+ (e) => {
6013
6087
  var _a2, _b2;
6014
- const isEnum = typeStr.includes("|");
6015
- const options = isEnum ? typeStr.split("|").map((o) => o.trim()) : [];
6016
- const label = key.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
6017
- return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.handbackField, children: [
6018
- /* @__PURE__ */ jsxRuntime.jsx("label", { className: widget_default.handbackFieldLabel, children: label }),
6019
- isEnum ? /* @__PURE__ */ jsxRuntime.jsxs(
6020
- "select",
6021
- {
6022
- className: widget_default.handbackFieldSelect,
6023
- value: (_a2 = handbackValues[key]) != null ? _a2 : "",
6024
- onChange: (e) => setHandbackValues((prev) => ({ ...prev, [key]: e.target.value })),
6025
- disabled: submitting,
6026
- children: [
6027
- /* @__PURE__ */ jsxRuntime.jsx("option", { value: "", disabled: true, children: "Select\u2026" }),
6028
- options.map((opt) => /* @__PURE__ */ jsxRuntime.jsx("option", { value: opt, children: opt }, opt))
6029
- ]
6030
- }
6031
- ) : /* @__PURE__ */ jsxRuntime.jsx(
6032
- "textarea",
6033
- {
6034
- className: widget_default.handbackFieldTextarea,
6035
- value: (_b2 = handbackValues[key]) != null ? _b2 : "",
6036
- onChange: (e) => setHandbackValues((prev) => ({ ...prev, [key]: e.target.value })),
6037
- disabled: submitting,
6038
- rows: 2
6039
- }
6040
- )
6041
- ] }, key);
6042
- }) }),
6043
- /* @__PURE__ */ jsxRuntime.jsx(
6044
- "button",
6045
- {
6046
- className: widget_default.handbackButton,
6047
- onClick: () => void submitHandback(
6048
- outputSchema != null ? handbackValues : void 0
6049
- ),
6050
- disabled: submitting || !handbackReady,
6051
- children: "Hand Back"
6052
- }
6053
- )
6054
- ] })
6055
- ] });
6056
- }
6057
- const field = activeSession ? extractField(activeSession) : null;
6058
- const surface = activeSession ? extractSurface(activeSession) : null;
6059
- const surfaceConfig = activeSession ? extractSurfaceConfig(activeSession) : null;
6060
- const nodeVoice = activeSession ? extractNodeVoice(activeSession) : null;
6061
- const InputComponent = field ? getInputComponent(field.input_type) : null;
6062
- const isConverseSession = ((_g = activeSession == null ? void 0 : activeSession.entry_context) == null ? void 0 : _g.converse_session) === true;
6063
- const effectiveVoiceMode = resolveVoiceMode(surface, surfaceConfig, nodeVoice);
6064
- const shouldUseVoice = effectiveVoiceMode !== "off";
6065
- const voiceRenderer = effectiveVoiceMode === "push_to_talk" ? "click" : "continuous";
6066
- const isLiveVoice = surface === "widget/voice" && (surfaceConfig == null ? void 0 : surfaceConfig.style) === "live";
6067
- if (shouldUseVoice && activeSession && field) {
6068
- const spokenHint = (_i = nodeVoice == null ? void 0 : nodeVoice.hint) != null ? _i : (_h = field.voice) == null ? void 0 : _h.hint;
6069
- const handleVoiceValue = (value) => {
6070
- setInputValue(value);
6071
- void submitHandback(value, crypto.randomUUID());
6072
- };
6073
- const handleLiveValue = (value) => {
6074
- setInputValue(value);
6075
- };
6076
- return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cls, children: [
6077
- /* @__PURE__ */ jsxRuntime.jsx(ChatTimeline, { entries: timeline, showTyping, streamingText }),
6078
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.activeInputArea, children: isLiveVoice ? /* @__PURE__ */ jsxRuntime.jsx(
6079
- VoiceLiveRenderer,
6088
+ return e.event_type === "message" || e.event_type === "prompt" && ((_a2 = e.payload) == null ? void 0 : _a2.layout) !== "form" || e.event_type === "response" && ((_b2 = e.payload) == null ? void 0 : _b2.layout) !== "form";
6089
+ }
6090
+ );
6091
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cls, style: rootStyle, children: [
6092
+ hasChatContent && /* @__PURE__ */ jsxRuntime.jsx(ChatTimeline, { entries: timeline, streamingText, components }),
6093
+ status === "completed" && /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.terminalCompleted, children: completedState != null ? completedState : t.conversationCompleted }),
6094
+ status === "error" && /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.terminalError, children: errorState != null ? errorState : t.somethingWentWrong })
6095
+ ] });
6096
+ }
6097
+ if (status === "awaiting_form" && activeSession) {
6098
+ const ctx = activeSession.entry_context;
6099
+ const formSpec = ctx.form_spec;
6100
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: cls, style: rootStyle, children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.formScrollArea, children: /* @__PURE__ */ jsxRuntime.jsx(
6101
+ FormRenderer,
6080
6102
  {
6081
- field,
6082
- voiceHint: spokenHint,
6083
- apiBase: apiBaseResolved,
6084
- participantToken,
6085
- sessionId: activeSession.id,
6086
- liveConfig: surfaceConfig != null ? surfaceConfig : void 0,
6087
- onValue: handleLiveValue,
6103
+ fields: formSpec == null ? void 0 : formSpec.fields,
6104
+ repeater: (_d = formSpec == null ? void 0 : formSpec.repeaters) == null ? void 0 : _d[0],
6105
+ onSubmit: (values) => void submitHandback(values),
6088
6106
  disabled: submitting
6089
6107
  }
6090
- ) : voiceRenderer === "continuous" ? /* @__PURE__ */ jsxRuntime.jsx(
6091
- VoiceContinuousRenderer,
6108
+ ) }) });
6109
+ }
6110
+ if (status === "awaiting_editor" && activeSession) {
6111
+ const editorCtx = activeSession.entry_context;
6112
+ const isImageSession = (editorCtx == null ? void 0 : editorCtx.document_type) === "image";
6113
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: cls, style: rootStyle, children: isImageSession ? /* @__PURE__ */ jsxRuntime.jsx(
6114
+ ImageEditorRenderer,
6092
6115
  {
6093
- field,
6094
- voiceHint: spokenHint,
6116
+ session: activeSession,
6117
+ onHandback: (output2) => submitHandback(output2).then(() => void 0),
6095
6118
  apiBase: apiBaseResolved,
6096
6119
  participantToken,
6097
- onValue: handleVoiceValue,
6098
- autoSubmitMode: "confirm",
6099
- 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,
6100
- enqueueSpeak,
6101
- isSpeaking,
6102
6120
  disabled: submitting
6103
6121
  }
6104
6122
  ) : /* @__PURE__ */ jsxRuntime.jsx(
6105
- VoiceRenderer,
6123
+ EditorRenderer,
6106
6124
  {
6107
- field,
6108
- voiceHint: spokenHint,
6125
+ session: activeSession,
6126
+ onHandback: (output2) => submitHandback(output2).then(() => void 0),
6109
6127
  apiBase: apiBaseResolved,
6110
6128
  participantToken,
6111
- onValue: handleVoiceValue,
6112
- useServerTTS: (surfaceConfig == null ? void 0 : surfaceConfig.tts) === "server",
6113
6129
  disabled: submitting
6114
6130
  }
6115
- ) })
6116
- ] });
6117
- }
6118
- const showConnectionOnboarding = !connectionsLoading && !allConnectionsProvided && !connectionOnboardingDismissed && requiredConnections.some((c) => !c.provided);
6119
- if (showConnectionOnboarding) {
6120
- return /* @__PURE__ */ jsxRuntime.jsx("div", { className: cls, children: /* @__PURE__ */ jsxRuntime.jsx(
6121
- ConnectionOnboarding,
6122
- {
6123
- connections: requiredConnections,
6124
- appBase: appBaseResolved,
6125
- participantToken,
6126
- onSkip: () => setConnectionOnboardingDismissed(true),
6127
- onDisconnect: disconnectConnection
6128
- }
6129
- ) });
6130
- }
6131
- return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cls, children: [
6132
- /* @__PURE__ */ jsxRuntime.jsx(ChatTimeline, { entries: timeline, showTyping, streamingText }),
6133
- activeSession && field && InputComponent && /* @__PURE__ */ jsxRuntime.jsxs("form", { ref: inputAreaRef, className: widget_default.activeInputArea, onSubmit: handleSubmit, children: [
6134
- isConverseSession && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.converseHint, children: [
6135
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.converseHintDot }),
6136
- "Collecting your answers\u2026"
6137
- ] }),
6138
- field.prompt && /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.activeInputPrompt, children: field.prompt }),
6139
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.activeInputRow, children: [
6140
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.activeInputField, children: /* @__PURE__ */ jsxRuntime.jsx(
6141
- InputComponent,
6131
+ ) });
6132
+ }
6133
+ const converseCtx = activeSession == null ? void 0 : activeSession.entry_context;
6134
+ const isConverseSession = (converseCtx == null ? void 0 : converseCtx.converse_session) === true;
6135
+ const converseUserCanEnd = (converseCtx == null ? void 0 : converseCtx.converse_user_can_end) === true;
6136
+ const field = activeSession ? extractField(activeSession) : null;
6137
+ if (status === "awaiting_chat" && activeSession && !(isConverseSession && field)) {
6138
+ const hbCtx = (_e = activeSession.entry_context) == null ? void 0 : _e.handback;
6139
+ const outputSchema = hbCtx == null ? void 0 : hbCtx.output_schema;
6140
+ const requireOutput = (_f = hbCtx == null ? void 0 : hbCtx.require_output) != null ? _f : false;
6141
+ const handbackReady = !requireOutput || outputSchema != null && Object.keys(outputSchema).every((k) => {
6142
+ var _a2;
6143
+ return ((_a2 = handbackValues[k]) != null ? _a2 : "").trim() !== "";
6144
+ });
6145
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cls, style: rootStyle, children: [
6146
+ header,
6147
+ /* @__PURE__ */ jsxRuntime.jsx(ChatTimeline, { entries: timeline, streamingText, components }),
6148
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { ref: inputAreaRef, className: widget_default.chatInputRow, children: [
6149
+ /* @__PURE__ */ jsxRuntime.jsx(
6150
+ "textarea",
6151
+ {
6152
+ className: widget_default.chatInput,
6153
+ placeholder: t.chatInputPlaceholder,
6154
+ value: inputValue != null ? inputValue : "",
6155
+ onChange: (e) => {
6156
+ setInputValue(e.target.value);
6157
+ setInputError(null);
6158
+ },
6159
+ onKeyDown: (e) => {
6160
+ if (e.key === "Enter" && !e.shiftKey) {
6161
+ e.preventDefault();
6162
+ if (inputValue) {
6163
+ void sendMessage(inputValue);
6164
+ setInputValue(void 0);
6165
+ }
6166
+ }
6167
+ },
6168
+ disabled: submitting,
6169
+ rows: 1
6170
+ }
6171
+ ),
6172
+ /* @__PURE__ */ jsxRuntime.jsx(
6173
+ "button",
6174
+ {
6175
+ className: widget_default.chatSendButton,
6176
+ disabled: submitting || !inputValue,
6177
+ onClick: () => {
6178
+ if (inputValue) {
6179
+ void sendMessage(inputValue);
6180
+ setInputValue(void 0);
6181
+ }
6182
+ },
6183
+ children: t.sendButton
6184
+ }
6185
+ )
6186
+ ] }),
6187
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.handbackSection, children: [
6188
+ outputSchema != null && /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.handbackForm, children: Object.entries(outputSchema).map(([key, typeStr]) => {
6189
+ var _a2, _b2;
6190
+ const isEnum = typeStr.includes("|");
6191
+ const options = isEnum ? typeStr.split("|").map((o) => o.trim()) : [];
6192
+ const label = key.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
6193
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.handbackField, children: [
6194
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: widget_default.handbackFieldLabel, children: label }),
6195
+ isEnum ? /* @__PURE__ */ jsxRuntime.jsxs(
6196
+ "select",
6197
+ {
6198
+ className: widget_default.handbackFieldSelect,
6199
+ value: (_a2 = handbackValues[key]) != null ? _a2 : "",
6200
+ onChange: (e) => setHandbackValues((prev) => ({ ...prev, [key]: e.target.value })),
6201
+ disabled: submitting,
6202
+ children: [
6203
+ /* @__PURE__ */ jsxRuntime.jsx("option", { value: "", disabled: true, children: "Select\u2026" }),
6204
+ options.map((opt) => /* @__PURE__ */ jsxRuntime.jsx("option", { value: opt, children: opt }, opt))
6205
+ ]
6206
+ }
6207
+ ) : /* @__PURE__ */ jsxRuntime.jsx(
6208
+ "textarea",
6209
+ {
6210
+ className: widget_default.handbackFieldTextarea,
6211
+ value: (_b2 = handbackValues[key]) != null ? _b2 : "",
6212
+ onChange: (e) => setHandbackValues((prev) => ({ ...prev, [key]: e.target.value })),
6213
+ disabled: submitting,
6214
+ rows: 2
6215
+ }
6216
+ )
6217
+ ] }, key);
6218
+ }) }),
6219
+ /* @__PURE__ */ jsxRuntime.jsx(
6220
+ "button",
6221
+ {
6222
+ className: widget_default.handbackButton,
6223
+ onClick: () => void submitHandback(
6224
+ outputSchema != null ? handbackValues : void 0
6225
+ ),
6226
+ disabled: submitting || !handbackReady,
6227
+ children: t.handBackButton
6228
+ }
6229
+ )
6230
+ ] })
6231
+ ] });
6232
+ }
6233
+ const surface = activeSession ? extractSurface(activeSession) : null;
6234
+ const surfaceConfig = activeSession ? extractSurfaceConfig(activeSession) : null;
6235
+ const nodeVoice = activeSession ? extractNodeVoice(activeSession) : null;
6236
+ const InputComponent = field ? getInputComponent(field.input_type) : null;
6237
+ const effectiveVoiceMode = resolveVoiceMode(surface, surfaceConfig, nodeVoice);
6238
+ const shouldUseVoice = effectiveVoiceMode !== "off";
6239
+ const voiceRenderer = effectiveVoiceMode === "push_to_talk" ? "click" : "continuous";
6240
+ const isLiveVoice = surface === "widget/voice" && (surfaceConfig == null ? void 0 : surfaceConfig.style) === "live";
6241
+ if (shouldUseVoice && activeSession && field) {
6242
+ const spokenHint = (_h = nodeVoice == null ? void 0 : nodeVoice.hint) != null ? _h : (_g = field.voice) == null ? void 0 : _g.hint;
6243
+ const handleVoiceValue = (value) => {
6244
+ setInputValue(value);
6245
+ void submitHandback(value, crypto.randomUUID());
6246
+ };
6247
+ const handleLiveValue = (value) => {
6248
+ setInputValue(value);
6249
+ };
6250
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cls, style: rootStyle, children: [
6251
+ header,
6252
+ /* @__PURE__ */ jsxRuntime.jsx(ChatTimeline, { entries: timeline, showTyping, streamingText, components }),
6253
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.activeInputArea, children: isLiveVoice ? /* @__PURE__ */ jsxRuntime.jsx(
6254
+ VoiceLiveRenderer,
6142
6255
  {
6143
6256
  field,
6144
- value: inputValue,
6145
- onChange: (v) => {
6146
- setInputValue(v);
6147
- setInputError(null);
6148
- setServerErrors([]);
6149
- },
6150
- onSubmit: handleAutoSubmit,
6151
- disabled: submitting,
6152
- uploadContext: field.input_type === "FileUpload" && activeSession ? {
6153
- apiBase: apiBaseResolved,
6154
- participantToken,
6155
- sessionId: activeSession.id
6156
- } : void 0
6257
+ voiceHint: spokenHint,
6258
+ apiBase: apiBaseResolved,
6259
+ participantToken,
6260
+ sessionId: activeSession.id,
6261
+ liveConfig: surfaceConfig != null ? surfaceConfig : void 0,
6262
+ onValue: handleLiveValue,
6263
+ disabled: submitting
6157
6264
  }
6158
- ) }),
6159
- field.input_type !== "Display" && !(field.input_type === "SingleSelect" && field.variant === "buttons") && /* @__PURE__ */ jsxRuntime.jsx(
6265
+ ) : voiceRenderer === "continuous" ? /* @__PURE__ */ jsxRuntime.jsx(
6266
+ VoiceContinuousRenderer,
6267
+ {
6268
+ field,
6269
+ voiceHint: spokenHint,
6270
+ apiBase: apiBaseResolved,
6271
+ participantToken,
6272
+ onValue: handleVoiceValue,
6273
+ autoSubmitMode: "confirm",
6274
+ 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,
6275
+ enqueueSpeak,
6276
+ isSpeaking,
6277
+ disabled: submitting
6278
+ }
6279
+ ) : /* @__PURE__ */ jsxRuntime.jsx(
6280
+ VoiceRenderer,
6281
+ {
6282
+ field,
6283
+ voiceHint: spokenHint,
6284
+ apiBase: apiBaseResolved,
6285
+ participantToken,
6286
+ onValue: handleVoiceValue,
6287
+ useServerTTS: (surfaceConfig == null ? void 0 : surfaceConfig.tts) === "server",
6288
+ disabled: submitting
6289
+ }
6290
+ ) })
6291
+ ] });
6292
+ }
6293
+ const showConnectionOnboarding = !connectionsLoading && !allConnectionsProvided && !connectionOnboardingDismissed && requiredConnections.some((c) => !c.provided);
6294
+ if (showConnectionOnboarding) {
6295
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: cls, style: rootStyle, children: /* @__PURE__ */ jsxRuntime.jsx(
6296
+ ConnectionOnboarding,
6297
+ {
6298
+ connections: requiredConnections,
6299
+ appBase: appBaseResolved,
6300
+ participantToken,
6301
+ onSkip: () => setConnectionOnboardingDismissed(true),
6302
+ onDisconnect: disconnectConnection
6303
+ }
6304
+ ) });
6305
+ }
6306
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: cls, style: rootStyle, children: [
6307
+ header,
6308
+ /* @__PURE__ */ jsxRuntime.jsx(ChatTimeline, { entries: timeline, showTyping, streamingText, components }),
6309
+ activeSession && field && InputComponent && /* @__PURE__ */ jsxRuntime.jsxs("form", { ref: inputAreaRef, className: widget_default.activeInputArea, onSubmit: handleSubmit, children: [
6310
+ isConverseSession && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.converseHint, children: [
6311
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.converseHintDot }),
6312
+ "Collecting your answers\u2026"
6313
+ ] }),
6314
+ field.prompt && /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.activeInputPrompt, children: field.prompt }),
6315
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.activeInputRow, children: [
6316
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.activeInputField, children: /* @__PURE__ */ jsxRuntime.jsx(
6317
+ InputComponent,
6318
+ {
6319
+ field,
6320
+ value: inputValue,
6321
+ onChange: (v) => {
6322
+ setInputValue(v);
6323
+ setInputError(null);
6324
+ setServerErrors([]);
6325
+ },
6326
+ onSubmit: handleAutoSubmit,
6327
+ disabled: submitting,
6328
+ uploadContext: field.input_type === "FileUpload" && activeSession ? {
6329
+ apiBase: apiBaseResolved,
6330
+ participantToken,
6331
+ sessionId: activeSession.id
6332
+ } : void 0
6333
+ }
6334
+ ) }),
6335
+ field.input_type !== "Display" && !(field.input_type === "SingleSelect" && field.variant === "buttons") && /* @__PURE__ */ jsxRuntime.jsx(
6336
+ "button",
6337
+ {
6338
+ type: "submit",
6339
+ className: widget_default.activeInputSubmit,
6340
+ disabled: submitting,
6341
+ children: submitting ? "\u2026" : t.sendButton
6342
+ }
6343
+ )
6344
+ ] }),
6345
+ inputError && /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.inlineError, children: inputError }),
6346
+ serverErrors.length > 1 && serverErrors.slice(1).map((e, i) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.inlineError, children: [
6347
+ e.field !== "_" ? `${e.field}: ` : "",
6348
+ e.message
6349
+ ] }, i)),
6350
+ isConverseSession && converseUserCanEnd && /* @__PURE__ */ jsxRuntime.jsx(
6160
6351
  "button",
6161
6352
  {
6162
- type: "submit",
6163
- className: widget_default.activeInputSubmit,
6353
+ type: "button",
6354
+ className: widget_default.converseDoneButton,
6355
+ onClick: () => void submitHandback({ _done: true }),
6164
6356
  disabled: submitting,
6165
- children: submitting ? "\u2026" : "Send"
6357
+ children: t.converseDoneButton
6166
6358
  }
6167
6359
  )
6168
6360
  ] }),
6169
- inputError && /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.inlineError, children: inputError }),
6170
- serverErrors.length > 1 && serverErrors.slice(1).map((e, i) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: widget_default.inlineError, children: [
6171
- e.field !== "_" ? `${e.field}: ` : "",
6172
- e.message
6173
- ] }, i))
6174
- ] }),
6175
- !activeSession && status === "running" && timeline.length === 0 && /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status: "running" })
6176
- ] });
6177
- }
6361
+ !activeSession && status === "running" && timeline.length === 0 && (emptyState != null ? emptyState : /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status: "running", strings })),
6362
+ footer
6363
+ ] });
6364
+ }
6365
+ );
6178
6366
  function extractField(session) {
6179
6367
  var _a, _b;
6180
6368
  const ctx = session.entry_context;
@@ -6255,34 +6443,326 @@ function resolveVoiceMode(surface, surfaceConfig, nodeVoice) {
6255
6443
  if ((nodeVoice == null ? void 0 : nodeVoice.capture) === "continuous") return "continuous";
6256
6444
  return style === "push_to_talk" ? "push_to_talk" : "continuous";
6257
6445
  }
6258
- function ChatterflyWidget(props) {
6446
+
6447
+ // src/sessionPersistence.ts
6448
+ function resolveOptions(config) {
6259
6449
  var _a, _b;
6450
+ if (!config) return null;
6451
+ const opts = config === true ? {} : config;
6452
+ return {
6453
+ storage: (_a = opts.storage) != null ? _a : "session",
6454
+ key: (_b = opts.key) != null ? _b : ""
6455
+ };
6456
+ }
6457
+ function storageFor(kind) {
6458
+ if (typeof window === "undefined") return null;
6459
+ try {
6460
+ return kind === "local" ? window.localStorage : window.sessionStorage;
6461
+ } catch {
6462
+ return null;
6463
+ }
6464
+ }
6465
+ function storageKey(target, custom) {
6466
+ return custom ? `chatterfly:session:${custom}` : `chatterfly:session:${target}`;
6467
+ }
6468
+ function loadPersistedSession(config, target) {
6469
+ const opts = config ? resolveOptions(config) : null;
6470
+ if (!opts || !target) return null;
6471
+ const store = storageFor(opts.storage);
6472
+ if (!store) return null;
6473
+ try {
6474
+ const raw = store.getItem(storageKey(target, opts.key));
6475
+ if (!raw) return null;
6476
+ const parsed = JSON.parse(raw);
6477
+ if (typeof parsed.runId === "string" && typeof parsed.participantToken === "string") {
6478
+ return { runId: parsed.runId, participantToken: parsed.participantToken };
6479
+ }
6480
+ } catch {
6481
+ }
6482
+ return null;
6483
+ }
6484
+ function savePersistedSession(config, target, session) {
6485
+ const opts = config ? resolveOptions(config) : null;
6486
+ if (!opts || !target) return;
6487
+ const store = storageFor(opts.storage);
6488
+ if (!store) return;
6489
+ try {
6490
+ store.setItem(storageKey(target, opts.key), JSON.stringify(session));
6491
+ } catch {
6492
+ }
6493
+ }
6494
+ function clearPersistedSession(config, target) {
6495
+ const opts = config ? resolveOptions(config) : null;
6496
+ if (!opts || !target) return;
6497
+ const store = storageFor(opts.storage);
6498
+ if (!store) return;
6499
+ try {
6500
+ store.removeItem(storageKey(target, opts.key));
6501
+ } catch {
6502
+ }
6503
+ }
6504
+ var ChatterflyWidget = react.forwardRef(
6505
+ function ChatterflyWidget2(props, ref) {
6506
+ var _a, _b, _c, _d, _e, _f, _g, _h;
6507
+ const [resolved, setResolved] = react.useState(null);
6508
+ const [configError, setConfigError] = react.useState(null);
6509
+ const [restartNonce, setRestartNonce] = react.useState(0);
6510
+ const adapterRef = react.useRef(null);
6511
+ const autoStarting = Boolean(!props.runId && (props.deploymentId || props.workflowId));
6512
+ const persistTarget = (_a = props.workflowId) != null ? _a : props.deploymentId;
6513
+ react.useEffect(() => {
6514
+ var _a2;
6515
+ if (props.runId) return;
6516
+ if (!props.deploymentId && !props.workflowId) return;
6517
+ if (!props.apiBase) {
6518
+ const err = new WidgetError(
6519
+ "config_missing_api_base",
6520
+ "ChatterflyWidget requires an `apiBase` prop pointing at your Chatterfly backend \u2014 there is no localhost default."
6521
+ );
6522
+ setConfigError(err);
6523
+ (_a2 = props.onError) == null ? void 0 : _a2.call(props, err);
6524
+ return;
6525
+ }
6526
+ 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;
6532
+ }
6533
+ }
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
+ );
6549
+ }
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
+ });
6562
+ }, [props.deploymentId, props.workflowId, props.apiBase, restartNonce]);
6563
+ const restart = react.useCallback(() => {
6564
+ var _a2;
6565
+ if (autoStarting) {
6566
+ clearPersistedSession(props.persistSession, persistTarget);
6567
+ setResolved(null);
6568
+ setRestartNonce((n) => n + 1);
6569
+ } else {
6570
+ (_a2 = adapterRef.current) == null ? void 0 : _a2.restart();
6571
+ }
6572
+ }, [autoStarting, props.persistSession, persistTarget]);
6573
+ const disconnect = react.useCallback(() => {
6574
+ var _a2;
6575
+ (_a2 = adapterRef.current) == null ? void 0 : _a2.disconnect();
6576
+ }, []);
6577
+ const sendMessage = react.useCallback((text) => {
6578
+ var _a2;
6579
+ (_a2 = adapterRef.current) == null ? void 0 : _a2.sendMessage(text);
6580
+ }, []);
6581
+ react.useImperativeHandle(ref, () => ({ restart, disconnect, sendMessage }), [
6582
+ restart,
6583
+ disconnect,
6584
+ sendMessage
6585
+ ]);
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);
6590
+ const [unreadCount, setUnreadCount] = react.useState(0);
6591
+ const toggleOpen = react.useCallback(() => {
6592
+ setOpen((prev) => {
6593
+ var _a2;
6594
+ const next = !prev;
6595
+ if (next) setUnreadCount(0);
6596
+ (_a2 = props.onOpenChange) == null ? void 0 : _a2.call(props, next);
6597
+ return next;
6598
+ });
6599
+ }, [props.onOpenChange]);
6600
+ const handleMessage = react.useCallback(
6601
+ (message) => {
6602
+ var _a2;
6603
+ if (mode === "floating" && !open) setUnreadCount((n) => n + 1);
6604
+ (_a2 = props.onMessage) == null ? void 0 : _a2.call(props, message);
6605
+ },
6606
+ // eslint-disable-next-line react-hooks/exhaustive-deps
6607
+ [mode, open, props.onMessage]
6608
+ );
6609
+ let content;
6610
+ if (configError) {
6611
+ content = (_f = props.loadingFallback) != null ? _f : /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status: "error" });
6612
+ } else if (!runId || !participantToken) {
6613
+ content = (_g = props.loadingFallback) != null ? _g : /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status: autoStarting ? "connecting" : "error" });
6614
+ } else {
6615
+ content = /* @__PURE__ */ jsxRuntime.jsx(
6616
+ ChatAdapter,
6617
+ {
6618
+ ...props,
6619
+ ref: adapterRef,
6620
+ runId,
6621
+ participantToken,
6622
+ onMessage: handleMessage
6623
+ }
6624
+ );
6625
+ }
6626
+ if (mode !== "floating") {
6627
+ return content;
6628
+ }
6629
+ const position = (_h = props.position) != null ? _h : "bottom-right";
6630
+ return /* @__PURE__ */ jsxRuntime.jsx(
6631
+ FloatingLauncherChrome,
6632
+ {
6633
+ position,
6634
+ open,
6635
+ onToggle: toggleOpen,
6636
+ unreadCount,
6637
+ icon: props.launcherIcon,
6638
+ children: content
6639
+ }
6640
+ );
6641
+ }
6642
+ );
6643
+ function DefaultLauncherIcon() {
6644
+ return /* @__PURE__ */ jsxRuntime.jsx("svg", { viewBox: "0 0 24 24", width: "24", height: "24", fill: "none", "aria-hidden": "true", children: /* @__PURE__ */ jsxRuntime.jsx(
6645
+ "path",
6646
+ {
6647
+ d: "M4 4h16v11H8l-4 4V4z",
6648
+ stroke: "currentColor",
6649
+ strokeWidth: "2",
6650
+ strokeLinejoin: "round",
6651
+ fill: "none"
6652
+ }
6653
+ ) });
6654
+ }
6655
+ function FloatingLauncherChrome({
6656
+ position,
6657
+ open,
6658
+ onToggle,
6659
+ unreadCount,
6660
+ icon,
6661
+ children
6662
+ }) {
6663
+ const rootClass = [
6664
+ widget_default.launcherRoot,
6665
+ position === "bottom-left" ? widget_default.launcherRootLeft : widget_default.launcherRootRight
6666
+ ].join(" ");
6667
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: rootClass, children: [
6668
+ open && /* @__PURE__ */ jsxRuntime.jsx("div", { className: widget_default.launcherPanel, children }),
6669
+ /* @__PURE__ */ jsxRuntime.jsxs(
6670
+ "button",
6671
+ {
6672
+ type: "button",
6673
+ className: widget_default.launcherButton,
6674
+ onClick: onToggle,
6675
+ "aria-expanded": open,
6676
+ "aria-label": open ? "Close chat" : "Open chat",
6677
+ children: [
6678
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.launcherIcon, children: icon != null ? icon : /* @__PURE__ */ jsxRuntime.jsx(DefaultLauncherIcon, {}) }),
6679
+ !open && unreadCount > 0 && /* @__PURE__ */ jsxRuntime.jsx("span", { className: widget_default.launcherBadge, children: unreadCount > 9 ? "9+" : unreadCount })
6680
+ ]
6681
+ }
6682
+ )
6683
+ ] });
6684
+ }
6685
+ function useChatterflyRun(options) {
6686
+ var _a, _b;
6687
+ const { runId, participantToken, apiBase, deploymentId, workflowId, initialInput, persistSession, onEvent } = options;
6260
6688
  const [resolved, setResolved] = react.useState(null);
6689
+ const [error, setError] = react.useState(null);
6690
+ const [restartNonce, setRestartNonce] = react.useState(0);
6691
+ const autoStarting = Boolean(!runId && (deploymentId || workflowId));
6692
+ const persistTarget = workflowId != null ? workflowId : deploymentId;
6261
6693
  react.useEffect(() => {
6262
- var _a2;
6263
- if (props.runId) return;
6264
- if (!props.deploymentId && !props.workflowId) return;
6265
- const base = (_a2 = props.apiBase) != null ? _a2 : "http://localhost:8080";
6266
- const startUrl = props.workflowId ? `${base}/api/public/workflows/${props.workflowId}/start` : `${base}/api/public/surveys/${props.deploymentId}/start`;
6694
+ if (runId) return;
6695
+ if (!deploymentId && !workflowId) return;
6696
+ if (!apiBase) {
6697
+ const err = new WidgetError(
6698
+ "config_missing_api_base",
6699
+ "useChatterflyRun requires `apiBase` \u2014 there is no localhost default."
6700
+ );
6701
+ setError(err);
6702
+ return;
6703
+ }
6704
+ setError(null);
6705
+ if (restartNonce === 0) {
6706
+ const persisted = loadPersistedSession(persistSession, persistTarget);
6707
+ if (persisted) {
6708
+ setResolved({ runId: persisted.runId, participantToken: persisted.participantToken });
6709
+ return;
6710
+ }
6711
+ }
6712
+ const startUrl = workflowId ? `${apiBase}/api/public/workflows/${workflowId}/start` : `${apiBase}/api/public/surveys/${deploymentId}/start`;
6713
+ const body = initialInput ? JSON.stringify({ input: initialInput }) : void 0;
6267
6714
  fetch(startUrl, {
6268
- method: "POST"
6269
- }).then((r) => {
6270
- if (!r.ok) throw new Error(`HTTP ${r.status}`);
6715
+ method: "POST",
6716
+ headers: body ? { "Content-Type": "application/json" } : void 0,
6717
+ body
6718
+ }).then(async (r) => {
6719
+ if (!r.ok) {
6720
+ const code = r.status === 404 ? "no_live_deployment" : "workflow_not_public";
6721
+ const detail = await r.text().catch(() => "");
6722
+ throw new WidgetError(
6723
+ code,
6724
+ `Failed to start run (HTTP ${r.status})${detail ? `: ${detail}` : ""}`
6725
+ );
6726
+ }
6271
6727
  return r.json();
6272
- }).then(
6273
- ({ run_id, participant_token }) => setResolved({ runId: run_id, participantToken: participant_token })
6274
- ).catch((err) => {
6275
- var _a3;
6276
- return (_a3 = props.onError) == null ? void 0 : _a3.call(props, err.message);
6728
+ }).then(({ run_id, participant_token }) => {
6729
+ setResolved({ runId: run_id, participantToken: participant_token });
6730
+ savePersistedSession(persistSession, persistTarget, {
6731
+ runId: run_id,
6732
+ participantToken: participant_token
6733
+ });
6734
+ }).catch((err) => {
6735
+ setError(
6736
+ err instanceof WidgetError ? err : new WidgetError("network", err instanceof Error ? err.message : String(err))
6737
+ );
6277
6738
  });
6278
- }, [props.deploymentId, props.workflowId]);
6279
- const runId = (_a = resolved == null ? void 0 : resolved.runId) != null ? _a : props.runId;
6280
- const participantToken = (_b = resolved == null ? void 0 : resolved.participantToken) != null ? _b : props.participantToken;
6281
- if (!runId || !participantToken) {
6282
- const autoStarting = props.deploymentId || props.workflowId;
6283
- return /* @__PURE__ */ jsxRuntime.jsx(StatusDisplay, { status: autoStarting ? "connecting" : "error" });
6284
- }
6285
- return /* @__PURE__ */ jsxRuntime.jsx(ChatAdapter, { ...props, runId, participantToken });
6739
+ }, [runId, deploymentId, workflowId, apiBase, restartNonce]);
6740
+ const effectiveRunId = (_a = resolved == null ? void 0 : resolved.runId) != null ? _a : runId;
6741
+ const effectiveToken = (_b = resolved == null ? void 0 : resolved.participantToken) != null ? _b : participantToken;
6742
+ const stream = useRunStream(
6743
+ {
6744
+ runId: effectiveRunId != null ? effectiveRunId : "",
6745
+ participantToken: effectiveToken != null ? effectiveToken : "",
6746
+ apiBase: apiBase != null ? apiBase : ""
6747
+ },
6748
+ onEvent
6749
+ );
6750
+ const restart = react.useCallback(() => {
6751
+ if (autoStarting) {
6752
+ clearPersistedSession(persistSession, persistTarget);
6753
+ setResolved(null);
6754
+ setRestartNonce((n) => n + 1);
6755
+ } else {
6756
+ stream.reconnect();
6757
+ }
6758
+ }, [autoStarting, persistSession, persistTarget, stream]);
6759
+ const connecting = autoStarting && !resolved && !error;
6760
+ return {
6761
+ ...stream,
6762
+ connecting,
6763
+ error,
6764
+ restart
6765
+ };
6286
6766
  }
6287
6767
 
6288
6768
  exports.ChatAdapter = ChatAdapter;
@@ -6305,13 +6785,17 @@ exports.VoiceLiveRenderer = VoiceLiveRenderer;
6305
6785
  exports.VoiceOrb = VoiceOrb;
6306
6786
  exports.VoicePromptCard = VoicePromptCard;
6307
6787
  exports.VoiceRenderer = VoiceRenderer;
6788
+ exports.WidgetError = WidgetError;
6308
6789
  exports.buildSpokenPrompt = buildSpokenPrompt;
6790
+ exports.defaultStrings = defaultStrings;
6309
6791
  exports.extractValue = extractValue;
6310
6792
  exports.getInputComponent = getInputComponent;
6311
6793
  exports.registerInputType = registerInputType;
6312
6794
  exports.registerSessionRenderer = registerSessionRenderer;
6313
6795
  exports.resolveInputType = resolveInputType;
6314
6796
  exports.resolveSessionRenderer = resolveSessionRenderer;
6797
+ exports.resolveStrings = resolveStrings;
6798
+ exports.useChatterflyRun = useChatterflyRun;
6315
6799
  exports.useContinuousVoiceSession = useContinuousVoiceSession;
6316
6800
  exports.useGeminiLiveSession = useGeminiLiveSession;
6317
6801
  exports.useParticipantConnections = useParticipantConnections;