@chatterfly/widget 0.1.0 → 0.2.0

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