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