@burdenoff/microfe-healthybowl 2026.901.4 → 2026.901.5
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/components/assistant/AssistantChatArea.js +94 -87
- package/dist/components/assistant/AssistantChatArea.js.map +1 -1
- package/dist/components/assistant/voice/AssistantVoiceSession.js +3 -3
- package/dist/components/assistant/voice/AssistantVoiceSession.js.map +1 -1
- package/dist/hooks/useVoiceSession.js +2 -0
- package/dist/hooks/useVoiceSession.js.map +1 -1
- package/dist/types/assistant.js.map +1 -1
- package/dist/utils/assistantPrompt.js +15 -5
- package/dist/utils/assistantPrompt.js.map +1 -1
- package/dist/utils/voiceTurnVisibility.js +14 -0
- package/dist/utils/voiceTurnVisibility.js.map +1 -0
- package/package.json +1 -1
|
@@ -20,24 +20,25 @@ import { dispatchAssistantQuotaExhausted as ue, notifyAiCreditsUpdated as de } f
|
|
|
20
20
|
import { buildPromptForMode as fe } from "../../utils/assistantPrompt.js";
|
|
21
21
|
import { isMultimodalBodyRejection as pe, isRecoverableAssistantError as me } from "../../utils/assistantTransportErrors.js";
|
|
22
22
|
import { pollDelayMs as he } from "../../utils/assistantPollSchedule.js";
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
23
|
+
import { chatTurns as ge, voiceTurnsOnly as _e } from "../../utils/voiceTurnVisibility.js";
|
|
24
|
+
import { createReadinessTracker as ve } from "../../utils/sandboxReadiness.js";
|
|
25
|
+
import { useCallback as T, useEffect as E, useMemo as D, useRef as O, useState as ye } from "react";
|
|
26
|
+
import { useI18n as be } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
|
|
27
|
+
import { jsx as k, jsxs as xe } from "react/jsx-runtime";
|
|
28
|
+
import { useGatewayClient as Se } from "@burdenoff/fe-libs/shared/graphql";
|
|
29
|
+
import { useAuthToken as Ce } from "@burdenoff/fe-libs/shared/providers/shell";
|
|
30
|
+
import { getAssistantMedia as we } from "@burdenoff/fe-libs/shared/assistant";
|
|
30
31
|
//#region src/components/assistant/AssistantChatArea.tsx
|
|
31
|
-
var
|
|
32
|
+
var Te = {
|
|
32
33
|
general: 18e4,
|
|
33
34
|
assistant: 18e4,
|
|
34
35
|
"api-calls": 18e4,
|
|
35
36
|
"vibe-plugins": 6e5
|
|
36
|
-
},
|
|
37
|
-
function
|
|
37
|
+
}, Ee = 18e4;
|
|
38
|
+
function De() {
|
|
38
39
|
return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
|
|
39
40
|
}
|
|
40
|
-
function
|
|
41
|
+
function Oe(e) {
|
|
41
42
|
return e.replace(/(Authorization\s*:\s*Bearer\s+)[^\s\n]+/gi, "$1[REDACTED]").replace(/(X-Workspace-Authorization\s*:\s*Bearer\s+)[^\s\n]+/gi, "$1[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9._-]+\.[A-Za-z0-9._-]+\b/g, "[REDACTED_JWT]").replace(/\bsk-ant-[A-Za-z0-9-]+\b/g, "[REDACTED_API_KEY]");
|
|
42
43
|
}
|
|
43
44
|
function A(e) {
|
|
@@ -52,13 +53,13 @@ function M(e) {
|
|
|
52
53
|
return t === "completed" ? `Completed: ${n}` : t === "failed" ? `Failed: ${n}` : `Running: ${n}`;
|
|
53
54
|
});
|
|
54
55
|
}
|
|
55
|
-
function
|
|
56
|
+
function ke(e, t) {
|
|
56
57
|
let n = e.filter((e) => e.info?.role === "assistant" && A(e) > t).sort((e, t) => A(e) - A(t));
|
|
57
58
|
if (n.length === 0) return {
|
|
58
59
|
content: "Thinking...",
|
|
59
60
|
done: !1
|
|
60
61
|
};
|
|
61
|
-
let r = n[n.length - 1], i = j(r.parts), a =
|
|
62
|
+
let r = n[n.length - 1], i = j(r.parts), a = we(r.parts), o = M(r.parts);
|
|
62
63
|
return {
|
|
63
64
|
content: [
|
|
64
65
|
i,
|
|
@@ -69,7 +70,7 @@ function De(e, t) {
|
|
|
69
70
|
tokens: r.info?.tokens
|
|
70
71
|
};
|
|
71
72
|
}
|
|
72
|
-
function
|
|
73
|
+
function Ae(e) {
|
|
73
74
|
switch (e) {
|
|
74
75
|
case "provisioning": return "Starting assistant environment...";
|
|
75
76
|
case "connecting": return "Connecting to assistant...";
|
|
@@ -77,21 +78,21 @@ function Oe(e) {
|
|
|
77
78
|
default: return "";
|
|
78
79
|
}
|
|
79
80
|
}
|
|
80
|
-
var N = ({ visible:
|
|
81
|
-
let j = t(), M =
|
|
81
|
+
var N = ({ visible: we = !0 }) => {
|
|
82
|
+
let j = t(), M = Se("workspace"), { getAccessToken: N, getWorkspaceToken: je, userId: Me } = Ce(), { locale: P } = be(), F = e((e) => e.assistantLanguage), Ne = D(() => g(F, P).english, [F, P]), Pe = h(F) !== null, Fe = D(() => g(F, P).code, [F, P]), { conversations: Ie, activeConversationId: I, mode: L, processingByConversationId: Le, setMode: R, setConversationMode: z, setActiveConversation: Re, createConversation: B, addMessage: ze, updateMessage: Be, patchMessage: V, setConversationProcessing: H, clearConversationProcessing: Ve, setBackendSessionId: He, clearBackendSessionId: U, setSandbox: W, clearSandbox: Ue, acknowledgeApiCalls: We } = e(), G = Ie.find((e) => e.id === I)?.messages ?? [], K = I ? Le[I] : void 0, q = _(K?.status), Ge = q ? K?.messageId ?? null : null, Ke = K?.status === "error" ? K.messageId : null, { canUseApiCalls: J, loading: qe } = ce(y()), Je = D(() => S.filter((e) => !e.requiresAdmin || J), [J]), [Ye, Xe] = ye(null), Ze = O({}), Y = O(ve()), Qe = O(/* @__PURE__ */ new Set());
|
|
82
83
|
E(() => {
|
|
83
|
-
if (
|
|
84
|
+
if (qe) return;
|
|
84
85
|
let e = S.find((e) => e.id === L);
|
|
85
86
|
(!e || e.requiresAdmin && !J) && L !== "assistant" && R("assistant");
|
|
86
87
|
}, [
|
|
87
88
|
L,
|
|
88
89
|
J,
|
|
89
|
-
|
|
90
|
+
qe,
|
|
90
91
|
R
|
|
91
92
|
]);
|
|
92
93
|
let X = T((e, t, n, r) => {
|
|
93
|
-
H(e, n, t, null), r ?
|
|
94
|
-
}, [H,
|
|
94
|
+
H(e, n, t, null), r ? Be(e, t, r) : Be(e, t, Ae(n));
|
|
95
|
+
}, [H, Be]), $e = T(async (t, n, a, s, c) => {
|
|
95
96
|
let u = e.getState().sandboxesByMode[a]?.sandboxId ?? null, d = async (e) => {
|
|
96
97
|
if (Y.current.isFresh(e)) return !0;
|
|
97
98
|
try {
|
|
@@ -117,7 +118,7 @@ var N = ({ visible: Se = !0 }) => {
|
|
|
117
118
|
} catch {
|
|
118
119
|
U(t), m = null;
|
|
119
120
|
}
|
|
120
|
-
return m || (X(t, n, "connecting", "Preparing session..."), m = (await i(M, u, s, a, c)).sessionId,
|
|
121
|
+
return m || (X(t, n, "connecting", "Preparing session..."), m = (await i(M, u, s, a, c)).sessionId, He(t, m)), {
|
|
121
122
|
sandboxId: u,
|
|
122
123
|
sessionId: m
|
|
123
124
|
};
|
|
@@ -125,39 +126,45 @@ var N = ({ visible: Se = !0 }) => {
|
|
|
125
126
|
M,
|
|
126
127
|
U,
|
|
127
128
|
N,
|
|
128
|
-
|
|
129
|
+
He,
|
|
129
130
|
W,
|
|
130
131
|
X
|
|
131
132
|
]), Z = T(async (t, r = [], i = {}) => {
|
|
132
133
|
let o = e.getState(), l = o.activeConversationId ?? I;
|
|
133
|
-
if (l && (_(o.processingByConversationId[l]?.status) ||
|
|
134
|
+
if (l && (_(o.processingByConversationId[l]?.status) || Qe.current.has(l))) return;
|
|
134
135
|
let f = o.mode, p = I, h = p ? e.getState().conversations.find((e) => e.id === p) : void 0;
|
|
135
136
|
if (p ? h && h.mode !== f && (h.messages.length > 0 || h.backendSessionId) ? p = B(void 0, f) : h && h.mode !== f && z(p, f) : p = B(void 0, f), !p) return;
|
|
136
|
-
|
|
137
|
+
Ze.current[p] = r;
|
|
137
138
|
let g = ee(), v = {
|
|
138
139
|
accessToken: N(),
|
|
139
|
-
workspaceToken:
|
|
140
|
-
userId:
|
|
140
|
+
workspaceToken: je(),
|
|
141
|
+
userId: Me,
|
|
141
142
|
organizationId: y()
|
|
142
143
|
}, b = {
|
|
143
|
-
id:
|
|
144
|
+
id: De(),
|
|
144
145
|
role: "user",
|
|
145
146
|
content: t,
|
|
146
147
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
147
|
-
metadata:
|
|
148
|
+
metadata: {
|
|
149
|
+
...r.length ? { attachments: r.map(ae) } : {},
|
|
150
|
+
...i.dictated === !0 ? { voice: !0 } : {}
|
|
151
|
+
}
|
|
148
152
|
};
|
|
149
|
-
|
|
150
|
-
let x =
|
|
151
|
-
|
|
153
|
+
ze(p, b);
|
|
154
|
+
let x = De();
|
|
155
|
+
ze(p, {
|
|
152
156
|
id: x,
|
|
153
157
|
role: "assistant",
|
|
154
158
|
content: "",
|
|
155
159
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
156
|
-
metadata: {
|
|
160
|
+
metadata: {
|
|
161
|
+
lang: Fe,
|
|
162
|
+
...i.dictated === !0 ? { voice: !0 } : {}
|
|
163
|
+
}
|
|
157
164
|
}), H(p, "provisioning", x, null);
|
|
158
|
-
let S = (e, t, n, r, i =
|
|
165
|
+
let S = (e, t, n, r, i = Fe) => {
|
|
159
166
|
V(p, x, {
|
|
160
|
-
content:
|
|
167
|
+
content: Oe(e),
|
|
161
168
|
metadata: {
|
|
162
169
|
lang: i,
|
|
163
170
|
...t?.length ? { artifacts: t } : {},
|
|
@@ -178,9 +185,9 @@ var N = ({ visible: Se = !0 }) => {
|
|
|
178
185
|
console.warn("[assistant] AI-credit pre-flight check failed with a non-quota error; proceeding — gateway @usage(checkQuota) still enforces the real budget downstream", e);
|
|
179
186
|
}
|
|
180
187
|
try {
|
|
181
|
-
let { sandboxId: e, sessionId: n } = await
|
|
188
|
+
let { sandboxId: e, sessionId: n } = await $e(p, x, f, g, v), l = (await c(M, e, g, n, v, 50).catch(() => [])).reduce((e, t) => Math.max(e, A(t)), 0);
|
|
182
189
|
X(p, x, "streaming", "Thinking...");
|
|
183
|
-
let h = fe(f, ne(t, r),
|
|
190
|
+
let h = fe(f, ne(t, r), Ne, Pe, i.dictated === !0), _ = te(h, r), y = ie(_), ee = y > 0, ae = m();
|
|
184
191
|
o = re(r) > y;
|
|
185
192
|
try {
|
|
186
193
|
await d(M, e, g, n, h, f, ae, v, _);
|
|
@@ -188,8 +195,8 @@ var N = ({ visible: Se = !0 }) => {
|
|
|
188
195
|
if (!_ || !pe(t)) throw t;
|
|
189
196
|
await d(M, e, g, n, h, f, ae, v, void 0), o ||= ee;
|
|
190
197
|
}
|
|
191
|
-
let b =
|
|
192
|
-
for (; Date.now() < C && (b =
|
|
198
|
+
let b = ke([], l), C = Date.now() + (Te[f] ?? Ee), w = Date.now(), oe = Date.now();
|
|
199
|
+
for (; Date.now() < C && (b = ke(await c(M, e, g, n, v, 50), l), V(p, x, { content: Oe(b.content) }), !b.done);) Date.now() - w > 3e4 && (await a(M, e, g, 600, v).catch(() => void 0), w = Date.now()), await new Promise((e) => setTimeout(e, he(Date.now() - oe)));
|
|
193
200
|
if (!b.done && f !== "vibe-plugins") throw Error("Assistant response timed out while streaming progress");
|
|
194
201
|
let se = f === "vibe-plugins" ? await s(M, e, g, n, v).catch(() => []) : void 0;
|
|
195
202
|
if (b.done || (b = {
|
|
@@ -206,11 +213,11 @@ var N = ({ visible: Se = !0 }) => {
|
|
|
206
213
|
}
|
|
207
214
|
H(p, "complete", x, null);
|
|
208
215
|
} catch (t) {
|
|
209
|
-
if (e === 1 && me(t)) return U(p),
|
|
216
|
+
if (e === 1 && me(t)) return U(p), Ue(f), C(2);
|
|
210
217
|
throw t;
|
|
211
218
|
}
|
|
212
219
|
}, w = p;
|
|
213
|
-
|
|
220
|
+
Qe.current.add(w);
|
|
214
221
|
try {
|
|
215
222
|
if (!g) throw Error("Assistant backend is unavailable without an active workspace context.");
|
|
216
223
|
await C();
|
|
@@ -225,33 +232,33 @@ var N = ({ visible: Se = !0 }) => {
|
|
|
225
232
|
metadata: { lang: "en" }
|
|
226
233
|
});
|
|
227
234
|
} finally {
|
|
228
|
-
|
|
235
|
+
Qe.current.delete(w);
|
|
229
236
|
}
|
|
230
237
|
}, [
|
|
231
238
|
I,
|
|
232
|
-
|
|
239
|
+
ze,
|
|
233
240
|
M,
|
|
234
241
|
U,
|
|
235
|
-
|
|
236
|
-
|
|
242
|
+
Ue,
|
|
243
|
+
Ie,
|
|
237
244
|
B,
|
|
238
|
-
|
|
245
|
+
$e,
|
|
239
246
|
N,
|
|
240
|
-
|
|
247
|
+
je,
|
|
241
248
|
V,
|
|
242
|
-
|
|
249
|
+
Pe,
|
|
250
|
+
Fe,
|
|
243
251
|
Ne,
|
|
244
|
-
|
|
245
|
-
Be,
|
|
252
|
+
He,
|
|
246
253
|
z,
|
|
247
254
|
H,
|
|
248
255
|
j,
|
|
249
256
|
X,
|
|
250
|
-
|
|
251
|
-
]),
|
|
257
|
+
Me
|
|
258
|
+
]), et = T((e) => {
|
|
252
259
|
Z(e);
|
|
253
|
-
}, [Z]),
|
|
254
|
-
let e = [...G].reverse().find((e) => e.role === "user"), t = I ?
|
|
260
|
+
}, [Z]), tt = T(() => {
|
|
261
|
+
let e = [...G].reverse().find((e) => e.role === "user"), t = I ? Ze.current[I] ?? [] : [];
|
|
255
262
|
e && Z(e.content, t);
|
|
256
263
|
}, [
|
|
257
264
|
G,
|
|
@@ -261,7 +268,7 @@ var N = ({ visible: Se = !0 }) => {
|
|
|
261
268
|
E(() => {
|
|
262
269
|
Q.current = Z;
|
|
263
270
|
}, [Z]);
|
|
264
|
-
let
|
|
271
|
+
let nt = D(() => {
|
|
265
272
|
if (q) return null;
|
|
266
273
|
for (let e = G.length - 1; e >= 0; --e) {
|
|
267
274
|
let t = G[e];
|
|
@@ -273,7 +280,7 @@ var N = ({ visible: Se = !0 }) => {
|
|
|
273
280
|
} : null;
|
|
274
281
|
}
|
|
275
282
|
return null;
|
|
276
|
-
}, [G, q]),
|
|
283
|
+
}, [G, q]), rt = D(() => ge(G), [G]), it = D(() => _e(G).filter((e) => e.role === "user" || e.role === "assistant").slice(-6).map((e) => ({
|
|
277
284
|
id: e.id,
|
|
278
285
|
role: e.role,
|
|
279
286
|
text: v(e.content).text.trim()
|
|
@@ -281,12 +288,12 @@ var N = ({ visible: Se = !0 }) => {
|
|
|
281
288
|
onSubmit: T((e) => {
|
|
282
289
|
Q.current(e, [], { dictated: !0 });
|
|
283
290
|
}, []),
|
|
284
|
-
latestReply:
|
|
291
|
+
latestReply: nt,
|
|
285
292
|
language: g(F, P).tag
|
|
286
293
|
});
|
|
287
294
|
E(() => {
|
|
288
|
-
!
|
|
289
|
-
}, [
|
|
295
|
+
!we && $.active && $.end();
|
|
296
|
+
}, [we, $]), E(() => {
|
|
290
297
|
let t = e.getState().consumePendingPrompt();
|
|
291
298
|
return t && Q.current(t), e.subscribe((t, n) => {
|
|
292
299
|
if (t.pendingPrompt && t.pendingPrompt !== n.pendingPrompt) {
|
|
@@ -295,53 +302,53 @@ var N = ({ visible: Se = !0 }) => {
|
|
|
295
302
|
}
|
|
296
303
|
});
|
|
297
304
|
}, []);
|
|
298
|
-
let
|
|
305
|
+
let at = T((t) => {
|
|
299
306
|
let n = I ? e.getState().conversations.find((e) => e.id === I) : void 0;
|
|
300
307
|
if (n && (n.messages.length > 0 || n.backendSessionId)) {
|
|
301
308
|
if (n.mode !== t) {
|
|
302
309
|
let n = e.getState().conversations.find((n) => n.mode === t && n.messages.length === 0 && !n.backendSessionId && !e.getState().processingByConversationId[n.id]);
|
|
303
|
-
n ?
|
|
310
|
+
n ? Re(n.id) : B(void 0, t);
|
|
304
311
|
}
|
|
305
312
|
} else I && z(I, t);
|
|
306
313
|
R(t);
|
|
307
314
|
}, [
|
|
308
315
|
I,
|
|
309
316
|
B,
|
|
310
|
-
|
|
317
|
+
Re,
|
|
311
318
|
z,
|
|
312
319
|
R
|
|
313
|
-
]),
|
|
320
|
+
]), ot = T((t) => {
|
|
314
321
|
if (S.find((e) => e.id === t)?.writeCapable && !e.getState().apiCallsAcknowledged) {
|
|
315
|
-
|
|
322
|
+
Xe(t);
|
|
316
323
|
return;
|
|
317
324
|
}
|
|
318
|
-
|
|
319
|
-
}, [
|
|
320
|
-
let e =
|
|
321
|
-
|
|
325
|
+
at(t);
|
|
326
|
+
}, [at]), st = T(() => {
|
|
327
|
+
let e = Ye;
|
|
328
|
+
Xe(null), We(), e && at(e);
|
|
322
329
|
}, [
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
]),
|
|
327
|
-
|
|
330
|
+
Ye,
|
|
331
|
+
We,
|
|
332
|
+
at
|
|
333
|
+
]), ct = T(() => {
|
|
334
|
+
Xe(null);
|
|
328
335
|
}, []);
|
|
329
|
-
return /* @__PURE__ */
|
|
336
|
+
return /* @__PURE__ */ xe("div", {
|
|
330
337
|
className: "relative flex flex-1 flex-col overflow-hidden",
|
|
331
338
|
children: [
|
|
332
|
-
/* @__PURE__ */
|
|
339
|
+
/* @__PURE__ */ xe("div", {
|
|
333
340
|
className: "contents",
|
|
334
341
|
inert: $.active || void 0,
|
|
335
|
-
children: [
|
|
342
|
+
children: [rt.length === 0 ? /* @__PURE__ */ k(C, {
|
|
336
343
|
mode: L,
|
|
337
|
-
onSuggestionClick:
|
|
344
|
+
onSuggestionClick: et
|
|
338
345
|
}) : /* @__PURE__ */ k("div", {
|
|
339
346
|
className: "flex min-h-0 flex-1 flex-col",
|
|
340
347
|
children: /* @__PURE__ */ k(b, {
|
|
341
|
-
messages:
|
|
342
|
-
streamingMessageId:
|
|
343
|
-
failedMessageId:
|
|
344
|
-
onRetry:
|
|
348
|
+
messages: rt,
|
|
349
|
+
streamingMessageId: Ge,
|
|
350
|
+
failedMessageId: Ke,
|
|
351
|
+
onRetry: tt
|
|
345
352
|
})
|
|
346
353
|
}), /* @__PURE__ */ k(w, {
|
|
347
354
|
onStartVoiceSession: $.available && L !== "api-calls" ? $.start : void 0,
|
|
@@ -349,23 +356,23 @@ var N = ({ visible: Se = !0 }) => {
|
|
|
349
356
|
disabled: q,
|
|
350
357
|
placeholder: L === "api-calls" ? j("healthybowl.assistant.chatArea.placeholderActions", "What would you like me to do?") : j("healthybowl.assistant.chatArea.placeholderGeneral", "Ask HealthyBowl anything…"),
|
|
351
358
|
mode: L,
|
|
352
|
-
availableModes:
|
|
353
|
-
onModeChange:
|
|
359
|
+
availableModes: Je,
|
|
360
|
+
onModeChange: ot
|
|
354
361
|
})]
|
|
355
362
|
}),
|
|
356
363
|
$.active && /* @__PURE__ */ k(oe, {
|
|
357
364
|
session: $.session,
|
|
358
365
|
notice: $.notice,
|
|
359
|
-
turns:
|
|
366
|
+
turns: it,
|
|
360
367
|
onInterrupt: $.interrupt,
|
|
361
|
-
spoken:
|
|
368
|
+
spoken: nt?.text ?? null,
|
|
362
369
|
onToggleMute: $.toggleMute,
|
|
363
370
|
onEnd: $.end
|
|
364
371
|
}),
|
|
365
372
|
/* @__PURE__ */ k(x, {
|
|
366
|
-
open:
|
|
367
|
-
onConfirm:
|
|
368
|
-
onCancel:
|
|
373
|
+
open: Ye !== null,
|
|
374
|
+
onConfirm: st,
|
|
375
|
+
onCancel: ct
|
|
369
376
|
})
|
|
370
377
|
]
|
|
371
378
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantChatArea.js","names":[],"sources":["../../../src/components/assistant/AssistantChatArea.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState, type FC } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { findAssistantLanguage, resolveAssistantLanguage } from '@/config/assistantLanguages';\nimport { AssistantMessageList } from './AssistantMessageList';\nimport { AssistantApiCallsConsentDialog } from './AssistantApiCallsConsentDialog';\nimport { AssistantEmptyState } from './AssistantEmptyState';\nimport { AssistantComposer } from './composer/AssistantComposer';\nimport { AssistantVoiceSession } from './voice/AssistantVoiceSession';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useVoiceSession } from '../../hooks/useVoiceSession';\nimport { useAssistantApiAccess } from '@/hooks/useAssistantApiAccess';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport {\n checkAssistantAiCredits,\n createAssistantSandbox,\n createAssistantSession,\n extendAssistantSandboxTTL,\n findExistingSandbox,\n getAssistantArtifacts,\n getAssistantMessages,\n getAssistantSession,\n reportAssistantAiTokenUsage,\n sendAssistantPromptAsync,\n waitForAssistantServiceReady,\n waitForSandboxReady,\n type AssistantRawMessage,\n type AssistantSandboxAuthContext,\n} from '@/services/assistantApi';\nimport { getAssistantMedia } from '@burdenoff/fe-libs/shared/assistant';\nimport { gatherPageContext } from '@/utils/pageContext';\nimport { getOrganizationId, getWorkspaceId } from '@/utils/assistantContext';\nimport { dispatchAssistantQuotaExhausted, notifyAiCreditsUpdated } from '@/utils/aiCredits';\nimport { isQuotaExhaustedError } from '@/utils/quotaUtils';\nimport { buildPromptForMode } from '@/utils/assistantPrompt';\nimport {\n buildPromptParts,\n buildPromptWithAttachments,\n countInlineImageCandidates,\n countInlinedImageParts,\n toMessageAttachment,\n type AssistantAttachment,\n} from '@/utils/assistantAttachments';\nimport { isMultimodalBodyRejection, isRecoverableAssistantError } from '@/utils/assistantTransportErrors';\nimport { isTurnInFlight } from '@/utils/assistantTurnState';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { ASSISTANT_MODES } from '@/types/assistant';\nimport type { AssistantArtifact, AssistantConversationStatus, AssistantMode, Message } from '@/types/assistant';\nimport { pollDelayMs } from '../../utils/assistantPollSchedule';\nimport { createReadinessTracker } from '../../utils/sandboxReadiness';\n\n// How long the client streams progress before giving up on a turn. Chat replies\n// (general / api-calls) finish in seconds; a vibe-plugins build is a multi-step\n// pipeline (read docs → scaffold → bun install → bun build → checklist) that runs\n// for minutes, so it gets a much larger budget. The sandbox TTL is auto-extended\n// every 30s during the poll loop, so a longer budget never outlives the sandbox.\nconst STREAM_BUDGET_MS: Record<AssistantMode, number> = {\n general: 180_000,\n assistant: 180_000,\n 'api-calls': 180_000,\n 'vibe-plugins': 600_000,\n};\nconst DEFAULT_STREAM_BUDGET_MS = 180_000;\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n}\n\nfunction sanitizeAssistantResponse(response: string): string {\n return response\n .replace(/(Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/(X-Workspace-Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9._-]+\\.[A-Za-z0-9._-]+\\b/g, '[REDACTED_JWT]')\n .replace(/\\bsk-ant-[A-Za-z0-9-]+\\b/g, '[REDACTED_API_KEY]');\n}\n\nfunction getRawMessageCreatedAt(message: AssistantRawMessage): number {\n return message.info?.time?.created ?? 0;\n}\n\nfunction getAssistantText(parts: AssistantRawMessage['parts']): string {\n return (parts ?? [])\n .filter((part) => part.type === 'text' && typeof part.text === 'string')\n .map((part) => part.text?.trim() ?? '')\n .filter(Boolean)\n .join('\\n');\n}\n\nfunction getToolProgress(parts: AssistantRawMessage['parts']): string[] {\n return (parts ?? [])\n .filter((part) => part.type === 'tool' && part.tool)\n .map((part) => {\n const status = part.state?.status ?? 'running';\n const tool = part.tool ?? 'tool';\n if (status === 'completed') return `Completed: ${tool}`;\n if (status === 'failed') return `Failed: ${tool}`;\n return `Running: ${tool}`;\n });\n}\n\nfunction buildAssistantProgress(\n messages: AssistantRawMessage[],\n // The `created` timestamp (sandbox clock) of the newest message that already\n // existed in this session BEFORE the prompt was sent. This turn's reply is the\n // assistant message created strictly after it. Crucially this stays WITHIN the\n // sandbox clock domain: the previous code compared the sandbox-stamped\n // `created` against the browser wall-clock (Date#now), so a reply stamped at\n // prompt-time was silently dropped whenever the sandbox clock lagged the\n // browser — the turn then hung on \"Thinking...\" until the stream budget\n // elapsed. A sandbox-domain floor is immune to clock skew and correct for both\n // fresh and reused (per-conversation) sessions, with no message-window gap.\n priorNewestCreatedMs: number\n): {\n content: string;\n done: boolean;\n tokens?: { input: number; output: number };\n} {\n const relevant = messages\n .filter((message) => message.info?.role === 'assistant' && getRawMessageCreatedAt(message) > priorNewestCreatedMs)\n .sort((left, right) => getRawMessageCreatedAt(left) - getRawMessageCreatedAt(right));\n\n if (relevant.length === 0) {\n return { content: 'Thinking...', done: false };\n }\n\n const latest = relevant[relevant.length - 1]!;\n const text = getAssistantText(latest.parts);\n // Inbound image/file parts, rendered to markdown by the shared helper (which\n // escapes the label and allowlists the protocol — this is model output).\n // Without this, HealthyBowl — the one product that SENDS parts — could not\n // read one back: a media-bearing reply would never satisfy `done` and the\n // turn would poll to a false timeout.\n const media = getAssistantMedia(latest.parts);\n const toolProgress = getToolProgress(latest.parts);\n const content = [text, ...media, ...toolProgress].filter(Boolean).join('\\n\\n') || 'Thinking...';\n\n return {\n content,\n done: Boolean(latest.info?.time?.completed) && (Boolean(text) || media.length > 0 || toolProgress.length > 0),\n tokens: latest.info?.tokens,\n };\n}\n\nfunction getConversationStatusMessage(status: AssistantConversationStatus): string {\n switch (status) {\n case 'provisioning':\n return 'Starting assistant environment...';\n case 'connecting':\n return 'Connecting to assistant...';\n case 'streaming':\n return 'Thinking...';\n default:\n return '';\n }\n}\n\n/**\n * `visible` is false when the host HIDES the panel without unmounting it, which\n * is what the supported `visible` prop does. That distinction matters here: a\n * live voice session would otherwise keep the microphone open and the silence\n * timer running behind an invisible panel.\n */\ninterface AssistantChatAreaProps {\n visible?: boolean;\n}\n\nexport const AssistantChatArea: FC<AssistantChatAreaProps> = ({ visible = true }) => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken, userId } = useAuthToken();\n const { locale } = useI18n();\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n // The language the user chose to SPEAK, which is not necessarily the one the\n // interface is in — that is the whole point of the preference (BOFF-7108).\n // Named in ENGLISH deliberately: the preamble around it is English, so\n // \"Answer in Tamil.\" reads as an instruction, where a bare tag (\"ta\") invites\n // the model to answer *about* the code instead of *in* the language.\n const replyLanguageName = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale).english,\n [assistantLanguage, locale]\n );\n // A stored preference is a deliberate choice; `null` is only the interface\n // language standing in as a default. The directive treats the two differently\n // — see `buildLanguagePreamble`.\n //\n // Resolved, not merely non-null: a stale persisted code from a build that\n // offered more languages is DISCARDED by `resolveAssistantLanguage`, and\n // treating that discarded value as deliberate would tell the model the user\n // had chosen the interface language on purpose — suppressing the typed-language\n // override on the strength of a preference the selector does not even show.\n const languageIsExplicit = findAssistantLanguage(assistantLanguage) !== null;\n const replyLanguageCode = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale).code,\n [assistantLanguage, locale]\n );\n\n const {\n conversations,\n activeConversationId,\n mode,\n processingByConversationId,\n setMode,\n setConversationMode,\n setActiveConversation,\n createConversation,\n addMessage,\n updateMessage,\n patchMessage,\n setConversationProcessing,\n clearConversationProcessing,\n setBackendSessionId,\n clearBackendSessionId,\n setSandbox,\n clearSandbox,\n acknowledgeApiCalls,\n } = useAssistantStore();\n\n const activeConversation = conversations.find((conversation) => conversation.id === activeConversationId);\n const messages = activeConversation?.messages ?? [];\n const activeProcessing = activeConversationId ? processingByConversationId[activeConversationId] : undefined;\n // Only while the turn is genuinely in flight. `messageId` outlives the turn\n // (setConversationProcessing keeps it on 'complete'/'error'), so keying off it\n // alone left the transcript's aria-busy latched true forever and screen\n // readers stopped announcing new replies.\n const activeIsProcessing = isTurnInFlight(activeProcessing?.status);\n const activeStreamingMessageId = activeIsProcessing ? (activeProcessing?.messageId ?? null) : null;\n // The assistant message whose turn ended in an error — drives the Retry\n // affordance in the transcript.\n const failedMessageId = activeProcessing?.status === 'error' ? activeProcessing.messageId : null;\n\n // ── api-calls (write) mode gating ──────────────────────────────────\n // Only a global Owner/Admin may use api-calls (it mints an OAuth app under the\n // caller identity). Re-read the org scope every render (a cheap localStorage\n // read) so the admin gate reacts to an org switch without the panel\n // remounting; the value is a stable string, so useAssistantApiAccess only\n // re-fetches myRoles when the org actually changes. An empty scope simply\n // hides the mode (it could not provision the sandbox anyway).\n const apiCallsScopeId = getOrganizationId();\n const { canUseApiCalls, loading: apiAccessLoading } = useAssistantApiAccess(apiCallsScopeId);\n const availableModes = useMemo(\n () => ASSISTANT_MODES.filter((modeConfig) => !modeConfig.requiresAdmin || canUseApiCalls),\n [canUseApiCalls]\n );\n\n // Target mode awaiting the one-time consent dialog (null = dialog closed).\n const [pendingConsentMode, setPendingConsentMode] = useState<AssistantMode | null>(null);\n\n // Full attachment payload of the last send, kept so Retry can replay it\n // byte-for-byte (see handleRetry).\n const lastSentAttachmentsRef = useRef<Record<string, AssistantAttachment[]>>({});\n\n // Conversations with a turn already dispatched. Synchronous, unlike the store\n // — see the re-entry guard in handleSend for why that matters.\n /**\n * Per-sandbox record of \"last proven reachable\", so a warm sandbox is not\n * re-probed on every turn. Invalidated by any failure — see both catches.\n */\n const sandboxReadiness = useRef(createReadinessTracker());\n const inFlightSendsRef = useRef<Set<string>>(new Set());\n\n // If the active mode is no longer permitted — a non-admin with a persisted\n // api-calls mode, or the master flag turned off — fall back to the read-only\n // `assistant` mode (the default \"Ask\", available to everyone), but only AFTER\n // the role check resolves (so an admin's persisted api-calls mode isn't reset\n // during the brief loading window).\n useEffect(() => {\n if (apiAccessLoading) return;\n const activeModeConfig = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === mode);\n const blocked = !activeModeConfig || (activeModeConfig.requiresAdmin && !canUseApiCalls);\n if (blocked && mode !== 'assistant') {\n setMode('assistant');\n }\n }, [mode, canUseApiCalls, apiAccessLoading, setMode]);\n\n const updateConversationStage = useCallback(\n (conversationId: string, assistantMessageId: string, status: AssistantConversationStatus, content?: string) => {\n setConversationProcessing(conversationId, status, assistantMessageId, null);\n if (content) {\n updateMessage(conversationId, assistantMessageId, content);\n } else {\n updateMessage(conversationId, assistantMessageId, getConversationStatusMessage(status));\n }\n },\n [setConversationProcessing, updateMessage]\n );\n\n const ensureAssistantRuntime = useCallback(\n async (\n conversationId: string,\n assistantMessageId: string,\n currentMode: AssistantMode,\n workspaceId: string,\n authContext: AssistantSandboxAuthContext\n ): Promise<{ sandboxId: string; sessionId: string }> => {\n let currentSandboxId = useAssistantStore.getState().sandboxesByMode[currentMode]?.sandboxId ?? null;\n\n // Validate that a candidate sandbox (remembered locally or found running on\n // the server) is actually reachable before we reuse it. A sandbox can expire\n // (ttlSeconds) or have its backend pod reclaimed while still being briefly\n // reported RUNNING; proxying to such a dead pod fails with a terminal state\n // (\"Backend resource no longer exists\") or a permanent 502 cf-proxy timeout.\n // Returns true only when the in-sandbox agent responds; false means stale.\n const ensureSandboxReachable = async (candidateId: string): Promise<boolean> => {\n // ★ Skip a proof we already have. This ran two network waits before the\n // model saw the prompt on EVERY turn, including turns seconds after the\n // last one succeeded — a constant tax, felt most in voice where it sits\n // between the user finishing a sentence and hearing anything.\n //\n // Safe only because every failure path below invalidates: see the catch\n // here and the turn-level catch. A cache that were only ever written on\n // success would pin a dead sandbox and turn a recoverable error into a\n // loop.\n if (sandboxReadiness.current.isFresh(candidateId)) return true;\n try {\n await waitForSandboxReady(apollo, candidateId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, candidateId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n sandboxReadiness.current.markVerified(candidateId);\n return true;\n } catch {\n // Stale/expired sandbox — drop it so we provision a fresh one below\n // instead of surfacing \"Internal server error\" to the user.\n sandboxReadiness.current.invalidate(candidateId);\n return false;\n }\n };\n\n // 1) Try the locally-remembered sandbox, then 2) any running one on the\n // server. Each is only kept if it's actually reachable.\n if (currentSandboxId) {\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', 'Reusing assistant environment...');\n if (!(await ensureSandboxReachable(currentSandboxId))) {\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = null;\n }\n }\n\n if (!currentSandboxId) {\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Looking for existing environment...'\n );\n const existingId = await findExistingSandbox(apollo, workspaceId, currentMode, authContext);\n\n if (existingId) {\n setSandbox(currentMode, existingId, 'provisioning');\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Reusing assistant environment...'\n );\n if (await ensureSandboxReachable(existingId)) {\n currentSandboxId = existingId;\n } else {\n setSandbox(currentMode, null, 'provisioning');\n }\n }\n }\n\n // 3) No reusable, reachable sandbox — provision a fresh one.\n if (!currentSandboxId) {\n if (currentMode === 'api-calls' && !getAccessToken()) {\n throw new Error('API Calls mode requires an authenticated session. Please sign in again.');\n }\n\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Starting assistant environment...'\n );\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = await createAssistantSandbox(apollo, currentMode, workspaceId, authContext);\n\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n await waitForSandboxReady(apollo, currentSandboxId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, currentSandboxId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n }\n\n setSandbox(currentMode, currentSandboxId, 'running');\n\n let sessionId =\n useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n ?.backendSessionId ?? null;\n\n if (sessionId) {\n try {\n const session = await getAssistantSession(apollo, currentSandboxId, workspaceId, sessionId, authContext);\n if (session.mode !== currentMode) {\n throw new Error(`Session mode mismatch: expected ${currentMode}, received ${session.mode}`);\n }\n } catch {\n clearBackendSessionId(conversationId);\n sessionId = null;\n }\n }\n\n if (!sessionId) {\n updateConversationStage(conversationId, assistantMessageId, 'connecting', 'Preparing session...');\n const result = await createAssistantSession(apollo, currentSandboxId, workspaceId, currentMode, authContext);\n sessionId = result.sessionId;\n setBackendSessionId(conversationId, sessionId);\n }\n\n return {\n sandboxId: currentSandboxId,\n sessionId,\n };\n },\n [apollo, clearBackendSessionId, getAccessToken, setBackendSessionId, setSandbox, updateConversationStage]\n );\n\n const handleSend = useCallback(\n async (content: string, attachments: AssistantAttachment[] = [], options: { dictated?: boolean } = {}) => {\n // Only block re-entry while a turn is genuinely in-flight. Earlier code\n // checked for *any* entry in the map, which stuck around as `complete`\n // / `error` after the first turn — making every subsequent message\n // silently disappear (the input cleared but handleSend bailed before\n // adding the user message to the conversation).\n //\n // The store is read LIVE, and that is what makes the guard work. The\n // render-captured `processingByConversationId` is stale by construction —\n // the click that starts a turn and the click that must be rejected can\n // belong to the same render. Reading `activeConversationId` live matters\n // for the same reason: on two racing first-ever sends, the second must see\n // the conversation the first one created a moment ago.\n //\n // Pairs with the synchronous `setConversationProcessing` below: because\n // the status is written before this function ever awaits, a second call —\n // however soon it arrives — always observes 'provisioning'.\n const storeAtEntry = useAssistantStore.getState();\n const guardConversationId = storeAtEntry.activeConversationId ?? activeConversationId;\n if (guardConversationId) {\n if (isTurnInFlight(storeAtEntry.processingByConversationId[guardConversationId]?.status)) return;\n // Second lock, in case a future change moves the status write later:\n // this one cannot be cleared by anything but the turn's own `finally`.\n // Deliberately per-conversation — a global key would keep blocking\n // after the conversation it belonged to was deleted mid-turn, and then\n // silently swallow every subsequent send.\n if (inFlightSendsRef.current.has(guardConversationId)) return;\n }\n\n const selectedMode = storeAtEntry.mode;\n let conversationId = activeConversationId;\n const currentConversation = conversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n : undefined;\n\n if (!conversationId) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (\n currentConversation &&\n currentConversation.mode !== selectedMode &&\n (currentConversation.messages.length > 0 || currentConversation.backendSessionId)\n ) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (currentConversation && currentConversation.mode !== selectedMode) {\n setConversationMode(conversationId, selectedMode);\n }\n\n if (!conversationId) return;\n\n // Keyed by conversation: the ref outlives a conversation switch, and a\n // single global slot meant Retry in one thread replayed another thread's\n // photo onto it.\n lastSentAttachmentsRef.current[conversationId] = attachments;\n\n const workspaceId = getWorkspaceId();\n const authContext: AssistantSandboxAuthContext = {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n };\n\n const userMessage: Message = {\n id: generateId(),\n role: 'user',\n content,\n timestamp: new Date().toISOString(),\n // Slim descriptors only — the bubble re-resolves thumbnails from the\n // file id, so the persisted conversation stays small.\n metadata: attachments.length ? { attachments: attachments.map(toMessageAttachment) } : undefined,\n };\n addMessage(conversationId, userMessage);\n\n const assistantMessageId = generateId();\n addMessage(conversationId, {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n timestamp: new Date().toISOString(),\n // Stamped now, not read later: this is the language the reply is being\n // generated in, and the preference may have moved on by the time\n // somebody presses Listen.\n metadata: { lang: replyLanguageCode },\n });\n\n // Mark the turn in-flight in the STORE right now, synchronously.\n //\n // Until this line the first status write happened inside\n // `ensureAssistantRuntime`, i.e. one await later. During that window\n // `activeIsProcessing` was false and `failedMessageId` still pointed at\n // the PREVIOUS failure — so the composer stayed enabled and, worse, the\n // Retry button (which has no `disabled` of its own) stayed mounted and\n // clickable on top of a turn that had already started.\n //\n // Status only, deliberately no stage copy: `ensureAssistantRuntime` picks\n // the accurate wording a moment later (\"Reusing...\" vs \"Starting...\"), and\n // guessing here would flash the wrong one on every reused sandbox.\n setConversationProcessing(conversationId, 'provisioning', assistantMessageId, null);\n\n const applyAssistantResponse = (\n response: string,\n artifacts?: AssistantArtifact[],\n sessionId?: string,\n sandboxId?: string,\n // Our own hard-coded copy is English regardless of what the user picked.\n // Stamping it with their language makes playback read an English quota\n // message in a Tamil voice — Latin text cannot be script-detected, so\n // this metadata is trusted absolutely.\n lang: string = replyLanguageCode\n ) => {\n // `patchMessage` REPLACES metadata rather than merging it, so anything\n // omitted here is destroyed — which is how the turn-language stamp set\n // at creation was being wiped the moment the response completed,\n // silently undoing per-message language resolution. Always re-assert it.\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n metadata: {\n lang,\n ...(artifacts?.length ? { artifacts } : {}),\n ...(artifacts?.length || sessionId || sandboxId ? { mode: selectedMode } : {}),\n ...(sessionId ? { sessionId } : {}),\n ...(sandboxId ? { sandboxId } : {}),\n },\n });\n };\n\n const sendWithRealBackend = async (attempt: 1 | 2 = 1): Promise<void> => {\n // Set when this attempt had to re-send without the image bytes, so the\n // answer can say so rather than quietly reading as if the model looked.\n let imagesDropped = false;\n // Pre-flight AI-credit gate. The wspace gateway's @usage(checkQuota)\n // rejects with 429 QUOTA_EXHAUSTED when the monthly token budget is\n // depleted — block the send (don't provision a sandbox or dispatch the\n // prompt) and surface the upgrade dialog instead of a generic error.\n try {\n await checkAssistantAiCredits(apollo, workspaceId, authContext);\n } catch (creditError) {\n if (isQuotaExhaustedError(creditError)) {\n dispatchAssistantQuotaExhausted('ai-credits');\n applyAssistantResponse(\n \"You've run out of AI credits for this billing cycle. Upgrade your plan to keep chatting.\",\n undefined,\n undefined,\n undefined,\n 'en'\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n // The pre-flight gate exists ONLY to catch a genuine QUOTA_EXHAUSTED\n // rejection. Any other failure here is a transient fault in the\n // credit check itself — e.g. the usage subgraph's getUsageSummary /\n // checkAiCredits intermittently 500s (Postgres/Prisma blip) and the\n // gateway masks it as the opaque \"Unexpected error.\". That is NOT\n // proof the user is out of budget, so it must not abort an otherwise\n // valid send. Fail open and proceed: the wspace gateway's\n // @usage(checkQuota) on createSandbox still enforces the real budget\n // downstream (a truly over-quota caller is stopped there with a 429\n // that surfaces the upgrade dialog via the outer catch).\n console.warn(\n '[assistant] AI-credit pre-flight check failed with a non-quota error; proceeding — gateway @usage(checkQuota) still enforces the real budget downstream',\n creditError\n );\n }\n\n try {\n const { sandboxId, sessionId } = await ensureAssistantRuntime(\n conversationId,\n assistantMessageId,\n selectedMode,\n workspaceId,\n authContext\n );\n\n // Snapshot the newest message timestamp already present in this\n // (possibly reused) session BEFORE sending the prompt, so we can\n // recognise THIS turn's reply as the one created after it — never by\n // comparing the browser clock to the sandbox clock (see\n // buildAssistantProgress). The newest-N window always contains the\n // newest message, so this floor is exact regardless of conversation depth.\n const priorMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n ).catch((): AssistantRawMessage[] => []);\n const priorNewestCreatedMs = priorMessages.reduce(\n (newest, message) => Math.max(newest, getRawMessageCreatedAt(message)),\n 0\n );\n\n updateConversationStage(conversationId, assistantMessageId, 'streaming', 'Thinking...');\n // Two agent-only wrappers around the raw content, both invisible in\n // the bubble: the soft confirm-before-mutate guard for api-calls mode,\n // and the attachment block (metadata + URLs, with text-like files\n // inlined) that carries this turn's files to the model.\n // …and the language directive, so the reply comes back in the user's\n // language rather than defaulting to the language of the docs the\n // model grounds on. The FE is the only layer that knows the locale —\n // it is not on the wire and `pageContext` silently drops unknown keys.\n const promptText = buildPromptForMode(\n selectedMode,\n buildPromptWithAttachments(content, attachments),\n replyLanguageName,\n languageIsExplicit,\n options.dictated === true\n );\n // Structured multimodal parts carry the image PIXELS, which no amount\n // of prompt text can. Built from the same `promptText`, so a bridge\n // that ignores `parts` loses nothing; `undefined` for an ordinary text\n // turn keeps the wire body unchanged.\n const promptParts = buildPromptParts(promptText, attachments);\n const inlinedCount = countInlinedImageParts(promptParts);\n const carriesPixels = inlinedCount > 0;\n const pageContext = gatherPageContext();\n\n // `buildPromptParts` may have demoted a photo to a link to keep the\n // body under the gateway's cap — a long message can do that on prompt\n // text alone. That decision is invisible to the user unless we say so,\n // and an answer that reads as if the model looked at a photo it never\n // received is worse than a short note.\n imagesDropped = countInlineImageCandidates(attachments) > inlinedCount;\n\n try {\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n promptParts\n );\n } catch (sendError) {\n // `buildPromptParts` already sizes the PARTS to the gateway's cap\n // (the prompt string itself is not bounded here), so reaching this\n // point means something rejected the body anyway — a tighter proxy\n // than we modelled, or a bridge that will not take `parts` at all.\n // Losing the whole question over that is the worst outcome\n // available: re-send it text-only. Only for errors that provably\n // never reached the agent (see isMultimodalBodyRejection) — a blind\n // retry would ask the same question twice and bill it twice.\n //\n // Gated on `parts` existing at all, NOT on it carrying pixels: the\n // array duplicates the whole prompt in `parts[0]`, so a url-only\n // parts array is itself enough to push a long message over the cap.\n // `carriesPixels` only decides whether the user is told something\n // was lost.\n if (!promptParts || !isMultimodalBodyRejection(sendError)) throw sendError;\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n undefined\n );\n // Only claim a photo was lost if one actually was — a url-only\n // retry loses nothing the prompt block did not already carry.\n imagesDropped = imagesDropped || carriesPixels;\n }\n\n let result = buildAssistantProgress([], priorNewestCreatedMs);\n const timeoutAt = Date.now() + (STREAM_BUDGET_MS[selectedMode] ?? DEFAULT_STREAM_BUDGET_MS);\n let lastTtlExtensionAt = Date.now();\n\n const pollStartedAt = Date.now();\n while (Date.now() < timeoutAt) {\n const sessionMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n );\n\n result = buildAssistantProgress(sessionMessages, priorNewestCreatedMs);\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(result.content),\n });\n\n if (result.done) break;\n\n if (Date.now() - lastTtlExtensionAt > 30_000) {\n await extendAssistantSandboxTTL(apollo, sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n // Fast early, backing off after — see assistantPollSchedule. This is\n // the granularity of the whole turn: it bounds how late the answer\n // appears AND how late speech can start, because auto-speak only\n // fires once a poll observes the reply completed.\n await new Promise((resolve) => setTimeout(resolve, pollDelayMs(Date.now() - pollStartedAt)));\n }\n\n // For non-build modes a timeout is a hard failure. For vibe-plugins the\n // prompt runs async server-side (/sessions/:id/prompt-async) and keeps\n // writing artifacts after the poll budget elapses, so we surface whatever\n // it has produced instead of discarding the turn.\n if (!result.done && selectedMode !== 'vibe-plugins') {\n throw new Error('Assistant response timed out while streaming progress');\n }\n\n const artifacts =\n selectedMode === 'vibe-plugins'\n ? await getAssistantArtifacts(apollo, sandboxId, workspaceId, sessionId, authContext).catch(() => [])\n : undefined;\n\n if (!result.done) {\n // vibe-plugins build still running in the background. Append a note so\n // the user knows the answer is partial and the artifacts will finish.\n result = {\n ...result,\n content: `${result.content}\\n\\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`,\n };\n }\n\n if (imagesDropped) {\n // Said plainly, because the alternative is an answer that looks like\n // it examined a photo it never received.\n result = {\n ...result,\n content: `${result.content}\\n\\n${tr(\n 'healthybowl.assistant.attachments.imagesNotSent',\n '_Your photo was too large to include with this message, so the answer above is from the text and the file link only. Try a smaller or more tightly cropped photo._'\n )}`,\n };\n }\n\n applyAssistantResponse(result.content, artifacts, sessionId, sandboxId);\n\n if (result.tokens) {\n patchMessage(conversationId, assistantMessageId, { tokens: result.tokens });\n // Charge the real token usage against the AI-credits quota (the\n // gateway records it via @usage(trackUsage)). We AWAIT it before\n // marking the turn complete / re-enabling input: otherwise a rapid\n // follow-up send would run its pre-flight checkAiCredits against a\n // stale balance (this turn's charge still in flight) and could\n // dispatch a prompt that should have been blocked, letting fast\n // sends bypass the credit cap. Still best-effort — a charge failure\n // never blocks the displayed answer.\n try {\n await reportAssistantAiTokenUsage(apollo, workspaceId, sessionId, result.tokens, authContext);\n notifyAiCreditsUpdated();\n } catch {\n // ignore — server-side @usage tracking is the source of truth\n }\n }\n setConversationProcessing(conversationId, 'complete', assistantMessageId, null);\n } catch (error) {\n if (attempt === 1 && isRecoverableAssistantError(error)) {\n clearBackendSessionId(conversationId);\n clearSandbox(selectedMode);\n return sendWithRealBackend(2);\n }\n\n throw error;\n }\n };\n\n // Claim the slot immediately before the first await, and release it in\n // `finally` so every exit — success, quota return, thrown error — frees\n // it. Registering here rather than earlier means a synchronous throw in\n // the setup above can never strand a key and wedge the conversation.\n const turnConversationId = conversationId;\n inFlightSendsRef.current.add(turnConversationId);\n\n try {\n if (!workspaceId) {\n throw new Error('Assistant backend is unavailable without an active workspace context.');\n }\n await sendWithRealBackend();\n } catch (error) {\n // ★ Any failed turn drops the readiness proof for the sandbox it used,\n // so the NEXT turn re-probes instead of trusting a cache entry that a\n // dead pod would otherwise keep alive until the TTL lapsed. This is the\n // half that makes the short-circuit above safe.\n sandboxReadiness.current.invalidate(\n useAssistantStore.getState().sandboxesByMode[selectedMode]?.sandboxId ?? null\n );\n // A quota error reaching here is the sandbox-environment wall hit\n // during runtime provisioning (createSandbox @usage). Surface the\n // upgrade dialog instead of a generic failure (the AI-credit wall is\n // already handled by the pre-flight gate above).\n if (isQuotaExhaustedError(error)) {\n dispatchAssistantQuotaExhausted('sandbox');\n applyAssistantResponse(\n \"You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.\",\n undefined,\n undefined,\n undefined,\n 'en'\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n const errorMessage = error instanceof Error ? error.message : 'Something went wrong';\n setConversationProcessing(conversationId, 'error', assistantMessageId, errorMessage);\n // Same reason: English copy must not inherit the turn's language stamp.\n patchMessage(conversationId, assistantMessageId, {\n content: `Sorry, an error occurred: ${errorMessage}. Please try again.`,\n metadata: { lang: 'en' },\n });\n } finally {\n inFlightSendsRef.current.delete(turnConversationId);\n }\n },\n [\n activeConversationId,\n addMessage,\n apollo,\n clearBackendSessionId,\n clearSandbox,\n conversations,\n createConversation,\n ensureAssistantRuntime,\n getAccessToken,\n getWorkspaceToken,\n patchMessage,\n // Without this, switching language mid-conversation keeps sending the\n // previous language's directive until something else re-creates the\n // callback.\n languageIsExplicit,\n replyLanguageCode,\n replyLanguageName,\n setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n tr,\n updateConversationStage,\n userId,\n ]\n );\n\n const handleSuggestionClick = useCallback(\n (suggestion: string) => {\n void handleSend(suggestion);\n },\n [handleSend]\n );\n\n // Retry re-sends the most recent user prompt through the same transport — the\n // failed assistant turn stays in the transcript, a fresh one is appended.\n // The attachments come from the in-memory ref rather than the message\n // metadata: the persisted descriptors deliberately drop the inlined text of\n // text-like files, so rebuilding from them would silently retry a WEAKER\n // prompt than the one that failed.\n const handleRetry = useCallback(() => {\n const lastUserMessage = [...messages].reverse().find((message) => message.role === 'user');\n const replay = activeConversationId ? (lastSentAttachmentsRef.current[activeConversationId] ?? []) : [];\n if (lastUserMessage) void handleSend(lastUserMessage.content, replay);\n }, [messages, handleSend, activeConversationId]);\n\n // Auto-send any prompt that was queued by `useOpenAssistantHelp` (from\n // the shared GetHelpButton). We keep the latest handleSend in a ref so\n // the subscription effect below doesn't need to tear down on every\n // render — the store subscription lives for the component lifetime and\n // always calls the freshest handler.\n const handleSendRef = useRef(handleSend);\n useEffect(() => {\n handleSendRef.current = handleSend;\n }, [handleSend]);\n\n /**\n * The newest assistant reply, as the voice session's advance signal.\n *\n * Keyed on the message ID rather than the text: two consecutive answers can be\n * word-for-word identical, and text alone would then never advance the second\n * turn.\n */\n const latestAssistantReply = useMemo(() => {\n // ★ Only once the turn is COMPLETE. While it is in flight the pending\n // assistant message is patched with progress text — 'Starting assistant\n // environment...', 'Thinking...' — and exposing that would make the voice\n // session consume the message id, enter `speaking` on a placeholder, and\n // then be unable to advance when the real answer replaced it.\n if (activeIsProcessing) return null;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (message?.role !== 'assistant') continue;\n // Tool-activity markup is stripped so the session captions and speaks the\n // answer, not the machinery that produced it.\n const text = parseToolActivity(message.content).text.trim();\n return text ? { id: message.id, text } : null;\n }\n return null;\n }, [messages, activeIsProcessing]);\n\n /**\n * The last few exchanges, for the session's on-screen transcript.\n *\n * Voice turns already go through the normal send path, so they are ordinary\n * conversation messages — this only surfaces them INSIDE the session, which\n * is what makes a second question in the same session make sense.\n */\n const voiceTurns = useMemo(\n () =>\n messages\n .filter((message) => message.role === 'user' || message.role === 'assistant')\n .slice(-6)\n .map((message) => ({\n id: message.id,\n role: message.role as 'user' | 'assistant',\n text: parseToolActivity(message.content).text.trim(),\n }))\n .filter((turn) => turn.text.length > 0),\n [messages]\n );\n\n const submitVoiceTurn = useCallback((text: string) => {\n // ★ Only the voice SESSION is unambiguously dictated. The composer's\n // microphone also produces a transcript, but the user reads and edits it in\n // the box before sending, so treating that as dictated would tell the model\n // to second-guess words the user had already approved.\n void handleSendRef.current(text, [], { dictated: true });\n }, []);\n\n const voiceSession = useVoiceSession({\n onSubmit: submitVoiceTurn,\n latestReply: latestAssistantReply,\n // The language the user SPEAKS, not the interface language — the same\n // preference the composer's dictation and the reply language already use.\n language: resolveAssistantLanguage(assistantLanguage, locale).tag,\n });\n\n // Hiding the panel must end a live voice session. The host may set `visible`\n // false WITHOUT unmounting, and an unmount-only cleanup would then leave the\n // microphone recording behind an invisible panel — a privacy problem, not\n // just a leak.\n useEffect(() => {\n if (!visible && voiceSession.active) voiceSession.end();\n }, [visible, voiceSession]);\n\n useEffect(() => {\n // Flush any prompt that was queued before this component mounted.\n const initial = useAssistantStore.getState().consumePendingPrompt();\n if (initial) {\n void handleSendRef.current(initial);\n }\n\n // Watch for new prompts queued while we're already mounted.\n const unsubscribe = useAssistantStore.subscribe((state, prev) => {\n if (state.pendingPrompt && state.pendingPrompt !== prev.pendingPrompt) {\n const queued = useAssistantStore.getState().consumePendingPrompt();\n if (queued) {\n void handleSendRef.current(queued);\n }\n }\n });\n return unsubscribe;\n }, []);\n\n const performModeChange = useCallback(\n (newMode: AssistantMode) => {\n const currentConversation = activeConversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === activeConversationId)\n : undefined;\n\n if (currentConversation && (currentConversation.messages.length > 0 || currentConversation.backendSessionId)) {\n if (currentConversation.mode !== newMode) {\n const reusableDraft = useAssistantStore\n .getState()\n .conversations.find(\n (conversation) =>\n conversation.mode === newMode &&\n conversation.messages.length === 0 &&\n !conversation.backendSessionId &&\n !useAssistantStore.getState().processingByConversationId[conversation.id]\n );\n\n if (reusableDraft) {\n setActiveConversation(reusableDraft.id);\n } else {\n createConversation(undefined, newMode);\n }\n }\n } else if (activeConversationId) {\n setConversationMode(activeConversationId, newMode);\n }\n\n setMode(newMode);\n },\n [activeConversationId, createConversation, setActiveConversation, setConversationMode, setMode]\n );\n\n const handleModeChange = useCallback(\n (newMode: AssistantMode) => {\n const target = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === newMode);\n // Gate the FIRST switch into a write-capable mode behind the one-time\n // consent dialog — the dependable confirm-before-mutate guardrail.\n if (target?.writeCapable && !useAssistantStore.getState().apiCallsAcknowledged) {\n setPendingConsentMode(newMode);\n return;\n }\n performModeChange(newMode);\n },\n [performModeChange]\n );\n\n const handleConsentConfirm = useCallback(() => {\n const target = pendingConsentMode;\n setPendingConsentMode(null);\n acknowledgeApiCalls();\n if (target) performModeChange(target);\n }, [pendingConsentMode, acknowledgeApiCalls, performModeChange]);\n\n const handleConsentCancel = useCallback(() => {\n setPendingConsentMode(null);\n }, []);\n\n return (\n // `relative` so the DOCKED voice session can position itself against the\n // assistant panel rather than the viewport. Without it the docked overlay\n // would anchor to the page and cover the whole app, which is the very thing\n // docking exists to avoid.\n <div className=\"relative flex flex-1 flex-col overflow-hidden\">\n {/* Everything the voice overlay covers is made `inert` while a session is\n open. Docked, the overlay hides the transcript and composer but does\n NOT cover the page, so a full focus trap would wrongly imprison the\n user — yet leaving these focusable lets them Shift+Tab into controls\n they cannot see and operate them blind. `inert` is the precise tool:\n the page stays reachable, the covered controls do not. */}\n <div className=\"contents\" inert={voiceSession.active || undefined}>\n {/* Transcript is always visible now — the old collapse-by-default accordion\n is gone; conversation history lives behind the header button instead. */}\n {messages.length === 0 ? (\n <AssistantEmptyState mode={mode} onSuggestionClick={handleSuggestionClick} />\n ) : (\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <AssistantMessageList\n messages={messages}\n streamingMessageId={activeStreamingMessageId}\n failedMessageId={failedMessageId}\n onRetry={handleRetry}\n />\n </div>\n )}\n\n <AssistantComposer\n // ★ Ask-mode only, and enforced here rather than merely documented.\n // In `api-calls` mode the assistant WRITES to farm data behind a consent\n // gate, and BOFF-6377 (\"confirm-before-write cannot prove a human\n // approved\") is still open — a spoken \"yes, do it\" is exactly the case\n // that ticket is about. Voice control of writes is the NEXT phase, not\n // this one, so the launcher is simply absent in that mode.\n onStartVoiceSession={voiceSession.available && mode !== 'api-calls' ? voiceSession.start : undefined}\n onSend={(value, attachments) => void handleSend(value, attachments)}\n disabled={activeIsProcessing}\n placeholder={\n mode === 'api-calls'\n ? tr('healthybowl.assistant.chatArea.placeholderActions', 'What would you like me to do?')\n : tr('healthybowl.assistant.chatArea.placeholderGeneral', 'Ask HealthyBowl anything…')\n }\n mode={mode}\n availableModes={availableModes}\n onModeChange={handleModeChange}\n />\n </div>\n\n {voiceSession.active && (\n <AssistantVoiceSession\n session={voiceSession.session}\n notice={voiceSession.notice}\n turns={voiceTurns}\n onInterrupt={voiceSession.interrupt}\n spoken={latestAssistantReply?.text ?? null}\n onToggleMute={voiceSession.toggleMute}\n onEnd={voiceSession.end}\n />\n )}\n\n <AssistantApiCallsConsentDialog\n open={pendingConsentMode !== null}\n onConfirm={handleConsentConfirm}\n onCancel={handleConsentCancel}\n />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,IAAM,KAAkD;CACtD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AAO,EAAa,UAAU,KAAA;cAAxD,CAGG,EAAS,WAAW,IACnB,kBAAC,GAAD;KAA2B;KAAM,mBAAmB;IAAwB,CAAA,IAE5E,kBAAC,OAAD;KAAK,WAAU;eACb,kBAAC,GAAD;MACY;MACV,oBAAoB;MACH;MACjB,SAAS;KACV,CAAA;IACE,CAAA,GAGP,kBAAC,GAAD;KAOE,qBAAqB,EAAa,aAAa,MAAS,cAAc,EAAa,QAAQ,KAAA;KAC3F,SAAS,GAAO,MAAgB,KAAK,EAAW,GAAO,CAAW;KAClE,UAAU;KACV,aACE,MAAS,cACL,EAAG,qDAAqD,+BAA+B,IACvF,EAAG,qDAAqD,2BAA2B;KAEnF;KACU;KAChB,cAAc;IACf,CAAA,CACE;;GAEJ,EAAa,UACZ,kBAAC,IAAD;IACE,SAAS,EAAa;IACtB,QAAQ,EAAa;IACrB,OAAO;IACP,aAAa,EAAa;IAC1B,QAAQ,IAAsB,QAAQ;IACtC,cAAc,EAAa;IAC3B,OAAO,EAAa;GACrB,CAAA;GAGH,kBAAC,GAAD;IACE,MAAM,OAAuB;IAC7B,WAAW;IACX,UAAU;GACX,CAAA;EACE;;AAET"}
|
|
1
|
+
{"version":3,"file":"AssistantChatArea.js","names":[],"sources":["../../../src/components/assistant/AssistantChatArea.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState, type FC } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { findAssistantLanguage, resolveAssistantLanguage } from '@/config/assistantLanguages';\nimport { AssistantMessageList } from './AssistantMessageList';\nimport { AssistantApiCallsConsentDialog } from './AssistantApiCallsConsentDialog';\nimport { AssistantEmptyState } from './AssistantEmptyState';\nimport { AssistantComposer } from './composer/AssistantComposer';\nimport { AssistantVoiceSession } from './voice/AssistantVoiceSession';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useVoiceSession } from '../../hooks/useVoiceSession';\nimport { useAssistantApiAccess } from '@/hooks/useAssistantApiAccess';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport {\n checkAssistantAiCredits,\n createAssistantSandbox,\n createAssistantSession,\n extendAssistantSandboxTTL,\n findExistingSandbox,\n getAssistantArtifacts,\n getAssistantMessages,\n getAssistantSession,\n reportAssistantAiTokenUsage,\n sendAssistantPromptAsync,\n waitForAssistantServiceReady,\n waitForSandboxReady,\n type AssistantRawMessage,\n type AssistantSandboxAuthContext,\n} from '@/services/assistantApi';\nimport { getAssistantMedia } from '@burdenoff/fe-libs/shared/assistant';\nimport { gatherPageContext } from '@/utils/pageContext';\nimport { getOrganizationId, getWorkspaceId } from '@/utils/assistantContext';\nimport { dispatchAssistantQuotaExhausted, notifyAiCreditsUpdated } from '@/utils/aiCredits';\nimport { isQuotaExhaustedError } from '@/utils/quotaUtils';\nimport { buildPromptForMode } from '@/utils/assistantPrompt';\nimport {\n buildPromptParts,\n buildPromptWithAttachments,\n countInlineImageCandidates,\n countInlinedImageParts,\n toMessageAttachment,\n type AssistantAttachment,\n} from '@/utils/assistantAttachments';\nimport { isMultimodalBodyRejection, isRecoverableAssistantError } from '@/utils/assistantTransportErrors';\nimport { isTurnInFlight } from '@/utils/assistantTurnState';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { ASSISTANT_MODES } from '@/types/assistant';\nimport type { AssistantArtifact, AssistantConversationStatus, AssistantMode, Message } from '@/types/assistant';\nimport { pollDelayMs } from '../../utils/assistantPollSchedule';\nimport { chatTurns, voiceTurnsOnly } from '../../utils/voiceTurnVisibility';\nimport { createReadinessTracker } from '../../utils/sandboxReadiness';\n\n// How long the client streams progress before giving up on a turn. Chat replies\n// (general / api-calls) finish in seconds; a vibe-plugins build is a multi-step\n// pipeline (read docs → scaffold → bun install → bun build → checklist) that runs\n// for minutes, so it gets a much larger budget. The sandbox TTL is auto-extended\n// every 30s during the poll loop, so a longer budget never outlives the sandbox.\nconst STREAM_BUDGET_MS: Record<AssistantMode, number> = {\n general: 180_000,\n assistant: 180_000,\n 'api-calls': 180_000,\n 'vibe-plugins': 600_000,\n};\nconst DEFAULT_STREAM_BUDGET_MS = 180_000;\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n}\n\nfunction sanitizeAssistantResponse(response: string): string {\n return response\n .replace(/(Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/(X-Workspace-Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9._-]+\\.[A-Za-z0-9._-]+\\b/g, '[REDACTED_JWT]')\n .replace(/\\bsk-ant-[A-Za-z0-9-]+\\b/g, '[REDACTED_API_KEY]');\n}\n\nfunction getRawMessageCreatedAt(message: AssistantRawMessage): number {\n return message.info?.time?.created ?? 0;\n}\n\nfunction getAssistantText(parts: AssistantRawMessage['parts']): string {\n return (parts ?? [])\n .filter((part) => part.type === 'text' && typeof part.text === 'string')\n .map((part) => part.text?.trim() ?? '')\n .filter(Boolean)\n .join('\\n');\n}\n\nfunction getToolProgress(parts: AssistantRawMessage['parts']): string[] {\n return (parts ?? [])\n .filter((part) => part.type === 'tool' && part.tool)\n .map((part) => {\n const status = part.state?.status ?? 'running';\n const tool = part.tool ?? 'tool';\n if (status === 'completed') return `Completed: ${tool}`;\n if (status === 'failed') return `Failed: ${tool}`;\n return `Running: ${tool}`;\n });\n}\n\nfunction buildAssistantProgress(\n messages: AssistantRawMessage[],\n // The `created` timestamp (sandbox clock) of the newest message that already\n // existed in this session BEFORE the prompt was sent. This turn's reply is the\n // assistant message created strictly after it. Crucially this stays WITHIN the\n // sandbox clock domain: the previous code compared the sandbox-stamped\n // `created` against the browser wall-clock (Date#now), so a reply stamped at\n // prompt-time was silently dropped whenever the sandbox clock lagged the\n // browser — the turn then hung on \"Thinking...\" until the stream budget\n // elapsed. A sandbox-domain floor is immune to clock skew and correct for both\n // fresh and reused (per-conversation) sessions, with no message-window gap.\n priorNewestCreatedMs: number\n): {\n content: string;\n done: boolean;\n tokens?: { input: number; output: number };\n} {\n const relevant = messages\n .filter((message) => message.info?.role === 'assistant' && getRawMessageCreatedAt(message) > priorNewestCreatedMs)\n .sort((left, right) => getRawMessageCreatedAt(left) - getRawMessageCreatedAt(right));\n\n if (relevant.length === 0) {\n return { content: 'Thinking...', done: false };\n }\n\n const latest = relevant[relevant.length - 1]!;\n const text = getAssistantText(latest.parts);\n // Inbound image/file parts, rendered to markdown by the shared helper (which\n // escapes the label and allowlists the protocol — this is model output).\n // Without this, HealthyBowl — the one product that SENDS parts — could not\n // read one back: a media-bearing reply would never satisfy `done` and the\n // turn would poll to a false timeout.\n const media = getAssistantMedia(latest.parts);\n const toolProgress = getToolProgress(latest.parts);\n const content = [text, ...media, ...toolProgress].filter(Boolean).join('\\n\\n') || 'Thinking...';\n\n return {\n content,\n done: Boolean(latest.info?.time?.completed) && (Boolean(text) || media.length > 0 || toolProgress.length > 0),\n tokens: latest.info?.tokens,\n };\n}\n\nfunction getConversationStatusMessage(status: AssistantConversationStatus): string {\n switch (status) {\n case 'provisioning':\n return 'Starting assistant environment...';\n case 'connecting':\n return 'Connecting to assistant...';\n case 'streaming':\n return 'Thinking...';\n default:\n return '';\n }\n}\n\n/**\n * `visible` is false when the host HIDES the panel without unmounting it, which\n * is what the supported `visible` prop does. That distinction matters here: a\n * live voice session would otherwise keep the microphone open and the silence\n * timer running behind an invisible panel.\n */\ninterface AssistantChatAreaProps {\n visible?: boolean;\n}\n\nexport const AssistantChatArea: FC<AssistantChatAreaProps> = ({ visible = true }) => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken, userId } = useAuthToken();\n const { locale } = useI18n();\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n // The language the user chose to SPEAK, which is not necessarily the one the\n // interface is in — that is the whole point of the preference (BOFF-7108).\n // Named in ENGLISH deliberately: the preamble around it is English, so\n // \"Answer in Tamil.\" reads as an instruction, where a bare tag (\"ta\") invites\n // the model to answer *about* the code instead of *in* the language.\n const replyLanguageName = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale).english,\n [assistantLanguage, locale]\n );\n // A stored preference is a deliberate choice; `null` is only the interface\n // language standing in as a default. The directive treats the two differently\n // — see `buildLanguagePreamble`.\n //\n // Resolved, not merely non-null: a stale persisted code from a build that\n // offered more languages is DISCARDED by `resolveAssistantLanguage`, and\n // treating that discarded value as deliberate would tell the model the user\n // had chosen the interface language on purpose — suppressing the typed-language\n // override on the strength of a preference the selector does not even show.\n const languageIsExplicit = findAssistantLanguage(assistantLanguage) !== null;\n const replyLanguageCode = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale).code,\n [assistantLanguage, locale]\n );\n\n const {\n conversations,\n activeConversationId,\n mode,\n processingByConversationId,\n setMode,\n setConversationMode,\n setActiveConversation,\n createConversation,\n addMessage,\n updateMessage,\n patchMessage,\n setConversationProcessing,\n clearConversationProcessing,\n setBackendSessionId,\n clearBackendSessionId,\n setSandbox,\n clearSandbox,\n acknowledgeApiCalls,\n } = useAssistantStore();\n\n const activeConversation = conversations.find((conversation) => conversation.id === activeConversationId);\n const messages = activeConversation?.messages ?? [];\n const activeProcessing = activeConversationId ? processingByConversationId[activeConversationId] : undefined;\n // Only while the turn is genuinely in flight. `messageId` outlives the turn\n // (setConversationProcessing keeps it on 'complete'/'error'), so keying off it\n // alone left the transcript's aria-busy latched true forever and screen\n // readers stopped announcing new replies.\n const activeIsProcessing = isTurnInFlight(activeProcessing?.status);\n const activeStreamingMessageId = activeIsProcessing ? (activeProcessing?.messageId ?? null) : null;\n // The assistant message whose turn ended in an error — drives the Retry\n // affordance in the transcript.\n const failedMessageId = activeProcessing?.status === 'error' ? activeProcessing.messageId : null;\n\n // ── api-calls (write) mode gating ──────────────────────────────────\n // Only a global Owner/Admin may use api-calls (it mints an OAuth app under the\n // caller identity). Re-read the org scope every render (a cheap localStorage\n // read) so the admin gate reacts to an org switch without the panel\n // remounting; the value is a stable string, so useAssistantApiAccess only\n // re-fetches myRoles when the org actually changes. An empty scope simply\n // hides the mode (it could not provision the sandbox anyway).\n const apiCallsScopeId = getOrganizationId();\n const { canUseApiCalls, loading: apiAccessLoading } = useAssistantApiAccess(apiCallsScopeId);\n const availableModes = useMemo(\n () => ASSISTANT_MODES.filter((modeConfig) => !modeConfig.requiresAdmin || canUseApiCalls),\n [canUseApiCalls]\n );\n\n // Target mode awaiting the one-time consent dialog (null = dialog closed).\n const [pendingConsentMode, setPendingConsentMode] = useState<AssistantMode | null>(null);\n\n // Full attachment payload of the last send, kept so Retry can replay it\n // byte-for-byte (see handleRetry).\n const lastSentAttachmentsRef = useRef<Record<string, AssistantAttachment[]>>({});\n\n // Conversations with a turn already dispatched. Synchronous, unlike the store\n // — see the re-entry guard in handleSend for why that matters.\n /**\n * Per-sandbox record of \"last proven reachable\", so a warm sandbox is not\n * re-probed on every turn. Invalidated by any failure — see both catches.\n */\n const sandboxReadiness = useRef(createReadinessTracker());\n const inFlightSendsRef = useRef<Set<string>>(new Set());\n\n // If the active mode is no longer permitted — a non-admin with a persisted\n // api-calls mode, or the master flag turned off — fall back to the read-only\n // `assistant` mode (the default \"Ask\", available to everyone), but only AFTER\n // the role check resolves (so an admin's persisted api-calls mode isn't reset\n // during the brief loading window).\n useEffect(() => {\n if (apiAccessLoading) return;\n const activeModeConfig = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === mode);\n const blocked = !activeModeConfig || (activeModeConfig.requiresAdmin && !canUseApiCalls);\n if (blocked && mode !== 'assistant') {\n setMode('assistant');\n }\n }, [mode, canUseApiCalls, apiAccessLoading, setMode]);\n\n const updateConversationStage = useCallback(\n (conversationId: string, assistantMessageId: string, status: AssistantConversationStatus, content?: string) => {\n setConversationProcessing(conversationId, status, assistantMessageId, null);\n if (content) {\n updateMessage(conversationId, assistantMessageId, content);\n } else {\n updateMessage(conversationId, assistantMessageId, getConversationStatusMessage(status));\n }\n },\n [setConversationProcessing, updateMessage]\n );\n\n const ensureAssistantRuntime = useCallback(\n async (\n conversationId: string,\n assistantMessageId: string,\n currentMode: AssistantMode,\n workspaceId: string,\n authContext: AssistantSandboxAuthContext\n ): Promise<{ sandboxId: string; sessionId: string }> => {\n let currentSandboxId = useAssistantStore.getState().sandboxesByMode[currentMode]?.sandboxId ?? null;\n\n // Validate that a candidate sandbox (remembered locally or found running on\n // the server) is actually reachable before we reuse it. A sandbox can expire\n // (ttlSeconds) or have its backend pod reclaimed while still being briefly\n // reported RUNNING; proxying to such a dead pod fails with a terminal state\n // (\"Backend resource no longer exists\") or a permanent 502 cf-proxy timeout.\n // Returns true only when the in-sandbox agent responds; false means stale.\n const ensureSandboxReachable = async (candidateId: string): Promise<boolean> => {\n // ★ Skip a proof we already have. This ran two network waits before the\n // model saw the prompt on EVERY turn, including turns seconds after the\n // last one succeeded — a constant tax, felt most in voice where it sits\n // between the user finishing a sentence and hearing anything.\n //\n // Safe only because every failure path below invalidates: see the catch\n // here and the turn-level catch. A cache that were only ever written on\n // success would pin a dead sandbox and turn a recoverable error into a\n // loop.\n if (sandboxReadiness.current.isFresh(candidateId)) return true;\n try {\n await waitForSandboxReady(apollo, candidateId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, candidateId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n sandboxReadiness.current.markVerified(candidateId);\n return true;\n } catch {\n // Stale/expired sandbox — drop it so we provision a fresh one below\n // instead of surfacing \"Internal server error\" to the user.\n sandboxReadiness.current.invalidate(candidateId);\n return false;\n }\n };\n\n // 1) Try the locally-remembered sandbox, then 2) any running one on the\n // server. Each is only kept if it's actually reachable.\n if (currentSandboxId) {\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', 'Reusing assistant environment...');\n if (!(await ensureSandboxReachable(currentSandboxId))) {\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = null;\n }\n }\n\n if (!currentSandboxId) {\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Looking for existing environment...'\n );\n const existingId = await findExistingSandbox(apollo, workspaceId, currentMode, authContext);\n\n if (existingId) {\n setSandbox(currentMode, existingId, 'provisioning');\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Reusing assistant environment...'\n );\n if (await ensureSandboxReachable(existingId)) {\n currentSandboxId = existingId;\n } else {\n setSandbox(currentMode, null, 'provisioning');\n }\n }\n }\n\n // 3) No reusable, reachable sandbox — provision a fresh one.\n if (!currentSandboxId) {\n if (currentMode === 'api-calls' && !getAccessToken()) {\n throw new Error('API Calls mode requires an authenticated session. Please sign in again.');\n }\n\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Starting assistant environment...'\n );\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = await createAssistantSandbox(apollo, currentMode, workspaceId, authContext);\n\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n await waitForSandboxReady(apollo, currentSandboxId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, currentSandboxId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n }\n\n setSandbox(currentMode, currentSandboxId, 'running');\n\n let sessionId =\n useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n ?.backendSessionId ?? null;\n\n if (sessionId) {\n try {\n const session = await getAssistantSession(apollo, currentSandboxId, workspaceId, sessionId, authContext);\n if (session.mode !== currentMode) {\n throw new Error(`Session mode mismatch: expected ${currentMode}, received ${session.mode}`);\n }\n } catch {\n clearBackendSessionId(conversationId);\n sessionId = null;\n }\n }\n\n if (!sessionId) {\n updateConversationStage(conversationId, assistantMessageId, 'connecting', 'Preparing session...');\n const result = await createAssistantSession(apollo, currentSandboxId, workspaceId, currentMode, authContext);\n sessionId = result.sessionId;\n setBackendSessionId(conversationId, sessionId);\n }\n\n return {\n sandboxId: currentSandboxId,\n sessionId,\n };\n },\n [apollo, clearBackendSessionId, getAccessToken, setBackendSessionId, setSandbox, updateConversationStage]\n );\n\n const handleSend = useCallback(\n async (content: string, attachments: AssistantAttachment[] = [], options: { dictated?: boolean } = {}) => {\n // Only block re-entry while a turn is genuinely in-flight. Earlier code\n // checked for *any* entry in the map, which stuck around as `complete`\n // / `error` after the first turn — making every subsequent message\n // silently disappear (the input cleared but handleSend bailed before\n // adding the user message to the conversation).\n //\n // The store is read LIVE, and that is what makes the guard work. The\n // render-captured `processingByConversationId` is stale by construction —\n // the click that starts a turn and the click that must be rejected can\n // belong to the same render. Reading `activeConversationId` live matters\n // for the same reason: on two racing first-ever sends, the second must see\n // the conversation the first one created a moment ago.\n //\n // Pairs with the synchronous `setConversationProcessing` below: because\n // the status is written before this function ever awaits, a second call —\n // however soon it arrives — always observes 'provisioning'.\n const storeAtEntry = useAssistantStore.getState();\n const guardConversationId = storeAtEntry.activeConversationId ?? activeConversationId;\n if (guardConversationId) {\n if (isTurnInFlight(storeAtEntry.processingByConversationId[guardConversationId]?.status)) return;\n // Second lock, in case a future change moves the status write later:\n // this one cannot be cleared by anything but the turn's own `finally`.\n // Deliberately per-conversation — a global key would keep blocking\n // after the conversation it belonged to was deleted mid-turn, and then\n // silently swallow every subsequent send.\n if (inFlightSendsRef.current.has(guardConversationId)) return;\n }\n\n const selectedMode = storeAtEntry.mode;\n let conversationId = activeConversationId;\n const currentConversation = conversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n : undefined;\n\n if (!conversationId) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (\n currentConversation &&\n currentConversation.mode !== selectedMode &&\n (currentConversation.messages.length > 0 || currentConversation.backendSessionId)\n ) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (currentConversation && currentConversation.mode !== selectedMode) {\n setConversationMode(conversationId, selectedMode);\n }\n\n if (!conversationId) return;\n\n // Keyed by conversation: the ref outlives a conversation switch, and a\n // single global slot meant Retry in one thread replayed another thread's\n // photo onto it.\n lastSentAttachmentsRef.current[conversationId] = attachments;\n\n const workspaceId = getWorkspaceId();\n const authContext: AssistantSandboxAuthContext = {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n };\n\n const userMessage: Message = {\n id: generateId(),\n role: 'user',\n content,\n timestamp: new Date().toISOString(),\n // Slim descriptors only — the bubble re-resolves thumbnails from the\n // file id, so the persisted conversation stays small.\n // ★ `voice` marks a turn that happened in the live voice session, so the\n // chat panel can leave it out. Both surfaces share one conversation, so\n // without it every spoken exchange showed up in the typed thread.\n metadata: {\n ...(attachments.length ? { attachments: attachments.map(toMessageAttachment) } : {}),\n ...(options.dictated === true ? { voice: true } : {}),\n },\n };\n addMessage(conversationId, userMessage);\n\n const assistantMessageId = generateId();\n addMessage(conversationId, {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n timestamp: new Date().toISOString(),\n // Stamped now, not read later: this is the language the reply is being\n // generated in, and the preference may have moved on by the time\n // somebody presses Listen.\n // Carries the voice marker too: a reply to a spoken question belongs to\n // the voice session, not to the typed thread.\n metadata: { lang: replyLanguageCode, ...(options.dictated === true ? { voice: true } : {}) },\n });\n\n // Mark the turn in-flight in the STORE right now, synchronously.\n //\n // Until this line the first status write happened inside\n // `ensureAssistantRuntime`, i.e. one await later. During that window\n // `activeIsProcessing` was false and `failedMessageId` still pointed at\n // the PREVIOUS failure — so the composer stayed enabled and, worse, the\n // Retry button (which has no `disabled` of its own) stayed mounted and\n // clickable on top of a turn that had already started.\n //\n // Status only, deliberately no stage copy: `ensureAssistantRuntime` picks\n // the accurate wording a moment later (\"Reusing...\" vs \"Starting...\"), and\n // guessing here would flash the wrong one on every reused sandbox.\n setConversationProcessing(conversationId, 'provisioning', assistantMessageId, null);\n\n const applyAssistantResponse = (\n response: string,\n artifacts?: AssistantArtifact[],\n sessionId?: string,\n sandboxId?: string,\n // Our own hard-coded copy is English regardless of what the user picked.\n // Stamping it with their language makes playback read an English quota\n // message in a Tamil voice — Latin text cannot be script-detected, so\n // this metadata is trusted absolutely.\n lang: string = replyLanguageCode\n ) => {\n // `patchMessage` REPLACES metadata rather than merging it, so anything\n // omitted here is destroyed — which is how the turn-language stamp set\n // at creation was being wiped the moment the response completed,\n // silently undoing per-message language resolution. Always re-assert it.\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n metadata: {\n lang,\n ...(artifacts?.length ? { artifacts } : {}),\n ...(artifacts?.length || sessionId || sandboxId ? { mode: selectedMode } : {}),\n ...(sessionId ? { sessionId } : {}),\n ...(sandboxId ? { sandboxId } : {}),\n },\n });\n };\n\n const sendWithRealBackend = async (attempt: 1 | 2 = 1): Promise<void> => {\n // Set when this attempt had to re-send without the image bytes, so the\n // answer can say so rather than quietly reading as if the model looked.\n let imagesDropped = false;\n // Pre-flight AI-credit gate. The wspace gateway's @usage(checkQuota)\n // rejects with 429 QUOTA_EXHAUSTED when the monthly token budget is\n // depleted — block the send (don't provision a sandbox or dispatch the\n // prompt) and surface the upgrade dialog instead of a generic error.\n try {\n await checkAssistantAiCredits(apollo, workspaceId, authContext);\n } catch (creditError) {\n if (isQuotaExhaustedError(creditError)) {\n dispatchAssistantQuotaExhausted('ai-credits');\n applyAssistantResponse(\n \"You've run out of AI credits for this billing cycle. Upgrade your plan to keep chatting.\",\n undefined,\n undefined,\n undefined,\n 'en'\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n // The pre-flight gate exists ONLY to catch a genuine QUOTA_EXHAUSTED\n // rejection. Any other failure here is a transient fault in the\n // credit check itself — e.g. the usage subgraph's getUsageSummary /\n // checkAiCredits intermittently 500s (Postgres/Prisma blip) and the\n // gateway masks it as the opaque \"Unexpected error.\". That is NOT\n // proof the user is out of budget, so it must not abort an otherwise\n // valid send. Fail open and proceed: the wspace gateway's\n // @usage(checkQuota) on createSandbox still enforces the real budget\n // downstream (a truly over-quota caller is stopped there with a 429\n // that surfaces the upgrade dialog via the outer catch).\n console.warn(\n '[assistant] AI-credit pre-flight check failed with a non-quota error; proceeding — gateway @usage(checkQuota) still enforces the real budget downstream',\n creditError\n );\n }\n\n try {\n const { sandboxId, sessionId } = await ensureAssistantRuntime(\n conversationId,\n assistantMessageId,\n selectedMode,\n workspaceId,\n authContext\n );\n\n // Snapshot the newest message timestamp already present in this\n // (possibly reused) session BEFORE sending the prompt, so we can\n // recognise THIS turn's reply as the one created after it — never by\n // comparing the browser clock to the sandbox clock (see\n // buildAssistantProgress). The newest-N window always contains the\n // newest message, so this floor is exact regardless of conversation depth.\n const priorMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n ).catch((): AssistantRawMessage[] => []);\n const priorNewestCreatedMs = priorMessages.reduce(\n (newest, message) => Math.max(newest, getRawMessageCreatedAt(message)),\n 0\n );\n\n updateConversationStage(conversationId, assistantMessageId, 'streaming', 'Thinking...');\n // Two agent-only wrappers around the raw content, both invisible in\n // the bubble: the soft confirm-before-mutate guard for api-calls mode,\n // and the attachment block (metadata + URLs, with text-like files\n // inlined) that carries this turn's files to the model.\n // …and the language directive, so the reply comes back in the user's\n // language rather than defaulting to the language of the docs the\n // model grounds on. The FE is the only layer that knows the locale —\n // it is not on the wire and `pageContext` silently drops unknown keys.\n const promptText = buildPromptForMode(\n selectedMode,\n buildPromptWithAttachments(content, attachments),\n replyLanguageName,\n languageIsExplicit,\n options.dictated === true\n );\n // Structured multimodal parts carry the image PIXELS, which no amount\n // of prompt text can. Built from the same `promptText`, so a bridge\n // that ignores `parts` loses nothing; `undefined` for an ordinary text\n // turn keeps the wire body unchanged.\n const promptParts = buildPromptParts(promptText, attachments);\n const inlinedCount = countInlinedImageParts(promptParts);\n const carriesPixels = inlinedCount > 0;\n const pageContext = gatherPageContext();\n\n // `buildPromptParts` may have demoted a photo to a link to keep the\n // body under the gateway's cap — a long message can do that on prompt\n // text alone. That decision is invisible to the user unless we say so,\n // and an answer that reads as if the model looked at a photo it never\n // received is worse than a short note.\n imagesDropped = countInlineImageCandidates(attachments) > inlinedCount;\n\n try {\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n promptParts\n );\n } catch (sendError) {\n // `buildPromptParts` already sizes the PARTS to the gateway's cap\n // (the prompt string itself is not bounded here), so reaching this\n // point means something rejected the body anyway — a tighter proxy\n // than we modelled, or a bridge that will not take `parts` at all.\n // Losing the whole question over that is the worst outcome\n // available: re-send it text-only. Only for errors that provably\n // never reached the agent (see isMultimodalBodyRejection) — a blind\n // retry would ask the same question twice and bill it twice.\n //\n // Gated on `parts` existing at all, NOT on it carrying pixels: the\n // array duplicates the whole prompt in `parts[0]`, so a url-only\n // parts array is itself enough to push a long message over the cap.\n // `carriesPixels` only decides whether the user is told something\n // was lost.\n if (!promptParts || !isMultimodalBodyRejection(sendError)) throw sendError;\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n undefined\n );\n // Only claim a photo was lost if one actually was — a url-only\n // retry loses nothing the prompt block did not already carry.\n imagesDropped = imagesDropped || carriesPixels;\n }\n\n let result = buildAssistantProgress([], priorNewestCreatedMs);\n const timeoutAt = Date.now() + (STREAM_BUDGET_MS[selectedMode] ?? DEFAULT_STREAM_BUDGET_MS);\n let lastTtlExtensionAt = Date.now();\n\n const pollStartedAt = Date.now();\n while (Date.now() < timeoutAt) {\n const sessionMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n );\n\n result = buildAssistantProgress(sessionMessages, priorNewestCreatedMs);\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(result.content),\n });\n\n if (result.done) break;\n\n if (Date.now() - lastTtlExtensionAt > 30_000) {\n await extendAssistantSandboxTTL(apollo, sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n // Fast early, backing off after — see assistantPollSchedule. This is\n // the granularity of the whole turn: it bounds how late the answer\n // appears AND how late speech can start, because auto-speak only\n // fires once a poll observes the reply completed.\n await new Promise((resolve) => setTimeout(resolve, pollDelayMs(Date.now() - pollStartedAt)));\n }\n\n // For non-build modes a timeout is a hard failure. For vibe-plugins the\n // prompt runs async server-side (/sessions/:id/prompt-async) and keeps\n // writing artifacts after the poll budget elapses, so we surface whatever\n // it has produced instead of discarding the turn.\n if (!result.done && selectedMode !== 'vibe-plugins') {\n throw new Error('Assistant response timed out while streaming progress');\n }\n\n const artifacts =\n selectedMode === 'vibe-plugins'\n ? await getAssistantArtifacts(apollo, sandboxId, workspaceId, sessionId, authContext).catch(() => [])\n : undefined;\n\n if (!result.done) {\n // vibe-plugins build still running in the background. Append a note so\n // the user knows the answer is partial and the artifacts will finish.\n result = {\n ...result,\n content: `${result.content}\\n\\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`,\n };\n }\n\n if (imagesDropped) {\n // Said plainly, because the alternative is an answer that looks like\n // it examined a photo it never received.\n result = {\n ...result,\n content: `${result.content}\\n\\n${tr(\n 'healthybowl.assistant.attachments.imagesNotSent',\n '_Your photo was too large to include with this message, so the answer above is from the text and the file link only. Try a smaller or more tightly cropped photo._'\n )}`,\n };\n }\n\n applyAssistantResponse(result.content, artifacts, sessionId, sandboxId);\n\n if (result.tokens) {\n patchMessage(conversationId, assistantMessageId, { tokens: result.tokens });\n // Charge the real token usage against the AI-credits quota (the\n // gateway records it via @usage(trackUsage)). We AWAIT it before\n // marking the turn complete / re-enabling input: otherwise a rapid\n // follow-up send would run its pre-flight checkAiCredits against a\n // stale balance (this turn's charge still in flight) and could\n // dispatch a prompt that should have been blocked, letting fast\n // sends bypass the credit cap. Still best-effort — a charge failure\n // never blocks the displayed answer.\n try {\n await reportAssistantAiTokenUsage(apollo, workspaceId, sessionId, result.tokens, authContext);\n notifyAiCreditsUpdated();\n } catch {\n // ignore — server-side @usage tracking is the source of truth\n }\n }\n setConversationProcessing(conversationId, 'complete', assistantMessageId, null);\n } catch (error) {\n if (attempt === 1 && isRecoverableAssistantError(error)) {\n clearBackendSessionId(conversationId);\n clearSandbox(selectedMode);\n return sendWithRealBackend(2);\n }\n\n throw error;\n }\n };\n\n // Claim the slot immediately before the first await, and release it in\n // `finally` so every exit — success, quota return, thrown error — frees\n // it. Registering here rather than earlier means a synchronous throw in\n // the setup above can never strand a key and wedge the conversation.\n const turnConversationId = conversationId;\n inFlightSendsRef.current.add(turnConversationId);\n\n try {\n if (!workspaceId) {\n throw new Error('Assistant backend is unavailable without an active workspace context.');\n }\n await sendWithRealBackend();\n } catch (error) {\n // ★ Any failed turn drops the readiness proof for the sandbox it used,\n // so the NEXT turn re-probes instead of trusting a cache entry that a\n // dead pod would otherwise keep alive until the TTL lapsed. This is the\n // half that makes the short-circuit above safe.\n sandboxReadiness.current.invalidate(\n useAssistantStore.getState().sandboxesByMode[selectedMode]?.sandboxId ?? null\n );\n // A quota error reaching here is the sandbox-environment wall hit\n // during runtime provisioning (createSandbox @usage). Surface the\n // upgrade dialog instead of a generic failure (the AI-credit wall is\n // already handled by the pre-flight gate above).\n if (isQuotaExhaustedError(error)) {\n dispatchAssistantQuotaExhausted('sandbox');\n applyAssistantResponse(\n \"You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.\",\n undefined,\n undefined,\n undefined,\n 'en'\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n const errorMessage = error instanceof Error ? error.message : 'Something went wrong';\n setConversationProcessing(conversationId, 'error', assistantMessageId, errorMessage);\n // Same reason: English copy must not inherit the turn's language stamp.\n patchMessage(conversationId, assistantMessageId, {\n content: `Sorry, an error occurred: ${errorMessage}. Please try again.`,\n metadata: { lang: 'en' },\n });\n } finally {\n inFlightSendsRef.current.delete(turnConversationId);\n }\n },\n [\n activeConversationId,\n addMessage,\n apollo,\n clearBackendSessionId,\n clearSandbox,\n conversations,\n createConversation,\n ensureAssistantRuntime,\n getAccessToken,\n getWorkspaceToken,\n patchMessage,\n // Without this, switching language mid-conversation keeps sending the\n // previous language's directive until something else re-creates the\n // callback.\n languageIsExplicit,\n replyLanguageCode,\n replyLanguageName,\n setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n tr,\n updateConversationStage,\n userId,\n ]\n );\n\n const handleSuggestionClick = useCallback(\n (suggestion: string) => {\n void handleSend(suggestion);\n },\n [handleSend]\n );\n\n // Retry re-sends the most recent user prompt through the same transport — the\n // failed assistant turn stays in the transcript, a fresh one is appended.\n // The attachments come from the in-memory ref rather than the message\n // metadata: the persisted descriptors deliberately drop the inlined text of\n // text-like files, so rebuilding from them would silently retry a WEAKER\n // prompt than the one that failed.\n const handleRetry = useCallback(() => {\n const lastUserMessage = [...messages].reverse().find((message) => message.role === 'user');\n const replay = activeConversationId ? (lastSentAttachmentsRef.current[activeConversationId] ?? []) : [];\n if (lastUserMessage) void handleSend(lastUserMessage.content, replay);\n }, [messages, handleSend, activeConversationId]);\n\n // Auto-send any prompt that was queued by `useOpenAssistantHelp` (from\n // the shared GetHelpButton). We keep the latest handleSend in a ref so\n // the subscription effect below doesn't need to tear down on every\n // render — the store subscription lives for the component lifetime and\n // always calls the freshest handler.\n const handleSendRef = useRef(handleSend);\n useEffect(() => {\n handleSendRef.current = handleSend;\n }, [handleSend]);\n\n /**\n * The newest assistant reply, as the voice session's advance signal.\n *\n * Keyed on the message ID rather than the text: two consecutive answers can be\n * word-for-word identical, and text alone would then never advance the second\n * turn.\n */\n const latestAssistantReply = useMemo(() => {\n // ★ Only once the turn is COMPLETE. While it is in flight the pending\n // assistant message is patched with progress text — 'Starting assistant\n // environment...', 'Thinking...' — and exposing that would make the voice\n // session consume the message id, enter `speaking` on a placeholder, and\n // then be unable to advance when the real answer replaced it.\n if (activeIsProcessing) return null;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (message?.role !== 'assistant') continue;\n // Tool-activity markup is stripped so the session captions and speaks the\n // answer, not the machinery that produced it.\n const text = parseToolActivity(message.content).text.trim();\n return text ? { id: message.id, text } : null;\n }\n return null;\n }, [messages, activeIsProcessing]);\n\n /**\n * The last few exchanges, for the session's on-screen transcript.\n *\n * Voice turns already go through the normal send path, so they are ordinary\n * conversation messages — this only surfaces them INSIDE the session, which\n * is what makes a second question in the same session make sense.\n */\n /**\n * What the CHAT panel shows: everything that was not spoken.\n *\n * Voice and chat share one conversation, so without this split every spoken\n * exchange appeared in the typed thread.\n */\n const chatMessages = useMemo(() => chatTurns(messages), [messages]);\n\n const voiceTurns = useMemo(\n () =>\n // ★ Only turns from this voice session. It used to take the last six\n // messages of the WHOLE conversation, so opening voice on an existing\n // thread painted typed replies — the wall of raw `##` and `**` the\n // operator screenshotted, because the voice panel renders plain text.\n voiceTurnsOnly(messages)\n .filter((message) => message.role === 'user' || message.role === 'assistant')\n .slice(-6)\n .map((message) => ({\n id: message.id,\n role: message.role as 'user' | 'assistant',\n text: parseToolActivity(message.content).text.trim(),\n }))\n .filter((turn) => turn.text.length > 0),\n [messages]\n );\n\n const submitVoiceTurn = useCallback((text: string) => {\n // ★ Only the voice SESSION is unambiguously dictated. The composer's\n // microphone also produces a transcript, but the user reads and edits it in\n // the box before sending, so treating that as dictated would tell the model\n // to second-guess words the user had already approved.\n void handleSendRef.current(text, [], { dictated: true });\n }, []);\n\n const voiceSession = useVoiceSession({\n onSubmit: submitVoiceTurn,\n latestReply: latestAssistantReply,\n // The language the user SPEAKS, not the interface language — the same\n // preference the composer's dictation and the reply language already use.\n language: resolveAssistantLanguage(assistantLanguage, locale).tag,\n });\n\n // Hiding the panel must end a live voice session. The host may set `visible`\n // false WITHOUT unmounting, and an unmount-only cleanup would then leave the\n // microphone recording behind an invisible panel — a privacy problem, not\n // just a leak.\n useEffect(() => {\n if (!visible && voiceSession.active) voiceSession.end();\n }, [visible, voiceSession]);\n\n useEffect(() => {\n // Flush any prompt that was queued before this component mounted.\n const initial = useAssistantStore.getState().consumePendingPrompt();\n if (initial) {\n void handleSendRef.current(initial);\n }\n\n // Watch for new prompts queued while we're already mounted.\n const unsubscribe = useAssistantStore.subscribe((state, prev) => {\n if (state.pendingPrompt && state.pendingPrompt !== prev.pendingPrompt) {\n const queued = useAssistantStore.getState().consumePendingPrompt();\n if (queued) {\n void handleSendRef.current(queued);\n }\n }\n });\n return unsubscribe;\n }, []);\n\n const performModeChange = useCallback(\n (newMode: AssistantMode) => {\n const currentConversation = activeConversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === activeConversationId)\n : undefined;\n\n if (currentConversation && (currentConversation.messages.length > 0 || currentConversation.backendSessionId)) {\n if (currentConversation.mode !== newMode) {\n const reusableDraft = useAssistantStore\n .getState()\n .conversations.find(\n (conversation) =>\n conversation.mode === newMode &&\n conversation.messages.length === 0 &&\n !conversation.backendSessionId &&\n !useAssistantStore.getState().processingByConversationId[conversation.id]\n );\n\n if (reusableDraft) {\n setActiveConversation(reusableDraft.id);\n } else {\n createConversation(undefined, newMode);\n }\n }\n } else if (activeConversationId) {\n setConversationMode(activeConversationId, newMode);\n }\n\n setMode(newMode);\n },\n [activeConversationId, createConversation, setActiveConversation, setConversationMode, setMode]\n );\n\n const handleModeChange = useCallback(\n (newMode: AssistantMode) => {\n const target = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === newMode);\n // Gate the FIRST switch into a write-capable mode behind the one-time\n // consent dialog — the dependable confirm-before-mutate guardrail.\n if (target?.writeCapable && !useAssistantStore.getState().apiCallsAcknowledged) {\n setPendingConsentMode(newMode);\n return;\n }\n performModeChange(newMode);\n },\n [performModeChange]\n );\n\n const handleConsentConfirm = useCallback(() => {\n const target = pendingConsentMode;\n setPendingConsentMode(null);\n acknowledgeApiCalls();\n if (target) performModeChange(target);\n }, [pendingConsentMode, acknowledgeApiCalls, performModeChange]);\n\n const handleConsentCancel = useCallback(() => {\n setPendingConsentMode(null);\n }, []);\n\n return (\n // `relative` so the DOCKED voice session can position itself against the\n // assistant panel rather than the viewport. Without it the docked overlay\n // would anchor to the page and cover the whole app, which is the very thing\n // docking exists to avoid.\n <div className=\"relative flex flex-1 flex-col overflow-hidden\">\n {/* Everything the voice overlay covers is made `inert` while a session is\n open. Docked, the overlay hides the transcript and composer but does\n NOT cover the page, so a full focus trap would wrongly imprison the\n user — yet leaving these focusable lets them Shift+Tab into controls\n they cannot see and operate them blind. `inert` is the precise tool:\n the page stays reachable, the covered controls do not. */}\n <div className=\"contents\" inert={voiceSession.active || undefined}>\n {/* Transcript is always visible now — the old collapse-by-default accordion\n is gone; conversation history lives behind the header button instead. */}\n {chatMessages.length === 0 ? (\n <AssistantEmptyState mode={mode} onSuggestionClick={handleSuggestionClick} />\n ) : (\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <AssistantMessageList\n messages={chatMessages}\n streamingMessageId={activeStreamingMessageId}\n failedMessageId={failedMessageId}\n onRetry={handleRetry}\n />\n </div>\n )}\n\n <AssistantComposer\n // ★ Ask-mode only, and enforced here rather than merely documented.\n // In `api-calls` mode the assistant WRITES to farm data behind a consent\n // gate, and BOFF-6377 (\"confirm-before-write cannot prove a human\n // approved\") is still open — a spoken \"yes, do it\" is exactly the case\n // that ticket is about. Voice control of writes is the NEXT phase, not\n // this one, so the launcher is simply absent in that mode.\n onStartVoiceSession={voiceSession.available && mode !== 'api-calls' ? voiceSession.start : undefined}\n onSend={(value, attachments) => void handleSend(value, attachments)}\n disabled={activeIsProcessing}\n placeholder={\n mode === 'api-calls'\n ? tr('healthybowl.assistant.chatArea.placeholderActions', 'What would you like me to do?')\n : tr('healthybowl.assistant.chatArea.placeholderGeneral', 'Ask HealthyBowl anything…')\n }\n mode={mode}\n availableModes={availableModes}\n onModeChange={handleModeChange}\n />\n </div>\n\n {voiceSession.active && (\n <AssistantVoiceSession\n session={voiceSession.session}\n notice={voiceSession.notice}\n turns={voiceTurns}\n onInterrupt={voiceSession.interrupt}\n spoken={latestAssistantReply?.text ?? null}\n onToggleMute={voiceSession.toggleMute}\n onEnd={voiceSession.end}\n />\n )}\n\n <AssistantApiCallsConsentDialog\n open={pendingConsentMode !== null}\n onConfirm={handleConsentConfirm}\n onCancel={handleConsentCancel}\n />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,IAAM,KAAkD;CACtD,SAAS;CACT,WAAW;CACX,aAAa;CACb,gBAAgB;AAClB,GACM,KAA2B;AAEjC,SAAS,KAAqB;CAC5B,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC;AAC/D;AAEA,SAAS,GAA0B,GAA0B;CAC3D,OAAO,EACJ,QAAQ,6CAA6C,cAAc,EACnE,QAAQ,yDAAyD,cAAc,EAC/E,QAAQ,4DAA4D,gBAAgB,EACpF,QAAQ,6BAA6B,oBAAoB;AAC9D;AAEA,SAAS,EAAuB,GAAsC;CACpE,OAAO,EAAQ,MAAM,MAAM,WAAW;AACxC;AAEA,SAAS,EAAiB,GAA6C;CACrE,QAAQ,KAAS,CAAC,GACf,QAAQ,MAAS,EAAK,SAAS,UAAU,OAAO,EAAK,QAAS,QAAQ,EACtE,KAAK,MAAS,EAAK,MAAM,KAAK,KAAK,EAAE,EACrC,OAAO,OAAO,EACd,KAAK,IAAI;AACd;AAEA,SAAS,EAAgB,GAA+C;CACtE,QAAQ,KAAS,CAAC,GACf,QAAQ,MAAS,EAAK,SAAS,UAAU,EAAK,IAAI,EAClD,KAAK,MAAS;EACb,IAAM,IAAS,EAAK,OAAO,UAAU,WAC/B,IAAO,EAAK,QAAQ;EAG1B,OAFI,MAAW,cAAoB,c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C3B,OAAO,EAAa;GACrB,CAAA;GAGH,kBAAC,GAAD;IACE,MAAM,OAAuB;IAC7B,WAAW;IACX,UAAU;GACX,CAAA;EACE;;AAET"}
|
|
@@ -36,7 +36,7 @@ var d = ({ session: d, turns: m = [], notice: h = null, spoken: g, onInterrupt:
|
|
|
36
36
|
ref: w,
|
|
37
37
|
type: "button",
|
|
38
38
|
onClick: y,
|
|
39
|
-
className: `absolute ${E ? "right-6 top-6 size-14" : "right-3 top-3 size-11"} flex items-center justify-center rounded-full
|
|
39
|
+
className: `absolute ${E ? "right-6 top-6 size-14" : "right-3 top-3 size-11"} flex items-center justify-center rounded-full border border-border-default bg-bg-elevated text-text-secondary hover:bg-bg-sunken transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`,
|
|
40
40
|
"aria-label": b("healthybowl.assistant.voiceSession.end", "End the voice conversation"),
|
|
41
41
|
"data-testid": "assistant-voice-end",
|
|
42
42
|
children: /* @__PURE__ */ l(c, { className: E ? "size-6" : "size-5" })
|
|
@@ -59,7 +59,7 @@ var d = ({ session: d, turns: m = [], notice: h = null, spoken: g, onInterrupt:
|
|
|
59
59
|
className: "flex min-h-0 w-full flex-1 flex-col items-center justify-center gap-4 px-14",
|
|
60
60
|
children: [
|
|
61
61
|
m.length > 0 ? /* @__PURE__ */ l("div", {
|
|
62
|
-
className:
|
|
62
|
+
className: `flex w-full flex-1 flex-col justify-end gap-2 overflow-y-auto text-sm ${E ? "max-w-3xl" : "max-w-md"}`,
|
|
63
63
|
"data-testid": "assistant-voice-turns",
|
|
64
64
|
children: m.map((e) => /* @__PURE__ */ l("p", {
|
|
65
65
|
className: e.role === "user" ? "self-end rounded-2xl bg-bg-elevated px-3 py-1.5 text-text-primary" : "self-start text-text-secondary",
|
|
@@ -73,7 +73,7 @@ var d = ({ session: d, turns: m = [], notice: h = null, spoken: g, onInterrupt:
|
|
|
73
73
|
label: x === "speaking" ? b("healthybowl.assistant.voiceSession.interrupt", "Stop the assistant and speak") : S ? b("healthybowl.assistant.voiceSession.unmute", "Turn the microphone on") : b("healthybowl.assistant.voiceSession.mute", "Turn the microphone off")
|
|
74
74
|
}),
|
|
75
75
|
A ? /* @__PURE__ */ l("p", {
|
|
76
|
-
className:
|
|
76
|
+
className: `text-center leading-relaxed text-text-secondary ${E ? "max-w-3xl text-2xl font-semibold" : "line-clamp-3 max-w-md text-base"}`,
|
|
77
77
|
"data-testid": "assistant-voice-caption",
|
|
78
78
|
children: A
|
|
79
79
|
}) : null
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantVoiceSession.js","names":[],"sources":["../../../../src/components/assistant/voice/AssistantVoiceSession.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type FC } from 'react';\nimport { Maximize2, Minimize2, X } from 'lucide-react';\nimport { AssistantVoiceOrb } from './AssistantVoiceOrb';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { spokenSoFar, type VoiceSessionSnapshot } from '../../../utils/voiceSession';\nimport type { VoiceSessionError } from '../../../utils/voiceSession';\nimport type { VoiceSessionNotice } from '../../../hooks/useVoiceSession';\n\ninterface Props {\n session: VoiceSessionSnapshot;\n /** Recent exchanges, oldest first — the running conversation. */\n turns?: ReadonlyArray<{ id: string; role: 'user' | 'assistant'; text: string }>;\n /** Cut the assistant off mid-reply. */\n onInterrupt?: () => void;\n /** A recoverable problem to surface. Null when the microphone is healthy. */\n notice?: VoiceSessionNotice | null;\n /** The assistant's last reply, captioned while it is spoken. */\n spoken: string | null;\n onToggleMute: () => void;\n onEnd: () => void;\n}\n\n/**\n * Full-screen voice conversation (BOFF-7120).\n *\n * ★ **Voice only, by explicit product decision.** The reference (Gemini Live)\n * also offers camera and screen sharing; those are deliberately absent here.\n * Attaching images is a separate, existing capability of the assistant and\n * stays in the composer, and screen sharing could not work on the primary\n * device anyway — `getDisplayMedia` is unsupported by every iOS browser, so\n * that control would be dead on an iPhone.\n *\n * The controls are therefore the two that a voice conversation actually needs:\n * mute, and end. Anything else would be a button the user has to think about\n * while talking.\n *\n * This component is presentational: every transition is owned by\n * `voiceSessionReducer`, which is pure and tested. That split exists because\n * this file cannot be tested at all in this repo — vitest runs in `node` with\n * no DOM and no audio.\n */\nexport const AssistantVoiceSession: FC<Props> = ({\n session,\n turns = [],\n notice = null,\n spoken,\n onInterrupt,\n onToggleMute,\n onEnd,\n}) => {\n const tr = useTr();\n const { phase, muted, error } = session;\n const endRef = useRef<HTMLButtonElement>(null);\n const dialogRef = useRef<HTMLDivElement>(null);\n /**\n * Docked inside the assistant panel by default; full-screen only on request.\n *\n * A voice conversation is usually a glance-and-listen thing, so taking over\n * the whole screen for it is the wrong default — the user loses the page they\n * were asking about. Expanding is opt-in and per-session: reopening starts\n * docked again, which is the behaviour that matches \"default should be the\n * same size as the assistant\".\n */\n const [expanded, setExpanded] = useState(false);\n\n // A full-screen `aria-modal` overlay that cannot be dismissed from the\n // keyboard is a trap. Escape ends the session, and focus starts on End so a\n // keyboard or screen-reader user lands somewhere useful rather than behind\n // the overlay.\n // Focus lands on End ONCE, on open. Keeping this in the keydown effect below\n // meant every expand/collapse re-ran it and silently stole focus from the\n // button just pressed — a Space or Enter a beat later would then end the\n // session instead of toggling the size again.\n useEffect(() => {\n endRef.current?.focus();\n }, []);\n\n useEffect(() => {\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n onEnd();\n return;\n }\n // Trapping focus is only correct when the overlay actually covers\n // everything. Docked, it sits inside the panel and the rest of the page\n // is legitimately reachable, so trapping there would be the bug rather\n // than the fix.\n if (event.key !== 'Tab' || !expanded) return;\n // `aria-modal` only TELLS assistive technology this is modal; it does not\n // make it so. Without this, Tab walks straight out of the overlay into the\n // page behind it, which is still fully interactive underneath — a\n // keyboard user ends up operating a screen they cannot see.\n const focusable = dialogRef.current?.querySelectorAll<HTMLElement>('button:not([disabled])');\n if (!focusable || focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (!first || !last) return;\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n window.addEventListener('keydown', onKeyDown);\n return () => window.removeEventListener('keydown', onKeyDown);\n }, [onEnd, expanded]);\n\n // Muted is reported ALONGSIDE the phase, not instead of it: the assistant may\n // still be speaking with the microphone off, and saying only \"Microphone off\"\n // would misreport that.\n const phaseText =\n phase === 'thinking'\n ? tr('healthybowl.assistant.voiceSession.thinking', 'Thinking…')\n : phase === 'speaking'\n ? tr('healthybowl.assistant.voiceSession.speaking', 'Speaking — tap to stop')\n : muted\n ? tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')\n : tr('healthybowl.assistant.voiceSession.listening', 'Listening…');\n\n const status =\n error !== null\n ? errorMessage(error, tr)\n : muted && phase !== 'listening'\n ? `${phaseText} · ${tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')}`\n : phaseText;\n\n // While speaking, the caption shows the REPLY; otherwise what we have heard.\n // Showing the stale transcript under the assistant's own voice reads as a\n // mis-transcription of the assistant, which is worse than showing nothing.\n const caption = phase === 'speaking' ? spoken : spokenSoFar(session);\n\n return (\n <div\n ref={dialogRef}\n className={`flex flex-col items-center justify-between bg-bg-sunken ${\n expanded ? 'fixed inset-0 z-[60] px-6 py-10' : 'absolute inset-0 z-20 px-4 py-6'\n }`}\n role=\"dialog\"\n // Only modal when it really is: docked, the page behind stays usable.\n // `undefined` rather than `false` — the ARIA default is already false, and\n // some older assistive technology treats an explicit \"false\" on a dialog\n // as still modal.\n aria-modal={expanded || undefined}\n aria-label={tr('healthybowl.assistant.voiceSession.title', 'Voice conversation')}\n data-testid=\"assistant-voice-session\"\n >\n {/* End sits top-right and expand bottom-left, out of the centre column.\n Absolute rather than part of the flow so the pill stays optically\n centred at both sizes — the overlay is already a positioning context\n (`fixed` when expanded, `absolute` when docked). */}\n <button\n ref={endRef}\n type=\"button\"\n onClick={onEnd}\n className={`absolute ${expanded ? 'right-6 top-6 size-14' : 'right-3 top-3 size-11'} flex items-center justify-center rounded-full bg-action-danger-bg text-action-danger-text transition-colors hover:bg-action-danger-bg-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n aria-label={tr('healthybowl.assistant.voiceSession.end', 'End the voice conversation')}\n data-testid=\"assistant-voice-end\"\n >\n <X className={expanded ? 'size-6' : 'size-5'} />\n </button>\n\n {/* The session's single live region. It has real words, unlike the orb. */}\n <div className=\"flex flex-col items-center gap-1 px-14\">\n <p className=\"text-sm text-text-muted\" role=\"status\" aria-live=\"polite\" data-testid=\"assistant-voice-status\">\n {status}\n </p>\n {/* A dead microphone used to look exactly like a live one. Whatever else\n happens, the session must never claim to be listening in silence. */}\n {notice && error === null ? (\n <p className=\"max-w-xs text-center text-xs text-status-warning\" data-testid=\"assistant-voice-notice\">\n {noticeMessage(notice, tr)}\n </p>\n ) : null}\n </div>\n\n {/* Padded so the pill and caption never collide with the corner controls\n in a docked panel only a few hundred pixels wide. */}\n <div className=\"flex min-h-0 w-full flex-1 flex-col items-center justify-center gap-4 px-14\">\n {/* The running conversation, as Gemini shows it — so a second question\n in the same session has the first still visible. Oldest first, with\n the newest pinned at the bottom next to the orb. */}\n {turns.length > 0 ? (\n <div\n className=\"flex w-full max-w-md flex-1 flex-col justify-end gap-2 overflow-y-auto text-sm\"\n data-testid=\"assistant-voice-turns\"\n >\n {turns.map((turn) => (\n <p\n key={turn.id}\n className={\n turn.role === 'user'\n ? 'self-end rounded-2xl bg-bg-elevated px-3 py-1.5 text-text-primary'\n : 'self-start text-text-secondary'\n }\n >\n {turn.text}\n </p>\n ))}\n </div>\n ) : null}\n\n <AssistantVoiceOrb\n session={session}\n compact={!expanded}\n onPress={phase === 'speaking' ? onInterrupt : onToggleMute}\n label={\n phase === 'speaking'\n ? tr('healthybowl.assistant.voiceSession.interrupt', 'Stop the assistant and speak')\n : muted\n ? tr('healthybowl.assistant.voiceSession.unmute', 'Turn the microphone on')\n : tr('healthybowl.assistant.voiceSession.mute', 'Turn the microphone off')\n }\n />\n\n {/* The LIVE caption: what is being said right now, before it is\n finalised into the conversation. `turns` only holds messages that\n already reached history, so without this the in-progress utterance\n appears nowhere and the session looks deaf while it is working. */}\n {caption ? (\n <p\n className=\"line-clamp-3 max-w-md text-center text-base leading-relaxed text-text-secondary\"\n data-testid=\"assistant-voice-caption\"\n >\n {caption}\n </p>\n ) : null}\n </div>\n\n <button\n type=\"button\"\n onClick={() => setExpanded((current) => !current)}\n className={`absolute ${expanded ? 'bottom-6 left-6 size-14' : 'bottom-3 left-3 size-11'} flex items-center justify-center rounded-full bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n aria-pressed={expanded}\n aria-label={\n expanded\n ? tr('healthybowl.assistant.voiceSession.collapse', 'Fit the conversation back into the panel')\n : tr('healthybowl.assistant.voiceSession.expand', 'Expand the conversation to full screen')\n }\n data-testid=\"assistant-voice-expand\"\n >\n {expanded ? <Minimize2 className=\"size-5\" /> : <Maximize2 className=\"size-5\" />}\n </button>\n </div>\n );\n};\n\n/**\n * Recoverable problems, shown WITHOUT ending the session.\n *\n * The bug these exist for: the overlay said \"Listening…\" while the recogniser\n * was dead, and nothing anywhere said otherwise.\n */\nfunction noticeMessage(notice: VoiceSessionNotice, tr: ReturnType<typeof useTr>): string {\n switch (notice) {\n case 'network':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNetwork',\n 'Speech recognition lost its connection. Check your network — it will retry.'\n );\n case 'not-capturing':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNotCapturing',\n 'The microphone did not start. Check that this site is allowed to use it, then try again.'\n );\n case 'nothing-heard':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNothingHeard',\n 'Nothing heard yet. Check your microphone is not muted or in use by another app.'\n );\n default: {\n const unhandled: never = notice;\n return unhandled;\n }\n }\n}\n\n/**\n * Every failure is explained rather than silently closing the session.\n *\n * A session that just vanishes is the dead-button bug in another shape — the\n * exact defect BOFF-7106 had to fix on the per-message speak control.\n */\nfunction errorMessage(error: VoiceSessionError, tr: ReturnType<typeof useTr>): string {\n switch (error) {\n case 'mic-denied':\n return tr(\n 'healthybowl.assistant.voiceSession.micDenied',\n 'Microphone access is blocked. Allow it in your browser settings to talk.'\n );\n case 'no-speech-support':\n return tr(\n 'healthybowl.assistant.voiceSession.noSpeechSupport',\n 'This browser cannot listen. Try a different browser, or type instead.'\n );\n case 'no-voice-support':\n return tr(\n 'healthybowl.assistant.voiceSession.noVoiceSupport',\n 'This device has no voice that can speak this language.'\n );\n default: {\n // Exhaustive: adding a variant without copy becomes a build error rather\n // than a silently empty status line.\n const unhandled: never = error;\n return unhandled;\n }\n }\n}\n"],"mappings":";;;;;;;AAyCA,IAAa,KAAoC,EAC/C,YACA,WAAQ,CAAC,GACT,YAAS,MACT,WACA,gBACA,iBACA,eACI;CACJ,IAAM,IAAK,EAAM,GACX,EAAE,UAAO,UAAO,aAAU,GAC1B,IAAS,EAA0B,IAAI,GACvC,IAAY,EAAuB,IAAI,GAUvC,CAAC,GAAU,KAAe,EAAS,EAAK;CAc9C,AAJA,QAAgB;EACd,EAAO,SAAS,MAAM;CACxB,GAAG,CAAC,CAAC,GAEL,QAAgB;EACd,IAAM,KAAa,MAAyB;GAC1C,IAAI,EAAM,QAAQ,UAAU;IAC1B,EAAM;IACN;GACF;GAKA,IAAI,EAAM,QAAQ,SAAS,CAAC,GAAU;GAKtC,IAAM,IAAY,EAAU,SAAS,iBAA8B,wBAAwB;GAC3F,IAAI,CAAC,KAAa,EAAU,WAAW,GAAG;GAC1C,IAAM,IAAQ,EAAU,IAClB,IAAO,EAAU,EAAU,SAAS;GACtC,CAAC,KAAS,CAAC,MACX,EAAM,YAAY,SAAS,kBAAkB,KAC/C,EAAM,eAAe,GACrB,EAAK,MAAM,KACF,CAAC,EAAM,YAAY,SAAS,kBAAkB,MACvD,EAAM,eAAe,GACrB,EAAM,MAAM;EAEhB;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CAAA,IACH;KAEJ,kBAAC,GAAD;MACW;MACT,SAAS,CAAC;MACV,SAAS,MAAU,aAAa,IAAc;MAC9C,OACE,MAAU,aACN,EAAG,gDAAgD,8BAA8B,IACjF,IACE,EAAG,6CAA6C,wBAAwB,IACxE,EAAG,2CAA2C,yBAAyB;KAEhF,CAAA;KAMA,IACC,kBAAC,KAAD;MACE,WAAU;MACV,eAAY;gBAEX;KACA,CAAA,IACD;IACD;;GAEL,kBAAC,UAAD;IACE,MAAK;IACL,eAAe,GAAa,MAAY,CAAC,CAAO;IAChD,WAAW,YAAY,IAAW,4BAA4B,0BAA0B;IACxF,gBAAc;IACd,cACE,IACI,EAAG,+CAA+C,0CAA0C,IAC5F,EAAG,6CAA6C,wCAAwC;IAE9F,eAAY;cAEA,EAAX,IAAY,IAAmC,GAApC,EAAW,WAAU,SAAU,CAAmC;GACxE,CAAA;EACL;;AAET;AAQA,SAAS,EAAc,GAA4B,GAAsC;CACvF,QAAQ,GAAR;EACE,KAAK,WACH,OAAO,EACL,oDACA,6EACF;EACF,KAAK,iBACH,OAAO,EACL,yDACA,0FACF;EACF,KAAK,iBACH,OAAO,EACL,yDACA,iFACF;EACF,SAEE,OAAO;CAEX;AACF;AAQA,SAAS,EAAa,GAA0B,GAAsC;CACpF,QAAQ,GAAR;EACE,KAAK,cACH,OAAO,EACL,gDACA,0EACF;EACF,KAAK,qBACH,OAAO,EACL,sDACA,uEACF;EACF,KAAK,oBACH,OAAO,EACL,qDACA,wDACF;EACF,SAIE,OAAO;CAEX;AACF"}
|
|
1
|
+
{"version":3,"file":"AssistantVoiceSession.js","names":[],"sources":["../../../../src/components/assistant/voice/AssistantVoiceSession.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type FC } from 'react';\nimport { Maximize2, Minimize2, X } from 'lucide-react';\nimport { AssistantVoiceOrb } from './AssistantVoiceOrb';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { spokenSoFar, type VoiceSessionSnapshot } from '../../../utils/voiceSession';\nimport type { VoiceSessionError } from '../../../utils/voiceSession';\nimport type { VoiceSessionNotice } from '../../../hooks/useVoiceSession';\n\ninterface Props {\n session: VoiceSessionSnapshot;\n /** Recent exchanges, oldest first — the running conversation. */\n turns?: ReadonlyArray<{ id: string; role: 'user' | 'assistant'; text: string }>;\n /** Cut the assistant off mid-reply. */\n onInterrupt?: () => void;\n /** A recoverable problem to surface. Null when the microphone is healthy. */\n notice?: VoiceSessionNotice | null;\n /** The assistant's last reply, captioned while it is spoken. */\n spoken: string | null;\n onToggleMute: () => void;\n onEnd: () => void;\n}\n\n/**\n * Full-screen voice conversation (BOFF-7120).\n *\n * ★ **Voice only, by explicit product decision.** The reference (Gemini Live)\n * also offers camera and screen sharing; those are deliberately absent here.\n * Attaching images is a separate, existing capability of the assistant and\n * stays in the composer, and screen sharing could not work on the primary\n * device anyway — `getDisplayMedia` is unsupported by every iOS browser, so\n * that control would be dead on an iPhone.\n *\n * The controls are therefore the two that a voice conversation actually needs:\n * mute, and end. Anything else would be a button the user has to think about\n * while talking.\n *\n * This component is presentational: every transition is owned by\n * `voiceSessionReducer`, which is pure and tested. That split exists because\n * this file cannot be tested at all in this repo — vitest runs in `node` with\n * no DOM and no audio.\n */\nexport const AssistantVoiceSession: FC<Props> = ({\n session,\n turns = [],\n notice = null,\n spoken,\n onInterrupt,\n onToggleMute,\n onEnd,\n}) => {\n const tr = useTr();\n const { phase, muted, error } = session;\n const endRef = useRef<HTMLButtonElement>(null);\n const dialogRef = useRef<HTMLDivElement>(null);\n /**\n * Docked inside the assistant panel by default; full-screen only on request.\n *\n * A voice conversation is usually a glance-and-listen thing, so taking over\n * the whole screen for it is the wrong default — the user loses the page they\n * were asking about. Expanding is opt-in and per-session: reopening starts\n * docked again, which is the behaviour that matches \"default should be the\n * same size as the assistant\".\n */\n const [expanded, setExpanded] = useState(false);\n\n // A full-screen `aria-modal` overlay that cannot be dismissed from the\n // keyboard is a trap. Escape ends the session, and focus starts on End so a\n // keyboard or screen-reader user lands somewhere useful rather than behind\n // the overlay.\n // Focus lands on End ONCE, on open. Keeping this in the keydown effect below\n // meant every expand/collapse re-ran it and silently stole focus from the\n // button just pressed — a Space or Enter a beat later would then end the\n // session instead of toggling the size again.\n useEffect(() => {\n endRef.current?.focus();\n }, []);\n\n useEffect(() => {\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n onEnd();\n return;\n }\n // Trapping focus is only correct when the overlay actually covers\n // everything. Docked, it sits inside the panel and the rest of the page\n // is legitimately reachable, so trapping there would be the bug rather\n // than the fix.\n if (event.key !== 'Tab' || !expanded) return;\n // `aria-modal` only TELLS assistive technology this is modal; it does not\n // make it so. Without this, Tab walks straight out of the overlay into the\n // page behind it, which is still fully interactive underneath — a\n // keyboard user ends up operating a screen they cannot see.\n const focusable = dialogRef.current?.querySelectorAll<HTMLElement>('button:not([disabled])');\n if (!focusable || focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (!first || !last) return;\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n window.addEventListener('keydown', onKeyDown);\n return () => window.removeEventListener('keydown', onKeyDown);\n }, [onEnd, expanded]);\n\n // Muted is reported ALONGSIDE the phase, not instead of it: the assistant may\n // still be speaking with the microphone off, and saying only \"Microphone off\"\n // would misreport that.\n const phaseText =\n phase === 'thinking'\n ? tr('healthybowl.assistant.voiceSession.thinking', 'Thinking…')\n : phase === 'speaking'\n ? tr('healthybowl.assistant.voiceSession.speaking', 'Speaking — tap to stop')\n : muted\n ? tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')\n : tr('healthybowl.assistant.voiceSession.listening', 'Listening…');\n\n const status =\n error !== null\n ? errorMessage(error, tr)\n : muted && phase !== 'listening'\n ? `${phaseText} · ${tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')}`\n : phaseText;\n\n // While speaking, the caption shows the REPLY; otherwise what we have heard.\n // Showing the stale transcript under the assistant's own voice reads as a\n // mis-transcription of the assistant, which is worse than showing nothing.\n const caption = phase === 'speaking' ? spoken : spokenSoFar(session);\n\n return (\n <div\n ref={dialogRef}\n className={`flex flex-col items-center justify-between bg-bg-sunken ${\n expanded ? 'fixed inset-0 z-[60] px-6 py-10' : 'absolute inset-0 z-20 px-4 py-6'\n }`}\n role=\"dialog\"\n // Only modal when it really is: docked, the page behind stays usable.\n // `undefined` rather than `false` — the ARIA default is already false, and\n // some older assistive technology treats an explicit \"false\" on a dialog\n // as still modal.\n aria-modal={expanded || undefined}\n aria-label={tr('healthybowl.assistant.voiceSession.title', 'Voice conversation')}\n data-testid=\"assistant-voice-session\"\n >\n {/* End sits top-right and expand bottom-left, out of the centre column.\n Absolute rather than part of the flow so the pill stays optically\n centred at both sizes — the overlay is already a positioning context\n (`fixed` when expanded, `absolute` when docked). */}\n <button\n ref={endRef}\n type=\"button\"\n onClick={onEnd}\n className={`absolute ${expanded ? 'right-6 top-6 size-14' : 'right-3 top-3 size-11'} flex items-center justify-center rounded-full border border-border-default bg-bg-elevated text-text-secondary hover:bg-bg-sunken transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n aria-label={tr('healthybowl.assistant.voiceSession.end', 'End the voice conversation')}\n data-testid=\"assistant-voice-end\"\n >\n <X className={expanded ? 'size-6' : 'size-5'} />\n </button>\n\n {/* The session's single live region. It has real words, unlike the orb. */}\n <div className=\"flex flex-col items-center gap-1 px-14\">\n <p className=\"text-sm text-text-muted\" role=\"status\" aria-live=\"polite\" data-testid=\"assistant-voice-status\">\n {status}\n </p>\n {/* A dead microphone used to look exactly like a live one. Whatever else\n happens, the session must never claim to be listening in silence. */}\n {notice && error === null ? (\n <p className=\"max-w-xs text-center text-xs text-status-warning\" data-testid=\"assistant-voice-notice\">\n {noticeMessage(notice, tr)}\n </p>\n ) : null}\n </div>\n\n {/* Padded so the pill and caption never collide with the corner controls\n in a docked panel only a few hundred pixels wide. */}\n <div className=\"flex min-h-0 w-full flex-1 flex-col items-center justify-center gap-4 px-14\">\n {/* The running conversation, as Gemini shows it — so a second question\n in the same session has the first still visible. Oldest first, with\n the newest pinned at the bottom next to the orb. */}\n {turns.length > 0 ? (\n <div\n className={`flex w-full flex-1 flex-col justify-end gap-2 overflow-y-auto text-sm ${expanded ? 'max-w-3xl' : 'max-w-md'}`}\n data-testid=\"assistant-voice-turns\"\n >\n {turns.map((turn) => (\n <p\n key={turn.id}\n className={\n turn.role === 'user'\n ? 'self-end rounded-2xl bg-bg-elevated px-3 py-1.5 text-text-primary'\n : 'self-start text-text-secondary'\n }\n >\n {turn.text}\n </p>\n ))}\n </div>\n ) : null}\n\n <AssistantVoiceOrb\n session={session}\n compact={!expanded}\n onPress={phase === 'speaking' ? onInterrupt : onToggleMute}\n label={\n phase === 'speaking'\n ? tr('healthybowl.assistant.voiceSession.interrupt', 'Stop the assistant and speak')\n : muted\n ? tr('healthybowl.assistant.voiceSession.unmute', 'Turn the microphone on')\n : tr('healthybowl.assistant.voiceSession.mute', 'Turn the microphone off')\n }\n />\n\n {/* The LIVE caption: what is being said right now, before it is\n finalised into the conversation. `turns` only holds messages that\n already reached history, so without this the in-progress utterance\n appears nowhere and the session looks deaf while it is working. */}\n {caption ? (\n <p\n className={`text-center leading-relaxed text-text-secondary ${expanded ? 'max-w-3xl text-2xl font-semibold' : 'line-clamp-3 max-w-md text-base'}`}\n data-testid=\"assistant-voice-caption\"\n >\n {caption}\n </p>\n ) : null}\n </div>\n\n <button\n type=\"button\"\n onClick={() => setExpanded((current) => !current)}\n className={`absolute ${expanded ? 'bottom-6 left-6 size-14' : 'bottom-3 left-3 size-11'} flex items-center justify-center rounded-full bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n aria-pressed={expanded}\n aria-label={\n expanded\n ? tr('healthybowl.assistant.voiceSession.collapse', 'Fit the conversation back into the panel')\n : tr('healthybowl.assistant.voiceSession.expand', 'Expand the conversation to full screen')\n }\n data-testid=\"assistant-voice-expand\"\n >\n {expanded ? <Minimize2 className=\"size-5\" /> : <Maximize2 className=\"size-5\" />}\n </button>\n </div>\n );\n};\n\n/**\n * Recoverable problems, shown WITHOUT ending the session.\n *\n * The bug these exist for: the overlay said \"Listening…\" while the recogniser\n * was dead, and nothing anywhere said otherwise.\n */\nfunction noticeMessage(notice: VoiceSessionNotice, tr: ReturnType<typeof useTr>): string {\n switch (notice) {\n case 'network':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNetwork',\n 'Speech recognition lost its connection. Check your network — it will retry.'\n );\n case 'not-capturing':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNotCapturing',\n 'The microphone did not start. Check that this site is allowed to use it, then try again.'\n );\n case 'nothing-heard':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNothingHeard',\n 'Nothing heard yet. Check your microphone is not muted or in use by another app.'\n );\n default: {\n const unhandled: never = notice;\n return unhandled;\n }\n }\n}\n\n/**\n * Every failure is explained rather than silently closing the session.\n *\n * A session that just vanishes is the dead-button bug in another shape — the\n * exact defect BOFF-7106 had to fix on the per-message speak control.\n */\nfunction errorMessage(error: VoiceSessionError, tr: ReturnType<typeof useTr>): string {\n switch (error) {\n case 'mic-denied':\n return tr(\n 'healthybowl.assistant.voiceSession.micDenied',\n 'Microphone access is blocked. Allow it in your browser settings to talk.'\n );\n case 'no-speech-support':\n return tr(\n 'healthybowl.assistant.voiceSession.noSpeechSupport',\n 'This browser cannot listen. Try a different browser, or type instead.'\n );\n case 'no-voice-support':\n return tr(\n 'healthybowl.assistant.voiceSession.noVoiceSupport',\n 'This device has no voice that can speak this language.'\n );\n default: {\n // Exhaustive: adding a variant without copy becomes a build error rather\n // than a silently empty status line.\n const unhandled: never = error;\n return unhandled;\n }\n }\n}\n"],"mappings":";;;;;;;AAyCA,IAAa,KAAoC,EAC/C,YACA,WAAQ,CAAC,GACT,YAAS,MACT,WACA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mC,GAApC,EAAW,WAAU,SAAU,CAAmC;GACxE,CAAA;EACL;;AAET;AAQA,SAAS,EAAc,GAA4B,GAAsC;CACvF,QAAQ,GAAR;EACE,KAAK,WACH,OAAO,EACL,oDACA,6EACF;EACF,KAAK,iBACH,OAAO,EACL,yDACA,0FACF;EACF,KAAK,iBACH,OAAO,EACL,yDACA,iFACF;EACF,SAEE,OAAO;CAEX;AACF;AAQA,SAAS,EAAa,GAA0B,GAAsC;CACpF,QAAQ,GAAR;EACE,KAAK,cACH,OAAO,EACL,gDACA,0EACF;EACF,KAAK,qBACH,OAAO,EACL,sDACA,uEACF;EACF,KAAK,oBACH,OAAO,EACL,qDACA,wDACF;EACF,SAIE,OAAO;CAEX;AACF"}
|
|
@@ -53,6 +53,8 @@ function b({ onSubmit: b, latestReply: x, language: S }) {
|
|
|
53
53
|
let e = k !== null;
|
|
54
54
|
P.current && !e && T({ type: "speech-ended" }), P.current = e;
|
|
55
55
|
}, [k]), u(() => {
|
|
56
|
+
w.phase !== "listening" && I((e) => e === "nothing-heard" ? null : e);
|
|
57
|
+
}, [w.phase]), u(() => {
|
|
56
58
|
if (w.phase !== "speaking" || k !== null) return;
|
|
57
59
|
let e = setTimeout(() => {
|
|
58
60
|
P.current || T({ type: "speech-ended" });
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useVoiceSession.js","names":[],"sources":["../../src/hooks/useVoiceSession.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react';\nimport { useVoiceInput } from './useVoiceInput';\nimport { useAssistantSpeech } from '../components/assistant/AssistantSpeechProvider';\nimport {\n INITIAL_SESSION,\n SILENCE_SUBMIT_MS,\n isCapturing,\n isSubmittable,\n planReplyConsumption,\n spokenSoFar,\n type VoiceSessionEvent,\n type VoiceSessionSnapshot,\n voiceSessionReducer,\n} from '../utils/voiceSession';\n\n/**\n * How long to wait for playback to actually start before assuming it never will.\n *\n * Generous enough to cover a hosted round trip (the voice is fetched, not local)\n * and short enough that a silent failure does not strand the session.\n */\nconst SPEECH_START_GRACE_MS = 4000;\n\n/**\n * How long the assistant's last reply stays usable as an echo reference after\n * playback ends.\n *\n * The recogniser emits a trailing FINAL result for speaker leakage a beat after\n * the audio stops. Without this window that result is treated as a fresh user\n * utterance and submitted, and the assistant answers itself — indefinitely.\n */\nconst ECHO_GRACE_MS = 2500;\n\n/**\n * How long the session may claim to be listening while the recogniser is not\n * actually running before saying so.\n *\n * Covers the permission prompt and the recogniser's own start-up, and is short\n * enough that a dead microphone is reported rather than mimed.\n */\nconst CAPTURE_START_GRACE_MS = 5000;\n\n/**\n * How long to listen with NOTHING heard at all before hinting that we may not\n * be hearing the user.\n *\n * Deliberately generous: a person thinking before they speak is normal, and a\n * hint that fires during a pause would be worse than no hint.\n */\nconst NOTHING_HEARD_MS = 12000;\n\n/**\n * A problem worth TELLING the user about that does not warrant killing the\n * session.\n *\n * These exist because the previous behaviour was the failure mode this whole\n * feature keeps hitting: the overlay said \"Listening…\" while the recogniser was\n * dead, and nothing anywhere said otherwise. `useVoiceInput` reports `network`\n * and `unknown` and the session ignored both.\n */\nexport type VoiceSessionNotice = 'network' | 'not-capturing' | 'nothing-heard';\n\n/** 44 bytes of silence — just enough to satisfy an autoplay unlock. */\nconst SILENT_WAV = 'data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA=';\n\ninterface Options {\n /** Send a turn. The reply is observed via `latestReply`, not returned here. */\n onSubmit: (text: string) => void;\n /**\n * Id + text of the newest assistant reply. A CHANGE of id is what advances\n * the session out of `thinking` — the text alone is not enough, because two\n * consecutive replies can be identical.\n */\n latestReply: { id: string; text: string } | null;\n /** Language the user is speaking, so the recogniser is pointed correctly. */\n language: string;\n}\n\n/**\n * Drives a live voice conversation (BOFF-7120).\n *\n * Deliberately thin: the loop itself is `voiceSessionReducer`, which is pure and\n * tested, and playback is the assistant's EXISTING auto-speak path rather than a\n * second speaking mechanism. Reusing auto-speak is what keeps the \"never speak a\n * reply in a language this device has no voice for\" guarantee from BOFF-7106/7107\n * true inside the session too — a bespoke playback path here would have quietly\n * bypassed all of it.\n *\n * What this hook owns is only the parts a reducer cannot: the silence timer, the\n * microphone's lifetime, and turning \"auto-speak is currently on\" back off again\n * when the session ends.\n */\nexport function useVoiceSession({ onSubmit, latestReply, language }: Options) {\n /**\n * What the assistant is saying right now, so the reducer can tell an\n * interruption from its own voice echoing back through the speaker. Held in a\n * ref so the reducer identity stays stable across renders.\n */\n const spokenTextRef = useRef<string | null>(null);\n const reduce = useCallback(\n (snapshot: VoiceSessionSnapshot, event: VoiceSessionEvent) =>\n voiceSessionReducer(snapshot, event, spokenTextRef.current),\n []\n );\n const [session, dispatch] = useReducer(reduce, INITIAL_SESSION);\n const speech = useAssistantSpeech();\n const { autoSpeakEnabled, setAutoSpeak, speakingMessageId, stop: stopSpeaking } = speech;\n\n const silenceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n /** Auto-speak as the user had it, so ending the session restores their choice. */\n const priorAutoSpeak = useRef<boolean | null>(null);\n /** The reply id already consumed, so one reply cannot advance two turns. */\n const consumedReplyId = useRef<string | null>(null);\n const wasSpeaking = useRef(false);\n const [notice, setNotice] = useState<VoiceSessionNotice | null>(null);\n\n const sessionRef = useRef(session);\n sessionRef.current = session;\n\n /**\n * The latest reply, readable from `start` without making it a dependency.\n *\n * `start` is a `useCallback` the UI holds across renders; adding `latestReply`\n * to its deps would rebuild the handler every time a message arrives.\n */\n const latestReplyRef = useRef(latestReply);\n latestReplyRef.current = latestReply;\n\n // The echo reference: the reply being spoken, held for a grace period after\n // playback stops. Cleared only once that window expires, so the recogniser's\n // trailing final result is still recognisable as echo.\n useEffect(() => {\n if (session.phase === 'speaking') {\n spokenTextRef.current = latestReply?.text ?? null;\n return;\n }\n if (spokenTextRef.current === null) return;\n const timer = setTimeout(() => {\n spokenTextRef.current = null;\n }, ECHO_GRACE_MS);\n return () => clearTimeout(timer);\n }, [session.phase, latestReply]);\n\n const handleSpeech = useCallback((transcript: string, final: boolean) => {\n dispatch({ type: 'speech', transcript, final });\n }, []);\n\n /**\n * Cut the assistant off. An explicit tap, never inferred from audio — the\n * microphone is closed while it speaks, precisely so its own voice cannot be\n * mistaken for the user's.\n */\n const interrupt = useCallback(() => {\n stopSpeaking();\n dispatch({ type: 'interrupt' });\n }, [stopSpeaking]);\n\n // `onFinalize` delivers each NEWLY finalised phrase on its own, so these are\n // committed and accumulated by the reducer rather than replacing what came\n // before — see the composer's `appendTranscript` for the same contract.\n const handleFinal = useCallback((phrase: string) => handleSpeech(phrase, true), [handleSpeech]);\n const voice = useVoiceInput({ onFinalize: handleFinal, language });\n\n // Interim results are what make barge-in feel immediate; waiting for the\n // recogniser to finalise would leave the assistant talking over the user.\n useEffect(() => {\n if (voice.interim) handleSpeech(voice.interim, false);\n }, [voice.interim, handleSpeech]);\n\n // Silence submits the turn. Restarted on every new fragment, so the timer\n // measures silence rather than elapsed time since the turn began.\n useEffect(() => {\n if (silenceTimer.current) clearTimeout(silenceTimer.current);\n if (session.phase !== 'listening' || session.muted || !isSubmittable(spokenSoFar(session))) return;\n silenceTimer.current = setTimeout(() => dispatch({ type: 'silence' }), SILENCE_SUBMIT_MS);\n return () => {\n if (silenceTimer.current) clearTimeout(silenceTimer.current);\n };\n }, [session]);\n\n // Submitting is a side effect OF entering `thinking`, not part of the\n // reduction — the reducer stays pure.\n const pendingAtSubmit = useRef('');\n if (session.phase === 'listening') pendingAtSubmit.current = spokenSoFar(session);\n useEffect(() => {\n if (session.phase !== 'thinking') return;\n const text = pendingAtSubmit.current.trim();\n if (text) onSubmit(text);\n // `onSubmit` deliberately not a dependency: a parent that recreates it each\n // render would otherwise resubmit the same turn repeatedly.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [session.phase]);\n\n /**\n * A NEW reply id advances the session. Guarded so a re-render, or two\n * identical answers in a row, cannot double-advance it.\n *\n * ★ A reply that lands while we are NOT thinking is CLAIMED, not ignored.\n *\n * Interrupting only stops playback — nothing cancels the model, so the\n * abandoned answer still arrives seconds later, while the phase is\n * `listening`. The old guard returned early WITHOUT recording its id, which\n * left it sitting there unconsumed; the next question then entered\n * `thinking`, found that stale reply, and spoke the answer to the question\n * the user had already cut off. Ending and restarting a session had the same\n * shape.\n *\n * So the rule is: a reply arriving outside a thinking phase belongs to a turn\n * that is over. Record it so it can never advance a LATER turn, and do not\n * act on it. This is the general form of the seeding fix — that one stopped\n * the FIRST turn consuming a persisted reply, this one stops every abandoned\n * turn doing the same thing.\n */\n useEffect(() => {\n const plan = planReplyConsumption(latestReply?.id, session.phase, consumedReplyId.current);\n if (!plan.claim) return;\n consumedReplyId.current = latestReply?.id ?? null;\n if (plan.advance && latestReply) dispatch({ type: 'reply', text: latestReply.text });\n }, [latestReply, session.phase]);\n\n // Playback finishing returns us to listening, detected on the FALLING edge of\n // `speakingMessageId`.\n useEffect(() => {\n const speakingNow = speakingMessageId !== null;\n if (wasSpeaking.current && !speakingNow) dispatch({ type: 'speech-ended' });\n wasSpeaking.current = speakingNow;\n }, [speakingMessageId]);\n\n /**\n * ★ A falling edge needs a RISING edge first.\n *\n * When a reply is never spoken at all — no installed voice for that language,\n * or the browser's autoplay policy refuses because auto-speak is not a user\n * gesture — `speakingMessageId` never becomes non-null, so the effect above\n * can never fire and the session hangs in `speaking` forever with the\n * microphone open and no way back except ending it.\n *\n * So entering `speaking` starts a watchdog: if nothing has actually begun\n * speaking shortly after, the turn is handed back and the conversation\n * continues silently rather than dying.\n */\n useEffect(() => {\n if (session.phase !== 'speaking' || speakingMessageId !== null) return;\n const timer = setTimeout(() => {\n if (!wasSpeaking.current) dispatch({ type: 'speech-ended' });\n }, SPEECH_START_GRACE_MS);\n return () => clearTimeout(timer);\n }, [session.phase, speakingMessageId]);\n\n // The microphone follows the state machine, including while the assistant\n // speaks — barge-in is impossible with a closed microphone.\n useEffect(() => {\n if (isCapturing(session)) {\n if (!voice.isListening) voice.start();\n } else if (voice.isListening) {\n voice.stop();\n }\n }, [session, voice]);\n\n // Only the FATAL recognition errors end the session. `no-speech`, `network`\n // and `unknown` are transient — the recogniser recovers from them, and tearing\n // the session down on a moment's silence or a network blip would be worse than\n // the problem.\n useEffect(() => {\n if (voice.error === 'not-allowed' || voice.error === 'audio-capture') {\n dispatch({ type: 'fail', error: 'mic-denied' });\n } else if (voice.error === 'language-not-supported') {\n dispatch({ type: 'fail', error: 'no-speech-support' });\n } else if (voice.error === 'network') {\n // Chrome's recogniser is a NETWORK service. Losing it leaves the session\n // deaf while still looking alive, so it is reported rather than ignored —\n // but not fatal, because it recovers on its own.\n setNotice('network');\n }\n }, [voice.error]);\n\n // Say so when we claim to be listening but the recogniser never actually\n // started. `useVoiceInput.start()` swallows a throw and simply leaves\n // `isListening` false, which previously produced a silent, permanent\n // \"Listening…\".\n useEffect(() => {\n if (!isCapturing(session) || voice.isListening) return;\n const timer = setTimeout(() => setNotice('not-capturing'), CAPTURE_START_GRACE_MS);\n return () => clearTimeout(timer);\n }, [session, voice.isListening]);\n\n // And say so when the microphone IS running but has heard nothing at all.\n useEffect(() => {\n if (session.phase !== 'listening' || session.muted || !voice.isListening) return;\n if (spokenSoFar(session) !== '') return;\n const timer = setTimeout(() => setNotice('nothing-heard'), NOTHING_HEARD_MS);\n return () => clearTimeout(timer);\n }, [session, voice.isListening]);\n\n // Any successful capture clears the complaint — the recogniser recovered.\n useEffect(() => {\n if (spokenSoFar(session) !== '') setNotice(null);\n }, [session]);\n\n const start = useCallback(() => {\n if (!voice.isSupported) {\n dispatch({ type: 'fail', error: 'no-speech-support' });\n return;\n }\n if (speech.isBlocked) {\n dispatch({ type: 'fail', error: 'no-voice-support' });\n return;\n }\n // Replies must be spoken for a voice conversation to be a conversation, so\n // auto-speak is forced on for the session and the user's own setting is\n // restored on exit.\n // ★ Unlock audio while we still hold a user gesture.\n //\n // iOS refuses `speechSynthesis.speak()` unless it originates from a user\n // interaction. In a session the reply arrives asynchronously and auto-speak\n // fires on its own, which is NOT a gesture — so on iPhone the assistant\n // answered on screen and stayed silent. Speaking an empty utterance inside\n // this click unlocks synthesis for the rest of the session.\n // BOTH media paths, because they are gated independently. `speechSynthesis`\n // is what the device engine uses; the hosted engine plays an\n // `HTMLAudioElement` (`new Audio(...).play()` in hostedTtsSpeechEngine), and\n // unlocking one does NOT unlock the other. Priming only synthesis would work\n // today and go silent again the moment hosted TTS is switched on — the same\n // iOS silence, reintroduced by a fix for it.\n try {\n const synthesis = typeof window !== 'undefined' ? window.speechSynthesis : null;\n if (synthesis && typeof window.SpeechSynthesisUtterance === 'function') {\n const primer = new window.SpeechSynthesisUtterance('');\n primer.volume = 0;\n synthesis.speak(primer);\n }\n } catch {\n // Best effort: a platform that throws here is one where playback was\n // never going to work, and the watchdog reports that.\n }\n\n try {\n if (typeof window !== 'undefined' && typeof window.Audio === 'function') {\n // A minimal silent WAV. Playing it inside the gesture is what grants the\n // media element permission for the rest of the session.\n const silent = new window.Audio(SILENT_WAV);\n silent.volume = 0;\n void silent.play().catch(() => {});\n }\n } catch {\n /* same rationale as above */\n }\n\n priorAutoSpeak.current = autoSpeakEnabled;\n if (!autoSpeakEnabled) setAutoSpeak(true);\n setNotice(null);\n\n /**\n * ★ Claim whatever reply already exists, so the first turn cannot consume it.\n *\n * `consumedReplyId` starts null, and conversations are persisted — so on the\n * first turn of a reopened session `latestReply` is the PREVIOUS answer. The\n * reply effect fired the moment the phase became `thinking`, consumed that\n * stale answer and advanced to `speaking`. Nothing was actually playing, so\n * the watchdog handed the turn back to `listening` while the real reply was\n * still in flight — with the echo reference already cleared. The microphone\n * was then open when the real answer came out of the speaker, transcribed\n * it, and submitted the assistant's own words as the next question.\n *\n * It never re-synced either: the real reply then arrived while the phase was\n * `listening`, so the effect returned early without updating the id, and\n * every following turn repeated the same stale advance. That is the \"it\n * gives result different things\" report, and it is not mis-hearing anyone.\n */\n consumedReplyId.current = latestReplyRef.current?.id ?? null;\n dispatch({ type: 'start' });\n }, [voice.isSupported, speech.isBlocked, autoSpeakEnabled, setAutoSpeak]);\n\n const end = useCallback(() => {\n dispatch({ type: 'end' });\n stopSpeaking();\n if (priorAutoSpeak.current !== null) setAutoSpeak(priorAutoSpeak.current);\n priorAutoSpeak.current = null;\n }, [stopSpeaking, setAutoSpeak]);\n\n const toggleMute = useCallback(() => {\n dispatch({ type: 'mute', muted: !sessionRef.current.muted });\n }, []);\n\n // Leaving the panel mid-session must not leave the microphone open or the\n // user's auto-speak preference flipped.\n useEffect(\n () => () => {\n if (priorAutoSpeak.current !== null) setAutoSpeak(priorAutoSpeak.current);\n },\n [setAutoSpeak]\n );\n\n return useMemo(\n () => ({\n session,\n /** A recoverable problem worth showing, or null when all is well. */\n notice,\n /** Whether the microphone is genuinely capturing right now. */\n capturing: voice.isListening,\n /** True once started and not yet ended — what decides whether to render. */\n active: session.phase !== 'idle' && session.phase !== 'ended',\n /** Can a session be offered at all on this device? */\n available: voice.isSupported && !speech.isBlocked,\n start,\n end,\n toggleMute,\n interrupt,\n }),\n [session, notice, voice.isListening, voice.isSupported, speech.isBlocked, start, end, toggleMute, interrupt]\n );\n}\n"],"mappings":";;;;;AAqBA,IAAM,IAAwB,KAUxB,IAAgB,MAShB,IAAyB,KASzB,IAAmB,MAcnB,IAAa;AA6BnB,SAAgB,EAAgB,EAAE,aAAU,gBAAa,eAAqB;CAM5E,IAAM,IAAgB,EAAsB,IAAI,GAM1C,CAAC,GAAS,KAAY,EALb,GACZ,GAAgC,MAC/B,EAAoB,GAAU,GAAO,EAAc,OAAO,GAC5D,CAAC,CAEoC,GAAQ,CAAe,GACxD,IAAS,EAAmB,GAC5B,EAAE,qBAAkB,iBAAc,sBAAmB,MAAM,MAAiB,GAE5E,IAAe,EAA6C,IAAI,GAEhE,IAAiB,EAAuB,IAAI,GAE5C,IAAkB,EAAsB,IAAI,GAC5C,IAAc,EAAO,EAAK,GAC1B,CAAC,GAAQ,KAAa,EAAoC,IAAI,GAE9D,IAAa,EAAO,CAAO;CACjC,EAAW,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M,EAAa,EAAe,OAAO,GACxE,EAAe,UAAU;CAC3B,GAAG,CAAC,GAAc,CAAY,CAAC,GAEzB,IAAa,QAAkB;EACnC,EAAS;GAAE,MAAM;GAAQ,OAAO,CAAC,EAAW,QAAQ;EAAM,CAAC;CAC7D,GAAG,CAAC,CAAC;CAWL,OAPA,cACc;EACV,AAAI,EAAe,YAAY,QAAM,EAAa,EAAe,OAAO;CAC1E,GACA,CAAC,CAAY,CACf,GAEO,SACE;EACL;EAEA;EAEA,WAAW,EAAM;EAEjB,QAAQ,EAAQ,UAAU,UAAU,EAAQ,UAAU;EAEtD,WAAW,EAAM,eAAe,CAAC,EAAO;EACxC;EACA;EACA;EACA;CACF,IACA;EAAC;EAAS;EAAQ,EAAM;EAAa,EAAM;EAAa,EAAO;EAAW;EAAO;EAAK;EAAY;CAAS,CAC7G;AACF"}
|
|
1
|
+
{"version":3,"file":"useVoiceSession.js","names":[],"sources":["../../src/hooks/useVoiceSession.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react';\nimport { useVoiceInput } from './useVoiceInput';\nimport { useAssistantSpeech } from '../components/assistant/AssistantSpeechProvider';\nimport {\n INITIAL_SESSION,\n SILENCE_SUBMIT_MS,\n isCapturing,\n isSubmittable,\n planReplyConsumption,\n spokenSoFar,\n type VoiceSessionEvent,\n type VoiceSessionSnapshot,\n voiceSessionReducer,\n} from '../utils/voiceSession';\n\n/**\n * How long to wait for playback to actually start before assuming it never will.\n *\n * Generous enough to cover a hosted round trip (the voice is fetched, not local)\n * and short enough that a silent failure does not strand the session.\n */\nconst SPEECH_START_GRACE_MS = 4000;\n\n/**\n * How long the assistant's last reply stays usable as an echo reference after\n * playback ends.\n *\n * The recogniser emits a trailing FINAL result for speaker leakage a beat after\n * the audio stops. Without this window that result is treated as a fresh user\n * utterance and submitted, and the assistant answers itself — indefinitely.\n */\nconst ECHO_GRACE_MS = 2500;\n\n/**\n * How long the session may claim to be listening while the recogniser is not\n * actually running before saying so.\n *\n * Covers the permission prompt and the recogniser's own start-up, and is short\n * enough that a dead microphone is reported rather than mimed.\n */\nconst CAPTURE_START_GRACE_MS = 5000;\n\n/**\n * How long to listen with NOTHING heard at all before hinting that we may not\n * be hearing the user.\n *\n * Deliberately generous: a person thinking before they speak is normal, and a\n * hint that fires during a pause would be worse than no hint.\n */\nconst NOTHING_HEARD_MS = 12000;\n\n/**\n * A problem worth TELLING the user about that does not warrant killing the\n * session.\n *\n * These exist because the previous behaviour was the failure mode this whole\n * feature keeps hitting: the overlay said \"Listening…\" while the recogniser was\n * dead, and nothing anywhere said otherwise. `useVoiceInput` reports `network`\n * and `unknown` and the session ignored both.\n */\nexport type VoiceSessionNotice = 'network' | 'not-capturing' | 'nothing-heard';\n\n/** 44 bytes of silence — just enough to satisfy an autoplay unlock. */\nconst SILENT_WAV = 'data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA=';\n\ninterface Options {\n /** Send a turn. The reply is observed via `latestReply`, not returned here. */\n onSubmit: (text: string) => void;\n /**\n * Id + text of the newest assistant reply. A CHANGE of id is what advances\n * the session out of `thinking` — the text alone is not enough, because two\n * consecutive replies can be identical.\n */\n latestReply: { id: string; text: string } | null;\n /** Language the user is speaking, so the recogniser is pointed correctly. */\n language: string;\n}\n\n/**\n * Drives a live voice conversation (BOFF-7120).\n *\n * Deliberately thin: the loop itself is `voiceSessionReducer`, which is pure and\n * tested, and playback is the assistant's EXISTING auto-speak path rather than a\n * second speaking mechanism. Reusing auto-speak is what keeps the \"never speak a\n * reply in a language this device has no voice for\" guarantee from BOFF-7106/7107\n * true inside the session too — a bespoke playback path here would have quietly\n * bypassed all of it.\n *\n * What this hook owns is only the parts a reducer cannot: the silence timer, the\n * microphone's lifetime, and turning \"auto-speak is currently on\" back off again\n * when the session ends.\n */\nexport function useVoiceSession({ onSubmit, latestReply, language }: Options) {\n /**\n * What the assistant is saying right now, so the reducer can tell an\n * interruption from its own voice echoing back through the speaker. Held in a\n * ref so the reducer identity stays stable across renders.\n */\n const spokenTextRef = useRef<string | null>(null);\n const reduce = useCallback(\n (snapshot: VoiceSessionSnapshot, event: VoiceSessionEvent) =>\n voiceSessionReducer(snapshot, event, spokenTextRef.current),\n []\n );\n const [session, dispatch] = useReducer(reduce, INITIAL_SESSION);\n const speech = useAssistantSpeech();\n const { autoSpeakEnabled, setAutoSpeak, speakingMessageId, stop: stopSpeaking } = speech;\n\n const silenceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n /** Auto-speak as the user had it, so ending the session restores their choice. */\n const priorAutoSpeak = useRef<boolean | null>(null);\n /** The reply id already consumed, so one reply cannot advance two turns. */\n const consumedReplyId = useRef<string | null>(null);\n const wasSpeaking = useRef(false);\n const [notice, setNotice] = useState<VoiceSessionNotice | null>(null);\n\n const sessionRef = useRef(session);\n sessionRef.current = session;\n\n /**\n * The latest reply, readable from `start` without making it a dependency.\n *\n * `start` is a `useCallback` the UI holds across renders; adding `latestReply`\n * to its deps would rebuild the handler every time a message arrives.\n */\n const latestReplyRef = useRef(latestReply);\n latestReplyRef.current = latestReply;\n\n // The echo reference: the reply being spoken, held for a grace period after\n // playback stops. Cleared only once that window expires, so the recogniser's\n // trailing final result is still recognisable as echo.\n useEffect(() => {\n if (session.phase === 'speaking') {\n spokenTextRef.current = latestReply?.text ?? null;\n return;\n }\n if (spokenTextRef.current === null) return;\n const timer = setTimeout(() => {\n spokenTextRef.current = null;\n }, ECHO_GRACE_MS);\n return () => clearTimeout(timer);\n }, [session.phase, latestReply]);\n\n const handleSpeech = useCallback((transcript: string, final: boolean) => {\n dispatch({ type: 'speech', transcript, final });\n }, []);\n\n /**\n * Cut the assistant off. An explicit tap, never inferred from audio — the\n * microphone is closed while it speaks, precisely so its own voice cannot be\n * mistaken for the user's.\n */\n const interrupt = useCallback(() => {\n stopSpeaking();\n dispatch({ type: 'interrupt' });\n }, [stopSpeaking]);\n\n // `onFinalize` delivers each NEWLY finalised phrase on its own, so these are\n // committed and accumulated by the reducer rather than replacing what came\n // before — see the composer's `appendTranscript` for the same contract.\n const handleFinal = useCallback((phrase: string) => handleSpeech(phrase, true), [handleSpeech]);\n const voice = useVoiceInput({ onFinalize: handleFinal, language });\n\n // Interim results are what make barge-in feel immediate; waiting for the\n // recogniser to finalise would leave the assistant talking over the user.\n useEffect(() => {\n if (voice.interim) handleSpeech(voice.interim, false);\n }, [voice.interim, handleSpeech]);\n\n // Silence submits the turn. Restarted on every new fragment, so the timer\n // measures silence rather than elapsed time since the turn began.\n useEffect(() => {\n if (silenceTimer.current) clearTimeout(silenceTimer.current);\n if (session.phase !== 'listening' || session.muted || !isSubmittable(spokenSoFar(session))) return;\n silenceTimer.current = setTimeout(() => dispatch({ type: 'silence' }), SILENCE_SUBMIT_MS);\n return () => {\n if (silenceTimer.current) clearTimeout(silenceTimer.current);\n };\n }, [session]);\n\n // Submitting is a side effect OF entering `thinking`, not part of the\n // reduction — the reducer stays pure.\n const pendingAtSubmit = useRef('');\n if (session.phase === 'listening') pendingAtSubmit.current = spokenSoFar(session);\n useEffect(() => {\n if (session.phase !== 'thinking') return;\n const text = pendingAtSubmit.current.trim();\n if (text) onSubmit(text);\n // `onSubmit` deliberately not a dependency: a parent that recreates it each\n // render would otherwise resubmit the same turn repeatedly.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [session.phase]);\n\n /**\n * A NEW reply id advances the session. Guarded so a re-render, or two\n * identical answers in a row, cannot double-advance it.\n *\n * ★ A reply that lands while we are NOT thinking is CLAIMED, not ignored.\n *\n * Interrupting only stops playback — nothing cancels the model, so the\n * abandoned answer still arrives seconds later, while the phase is\n * `listening`. The old guard returned early WITHOUT recording its id, which\n * left it sitting there unconsumed; the next question then entered\n * `thinking`, found that stale reply, and spoke the answer to the question\n * the user had already cut off. Ending and restarting a session had the same\n * shape.\n *\n * So the rule is: a reply arriving outside a thinking phase belongs to a turn\n * that is over. Record it so it can never advance a LATER turn, and do not\n * act on it. This is the general form of the seeding fix — that one stopped\n * the FIRST turn consuming a persisted reply, this one stops every abandoned\n * turn doing the same thing.\n */\n useEffect(() => {\n const plan = planReplyConsumption(latestReply?.id, session.phase, consumedReplyId.current);\n if (!plan.claim) return;\n consumedReplyId.current = latestReply?.id ?? null;\n if (plan.advance && latestReply) dispatch({ type: 'reply', text: latestReply.text });\n }, [latestReply, session.phase]);\n\n // Playback finishing returns us to listening, detected on the FALLING edge of\n // `speakingMessageId`.\n useEffect(() => {\n const speakingNow = speakingMessageId !== null;\n if (wasSpeaking.current && !speakingNow) dispatch({ type: 'speech-ended' });\n wasSpeaking.current = speakingNow;\n }, [speakingMessageId]);\n\n /**\n * ★ A falling edge needs a RISING edge first.\n *\n * When a reply is never spoken at all — no installed voice for that language,\n * or the browser's autoplay policy refuses because auto-speak is not a user\n * gesture — `speakingMessageId` never becomes non-null, so the effect above\n * can never fire and the session hangs in `speaking` forever with the\n * microphone open and no way back except ending it.\n *\n * So entering `speaking` starts a watchdog: if nothing has actually begun\n * speaking shortly after, the turn is handed back and the conversation\n * continues silently rather than dying.\n */\n /**\n * ★ Clear the \"we can't hear you\" hint the moment listening ends.\n *\n * It fired after 12s of silence and then had no path back: nothing cleared it\n * on LEAVING `listening`, so it stayed on screen through \"Thinking…\", through\n * the assistant speaking, and into every later turn. On a screenshot taken\n * mid-reply it claimed the microphone was dead while the assistant was\n * talking — a warning that is not merely stale but false.\n */\n useEffect(() => {\n if (session.phase === 'listening') return;\n setNotice((current) => (current === 'nothing-heard' ? null : current));\n }, [session.phase]);\n\n useEffect(() => {\n if (session.phase !== 'speaking' || speakingMessageId !== null) return;\n const timer = setTimeout(() => {\n if (!wasSpeaking.current) dispatch({ type: 'speech-ended' });\n }, SPEECH_START_GRACE_MS);\n return () => clearTimeout(timer);\n }, [session.phase, speakingMessageId]);\n\n // The microphone follows the state machine, including while the assistant\n // speaks — barge-in is impossible with a closed microphone.\n useEffect(() => {\n if (isCapturing(session)) {\n if (!voice.isListening) voice.start();\n } else if (voice.isListening) {\n voice.stop();\n }\n }, [session, voice]);\n\n // Only the FATAL recognition errors end the session. `no-speech`, `network`\n // and `unknown` are transient — the recogniser recovers from them, and tearing\n // the session down on a moment's silence or a network blip would be worse than\n // the problem.\n useEffect(() => {\n if (voice.error === 'not-allowed' || voice.error === 'audio-capture') {\n dispatch({ type: 'fail', error: 'mic-denied' });\n } else if (voice.error === 'language-not-supported') {\n dispatch({ type: 'fail', error: 'no-speech-support' });\n } else if (voice.error === 'network') {\n // Chrome's recogniser is a NETWORK service. Losing it leaves the session\n // deaf while still looking alive, so it is reported rather than ignored —\n // but not fatal, because it recovers on its own.\n setNotice('network');\n }\n }, [voice.error]);\n\n // Say so when we claim to be listening but the recogniser never actually\n // started. `useVoiceInput.start()` swallows a throw and simply leaves\n // `isListening` false, which previously produced a silent, permanent\n // \"Listening…\".\n useEffect(() => {\n if (!isCapturing(session) || voice.isListening) return;\n const timer = setTimeout(() => setNotice('not-capturing'), CAPTURE_START_GRACE_MS);\n return () => clearTimeout(timer);\n }, [session, voice.isListening]);\n\n // And say so when the microphone IS running but has heard nothing at all.\n useEffect(() => {\n if (session.phase !== 'listening' || session.muted || !voice.isListening) return;\n if (spokenSoFar(session) !== '') return;\n const timer = setTimeout(() => setNotice('nothing-heard'), NOTHING_HEARD_MS);\n return () => clearTimeout(timer);\n }, [session, voice.isListening]);\n\n // Any successful capture clears the complaint — the recogniser recovered.\n useEffect(() => {\n if (spokenSoFar(session) !== '') setNotice(null);\n }, [session]);\n\n const start = useCallback(() => {\n if (!voice.isSupported) {\n dispatch({ type: 'fail', error: 'no-speech-support' });\n return;\n }\n if (speech.isBlocked) {\n dispatch({ type: 'fail', error: 'no-voice-support' });\n return;\n }\n // Replies must be spoken for a voice conversation to be a conversation, so\n // auto-speak is forced on for the session and the user's own setting is\n // restored on exit.\n // ★ Unlock audio while we still hold a user gesture.\n //\n // iOS refuses `speechSynthesis.speak()` unless it originates from a user\n // interaction. In a session the reply arrives asynchronously and auto-speak\n // fires on its own, which is NOT a gesture — so on iPhone the assistant\n // answered on screen and stayed silent. Speaking an empty utterance inside\n // this click unlocks synthesis for the rest of the session.\n // BOTH media paths, because they are gated independently. `speechSynthesis`\n // is what the device engine uses; the hosted engine plays an\n // `HTMLAudioElement` (`new Audio(...).play()` in hostedTtsSpeechEngine), and\n // unlocking one does NOT unlock the other. Priming only synthesis would work\n // today and go silent again the moment hosted TTS is switched on — the same\n // iOS silence, reintroduced by a fix for it.\n try {\n const synthesis = typeof window !== 'undefined' ? window.speechSynthesis : null;\n if (synthesis && typeof window.SpeechSynthesisUtterance === 'function') {\n const primer = new window.SpeechSynthesisUtterance('');\n primer.volume = 0;\n synthesis.speak(primer);\n }\n } catch {\n // Best effort: a platform that throws here is one where playback was\n // never going to work, and the watchdog reports that.\n }\n\n try {\n if (typeof window !== 'undefined' && typeof window.Audio === 'function') {\n // A minimal silent WAV. Playing it inside the gesture is what grants the\n // media element permission for the rest of the session.\n const silent = new window.Audio(SILENT_WAV);\n silent.volume = 0;\n void silent.play().catch(() => {});\n }\n } catch {\n /* same rationale as above */\n }\n\n priorAutoSpeak.current = autoSpeakEnabled;\n if (!autoSpeakEnabled) setAutoSpeak(true);\n setNotice(null);\n\n /**\n * ★ Claim whatever reply already exists, so the first turn cannot consume it.\n *\n * `consumedReplyId` starts null, and conversations are persisted — so on the\n * first turn of a reopened session `latestReply` is the PREVIOUS answer. The\n * reply effect fired the moment the phase became `thinking`, consumed that\n * stale answer and advanced to `speaking`. Nothing was actually playing, so\n * the watchdog handed the turn back to `listening` while the real reply was\n * still in flight — with the echo reference already cleared. The microphone\n * was then open when the real answer came out of the speaker, transcribed\n * it, and submitted the assistant's own words as the next question.\n *\n * It never re-synced either: the real reply then arrived while the phase was\n * `listening`, so the effect returned early without updating the id, and\n * every following turn repeated the same stale advance. That is the \"it\n * gives result different things\" report, and it is not mis-hearing anyone.\n */\n consumedReplyId.current = latestReplyRef.current?.id ?? null;\n dispatch({ type: 'start' });\n }, [voice.isSupported, speech.isBlocked, autoSpeakEnabled, setAutoSpeak]);\n\n const end = useCallback(() => {\n dispatch({ type: 'end' });\n stopSpeaking();\n if (priorAutoSpeak.current !== null) setAutoSpeak(priorAutoSpeak.current);\n priorAutoSpeak.current = null;\n }, [stopSpeaking, setAutoSpeak]);\n\n const toggleMute = useCallback(() => {\n dispatch({ type: 'mute', muted: !sessionRef.current.muted });\n }, []);\n\n // Leaving the panel mid-session must not leave the microphone open or the\n // user's auto-speak preference flipped.\n useEffect(\n () => () => {\n if (priorAutoSpeak.current !== null) setAutoSpeak(priorAutoSpeak.current);\n },\n [setAutoSpeak]\n );\n\n return useMemo(\n () => ({\n session,\n /** A recoverable problem worth showing, or null when all is well. */\n notice,\n /** Whether the microphone is genuinely capturing right now. */\n capturing: voice.isListening,\n /** True once started and not yet ended — what decides whether to render. */\n active: session.phase !== 'idle' && session.phase !== 'ended',\n /** Can a session be offered at all on this device? */\n available: voice.isSupported && !speech.isBlocked,\n start,\n end,\n toggleMute,\n interrupt,\n }),\n [session, notice, voice.isListening, voice.isSupported, speech.isBlocked, start, end, toggleMute, interrupt]\n );\n}\n"],"mappings":";;;;;AAqBA,IAAM,IAAwB,KAUxB,IAAgB,MAShB,IAAyB,KASzB,IAAmB,MAcnB,IAAa;AA6BnB,SAAgB,EAAgB,EAAE,aAAU,gBAAa,eAAqB;CAM5E,IAAM,IAAgB,EAAsB,IAAI,GAM1C,CAAC,GAAS,KAAY,EALb,GACZ,GAAgC,MAC/B,EAAoB,GAAU,GAAO,EAAc,OAAO,GAC5D,CAAC,CAEoC,GAAQ,CAAe,GACxD,IAAS,EAAmB,GAC5B,EAAE,qBAAkB,iBAAc,sBAAmB,MAAM,MAAiB,GAE5E,IAAe,EAA6C,IAAI,GAEhE,IAAiB,EAAuB,IAAI,GAE5C,IAAkB,EAAsB,IAAI,GAC5C,IAAc,EAAO,EAAK,GAC1B,CAAC,GAAQ,KAAa,EAAoC,IAAI,GAE9D,IAAa,EAAO,CAAO;CACjC,E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;EAAW;EAAkB;CAAY,CAAC,GAElE,IAAM,QAAkB;EAI5B,AAHA,EAAS,EAAE,MAAM,MAAM,CAAC,GACxB,EAAa,GACT,EAAe,YAAY,QAAM,EAAa,EAAe,OAAO,GACxE,EAAe,UAAU;CAC3B,GAAG,CAAC,GAAc,CAAY,CAAC,GAEzB,IAAa,QAAkB;EACnC,EAAS;GAAE,MAAM;GAAQ,OAAO,CAAC,EAAW,QAAQ;EAAM,CAAC;CAC7D,GAAG,CAAC,CAAC;CAWL,OAPA,cACc;EACV,AAAI,EAAe,YAAY,QAAM,EAAa,EAAe,OAAO;CAC1E,GACA,CAAC,CAAY,CACf,GAEO,SACE;EACL;EAEA;EAEA,WAAW,EAAM;EAEjB,QAAQ,EAAQ,UAAU,UAAU,EAAQ,UAAU;EAEtD,WAAW,EAAM,eAAe,CAAC,EAAO;EACxC;EACA;EACA;EACA;CACF,IACA;EAAC;EAAS;EAAQ,EAAM;EAAa,EAAM;EAAa,EAAO;EAAW;EAAO;EAAK;EAAY;CAAS,CAC7G;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assistant.js","names":[],"sources":["../../src/types/assistant.ts"],"sourcesContent":["/**\n * AI Assistant types.\n *\n * Defines the data model for the right-pane AI assistant panel.\n * Interface shapes align with aiApi.ts (AISession, AISessionLog), which is\n * the real workspace gateway backed assistant contract.\n */\n\nimport { ASSISTANT_USECASE_CONFIG, type AssistantUsecaseId } from '@/config/assistantUsecases';\nimport type { AssistantMessageAttachment } from '@/utils/assistantAttachments';\n\nexport type AssistantMode = AssistantUsecaseId;\n\nexport type AssistantSandboxStatus = 'none' | 'provisioning' | 'running' | 'stopping' | 'error';\n\nexport type AssistantConversationStatus = 'idle' | 'provisioning' | 'connecting' | 'streaming' | 'complete' | 'error';\n\nexport interface AssistantArtifact {\n name: string;\n path: string;\n type: 'file' | 'directory';\n size: number;\n downloadPath?: string;\n}\n\nexport interface AssistantMessageMetadata {\n artifacts?: AssistantArtifact[];\n mode?: AssistantMode;\n sandboxId?: string;\n sessionId?: string;\n /**\n * Files the user attached to this turn. Deliberately the SLIM descriptor —\n * conversations are persisted to localStorage, so preview data URLs and\n * inlined text content must never land here (see AssistantMessageAttachment).\n */\n attachments?: AssistantMessageAttachment[];\n /**\n * The language this turn was generated under (BOFF-7108), as an assistant\n * language code.\n *\n * Fixed at send time, because it is a property of the TURN and not of the\n * current preference. `resolveSpeechLocale` cannot tell English from Spanish\n * or French — they share a script — so it falls back to whatever language is\n * selected NOW. Without this, a French reply starts being read by a Spanish\n * voice the moment the user switches, even with the right voice installed.\n */\n lang?: string;\n [key: string]: unknown;\n}\n\nexport interface Message {\n id: string;\n role: 'user' | 'assistant' | 'system';\n content: string;\n timestamp: string;\n tokens?: { input: number; output: number };\n metadata?: AssistantMessageMetadata;\n}\n\nexport interface Conversation {\n id: string;\n title: string;\n mode: AssistantMode;\n messages: Message[];\n createdAt: string;\n updatedAt: string;\n /** Backend session ID for this conversation */\n backendSessionId?: string | null;\n}\n\nexport interface AssistantSandboxRuntime {\n sandboxId: string;\n status: AssistantSandboxStatus;\n}\n\nexport interface AssistantConversationProcessing {\n status: AssistantConversationStatus;\n messageId: string | null;\n error?: string | null;\n updatedAt: string;\n}\n\nexport interface AssistantModeConfig {\n id: AssistantMode;\n label: string;\n description: string;\n suggestions: readonly string[];\n /** Only offered to a global Owner/Admin (see useAssistantApiAccess). */\n requiresAdmin?: boolean;\n /** Executes mutations on live data → triggers the confirm-before-mutate guard. */\n writeCapable?: boolean;\n}\n\nexport const ASSISTANT_MODES: AssistantModeConfig[] = [...ASSISTANT_USECASE_CONFIG];\n"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"assistant.js","names":[],"sources":["../../src/types/assistant.ts"],"sourcesContent":["/**\n * AI Assistant types.\n *\n * Defines the data model for the right-pane AI assistant panel.\n * Interface shapes align with aiApi.ts (AISession, AISessionLog), which is\n * the real workspace gateway backed assistant contract.\n */\n\nimport { ASSISTANT_USECASE_CONFIG, type AssistantUsecaseId } from '@/config/assistantUsecases';\nimport type { AssistantMessageAttachment } from '@/utils/assistantAttachments';\n\nexport type AssistantMode = AssistantUsecaseId;\n\nexport type AssistantSandboxStatus = 'none' | 'provisioning' | 'running' | 'stopping' | 'error';\n\nexport type AssistantConversationStatus = 'idle' | 'provisioning' | 'connecting' | 'streaming' | 'complete' | 'error';\n\nexport interface AssistantArtifact {\n name: string;\n path: string;\n type: 'file' | 'directory';\n size: number;\n downloadPath?: string;\n}\n\nexport interface AssistantMessageMetadata {\n artifacts?: AssistantArtifact[];\n mode?: AssistantMode;\n sandboxId?: string;\n sessionId?: string;\n /**\n * Files the user attached to this turn. Deliberately the SLIM descriptor —\n * conversations are persisted to localStorage, so preview data URLs and\n * inlined text content must never land here (see AssistantMessageAttachment).\n */\n attachments?: AssistantMessageAttachment[];\n /**\n * The language this turn was generated under (BOFF-7108), as an assistant\n * language code.\n *\n * Fixed at send time, because it is a property of the TURN and not of the\n * current preference. `resolveSpeechLocale` cannot tell English from Spanish\n * or French — they share a script — so it falls back to whatever language is\n * selected NOW. Without this, a French reply starts being read by a Spanish\n * voice the moment the user switches, even with the right voice installed.\n */\n lang?: string;\n /**\n * This turn happened inside a live VOICE session, not in the chat panel.\n *\n * ★ The two surfaces share one conversation and one backend session — voice\n * was built as an overlay over the chat thread, so `submitVoiceTurn` calls\n * the same `handleSend` the composer does. Without a marker there is no way\n * to tell a spoken turn from a typed one once it is in the store, and every\n * voice exchange therefore appeared in the normal chat: the operator's own\n * report, \"I see the same chat in the normal conversation tab, both are\n * separate, don't confuse\".\n *\n * Stamped at send time and persisted, so the distinction survives a reload —\n * the chat transcript is never rehydrated from the backend, so the store is\n * the only source of truth for what the panel shows.\n */\n voice?: boolean;\n [key: string]: unknown;\n}\n\nexport interface Message {\n id: string;\n role: 'user' | 'assistant' | 'system';\n content: string;\n timestamp: string;\n tokens?: { input: number; output: number };\n metadata?: AssistantMessageMetadata;\n}\n\nexport interface Conversation {\n id: string;\n title: string;\n mode: AssistantMode;\n messages: Message[];\n createdAt: string;\n updatedAt: string;\n /** Backend session ID for this conversation */\n backendSessionId?: string | null;\n}\n\nexport interface AssistantSandboxRuntime {\n sandboxId: string;\n status: AssistantSandboxStatus;\n}\n\nexport interface AssistantConversationProcessing {\n status: AssistantConversationStatus;\n messageId: string | null;\n error?: string | null;\n updatedAt: string;\n}\n\nexport interface AssistantModeConfig {\n id: AssistantMode;\n label: string;\n description: string;\n suggestions: readonly string[];\n /** Only offered to a global Owner/Admin (see useAssistantApiAccess). */\n requiresAdmin?: boolean;\n /** Executes mutations on live data → triggers the confirm-before-mutate guard. */\n writeCapable?: boolean;\n}\n\nexport const ASSISTANT_MODES: AssistantModeConfig[] = [...ASSISTANT_USECASE_CONFIG];\n"],"mappings":";;AA6GA,IAAa,IAAyC,CAAC,GAAG,CAAwB"}
|
|
@@ -12,19 +12,29 @@ var e = "--- User request ---", t = [
|
|
|
12
12
|
"Errors cluster on English technical terms, product and crop names, and numbers spoken inside a sentence in another language.",
|
|
13
13
|
"Read the message for INTENT rather than literally: where a word is clearly a recognition error, infer what was meant from the agricultural context instead of answering the garbled word.",
|
|
14
14
|
"But do NOT guess when a mis-heard word would change what is being asked — a crop, a chemical, a quantity or a unit. Ask one short clarifying question instead. A wrong dose is far worse than an extra question."
|
|
15
|
+
].join("\n"), r = [
|
|
16
|
+
"Your answer will be SPOKEN ALOUD and shown as a live caption, not read as a document.",
|
|
17
|
+
"Write plain conversational sentences. Use NO markdown whatsoever: no #, ##, ###, no **bold**, no bullet or numbered lists, no tables, no code fences.",
|
|
18
|
+
"Keep it SHORT — normally one to four sentences. The listener cannot skim, so a long answer is worse than an incomplete one.",
|
|
19
|
+
"If the full answer is genuinely long, give the useful part first and offer to go deeper, rather than listing every option.",
|
|
20
|
+
"Speak numbers, units and quantities the way a person says them."
|
|
15
21
|
].join("\n");
|
|
16
|
-
function
|
|
22
|
+
function i(e, t = !1) {
|
|
17
23
|
return [
|
|
18
24
|
`Answer in ${e}.`,
|
|
19
25
|
t ? `The user has chosen ${e} deliberately: answer in it even when their message is written in another language.` : "If the user writes in a different language, answer in THAT language instead — what they wrote in always wins.",
|
|
20
26
|
"Your documentation and tool output are in English: translate what you quote from them rather than switching language."
|
|
21
27
|
].join("\n");
|
|
22
28
|
}
|
|
23
|
-
function
|
|
24
|
-
let
|
|
25
|
-
|
|
29
|
+
function a(a, o, s, c = !1, l = !1) {
|
|
30
|
+
let u = [
|
|
31
|
+
s ? i(s, c) : "",
|
|
32
|
+
l ? n : "",
|
|
33
|
+
l ? r : ""
|
|
34
|
+
].filter(Boolean).join("\n\n"), d = u ? `${u}\n\n` : "";
|
|
35
|
+
return a === "api-calls" ? `${d}${t}\n${o}` : d ? `${d}${e}\n${o}` : o;
|
|
26
36
|
}
|
|
27
37
|
//#endregion
|
|
28
|
-
export {
|
|
38
|
+
export { a as buildPromptForMode };
|
|
29
39
|
|
|
30
40
|
//# sourceMappingURL=assistantPrompt.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assistantPrompt.js","names":[],"sources":["../../src/utils/assistantPrompt.ts"],"sourcesContent":["/**\n * Soft confirm-before-mutate guardrail for the assistant's api-calls (write)\n * mode. The in-sandbox agent executes mutations autonomously — there is no hard\n * server-side confirmation — so we prepend a describe-and-confirm instruction to\n * the user's TURN (not the session system prompt, which would clobber the\n * agent's api-calls behaviour). This is ADVISORY; the dependable guard is the\n * host-side consent dialog + the admin gate. Only the agent receives the\n * prepended text — the user-facing message bubble keeps the raw content.\n */\n\nimport type { AssistantMode } from '@/types/assistant';\n\n/**\n * Marks where our instructions stop and the user's words begin. Exactly one may\n * exist in a prompt, and it must be last — see `buildPromptForMode`.\n */\nexport const USER_REQUEST_DELIMITER = '--- User request ---';\n\nexport const API_CALLS_CONFIRM_PREAMBLE = [\n \"You are in api-calls mode for HealthyBowl and can run GraphQL queries and mutations on the user's behalf.\",\n 'Before performing ANY write (create, update, delete — any mutation):',\n '1. State exactly what you are about to change (entity, fields, and values).',\n '2. Ask the user to confirm, and WAIT for an explicit \"yes\"/\"confirm\" before executing it.',\n 'Read-only queries may run without confirmation. Confirm each write separately; never batch mutations behind a single confirmation.',\n '',\n USER_REQUEST_DELIMITER,\n].join('\\n');\n\n/**\n * Ask for the reply in the user's language (BOFF-7107).\n *\n * Nothing else does. The sandbox system prompt carries no language instruction,\n * the grounding documentation is entirely in English, and the persona insists on\n * grounding in it — so every force in the session pushes the answer towards\n * English regardless of what the user wrote. The model's tendency to mirror the\n * input is the only thing resisting that, and it is being outvoted.\n *\n * Three deliberate choices:\n *\n * - **The user's own language wins over the UI language.** The chrome being in\n * English says nothing about the person typing Tamil into it; treating the\n * locale as an instruction rather than a default would be the actual bug.\n * - **Translate the docs, do not switch to their language.** This is the clause\n * that matters. Without it a grounded answer drifts back to English mid-reply\n * simply because the source material is English.\n * - **Prepended per TURN, not sent as `system`.** The transport's `system` field\n * REPLACES the whole mode prompt, which would silently delete the docs and\n * api-calls instructions along with it.\n */\n/**\n * The instruction lines only — deliberately WITHOUT the delimiter.\n *\n * The delimiter marks where our instructions stop and the user's words begin, so\n * exactly one may exist and it must be last. Emitting it here too put a second\n * one mid-prompt, which left the api-calls safety instructions sitting *after* a\n * \"User request\" marker — i.e. presented to the model as though the user had\n * written them. `buildPromptForMode` owns placing it, once.\n */\n/**\n * Told to the model when the turn was SPOKEN rather than typed.\n *\n * Speech recognition does not fail uniformly — it fails on specific words, and\n * the ones it fails on here are predictable: English technical terms, product\n * and crop names, and numbers spoken inside an Indic sentence. A recogniser set\n * to `ta-IN` has no good model for \"urea\", \"pH\" or \"NPK\", so a Tamil sentence\n * comes back mostly right with a few words wrong. That is exactly the report:\n * \"some word some times\".\n *\n * The model is far better placed to repair that than the recogniser is, because\n * it has the farming context — but only if it is TOLD the text was dictated.\n * Otherwise it answers the garbled word literally, which is what makes the\n * assistant look like it misunderstood.\n *\n * ★ The refusal to guess is the important half. Charitable interpretation is\n * right for a mangled verb and dangerous for a mangled QUANTITY: this is\n * agriculture, and a dose or a unit that the recogniser mis-heard must be asked\n * about, not inferred. One extra question costs a few seconds; a wrong dose\n * costs a crop.\n */\nconst DICTATION_PREAMBLE = [\n 'This message was DICTATED using speech recognition, so some words may be mis-heard.',\n 'Errors cluster on English technical terms, product and crop names, and numbers spoken inside a sentence in another language.',\n 'Read the message for INTENT rather than literally: where a word is clearly a recognition error, infer what was meant from the agricultural context instead of answering the garbled word.',\n 'But do NOT guess when a mis-heard word would change what is being asked — a crop, a chemical, a quantity or a unit. Ask one short clarifying question instead. A wrong dose is far worse than an extra question.',\n].join('\\n');\n\nexport function buildLanguagePreamble(languageName: string, isExplicitChoice = false): string {\n return [\n `Answer in ${languageName}.`,\n // The mirror clause is right for a DEFAULT and wrong for a CHOICE.\n //\n // Derived from the interface language it is only a guess, and the language\n // the user actually wrote in is better evidence. But once they have picked a\n // language deliberately, \"what they wrote in wins\" silently overrides them —\n // and it does so hardest for people who TYPE, since a typed English question\n // would come back in English no matter what they selected. That makes the\n // preference inert for exactly the users who cannot dictate.\n isExplicitChoice\n ? `The user has chosen ${languageName} deliberately: answer in it even when their message is written in another language.`\n : 'If the user writes in a different language, answer in THAT language instead — what they wrote in always wins.',\n 'Your documentation and tool output are in English: translate what you quote from them rather than switching language.',\n ].join('\\n');\n}\n\n/**\n * `languageName` is the human name of the user's language (\"Tamil\"), not a code:\n * a code invites the model to answer *about* the tag instead of *in* it.\n * Omitted (or empty) leaves the prompt untouched, so a caller without locale\n * context behaves exactly as before.\n *\n * Order is load-bearing: instructions, then the delimiter, then the user's text.\n * The language preamble goes FIRST so the api-calls preamble keeps its own\n * delimiter adjacent to the content it introduces.\n */\nexport function buildPromptForMode(\n mode: AssistantMode,\n content: string,\n languageName?: string,\n isExplicitChoice = false,\n dictated = false\n): string {\n // Dictation goes AFTER the language lines and before the delimiter: it is an\n // instruction about the user's text, so it belongs with the instructions, not\n // inside them. Defaults to false, so every typed turn is byte-identical to\n // before — the composer's own dictation is excluded deliberately, because the\n // user can read and edit that text before sending it.\n const preamble = [\n languageName ? buildLanguagePreamble(languageName, isExplicitChoice) : '',\n dictated ? DICTATION_PREAMBLE : '',\n ]\n .filter(Boolean)\n .join('\\n\\n');\n const language = preamble ? `${preamble}\\n\\n` : '';\n if (mode === 'api-calls') return `${language}${API_CALLS_CONFIRM_PREAMBLE}\\n${content}`;\n return language ? `${language}${USER_REQUEST_DELIMITER}\\n${content}` : content;\n}\n"],"mappings":";AAgBA,IAAa,IAAyB,wBAEzB,IAA6B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;AACF,EAAE,KAAK,IAAI,GAqDL,IAAqB;CACzB;CACA;CACA;CACA;AACF,EAAE,KAAK,IAAI;AAEX,SAAgB,EAAsB,GAAsB,IAAmB,IAAe;CAC5F,OAAO;EACL,aAAa,EAAa;EAS1B,IACI,uBAAuB,EAAa,uFACpC;EACJ;CACF,EAAE,KAAK,IAAI;AACb;AAYA,SAAgB,EACd,GACA,GACA,GACA,IAAmB,IACnB,IAAW,IACH;CAMR,IAAM,IAAW,
|
|
1
|
+
{"version":3,"file":"assistantPrompt.js","names":[],"sources":["../../src/utils/assistantPrompt.ts"],"sourcesContent":["/**\n * Soft confirm-before-mutate guardrail for the assistant's api-calls (write)\n * mode. The in-sandbox agent executes mutations autonomously — there is no hard\n * server-side confirmation — so we prepend a describe-and-confirm instruction to\n * the user's TURN (not the session system prompt, which would clobber the\n * agent's api-calls behaviour). This is ADVISORY; the dependable guard is the\n * host-side consent dialog + the admin gate. Only the agent receives the\n * prepended text — the user-facing message bubble keeps the raw content.\n */\n\nimport type { AssistantMode } from '@/types/assistant';\n\n/**\n * Marks where our instructions stop and the user's words begin. Exactly one may\n * exist in a prompt, and it must be last — see `buildPromptForMode`.\n */\nexport const USER_REQUEST_DELIMITER = '--- User request ---';\n\nexport const API_CALLS_CONFIRM_PREAMBLE = [\n \"You are in api-calls mode for HealthyBowl and can run GraphQL queries and mutations on the user's behalf.\",\n 'Before performing ANY write (create, update, delete — any mutation):',\n '1. State exactly what you are about to change (entity, fields, and values).',\n '2. Ask the user to confirm, and WAIT for an explicit \"yes\"/\"confirm\" before executing it.',\n 'Read-only queries may run without confirmation. Confirm each write separately; never batch mutations behind a single confirmation.',\n '',\n USER_REQUEST_DELIMITER,\n].join('\\n');\n\n/**\n * Ask for the reply in the user's language (BOFF-7107).\n *\n * Nothing else does. The sandbox system prompt carries no language instruction,\n * the grounding documentation is entirely in English, and the persona insists on\n * grounding in it — so every force in the session pushes the answer towards\n * English regardless of what the user wrote. The model's tendency to mirror the\n * input is the only thing resisting that, and it is being outvoted.\n *\n * Three deliberate choices:\n *\n * - **The user's own language wins over the UI language.** The chrome being in\n * English says nothing about the person typing Tamil into it; treating the\n * locale as an instruction rather than a default would be the actual bug.\n * - **Translate the docs, do not switch to their language.** This is the clause\n * that matters. Without it a grounded answer drifts back to English mid-reply\n * simply because the source material is English.\n * - **Prepended per TURN, not sent as `system`.** The transport's `system` field\n * REPLACES the whole mode prompt, which would silently delete the docs and\n * api-calls instructions along with it.\n */\n/**\n * The instruction lines only — deliberately WITHOUT the delimiter.\n *\n * The delimiter marks where our instructions stop and the user's words begin, so\n * exactly one may exist and it must be last. Emitting it here too put a second\n * one mid-prompt, which left the api-calls safety instructions sitting *after* a\n * \"User request\" marker — i.e. presented to the model as though the user had\n * written them. `buildPromptForMode` owns placing it, once.\n */\n/**\n * Told to the model when the turn was SPOKEN rather than typed.\n *\n * Speech recognition does not fail uniformly — it fails on specific words, and\n * the ones it fails on here are predictable: English technical terms, product\n * and crop names, and numbers spoken inside an Indic sentence. A recogniser set\n * to `ta-IN` has no good model for \"urea\", \"pH\" or \"NPK\", so a Tamil sentence\n * comes back mostly right with a few words wrong. That is exactly the report:\n * \"some word some times\".\n *\n * The model is far better placed to repair that than the recogniser is, because\n * it has the farming context — but only if it is TOLD the text was dictated.\n * Otherwise it answers the garbled word literally, which is what makes the\n * assistant look like it misunderstood.\n *\n * ★ The refusal to guess is the important half. Charitable interpretation is\n * right for a mangled verb and dangerous for a mangled QUANTITY: this is\n * agriculture, and a dose or a unit that the recogniser mis-heard must be asked\n * about, not inferred. One extra question costs a few seconds; a wrong dose\n * costs a crop.\n */\nconst DICTATION_PREAMBLE = [\n 'This message was DICTATED using speech recognition, so some words may be mis-heard.',\n 'Errors cluster on English technical terms, product and crop names, and numbers spoken inside a sentence in another language.',\n 'Read the message for INTENT rather than literally: where a word is clearly a recognition error, infer what was meant from the agricultural context instead of answering the garbled word.',\n 'But do NOT guess when a mis-heard word would change what is being asked — a crop, a chemical, a quantity or a unit. Ask one short clarifying question instead. A wrong dose is far worse than an extra question.',\n].join('\\n');\n\n/**\n * Told to the model when its answer will be SPOKEN ALOUD, not read.\n *\n * The assistant was never told this, so it replied the way it replies in chat:\n * documentation-style markdown with `##` headings, `**bold**` and long\n * enumerated sections. In the chat panel that renders correctly. In the voice\n * panel it is read aloud AND shown as a caption, where the syntax is literal\n * and the length is unusable — the operator screenshotted a live session whose\n * caption was a wall of \"### **Budget Planning Features:**\".\n *\n * ★ This is the fix at SOURCE. Stripping markdown at render time is a\n * necessary backstop, but it cannot shorten a 500-word answer that was never\n * meant to be listened to. A spoken reply has to be short because the listener\n * cannot skim it.\n */\nconst VOICE_REPLY_PREAMBLE = [\n 'Your answer will be SPOKEN ALOUD and shown as a live caption, not read as a document.',\n 'Write plain conversational sentences. Use NO markdown whatsoever: no #, ##, ###, no **bold**, no bullet or numbered lists, no tables, no code fences.',\n 'Keep it SHORT — normally one to four sentences. The listener cannot skim, so a long answer is worse than an incomplete one.',\n 'If the full answer is genuinely long, give the useful part first and offer to go deeper, rather than listing every option.',\n 'Speak numbers, units and quantities the way a person says them.',\n].join('\\n');\n\nexport function buildLanguagePreamble(languageName: string, isExplicitChoice = false): string {\n return [\n `Answer in ${languageName}.`,\n // The mirror clause is right for a DEFAULT and wrong for a CHOICE.\n //\n // Derived from the interface language it is only a guess, and the language\n // the user actually wrote in is better evidence. But once they have picked a\n // language deliberately, \"what they wrote in wins\" silently overrides them —\n // and it does so hardest for people who TYPE, since a typed English question\n // would come back in English no matter what they selected. That makes the\n // preference inert for exactly the users who cannot dictate.\n isExplicitChoice\n ? `The user has chosen ${languageName} deliberately: answer in it even when their message is written in another language.`\n : 'If the user writes in a different language, answer in THAT language instead — what they wrote in always wins.',\n 'Your documentation and tool output are in English: translate what you quote from them rather than switching language.',\n ].join('\\n');\n}\n\n/**\n * `languageName` is the human name of the user's language (\"Tamil\"), not a code:\n * a code invites the model to answer *about* the tag instead of *in* it.\n * Omitted (or empty) leaves the prompt untouched, so a caller without locale\n * context behaves exactly as before.\n *\n * Order is load-bearing: instructions, then the delimiter, then the user's text.\n * The language preamble goes FIRST so the api-calls preamble keeps its own\n * delimiter adjacent to the content it introduces.\n */\nexport function buildPromptForMode(\n mode: AssistantMode,\n content: string,\n languageName?: string,\n isExplicitChoice = false,\n dictated = false\n): string {\n // Dictation goes AFTER the language lines and before the delimiter: it is an\n // instruction about the user's text, so it belongs with the instructions, not\n // inside them. Defaults to false, so every typed turn is byte-identical to\n // before — the composer's own dictation is excluded deliberately, because the\n // user can read and edit that text before sending it.\n const preamble = [\n languageName ? buildLanguagePreamble(languageName, isExplicitChoice) : '',\n dictated ? DICTATION_PREAMBLE : '',\n // A dictated turn is a SPOKEN conversation, so the reply is spoken too.\n dictated ? VOICE_REPLY_PREAMBLE : '',\n ]\n .filter(Boolean)\n .join('\\n\\n');\n const language = preamble ? `${preamble}\\n\\n` : '';\n if (mode === 'api-calls') return `${language}${API_CALLS_CONFIRM_PREAMBLE}\\n${content}`;\n return language ? `${language}${USER_REQUEST_DELIMITER}\\n${content}` : content;\n}\n"],"mappings":";AAgBA,IAAa,IAAyB,wBAEzB,IAA6B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;AACF,EAAE,KAAK,IAAI,GAqDL,IAAqB;CACzB;CACA;CACA;CACA;AACF,EAAE,KAAK,IAAI,GAiBL,IAAuB;CAC3B;CACA;CACA;CACA;CACA;AACF,EAAE,KAAK,IAAI;AAEX,SAAgB,EAAsB,GAAsB,IAAmB,IAAe;CAC5F,OAAO;EACL,aAAa,EAAa;EAS1B,IACI,uBAAuB,EAAa,uFACpC;EACJ;CACF,EAAE,KAAK,IAAI;AACb;AAYA,SAAgB,EACd,GACA,GACA,GACA,IAAmB,IACnB,IAAW,IACH;CAMR,IAAM,IAAW;EACf,IAAe,EAAsB,GAAc,CAAgB,IAAI;EACvE,IAAW,IAAqB;EAEhC,IAAW,IAAuB;CACpC,EACG,OAAO,OAAO,EACd,KAAK,MAAM,GACR,IAAW,IAAW,GAAG,EAAS,QAAQ;CAEhD,OADI,MAAS,cAAoB,GAAG,IAAW,EAA2B,IAAI,MACvE,IAAW,GAAG,IAAW,EAAuB,IAAI,MAAY;AACzE"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/utils/voiceTurnVisibility.ts
|
|
2
|
+
function e(e) {
|
|
3
|
+
return e.metadata?.voice === !0;
|
|
4
|
+
}
|
|
5
|
+
function t(t) {
|
|
6
|
+
return t.filter((t) => !e(t));
|
|
7
|
+
}
|
|
8
|
+
function n(t) {
|
|
9
|
+
return t.filter(e);
|
|
10
|
+
}
|
|
11
|
+
//#endregion
|
|
12
|
+
export { t as chatTurns, n as voiceTurnsOnly };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=voiceTurnVisibility.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"voiceTurnVisibility.js","names":[],"sources":["../../src/utils/voiceTurnVisibility.ts"],"sourcesContent":["/**\n * Which surface does a turn belong to?\n *\n * Voice and chat share ONE conversation: the live session was built as an\n * overlay over the chat thread, so `submitVoiceTurn` calls the same `handleSend`\n * the composer does and both write into the same persisted `messages` array.\n * That is why every spoken exchange appeared in the typed thread, and why the\n * voice panel painted the last six messages of the whole conversation —\n * including typed replies full of `##` and `**`, which it renders as literal\n * text.\n *\n * One marker fixes both directions:\n * - the chat panel hides turns that happened in voice\n * - the voice panel shows ONLY turns that happened in voice\n *\n * ★ Deliberately a display split, not separate persistence. It survives a\n * reload because the chat transcript is never rehydrated from the backend — the\n * store is the only source of truth for what either panel shows. The backend\n * session is still shared, so the model keeps full context of the conversation\n * across both surfaces, which is what makes \"carry on where we left off\" work.\n * Genuinely separate backend sessions are a larger change and would cost that.\n */\n\ninterface TurnLike {\n metadata?: ({ voice?: boolean } & Record<string, unknown>) | undefined;\n}\n\n/** True when this turn happened inside a live voice session. */\nexport function isVoiceTurn(message: TurnLike): boolean {\n return message.metadata?.voice === true;\n}\n\n/**\n * The turns the CHAT panel should show: everything that was not spoken.\n *\n * Untagged turns are treated as chat, so every conversation recorded before the\n * marker existed keeps rendering exactly as it did.\n */\nexport function chatTurns<T extends TurnLike>(messages: readonly T[]): T[] {\n return messages.filter((message) => !isVoiceTurn(message));\n}\n\n/**\n * The turns the VOICE panel should show: only what was spoken.\n *\n * This is also what scopes the voice transcript to the session. Previously it\n * took the last six messages of the whole conversation, so opening voice on an\n * existing thread immediately painted typed replies — the wall of raw markdown\n * in the operator's screenshot.\n */\nexport function voiceTurnsOnly<T extends TurnLike>(messages: readonly T[]): T[] {\n return messages.filter(isVoiceTurn);\n}\n"],"mappings":";AA4BA,SAAgB,EAAY,GAA4B;CACtD,OAAO,EAAQ,UAAU,UAAU;AACrC;AAQA,SAAgB,EAA8B,GAA6B;CACzE,OAAO,EAAS,QAAQ,MAAY,CAAC,EAAY,CAAO,CAAC;AAC3D;AAUA,SAAgB,EAAmC,GAA6B;CAC9E,OAAO,EAAS,OAAO,CAAW;AACpC"}
|
package/package.json
CHANGED