@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.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",
@@ -444,6 +490,7 @@ var widget_default = {
444
490
  converseHint: "widget_converseHint",
445
491
  converseHintDot: "widget_converseHintDot",
446
492
  "cf-converse-pulse": "widget_cf-converse-pulse",
493
+ converseDoneButton: "widget_converseDoneButton",
447
494
  newMessageChip: "widget_newMessageChip",
448
495
  activeInputRow: "widget_activeInputRow",
449
496
  activeInputField: "widget_activeInputField",
@@ -804,6 +851,12 @@ function DocumentCard({ content, descriptor }) {
804
851
  )) })
805
852
  ] });
806
853
  }
854
+ function DefaultBotBubble({ children }) {
855
+ return /* @__PURE__ */ jsx("div", { className: widget_default.bubbleBot, children });
856
+ }
857
+ function DefaultUserBubble({ children }) {
858
+ return /* @__PURE__ */ jsx("div", { className: widget_default.bubbleUser, children });
859
+ }
807
860
  function FormDataView({
808
861
  data,
809
862
  depth = 0
@@ -943,7 +996,10 @@ function entryToDisplay(entry) {
943
996
  return null;
944
997
  }
945
998
  }
946
- function ChatTimeline({ entries, showTyping, streamingText }) {
999
+ function ChatTimeline({ entries, showTyping, streamingText, components }) {
1000
+ var _a, _b;
1001
+ const BotBubble = (_a = components == null ? void 0 : components.BotBubble) != null ? _a : DefaultBotBubble;
1002
+ const UserBubble = (_b = components == null ? void 0 : components.UserBubble) != null ? _b : DefaultUserBubble;
947
1003
  const containerRef = useRef(null);
948
1004
  const prevLengthRef = useRef(0);
949
1005
  const prevShowTypingRef = useRef(false);
@@ -1059,7 +1115,7 @@ function ChatTimeline({ entries, showTyping, streamingText }) {
1059
1115
  )
1060
1116
  ] }, t)) }) : /* @__PURE__ */ jsx(MarkdownBubble, { content: display.text });
1061
1117
  return /* @__PURE__ */ jsxs("div", { className: widget_default.bubbleUserRow, children: [
1062
- /* @__PURE__ */ jsx("div", { className: widget_default.bubbleUser, children: userContent }),
1118
+ /* @__PURE__ */ jsx(UserBubble, { children: userContent }),
1063
1119
  /* @__PURE__ */ jsx(
1064
1120
  "div",
1065
1121
  {
@@ -1072,7 +1128,7 @@ function ChatTimeline({ entries, showTyping, streamingText }) {
1072
1128
  }
1073
1129
  const content = display.format !== "text" ? /* @__PURE__ */ jsx(MarkdownBubble, { content: display.text }) : display.text;
1074
1130
  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 }),
1131
+ display.document ? /* @__PURE__ */ jsx(DocumentCard, { content: display.text, descriptor: display.document }) : /* @__PURE__ */ jsx(BotBubble, { children: content }),
1076
1132
  /* @__PURE__ */ jsx(
1077
1133
  "div",
1078
1134
  {
@@ -2612,38 +2668,62 @@ function FormRenderer({
2612
2668
  ) })
2613
2669
  ] });
2614
2670
  }
2615
- function StatusDisplay({ status, error }) {
2671
+
2672
+ // src/strings.ts
2673
+ var defaultStrings = {
2674
+ statusInitialising: "Initialising\u2026",
2675
+ statusConnecting: "Connecting\u2026",
2676
+ statusRunning: "Running\u2026",
2677
+ statusCompletedTitle: "Completed",
2678
+ statusCompletedBody: "This workflow run has finished.",
2679
+ statusErrorTitle: "Something went wrong",
2680
+ statusOfflineTitle: "Connection lost",
2681
+ statusOfflineBody: "Unable to reach the server. Please check your connection and refresh.",
2682
+ statusListening: "Listening\u2026",
2683
+ resumingConversation: "Resuming conversation\u2026",
2684
+ conversationCompleted: "Conversation completed.",
2685
+ somethingWentWrong: "Something went wrong",
2686
+ chatInputPlaceholder: "Type a message\u2026",
2687
+ sendButton: "Send",
2688
+ handBackButton: "Hand Back",
2689
+ converseDoneButton: "I'm done"
2690
+ };
2691
+ function resolveStrings(overrides) {
2692
+ return overrides ? { ...defaultStrings, ...overrides } : defaultStrings;
2693
+ }
2694
+ function StatusDisplay({ status, error, strings }) {
2695
+ const t = strings ? { ...defaultStrings, ...strings } : defaultStrings;
2616
2696
  switch (status) {
2617
2697
  case "idle":
2618
2698
  case "connecting":
2619
2699
  return /* @__PURE__ */ jsxs("div", { className: widget_default.statusWrapper, children: [
2620
2700
  /* @__PURE__ */ jsx("div", { className: widget_default.spinner }),
2621
- /* @__PURE__ */ jsx("div", { className: widget_default.statusLabel, children: status === "idle" ? "Initialising\u2026" : "Connecting\u2026" })
2701
+ /* @__PURE__ */ jsx("div", { className: widget_default.statusLabel, children: status === "idle" ? t.statusInitialising : t.statusConnecting })
2622
2702
  ] });
2623
2703
  case "running":
2624
2704
  return /* @__PURE__ */ jsxs("div", { className: widget_default.statusWrapper, children: [
2625
2705
  /* @__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" })
2706
+ /* @__PURE__ */ jsx("div", { className: widget_default.statusLabel, children: t.statusRunning })
2627
2707
  ] });
2628
2708
  case "completed":
2629
2709
  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." })
2710
+ /* @__PURE__ */ jsx("div", { className: widget_default.statusTitle, children: t.statusCompletedTitle }),
2711
+ /* @__PURE__ */ jsx("div", { className: widget_default.statusLabel, children: t.statusCompletedBody })
2632
2712
  ] });
2633
2713
  case "error":
2634
2714
  return /* @__PURE__ */ jsxs("div", { className: widget_default.statusWrapper, children: [
2635
- /* @__PURE__ */ jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: "Something went wrong" }),
2715
+ /* @__PURE__ */ jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: t.statusErrorTitle }),
2636
2716
  error && /* @__PURE__ */ jsx("div", { className: `${widget_default.statusLabel} ${widget_default.statusError}`, children: error })
2637
2717
  ] });
2638
2718
  case "offline":
2639
2719
  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." })
2720
+ /* @__PURE__ */ jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: t.statusOfflineTitle }),
2721
+ /* @__PURE__ */ jsx("div", { className: `${widget_default.statusLabel} ${widget_default.statusError}`, children: t.statusOfflineBody })
2642
2722
  ] });
2643
2723
  case "awaiting_voice":
