@chatterfly/widget 0.3.0 → 0.5.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/README.md +12 -2
- package/dist/embed.css +1 -1
- package/dist/embed.css.map +1 -1
- package/dist/embed.global.js +33 -27
- package/dist/embed.global.js.map +1 -1
- package/dist/index.css +140 -15
- package/dist/index.css.map +1 -1
- package/dist/index.d.mts +106 -7
- package/dist/index.d.ts +106 -7
- package/dist/index.js +904 -263
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +905 -264
- package/dist/index.mjs.map +1 -1
- package/package.json +61 -60
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { forwardRef, useCallback, useImperativeHandle,
|
|
1
|
+
import { forwardRef, useCallback, useImperativeHandle, useState, useEffect, useMemo, useRef, createElement } from 'react';
|
|
2
2
|
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
|
|
3
3
|
|
|
4
4
|
// src/components/ChatterflyWidget.tsx
|
|
@@ -13,11 +13,68 @@ var WidgetError = class {
|
|
|
13
13
|
return this.message;
|
|
14
14
|
}
|
|
15
15
|
};
|
|
16
|
-
|
|
16
|
+
|
|
17
|
+
// src/strings.ts
|
|
18
|
+
var defaultStrings = {
|
|
19
|
+
statusInitialising: "Initialising\u2026",
|
|
20
|
+
statusConnecting: "Connecting\u2026",
|
|
21
|
+
statusRunning: "Running\u2026",
|
|
22
|
+
statusCompletedTitle: "Completed",
|
|
23
|
+
statusCompletedBody: "This workflow run has finished.",
|
|
24
|
+
statusErrorTitle: "Something went wrong",
|
|
25
|
+
statusOfflineTitle: "Connection lost",
|
|
26
|
+
statusOfflineBody: "Unable to reach the server. Please check your connection and refresh.",
|
|
27
|
+
statusExpiredTitle: "Session expired",
|
|
28
|
+
statusExpiredBody: "This conversation's session has expired. Start a new one to continue.",
|
|
29
|
+
statusListening: "Listening\u2026",
|
|
30
|
+
resumingConversation: "Resuming conversation\u2026",
|
|
31
|
+
reconnecting: "Reconnecting\u2026",
|
|
32
|
+
conversationCompleted: "Conversation completed.",
|
|
33
|
+
somethingWentWrong: "Something went wrong",
|
|
34
|
+
chatInputPlaceholder: "Type a message\u2026",
|
|
35
|
+
sendButton: "Send",
|
|
36
|
+
handBackButton: "Hand Back",
|
|
37
|
+
converseDoneButton: "I'm done",
|
|
38
|
+
startConversation: "Start conversation",
|
|
39
|
+
clickToStartDescription: "Click below to begin.",
|
|
40
|
+
resumeTitle: "Continue where you left off?",
|
|
41
|
+
resumeContinue: "Continue",
|
|
42
|
+
resumeRestart: "Start fresh",
|
|
43
|
+
startNewConversation: "Start new conversation",
|
|
44
|
+
conversationEnded: "This conversation has ended."
|
|
45
|
+
};
|
|
46
|
+
function resolveStrings(overrides) {
|
|
47
|
+
return overrides ? { ...defaultStrings, ...overrides } : defaultStrings;
|
|
48
|
+
}
|
|
49
|
+
var RECONNECT_BASE_DELAY_MS = 2e3;
|
|
50
|
+
var RECONNECT_MAX_DELAY_MS = 3e4;
|
|
17
51
|
var MAX_RECONNECT_ATTEMPTS = 5;
|
|
18
|
-
var TERMINAL_STATUSES = ["completed", "error", "offline"];
|
|
52
|
+
var TERMINAL_STATUSES = ["completed", "error", "offline", "expired"];
|
|
53
|
+
var PARKED_STATUSES = [
|
|
54
|
+
"awaiting_input",
|
|
55
|
+
"awaiting_voice",
|
|
56
|
+
"awaiting_form",
|
|
57
|
+
"awaiting_chat",
|
|
58
|
+
"awaiting_editor"
|
|
59
|
+
];
|
|
60
|
+
var DEFAULT_IDLE_DISCONNECT_MS = 5 * 6e4;
|
|
61
|
+
var DEFAULT_POLL_INTERVAL_MS = 45e3;
|
|
62
|
+
var DEFAULT_HIBERNATE_AFTER_MS = 60 * 6e4;
|
|
63
|
+
function computeReconnectDelay(attempt) {
|
|
64
|
+
const cap = Math.min(
|
|
65
|
+
RECONNECT_MAX_DELAY_MS,
|
|
66
|
+
RECONNECT_BASE_DELAY_MS * 2 ** attempt
|
|
67
|
+
);
|
|
68
|
+
return Math.random() * cap;
|
|
69
|
+
}
|
|
19
70
|
function useRunStream(config, onEvent) {
|
|
71
|
+
var _a, _b, _c;
|
|
20
72
|
const { runId, participantToken, apiBase } = config;
|
|
73
|
+
const policyConfig = config.connectionPolicy;
|
|
74
|
+
const dormancyDisabled = policyConfig === "always-on";
|
|
75
|
+
const idleDisconnectMs = (_a = !dormancyDisabled && typeof policyConfig === "object" ? policyConfig == null ? void 0 : policyConfig.idleDisconnectMs : void 0) != null ? _a : DEFAULT_IDLE_DISCONNECT_MS;
|
|
76
|
+
const pollIntervalMs = (_b = !dormancyDisabled && typeof policyConfig === "object" ? policyConfig == null ? void 0 : policyConfig.pollIntervalMs : void 0) != null ? _b : DEFAULT_POLL_INTERVAL_MS;
|
|
77
|
+
const hibernateAfterMs = (_c = !dormancyDisabled && typeof policyConfig === "object" ? policyConfig == null ? void 0 : policyConfig.hibernateAfterMs : void 0) != null ? _c : DEFAULT_HIBERNATE_AFTER_MS;
|
|
21
78
|
const [status, setStatus] = useState("idle");
|
|
22
79
|
const [activeSession, setActiveSession] = useState(null);
|
|
23
80
|
const [messages, setMessages] = useState([]);
|
|
@@ -26,11 +83,19 @@ function useRunStream(config, onEvent) {
|
|
|
26
83
|
const [output, setOutput] = useState(null);
|
|
27
84
|
const lastSeqRef = useRef(0);
|
|
28
85
|
const [lastSeq, setLastSeq] = useState(0);
|
|
86
|
+
const [currentToken, setCurrentToken] = useState(participantToken);
|
|
87
|
+
const currentTokenRef = useRef(currentToken);
|
|
88
|
+
currentTokenRef.current = currentToken;
|
|
89
|
+
useEffect(() => setCurrentToken(participantToken), [participantToken]);
|
|
29
90
|
const wsRef = useRef(null);
|
|
30
91
|
const statusRef = useRef("idle");
|
|
31
92
|
const reconnectTimerRef = useRef(null);
|
|
32
93
|
const replayTimeoutRef = useRef(null);
|
|
33
94
|
const mountedRef = useRef(true);
|
|
95
|
+
const connectionStateRef = useRef("active");
|
|
96
|
+
const idleTimerRef = useRef(null);
|
|
97
|
+
const hibernateTimerRef = useRef(null);
|
|
98
|
+
const pollTimerRef = useRef(null);
|
|
34
99
|
const reconnectAttemptsRef = useRef(0);
|
|
35
100
|
const manualDisconnectRef = useRef(false);
|
|
36
101
|
const onEventRef = useRef(onEvent);
|
|
@@ -40,8 +105,8 @@ function useRunStream(config, onEvent) {
|
|
|
40
105
|
setStatus(next);
|
|
41
106
|
}, []);
|
|
42
107
|
const authHeaders = useCallback(
|
|
43
|
-
() => ({ Authorization: `Bearer ${
|
|
44
|
-
[
|
|
108
|
+
() => ({ Authorization: `Bearer ${currentTokenRef.current}` }),
|
|
109
|
+
[]
|
|
45
110
|
);
|
|
46
111
|
const mergeTimeline = useCallback(
|
|
47
112
|
(incoming) => {
|
|
@@ -63,9 +128,18 @@ function useRunStream(config, onEvent) {
|
|
|
63
128
|
if (!mountedRef.current) return;
|
|
64
129
|
if (!runId || !apiBase) return;
|
|
65
130
|
manualDisconnectRef.current = false;
|
|
131
|
+
connectionStateRef.current = "active";
|
|
132
|
+
if (pollTimerRef.current) {
|
|
133
|
+
clearInterval(pollTimerRef.current);
|
|
134
|
+
pollTimerRef.current = null;
|
|
135
|
+
}
|
|
136
|
+
if (hibernateTimerRef.current) {
|
|
137
|
+
clearTimeout(hibernateTimerRef.current);
|
|
138
|
+
hibernateTimerRef.current = null;
|
|
139
|
+
}
|
|
66
140
|
updateStatus("connecting");
|
|
67
141
|
const wsUrl = apiBase.replace(/^http/, "ws") + `/api/participant/runs/${runId}/stream`;
|
|
68
|
-
const params = new URLSearchParams({ token:
|
|
142
|
+
const params = new URLSearchParams({ token: currentTokenRef.current });
|
|
69
143
|
const ws = new WebSocket(`${wsUrl}?${params}`);
|
|
70
144
|
wsRef.current = ws;
|
|
71
145
|
ws.onopen = () => {
|
|
@@ -103,15 +177,128 @@ function useRunStream(config, onEvent) {
|
|
|
103
177
|
if (isOffline) {
|
|
104
178
|
updateStatus("offline");
|
|
105
179
|
} else {
|
|
180
|
+
const attempt = reconnectAttemptsRef.current;
|
|
106
181
|
reconnectAttemptsRef.current += 1;
|
|
107
|
-
reconnectTimerRef.current = setTimeout(
|
|
182
|
+
reconnectTimerRef.current = setTimeout(
|
|
183
|
+
connect,
|
|
184
|
+
computeReconnectDelay(attempt)
|
|
185
|
+
);
|
|
108
186
|
}
|
|
109
187
|
}
|
|
110
188
|
};
|
|
111
189
|
}, [runId, participantToken, apiBase]);
|
|
190
|
+
const remintToken = useCallback(async () => {
|
|
191
|
+
try {
|
|
192
|
+
const res = await fetch(`${apiBase}/api/public/runs/${runId}/token`, {
|
|
193
|
+
method: "POST",
|
|
194
|
+
headers: { "Content-Type": "application/json" },
|
|
195
|
+
body: JSON.stringify({ participant_token: currentTokenRef.current })
|
|
196
|
+
});
|
|
197
|
+
if (!res.ok) return null;
|
|
198
|
+
const data = await res.json();
|
|
199
|
+
if (!data.participant_token) return null;
|
|
200
|
+
setCurrentToken(data.participant_token);
|
|
201
|
+
return data.participant_token;
|
|
202
|
+
} catch {
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
}, [apiBase, runId]);
|
|
206
|
+
const stopPolling = useCallback(() => {
|
|
207
|
+
if (pollTimerRef.current) {
|
|
208
|
+
clearInterval(pollTimerRef.current);
|
|
209
|
+
pollTimerRef.current = null;
|
|
210
|
+
}
|
|
211
|
+
if (hibernateTimerRef.current) {
|
|
212
|
+
clearTimeout(hibernateTimerRef.current);
|
|
213
|
+
hibernateTimerRef.current = null;
|
|
214
|
+
}
|
|
215
|
+
}, []);
|
|
216
|
+
const wake = useCallback(() => {
|
|
217
|
+
if (!mountedRef.current) return;
|
|
218
|
+
if (connectionStateRef.current === "active") return;
|
|
219
|
+
stopPolling();
|
|
220
|
+
reconnectAttemptsRef.current = 0;
|
|
221
|
+
connect();
|
|
222
|
+
}, [connect, stopPolling]);
|
|
223
|
+
const startPolling = useCallback(() => {
|
|
224
|
+
if (pollTimerRef.current) return;
|
|
225
|
+
pollTimerRef.current = setInterval(async () => {
|
|
226
|
+
if (!mountedRef.current) return;
|
|
227
|
+
try {
|
|
228
|
+
const res = await fetch(
|
|
229
|
+
`${apiBase}/api/participant/runs/${runId}/timeline?since_seq=${lastSeqRef.current}`,
|
|
230
|
+
{ headers: { Authorization: `Bearer ${currentTokenRef.current}` } }
|
|
231
|
+
);
|
|
232
|
+
if (res.status === 401) {
|
|
233
|
+
const fresh = await remintToken();
|
|
234
|
+
if (!fresh) {
|
|
235
|
+
stopPolling();
|
|
236
|
+
updateStatus("expired");
|
|
237
|
+
}
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (!res.ok) return;
|
|
241
|
+
const entries = await res.json();
|
|
242
|
+
if (Array.isArray(entries) && entries.length > 0) {
|
|
243
|
+
wake();
|
|
244
|
+
}
|
|
245
|
+
} catch {
|
|
246
|
+
}
|
|
247
|
+
}, pollIntervalMs);
|
|
248
|
+
hibernateTimerRef.current = setTimeout(() => {
|
|
249
|
+
connectionStateRef.current = "hibernating";
|
|
250
|
+
if (pollTimerRef.current) {
|
|
251
|
+
clearInterval(pollTimerRef.current);
|
|
252
|
+
pollTimerRef.current = null;
|
|
253
|
+
}
|
|
254
|
+
}, hibernateAfterMs);
|
|
255
|
+
}, [apiBase, runId, pollIntervalMs, hibernateAfterMs, remintToken, stopPolling, updateStatus, wake]);
|
|
256
|
+
const goDormant = useCallback(() => {
|
|
257
|
+
var _a2;
|
|
258
|
+
if (connectionStateRef.current !== "active") return;
|
|
259
|
+
connectionStateRef.current = "dormant";
|
|
260
|
+
manualDisconnectRef.current = true;
|
|
261
|
+
(_a2 = wsRef.current) == null ? void 0 : _a2.close();
|
|
262
|
+
wsRef.current = null;
|
|
263
|
+
startPolling();
|
|
264
|
+
}, [startPolling]);
|
|
265
|
+
useEffect(() => {
|
|
266
|
+
if (dormancyDisabled) return;
|
|
267
|
+
if (idleTimerRef.current) {
|
|
268
|
+
clearTimeout(idleTimerRef.current);
|
|
269
|
+
idleTimerRef.current = null;
|
|
270
|
+
}
|
|
271
|
+
if (PARKED_STATUSES.includes(status) && connectionStateRef.current === "active") {
|
|
272
|
+
idleTimerRef.current = setTimeout(goDormant, idleDisconnectMs);
|
|
273
|
+
}
|
|
274
|
+
return () => {
|
|
275
|
+
if (idleTimerRef.current) {
|
|
276
|
+
clearTimeout(idleTimerRef.current);
|
|
277
|
+
idleTimerRef.current = null;
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
}, [status, dormancyDisabled, idleDisconnectMs, goDormant]);
|
|
281
|
+
useEffect(() => {
|
|
282
|
+
if (dormancyDisabled) return;
|
|
283
|
+
const handleVisibility = () => {
|
|
284
|
+
if (document.visibilityState === "visible") wake();
|
|
285
|
+
};
|
|
286
|
+
document.addEventListener("visibilitychange", handleVisibility);
|
|
287
|
+
window.addEventListener("online", wake);
|
|
288
|
+
window.addEventListener("focus", wake);
|
|
289
|
+
window.addEventListener("pointerdown", wake);
|
|
290
|
+
window.addEventListener("keydown", wake);
|
|
291
|
+
return () => {
|
|
292
|
+
document.removeEventListener("visibilitychange", handleVisibility);
|
|
293
|
+
window.removeEventListener("online", wake);
|
|
294
|
+
window.removeEventListener("focus", wake);
|
|
295
|
+
window.removeEventListener("pointerdown", wake);
|
|
296
|
+
window.removeEventListener("keydown", wake);
|
|
297
|
+
};
|
|
298
|
+
}, [dormancyDisabled, wake]);
|
|
112
299
|
function handleEvent(event) {
|
|
113
|
-
var
|
|
114
|
-
(
|
|
300
|
+
var _a2, _b2, _c2, _d, _e;
|
|
301
|
+
(_a2 = onEventRef.current) == null ? void 0 : _a2.call(onEventRef, event);
|
|
115
302
|
switch (event.type) {
|
|
116
303
|
case "timeline.replay": {
|
|
117
304
|
mergeTimeline(event.payload);
|
|
@@ -148,7 +335,7 @@ function useRunStream(config, onEvent) {
|
|
|
148
335
|
entry_context: event.entry_context,
|
|
149
336
|
status: "open",
|
|
150
337
|
messages: replayedMessages,
|
|
151
|
-
document_content: (
|
|
338
|
+
document_content: (_b2 = event.document_content) != null ? _b2 : null
|
|
152
339
|
};
|
|
153
340
|
setActiveSession(session);
|
|
154
341
|
if (replayedMessages.length > 0) {
|
|
@@ -161,7 +348,7 @@ function useRunStream(config, onEvent) {
|
|
|
161
348
|
} else if (event.layout === "form") {
|
|
162
349
|
updateStatus("awaiting_form");
|
|
163
350
|
} else {
|
|
164
|
-
const surface = (
|
|
351
|
+
const surface = (_c2 = event.entry_context) == null ? void 0 : _c2.surface;
|
|
165
352
|
const isVoice = typeof surface === "string" && (surface === "widget/voice" || surface === "phone" || surface === "phone/outbound");
|
|
166
353
|
if (isVoice) {
|
|
167
354
|
updateStatus("awaiting_voice");
|
|
@@ -183,6 +370,9 @@ function useRunStream(config, onEvent) {
|
|
|
183
370
|
]);
|
|
184
371
|
break;
|
|
185
372
|
}
|
|
373
|
+
case "run_complete":
|
|
374
|
+
case "run_error":
|
|
375
|
+
break;
|
|
186
376
|
case "run.completed":
|
|
187
377
|
case "run.cancelled":
|
|
188
378
|
setStreamingText("");
|
|
@@ -201,17 +391,21 @@ function useRunStream(config, onEvent) {
|
|
|
201
391
|
mountedRef.current = true;
|
|
202
392
|
reconnectTimerRef.current = setTimeout(connect, 0);
|
|
203
393
|
return () => {
|
|
204
|
-
var
|
|
394
|
+
var _a2;
|
|
205
395
|
mountedRef.current = false;
|
|
206
396
|
if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
|
|
207
397
|
if (replayTimeoutRef.current) clearTimeout(replayTimeoutRef.current);
|
|
208
|
-
(
|
|
398
|
+
if (idleTimerRef.current) clearTimeout(idleTimerRef.current);
|
|
399
|
+
if (pollTimerRef.current) clearInterval(pollTimerRef.current);
|
|
400
|
+
if (hibernateTimerRef.current) clearTimeout(hibernateTimerRef.current);
|
|
401
|
+
(_a2 = wsRef.current) == null ? void 0 : _a2.close();
|
|
209
402
|
wsRef.current = null;
|
|
210
403
|
};
|
|
211
404
|
}, [connect]);
|
|
212
405
|
const sendMessage = useCallback(
|
|
213
406
|
async (content) => {
|
|
214
407
|
if (!activeSession) return;
|
|
408
|
+
wake();
|
|
215
409
|
setMessages((prev) => [
|
|
216
410
|
...prev,
|
|
217
411
|
{ role: "human", content }
|
|
@@ -238,12 +432,13 @@ function useRunStream(config, onEvent) {
|
|
|
238
432
|
throw new Error(`sendMessage failed: ${res.status} ${text}`);
|
|
239
433
|
}
|
|
240
434
|
},
|
|
241
|
-
[activeSession, apiBase, authHeaders, updateStatus]
|
|
435
|
+
[activeSession, apiBase, authHeaders, updateStatus, wake]
|
|
242
436
|
);
|
|
243
437
|
const submitHandback = useCallback(
|
|
244
438
|
async (output2, idempotencyKey) => {
|
|
245
|
-
var
|
|
439
|
+
var _a2;
|
|
246
440
|
if (!activeSession) return null;
|
|
441
|
+
wake();
|
|
247
442
|
const body = { output: output2 };
|
|
248
443
|
if (idempotencyKey) body.idempotency_key = idempotencyKey;
|
|
249
444
|
let res;
|
|
@@ -265,7 +460,7 @@ function useRunStream(config, onEvent) {
|
|
|
265
460
|
}
|
|
266
461
|
if (res.status === 422) {
|
|
267
462
|
const data = await res.json();
|
|
268
|
-
return (
|
|
463
|
+
return (_a2 = data.errors) != null ? _a2 : [{ field: "_", message: "Validation failed" }];
|
|
269
464
|
}
|
|
270
465
|
if (!res.ok) {
|
|
271
466
|
const text = await res.text();
|
|
@@ -276,13 +471,13 @@ function useRunStream(config, onEvent) {
|
|
|
276
471
|
updateStatus("running");
|
|
277
472
|
return null;
|
|
278
473
|
},
|
|
279
|
-
[activeSession, apiBase, authHeaders, updateStatus]
|
|
474
|
+
[activeSession, apiBase, authHeaders, updateStatus, wake]
|
|
280
475
|
);
|
|
281
476
|
const disconnect = useCallback(() => {
|
|
282
|
-
var
|
|
477
|
+
var _a2;
|
|
283
478
|
manualDisconnectRef.current = true;
|
|
284
479
|
if (reconnectTimerRef.current) clearTimeout(reconnectTimerRef.current);
|
|
285
|
-
(
|
|
480
|
+
(_a2 = wsRef.current) == null ? void 0 : _a2.close();
|
|
286
481
|
wsRef.current = null;
|
|
287
482
|
updateStatus("offline");
|
|
288
483
|
}, [updateStatus]);
|
|
@@ -484,6 +679,7 @@ var widget_default = {
|
|
|
484
679
|
formKvValue: "widget_formKvValue",
|
|
485
680
|
formKvNested: "widget_formKvNested",
|
|
486
681
|
activeInputArea: "widget_activeInputArea",
|
|
682
|
+
activeInputAreaVoice: "widget_activeInputAreaVoice",
|
|
487
683
|
formTimelineWrapper: "widget_formTimelineWrapper",
|
|
488
684
|
formScrollArea: "widget_formScrollArea",
|
|
489
685
|
activeInputPrompt: "widget_activeInputPrompt",
|
|
@@ -497,9 +693,17 @@ var widget_default = {
|
|
|
497
693
|
activeInputSubmit: "widget_activeInputSubmit",
|
|
498
694
|
inlineError: "widget_inlineError",
|
|
499
695
|
resumingBanner: "widget_resumingBanner",
|
|
696
|
+
reconnectingPill: "widget_reconnectingPill",
|
|
500
697
|
terminalBanner: "widget_terminalBanner",
|
|
501
698
|
terminalCompleted: "widget_terminalBanner widget_terminalCompleted",
|
|
502
699
|
terminalError: "widget_terminalBanner widget_terminalError",
|
|
700
|
+
startNewConversationButton: "widget_startNewConversationButton",
|
|
701
|
+
gateCard: "widget_gateCard",
|
|
702
|
+
gateTitle: "widget_gateTitle",
|
|
703
|
+
gateDescription: "widget_gateDescription",
|
|
704
|
+
gateActions: "widget_gateActions",
|
|
705
|
+
gateButtonPrimary: "widget_gateButtonPrimary",
|
|
706
|
+
gateButtonSecondary: "widget_gateButtonSecondary",
|
|
503
707
|
typingIndicator: "widget_typingIndicator",
|
|
504
708
|
typingDot: "widget_typingDot",
|
|
505
709
|
cfTyping: "widget_cfTyping",
|
|
@@ -523,13 +727,17 @@ var widget_default = {
|
|
|
523
727
|
voiceRatingMatched: "widget_voiceRatingMatched",
|
|
524
728
|
voiceRatingLabels: "widget_voiceRatingLabels",
|
|
525
729
|
voiceTranscript: "widget_voiceTranscript",
|
|
526
|
-
|
|
730
|
+
voiceLiveLog: "widget_voiceLiveLog",
|
|
731
|
+
voiceLiveLogUser: "widget_voiceLiveLogUser",
|
|
732
|
+
voiceLiveLogAssistant: "widget_voiceLiveLogAssistant",
|
|
527
733
|
voiceTranscriptText: "widget_voiceTranscriptText",
|
|
734
|
+
voiceTranscriptLabel: "widget_voiceTranscriptLabel",
|
|
528
735
|
voiceError: "widget_voiceError",
|
|
529
736
|
cfVoiceShake: "widget_cfVoiceShake",
|
|
530
737
|
voiceOrbContainer: "widget_voiceOrbContainer",
|
|
531
|
-
|
|
738
|
+
voiceOrbRow: "widget_voiceOrbRow",
|
|
532
739
|
voiceOrbHint: "widget_voiceOrbHint",
|
|
740
|
+
voiceAssistantStatus: "widget_voiceAssistantStatus",
|
|
533
741
|
voiceOrb: "widget_voiceOrb",
|
|
534
742
|
cfVoiceBreathe: "widget_cfVoiceBreathe",
|
|
535
743
|
voiceOrbDisabled: "widget_voiceOrbDisabled",
|
|
@@ -538,12 +746,12 @@ var widget_default = {
|
|
|
538
746
|
voiceOrbRing2: "widget_voiceOrbRing2",
|
|
539
747
|
voiceOrb_idle: "widget_voiceOrb_idle",
|
|
540
748
|
voiceOrb_listening: "widget_voiceOrb_listening",
|
|
541
|
-
cfVoicePulse: "widget_cfVoicePulse",
|
|
542
749
|
voiceOrb_speaking: "widget_voiceOrb_speaking",
|
|
543
|
-
cfVoiceWave: "widget_cfVoiceWave",
|
|
544
750
|
voiceOrb_processing: "widget_voiceOrb_processing",
|
|
545
751
|
voiceOrb_confirming: "widget_voiceOrb_confirming",
|
|
546
752
|
voiceOrb_error: "widget_voiceOrb_error",
|
|
753
|
+
cfVoicePulse: "widget_cfVoicePulse",
|
|
754
|
+
cfVoiceWave: "widget_cfVoiceWave",
|
|
547
755
|
voiceAudioLevelBar: "widget_voiceAudioLevelBar",
|
|
548
756
|
voiceMuteButton: "widget_voiceMuteButton",
|
|
549
757
|
voiceConfirmation: "widget_voiceConfirmation",
|
|
@@ -2668,29 +2876,6 @@ function FormRenderer({
|
|
|
2668
2876
|
) })
|
|
2669
2877
|
] });
|
|
2670
2878
|
}
|
|
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
2879
|
function StatusDisplay({ status, error, strings }) {
|
|
2695
2880
|
const t = strings ? { ...defaultStrings, ...strings } : defaultStrings;
|
|
2696
2881
|
switch (status) {
|
|
@@ -2720,6 +2905,11 @@ function StatusDisplay({ status, error, strings }) {
|
|
|
2720
2905
|
/* @__PURE__ */ jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: t.statusOfflineTitle }),
|
|
2721
2906
|
/* @__PURE__ */ jsx("div", { className: `${widget_default.statusLabel} ${widget_default.statusError}`, children: t.statusOfflineBody })
|
|
2722
2907
|
] });
|
|
2908
|
+
case "expired":
|
|
2909
|
+
return /* @__PURE__ */ jsxs("div", { className: widget_default.statusWrapper, children: [
|
|
2910
|
+
/* @__PURE__ */ jsx("div", { className: `${widget_default.statusTitle} ${widget_default.statusError}`, children: t.statusExpiredTitle }),
|
|
2911
|
+
/* @__PURE__ */ jsx("div", { className: `${widget_default.statusLabel} ${widget_default.statusError}`, children: t.statusExpiredBody })
|
|
2912
|
+
] });
|
|
2723
2913
|
case "awaiting_voice":
|
|
2724
2914
|
return /* @__PURE__ */ jsxs("div", { className: widget_default.statusWrapper, children: [
|
|
2725
2915
|
/* @__PURE__ */ jsx("div", { className: widget_default.spinner, "aria-hidden": true }),
|
|
@@ -2731,6 +2921,7 @@ function StatusDisplay({ status, error, strings }) {
|
|
|
2731
2921
|
}
|
|
2732
2922
|
function VoiceOrb({
|
|
2733
2923
|
state,
|
|
2924
|
+
inputLevel = 0,
|
|
2734
2925
|
onPress,
|
|
2735
2926
|
onRelease,
|
|
2736
2927
|
disabled
|
|
@@ -2756,6 +2947,7 @@ function VoiceOrb({
|
|
|
2756
2947
|
},
|
|
2757
2948
|
[disabled, onRelease]
|
|
2758
2949
|
);
|
|
2950
|
+
const level = Math.min(1, Math.max(0, inputLevel));
|
|
2759
2951
|
return /* @__PURE__ */ jsxs(
|
|
2760
2952
|
"button",
|
|
2761
2953
|
{
|
|
@@ -2768,8 +2960,26 @@ function VoiceOrb({
|
|
|
2768
2960
|
disabled,
|
|
2769
2961
|
"aria-label": ariaForState(state),
|
|
2770
2962
|
children: [
|
|
2771
|
-
/* @__PURE__ */ jsx(
|
|
2772
|
-
|
|
2963
|
+
/* @__PURE__ */ jsx(
|
|
2964
|
+
"span",
|
|
2965
|
+
{
|
|
2966
|
+
className: widget_default.voiceOrbRing1,
|
|
2967
|
+
style: {
|
|
2968
|
+
opacity: 0.18 + level * 0.42,
|
|
2969
|
+
transform: `scale(${1.08 + level * 0.24})`
|
|
2970
|
+
}
|
|
2971
|
+
}
|
|
2972
|
+
),
|
|
2973
|
+
/* @__PURE__ */ jsx(
|
|
2974
|
+
"span",
|
|
2975
|
+
{
|
|
2976
|
+
className: widget_default.voiceOrbRing2,
|
|
2977
|
+
style: {
|
|
2978
|
+
opacity: 0.1 + level * 0.32,
|
|
2979
|
+
transform: `scale(${1.18 + level * 0.42})`
|
|
2980
|
+
}
|
|
2981
|
+
}
|
|
2982
|
+
),
|
|
2773
2983
|
/* @__PURE__ */ jsx("span", { className: widget_default.voiceOrbIcon, children: state === "listening" ? micIcon : state === "speaking" ? speakerIcon : micIcon })
|
|
2774
2984
|
]
|
|
2775
2985
|
}
|
|
@@ -4142,13 +4352,29 @@ function VoiceContinuousRenderer({
|
|
|
4142
4352
|
/* @__PURE__ */ jsx("button", { onClick: () => handleConfirmation(false), children: "No, retry" })
|
|
4143
4353
|
] }),
|
|
4144
4354
|
/* @__PURE__ */ jsxs("div", { className: widget_default.voiceOrbContainer, children: [
|
|
4145
|
-
/* @__PURE__ */
|
|
4146
|
-
|
|
4147
|
-
|
|
4148
|
-
|
|
4149
|
-
|
|
4150
|
-
|
|
4151
|
-
|
|
4355
|
+
/* @__PURE__ */ jsxs("div", { className: widget_default.voiceOrbRow, children: [
|
|
4356
|
+
/* @__PURE__ */ jsx(
|
|
4357
|
+
VoiceOrb,
|
|
4358
|
+
{
|
|
4359
|
+
state: getOrbState(),
|
|
4360
|
+
disabled: disabled || voiceState === "processing" || transcribing
|
|
4361
|
+
}
|
|
4362
|
+
),
|
|
4363
|
+
/* @__PURE__ */ jsx(
|
|
4364
|
+
"button",
|
|
4365
|
+
{
|
|
4366
|
+
type: "button",
|
|
4367
|
+
"data-cf-voice-mute": "true",
|
|
4368
|
+
className: `${widget_default.voiceMuteButton}${isMuted ? " " + widget_default.voiceMuteButtonMuted : ""}`,
|
|
4369
|
+
onClick: handleMuteToggle,
|
|
4370
|
+
title: isMuted ? "Unmute microphone (Spacebar)" : "Mute microphone (Spacebar)",
|
|
4371
|
+
"aria-label": isMuted ? "Unmute microphone" : "Mute microphone",
|
|
4372
|
+
"aria-pressed": isMuted,
|
|
4373
|
+
"aria-keyshortcuts": "Space",
|
|
4374
|
+
children: isMuted ? "\u{1F507}" : "\u{1F3A4}"
|
|
4375
|
+
}
|
|
4376
|
+
)
|
|
4377
|
+
] }),
|
|
4152
4378
|
/* @__PURE__ */ jsxs("div", { className: widget_default.voiceOrbStats, children: [
|
|
4153
4379
|
/* @__PURE__ */ jsxs("span", { className: widget_default.voiceOrbHint, children: [
|
|
4154
4380
|
isMuted && "\u{1F507} Muted",
|
|
@@ -4171,21 +4397,7 @@ function VoiceContinuousRenderer({
|
|
|
4171
4397
|
Math.round(confidence * 100),
|
|
4172
4398
|
"% confident"
|
|
4173
4399
|
] })
|
|
4174
|
-
] })
|
|
4175
|
-
/* @__PURE__ */ jsx(
|
|
4176
|
-
"button",
|
|
4177
|
-
{
|
|
4178
|
-
type: "button",
|
|
4179
|
-
"data-cf-voice-mute": "true",
|
|
4180
|
-
className: `${widget_default.voiceMuteButton}${isMuted ? " " + widget_default.voiceMuteButtonMuted : ""}`,
|
|
4181
|
-
onClick: handleMuteToggle,
|
|
4182
|
-
title: isMuted ? "Unmute microphone (Spacebar)" : "Mute microphone (Spacebar)",
|
|
4183
|
-
"aria-label": isMuted ? "Unmute microphone" : "Mute microphone",
|
|
4184
|
-
"aria-pressed": isMuted,
|
|
4185
|
-
"aria-keyshortcuts": "Space",
|
|
4186
|
-
children: isMuted ? "\u{1F507}" : "\u{1F3A4}"
|
|
4187
|
-
}
|
|
4188
|
-
)
|
|
4400
|
+
] })
|
|
4189
4401
|
] }),
|
|
4190
4402
|
retryCount >= 3 && /* @__PURE__ */ jsx("a", { href: "#", className: widget_default.voiceTypeFallback, children: "Switch to typing mode" })
|
|
4191
4403
|
] });
|
|
@@ -4235,7 +4447,7 @@ class PcmCaptureProcessor extends AudioWorkletProcessor {
|
|
|
4235
4447
|
this._buf = new Int16Array(this.frameSamples);
|
|
4236
4448
|
this._pos = 0;
|
|
4237
4449
|
this._acc = 0;
|
|
4238
|
-
this.
|
|
4450
|
+
this._accWeight = 0;
|
|
4239
4451
|
}
|
|
4240
4452
|
|
|
4241
4453
|
_emit() {
|
|
@@ -4250,18 +4462,24 @@ class PcmCaptureProcessor extends AudioWorkletProcessor {
|
|
|
4250
4462
|
if (!input || !input[0]) return true;
|
|
4251
4463
|
const ch = input[0];
|
|
4252
4464
|
for (let i = 0; i < ch.length; i++) {
|
|
4253
|
-
|
|
4254
|
-
|
|
4255
|
-
|
|
4256
|
-
|
|
4257
|
-
|
|
4258
|
-
|
|
4259
|
-
|
|
4260
|
-
|
|
4261
|
-
|
|
4262
|
-
|
|
4263
|
-
|
|
4264
|
-
|
|
4465
|
+
let sourceWeight = 1;
|
|
4466
|
+
while (sourceWeight > 0) {
|
|
4467
|
+
const weight = Math.min(sourceWeight, this.ratio - this._accWeight);
|
|
4468
|
+
this._acc += ch[i] * weight;
|
|
4469
|
+
this._accWeight += weight;
|
|
4470
|
+
sourceWeight -= weight;
|
|
4471
|
+
|
|
4472
|
+
if (this._accWeight + 1e-10 >= this.ratio) {
|
|
4473
|
+
const avg = this._acc / this._accWeight;
|
|
4474
|
+
// Clamp to [-1, 1] then quantize to int16.
|
|
4475
|
+
let s = avg;
|
|
4476
|
+
if (s > 1) s = 1;
|
|
4477
|
+
else if (s < -1) s = -1;
|
|
4478
|
+
this._buf[this._pos++] = s < 0 ? s * 0x8000 : s * 0x7fff;
|
|
4479
|
+
this._acc = 0;
|
|
4480
|
+
this._accWeight = 0;
|
|
4481
|
+
if (this._pos >= this.frameSamples) this._emit();
|
|
4482
|
+
}
|
|
4265
4483
|
}
|
|
4266
4484
|
}
|
|
4267
4485
|
return true;
|
|
@@ -4297,7 +4515,10 @@ function useGeminiLiveSession(cfg, onValue) {
|
|
|
4297
4515
|
const [transcripts, setTranscripts] = useState([]);
|
|
4298
4516
|
const [assistantText, setAssistantText] = useState("");
|
|
4299
4517
|
const [activeFieldId, setActiveFieldId] = useState(null);
|
|
4518
|
+
const [askedFieldId, setAskedFieldId] = useState(null);
|
|
4519
|
+
const [playbackComplete, setPlaybackComplete] = useState(false);
|
|
4300
4520
|
const [lastValue, setLastValue] = useState(null);
|
|
4521
|
+
const [inputLevel, setInputLevel] = useState(0);
|
|
4301
4522
|
const [isMuted, setIsMuted] = useState(false);
|
|
4302
4523
|
const [error, setError] = useState(null);
|
|
4303
4524
|
const wsRef = useRef(null);
|
|
@@ -4306,17 +4527,55 @@ function useGeminiLiveSession(cfg, onValue) {
|
|
|
4306
4527
|
const workletRef = useRef(null);
|
|
4307
4528
|
const sourceRef = useRef(null);
|
|
4308
4529
|
const playbackQueueTimeRef = useRef(0);
|
|
4530
|
+
const playbackNodesRef = useRef(/* @__PURE__ */ new Set());
|
|
4309
4531
|
const isMutedRef = useRef(false);
|
|
4310
4532
|
const onValueRef = useRef(onValue);
|
|
4311
4533
|
const disposedRef = useRef(false);
|
|
4534
|
+
const smoothedInputLevelRef = useRef(0);
|
|
4535
|
+
const inputLevelFrameRef = useRef(0);
|
|
4536
|
+
const terminalReceivedRef = useRef(false);
|
|
4537
|
+
const currentPlaybackTurnRef = useRef(null);
|
|
4538
|
+
const playbackTurnsRef = useRef(/* @__PURE__ */ new Map());
|
|
4539
|
+
const socketSessionIdRef = useRef(null);
|
|
4540
|
+
if (sessionId && socketSessionIdRef.current === null) {
|
|
4541
|
+
socketSessionIdRef.current = sessionId;
|
|
4542
|
+
}
|
|
4543
|
+
const socketSessionId = socketSessionIdRef.current;
|
|
4312
4544
|
useEffect(() => {
|
|
4313
4545
|
onValueRef.current = onValue;
|
|
4314
4546
|
}, [onValue]);
|
|
4315
4547
|
useEffect(() => {
|
|
4316
4548
|
isMutedRef.current = isMuted;
|
|
4317
4549
|
}, [isMuted]);
|
|
4550
|
+
const maybeCompletePlayback = useCallback(() => {
|
|
4551
|
+
if (terminalReceivedRef.current && playbackNodesRef.current.size === 0) {
|
|
4552
|
+
setPlaybackComplete(true);
|
|
4553
|
+
}
|
|
4554
|
+
}, []);
|
|
4555
|
+
const maybeFinishPlaybackTurn = useCallback(
|
|
4556
|
+
(turnId) => {
|
|
4557
|
+
const turn = playbackTurnsRef.current.get(turnId);
|
|
4558
|
+
if (!turn || !turn.serverEnded || turn.nodes.size > 0) return;
|
|
4559
|
+
playbackTurnsRef.current.delete(turnId);
|
|
4560
|
+
if (turn.purpose === "field" && turn.fieldId !== null) {
|
|
4561
|
+
setAskedFieldId(turn.fieldId);
|
|
4562
|
+
}
|
|
4563
|
+
const ws = wsRef.current;
|
|
4564
|
+
if ((ws == null ? void 0 : ws.readyState) === WebSocket.OPEN) {
|
|
4565
|
+
ws.send(
|
|
4566
|
+
JSON.stringify({
|
|
4567
|
+
type: "playback_turn_complete",
|
|
4568
|
+
turnId
|
|
4569
|
+
})
|
|
4570
|
+
);
|
|
4571
|
+
}
|
|
4572
|
+
maybeCompletePlayback();
|
|
4573
|
+
},
|
|
4574
|
+
[maybeCompletePlayback]
|
|
4575
|
+
);
|
|
4318
4576
|
const enqueuePlayback = useCallback(
|
|
4319
4577
|
(pcm) => {
|
|
4578
|
+
var _a;
|
|
4320
4579
|
const ctx = ctxRef.current;
|
|
4321
4580
|
if (!ctx) return;
|
|
4322
4581
|
const samples = new Int16Array(pcm);
|
|
@@ -4333,70 +4592,208 @@ function useGeminiLiveSession(cfg, onValue) {
|
|
|
4333
4592
|
const startAt = Math.max(now, playbackQueueTimeRef.current);
|
|
4334
4593
|
node.start(startAt);
|
|
4335
4594
|
playbackQueueTimeRef.current = startAt + buf.duration;
|
|
4595
|
+
const scheduled = playbackNodesRef.current;
|
|
4596
|
+
scheduled.add(node);
|
|
4597
|
+
const turnId = currentPlaybackTurnRef.current;
|
|
4598
|
+
if (turnId !== null) {
|
|
4599
|
+
(_a = playbackTurnsRef.current.get(turnId)) == null ? void 0 : _a.nodes.add(node);
|
|
4600
|
+
}
|
|
4601
|
+
node.onended = () => {
|
|
4602
|
+
var _a2;
|
|
4603
|
+
scheduled.delete(node);
|
|
4604
|
+
let turnEnded = false;
|
|
4605
|
+
if (turnId !== null) {
|
|
4606
|
+
const turn = playbackTurnsRef.current.get(turnId);
|
|
4607
|
+
turnEnded = (_a2 = turn == null ? void 0 : turn.serverEnded) != null ? _a2 : false;
|
|
4608
|
+
turn == null ? void 0 : turn.nodes.delete(node);
|
|
4609
|
+
maybeFinishPlaybackTurn(turnId);
|
|
4610
|
+
}
|
|
4611
|
+
if (scheduled.size === 0) {
|
|
4612
|
+
setState(
|
|
4613
|
+
(prev) => prev === "speaking" ? turnEnded ? "listening" : "processing" : prev
|
|
4614
|
+
);
|
|
4615
|
+
maybeCompletePlayback();
|
|
4616
|
+
}
|
|
4617
|
+
};
|
|
4618
|
+
setState(
|
|
4619
|
+
(prev) => prev === "listening" || prev === "processing" ? "speaking" : prev
|
|
4620
|
+
);
|
|
4336
4621
|
},
|
|
4337
|
-
[outputSampleRate]
|
|
4622
|
+
[maybeCompletePlayback, maybeFinishPlaybackTurn, outputSampleRate]
|
|
4338
4623
|
);
|
|
4339
|
-
const
|
|
4340
|
-
|
|
4341
|
-
|
|
4342
|
-
|
|
4343
|
-
|
|
4344
|
-
|
|
4345
|
-
|
|
4346
|
-
|
|
4347
|
-
|
|
4624
|
+
const noteMicLevel = useCallback((pcm) => {
|
|
4625
|
+
const samples = new Int16Array(pcm);
|
|
4626
|
+
if (samples.length === 0) return;
|
|
4627
|
+
let sum = 0;
|
|
4628
|
+
for (let i = 0; i < samples.length; i++) sum += samples[i] * samples[i];
|
|
4629
|
+
const rms = Math.sqrt(sum / samples.length);
|
|
4630
|
+
const normalized = Math.min(1, Math.max(0, (rms - 80) / 2400));
|
|
4631
|
+
const previous = smoothedInputLevelRef.current;
|
|
4632
|
+
const smoothing = normalized > previous ? 0.45 : 0.16;
|
|
4633
|
+
const next = previous + (normalized - previous) * smoothing;
|
|
4634
|
+
smoothedInputLevelRef.current = next;
|
|
4635
|
+
inputLevelFrameRef.current += 1;
|
|
4636
|
+
if (inputLevelFrameRef.current % 3 === 0) setInputLevel(next);
|
|
4637
|
+
}, []);
|
|
4638
|
+
const flushPlayback = useCallback(() => {
|
|
4639
|
+
const ws = wsRef.current;
|
|
4640
|
+
if ((ws == null ? void 0 : ws.readyState) === WebSocket.OPEN) {
|
|
4641
|
+
for (const turnId of playbackTurnsRef.current.keys()) {
|
|
4642
|
+
ws.send(
|
|
4643
|
+
JSON.stringify({
|
|
4644
|
+
type: "playback_turn_cancelled",
|
|
4645
|
+
turnId
|
|
4646
|
+
})
|
|
4647
|
+
);
|
|
4348
4648
|
}
|
|
4349
|
-
|
|
4350
|
-
|
|
4351
|
-
|
|
4352
|
-
|
|
4353
|
-
|
|
4354
|
-
|
|
4649
|
+
}
|
|
4650
|
+
const scheduled = playbackNodesRef.current;
|
|
4651
|
+
scheduled.forEach((node) => {
|
|
4652
|
+
try {
|
|
4653
|
+
node.onended = null;
|
|
4654
|
+
node.stop();
|
|
4655
|
+
node.disconnect();
|
|
4656
|
+
} catch {
|
|
4657
|
+
}
|
|
4658
|
+
});
|
|
4659
|
+
scheduled.clear();
|
|
4660
|
+
playbackTurnsRef.current.clear();
|
|
4661
|
+
currentPlaybackTurnRef.current = null;
|
|
4662
|
+
playbackQueueTimeRef.current = 0;
|
|
4663
|
+
}, []);
|
|
4664
|
+
const handleInbound = useCallback(
|
|
4665
|
+
(msg) => {
|
|
4666
|
+
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
4667
|
+
switch (msg.type) {
|
|
4668
|
+
case "state": {
|
|
4669
|
+
const next = String((_a = msg.state) != null ? _a : "");
|
|
4670
|
+
if (next === "listening" || next === "speaking" || next === "idle" || next === "connecting") {
|
|
4671
|
+
setState(next);
|
|
4672
|
+
} else if (next === "processing") {
|
|
4673
|
+
setState("connecting");
|
|
4674
|
+
}
|
|
4675
|
+
break;
|
|
4676
|
+
}
|
|
4677
|
+
case "interrupt": {
|
|
4678
|
+
flushPlayback();
|
|
4679
|
+
setState("listening");
|
|
4680
|
+
break;
|
|
4681
|
+
}
|
|
4682
|
+
case "transcript": {
|
|
4683
|
+
const text = String((_b = msg.text) != null ? _b : "");
|
|
4684
|
+
const final = msg.partial !== true;
|
|
4685
|
+
if (text.length === 0) break;
|
|
4686
|
+
setState((prev) => prev === "listening" ? "processing" : prev);
|
|
4687
|
+
setTranscripts((prev) => {
|
|
4355
4688
|
const next = prev.slice();
|
|
4356
|
-
const
|
|
4357
|
-
if (
|
|
4358
|
-
next[
|
|
4689
|
+
const last = next[next.length - 1];
|
|
4690
|
+
if (last && last.who === "user" && !last.final) {
|
|
4691
|
+
next[next.length - 1] = {
|
|
4692
|
+
who: "user",
|
|
4693
|
+
text: last.text + text,
|
|
4694
|
+
final
|
|
4695
|
+
};
|
|
4359
4696
|
return next;
|
|
4360
4697
|
}
|
|
4361
|
-
return [...next, { who, text, final }];
|
|
4698
|
+
return [...next, { who: "user", text, final }];
|
|
4699
|
+
});
|
|
4700
|
+
break;
|
|
4701
|
+
}
|
|
4702
|
+
case "assistant_text": {
|
|
4703
|
+
const text = String((_c = msg.text) != null ? _c : "");
|
|
4704
|
+
if (text.length === 0) break;
|
|
4705
|
+
setAssistantText(text);
|
|
4706
|
+
setTranscripts((prev) => {
|
|
4707
|
+
const next = prev.slice();
|
|
4708
|
+
const last = next[next.length - 1];
|
|
4709
|
+
if (last && last.who === "assistant" && !last.final) {
|
|
4710
|
+
next[next.length - 1] = {
|
|
4711
|
+
who: "assistant",
|
|
4712
|
+
text: last.text + text,
|
|
4713
|
+
final: false
|
|
4714
|
+
};
|
|
4715
|
+
return next;
|
|
4716
|
+
}
|
|
4717
|
+
return [...next, { who: "assistant", text, final: false }];
|
|
4718
|
+
});
|
|
4719
|
+
break;
|
|
4720
|
+
}
|
|
4721
|
+
case "audio_turn_start": {
|
|
4722
|
+
const turnId = String((_d = msg.turnId) != null ? _d : "");
|
|
4723
|
+
if (turnId.length === 0) break;
|
|
4724
|
+
currentPlaybackTurnRef.current = turnId;
|
|
4725
|
+
playbackTurnsRef.current.set(turnId, {
|
|
4726
|
+
purpose: String((_e = msg.purpose) != null ? _e : ""),
|
|
4727
|
+
fieldId: typeof msg.fieldId === "string" && msg.fieldId.length > 0 ? msg.fieldId : null,
|
|
4728
|
+
nodes: /* @__PURE__ */ new Set(),
|
|
4729
|
+
serverEnded: false
|
|
4730
|
+
});
|
|
4731
|
+
setState(
|
|
4732
|
+
(prev) => prev === "speaking" || prev === "completed" || prev === "error" ? prev : "processing"
|
|
4733
|
+
);
|
|
4734
|
+
break;
|
|
4735
|
+
}
|
|
4736
|
+
case "audio_turn_end": {
|
|
4737
|
+
const turnId = String((_f = msg.turnId) != null ? _f : "");
|
|
4738
|
+
if (turnId.length === 0) break;
|
|
4739
|
+
const turn = playbackTurnsRef.current.get(turnId);
|
|
4740
|
+
if (turn) turn.serverEnded = true;
|
|
4741
|
+
if (currentPlaybackTurnRef.current === turnId) {
|
|
4742
|
+
currentPlaybackTurnRef.current = null;
|
|
4362
4743
|
}
|
|
4363
|
-
|
|
4364
|
-
|
|
4365
|
-
|
|
4366
|
-
|
|
4367
|
-
|
|
4368
|
-
|
|
4369
|
-
|
|
4370
|
-
|
|
4371
|
-
|
|
4372
|
-
|
|
4373
|
-
|
|
4374
|
-
|
|
4375
|
-
|
|
4376
|
-
|
|
4377
|
-
|
|
4378
|
-
|
|
4379
|
-
|
|
4380
|
-
|
|
4381
|
-
|
|
4744
|
+
setTranscripts((prev) => {
|
|
4745
|
+
const last = prev[prev.length - 1];
|
|
4746
|
+
if (!last || last.who !== "assistant" || last.final) return prev;
|
|
4747
|
+
const next = prev.slice();
|
|
4748
|
+
next[next.length - 1] = { ...last, final: true };
|
|
4749
|
+
return next;
|
|
4750
|
+
});
|
|
4751
|
+
maybeFinishPlaybackTurn(turnId);
|
|
4752
|
+
break;
|
|
4753
|
+
}
|
|
4754
|
+
case "field_change": {
|
|
4755
|
+
const fieldId = String((_g = msg.fieldId) != null ? _g : "");
|
|
4756
|
+
setActiveFieldId(fieldId);
|
|
4757
|
+
setState(
|
|
4758
|
+
(prev) => prev === "speaking" || prev === "error" ? prev : "processing"
|
|
4759
|
+
);
|
|
4760
|
+
break;
|
|
4761
|
+
}
|
|
4762
|
+
case "value": {
|
|
4763
|
+
const v = msg.value;
|
|
4764
|
+
setLastValue(v);
|
|
4765
|
+
setState(
|
|
4766
|
+
(prev) => prev === "speaking" || prev === "error" ? prev : "processing"
|
|
4767
|
+
);
|
|
4768
|
+
try {
|
|
4769
|
+
onValueRef.current(v);
|
|
4770
|
+
} catch {
|
|
4771
|
+
}
|
|
4772
|
+
break;
|
|
4773
|
+
}
|
|
4774
|
+
case "completed": {
|
|
4775
|
+
terminalReceivedRef.current = true;
|
|
4776
|
+
setState("completed");
|
|
4777
|
+
maybeCompletePlayback();
|
|
4778
|
+
break;
|
|
4779
|
+
}
|
|
4780
|
+
case "error": {
|
|
4781
|
+
setError(String((_h = msg.message) != null ? _h : "voice session error"));
|
|
4782
|
+
setState("error");
|
|
4783
|
+
break;
|
|
4382
4784
|
}
|
|
4383
|
-
break;
|
|
4384
|
-
}
|
|
4385
|
-
case "completed": {
|
|
4386
|
-
setState("completed");
|
|
4387
|
-
break;
|
|
4388
|
-
}
|
|
4389
|
-
case "error": {
|
|
4390
|
-
setError(String((_e = msg.message) != null ? _e : "voice session error"));
|
|
4391
|
-
setState("error");
|
|
4392
|
-
break;
|
|
4393
4785
|
}
|
|
4394
|
-
}
|
|
4395
|
-
|
|
4786
|
+
},
|
|
4787
|
+
[flushPlayback, maybeCompletePlayback, maybeFinishPlaybackTurn]
|
|
4788
|
+
);
|
|
4396
4789
|
useEffect(() => {
|
|
4397
|
-
if (!
|
|
4790
|
+
if (!socketSessionId || !participantToken) return;
|
|
4398
4791
|
let cancelled = false;
|
|
4399
4792
|
disposedRef.current = false;
|
|
4793
|
+
terminalReceivedRef.current = false;
|
|
4794
|
+
currentPlaybackTurnRef.current = null;
|
|
4795
|
+
playbackTurnsRef.current.clear();
|
|
4796
|
+
setPlaybackComplete(false);
|
|
4400
4797
|
const start = async () => {
|
|
4401
4798
|
try {
|
|
4402
4799
|
setState("connecting");
|
|
@@ -4428,7 +4825,7 @@ function useGeminiLiveSession(cfg, onValue) {
|
|
|
4428
4825
|
});
|
|
4429
4826
|
workletRef.current = worklet;
|
|
4430
4827
|
source.connect(worklet);
|
|
4431
|
-
const wsUrl = apiBase.replace(/^http/, "ws") + `/api/participant/inbox/${encodeURIComponent(
|
|
4828
|
+
const wsUrl = apiBase.replace(/^http/, "ws") + `/api/participant/inbox/${encodeURIComponent(socketSessionId)}/voice-stream?token=${encodeURIComponent(participantToken)}`;
|
|
4432
4829
|
const ws = new WebSocket(wsUrl, SUBPROTOCOL);
|
|
4433
4830
|
ws.binaryType = "arraybuffer";
|
|
4434
4831
|
wsRef.current = ws;
|
|
@@ -4468,7 +4865,9 @@ function useGeminiLiveSession(cfg, onValue) {
|
|
|
4468
4865
|
worklet.port.onmessage = (ev) => {
|
|
4469
4866
|
if (isMutedRef.current) return;
|
|
4470
4867
|
if (ws.readyState !== WebSocket.OPEN) return;
|
|
4471
|
-
|
|
4868
|
+
const pcm = ev.data;
|
|
4869
|
+
noteMicLevel(pcm);
|
|
4870
|
+
ws.send(pcm);
|
|
4472
4871
|
};
|
|
4473
4872
|
} catch (err) {
|
|
4474
4873
|
if (cancelled) return;
|
|
@@ -4509,11 +4908,12 @@ function useGeminiLiveSession(cfg, onValue) {
|
|
|
4509
4908
|
}, [
|
|
4510
4909
|
apiBase,
|
|
4511
4910
|
participantToken,
|
|
4512
|
-
|
|
4911
|
+
socketSessionId,
|
|
4513
4912
|
inputSampleRate,
|
|
4514
4913
|
outputSampleRate,
|
|
4515
4914
|
enqueuePlayback,
|
|
4516
|
-
handleInbound
|
|
4915
|
+
handleInbound,
|
|
4916
|
+
noteMicLevel
|
|
4517
4917
|
]);
|
|
4518
4918
|
const toggleMute = useCallback(() => {
|
|
4519
4919
|
setIsMuted((prev) => {
|
|
@@ -4531,7 +4931,10 @@ function useGeminiLiveSession(cfg, onValue) {
|
|
|
4531
4931
|
transcripts,
|
|
4532
4932
|
assistantText,
|
|
4533
4933
|
activeFieldId,
|
|
4934
|
+
askedFieldId,
|
|
4935
|
+
playbackComplete,
|
|
4534
4936
|
lastValue,
|
|
4937
|
+
inputLevel: isMuted ? 0 : inputLevel,
|
|
4535
4938
|
isMuted,
|
|
4536
4939
|
toggleMute,
|
|
4537
4940
|
error
|
|
@@ -4542,11 +4945,13 @@ function VoiceLiveRenderer({
|
|
|
4542
4945
|
apiBase,
|
|
4543
4946
|
participantToken,
|
|
4544
4947
|
sessionId,
|
|
4948
|
+
fieldSessionId,
|
|
4545
4949
|
liveConfig,
|
|
4546
4950
|
onValue,
|
|
4951
|
+
onPlaybackComplete,
|
|
4952
|
+
onFieldRevealed,
|
|
4547
4953
|
disabled
|
|
4548
4954
|
}) {
|
|
4549
|
-
var _a;
|
|
4550
4955
|
const session = useGeminiLiveSession(
|
|
4551
4956
|
{
|
|
4552
4957
|
apiBase,
|
|
@@ -4557,13 +4962,20 @@ function VoiceLiveRenderer({
|
|
|
4557
4962
|
},
|
|
4558
4963
|
onValue
|
|
4559
4964
|
);
|
|
4965
|
+
useEffect(() => {
|
|
4966
|
+
if (session.playbackComplete) onPlaybackComplete == null ? void 0 : onPlaybackComplete();
|
|
4967
|
+
}, [session.playbackComplete, onPlaybackComplete]);
|
|
4560
4968
|
useEffect(() => {
|
|
4561
4969
|
}, [session.activeFieldId]);
|
|
4970
|
+
const fieldRevealed = session.askedFieldId === field.id;
|
|
4971
|
+
useEffect(() => {
|
|
4972
|
+
if (fieldRevealed) onFieldRevealed == null ? void 0 : onFieldRevealed(fieldSessionId);
|
|
4973
|
+
}, [fieldRevealed, fieldSessionId, onFieldRevealed]);
|
|
4562
4974
|
const promptRef = useRef(null);
|
|
4563
4975
|
useEffect(() => {
|
|
4564
|
-
var
|
|
4565
|
-
(
|
|
4566
|
-
}, [field]);
|
|
4976
|
+
var _a;
|
|
4977
|
+
(_a = promptRef.current) == null ? void 0 : _a.scrollIntoView({ behavior: "smooth", block: "nearest" });
|
|
4978
|
+
}, [field, fieldRevealed]);
|
|
4567
4979
|
const orbState = (() => {
|
|
4568
4980
|
if (session.error) return "error";
|
|
4569
4981
|
if (session.isMuted) return "idle";
|
|
@@ -4573,8 +4985,10 @@ function VoiceLiveRenderer({
|
|
|
4573
4985
|
return "idle";
|
|
4574
4986
|
case "listening":
|
|
4575
4987
|
return "listening";
|
|
4576
|
-
case "
|
|
4988
|
+
case "processing":
|
|
4577
4989
|
return "processing";
|
|
4990
|
+
case "speaking":
|
|
4991
|
+
return "speaking";
|
|
4578
4992
|
case "completed":
|
|
4579
4993
|
return "idle";
|
|
4580
4994
|
case "error":
|
|
@@ -4583,12 +4997,17 @@ function VoiceLiveRenderer({
|
|
|
4583
4997
|
return "idle";
|
|
4584
4998
|
}
|
|
4585
4999
|
})();
|
|
4586
|
-
const
|
|
5000
|
+
const logRef = useRef(null);
|
|
5001
|
+
useEffect(() => {
|
|
5002
|
+
const el = logRef.current;
|
|
5003
|
+
if (el) el.scrollTop = el.scrollHeight;
|
|
5004
|
+
}, [session.transcripts]);
|
|
4587
5005
|
const announcement = (() => {
|
|
4588
5006
|
if (session.error) return session.error;
|
|
4589
5007
|
if (session.isMuted) return "Microphone muted.";
|
|
4590
5008
|
if (session.state === "connecting") return "Connecting to voice service.";
|
|
4591
|
-
if (session.state === "listening") return "
|
|
5009
|
+
if (session.state === "listening") return "Microphone listening.";
|
|
5010
|
+
if (session.state === "processing") return "Preparing the next step.";
|
|
4592
5011
|
if (session.state === "speaking") return "Assistant speaking.";
|
|
4593
5012
|
return "";
|
|
4594
5013
|
})();
|
|
@@ -4603,42 +5022,49 @@ function VoiceLiveRenderer({
|
|
|
4603
5022
|
children: announcement
|
|
4604
5023
|
}
|
|
4605
5024
|
),
|
|
4606
|
-
/* @__PURE__ */
|
|
4607
|
-
|
|
4608
|
-
|
|
4609
|
-
|
|
4610
|
-
|
|
4611
|
-
|
|
4612
|
-
|
|
4613
|
-
|
|
4614
|
-
|
|
5025
|
+
/* @__PURE__ */ jsxs("div", { className: widget_default.voiceOrbContainer, children: [
|
|
5026
|
+
/* @__PURE__ */ jsxs("div", { className: widget_default.voiceOrbRow, children: [
|
|
5027
|
+
/* @__PURE__ */ jsx(
|
|
5028
|
+
VoiceOrb,
|
|
5029
|
+
{
|
|
5030
|
+
state: orbState,
|
|
5031
|
+
inputLevel: session.isMuted ? 0 : session.inputLevel,
|
|
5032
|
+
disabled
|
|
5033
|
+
}
|
|
5034
|
+
),
|
|
5035
|
+
/* @__PURE__ */ jsx(
|
|
5036
|
+
"button",
|
|
5037
|
+
{
|
|
5038
|
+
type: "button",
|
|
5039
|
+
"data-cf-voice-mute": "true",
|
|
5040
|
+
className: `${widget_default.voiceMuteButton}${session.isMuted ? " " + widget_default.voiceMuteButtonMuted : ""}`,
|
|
5041
|
+
onClick: session.toggleMute,
|
|
5042
|
+
"aria-label": session.isMuted ? "Unmute microphone" : "Mute microphone",
|
|
5043
|
+
"aria-pressed": session.isMuted,
|
|
5044
|
+
children: session.isMuted ? "Muted" : "Mute"
|
|
5045
|
+
}
|
|
5046
|
+
)
|
|
5047
|
+
] }),
|
|
5048
|
+
/* @__PURE__ */ jsxs("div", { className: widget_default.voiceOrbStats, children: [
|
|
5049
|
+
session.isMuted && /* @__PURE__ */ jsx("span", { className: widget_default.voiceOrbHint, "aria-hidden": "true", children: "Microphone muted" }),
|
|
5050
|
+
!session.isMuted && session.state === "connecting" && /* @__PURE__ */ jsx("span", { className: widget_default.voiceAssistantStatus, children: "Connecting\u2026" }),
|
|
5051
|
+
!session.isMuted && session.state === "processing" && /* @__PURE__ */ jsx("span", { className: widget_default.voiceAssistantStatus, children: "Preparing the next step\u2026" }),
|
|
5052
|
+
!session.isMuted && session.state === "speaking" && /* @__PURE__ */ jsx("span", { className: widget_default.voiceAssistantStatus, children: "Assistant speaking\u2026" })
|
|
5053
|
+
] })
|
|
5054
|
+
] }),
|
|
5055
|
+
session.transcripts.length > 0 && /* @__PURE__ */ jsx("div", { ref: logRef, className: widget_default.voiceLiveLog, children: session.transcripts.map((t, i) => /* @__PURE__ */ jsxs(
|
|
4615
5056
|
"div",
|
|
4616
5057
|
{
|
|
4617
|
-
className:
|
|
5058
|
+
className: t.who === "user" ? widget_default.voiceLiveLogUser : widget_default.voiceLiveLogAssistant,
|
|
4618
5059
|
children: [
|
|
4619
|
-
/* @__PURE__ */ jsx(
|
|
4620
|
-
/* @__PURE__ */ jsx("
|
|
4621
|
-
session.isMuted && "\u{1F507} Muted",
|
|
4622
|
-
!session.isMuted && session.state === "connecting" && "Connecting\u2026",
|
|
4623
|
-
!session.isMuted && session.state === "listening" && "Listening\u2026",
|
|
4624
|
-
!session.isMuted && session.state === "speaking" && "Assistant speaking\u2026",
|
|
4625
|
-
!session.isMuted && session.state === "idle" && "Ready"
|
|
4626
|
-
] }) }),
|
|
4627
|
-
/* @__PURE__ */ jsx(
|
|
4628
|
-
"button",
|
|
4629
|
-
{
|
|
4630
|
-
type: "button",
|
|
4631
|
-
"data-cf-voice-mute": "true",
|
|
4632
|
-
className: `${widget_default.voiceMuteButton}${session.isMuted ? " " + widget_default.voiceMuteButtonMuted : ""}`,
|
|
4633
|
-
onClick: session.toggleMute,
|
|
4634
|
-
"aria-label": session.isMuted ? "Unmute microphone" : "Mute microphone",
|
|
4635
|
-
"aria-pressed": session.isMuted,
|
|
4636
|
-
children: session.isMuted ? "\u{1F507}" : "\u{1F3A4}"
|
|
4637
|
-
}
|
|
4638
|
-
)
|
|
5060
|
+
/* @__PURE__ */ jsx("span", { className: widget_default.voiceTranscriptLabel, children: t.who === "user" ? "You" : "Assistant" }),
|
|
5061
|
+
/* @__PURE__ */ jsx("span", { className: widget_default.voiceTranscriptText, children: t.text })
|
|
4639
5062
|
]
|
|
4640
|
-
}
|
|
4641
|
-
|
|
5063
|
+
},
|
|
5064
|
+
i
|
|
5065
|
+
)) }),
|
|
5066
|
+
fieldRevealed && /* @__PURE__ */ jsx("div", { ref: promptRef, children: /* @__PURE__ */ jsx(VoicePromptCard, { field }) }),
|
|
5067
|
+
session.error && /* @__PURE__ */ jsx("p", { className: widget_default.voiceError, children: session.error })
|
|
4642
5068
|
] });
|
|
4643
5069
|
}
|
|
4644
5070
|
function InputText({
|
|
@@ -5817,6 +6243,7 @@ var ChatAdapter = forwardRef(
|
|
|
5817
6243
|
runId,
|
|
5818
6244
|
participantToken,
|
|
5819
6245
|
apiBase,
|
|
6246
|
+
connectionPolicy,
|
|
5820
6247
|
className,
|
|
5821
6248
|
onCompleted,
|
|
5822
6249
|
onError,
|
|
@@ -5836,7 +6263,7 @@ var ChatAdapter = forwardRef(
|
|
|
5836
6263
|
components,
|
|
5837
6264
|
strings
|
|
5838
6265
|
}, ref) {
|
|
5839
|
-
var _a, _b, _c, _d, _e, _f, _g, _h, _i;
|
|
6266
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
|
|
5840
6267
|
const t = resolveStrings(strings);
|
|
5841
6268
|
const apiBaseResolved = apiBase;
|
|
5842
6269
|
const appBaseResolved = typeof window !== "undefined" ? window.location.origin : (_a = process.env.APP_URL) != null ? _a : "http://localhost:3000";
|
|
@@ -5872,7 +6299,7 @@ var ChatAdapter = forwardRef(
|
|
|
5872
6299
|
output,
|
|
5873
6300
|
disconnect,
|
|
5874
6301
|
reconnect
|
|
5875
|
-
} = useRunStream({ runId, participantToken, apiBase }, onEventFirehose);
|
|
6302
|
+
} = useRunStream({ runId, participantToken, apiBase, connectionPolicy }, onEventFirehose);
|
|
5876
6303
|
useImperativeHandle(
|
|
5877
6304
|
ref,
|
|
5878
6305
|
() => ({
|
|
@@ -5882,12 +6309,6 @@ var ChatAdapter = forwardRef(
|
|
|
5882
6309
|
}),
|
|
5883
6310
|
[reconnect, disconnect, sendMessage]
|
|
5884
6311
|
);
|
|
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
6312
|
const {
|
|
5892
6313
|
connections: requiredConnections,
|
|
5893
6314
|
allProvided: allConnectionsProvided,
|
|
@@ -5971,7 +6392,11 @@ var ChatAdapter = forwardRef(
|
|
|
5971
6392
|
if (!isVoiceSurface && activeSession && extractSurface(activeSession) === "widget/voice") {
|
|
5972
6393
|
setIsVoiceSurface(true);
|
|
5973
6394
|
}
|
|
5974
|
-
const
|
|
6395
|
+
const [isLiveVoiceSurface, setIsLiveVoiceSurface] = useState(false);
|
|
6396
|
+
if (!isLiveVoiceSurface && activeSession && extractSurface(activeSession) === "widget/voice" && ((_b = extractSurfaceConfig(activeSession)) == null ? void 0 : _b.style) === "live") {
|
|
6397
|
+
setIsLiveVoiceSurface(true);
|
|
6398
|
+
}
|
|
6399
|
+
const voiceSessionId = (_c = activeSession == null ? void 0 : activeSession.id) != null ? _c : null;
|
|
5975
6400
|
const prevVoiceSessionIdRef = useRef(null);
|
|
5976
6401
|
useEffect(() => {
|
|
5977
6402
|
if (!isVoiceSurface) return;
|
|
@@ -5981,6 +6406,25 @@ var ChatAdapter = forwardRef(
|
|
|
5981
6406
|
}
|
|
5982
6407
|
prevVoiceSessionIdRef.current = voiceSessionId;
|
|
5983
6408
|
}, [voiceSessionId, isVoiceSurface, clearSpeech]);
|
|
6409
|
+
const liveVoiceRef = useRef(null);
|
|
6410
|
+
const [revealedLivePromptSessions, setRevealedLivePromptSessions] = useState(
|
|
6411
|
+
() => /* @__PURE__ */ new Set()
|
|
6412
|
+
);
|
|
6413
|
+
const [livePlaybackComplete, setLivePlaybackComplete] = useState(false);
|
|
6414
|
+
const livePlaybackSessionRef = useRef(null);
|
|
6415
|
+
useEffect(() => {
|
|
6416
|
+
if (!activeSession || activeSession.id === livePlaybackSessionRef.current) return;
|
|
6417
|
+
livePlaybackSessionRef.current = activeSession.id;
|
|
6418
|
+
setLivePlaybackComplete(false);
|
|
6419
|
+
}, [activeSession]);
|
|
6420
|
+
const terminalVoiceDraining = (status === "completed" || status === "error") && isLiveVoiceSurface && liveVoiceRef.current !== null && !livePlaybackComplete;
|
|
6421
|
+
const reportedStatus = terminalVoiceDraining ? "running" : status;
|
|
6422
|
+
const prevStatusRef = useRef(null);
|
|
6423
|
+
useEffect(() => {
|
|
6424
|
+
if (prevStatusRef.current === reportedStatus) return;
|
|
6425
|
+
prevStatusRef.current = reportedStatus;
|
|
6426
|
+
onStatusChange == null ? void 0 : onStatusChange(reportedStatus);
|
|
6427
|
+
}, [reportedStatus, onStatusChange]);
|
|
5984
6428
|
useEffect(() => {
|
|
5985
6429
|
if (!isVoiceSurface) return;
|
|
5986
6430
|
for (const entry of timeline) {
|
|
@@ -5988,15 +6432,17 @@ var ChatAdapter = forwardRef(
|
|
|
5988
6432
|
if (entry.sender === "user") continue;
|
|
5989
6433
|
if (spokenMessageSeqsRef.current.has(entry.seq)) continue;
|
|
5990
6434
|
spokenMessageSeqsRef.current.add(entry.seq);
|
|
6435
|
+
if (isLiveVoiceSurface) continue;
|
|
5991
6436
|
const text = entry.payload.voice_hint || entry.payload.content || "";
|
|
5992
6437
|
void enqueueSpeak(text);
|
|
5993
6438
|
}
|
|
5994
|
-
}, [timeline, isVoiceSurface, enqueueSpeak]);
|
|
6439
|
+
}, [timeline, isVoiceSurface, isLiveVoiceSurface, enqueueSpeak]);
|
|
5995
6440
|
const completedFiredRef = useRef(false);
|
|
5996
6441
|
const errorFiredRef = useRef(false);
|
|
6442
|
+
const expiredFiredRef = useRef(false);
|
|
5997
6443
|
const inputAreaRef = useRef(null);
|
|
5998
6444
|
const lastFocusedSessionRef = useRef(null);
|
|
5999
|
-
const activeSessionId = (
|
|
6445
|
+
const activeSessionId = (_d = activeSession == null ? void 0 : activeSession.id) != null ? _d : null;
|
|
6000
6446
|
useEffect(() => {
|
|
6001
6447
|
if (!autoFocusInput) return;
|
|
6002
6448
|
if (!activeSessionId) return;
|
|
@@ -6012,15 +6458,21 @@ var ChatAdapter = forwardRef(
|
|
|
6012
6458
|
}
|
|
6013
6459
|
}, [autoFocusInput, activeSessionId, status]);
|
|
6014
6460
|
useEffect(() => {
|
|
6015
|
-
if (status === "completed" && !completedFiredRef.current) {
|
|
6461
|
+
if (status === "completed" && !terminalVoiceDraining && !completedFiredRef.current) {
|
|
6016
6462
|
completedFiredRef.current = true;
|
|
6017
6463
|
onCompleted == null ? void 0 : onCompleted(output != null ? output : void 0);
|
|
6018
6464
|
}
|
|
6019
|
-
if (status === "error" && !errorFiredRef.current) {
|
|
6465
|
+
if (status === "error" && !terminalVoiceDraining && !errorFiredRef.current) {
|
|
6020
6466
|
errorFiredRef.current = true;
|
|
6021
6467
|
onError == null ? void 0 : onError(new WidgetError("run_failed", "The run encountered an error."));
|
|
6022
6468
|
}
|
|
6023
|
-
|
|
6469
|
+
if (status === "expired" && !expiredFiredRef.current) {
|
|
6470
|
+
expiredFiredRef.current = true;
|
|
6471
|
+
onError == null ? void 0 : onError(
|
|
6472
|
+
new WidgetError("token_expired", "The participant token expired and could not be renewed.")
|
|
6473
|
+
);
|
|
6474
|
+
}
|
|
6475
|
+
}, [status, terminalVoiceDraining, output, onCompleted, onError]);
|
|
6024
6476
|
const colorSchemeClass = colorScheme === "dark" ? widget_default.cfDark : colorScheme === "auto" ? widget_default.cfAuto : void 0;
|
|
6025
6477
|
const cls = [widget_default.widget, colorSchemeClass, className].filter(Boolean).join(" ");
|
|
6026
6478
|
const rootStyle = useMemo(() => themeToStyle(theme), [theme]);
|
|
@@ -6066,10 +6518,11 @@ var ChatAdapter = forwardRef(
|
|
|
6066
6518
|
},
|
|
6067
6519
|
[handleSubmit]
|
|
6068
6520
|
);
|
|
6069
|
-
|
|
6521
|
+
const isSilentReconnect = (status === "connecting" || status === "replaying") && timeline.length > 0;
|
|
6522
|
+
if (status === "idle" || status === "connecting" && !isSilentReconnect) {
|
|
6070
6523
|
return /* @__PURE__ */ jsx("div", { className: cls, style: rootStyle, children: loadingFallback != null ? loadingFallback : /* @__PURE__ */ jsx(StatusDisplay, { status, strings }) });
|
|
6071
6524
|
}
|
|
6072
|
-
if (status === "replaying") {
|
|
6525
|
+
if (status === "replaying" && !isSilentReconnect) {
|
|
6073
6526
|
return /* @__PURE__ */ jsxs("div", { className: cls, style: rootStyle, children: [
|
|
6074
6527
|
header,
|
|
6075
6528
|
/* @__PURE__ */ jsxs("div", { className: widget_default.resumingBanner, children: [
|
|
@@ -6079,7 +6532,8 @@ var ChatAdapter = forwardRef(
|
|
|
6079
6532
|
/* @__PURE__ */ jsx(ChatTimeline, { entries: timeline, streamingText, components })
|
|
6080
6533
|
] });
|
|
6081
6534
|
}
|
|
6082
|
-
|
|
6535
|
+
const awaitingLivePlayback = terminalVoiceDraining;
|
|
6536
|
+
if ((status === "completed" || status === "error") && !awaitingLivePlayback) {
|
|
6083
6537
|
const hasChatContent = timeline.some(
|
|
6084
6538
|
(e) => {
|
|
6085
6539
|
var _a2, _b2;
|
|
@@ -6099,7 +6553,7 @@ var ChatAdapter = forwardRef(
|
|
|
6099
6553
|
FormRenderer,
|
|
6100
6554
|
{
|
|
6101
6555
|
fields: formSpec == null ? void 0 : formSpec.fields,
|
|
6102
|
-
repeater: (
|
|
6556
|
+
repeater: (_e = formSpec == null ? void 0 : formSpec.repeaters) == null ? void 0 : _e[0],
|
|
6103
6557
|
onSubmit: (values) => void submitHandback(values),
|
|
6104
6558
|
disabled: submitting
|
|
6105
6559
|
}
|
|
@@ -6133,9 +6587,9 @@ var ChatAdapter = forwardRef(
|
|
|
6133
6587
|
const converseUserCanEnd = (converseCtx == null ? void 0 : converseCtx.converse_user_can_end) === true;
|
|
6134
6588
|
const field = activeSession ? extractField(activeSession) : null;
|
|
6135
6589
|
if (status === "awaiting_chat" && activeSession && !(isConverseSession && field)) {
|
|
6136
|
-
const hbCtx = (
|
|
6590
|
+
const hbCtx = (_f = activeSession.entry_context) == null ? void 0 : _f.handback;
|
|
6137
6591
|
const outputSchema = hbCtx == null ? void 0 : hbCtx.output_schema;
|
|
6138
|
-
const requireOutput = (
|
|
6592
|
+
const requireOutput = (_g = hbCtx == null ? void 0 : hbCtx.require_output) != null ? _g : false;
|
|
6139
6593
|
const handbackReady = !requireOutput || outputSchema != null && Object.keys(outputSchema).every((k) => {
|
|
6140
6594
|
var _a2;
|
|
6141
6595
|
return ((_a2 = handbackValues[k]) != null ? _a2 : "").trim() !== "";
|
|
@@ -6236,31 +6690,63 @@ var ChatAdapter = forwardRef(
|
|
|
6236
6690
|
const shouldUseVoice = effectiveVoiceMode !== "off";
|
|
6237
6691
|
const voiceRenderer = effectiveVoiceMode === "push_to_talk" ? "click" : "continuous";
|
|
6238
6692
|
const isLiveVoice = surface === "widget/voice" && (surfaceConfig == null ? void 0 : surfaceConfig.style) === "live";
|
|
6239
|
-
if (
|
|
6240
|
-
|
|
6241
|
-
|
|
6242
|
-
|
|
6243
|
-
|
|
6244
|
-
|
|
6245
|
-
|
|
6246
|
-
|
|
6693
|
+
if (activeSession && !isLiveVoice) {
|
|
6694
|
+
liveVoiceRef.current = null;
|
|
6695
|
+
} else if (isLiveVoice && activeSession && field) {
|
|
6696
|
+
liveVoiceRef.current = {
|
|
6697
|
+
// Pin the FIRST id: it only picks which socket to open, and the proxy
|
|
6698
|
+
// tracks field transitions itself from then on.
|
|
6699
|
+
sessionId: (_i = (_h = liveVoiceRef.current) == null ? void 0 : _h.sessionId) != null ? _i : activeSession.id,
|
|
6700
|
+
fieldSessionId: activeSession.id,
|
|
6701
|
+
field,
|
|
6702
|
+
hint: (_k = nodeVoice == null ? void 0 : nodeVoice.hint) != null ? _k : (_j = field.voice) == null ? void 0 : _j.hint,
|
|
6703
|
+
config: surfaceConfig != null ? surfaceConfig : void 0
|
|
6247
6704
|
};
|
|
6705
|
+
}
|
|
6706
|
+
const liveVoice = isLiveVoice && activeSession && field || !activeSession && status === "running" || awaitingLivePlayback ? liveVoiceRef.current : null;
|
|
6707
|
+
if (liveVoice) {
|
|
6708
|
+
const respondedSessionIds = new Set(
|
|
6709
|
+
timeline.filter((entry) => entry.event_type === "response" && entry.session_id).map((entry) => entry.session_id)
|
|
6710
|
+
);
|
|
6711
|
+
const visibleLiveTimeline = timeline.filter(
|
|
6712
|
+
(entry) => entry.event_type !== "prompt" || entry.session_id === null || respondedSessionIds.has(entry.session_id) || revealedLivePromptSessions.has(entry.session_id)
|
|
6713
|
+
);
|
|
6248
6714
|
return /* @__PURE__ */ jsxs("div", { className: cls, style: rootStyle, children: [
|
|
6249
6715
|
header,
|
|
6250
|
-
/* @__PURE__ */ jsx(ChatTimeline, { entries:
|
|
6251
|
-
/* @__PURE__ */ jsx("div", { className: widget_default.activeInputArea
|
|
6716
|
+
/* @__PURE__ */ jsx(ChatTimeline, { entries: visibleLiveTimeline, showTyping, streamingText, components }),
|
|
6717
|
+
/* @__PURE__ */ jsx("div", { className: `${widget_default.activeInputArea} ${widget_default.activeInputAreaVoice}`, children: /* @__PURE__ */ jsx(
|
|
6252
6718
|
VoiceLiveRenderer,
|
|
6253
6719
|
{
|
|
6254
|
-
field,
|
|
6255
|
-
voiceHint:
|
|
6720
|
+
field: liveVoice.field,
|
|
6721
|
+
voiceHint: liveVoice.hint,
|
|
6256
6722
|
apiBase: apiBaseResolved,
|
|
6257
6723
|
participantToken,
|
|
6258
|
-
sessionId:
|
|
6259
|
-
|
|
6260
|
-
|
|
6724
|
+
sessionId: liveVoice.sessionId,
|
|
6725
|
+
fieldSessionId: liveVoice.fieldSessionId,
|
|
6726
|
+
liveConfig: liveVoice.config,
|
|
6727
|
+
onValue: (value) => setInputValue(value),
|
|
6728
|
+
onPlaybackComplete: () => setLivePlaybackComplete(true),
|
|
6729
|
+
onFieldRevealed: (revealedSessionId) => setRevealedLivePromptSessions((prev) => {
|
|
6730
|
+
if (prev.has(revealedSessionId)) return prev;
|
|
6731
|
+
const next = new Set(prev);
|
|
6732
|
+
next.add(revealedSessionId);
|
|
6733
|
+
return next;
|
|
6734
|
+
}),
|
|
6261
6735
|
disabled: submitting
|
|
6262
6736
|
}
|
|
6263
|
-
)
|
|
6737
|
+
) })
|
|
6738
|
+
] });
|
|
6739
|
+
}
|
|
6740
|
+
if (shouldUseVoice && activeSession && field) {
|
|
6741
|
+
const spokenHint = (_m = nodeVoice == null ? void 0 : nodeVoice.hint) != null ? _m : (_l = field.voice) == null ? void 0 : _l.hint;
|
|
6742
|
+
const handleVoiceValue = (value) => {
|
|
6743
|
+
setInputValue(value);
|
|
6744
|
+
void submitHandback(value, crypto.randomUUID());
|
|
6745
|
+
};
|
|
6746
|
+
return /* @__PURE__ */ jsxs("div", { className: cls, style: rootStyle, children: [
|
|
6747
|
+
header,
|
|
6748
|
+
/* @__PURE__ */ jsx(ChatTimeline, { entries: timeline, showTyping, streamingText, components }),
|
|
6749
|
+
/* @__PURE__ */ jsx("div", { className: `${widget_default.activeInputArea} ${widget_default.activeInputAreaVoice}`, children: voiceRenderer === "continuous" ? /* @__PURE__ */ jsx(
|
|
6264
6750
|
VoiceContinuousRenderer,
|
|
6265
6751
|
{
|
|
6266
6752
|
field,
|
|
@@ -6269,7 +6755,7 @@ var ChatAdapter = forwardRef(
|
|
|
6269
6755
|
participantToken,
|
|
6270
6756
|
onValue: handleVoiceValue,
|
|
6271
6757
|
autoSubmitMode: "confirm",
|
|
6272
|
-
confidenceThreshold: (
|
|
6758
|
+
confidenceThreshold: (_n = nodeVoice == null ? void 0 : nodeVoice.confidence_threshold) != null ? _n : typeof (surfaceConfig == null ? void 0 : surfaceConfig.confidence_threshold) === "number" ? surfaceConfig.confidence_threshold : 0.7,
|
|
6273
6759
|
enqueueSpeak,
|
|
6274
6760
|
isSpeaking,
|
|
6275
6761
|
disabled: submitting
|
|
@@ -6302,6 +6788,10 @@ var ChatAdapter = forwardRef(
|
|
|
6302
6788
|
) });
|
|
6303
6789
|
}
|
|
6304
6790
|
return /* @__PURE__ */ jsxs("div", { className: cls, style: rootStyle, children: [
|
|
6791
|
+
isSilentReconnect && /* @__PURE__ */ jsxs("div", { className: widget_default.reconnectingPill, children: [
|
|
6792
|
+
/* @__PURE__ */ jsx("span", { className: widget_default.spinner }),
|
|
6793
|
+
t.reconnecting
|
|
6794
|
+
] }),
|
|
6305
6795
|
header,
|
|
6306
6796
|
/* @__PURE__ */ jsx(ChatTimeline, { entries: timeline, showTyping, streamingText, components }),
|
|
6307
6797
|
activeSession && field && InputComponent && /* @__PURE__ */ jsxs("form", { ref: inputAreaRef, className: widget_default.activeInputArea, onSubmit: handleSubmit, children: [
|
|
@@ -6499,15 +6989,44 @@ function clearPersistedSession(config, target) {
|
|
|
6499
6989
|
} catch {
|
|
6500
6990
|
}
|
|
6501
6991
|
}
|
|
6992
|
+
async function fetchPersistedRunTerminalStatus(apiBase, runId, participantToken) {
|
|
6993
|
+
var _a;
|
|
6994
|
+
try {
|
|
6995
|
+
const res = await fetch(`${apiBase}/api/participant/runs/${runId}/timeline`, {
|
|
6996
|
+
headers: { Authorization: `Bearer ${participantToken}` }
|
|
6997
|
+
});
|
|
6998
|
+
if (!res.ok) return null;
|
|
6999
|
+
const entries = await res.json();
|
|
7000
|
+
if (!Array.isArray(entries)) return null;
|
|
7001
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
7002
|
+
const e = entries[i];
|
|
7003
|
+
if (e.event_type === "status_change") {
|
|
7004
|
+
const s = (_a = e.payload) == null ? void 0 : _a.status;
|
|
7005
|
+
if (s === "completed" || s === "failed") return s;
|
|
7006
|
+
}
|
|
7007
|
+
}
|
|
7008
|
+
return null;
|
|
7009
|
+
} catch {
|
|
7010
|
+
return null;
|
|
7011
|
+
}
|
|
7012
|
+
}
|
|
6502
7013
|
var ChatterflyWidget = forwardRef(
|
|
6503
7014
|
function ChatterflyWidget2(props, ref) {
|
|
6504
|
-
var _a, _b, _c, _d, _e, _f, _g, _h;
|
|
7015
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
|
|
6505
7016
|
const [resolved, setResolved] = useState(null);
|
|
6506
7017
|
const [configError, setConfigError] = useState(null);
|
|
6507
7018
|
const [restartNonce, setRestartNonce] = useState(0);
|
|
6508
7019
|
const adapterRef = useRef(null);
|
|
6509
7020
|
const autoStarting = Boolean(!props.runId && (props.deploymentId || props.workflowId));
|
|
6510
7021
|
const persistTarget = (_a = props.workflowId) != null ? _a : props.deploymentId;
|
|
7022
|
+
const effectivePersistSession = props.persistSession === void 0 ? true : props.persistSession;
|
|
7023
|
+
const showCompletedHistory = (_b = props.showCompletedHistory) != null ? _b : true;
|
|
7024
|
+
const t = { ...defaultStrings, ...props.strings };
|
|
7025
|
+
const [gate, setGate] = useState("idle");
|
|
7026
|
+
const [terminalReplayActive, setTerminalReplayActive] = useState(false);
|
|
7027
|
+
const pendingPersistedRef = useRef(null);
|
|
7028
|
+
const startNewRunRef = useRef(() => {
|
|
7029
|
+
});
|
|
6511
7030
|
useEffect(() => {
|
|
6512
7031
|
var _a2;
|
|
6513
7032
|
if (props.runId) return;
|
|
@@ -6522,52 +7041,109 @@ var ChatterflyWidget = forwardRef(
|
|
|
6522
7041
|
return;
|
|
6523
7042
|
}
|
|
6524
7043
|
setConfigError(null);
|
|
6525
|
-
|
|
6526
|
-
|
|
6527
|
-
|
|
6528
|
-
|
|
6529
|
-
|
|
7044
|
+
const base = props.apiBase;
|
|
7045
|
+
const doStart = (input) => {
|
|
7046
|
+
const startUrl = props.workflowId ? `${base}/api/public/workflows/${props.workflowId}/start` : `${base}/api/public/surveys/${props.deploymentId}/start`;
|
|
7047
|
+
const body = input ? JSON.stringify({ input }) : void 0;
|
|
7048
|
+
fetch(startUrl, {
|
|
7049
|
+
method: "POST",
|
|
7050
|
+
headers: body ? { "Content-Type": "application/json" } : void 0,
|
|
7051
|
+
body
|
|
7052
|
+
}).then(async (r) => {
|
|
7053
|
+
if (!r.ok) {
|
|
7054
|
+
const code = r.status === 404 ? "no_live_deployment" : "workflow_not_public";
|
|
7055
|
+
const detail = await r.text().catch(() => "");
|
|
7056
|
+
throw new WidgetError(
|
|
7057
|
+
code,
|
|
7058
|
+
`Failed to start run (HTTP ${r.status})${detail ? `: ${detail}` : ""}`
|
|
7059
|
+
);
|
|
7060
|
+
}
|
|
7061
|
+
return r.json();
|
|
7062
|
+
}).then(({ run_id, participant_token }) => {
|
|
7063
|
+
setGate("idle");
|
|
7064
|
+
setTerminalReplayActive(false);
|
|
7065
|
+
setResolved({ runId: run_id, participantToken: participant_token });
|
|
7066
|
+
savePersistedSession(effectivePersistSession, persistTarget, {
|
|
7067
|
+
runId: run_id,
|
|
7068
|
+
participantToken: participant_token
|
|
7069
|
+
});
|
|
7070
|
+
}).catch((err) => {
|
|
7071
|
+
var _a3;
|
|
7072
|
+
const widgetErr = err instanceof WidgetError ? err : new WidgetError("network", err instanceof Error ? err.message : String(err));
|
|
7073
|
+
(_a3 = props.onError) == null ? void 0 : _a3.call(props, widgetErr);
|
|
7074
|
+
});
|
|
7075
|
+
};
|
|
7076
|
+
startNewRunRef.current = doStart;
|
|
7077
|
+
if (restartNonce > 0) {
|
|
7078
|
+
doStart(props.initialInput);
|
|
7079
|
+
return;
|
|
7080
|
+
}
|
|
7081
|
+
const persisted = loadPersistedSession(effectivePersistSession, persistTarget);
|
|
7082
|
+
if (!persisted) {
|
|
7083
|
+
if (props.clickToStart) {
|
|
7084
|
+
setGate("click-to-start");
|
|
7085
|
+
} else {
|
|
7086
|
+
doStart(props.initialInput);
|
|
6530
7087
|
}
|
|
7088
|
+
return;
|
|
6531
7089
|
}
|
|
6532
|
-
|
|
6533
|
-
|
|
6534
|
-
|
|
6535
|
-
|
|
6536
|
-
|
|
6537
|
-
|
|
6538
|
-
|
|
6539
|
-
|
|
6540
|
-
|
|
6541
|
-
|
|
6542
|
-
|
|
6543
|
-
|
|
6544
|
-
|
|
6545
|
-
|
|
6546
|
-
|
|
7090
|
+
let cancelled = false;
|
|
7091
|
+
fetchPersistedRunTerminalStatus(base, persisted.runId, persisted.participantToken).then(
|
|
7092
|
+
(terminal) => {
|
|
7093
|
+
if (cancelled) return;
|
|
7094
|
+
if (terminal) {
|
|
7095
|
+
if (showCompletedHistory) {
|
|
7096
|
+
setTerminalReplayActive(true);
|
|
7097
|
+
setGate("idle");
|
|
7098
|
+
setResolved(persisted);
|
|
7099
|
+
} else {
|
|
7100
|
+
clearPersistedSession(effectivePersistSession, persistTarget);
|
|
7101
|
+
doStart(props.initialInput);
|
|
7102
|
+
}
|
|
7103
|
+
} else if (props.resumePrompt) {
|
|
7104
|
+
pendingPersistedRef.current = persisted;
|
|
7105
|
+
setGate("resume-choice");
|
|
7106
|
+
} else {
|
|
7107
|
+
setResolved(persisted);
|
|
7108
|
+
}
|
|
6547
7109
|
}
|
|
6548
|
-
|
|
6549
|
-
|
|
6550
|
-
|
|
6551
|
-
|
|
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
|
-
});
|
|
7110
|
+
);
|
|
7111
|
+
return () => {
|
|
7112
|
+
cancelled = true;
|
|
7113
|
+
};
|
|
6560
7114
|
}, [props.deploymentId, props.workflowId, props.apiBase, restartNonce]);
|
|
6561
7115
|
const restart = useCallback(() => {
|
|
6562
7116
|
var _a2;
|
|
6563
7117
|
if (autoStarting) {
|
|
6564
|
-
clearPersistedSession(
|
|
7118
|
+
clearPersistedSession(effectivePersistSession, persistTarget);
|
|
6565
7119
|
setResolved(null);
|
|
7120
|
+
setTerminalReplayActive(false);
|
|
7121
|
+
setGate("idle");
|
|
6566
7122
|
setRestartNonce((n) => n + 1);
|
|
6567
7123
|
} else {
|
|
6568
7124
|
(_a2 = adapterRef.current) == null ? void 0 : _a2.restart();
|
|
6569
7125
|
}
|
|
6570
|
-
}, [autoStarting,
|
|
7126
|
+
}, [autoStarting, effectivePersistSession, persistTarget]);
|
|
7127
|
+
const handleClickToStart = useCallback(() => {
|
|
7128
|
+
startNewRunRef.current(props.initialInput);
|
|
7129
|
+
}, [props.initialInput]);
|
|
7130
|
+
const handleResumeContinue = useCallback(() => {
|
|
7131
|
+
if (pendingPersistedRef.current) {
|
|
7132
|
+
setResolved(pendingPersistedRef.current);
|
|
7133
|
+
setGate("idle");
|
|
7134
|
+
}
|
|
7135
|
+
}, []);
|
|
7136
|
+
const handleResumeRestart = useCallback(() => {
|
|
7137
|
+
clearPersistedSession(effectivePersistSession, persistTarget);
|
|
7138
|
+
setGate("idle");
|
|
7139
|
+
startNewRunRef.current(props.initialInput);
|
|
7140
|
+
}, [effectivePersistSession, persistTarget, props.initialInput]);
|
|
7141
|
+
const handleStartNewFromReplay = useCallback(() => {
|
|
7142
|
+
clearPersistedSession(effectivePersistSession, persistTarget);
|
|
7143
|
+
setTerminalReplayActive(false);
|
|
7144
|
+
setResolved(null);
|
|
7145
|
+
startNewRunRef.current(props.initialInput);
|
|
7146
|
+
}, [effectivePersistSession, persistTarget, props.initialInput]);
|
|
6571
7147
|
const disconnect = useCallback(() => {
|
|
6572
7148
|
var _a2;
|
|
6573
7149
|
(_a2 = adapterRef.current) == null ? void 0 : _a2.disconnect();
|
|
@@ -6581,10 +7157,10 @@ var ChatterflyWidget = forwardRef(
|
|
|
6581
7157
|
disconnect,
|
|
6582
7158
|
sendMessage
|
|
6583
7159
|
]);
|
|
6584
|
-
const runId = (
|
|
6585
|
-
const participantToken = (
|
|
6586
|
-
const mode = (
|
|
6587
|
-
const [open, setOpen] = useState((
|
|
7160
|
+
const runId = (_c = resolved == null ? void 0 : resolved.runId) != null ? _c : props.runId;
|
|
7161
|
+
const participantToken = (_d = resolved == null ? void 0 : resolved.participantToken) != null ? _d : props.participantToken;
|
|
7162
|
+
const mode = (_e = props.mode) != null ? _e : "inline";
|
|
7163
|
+
const [open, setOpen] = useState((_f = props.defaultOpen) != null ? _f : false);
|
|
6588
7164
|
const [unreadCount, setUnreadCount] = useState(0);
|
|
6589
7165
|
const toggleOpen = useCallback(() => {
|
|
6590
7166
|
setOpen((prev) => {
|
|
@@ -6606,10 +7182,62 @@ var ChatterflyWidget = forwardRef(
|
|
|
6606
7182
|
);
|
|
6607
7183
|
let content;
|
|
6608
7184
|
if (configError) {
|
|
6609
|
-
content = (
|
|
7185
|
+
content = (_g = props.loadingFallback) != null ? _g : /* @__PURE__ */ jsx(StatusDisplay, { status: "error" });
|
|
7186
|
+
} else if (gate === "click-to-start") {
|
|
7187
|
+
const cfg = typeof props.clickToStart === "object" ? props.clickToStart : void 0;
|
|
7188
|
+
content = /* @__PURE__ */ jsxs("div", { className: widget_default.gateCard, children: [
|
|
7189
|
+
/* @__PURE__ */ jsx("div", { className: widget_default.gateTitle, children: (_h = cfg == null ? void 0 : cfg.label) != null ? _h : t.startConversation }),
|
|
7190
|
+
/* @__PURE__ */ jsx("div", { className: widget_default.gateDescription, children: (_i = cfg == null ? void 0 : cfg.description) != null ? _i : t.clickToStartDescription }),
|
|
7191
|
+
/* @__PURE__ */ jsx("div", { className: widget_default.gateActions, children: /* @__PURE__ */ jsx(
|
|
7192
|
+
"button",
|
|
7193
|
+
{
|
|
7194
|
+
type: "button",
|
|
7195
|
+
className: widget_default.gateButtonPrimary,
|
|
7196
|
+
onClick: handleClickToStart,
|
|
7197
|
+
children: (_j = cfg == null ? void 0 : cfg.label) != null ? _j : t.startConversation
|
|
7198
|
+
}
|
|
7199
|
+
) })
|
|
7200
|
+
] });
|
|
7201
|
+
} else if (gate === "resume-choice") {
|
|
7202
|
+
const cfg = typeof props.resumePrompt === "object" ? props.resumePrompt : void 0;
|
|
7203
|
+
content = /* @__PURE__ */ jsxs("div", { className: widget_default.gateCard, children: [
|
|
7204
|
+
/* @__PURE__ */ jsx("div", { className: widget_default.gateTitle, children: (_k = cfg == null ? void 0 : cfg.title) != null ? _k : t.resumeTitle }),
|
|
7205
|
+
/* @__PURE__ */ jsxs("div", { className: widget_default.gateActions, children: [
|
|
7206
|
+
/* @__PURE__ */ jsx(
|
|
7207
|
+
"button",
|
|
7208
|
+
{
|
|
7209
|
+
type: "button",
|
|
7210
|
+
className: widget_default.gateButtonPrimary,
|
|
7211
|
+
onClick: handleResumeContinue,
|
|
7212
|
+
children: (_l = cfg == null ? void 0 : cfg.continueLabel) != null ? _l : t.resumeContinue
|
|
7213
|
+
}
|
|
7214
|
+
),
|
|
7215
|
+
/* @__PURE__ */ jsx(
|
|
7216
|
+
"button",
|
|
7217
|
+
{
|
|
7218
|
+
type: "button",
|
|
7219
|
+
className: widget_default.gateButtonSecondary,
|
|
7220
|
+
onClick: handleResumeRestart,
|
|
7221
|
+
children: (_m = cfg == null ? void 0 : cfg.restartLabel) != null ? _m : t.resumeRestart
|
|
7222
|
+
}
|
|
7223
|
+
)
|
|
7224
|
+
] })
|
|
7225
|
+
] });
|
|
6610
7226
|
} else if (!runId || !participantToken) {
|
|
6611
|
-
content = (
|
|
7227
|
+
content = (_n = props.loadingFallback) != null ? _n : /* @__PURE__ */ jsx(StatusDisplay, { status: autoStarting ? "connecting" : "error" });
|
|
6612
7228
|
} else {
|
|
7229
|
+
const replayCompletedState = terminalReplayActive ? /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
7230
|
+
t.conversationEnded,
|
|
7231
|
+
/* @__PURE__ */ jsx(
|
|
7232
|
+
"button",
|
|
7233
|
+
{
|
|
7234
|
+
type: "button",
|
|
7235
|
+
className: widget_default.startNewConversationButton,
|
|
7236
|
+
onClick: handleStartNewFromReplay,
|
|
7237
|
+
children: t.startNewConversation
|
|
7238
|
+
}
|
|
7239
|
+
)
|
|
7240
|
+
] }) : void 0;
|
|
6613
7241
|
content = /* @__PURE__ */ jsx(
|
|
6614
7242
|
ChatAdapter,
|
|
6615
7243
|
{
|
|
@@ -6617,14 +7245,16 @@ var ChatterflyWidget = forwardRef(
|
|
|
6617
7245
|
ref: adapterRef,
|
|
6618
7246
|
runId,
|
|
6619
7247
|
participantToken,
|
|
6620
|
-
onMessage: handleMessage
|
|
7248
|
+
onMessage: handleMessage,
|
|
7249
|
+
completedState: (_o = props.completedState) != null ? _o : replayCompletedState,
|
|
7250
|
+
errorState: (_p = props.errorState) != null ? _p : replayCompletedState
|
|
6621
7251
|
}
|
|
6622
7252
|
);
|
|
6623
7253
|
}
|
|
6624
7254
|
if (mode !== "floating") {
|
|
6625
7255
|
return content;
|
|
6626
7256
|
}
|
|
6627
|
-
const position = (
|
|
7257
|
+
const position = (_q = props.position) != null ? _q : "bottom-right";
|
|
6628
7258
|
return /* @__PURE__ */ jsx(
|
|
6629
7259
|
FloatingLauncherChrome,
|
|
6630
7260
|
{
|
|
@@ -6682,7 +7312,8 @@ function FloatingLauncherChrome({
|
|
|
6682
7312
|
}
|
|
6683
7313
|
function useChatterflyRun(options) {
|
|
6684
7314
|
var _a, _b;
|
|
6685
|
-
const { runId, participantToken, apiBase, deploymentId, workflowId, initialInput, persistSession, onEvent } = options;
|
|
7315
|
+
const { runId, participantToken, apiBase, deploymentId, workflowId, initialInput, persistSession, connectionPolicy, onEvent } = options;
|
|
7316
|
+
const effectivePersistSession = persistSession === void 0 ? true : persistSession;
|
|
6686
7317
|
const [resolved, setResolved] = useState(null);
|
|
6687
7318
|
const [error, setError] = useState(null);
|
|
6688
7319
|
const [restartNonce, setRestartNonce] = useState(0);
|
|
@@ -6701,7 +7332,7 @@ function useChatterflyRun(options) {
|
|
|
6701
7332
|
}
|
|
6702
7333
|
setError(null);
|
|
6703
7334
|
if (restartNonce === 0) {
|
|
6704
|
-
const persisted = loadPersistedSession(
|
|
7335
|
+
const persisted = loadPersistedSession(effectivePersistSession, persistTarget);
|
|
6705
7336
|
if (persisted) {
|
|
6706
7337
|
setResolved({ runId: persisted.runId, participantToken: persisted.participantToken });
|
|
6707
7338
|
return;
|
|
@@ -6725,7 +7356,7 @@ function useChatterflyRun(options) {
|
|
|
6725
7356
|
return r.json();
|
|
6726
7357
|
}).then(({ run_id, participant_token }) => {
|
|
6727
7358
|
setResolved({ runId: run_id, participantToken: participant_token });
|
|
6728
|
-
savePersistedSession(
|
|
7359
|
+
savePersistedSession(effectivePersistSession, persistTarget, {
|
|
6729
7360
|
runId: run_id,
|
|
6730
7361
|
participantToken: participant_token
|
|
6731
7362
|
});
|
|
@@ -6741,19 +7372,29 @@ function useChatterflyRun(options) {
|
|
|
6741
7372
|
{
|
|
6742
7373
|
runId: effectiveRunId != null ? effectiveRunId : "",
|
|
6743
7374
|
participantToken: effectiveToken != null ? effectiveToken : "",
|
|
6744
|
-
apiBase: apiBase != null ? apiBase : ""
|
|
7375
|
+
apiBase: apiBase != null ? apiBase : "",
|
|
7376
|
+
connectionPolicy
|
|
6745
7377
|
},
|
|
6746
7378
|
onEvent
|
|
6747
7379
|
);
|
|
6748
7380
|
const restart = useCallback(() => {
|
|
6749
7381
|
if (autoStarting) {
|
|
6750
|
-
clearPersistedSession(
|
|
7382
|
+
clearPersistedSession(effectivePersistSession, persistTarget);
|
|
6751
7383
|
setResolved(null);
|
|
6752
7384
|
setRestartNonce((n) => n + 1);
|
|
6753
7385
|
} else {
|
|
6754
7386
|
stream.reconnect();
|
|
6755
7387
|
}
|
|
6756
|
-
}, [autoStarting,
|
|
7388
|
+
}, [autoStarting, effectivePersistSession, persistTarget, stream]);
|
|
7389
|
+
const expiredErrorFiredRef = useRef(false);
|
|
7390
|
+
useEffect(() => {
|
|
7391
|
+
if (stream.status === "expired" && !expiredErrorFiredRef.current) {
|
|
7392
|
+
expiredErrorFiredRef.current = true;
|
|
7393
|
+
setError(
|
|
7394
|
+
new WidgetError("token_expired", "The participant token expired and could not be renewed.")
|
|
7395
|
+
);
|
|
7396
|
+
}
|
|
7397
|
+
}, [stream.status]);
|
|
6757
7398
|
const connecting = autoStarting && !resolved && !error;
|
|
6758
7399
|
return {
|
|
6759
7400
|
...stream,
|