2644
2724
  return /* @__PURE__ */ jsxs("div", { className: widget_default.statusWrapper, children: [
2645
2725
  /* @__PURE__ */ jsx("div", { className: widget_default.spinner, "aria-hidden": true }),
2646
- /* @__PURE__ */ jsx("div", { className: widget_default.statusLabel, children: "Listening\u2026" })
2726
+ /* @__PURE__ */ jsx("div", { className: widget_default.statusLabel, children: t.statusListening })
2647
2727
  ] });
2648
2728
  default:
2649
2729
  return null;
@@ -5699,480 +5779,588 @@ function stripForSpeech(text) {
5699
5779
  return text.replace(/[\p{Emoji_Presentation}\p{Extended_Pictographic}]/gu, "").replace(/\s+/g, " ").trim();
5700
5780
  }
5701
5781
  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);
5782
+ function themeToStyle(theme) {
5783
+ if (!theme) return {};
5784
+ const map = {
5785
+ primary: "--cf-primary",
5786
+ accent: "--cf-accent",
5787
+ info: "--cf-info",
5788
+ bg: "--cf-bg",
5789
+ fg: "--cf-fg",
5790
+ muted: "--cf-muted",
5791
+ border: "--cf-border",
5792
+ surface: "--cf-surface",
5793
+ error: "--cf-error",
5794
+ radius: "--cf-radius",
5795
+ font: "--cf-font",
5796
+ height: "--cf-height",
5797
+ bubbleBotBg: "--cf-bubble-bot-bg",
5798
+ bubbleBotFg: "--cf-bubble-bot-fg",
5799
+ bubbleUserBg: "--cf-bubble-user-bg",
5800
+ bubbleUserFg: "--cf-bubble-user-fg",
5801
+ headerBg: "--cf-header-bg",
5802
+ headerFg: "--cf-header-fg",
5803
+ inputBg: "--cf-input-bg",
5804
+ shadow: "--cf-shadow",
5805
+ spacing: "--cf-spacing",
5806
+ avatarSize: "--cf-avatar-size"
5807
+ };
5808
+ const style = {};
5809
+ for (const key of Object.keys(map)) {
5810
+ const value = theme[key];
5811
+ if (value !== void 0) style[map[key]] = value;
5805
5812
  }
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;
5813
+ return style;
5814
+ }
5815
+ var ChatAdapter = forwardRef(
5816
+ function ChatAdapter2({
5817
+ runId,
5818
+ participantToken,
5819
+ apiBase,
5820
+ className,
5821
+ onCompleted,
5822
+ onError,
5823
+ onEvent,
5824
+ onStatusChange,
5825
+ onSessionOpened,
5826
+ onMessage,
5827
+ autoFocusInput,
5828
+ loadingFallback,
5829
+ theme,
5830
+ colorScheme,
5831
+ header,
5832
+ footer,
5833
+ emptyState,
5834
+ completedState,
5835
+ errorState,
5836
+ components,
5837
+ strings
5838
+ }, ref) {
5839
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
5840
+ const t = resolveStrings(strings);
5841
+ const apiBaseResolved = apiBase;
5842
+ const appBaseResolved = typeof window !== "undefined" ? window.location.origin : (_a = process.env.APP_URL) != null ? _a : "http://localhost:3000";
5843
+ const onEventFirehose = useCallback(
5844
+ (event) => {
5845
+ var _a2;
5846
+ onEvent == null ? void 0 : onEvent(event);
5847
+ if (event.type === "hitl.session_opened") {
5848
+ onSessionOpened == null ? void 0 : onSessionOpened({
5849
+ id: event.session_id,
5850
+ step_id: event.step_id,
5851
+ counterparty: event.counterparty,
5852
+ layout: event.layout,
5853
+ entry_context: event.entry_context,
5854
+ status: "open",
5855
+ messages: Array.isArray(event.messages) ? event.messages : [],
5856
+ document_content: (_a2 = event.document_content) != null ? _a2 : null
5857
+ });
5858
+ } else if (event.type === "message.sent") {
5859
+ onMessage == null ? void 0 : onMessage({ role: "assistant", content: event.content });
5869
5860
  }
5861
+ },
5862
+ [onEvent, onSessionOpened, onMessage]
5863
+ );
5864
+ const {
5865
+ status,
5866
+ activeSession,
5867
+ timeline,
5868
+ submitHandback,
5869
+ sendMessage,
5870
+ messages,
5871
+ streamingText,
5872
+ output,
5873
+ disconnect,
5874
+ reconnect
5875
+ } = useRunStream({ runId, participantToken, apiBase }, onEventFirehose);
5876
+ useImperativeHandle(
5877
+ ref,
5878
+ () => ({
5879
+ restart: reconnect,
5880
+ disconnect,
5881
+ sendMessage: (text) => void sendMessage(text)
5882
+ }),
5883
+ [reconnect, disconnect, sendMessage]
5884
+ );
5885
+ const prevStatusRef = useRef(null);
5886
+ useEffect(() => {
5887
+ if (prevStatusRef.current === status) return;
5888
+ prevStatusRef.current = status;
5889
+ onStatusChange == null ? void 0 : onStatusChange(status);
5890
+ }, [status, onStatusChange]);
5891
+ const {
5892
+ connections: requiredConnections,
5893
+ allProvided: allConnectionsProvided,
5894
+ loading: connectionsLoading,
5895
+ refresh: refreshConnections,
5896
+ disconnect: disconnectConnection
5897
+ } = useParticipantConnections(runId, participantToken, apiBaseResolved);
5898
+ const [connectionOnboardingDismissed, setConnectionOnboardingDismissed] = useState(false);
5899
+ useEffect(() => {
5900
+ const params = new URLSearchParams(window.location.search);
5901
+ if (params.has("connected") || params.has("connect_error")) {
5902
+ refreshConnections();
5903
+ const url = new URL(window.location.href);
5904
+ url.searchParams.delete("connected");
5905
+ url.searchParams.delete("connect_error");
5906
+ window.history.replaceState({}, "", url.toString());
5870
5907
  }
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);
5908
+ }, [refreshConnections]);
5909
+ const [inputValue, setInputValue] = useState(void 0);
5910
+ const [inputError, setInputError] = useState(null);
5911
+ const [serverErrors, setServerErrors] = useState([]);
5912
+ const [submitting, setSubmitting] = useState(false);
5913
+ const [handbackValues, setHandbackValues] = useState({});
5914
+ const voiceServerCfg = useMemo(() => {
5915
+ var _a2;
5916
+ if (!activeSession) return void 0;
5917
+ if (extractSurface(activeSession) === "widget/voice" && ((_a2 = extractSurfaceConfig(activeSession)) == null ? void 0 : _a2.tts) === "server") {
5918
+ return { apiBase: apiBaseResolved, participantToken };
5919
+ }
5920
+ return void 0;
5921
+ }, [activeSession, apiBaseResolved, participantToken]);
5922
+ const { speak: rawSpeak, cancel: rawCancel } = useSpeechSynthesis(voiceServerCfg);
5923
+ const [isSpeaking, setIsSpeaking] = useState(false);
5924
+ const speechQueueRef = useRef([]);
5925
+ const drainingRef = useRef(false);
5926
+ const speechGenRef = useRef(0);
5927
+ const drainSpeech = useCallback(async () => {
5928
+ if (drainingRef.current) return;
5929
+ drainingRef.current = true;
5930
+ const myGen = speechGenRef.current;
5931
+ setIsSpeaking(true);
5932
+ while (true) {
5933
+ if (speechGenRef.current !== myGen) return;
5934
+ const item = speechQueueRef.current.shift();
5935
+ if (item) {
5936
+ try {
5937
+ await rawSpeak(item.text);
5938
+ } catch {
5881
5939
  }
5882
- } else {
5883
- setInputValue(void 0);
5884
- setInputError(null);
5885
- setServerErrors([]);
5940
+ item.resolve();
5941
+ continue;
5886
5942
  }
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";
5943
+ await new Promise((r) => setTimeout(r, SPEECH_SETTLE_MS));
5944
+ if (speechGenRef.current !== myGen) return;
5945
+ if (speechQueueRef.current.length === 0) break;
5916
5946
  }
5947
+ drainingRef.current = false;
5948
+ setIsSpeaking(false);
5949
+ }, [rawSpeak]);
5950
+ const enqueueSpeak = useCallback(
5951
+ (text) => {
5952
+ const t2 = stripForSpeech(text != null ? text : "");
5953
+ if (!t2) return Promise.resolve();
5954
+ return new Promise((resolve) => {
5955
+ speechQueueRef.current.push({ text: t2, resolve });
5956
+ void drainSpeech();
5957
+ });
5958
+ },
5959
+ [drainSpeech]
5917
5960
  );
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
5961
+ const clearSpeech = useCallback(() => {
5962
+ speechGenRef.current += 1;
5963
+ for (const item of speechQueueRef.current) item.resolve();
5964
+ speechQueueRef.current = [];
5965
+ rawCancel();
5966
+ drainingRef.current = false;
5967
+ setIsSpeaking(false);
5968
+ }, [rawCancel]);
5969
+ const spokenMessageSeqsRef = useRef(/* @__PURE__ */ new Set());
5970
+ const [isVoiceSurface, setIsVoiceSurface] = useState(false);
5971
+ if (!isVoiceSurface && activeSession && extractSurface(activeSession) === "widget/voice") {
5972
+ setIsVoiceSurface(true);
5973
+ }
5974
+ const voiceSessionId = (_b = activeSession == null ? void 0 : activeSession.id) != null ? _b : null;
5975
+ const prevVoiceSessionIdRef = useRef(null);
5976
+ useEffect(() => {
5977
+ if (!isVoiceSurface) return;
5978
+ const prev = prevVoiceSessionIdRef.current;
5979
+ if (prev && voiceSessionId && prev !== voiceSessionId) {
5980
+ clearSpeech();
5934
5981
  }
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
5982
+ prevVoiceSessionIdRef.current = voiceSessionId;
5983
+ }, [voiceSessionId, isVoiceSurface, clearSpeech]);
5984
+ useEffect(() => {
5985
+ if (!isVoiceSurface) return;
5986
+ for (const entry of timeline) {
5987
+ if (entry.event_type !== "message") continue;
5988
+ if (entry.sender === "user") continue;
5989
+ if (spokenMessageSeqsRef.current.has(entry.seq)) continue;
5990
+ spokenMessageSeqsRef.current.add(entry.seq);
5991
+ const text = entry.payload.voice_hint || entry.payload.content || "";
5992
+ void enqueueSpeak(text);
5948
5993
  }
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
5994
+ }, [timeline, isVoiceSurface, enqueueSpeak]);
5995
+ const completedFiredRef = useRef(false);
5996
+ const errorFiredRef = useRef(false);
5997
+ const inputAreaRef = useRef(null);
5998
+ const lastFocusedSessionRef = useRef(null);
5999
+ const activeSessionId = (_c = activeSession == null ? void 0 : activeSession.id) != null ? _c : null;
6000
+ useEffect(() => {
6001
+ if (!autoFocusInput) return;
6002
+ if (!activeSessionId) return;
6003
+ if (lastFocusedSessionRef.current === activeSessionId) return;
6004
+ const root = inputAreaRef.current;
6005
+ if (!root) return;
6006
+ const focusable = root.querySelector(
6007
+ "input:not([type=hidden]):not([disabled]), textarea:not([disabled]), select:not([disabled]), [contenteditable=true]"
6008
+ );
6009
+ if (focusable) {
6010
+ focusable.focus({ preventScroll: true });
6011
+ lastFocusedSessionRef.current = activeSessionId;
5957
6012
  }
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
6013
+ }, [autoFocusInput, activeSessionId, status]);
6014
+ useEffect(() => {
6015
+ if (status === "completed" && !completedFiredRef.current) {
6016
+ completedFiredRef.current = true;
6017
+ onCompleted == null ? void 0 : onCompleted(output != null ? output : void 0);
6018
+ }
6019
+ if (status === "error" && !errorFiredRef.current) {
6020
+ errorFiredRef.current = true;
6021
+ onError == null ? void 0 : onError(new WidgetError("run_failed", "The run encountered an error."));
6022
+ }
6023
+ }, [status, output, onCompleted, onError]);
6024
+ const colorSchemeClass = colorScheme === "dark" ? widget_default.cfDark : colorScheme === "auto" ? widget_default.cfAuto : void 0;
6025
+ const cls = [widget_default.widget, colorSchemeClass, className].filter(Boolean).join(" ");
6026
+ const rootStyle = useMemo(() => themeToStyle(theme), [theme]);
6027
+ const showTyping = status === "running" && timeline.length > 0 && !streamingText;
6028
+ const handleSubmit = useCallback(
6029
+ async (e, valueOverride) => {
6030
+ e == null ? void 0 : e.preventDefault();
6031
+ if (!activeSession) return;
6032
+ const valueToSubmit = valueOverride !== void 0 ? valueOverride : inputValue;
6033
+ const field2 = extractField(activeSession);
6034
+ if (field2) {
6035
+ const clientErr = validate(valueToSubmit, field2.validation);
6036
+ if (clientErr) {
6037
+ setInputError(clientErr);
6038
+ return;
5992
6039
  }
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"
6040
+ }
6041
+ setSubmitting(true);
6042
+ setInputError(null);
6043
+ setServerErrors([]);
6044
+ try {
6045
+ const idempotencyKey = crypto.randomUUID();
6046
+ const errors = await submitHandback(valueToSubmit, idempotencyKey);
6047
+ if (errors) {
6048
+ setServerErrors(errors);
6049
+ if (errors.length > 0) {
6050
+ setInputError(errors[0].message);
6051
+ }
6052
+ } else {
6053
+ setInputValue(void 0);
6054
+ setInputError(null);
6055
+ setServerErrors([]);
6006
6056
  }
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]) => {
6057
+ } finally {
6058
+ setSubmitting(false);
6059
+ }
6060
+ },
6061
+ [activeSession, inputValue, submitHandback]
6062
+ );
6063
+ const handleAutoSubmit = useCallback(
6064
+ (autoValue) => {
6065
+ void handleSubmit(void 0, autoValue);
6066
+ },
6067
+ [handleSubmit]
6068
+ );
6069
+ if (status === "idle" || status === "connecting") {
6070
+ return /* @__PURE__ */ jsx("div", { className: cls, style: rootStyle, children: loadingFallback != null ? loadingFallback : /* @__PURE__ */ jsx(StatusDisplay, { status, strings }) });
6071
+ }
6072
+ if (status === "replaying") {
6073
+ return /* @__PURE__ */ jsxs("div", { className: cls, style: rootStyle, children: [
6074
+ header,
6075
+ /* @__PURE__ */ jsxs("div", { className: widget_default.resumingBanner, children: [
6076
+ /* @__PURE__ */ jsx("span", { className: widget_default.spinner }),
6077
+ t.resumingConversation
6078
+ ] }),
6079
+ /* @__PURE__ */ jsx(ChatTimeline, { entries: timeline, streamingText, components })
6080
+ ] });
6081
+ }
6082
+ if (status === "completed" || status === "error") {
6083
+ const hasChatContent = timeline.some(
6084
+ (e) => {
6011
6085
  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,
6086
+ 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";
6087
+ }
6088
+ );
6089
+ return /* @__PURE__ */ jsxs("div", { className: cls, style: rootStyle, children: [
6090
+ hasChatContent && /* @__PURE__ */ jsx(ChatTimeline, { entries: timeline, streamingText, components }),
6091
+ status === "completed" && /* @__PURE__ */ jsx("div", { className: widget_default.terminalCompleted, children: completedState != null ? completedState : t.conversationCompleted }),
6092
+ status === "error" && /* @__PURE__ */ jsx("div", { className: widget_default.terminalError, children: errorState != null ? errorState : t.somethingWentWrong })
6093
+ ] });
6094
+ }
6095
+ if (status === "awaiting_form" && activeSession) {
6096
+ const ctx = activeSession.entry_context;
6097
+ const formSpec = ctx.form_spec;
6098
+ return /* @__PURE__ */ jsx("div", { className: cls, style: rootStyle, children: /* @__PURE__ */ jsx("div", { className: widget_default.formScrollArea, children: /* @__PURE__ */ jsx(
6099
+ FormRenderer,
6078
6100
  {
6079
- field,
6080
- voiceHint: spokenHint,
6081
- apiBase: apiBaseResolved,
6082
- participantToken,
6083
- sessionId: activeSession.id,
6084
- liveConfig: surfaceConfig != null ? surfaceConfig : void 0,
6085
- onValue: handleLiveValue,
6101
+ fields: formSpec == null ? void 0 : formSpec.fields,
6102
+ repeater: (_d = formSpec == null ? void 0 : formSpec.repeaters) == null ? void 0 : _d[0],
6103
+ onSubmit: (values) => void submitHandback(values),
6086
6104
  disabled: submitting
6087
6105
  }
6088
- ) : voiceRenderer === "continuous" ? /* @__PURE__ */ jsx(
6089
- VoiceContinuousRenderer,
6106
+ ) }) });
6107
+ }
6108
+ if (status === "awaiting_editor" && activeSession) {
6109
+ const editorCtx = activeSession.entry_context;
6110
+ const isImageSession = (editorCtx == null ? void 0 : editorCtx.document_type) === "image";
6111
+ return /* @__PURE__ */ jsx("div", { className: cls, style: rootStyle, children: isImageSession ? /* @__PURE__ */ jsx(
6112
+ ImageEditorRenderer,
6090
6113
  {
6091
- field,
6092
- voiceHint: spokenHint,
6114
+ session: activeSession,
6115
+ onHandback: (output2) => submitHandback(output2).then(() => void 0),
6093
6116
  apiBase: apiBaseResolved,
6094
6117
  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
6118
  disabled: submitting
6101
6119
  }
6102
6120
  ) : /* @__PURE__ */ jsx(
6103
- VoiceRenderer,
6121
+ EditorRenderer,
6104
6122
  {
6105
- field,
6106
- voiceHint: spokenHint,
6123
+ session: activeSession,
6124
+ onHandback: (output2) => submitHandback(output2).then(() => void 0),
6107
6125
  apiBase: apiBaseResolved,
6108
6126
  participantToken,
6109
- onValue: handleVoiceValue,
6110
- useServerTTS: (surfaceConfig == null ? void 0 : surfaceConfig.tts) === "server",
6111
6127
  disabled: submitting
6112
6128
  }
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,
6129
+ ) });
6130
+ }
6131
+ const converseCtx = activeSession == null ? void 0 : activeSession.entry_context;
6132
+ const isConverseSession = (converseCtx == null ? void 0 : converseCtx.converse_session) === true;
6133
+ const converseUserCanEnd = (converseCtx == null ? void 0 : converseCtx.converse_user_can_end) === true;
6134
+ const field = activeSession ? extractField(activeSession) : null;
6135
+ if (status === "awaiting_chat" && activeSession && !(isConverseSession && field)) {
6136
+ const hbCtx = (_e = activeSession.entry_context) == null ? void 0 : _e.handback;
6137
+ const outputSchema = hbCtx == null ? void 0 : hbCtx.output_schema;
6138
+ const requireOutput = (_f = hbCtx == null ? void 0 : hbCtx.require_output) != null ? _f : false;
6139
+ const handbackReady = !requireOutput || outputSchema != null && Object.keys(outputSchema).every((k) => {
6140
+ var _a2;
6141
+ return ((_a2 = handbackValues[k]) != null ? _a2 : "").trim() !== "";
6142
+ });
6143
+ return /* @__PURE__ */ jsxs("div", { className: cls, style: rootStyle, children: [
6144
+ header,
6145
+ /* @__PURE__ */ jsx(ChatTimeline, { entries: timeline, streamingText, components }),
6146
+ /* @__PURE__ */ jsxs("div", { ref: inputAreaRef, className: widget_default.chatInputRow, children: [
6147
+ /* @__PURE__ */ jsx(
6148
+ "textarea",
6149
+ {
6150
+ className: widget_default.chatInput,
6151
+ placeholder: t.chatInputPlaceholder,
6152
+ value: inputValue != null ? inputValue : "",
6153
+ onChange: (e) => {
6154
+ setInputValue(e.target.value);
6155
+ setInputError(null);
6156
+ },
6157
+ onKeyDown: (e) => {
6158
+ if (e.key === "Enter" && !e.shiftKey) {
6159
+ e.preventDefault();
6160
+ if (inputValue) {
6161
+ void sendMessage(inputValue);
6162
+ setInputValue(void 0);
6163
+ }
6164
+ }
6165
+ },
6166
+ disabled: submitting,
6167
+ rows: 1
6168
+ }
6169
+ ),
6170
+ /* @__PURE__ */ jsx(
6171
+ "button",
6172
+ {
6173
+ className: widget_default.chatSendButton,
6174
+ disabled: submitting || !inputValue,
6175
+ onClick: () => {
6176
+ if (inputValue) {
6177
+ void sendMessage(inputValue);
6178
+ setInputValue(void 0);
6179
+ }
6180
+ },
6181
+ children: t.sendButton
6182
+ }
6183
+ )
6184
+ ] }),
6185
+ /* @__PURE__ */ jsxs("div", { className: widget_default.handbackSection, children: [
6186
+ outputSchema != null && /* @__PURE__ */ jsx("div", { className: widget_default.handbackForm, children: Object.entries(outputSchema).map(([key, typeStr]) => {
6187
+ var _a2, _b2;
6188
+ const isEnum = typeStr.includes("|");
6189
+ const options = isEnum ? typeStr.split("|").map((o) => o.trim()) : [];
6190
+ const label = key.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
6191
+ return /* @__PURE__ */ jsxs("div", { className: widget_default.handbackField, children: [
6192
+ /* @__PURE__ */ jsx("label", { className: widget_default.handbackFieldLabel, children: label }),
6193
+ isEnum ? /* @__PURE__ */ jsxs(
6194
+ "select",
6195
+ {
6196
+ className: widget_default.handbackFieldSelect,
6197
+ value: (_a2 = handbackValues[key]) != null ? _a2 : "",
6198
+ onChange: (e) => setHandbackValues((prev) => ({ ...prev, [key]: e.target.value })),
6199
+ disabled: submitting,
6200
+ children: [
6201
+ /* @__PURE__ */ jsx("option", { value: "", disabled: true, children: "Select\u2026" }),
6202
+ options.map((opt) => /* @__PURE__ */ jsx("option", { value: opt, children: opt }, opt))
6203
+ ]
6204
+ }
6205
+ ) : /* @__PURE__ */ jsx(
6206
+ "textarea",
6207
+ {
6208
+ className: widget_default.handbackFieldTextarea,
6209
+ value: (_b2 = handbackValues[key]) != null ? _b2 : "",
6210
+ onChange: (e) => setHandbackValues((prev) => ({ ...prev, [key]: e.target.value })),
6211
+ disabled: submitting,
6212
+ rows: 2
6213
+ }
6214
+ )
6215
+ ] }, key);
6216
+ }) }),
6217
+ /* @__PURE__ */ jsx(
6218
+ "button",
6219
+ {
6220
+ className: widget_default.handbackButton,
6221
+ onClick: () => void submitHandback(
6222
+ outputSchema != null ? handbackValues : void 0
6223
+ ),
6224
+ disabled: submitting || !handbackReady,
6225
+ children: t.handBackButton
6226
+ }
6227
+ )
6228
+ ] })
6229
+ ] });
6230
+ }
6231
+ const surface = activeSession ? extractSurface(activeSession) : null;
6232
+ const surfaceConfig = activeSession ? extractSurfaceConfig(activeSession) : null;
6233
+ const nodeVoice = activeSession ? extractNodeVoice(activeSession) : null;
6234
+ const InputComponent = field ? getInputComponent(field.input_type) : null;
6235
+ const effectiveVoiceMode = resolveVoiceMode(surface, surfaceConfig, nodeVoice);
6236
+ const shouldUseVoice = effectiveVoiceMode !== "off";
6237
+ const voiceRenderer = effectiveVoiceMode === "push_to_talk" ? "click" : "continuous";
6238
+ const isLiveVoice = surface === "widget/voice" && (surfaceConfig == null ? void 0 : surfaceConfig.style) === "live";
6239
+ if (shouldUseVoice && activeSession && field) {
6240
+ const spokenHint = (_h = nodeVoice == null ? void 0 : nodeVoice.hint) != null ? _h : (_g = field.voice) == null ? void 0 : _g.hint;
6241
+ const handleVoiceValue = (value) => {
6242
+ setInputValue(value);
6243
+ void submitHandback(value, crypto.randomUUID());
6244
+ };
6245
+ const handleLiveValue = (value) => {
6246
+ setInputValue(value);
6247
+ };
6248
+ return /* @__PURE__ */ jsxs("div", { className: cls, style: rootStyle, children: [
6249
+ header,
6250
+ /* @__PURE__ */ jsx(ChatTimeline, { entries: timeline, showTyping, streamingText, components }),
6251
+ /* @__PURE__ */ jsx("div", { className: widget_default.activeInputArea, children: isLiveVoice ? /* @__PURE__ */ jsx(
6252
+ VoiceLiveRenderer,
6140
6253
  {
6141
6254
  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
6255
+ voiceHint: spokenHint,
6256
+ apiBase: apiBaseResolved,
6257
+ participantToken,
6258
+ sessionId: activeSession.id,
6259
+ liveConfig: surfaceConfig != null ? surfaceConfig : void 0,
6260
+ onValue: handleLiveValue,
6261
+ disabled: submitting
6155
6262
  }
6156
- ) }),
6157
- field.input_type !== "Display" && !(field.input_type === "SingleSelect" && field.variant === "buttons") && /* @__PURE__ */ jsx(
6263
+ ) : voiceRenderer === "continuous" ? /* @__PURE__ */ jsx(
6264
+ VoiceContinuousRenderer,
6265
+ {
6266
+ field,
6267
+ voiceHint: spokenHint,
6268
+ apiBase: apiBaseResolved,
6269
+ participantToken,
6270
+ onValue: handleVoiceValue,
6271
+ autoSubmitMode: "confirm",
6272
+ 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,
6273
+ enqueueSpeak,
6274
+ isSpeaking,
6275
+ disabled: submitting
6276
+ }
6277
+ ) : /* @__PURE__ */ jsx(
6278
+ VoiceRenderer,
6279
+ {
6280
+ field,
6281
+ voiceHint: spokenHint,
6282
+ apiBase: apiBaseResolved,
6283
+ participantToken,
6284
+ onValue: handleVoiceValue,
6285
+ useServerTTS: (surfaceConfig == null ? void 0 : surfaceConfig.tts) === "server",
6286
+ disabled: submitting
6287
+ }
6288
+ ) })
6289
+ ] });
6290
+ }
6291
+ const showConnectionOnboarding = !connectionsLoading && !allConnectionsProvided && !connectionOnboardingDismissed && requiredConnections.some((c) => !c.provided);
6292
+ if (showConnectionOnboarding) {
6293
+ return /* @__PURE__ */ jsx("div", { className: cls, style: rootStyle, children: /* @__PURE__ */ jsx(
6294
+ ConnectionOnboarding,
6295
+ {
6296
+ connections: requiredConnections,
6297
+ appBase: appBaseResolved,
6298
+ participantToken,
6299
+ onSkip: () => setConnectionOnboardingDismissed(true),
6300
+ onDisconnect: disconnectConnection
6301
+ }
6302
+ ) });
6303
+ }
6304
+ return /* @__PURE__ */ jsxs("div", { className: cls, style: rootStyle, children: [
6305
+ header,
6306
+ /* @__PURE__ */ jsx(ChatTimeline, { entries: timeline, showTyping, streamingText, components }),
6307
+ activeSession && field && InputComponent && /* @__PURE__ */ jsxs("form", { ref: inputAreaRef, className: widget_default.activeInputArea, onSubmit: handleSubmit, children: [
6308
+ isConverseSession && /* @__PURE__ */ jsxs("div", { className: widget_default.converseHint, children: [
6309
+ /* @__PURE__ */ jsx("span", { className: widget_default.converseHintDot }),
6310
+ "Collecting your answers\u2026"
6311
+ ] }),
6312
+ field.prompt && /* @__PURE__ */ jsx("div", { className: widget_default.activeInputPrompt, children: field.prompt }),
6313
+ /* @__PURE__ */ jsxs("div", { className: widget_default.activeInputRow, children: [
6314
+ /* @__PURE__ */ jsx("div", { className: widget_default.activeInputField, children: /* @__PURE__ */ jsx(
6315
+ InputComponent,
6316
+ {
6317
+ field,
6318
+ value: inputValue,
6319
+ onChange: (v) => {
6320
+ setInputValue(v);
6321
+ setInputError(null);
6322
+ setServerErrors([]);
6323
+ },
6324
+ onSubmit: handleAutoSubmit,
6325
+ disabled: submitting,
6326
+ uploadContext: field.input_type === "FileUpload" && activeSession ? {
6327
+ apiBase: apiBaseResolved,
6328
+ participantToken,
6329
+ sessionId: activeSession.id
6330
+ } : void 0
6331
+ }
6332
+ ) }),
6333
+ field.input_type !== "Display" && !(field.input_type === "SingleSelect" && field.variant === "buttons") && /* @__PURE__ */ jsx(
6334
+ "button",
6335
+ {
6336
+ type: "submit",
6337
+ className: widget_default.activeInputSubmit,
6338
+ disabled: submitting,
6339
+ children: submitting ? "\u2026" : t.sendButton
6340
+ }
6341
+ )
6342
+ ] }),
6343
+ inputError && /* @__PURE__ */ jsx("div", { className: widget_default.inlineError, children: inputError }),
6344
+ serverErrors.length > 1 && serverErrors.slice(1).map((e, i) => /* @__PURE__ */ jsxs("div", { className: widget_default.inlineError, children: [
6345
+ e.field !== "_" ? `${e.field}: ` : "",
6346
+ e.message
6347
+ ] }, i)),
6348
+ isConverseSession && converseUserCanEnd && /* @__PURE__ */ jsx(
6158
6349
  "button",
6159
6350
  {
6160
- type: "submit",
6161
- className: widget_default.activeInputSubmit,
6351
+ type: "button",
6352
+ className: widget_default.converseDoneButton,
6353
+ onClick: () => void submitHandback({ _done: true }),
6162
6354
  disabled: submitting,
6163
- children: submitting ? "\u2026" : "Send"
6355
+ children: t.converseDoneButton
6164
6356
  }
6165
6357
  )
6166
6358
  ] }),
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
- }
6359
+ !activeSession && status === "running" && timeline.length === 0 && (emptyState != null ? emptyState : /* @__PURE__ */ jsx(StatusDisplay, { status: "running", strings })),
6360
+ footer
6361
+ ] });
6362
+ }
6363
+ );
6176
6364
  function extractField(session) {
6177
6365
  var _a, _b;
6178
6366
  const ctx = session.entry_context;
@@ -6253,36 +6441,328 @@ function resolveVoiceMode(surface, surfaceConfig, nodeVoice) {
6253
6441
  if ((nodeVoice == null ? void 0 : nodeVoice.capture) === "continuous") return "continuous";
6254
6442
  return style === "push_to_talk" ? "push_to_talk" : "continuous";
6255
6443
  }
6256
- function ChatterflyWidget(props) {
6444
+
6445
+ // src/sessionPersistence.ts
6446
+ function resolveOptions(config) {
6257
6447
  var _a, _b;
6448
+ if (!config) return null;
6449
+ const opts = config === true ? {} : config;
6450
+ return {
6451
+ storage: (_a = opts.storage) != null ? _a : "session",
6452
+ key: (_b = opts.key) != null ? _b : ""
6453
+ };
6454
+ }
6455
+ function storageFor(kind) {
6456
+ if (typeof window === "undefined") return null;
6457
+ try {
6458
+ return kind === "local" ? window.localStorage : window.sessionStorage;
6459
+ } catch {
6460
+ return null;
6461
+ }
6462
+ }
6463
+ function storageKey(target, custom) {
6464
+ return custom ? `chatterfly:session:${custom}` : `chatterfly:session:${target}`;
6465
+ }
6466
+ function loadPersistedSession(config, target) {
6467
+ const opts = config ? resolveOptions(config) : null;
6468
+ if (!opts || !target) return null;
6469
+ const store = storageFor(opts.storage);
6470
+ if (!store) return null;
6471
+ try {
6472
+ const raw = store.getItem(storageKey(target, opts.key));
6473
+ if (!raw) return null;
6474
+ const parsed = JSON.parse(raw);
6475
+ if (typeof parsed.runId === "string" && typeof parsed.participantToken === "string") {
6476
+ return { runId: parsed.runId, participantToken: parsed.participantToken };
6477
+ }
6478
+ } catch {
6479
+ }
6480
+ return null;
6481
+ }
6482
+ function savePersistedSession(config, target, session) {
6483
+ const opts = config ? resolveOptions(config) : null;
6484
+ if (!opts || !target) return;
6485
+ const store = storageFor(opts.storage);
6486
+ if (!store) return;
6487
+ try {
6488
+ store.setItem(storageKey(target, opts.key), JSON.stringify(session));
6489
+ } catch {
6490
+ }
6491
+ }
6492
+ function clearPersistedSession(config, target) {
6493
+ const opts = config ? resolveOptions(config) : null;
6494
+ if (!opts || !target) return;
6495
+ const store = storageFor(opts.storage);
6496
+ if (!store) return;
6497
+ try {
6498
+ store.removeItem(storageKey(target, opts.key));
6499
+ } catch {
6500
+ }
6501
+ }
6502
+ var ChatterflyWidget = forwardRef(
6503
+ function ChatterflyWidget2(props, ref) {
6504
+ var _a, _b, _c, _d, _e, _f, _g, _h;
6505
+ const [resolved, setResolved] = useState(null);
6506
+ const [configError, setConfigError] = useState(null);
6507
+ const [restartNonce, setRestartNonce] = useState(0);
6508
+ const adapterRef = useRef(null);
6509
+ const autoStarting = Boolean(!props.runId && (props.deploymentId || props.workflowId));
6510
+ const persistTarget = (_a = props.workflowId) != null ? _a : props.deploymentId;
6511
+ useEffect(() => {
6512
+ var _a2;
6513
+ if (props.runId) return;
6514
+ if (!props.deploymentId && !props.workflowId) return;
6515
+ if (!props.apiBase) {
6516
+ const err = new WidgetError(
6517
+ "config_missing_api_base",
6518
+ "ChatterflyWidget requires an `apiBase` prop pointing at your Chatterfly backend \u2014 there is no localhost default."
6519
+ );
6520
+ setConfigError(err);
6521
+ (_a2 = props.onError) == null ? void 0 : _a2.call(props, err);
6522
+ return;
6523
+ }
6524
+ setConfigError(null);
6525
+ if (restartNonce === 0) {
6526
+ const persisted = loadPersistedSession(props.persistSession, persistTarget);
6527
+ if (persisted) {
6528
+ setResolved({ runId: persisted.runId, participantToken: persisted.participantToken });
6529
+ return;
6530
+ }
6531
+ }
6532
+ const base = props.apiBase;
6533
+ const startUrl = props.workflowId ? `${base}/api/public/workflows/${props.workflowId}/start` : `${base}/api/public/surveys/${props.deploymentId}/start`;
6534
+ const body = props.initialInput ? JSON.stringify({ input: props.initialInput }) : void 0;
6535
+ fetch(startUrl, {
6536
+ method: "POST",
6537
+ headers: body ? { "Content-Type": "application/json" } : void 0,
6538
+ body
6539
+ }).then(async (r) => {
6540
+ if (!r.ok) {
6541
+ const code = r.status === 404 ? "no_live_deployment" : "workflow_not_public";
6542
+ const detail = await r.text().catch(() => "");
6543
+ throw new WidgetError(
6544
+ code,
6545
+ `Failed to start run (HTTP ${r.status})${detail ? `: ${detail}` : ""}`
6546
+ );
6547
+ }
6548
+ return r.json();
6549
+ }).then(({ run_id, participant_token }) => {
6550
+ setResolved({ runId: run_id, participantToken: participant_token });
6551
+ savePersistedSession(props.persistSession, persistTarget, {
6552
+ runId: run_id,
6553
+ participantToken: participant_token
6554
+ });
6555
+ }).catch((err) => {
6556
+ var _a3;
6557
+ const widgetErr = err instanceof WidgetError ? err : new WidgetError("network", err instanceof Error ? err.message : String(err));
6558
+ (_a3 = props.onError) == null ? void 0 : _a3.call(props, widgetErr);
6559
+ });
6560
+ }, [props.deploymentId, props.workflowId, props.apiBase, restartNonce]);
6561
+ const restart = useCallback(() => {
6562
+ var _a2;
6563
+ if (autoStarting) {
6564
+ clearPersistedSession(props.persistSession, persistTarget);
6565
+ setResolved(null);
6566
+ setRestartNonce((n) => n + 1);
6567
+ } else {
6568
+ (_a2 = adapterRef.current) == null ? void 0 : _a2.restart();
6569
+ }
6570
+ }, [autoStarting, props.persistSession, persistTarget]);
6571
+ const disconnect = useCallback(() => {
6572
+ var _a2;
6573
+ (_a2 = adapterRef.current) == null ? void 0 : _a2.disconnect();
6574
+ }, []);
6575
+ const sendMessage = useCallback((text) => {
6576
+ var _a2;
6577
+ (_a2 = adapterRef.current) == null ? void 0 : _a2.sendMessage(text);
6578
+ }, []);
6579
+ useImperativeHandle(ref, () => ({ restart, disconnect, sendMessage }), [
6580
+ restart,
6581
+ disconnect,
6582
+ sendMessage
6583
+ ]);
6584
+ const runId = (_b = resolved == null ? void 0 : resolved.runId) != null ? _b : props.runId;
6585
+ const participantToken = (_c = resolved == null ? void 0 : resolved.participantToken) != null ? _c : props.participantToken;
6586
+ const mode = (_d = props.mode) != null ? _d : "inline";
6587
+ const [open, setOpen] = useState((_e = props.defaultOpen) != null ? _e : false);
6588
+ const [unreadCount, setUnreadCount] = useState(0);
6589
+ const toggleOpen = useCallback(() => {
6590
+ setOpen((prev) => {
6591
+ var _a2;
6592
+ const next = !prev;
6593
+ if (next) setUnreadCount(0);
6594
+ (_a2 = props.onOpenChange) == null ? void 0 : _a2.call(props, next);
6595
+ return next;
6596
+ });
6597
+ }, [props.onOpenChange]);
6598
+ const handleMessage = useCallback(
6599
+ (message) => {
6600
+ var _a2;
6601
+ if (mode === "floating" && !open) setUnreadCount((n) => n + 1);
6602
+ (_a2 = props.onMessage) == null ? void 0 : _a2.call(props, message);
6603
+ },
6604
+ // eslint-disable-next-line react-hooks/exhaustive-deps
6605
+ [mode, open, props.onMessage]
6606
+ );
6607
+ let content;
6608
+ if (configError) {
6609
+ content = (_f = props.loadingFallback) != null ? _f : /* @__PURE__ */ jsx(StatusDisplay, { status: "error" });
6610
+ } else if (!runId || !participantToken) {
6611
+ content = (_g = props.loadingFallback) != null ? _g : /* @__PURE__ */ jsx(StatusDisplay, { status: autoStarting ? "connecting" : "error" });
6612
+ } else {
6613
+ content = /* @__PURE__ */ jsx(
6614
+ ChatAdapter,
6615
+ {
6616
+ ...props,
6617
+ ref: adapterRef,
6618
+ runId,
6619
+ participantToken,
6620
+ onMessage: handleMessage
6621
+ }
6622
+ );
6623
+ }
6624
+ if (mode !== "floating") {
6625
+ return content;
6626
+ }
6627
+ const position = (_h = props.position) != null ? _h : "bottom-right";
6628
+ return /* @__PURE__ */ jsx(
6629
+ FloatingLauncherChrome,
6630
+ {
6631
+ position,
6632
+ open,
6633
+ onToggle: toggleOpen,
6634
+ unreadCount,
6635
+ icon: props.launcherIcon,
6636
+ children: content
6637
+ }
6638
+ );
6639
+ }
6640
+ );
6641
+ function DefaultLauncherIcon() {
6642
+ return /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", width: "24", height: "24", fill: "none", "aria-hidden": "true", children: /* @__PURE__ */ jsx(
6643
+ "path",
6644
+ {
6645
+ d: "M4 4h16v11H8l-4 4V4z",
6646
+ stroke: "currentColor",
6647
+ strokeWidth: "2",
6648
+ strokeLinejoin: "round",
6649
+ fill: "none"
6650
+ }
6651
+ ) });
6652
+ }
6653
+ function FloatingLauncherChrome({
6654
+ position,
6655
+ open,
6656
+ onToggle,
6657
+ unreadCount,
6658
+ icon,
6659
+ children
6660
+ }) {
6661
+ const rootClass = [
6662
+ widget_default.launcherRoot,
6663
+ position === "bottom-left" ? widget_default.launcherRootLeft : widget_default.launcherRootRight
6664
+ ].join(" ");
6665
+ return /* @__PURE__ */ jsxs("div", { className: rootClass, children: [
6666
+ open && /* @__PURE__ */ jsx("div", { className: widget_default.launcherPanel, children }),
6667
+ /* @__PURE__ */ jsxs(
6668
+ "button",
6669
+ {
6670
+ type: "button",
6671
+ className: widget_default.launcherButton,
6672
+ onClick: onToggle,
6673
+ "aria-expanded": open,
6674
+ "aria-label": open ? "Close chat" : "Open chat",
6675
+ children: [
6676
+ /* @__PURE__ */ jsx("span", { className: widget_default.launcherIcon, children: icon != null ? icon : /* @__PURE__ */ jsx(DefaultLauncherIcon, {}) }),
6677
+ !open && unreadCount > 0 && /* @__PURE__ */ jsx("span", { className: widget_default.launcherBadge, children: unreadCount > 9 ? "9+" : unreadCount })
6678
+ ]
6679
+ }
6680
+ )
6681
+ ] });
6682
+ }
6683
+ function useChatterflyRun(options) {
6684
+ var _a, _b;
6685
+ const { runId, participantToken, apiBase, deploymentId, workflowId, initialInput, persistSession, onEvent } = options;
6258
6686
  const [resolved, setResolved] = useState(null);
6687
+ const [error, setError] = useState(null);
6688
+ const [restartNonce, setRestartNonce] = useState(0);
6689
+ const autoStarting = Boolean(!runId && (deploymentId || workflowId));
6690
+ const persistTarget = workflowId != null ? workflowId : deploymentId;
6259
6691
  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`;
6692
+ if (runId) return;
6693
+ if (!deploymentId && !workflowId) return;
6694
+ if (!apiBase) {
6695
+ const err = new WidgetError(
6696
+ "config_missing_api_base",
6697
+ "useChatterflyRun requires `apiBase` \u2014 there is no localhost default."
6698
+ );
6699
+ setError(err);
6700
+ return;
6701
+ }
6702
+ setError(null);
6703
+ if (restartNonce === 0) {
6704
+ const persisted = loadPersistedSession(persistSession, persistTarget);
6705
+ if (persisted) {
6706
+ setResolved({ runId: persisted.runId, participantToken: persisted.participantToken });
6707
+ return;
6708
+ }
6709
+ }
6710
+ const startUrl = workflowId ? `${apiBase}/api/public/workflows/${workflowId}/start` : `${apiBase}/api/public/surveys/${deploymentId}/start`;
6711
+ const body = initialInput ? JSON.stringify({ input: initialInput }) : void 0;
6265
6712
  fetch(startUrl, {
6266
- method: "POST"
6267
- }).then((r) => {
6268
- if (!r.ok) throw new Error(`HTTP ${r.status}`);
6713
+ method: "POST",
6714
+ headers: body ? { "Content-Type": "application/json" } : void 0,
6715
+ body
6716
+ }).then(async (r) => {
6717
+ if (!r.ok) {
6718
+ const code = r.status === 404 ? "no_live_deployment" : "workflow_not_public";
6719
+ const detail = await r.text().catch(() => "");
6720
+ throw new WidgetError(
6721
+ code,
6722
+ `Failed to start run (HTTP ${r.status})${detail ? `: ${detail}` : ""}`
6723
+ );
6724
+ }
6269
6725
  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);
6726
+ }).then(({ run_id, participant_token }) => {
6727
+ setResolved({ runId: run_id, participantToken: participant_token });
6728
+ savePersistedSession(persistSession, persistTarget, {
6729
+ runId: run_id,
6730
+ participantToken: participant_token
6731
+ });
6732
+ }).catch((err) => {
6733
+ setError(
6734
+ err instanceof WidgetError ? err : new WidgetError("network", err instanceof Error ? err.message : String(err))
6735
+ );
6275
6736
  });
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 });
6737
+ }, [runId, deploymentId, workflowId, apiBase, restartNonce]);
6738
+ const effectiveRunId = (_a = resolved == null ? void 0 : resolved.runId) != null ? _a : runId;
6739
+ const effectiveToken = (_b = resolved == null ? void 0 : resolved.participantToken) != null ? _b : participantToken;
6740
+ const stream = useRunStream(
6741
+ {
6742
+ runId: effectiveRunId != null ? effectiveRunId : "",
6743
+ participantToken: effectiveToken != null ? effectiveToken : "",
6744
+ apiBase: apiBase != null ? apiBase : ""
6745
+ },
6746
+ onEvent
6747
+ );
6748
+ const restart = useCallback(() => {
6749
+ if (autoStarting) {
6750
+ clearPersistedSession(persistSession, persistTarget);
6751
+ setResolved(null);
6752
+ setRestartNonce((n) => n + 1);
6753
+ } else {
6754
+ stream.reconnect();
6755
+ }
6756
+ }, [autoStarting, persistSession, persistTarget, stream]);
6757
+ const connecting = autoStarting && !resolved && !error;
6758
+ return {
6759
+ ...stream,
6760
+ connecting,
6761
+ error,
6762
+ restart
6763
+ };
6284
6764
  }
6285
6765
 
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 };
6766
+ 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
6767
  //# sourceMappingURL=index.mjs.map
6288
6768
  //# sourceMappingURL=index.mjs.map