@burdenoff/microfe-healthybowl 2026.901.14 → 2026.901.15
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 +199 -198
- package/dist/components/assistant/AssistantChatArea.js.map +1 -1
- package/dist/components/assistant/voice/VoiceCaption.js +1 -1
- package/dist/components/assistant/voice/VoiceCaption.js.map +1 -1
- package/dist/components/assistant/voice/VoiceMiniController.js.map +1 -1
- package/dist/utils/captionText.js +51 -0
- package/dist/utils/captionText.js.map +1 -0
- package/package.json +1 -1
|
@@ -10,56 +10,57 @@ import { buildPromptParts as te, buildPromptWithAttachments as ne, countInlineIm
|
|
|
10
10
|
import { AssistantMessageList as b } from "./AssistantMessageList.js";
|
|
11
11
|
import { AssistantApiCallsConsentDialog as x } from "./AssistantApiCallsConsentDialog.js";
|
|
12
12
|
import { ASSISTANT_MODES as S } from "../../types/assistant.js";
|
|
13
|
-
import { AssistantEmptyState as
|
|
14
|
-
import { AssistantComposer as
|
|
15
|
-
import { AssistantVoiceSession as
|
|
16
|
-
import { useVoiceSession as
|
|
17
|
-
import { useAssistantApiAccess as
|
|
18
|
-
import { isQuotaExhaustedError as
|
|
19
|
-
import { dispatchAssistantQuotaExhausted as
|
|
20
|
-
import { buildPromptForMode as
|
|
21
|
-
import { isMultimodalBodyRejection as
|
|
22
|
-
import { pollDelayMs as
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
30
|
-
import {
|
|
13
|
+
import { AssistantEmptyState as oe } from "./AssistantEmptyState.js";
|
|
14
|
+
import { AssistantComposer as C } from "./composer/AssistantComposer.js";
|
|
15
|
+
import { AssistantVoiceSession as se } from "./voice/AssistantVoiceSession.js";
|
|
16
|
+
import { useVoiceSession as ce } from "../../hooks/useVoiceSession.js";
|
|
17
|
+
import { useAssistantApiAccess as le } from "../../hooks/useAssistantApiAccess.js";
|
|
18
|
+
import { isQuotaExhaustedError as ue } from "../../utils/quotaUtils.js";
|
|
19
|
+
import { dispatchAssistantQuotaExhausted as de, notifyAiCreditsUpdated as fe } from "../../utils/aiCredits.js";
|
|
20
|
+
import { buildPromptForMode as pe } from "../../utils/assistantPrompt.js";
|
|
21
|
+
import { isMultimodalBodyRejection as me, isRecoverableAssistantError as he } from "../../utils/assistantTransportErrors.js";
|
|
22
|
+
import { pollDelayMs as ge } from "../../utils/assistantPollSchedule.js";
|
|
23
|
+
import { toCaptionText as _e } from "../../utils/captionText.js";
|
|
24
|
+
import { chatTurns as ve, voiceMarker as w, voiceTurnsOnly as ye } from "../../utils/voiceTurnVisibility.js";
|
|
25
|
+
import { createReadinessTracker as be } from "../../utils/sandboxReadiness.js";
|
|
26
|
+
import { useCallback as T, useEffect as E, useMemo as D, useRef as O, useState as xe } from "react";
|
|
27
|
+
import { useI18n as Se } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
|
|
28
|
+
import { jsx as k, jsxs as Ce } from "react/jsx-runtime";
|
|
29
|
+
import { useGatewayClient as we } from "@burdenoff/fe-libs/shared/graphql";
|
|
30
|
+
import { useAuthToken as Te } from "@burdenoff/fe-libs/shared/providers/shell";
|
|
31
|
+
import { getAssistantMedia as Ee } from "@burdenoff/fe-libs/shared/assistant";
|
|
31
32
|
//#region src/components/assistant/AssistantChatArea.tsx
|
|
32
|
-
var
|
|
33
|
+
var De = {
|
|
33
34
|
general: 18e4,
|
|
34
35
|
assistant: 18e4,
|
|
35
36
|
"api-calls": 18e4,
|
|
36
37
|
"vibe-plugins": 6e5
|
|
37
|
-
},
|
|
38
|
-
function
|
|
38
|
+
}, Oe = 18e4;
|
|
39
|
+
function ke() {
|
|
39
40
|
return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
|
|
40
41
|
}
|
|
41
|
-
function
|
|
42
|
+
function Ae(e) {
|
|
42
43
|
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]");
|
|
43
44
|
}
|
|
44
|
-
function
|
|
45
|
+
function A(e) {
|
|
45
46
|
return e.info?.time?.created ?? 0;
|
|
46
47
|
}
|
|
47
|
-
function
|
|
48
|
+
function j(e) {
|
|
48
49
|
return (e ?? []).filter((e) => e.type === "text" && typeof e.text == "string").map((e) => e.text?.trim() ?? "").filter(Boolean).join("\n");
|
|
49
50
|
}
|
|
50
|
-
function
|
|
51
|
+
function M(e) {
|
|
51
52
|
return (e ?? []).filter((e) => e.type === "tool" && e.tool).map((e) => {
|
|
52
53
|
let t = e.state?.status ?? "running", n = e.tool ?? "tool";
|
|
53
54
|
return t === "completed" ? `Completed: ${n}` : t === "failed" ? `Failed: ${n}` : `Running: ${n}`;
|
|
54
55
|
});
|
|
55
56
|
}
|
|
56
|
-
function
|
|
57
|
-
let n = e.filter((e) => e.info?.role === "assistant" &&
|
|
57
|
+
function je(e, t) {
|
|
58
|
+
let n = e.filter((e) => e.info?.role === "assistant" && A(e) > t).sort((e, t) => A(e) - A(t));
|
|
58
59
|
if (n.length === 0) return {
|
|
59
60
|
content: "Thinking...",
|
|
60
61
|
done: !1
|
|
61
62
|
};
|
|
62
|
-
let r = n[n.length - 1], i =
|
|
63
|
+
let r = n[n.length - 1], i = j(r.parts), a = Ee(r.parts), o = M(r.parts);
|
|
63
64
|
return {
|
|
64
65
|
content: [
|
|
65
66
|
i,
|
|
@@ -70,7 +71,7 @@ function ke(e, t) {
|
|
|
70
71
|
tokens: r.info?.tokens
|
|
71
72
|
};
|
|
72
73
|
}
|
|
73
|
-
function
|
|
74
|
+
function Me(e) {
|
|
74
75
|
switch (e) {
|
|
75
76
|
case "provisioning": return "Starting assistant environment...";
|
|
76
77
|
case "connecting": return "Connecting to assistant...";
|
|
@@ -78,204 +79,204 @@ function Ae(e) {
|
|
|
78
79
|
default: return "";
|
|
79
80
|
}
|
|
80
81
|
}
|
|
81
|
-
var
|
|
82
|
-
let
|
|
83
|
-
|
|
84
|
-
if (
|
|
85
|
-
let e = S.find((e) => e.id ===
|
|
86
|
-
(!e || e.requiresAdmin && !
|
|
82
|
+
var N = ({ visible: Ee = !0 }) => {
|
|
83
|
+
let j = t(), M = we("workspace"), { getAccessToken: N, getWorkspaceToken: Ne, userId: Pe } = Te(), { locale: P } = Se(), F = e((e) => e.assistantLanguage), Fe = D(() => g(F, P).english, [F, P]), Ie = h(F) !== null, Le = D(() => g(F, P).code, [F, P]), { conversations: Re, activeConversationId: I, mode: L, processingByConversationId: ze, setMode: R, setConversationMode: z, setActiveConversation: Be, createConversation: B, addMessage: Ve, updateMessage: He, patchMessage: V, setConversationProcessing: H, clearConversationProcessing: Ue, setBackendSessionId: We, clearBackendSessionId: U, setSandbox: W, clearSandbox: Ge, acknowledgeApiCalls: Ke } = e(), G = Re.find((e) => e.id === I)?.messages ?? [], K = I ? ze[I] : void 0, q = _(K?.status), qe = q ? K?.messageId ?? null : null, Je = K?.status === "error" ? K.messageId : null, { canUseApiCalls: J, loading: Ye } = le(y()), Xe = D(() => S.filter((e) => !e.requiresAdmin || J), [J]), [Ze, Qe] = xe(null), $e = O({}), Y = O(be()), et = O(/* @__PURE__ */ new Set());
|
|
84
|
+
E(() => {
|
|
85
|
+
if (Ye) return;
|
|
86
|
+
let e = S.find((e) => e.id === L);
|
|
87
|
+
(!e || e.requiresAdmin && !J) && L !== "assistant" && R("assistant");
|
|
87
88
|
}, [
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
89
|
+
L,
|
|
90
|
+
J,
|
|
91
|
+
Ye,
|
|
92
|
+
R
|
|
92
93
|
]);
|
|
93
|
-
let
|
|
94
|
-
|
|
95
|
-
}, [
|
|
94
|
+
let X = T((e, t, n, r) => {
|
|
95
|
+
H(e, n, t, null), r ? He(e, t, r) : He(e, t, Me(n));
|
|
96
|
+
}, [H, He]), tt = T(async (t, n, a, s, c) => {
|
|
96
97
|
let u = e.getState().sandboxesByMode[a]?.sandboxId ?? null, d = async (e) => {
|
|
97
|
-
if (
|
|
98
|
+
if (Y.current.isFresh(e)) return !0;
|
|
98
99
|
try {
|
|
99
|
-
return await p(
|
|
100
|
+
return await p(M, e, s, c, 3e5, (e) => X(t, n, "provisioning", e)), await f(M, e, s, c, 9e4, (e) => X(t, n, "connecting", e)), Y.current.markVerified(e), !0;
|
|
100
101
|
} catch {
|
|
101
|
-
return
|
|
102
|
+
return Y.current.invalidate(e), !1;
|
|
102
103
|
}
|
|
103
104
|
};
|
|
104
|
-
if (u && (
|
|
105
|
-
|
|
106
|
-
let e = await o(
|
|
107
|
-
e && (
|
|
105
|
+
if (u && (W(a, u, "provisioning"), X(t, n, "provisioning", "Reusing assistant environment..."), await d(u) || (W(a, null, "provisioning"), u = null)), !u) {
|
|
106
|
+
X(t, n, "provisioning", "Looking for existing environment...");
|
|
107
|
+
let e = await o(M, s, a, c);
|
|
108
|
+
e && (W(a, e, "provisioning"), X(t, n, "provisioning", "Reusing assistant environment..."), await d(e) ? u = e : W(a, null, "provisioning"));
|
|
108
109
|
}
|
|
109
110
|
if (!u) {
|
|
110
|
-
if (a === "api-calls" && !
|
|
111
|
-
|
|
111
|
+
if (a === "api-calls" && !N()) throw Error("API Calls mode requires an authenticated session. Please sign in again.");
|
|
112
|
+
X(t, n, "provisioning", "Starting assistant environment..."), W(a, null, "provisioning"), u = await r(M, a, s, c), W(a, u, "provisioning"), await p(M, u, s, c, 3e5, (e) => X(t, n, "provisioning", e)), await f(M, u, s, c, 9e4, (e) => X(t, n, "connecting", e));
|
|
112
113
|
}
|
|
113
|
-
|
|
114
|
+
W(a, u, "running");
|
|
114
115
|
let m = e.getState().conversations.find((e) => e.id === t)?.backendSessionId ?? null;
|
|
115
116
|
if (m) try {
|
|
116
|
-
let e = await l(
|
|
117
|
+
let e = await l(M, u, s, m, c);
|
|
117
118
|
if (e.mode !== a) throw Error(`Session mode mismatch: expected ${a}, received ${e.mode}`);
|
|
118
119
|
} catch {
|
|
119
|
-
|
|
120
|
+
U(t), m = null;
|
|
120
121
|
}
|
|
121
|
-
return m || (
|
|
122
|
+
return m || (X(t, n, "connecting", "Preparing session..."), m = (await i(M, u, s, a, c)).sessionId, We(t, m)), {
|
|
122
123
|
sandboxId: u,
|
|
123
124
|
sessionId: m
|
|
124
125
|
};
|
|
125
126
|
}, [
|
|
127
|
+
M,
|
|
128
|
+
U,
|
|
126
129
|
N,
|
|
130
|
+
We,
|
|
127
131
|
W,
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
let f = o.mode, p = L, h = p ? e.getState().conversations.find((e) => e.id === p) : void 0;
|
|
136
|
-
if (p ? h && h.mode !== f && (h.messages.length > 0 || h.backendSessionId) ? p = V(void 0, f) : h && h.mode !== f && B(p, f) : p = V(void 0, f), !p) return;
|
|
137
|
-
Ze.current[p] = r;
|
|
132
|
+
X
|
|
133
|
+
]), Z = T(async (t, r = [], i = {}) => {
|
|
134
|
+
let o = e.getState(), l = o.activeConversationId ?? I;
|
|
135
|
+
if (l && (_(o.processingByConversationId[l]?.status) || et.current.has(l))) return;
|
|
136
|
+
let f = o.mode, p = I, h = p ? e.getState().conversations.find((e) => e.id === p) : void 0;
|
|
137
|
+
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;
|
|
138
|
+
$e.current[p] = r;
|
|
138
139
|
let g = ee(), v = {
|
|
139
|
-
accessToken:
|
|
140
|
-
workspaceToken:
|
|
141
|
-
userId:
|
|
140
|
+
accessToken: N(),
|
|
141
|
+
workspaceToken: Ne(),
|
|
142
|
+
userId: Pe,
|
|
142
143
|
organizationId: y()
|
|
143
144
|
}, b = {
|
|
144
|
-
id:
|
|
145
|
+
id: ke(),
|
|
145
146
|
role: "user",
|
|
146
147
|
content: t,
|
|
147
148
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
148
149
|
metadata: {
|
|
149
150
|
...r.length ? { attachments: r.map(ae) } : {},
|
|
150
|
-
...
|
|
151
|
+
...w(i.dictated)
|
|
151
152
|
}
|
|
152
153
|
};
|
|
153
|
-
|
|
154
|
-
let x =
|
|
155
|
-
|
|
154
|
+
Ve(p, b);
|
|
155
|
+
let x = ke();
|
|
156
|
+
Ve(p, {
|
|
156
157
|
id: x,
|
|
157
158
|
role: "assistant",
|
|
158
159
|
content: "",
|
|
159
160
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
160
161
|
metadata: {
|
|
161
|
-
lang:
|
|
162
|
-
...
|
|
162
|
+
lang: Le,
|
|
163
|
+
...w(i.dictated)
|
|
163
164
|
}
|
|
164
|
-
}),
|
|
165
|
-
let S = (e, t, n, r, a =
|
|
166
|
-
|
|
167
|
-
content:
|
|
165
|
+
}), H(p, "provisioning", x, null);
|
|
166
|
+
let S = (e, t, n, r, a = Le) => {
|
|
167
|
+
V(p, x, {
|
|
168
|
+
content: Ae(e),
|
|
168
169
|
metadata: {
|
|
169
170
|
lang: a,
|
|
170
171
|
...t?.length ? { artifacts: t } : {},
|
|
171
172
|
...t?.length || n || r ? { mode: f } : {},
|
|
172
173
|
...n ? { sessionId: n } : {},
|
|
173
174
|
...r ? { sandboxId: r } : {},
|
|
174
|
-
...
|
|
175
|
+
...w(i.dictated)
|
|
175
176
|
}
|
|
176
177
|
});
|
|
177
|
-
},
|
|
178
|
+
}, oe = async (e = 1) => {
|
|
178
179
|
let o = !1;
|
|
179
180
|
try {
|
|
180
|
-
await n(
|
|
181
|
+
await n(M, g, v);
|
|
181
182
|
} catch (e) {
|
|
182
|
-
if (
|
|
183
|
-
|
|
183
|
+
if (ue(e)) {
|
|
184
|
+
de("ai-credits"), S("You've run out of AI credits for this billing cycle. Upgrade your plan to keep chatting.", void 0, void 0, void 0, "en"), H(p, "error", x, null);
|
|
184
185
|
return;
|
|
185
186
|
}
|
|
186
187
|
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);
|
|
187
188
|
}
|
|
188
189
|
try {
|
|
189
|
-
let { sandboxId: e, sessionId: n } = await
|
|
190
|
-
|
|
191
|
-
let h =
|
|
190
|
+
let { sandboxId: e, sessionId: n } = await tt(p, x, f, g, v), l = (await c(M, e, g, n, v, 50).catch(() => [])).reduce((e, t) => Math.max(e, A(t)), 0);
|
|
191
|
+
X(p, x, "streaming", "Thinking...");
|
|
192
|
+
let h = pe(f, ne(t, r), Fe, Ie, i.dictated === !0), _ = te(h, r), y = ie(_), ee = y > 0, ae = m();
|
|
192
193
|
o = re(r) > y;
|
|
193
194
|
try {
|
|
194
|
-
await d(
|
|
195
|
+
await d(M, e, g, n, h, f, ae, v, _);
|
|
195
196
|
} catch (t) {
|
|
196
|
-
if (!_ || !
|
|
197
|
-
await d(
|
|
197
|
+
if (!_ || !me(t)) throw t;
|
|
198
|
+
await d(M, e, g, n, h, f, ae, v, void 0), o ||= ee;
|
|
198
199
|
}
|
|
199
|
-
let b =
|
|
200
|
-
for (; Date.now() <
|
|
200
|
+
let b = je([], l), oe = Date.now() + (De[f] ?? Oe), C = Date.now(), se = Date.now();
|
|
201
|
+
for (; Date.now() < oe && (b = je(await c(M, e, g, n, v, 50), l), V(p, x, { content: Ae(b.content) }), !b.done);) Date.now() - C > 3e4 && (await a(M, e, g, 600, v).catch(() => void 0), C = Date.now()), await new Promise((e) => setTimeout(e, ge(Date.now() - se)));
|
|
201
202
|
if (!b.done && f !== "vibe-plugins") throw Error("Assistant response timed out while streaming progress");
|
|
202
|
-
let
|
|
203
|
+
let ce = f === "vibe-plugins" ? await s(M, e, g, n, v).catch(() => []) : void 0;
|
|
203
204
|
if (b.done || (b = {
|
|
204
205
|
...b,
|
|
205
206
|
content: `${b.content}\n\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`
|
|
206
207
|
}), o && (b = {
|
|
207
208
|
...b,
|
|
208
|
-
content: `${b.content}\n\n${
|
|
209
|
-
}), S(b.content,
|
|
210
|
-
|
|
209
|
+
content: `${b.content}\n\n${j("healthybowl.assistant.attachments.imagesNotSent", "_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._")}`
|
|
210
|
+
}), S(b.content, ce, n, e), b.tokens) {
|
|
211
|
+
V(p, x, { tokens: b.tokens });
|
|
211
212
|
try {
|
|
212
|
-
await u(
|
|
213
|
+
await u(M, g, n, b.tokens, v), fe();
|
|
213
214
|
} catch {}
|
|
214
215
|
}
|
|
215
|
-
|
|
216
|
+
H(p, "complete", x, null);
|
|
216
217
|
} catch (t) {
|
|
217
|
-
if (e === 1 &&
|
|
218
|
+
if (e === 1 && he(t)) return U(p), Ge(f), oe(2);
|
|
218
219
|
throw t;
|
|
219
220
|
}
|
|
220
|
-
},
|
|
221
|
-
|
|
221
|
+
}, C = p;
|
|
222
|
+
et.current.add(C);
|
|
222
223
|
try {
|
|
223
224
|
if (!g) throw Error("Assistant backend is unavailable without an active workspace context.");
|
|
224
|
-
await
|
|
225
|
+
await oe();
|
|
225
226
|
} catch (t) {
|
|
226
|
-
if (
|
|
227
|
-
|
|
227
|
+
if (Y.current.invalidate(e.getState().sandboxesByMode[f]?.sandboxId ?? null), ue(t)) {
|
|
228
|
+
de("sandbox"), S("You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.", void 0, void 0, void 0, "en"), H(p, "error", x, null);
|
|
228
229
|
return;
|
|
229
230
|
}
|
|
230
231
|
let n = t instanceof Error ? t.message : "Something went wrong";
|
|
231
|
-
|
|
232
|
+
H(p, "error", x, n), V(p, x, {
|
|
232
233
|
content: `Sorry, an error occurred: ${n}. Please try again.`,
|
|
233
234
|
metadata: {
|
|
234
235
|
lang: "en",
|
|
235
|
-
...
|
|
236
|
+
...w(i.dictated)
|
|
236
237
|
}
|
|
237
238
|
});
|
|
238
239
|
} finally {
|
|
239
|
-
|
|
240
|
+
et.current.delete(C);
|
|
240
241
|
}
|
|
241
242
|
}, [
|
|
242
|
-
|
|
243
|
-
|
|
243
|
+
I,
|
|
244
|
+
Ve,
|
|
245
|
+
M,
|
|
246
|
+
U,
|
|
247
|
+
Ge,
|
|
248
|
+
Re,
|
|
249
|
+
B,
|
|
250
|
+
tt,
|
|
244
251
|
N,
|
|
245
|
-
|
|
246
|
-
Ue,
|
|
247
|
-
Ie,
|
|
252
|
+
Ne,
|
|
248
253
|
V,
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
je,
|
|
252
|
-
H,
|
|
253
|
-
Pe,
|
|
254
|
+
Ie,
|
|
255
|
+
Le,
|
|
254
256
|
Fe,
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
e && Q(e.content, t);
|
|
257
|
+
We,
|
|
258
|
+
z,
|
|
259
|
+
H,
|
|
260
|
+
j,
|
|
261
|
+
X,
|
|
262
|
+
Pe
|
|
263
|
+
]), nt = T((e) => {
|
|
264
|
+
Z(e);
|
|
265
|
+
}, [Z]), rt = T(() => {
|
|
266
|
+
let e = [...G].reverse().find((e) => e.role === "user"), t = I ? $e.current[I] ?? [] : [];
|
|
267
|
+
e && Z(e.content, t);
|
|
267
268
|
}, [
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
]),
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
}, [
|
|
275
|
-
let
|
|
276
|
-
if (
|
|
277
|
-
for (let e =
|
|
278
|
-
let t =
|
|
269
|
+
G,
|
|
270
|
+
Z,
|
|
271
|
+
I
|
|
272
|
+
]), it = O(Z);
|
|
273
|
+
E(() => {
|
|
274
|
+
it.current = Z;
|
|
275
|
+
}, [Z]);
|
|
276
|
+
let Q = D(() => {
|
|
277
|
+
if (q) return null;
|
|
278
|
+
for (let e = G.length - 1; e >= 0; --e) {
|
|
279
|
+
let t = G[e];
|
|
279
280
|
if (t?.role !== "assistant") continue;
|
|
280
281
|
let n = v(t.content).text.trim();
|
|
281
282
|
return n ? {
|
|
@@ -284,105 +285,105 @@ var P = ({ visible: we = !0 }) => {
|
|
|
284
285
|
} : null;
|
|
285
286
|
}
|
|
286
287
|
return null;
|
|
287
|
-
}, [
|
|
288
|
+
}, [G, q]), at = D(() => Q ? _e(Q.text) : null, [Q]), ot = D(() => ve(G), [G]), st = D(() => ye(G).filter((e) => e.role === "user" || e.role === "assistant").map((e) => ({
|
|
288
289
|
id: e.id,
|
|
289
290
|
role: e.role,
|
|
290
291
|
text: v(e.content).text.trim()
|
|
291
|
-
})).filter((e) => e.text.length > 0), [
|
|
292
|
-
onSubmit:
|
|
293
|
-
|
|
292
|
+
})).filter((e) => e.text.length > 0), [G]), $ = ce({
|
|
293
|
+
onSubmit: T((e) => {
|
|
294
|
+
it.current(e, [], { dictated: !0 });
|
|
294
295
|
}, []),
|
|
295
|
-
latestReply:
|
|
296
|
-
language: g(
|
|
296
|
+
latestReply: Q,
|
|
297
|
+
language: g(F, P).tag
|
|
297
298
|
});
|
|
298
|
-
|
|
299
|
-
!
|
|
300
|
-
}, [
|
|
299
|
+
E(() => {
|
|
300
|
+
!Ee && $.active && $.end();
|
|
301
|
+
}, [Ee, $]), E(() => {
|
|
301
302
|
let t = e.getState().consumePendingPrompt();
|
|
302
|
-
return t &&
|
|
303
|
+
return t && it.current(t), e.subscribe((t, n) => {
|
|
303
304
|
if (t.pendingPrompt && t.pendingPrompt !== n.pendingPrompt) {
|
|
304
305
|
let t = e.getState().consumePendingPrompt();
|
|
305
|
-
t &&
|
|
306
|
+
t && it.current(t);
|
|
306
307
|
}
|
|
307
308
|
});
|
|
308
309
|
}, []);
|
|
309
|
-
let
|
|
310
|
-
let n =
|
|
310
|
+
let ct = T((t) => {
|
|
311
|
+
let n = I ? e.getState().conversations.find((e) => e.id === I) : void 0;
|
|
311
312
|
if (n && (n.messages.length > 0 || n.backendSessionId)) {
|
|
312
313
|
if (n.mode !== t) {
|
|
313
314
|
let n = e.getState().conversations.find((n) => n.mode === t && n.messages.length === 0 && !n.backendSessionId && !e.getState().processingByConversationId[n.id]);
|
|
314
|
-
n ?
|
|
315
|
+
n ? Be(n.id) : B(void 0, t);
|
|
315
316
|
}
|
|
316
|
-
} else
|
|
317
|
-
|
|
317
|
+
} else I && z(I, t);
|
|
318
|
+
R(t);
|
|
318
319
|
}, [
|
|
319
|
-
|
|
320
|
-
V,
|
|
321
|
-
Re,
|
|
320
|
+
I,
|
|
322
321
|
B,
|
|
323
|
-
|
|
324
|
-
|
|
322
|
+
Be,
|
|
323
|
+
z,
|
|
324
|
+
R
|
|
325
|
+
]), lt = T((t) => {
|
|
325
326
|
if (S.find((e) => e.id === t)?.writeCapable && !e.getState().apiCallsAcknowledged) {
|
|
326
|
-
|
|
327
|
+
Qe(t);
|
|
327
328
|
return;
|
|
328
329
|
}
|
|
329
|
-
|
|
330
|
-
}, [
|
|
331
|
-
let e =
|
|
332
|
-
|
|
330
|
+
ct(t);
|
|
331
|
+
}, [ct]), ut = T(() => {
|
|
332
|
+
let e = Ze;
|
|
333
|
+
Qe(null), Ke(), e && ct(e);
|
|
333
334
|
}, [
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
]),
|
|
338
|
-
|
|
335
|
+
Ze,
|
|
336
|
+
Ke,
|
|
337
|
+
ct
|
|
338
|
+
]), dt = T(() => {
|
|
339
|
+
Qe(null);
|
|
339
340
|
}, []);
|
|
340
|
-
return /* @__PURE__ */
|
|
341
|
+
return /* @__PURE__ */ Ce("div", {
|
|
341
342
|
className: "relative flex flex-1 flex-col overflow-hidden",
|
|
342
343
|
children: [
|
|
343
|
-
/* @__PURE__ */
|
|
344
|
+
/* @__PURE__ */ Ce("div", {
|
|
344
345
|
className: "contents",
|
|
345
346
|
inert: $.active || void 0,
|
|
346
|
-
children: [
|
|
347
|
-
mode:
|
|
348
|
-
onSuggestionClick:
|
|
349
|
-
}) : /* @__PURE__ */
|
|
347
|
+
children: [ot.length === 0 ? /* @__PURE__ */ k(oe, {
|
|
348
|
+
mode: L,
|
|
349
|
+
onSuggestionClick: nt
|
|
350
|
+
}) : /* @__PURE__ */ k("div", {
|
|
350
351
|
className: "flex min-h-0 flex-1 flex-col",
|
|
351
|
-
children: /* @__PURE__ */
|
|
352
|
-
messages:
|
|
353
|
-
streamingMessageId:
|
|
354
|
-
failedMessageId:
|
|
355
|
-
onRetry:
|
|
352
|
+
children: /* @__PURE__ */ k(b, {
|
|
353
|
+
messages: ot,
|
|
354
|
+
streamingMessageId: qe,
|
|
355
|
+
failedMessageId: Je,
|
|
356
|
+
onRetry: rt
|
|
356
357
|
})
|
|
357
|
-
}), /* @__PURE__ */
|
|
358
|
-
onStartVoiceSession: $.available &&
|
|
359
|
-
onSend: (e, t) => void
|
|
360
|
-
disabled:
|
|
361
|
-
placeholder:
|
|
362
|
-
mode:
|
|
363
|
-
availableModes:
|
|
364
|
-
onModeChange:
|
|
358
|
+
}), /* @__PURE__ */ k(C, {
|
|
359
|
+
onStartVoiceSession: $.available && L !== "api-calls" ? $.start : void 0,
|
|
360
|
+
onSend: (e, t) => void Z(e, t),
|
|
361
|
+
disabled: q,
|
|
362
|
+
placeholder: L === "api-calls" ? j("healthybowl.assistant.chatArea.placeholderActions", "What would you like me to do?") : j("healthybowl.assistant.chatArea.placeholderGeneral", "Ask HealthyBowl anything…"),
|
|
363
|
+
mode: L,
|
|
364
|
+
availableModes: Xe,
|
|
365
|
+
onModeChange: lt
|
|
365
366
|
})]
|
|
366
367
|
}),
|
|
367
|
-
$.active && /* @__PURE__ */
|
|
368
|
+
$.active && /* @__PURE__ */ k(se, {
|
|
368
369
|
session: $.session,
|
|
369
370
|
notice: $.notice,
|
|
370
371
|
capturing: $.capturing,
|
|
371
|
-
turns:
|
|
372
|
+
turns: st,
|
|
372
373
|
onInterrupt: $.interrupt,
|
|
373
|
-
spoken:
|
|
374
|
+
spoken: at,
|
|
374
375
|
onToggleMute: $.toggleMute,
|
|
375
376
|
onEnd: $.end
|
|
376
377
|
}),
|
|
377
|
-
/* @__PURE__ */
|
|
378
|
-
open:
|
|
379
|
-
onConfirm:
|
|
380
|
-
onCancel:
|
|
378
|
+
/* @__PURE__ */ k(x, {
|
|
379
|
+
open: Ze !== null,
|
|
380
|
+
onConfirm: ut,
|
|
381
|
+
onCancel: dt
|
|
381
382
|
})
|
|
382
383
|
]
|
|
383
384
|
});
|
|
384
385
|
};
|
|
385
386
|
//#endregion
|
|
386
|
-
export {
|
|
387
|
+
export { N as AssistantChatArea };
|
|
387
388
|
|
|
388
389
|
//# sourceMappingURL=AssistantChatArea.js.map
|
|
@@ -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 { chatTurns, voiceMarker, 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 ...voiceMarker(options.dictated),\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, ...voiceMarker(options.dictated) },\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 //\n // ★ The voice marker was being lost the same way, and it was worse: this\n // runs on every completed turn, and the reply is only handed to the voice\n // session AFTER it runs, so NO spoken answer could ever stay a voice\n // turn. Each one jumped into the typed thread — under a question that\n // had been correctly hidden, so chat showed orphaned answers — and\n // vanished from the transcript drawer at the same instant.\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 ...voiceMarker(options.dictated),\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 // The voice marker still has to survive though — a failed spoken turn\n // belongs to the session that asked. Without it the failure surfaced as\n // a bare \"Sorry, an error occurred\" in the typed thread with no question\n // above it, while the voice session showed nothing at all.\n patchMessage(conversationId, assistantMessageId, {\n content: `Sorry, an error occurred: ${errorMessage}. Please try again.`,\n metadata: { lang: 'en', ...voiceMarker(options.dictated) },\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 .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 capturing={voiceSession.capturing}\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,KAA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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,WAAW,EAAa;IACxB,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 { toCaptionText } from '../../utils/captionText';\nimport { chatTurns, voiceMarker, 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 ...voiceMarker(options.dictated),\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, ...voiceMarker(options.dictated) },\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 //\n // ★ The voice marker was being lost the same way, and it was worse: this\n // runs on every completed turn, and the reply is only handed to the voice\n // session AFTER it runs, so NO spoken answer could ever stay a voice\n // turn. Each one jumped into the typed thread — under a question that\n // had been correctly hidden, so chat showed orphaned answers — and\n // vanished from the transcript drawer at the same instant.\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 ...voiceMarker(options.dictated),\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 // The voice marker still has to survive though — a failed spoken turn\n // belongs to the session that asked. Without it the failure surfaced as\n // a bare \"Sorry, an error occurred\" in the typed thread with no question\n // above it, while the voice session showed nothing at all.\n patchMessage(conversationId, assistantMessageId, {\n content: `Sorry, an error occurred: ${errorMessage}. Please try again.`,\n metadata: { lang: 'en', ...voiceMarker(options.dictated) },\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 same reply, with its Markdown markers removed, for the on-screen caption.\n *\n * ★ Deliberately a SEPARATE memo rather than a change to the one above, whose\n * `text` is not just display: it is the echo reference the recogniser compares\n * against while the answer is being spoken, and the payload of the session's\n * `reply` dispatch. Stripping it there would silently shift what counts as an\n * echo of our own voice. The audio path keeps its own transform\n * (`toSpeakableText`) — the two want genuinely different output, which is why\n * they are two functions and not one.\n */\n const voiceCaption = useMemo(\n () => (latestAssistantReply ? toCaptionText(latestAssistantReply.text) : null),\n [latestAssistantReply]\n );\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 .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 capturing={voiceSession.capturing}\n turns={voiceTurns}\n onInterrupt={voiceSession.interrupt}\n spoken={voiceCaption}\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,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,EAA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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,WAAW,EAAa;IACxB,OAAO;IACP,aAAa,EAAa;IAC1B,QAAQ;IACR,cAAc,EAAa;IAC3B,OAAO,EAAa;GACrB,CAAA;GAGH,kBAAC,GAAD;IACE,MAAM,OAAuB;IAC7B,WAAW;IACX,UAAU;GACX,CAAA;EACE;;AAET"}
|
|
@@ -6,7 +6,7 @@ var t = ({ text: t, role: n, expanded: r, testId: i }) => {
|
|
|
6
6
|
className: "flex w-full justify-center",
|
|
7
7
|
children: /* @__PURE__ */ e("p", {
|
|
8
8
|
className: [
|
|
9
|
-
"w-full text-left",
|
|
9
|
+
"w-full whitespace-pre-wrap text-left",
|
|
10
10
|
r ? "max-w-[34rem]" : "max-w-md",
|
|
11
11
|
a ? "font-semibold text-text-primary" : "font-medium text-text-secondary",
|
|
12
12
|
r ? a ? "text-[clamp(1.5rem,2.6vw,2.125rem)] leading-[1.5]" : "text-[clamp(1.125rem,1.8vw,1.375rem)] leading-[1.5]" : a ? "text-lg leading-relaxed" : "text-base leading-relaxed"
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"VoiceCaption.js","names":[],"sources":["../../../../src/components/assistant/voice/VoiceCaption.tsx"],"sourcesContent":["import type { FC } from 'react';\n\n/**\n * One live caption — either what the user is saying or what the assistant is.\n *\n * Replaces the message-bubble list the voice overlay used to render. That list\n * was the chat transcript squeezed into a modal: bubbles, the whole scrollback,\n * and raw `##`/`**` because it printed the model's markdown as plain text.\n *\n * Three things here are deliberate and were all wrong before:\n *\n * ★ **Left-aligned, not centred.** Centring is fine for one short line and\n * unreadable for four — every line starts in a different place, so the eye has\n * to hunt for each beginning. Tamil/English mixed text makes it worse, because\n * the line lengths vary wildly. The BLOCK is centred on the stage; the text\n * inside it is not.\n *\n * ★ **Responsive type, not one fixed size.** `clamp()` so the same component is\n * legible in a 380px docked panel and from arm's length on a maximised desktop\n * window, without a second component or a transform.\n *\n * ★ **Bounded width.** ~34rem keeps the line length inside the range prose is\n * actually readable at; a caption spanning a 1440px window is one long line the\n * eye cannot track back from.\n */\n\ninterface Props {\n text: string;\n /** Who is speaking. The assistant's caption is the loud one. */\n role: 'user' | 'assistant';\n /** Full-screen rather than docked in the panel. */\n expanded: boolean;\n testId?: string;\n}\n\nexport const VoiceCaption: FC<Props> = ({ text, role, expanded, testId }) => {\n const assistant = role === 'assistant';\n return (\n <div className=\"flex w-full justify-center\">\n <p\n className={[\n // Left-aligned inside a centred block — see above.\n 'w-full text-left',\n expanded ? 'max-w-[34rem]' : 'max-w-md',\n assistant ? 'font-semibold text-text-primary' : 'font-medium text-text-secondary',\n expanded\n ? assistant\n ? 'text-[clamp(1.5rem,2.6vw,2.125rem)] leading-[1.5]'\n : 'text-[clamp(1.125rem,1.8vw,1.375rem)] leading-[1.5]'\n : assistant\n ? 'text-lg leading-relaxed'\n : 'text-base leading-relaxed',\n ].join(' ')}\n // The stage's live region: the caption is what actually changes, so a\n // screen reader should hear it rather than only the status word.\n role=\"status\"\n aria-live=\"polite\"\n data-testid={testId}\n >\n {text}\n </p>\n </div>\n );\n};\n"],"mappings":";;AAmCA,IAAa,KAA2B,EAAE,SAAM,SAAM,aAAU,gBAAa;CAC3E,IAAM,IAAY,MAAS;CAC3B,OACE,kBAAC,OAAD;EAAK,WAAU;YACb,kBAAC,KAAD;GACE,WAAW;
|
|
1
|
+
{"version":3,"file":"VoiceCaption.js","names":[],"sources":["../../../../src/components/assistant/voice/VoiceCaption.tsx"],"sourcesContent":["import type { FC } from 'react';\n\n/**\n * One live caption — either what the user is saying or what the assistant is.\n *\n * Replaces the message-bubble list the voice overlay used to render. That list\n * was the chat transcript squeezed into a modal: bubbles, the whole scrollback,\n * and raw `##`/`**` because it printed the model's markdown as plain text.\n *\n * Three things here are deliberate and were all wrong before:\n *\n * ★ **Left-aligned, not centred.** Centring is fine for one short line and\n * unreadable for four — every line starts in a different place, so the eye has\n * to hunt for each beginning. Tamil/English mixed text makes it worse, because\n * the line lengths vary wildly. The BLOCK is centred on the stage; the text\n * inside it is not.\n *\n * ★ **Responsive type, not one fixed size.** `clamp()` so the same component is\n * legible in a 380px docked panel and from arm's length on a maximised desktop\n * window, without a second component or a transform.\n *\n * ★ **Bounded width.** ~34rem keeps the line length inside the range prose is\n * actually readable at; a caption spanning a 1440px window is one long line the\n * eye cannot track back from.\n */\n\ninterface Props {\n text: string;\n /** Who is speaking. The assistant's caption is the loud one. */\n role: 'user' | 'assistant';\n /** Full-screen rather than docked in the panel. */\n expanded: boolean;\n testId?: string;\n}\n\nexport const VoiceCaption: FC<Props> = ({ text, role, expanded, testId }) => {\n const assistant = role === 'assistant';\n return (\n <div className=\"flex w-full justify-center\">\n <p\n className={[\n // Left-aligned inside a centred block — see above.\n // ★ `toCaptionText` PRESERVES newlines; without pre-wrap they collapse\n // and a multi-paragraph answer renders as one wall of text.\n 'w-full whitespace-pre-wrap text-left',\n expanded ? 'max-w-[34rem]' : 'max-w-md',\n assistant ? 'font-semibold text-text-primary' : 'font-medium text-text-secondary',\n expanded\n ? assistant\n ? 'text-[clamp(1.5rem,2.6vw,2.125rem)] leading-[1.5]'\n : 'text-[clamp(1.125rem,1.8vw,1.375rem)] leading-[1.5]'\n : assistant\n ? 'text-lg leading-relaxed'\n : 'text-base leading-relaxed',\n ].join(' ')}\n // The stage's live region: the caption is what actually changes, so a\n // screen reader should hear it rather than only the status word.\n role=\"status\"\n aria-live=\"polite\"\n data-testid={testId}\n >\n {text}\n </p>\n </div>\n );\n};\n"],"mappings":";;AAmCA,IAAa,KAA2B,EAAE,SAAM,SAAM,aAAU,gBAAa;CAC3E,IAAM,IAAY,MAAS;CAC3B,OACE,kBAAC,OAAD;EAAK,WAAU;YACb,kBAAC,KAAD;GACE,WAAW;IAIT;IACA,IAAW,kBAAkB;IAC7B,IAAY,oCAAoC;IAChD,IACI,IACE,sDACA,wDACF,IACE,4BACA;GACR,EAAE,KAAK,GAAG;GAGV,MAAK;GACL,aAAU;GACV,eAAa;aAEZ;EACA,CAAA;CACA,CAAA;AAET"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"VoiceMiniController.js","names":[],"sources":["../../../../src/components/assistant/voice/VoiceMiniController.tsx"],"sourcesContent":["import type { FC, ReactNode } from 'react';\nimport { VoiceWaveform } from './VoiceWaveform';\nimport { showsAssistantCaption, type VoiceStageState } from '../../../utils/voiceStageState';\n\n/**\n * Docked voice: a compact live controller, not the full stage shrunk.\n *\n * Measured in prod, the docked panel was 554px tall — the expanded composition\n * scaled down, with the same generous vertical rhythm in a space that cannot\n * carry it. Docked is a glance-and-listen surface: state, the last thing said,\n * and the controls. Everything else belongs to the expanded stage or the\n * transcript.\n *\n * ★ Two to three lines of caption, hard-clamped. The point is not to save\n * pixels — it is that a docked panel scrolling a long reply is the chat window\n * this feature exists to stop being. If the user wants the whole answer, they\n * expand or open the transcript.\n *\n * The row is deliberately horizontal: status and caption on the left, controls\n * on the right, so the panel reads as one strip rather than a stack. That is\n * what makes it feel like a controller instead of a small conversation.\n */\n\ninterface Props {\n state: VoiceStageState;\n /** Live user transcript, or the assistant's caption while speaking. */\n caption: string | null;\n statusText: string;\n /** Mic / interrupt control — the same orb, in its compact size. */\n control: ReactNode;\n errorText?: string | null;\n}\n\nexport const VoiceMiniController: FC<Props> = ({ state, caption, statusText, control, errorText = null }) => {\n const assistantSpeaking = showsAssistantCaption(state);\n\n return (\n <div\n className=\"flex min-h-0 w-full flex-1 items-center gap-3 px-4\"\n data-testid=\"assistant-voice-mini\"\n data-state={state}\n >\n <div className=\"flex min-w-0 flex-1 flex-col gap-1.5\">\n <div className=\"flex items-center gap-2\">\n <VoiceWaveform\n active={state === 'listening' || state === 'speaking'}\n tone={state === 'speaking' ? 'speaking' : 'listening'}\n />\n <p className=\"truncate text-xs text-text-muted\" data-testid=\"assistant-voice-status\">\n {statusText}\n </p>\n </div>\n\n {state === 'mic-error' ? (\n <p className=\"line-clamp-2 text-xs text-status-warning\" role=\"alert\" data-testid=\"assistant-voice-mini-error\">\n {errorText}\n </p>\n ) : caption ? (\n <p\n className={[\n // Three lines maximum. Older content scrolls out of existence\n // rather than growing the panel — see the note above.\n 'line-clamp-3 text-left text-sm leading-snug',\n assistantSpeaking ? 'font-semibold text-text-primary' : 'font-medium text-text-secondary',\n ].join(' ')}\n // The live region lives here when docked: this is the element that\n // actually changes.\n role=\"status\"\n aria-live=\"polite\"\n data-testid=\"assistant-voice-caption\"\n >\n {caption}\n </p>\n ) : (\n // Hold two lines so the controls do not shift when speech starts.\n <div className=\"h-9\" aria-hidden=\"true\" />\n )}\n </div>\n\n <div className=\"shrink-0\">{control}</div>\n </div>\n );\n};\n"],"mappings":";;;;AAiCA,IAAa,KAAkC,EAAE,UAAO,YAAS,eAAY,YAAS,eAAY,WAAW;CAC3G,IAAM,IAAoB,EAAsB,CAAK;CAErD,OACE,kBAAC,OAAD;EACE,WAAU;EACV,eAAY;EACZ,cAAY;YAHd,CAKE,kBAAC,OAAD;GAAK,WAAU;aAAf,CACE,kBAAC,OAAD;IAAK,WAAU;cAAf,CACE,kBAAC,GAAD;KACE,QAAQ,MAAU,eAAe,MAAU;KAC3C,MAAM,MAAU,aAAa,aAAa;IAC3C,CAAA,GACD,kBAAC,KAAD;KAAG,WAAU;KAAmC,eAAY;eACzD;IACA,CAAA,CACA;OAEJ,MAAU,cACT,kBAAC,KAAD;IAAG,WAAU;IAA2C,MAAK;IAAQ,eAAY;cAC9E;GACA,CAAA,IACD,IACF,kBAAC,KAAD;IACE,WAAW,
|
|
1
|
+
{"version":3,"file":"VoiceMiniController.js","names":[],"sources":["../../../../src/components/assistant/voice/VoiceMiniController.tsx"],"sourcesContent":["import type { FC, ReactNode } from 'react';\nimport { VoiceWaveform } from './VoiceWaveform';\nimport { showsAssistantCaption, type VoiceStageState } from '../../../utils/voiceStageState';\n\n/**\n * Docked voice: a compact live controller, not the full stage shrunk.\n *\n * Measured in prod, the docked panel was 554px tall — the expanded composition\n * scaled down, with the same generous vertical rhythm in a space that cannot\n * carry it. Docked is a glance-and-listen surface: state, the last thing said,\n * and the controls. Everything else belongs to the expanded stage or the\n * transcript.\n *\n * ★ Two to three lines of caption, hard-clamped. The point is not to save\n * pixels — it is that a docked panel scrolling a long reply is the chat window\n * this feature exists to stop being. If the user wants the whole answer, they\n * expand or open the transcript.\n *\n * The row is deliberately horizontal: status and caption on the left, controls\n * on the right, so the panel reads as one strip rather than a stack. That is\n * what makes it feel like a controller instead of a small conversation.\n */\n\ninterface Props {\n state: VoiceStageState;\n /** Live user transcript, or the assistant's caption while speaking. */\n caption: string | null;\n statusText: string;\n /** Mic / interrupt control — the same orb, in its compact size. */\n control: ReactNode;\n errorText?: string | null;\n}\n\nexport const VoiceMiniController: FC<Props> = ({ state, caption, statusText, control, errorText = null }) => {\n const assistantSpeaking = showsAssistantCaption(state);\n\n return (\n <div\n className=\"flex min-h-0 w-full flex-1 items-center gap-3 px-4\"\n data-testid=\"assistant-voice-mini\"\n data-state={state}\n >\n <div className=\"flex min-w-0 flex-1 flex-col gap-1.5\">\n <div className=\"flex items-center gap-2\">\n <VoiceWaveform\n active={state === 'listening' || state === 'speaking'}\n tone={state === 'speaking' ? 'speaking' : 'listening'}\n />\n <p className=\"truncate text-xs text-text-muted\" data-testid=\"assistant-voice-status\">\n {statusText}\n </p>\n </div>\n\n {state === 'mic-error' ? (\n <p className=\"line-clamp-2 text-xs text-status-warning\" role=\"alert\" data-testid=\"assistant-voice-mini-error\">\n {errorText}\n </p>\n ) : caption ? (\n <p\n className={[\n // Three lines maximum. Older content scrolls out of existence\n // rather than growing the panel — see the note above.\n // ★ Deliberately NO whitespace-pre-wrap here, unlike VoiceCaption.\n // This strip is line-clamp-3, so every preserved newline burns one of\n // the three lines: measured at the strip's real width it cut a\n // 116-character reply to 41 visible characters. Markers are still\n // stripped; the breaks are allowed to collapse on this surface only.\n 'line-clamp-3 text-left text-sm leading-snug',\n assistantSpeaking ? 'font-semibold text-text-primary' : 'font-medium text-text-secondary',\n ].join(' ')}\n // The live region lives here when docked: this is the element that\n // actually changes.\n role=\"status\"\n aria-live=\"polite\"\n data-testid=\"assistant-voice-caption\"\n >\n {caption}\n </p>\n ) : (\n // Hold two lines so the controls do not shift when speech starts.\n <div className=\"h-9\" aria-hidden=\"true\" />\n )}\n </div>\n\n <div className=\"shrink-0\">{control}</div>\n </div>\n );\n};\n"],"mappings":";;;;AAiCA,IAAa,KAAkC,EAAE,UAAO,YAAS,eAAY,YAAS,eAAY,WAAW;CAC3G,IAAM,IAAoB,EAAsB,CAAK;CAErD,OACE,kBAAC,OAAD;EACE,WAAU;EACV,eAAY;EACZ,cAAY;YAHd,CAKE,kBAAC,OAAD;GAAK,WAAU;aAAf,CACE,kBAAC,OAAD;IAAK,WAAU;cAAf,CACE,kBAAC,GAAD;KACE,QAAQ,MAAU,eAAe,MAAU;KAC3C,MAAM,MAAU,aAAa,aAAa;IAC3C,CAAA,GACD,kBAAC,KAAD;KAAG,WAAU;KAAmC,eAAY;eACzD;IACA,CAAA,CACA;OAEJ,MAAU,cACT,kBAAC,KAAD;IAAG,WAAU;IAA2C,MAAK;IAAQ,eAAY;cAC9E;GACA,CAAA,IACD,IACF,kBAAC,KAAD;IACE,WAAW,CAQT,+CACA,IAAoB,oCAAoC,iCAC1D,EAAE,KAAK,GAAG;IAGV,MAAK;IACL,aAAU;IACV,eAAY;cAEX;GACA,CAAA,IAGH,kBAAC,OAAD;IAAK,WAAU;IAAM,eAAY;GAAQ,CAAA,CAExC;MAEL,kBAAC,OAAD;GAAK,WAAU;aAAY;EAAa,CAAA,CACrC;;AAET"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
//#region src/utils/captionText.ts
|
|
2
|
+
var e = "", t = "\\uE000", n = /^[\s:|-]*$/, r = /^\s*([-*_])\s*(?:\1\s*){2,}$/, i = /^\s*=+\s*$/;
|
|
3
|
+
function a(e) {
|
|
4
|
+
return e.includes("|") && e.includes("-") && n.test(e);
|
|
5
|
+
}
|
|
6
|
+
function o(e) {
|
|
7
|
+
let t = /* @__PURE__ */ new Set();
|
|
8
|
+
return e.forEach((n, r) => {
|
|
9
|
+
if (!a(n)) return;
|
|
10
|
+
let i = e[r - 1];
|
|
11
|
+
r > 0 && i !== void 0 && i.includes("|") && t.add(r - 1);
|
|
12
|
+
for (let n = r + 1; n < e.length; n += 1) {
|
|
13
|
+
let r = e[n];
|
|
14
|
+
if (r === void 0 || r.trim() === "" || !r.includes("|")) break;
|
|
15
|
+
t.add(n);
|
|
16
|
+
}
|
|
17
|
+
}), t;
|
|
18
|
+
}
|
|
19
|
+
function s(n, r) {
|
|
20
|
+
let i = (t) => (r.push(t), `${e}${r.length - 1}${e}`);
|
|
21
|
+
return n.replace(/^ {0,3}```[^\n]*\n([\s\S]*?)^ {0,3}```[^\n]*$/gm, (e, t) => i(t.replace(/\n$/, ""))).replace(/^ {0,3}```[^\n]*\n?([\s\S]*)$/m, (e, t) => i(t)).replace(/`([^`\n]+)`/g, (e, t) => i(t)).replace(RegExp(`<((?:https?://|mailto:)[^>\\s${t}]+)>`, "gi"), (e, t) => i(t)).replace(RegExp(`<([^@<>\\s${t}]+@[^@<>\\s${t}]+\\.[^@<>\\s${t}]+)>`, "g"), (e, t) => i(t)).replace(RegExp(`\\b(?:https?://|www\\.)[^\\s<>()\\[\\]${t}]+`, "gi"), (e) => i(e)).replace(/\b[\w.+-]{1,64}@[\w-]{1,63}\.[\w.-]{1,63}\b/g, (e) => i(e));
|
|
22
|
+
}
|
|
23
|
+
function c(t, n) {
|
|
24
|
+
let r = RegExp(`${e}(\\d+)${e}`, "g"), i = t;
|
|
25
|
+
for (let e = 0; e <= n.length; e += 1) {
|
|
26
|
+
let e = i.replace(r, (e, t) => n[Number(t)] ?? "");
|
|
27
|
+
if (e === i) break;
|
|
28
|
+
i = e;
|
|
29
|
+
}
|
|
30
|
+
return i;
|
|
31
|
+
}
|
|
32
|
+
function l(e) {
|
|
33
|
+
return e.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\[([^\]]*)\]\[[^\]]*\]/g, "$1").replace(/(^|[^\w~])~~(\S(?:[^\n]*?\S)?)~~(?=[^\w~]|$)/g, "$1$2").replace(/(^|[^\w*])\*\*(\S(?:[^\n]*?\S)?)\*\*(?=[^\w*]|$)/g, "$1$2").replace(/(^|[^\p{L}\p{N}_])__(\S(?:[^\n]*?\S)?)__(?=[^\p{L}\p{N}_]|$)/gu, "$1$2").replace(/(^|[^\w*])\*(\S(?:[^*\n]*\S)?)\*(?=[^\w*]|$)/g, "$1$2").replace(/(^|[^\p{L}\p{N}_])_(\S(?:[^_\n]*\S)?)_(?=[^\p{L}\p{N}_]|$)/gu, "$1$2");
|
|
34
|
+
}
|
|
35
|
+
function u(e) {
|
|
36
|
+
return e.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((e) => e.trim()).join(" · ");
|
|
37
|
+
}
|
|
38
|
+
function d(t) {
|
|
39
|
+
if (!t) return "";
|
|
40
|
+
let n = [], d = s(t.replace(/\r\n/g, "\n").replace(new RegExp(e, "g"), ""), n).split("\n"), f = o(d), p = [];
|
|
41
|
+
return d.forEach((e, t) => {
|
|
42
|
+
if (a(e) || r.test(e) || i.test(e) && (p[p.length - 1] ?? "").trim() !== "") return;
|
|
43
|
+
let n = e;
|
|
44
|
+
for (; /^\s*>\s?/.test(n);) n = n.replace(/^\s*>\s?/, "");
|
|
45
|
+
n = n.replace(/^\s*#{1,6}\s+/, ""), n = n.replace(/^(\s*)[-*+]\s+/, "$1"), n = n.replace(/^(\s*)\d{1,2}[.)]\s+/, "$1"), f.has(t) && (n = u(n)), p.push(l(n).replace(/\s+$/, ""));
|
|
46
|
+
}), c(p.join("\n").replace(/\n{3,}/g, "\n\n").trim(), n);
|
|
47
|
+
}
|
|
48
|
+
//#endregion
|
|
49
|
+
export { d as toCaptionText };
|
|
50
|
+
|
|
51
|
+
//# sourceMappingURL=captionText.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"captionText.js","names":[],"sources":["../../src/utils/captionText.ts"],"sourcesContent":["/**\n * Markdown → the words, for a caption someone READS.\n *\n * The live voice caption is the one surface where the model's raw Markdown was\n * printed literally: bold stars, hash headings, table pipes, fence backticks.\n * The audio path has been clean for a while (`toSpeakableText`), but that\n * function is the wrong tool here and reusing it would be worse than the bug.\n *\n * ★ `toSpeakableText` is a SCRIPT FOR A VOICE, not a Markdown cleaner. It\n * replaces a table with \"Table with 40 rows and 2 columns\", a fenced block with\n * \"Code block\", a link with the word \"link\", and rewrites `x@y.com` as \"x at y\n * dot com\" — sensible in an earpiece, destructive on a screen where the reader\n * can simply read the thing. Worse, those replacements come from an English\n * default list only localised inside the speech provider, so reusing it would\n * print English chrome inside a Tamil or Hindi caption: the exact\n * mixed-language defect that code exists to prevent.\n *\n * So this strips MARKERS and keeps CONTENT. Every cell value, all code text,\n * bare URLs, email addresses, emoji and punctuation survive verbatim. Nothing\n * is summarised, truncated or annotated: a caption that quietly drops the\n * user's numbers is a worse failure than one showing a stray asterisk. Where\n * this function is unsure, it leaves the text ALONE.\n *\n * ★ Newlines are PRESERVED, which only helps where the element renders them.\n * `VoiceCaption` carries `whitespace-pre-wrap` for exactly that. The mini\n * controller deliberately does NOT: it is `line-clamp-3`, and real newlines\n * each burn one of the three lines — measured at the strip's true width, that\n * cut a 116-character reply to 41 visible characters. Markers still go; the\n * breaks are allowed to collapse on the clamped surface.\n *\n * ★ NO LOOKBEHIND ANYWHERE IN CODE. Safari < 16.4 throws on that assertion\n * class at PARSE time, not match time — one literal takes down the whole chunk\n * on those devices, and this ships to phones. Lookahead is fine; where a\n * leading boundary is needed it is CAPTURED and put back. Same rule as\n * `speakableText.ts`, and `captionText.test.ts` asserts it on the source.\n */\n\n/**\n * Placeholder sentinel. Private Use Area: it cannot occur in a real reply and,\n * unlike NUL, survives ordinary string plumbing without tripping tools.\n * Stripped from input on entry so it can never be forged.\n */\n// Written as an escape, never as the literal character: an invisible Private\n// Use Area glyph in source is unreadable in review and travels badly.\nconst MARK = '\\uE000';\n\n/** Anything a placeholder must never swallow. */\nconst NOT_MARK = '\\\\uE000';\n\n/**\n * A `|`-only rule row (`|---|:--:|`) — the line that makes a table a table.\n *\n * ★ Kept anchored and alternation-free. The earlier `[\\s:|-]*-[\\s:|-]*` had\n * two overlapping stars around a literal, which backtracks quadratically: a\n * 40k-dash line measured 4.8s on this box, and this runs synchronously in a\n * `useMemo` on the render thread while a call is live. The `-`/`|` presence\n * check is done separately by the caller.\n */\nconst TABLE_RULE = /^[\\s:|-]*$/;\n\n/** `---`, `***`, `___` alone on a line. */\nconst THEMATIC_BREAK = /^\\s*([-*_])\\s*(?:\\1\\s*){2,}$/;\n\n/** A setext underline (`===`), which is heading chrome, not content. */\nconst SETEXT_UNDERLINE = /^\\s*=+\\s*$/;\n\n/** True for the rule row beneath a table header. */\nfunction isTableRule(line: string): boolean {\n return line.includes('|') && line.includes('-') && TABLE_RULE.test(line);\n}\n\n/**\n * Which line indices belong to a real table.\n *\n * ★ Gating on \"contains a pipe\" alone rewrote ordinary prose: `grep foo | wc -l`\n * became `grep foo · wc -l`, and `|v| equals 3` lost its bars entirely. A line\n * only counts if a rule row vouches for it — the header immediately above, and\n * the body rows below until the block ends.\n */\nfunction findTableLines(lines: readonly string[]): Set<number> {\n const marked = new Set<number>();\n lines.forEach((line, index) => {\n if (!isTableRule(line)) return;\n const header = lines[index - 1];\n if (index > 0 && header !== undefined && header.includes('|')) marked.add(index - 1);\n for (let next = index + 1; next < lines.length; next += 1) {\n const row = lines[next];\n if (row === undefined || row.trim() === '' || !row.includes('|')) break;\n marked.add(next);\n }\n });\n return marked;\n}\n\n/**\n * Spans that must come through untouched, lifted out before anything else runs.\n *\n * ★ Both fence rules are anchored to a line start. Unanchored, a stray triple\n * backtick mid-sentence — which the assistant writes whenever it explains\n * Markdown — opened a fence whose body was empty, and EVERYTHING after it was\n * deleted. \"Put your SQL between ``` markers\" came out as \"Put your SQL\n * between\". Anchoring also drops the terminated-fence scan from O(n) start\n * positions to O(lines).\n */\nfunction protectSpans(input: string, keep: string[]): string {\n const stash = (value: string): string => {\n keep.push(value);\n return `${MARK}${keep.length - 1}${MARK}`;\n };\n return (\n input\n // A closed fence: drop the fence lines, keep every line between them.\n .replace(/^ {0,3}```[^\\n]*\\n([\\s\\S]*?)^ {0,3}```[^\\n]*$/gm, (_all, body: string) =>\n stash(body.replace(/\\n$/, ''))\n )\n // An unterminated fence still must not print its backticks.\n .replace(/^ {0,3}```[^\\n]*\\n?([\\s\\S]*)$/m, (_all, body: string) => stash(body))\n .replace(/`([^`\\n]+)`/g, (_all, body: string) => stash(body))\n // Autolinks first, so the angle brackets go and the target is protected.\n .replace(new RegExp(`<((?:https?://|mailto:)[^>\\\\s${NOT_MARK}]+)>`, 'gi'), (_all, url: string) => stash(url))\n .replace(\n new RegExp(`<([^@<>\\\\s${NOT_MARK}]+@[^@<>\\\\s${NOT_MARK}]+\\\\.[^@<>\\\\s${NOT_MARK}]+)>`, 'g'),\n (_all, mail: string) => stash(mail)\n )\n // ★ Every class below excludes the sentinel, or a URL rule would swallow\n // a placeholder left by the inline-code rule and print it on screen.\n .replace(new RegExp(`\\\\b(?:https?://|www\\\\.)[^\\\\s<>()\\\\[\\\\]${NOT_MARK}]+`, 'gi'), (url: string) => stash(url))\n // Bounded parts: the unbounded form backtracked for seconds on a long\n // dotted token that never reached an `@`.\n .replace(/\\b[\\w.+-]{1,64}@[\\w-]{1,63}\\.[\\w.-]{1,63}\\b/g, (mail: string) => stash(mail))\n );\n}\n\n/**\n * Put the protected spans back exactly as they were.\n *\n * ★ Looped, not a single pass: a stashed value can itself contain a\n * placeholder (an autolink stashed after the inline-code rule already ran), and\n * one pass would leave a Private Use Area character on screen. Bounded by the\n * stash size, so a self-referential value cannot spin.\n */\nfunction restoreSpans(input: string, keep: string[]): string {\n const pattern = new RegExp(`${MARK}(\\\\d+)${MARK}`, 'g');\n let out = input;\n for (let pass = 0; pass <= keep.length; pass += 1) {\n const next = out.replace(pattern, (_all, index: string) => keep[Number(index)] ?? '');\n if (next === out) break;\n out = next;\n }\n return out;\n}\n\n/**\n * Emphasis, links and images — the inline markers, on one line of prose.\n *\n * ★ Emphasis requires FLANKING: the opener followed by a non-space, the closer\n * preceded by one. Without it `2 * 3 * 4 kg` lost its operators and read\n * `2 3 4 kg` — a silent corruption of exactly the numbers a farm assistant\n * exists to report. The leading boundary is captured, never looked behind.\n *\n * ★ Underscore boundaries are Unicode-aware. `\\w` is ASCII-only, so with it\n * Tamil and Devanagari letters counted as non-word and `நிலம்_வகை` collapsed to\n * `நிலம்வகை` — in the one function written specifically because captions render\n * in those scripts.\n */\nfunction stripInline(line: string): string {\n return (\n line\n // Images before links: `` is a link pattern with a `!` in front.\n .replace(/!\\[([^\\]]*)\\]\\([^)]*\\)/g, '$1')\n .replace(/\\[([^\\]]*)\\]\\([^)]*\\)/g, '$1')\n .replace(/\\[([^\\]]*)\\]\\[[^\\]]*\\]/g, '$1')\n .replace(/(^|[^\\w~])~~(\\S(?:[^\\n]*?\\S)?)~~(?=[^\\w~]|$)/g, '$1$2')\n .replace(/(^|[^\\w*])\\*\\*(\\S(?:[^\\n]*?\\S)?)\\*\\*(?=[^\\w*]|$)/g, '$1$2')\n .replace(/(^|[^\\p{L}\\p{N}_])__(\\S(?:[^\\n]*?\\S)?)__(?=[^\\p{L}\\p{N}_]|$)/gu, '$1$2')\n .replace(/(^|[^\\w*])\\*(\\S(?:[^*\\n]*\\S)?)\\*(?=[^\\w*]|$)/g, '$1$2')\n .replace(/(^|[^\\p{L}\\p{N}_])_(\\S(?:[^_\\n]*\\S)?)_(?=[^\\p{L}\\p{N}_]|$)/gu, '$1$2')\n );\n}\n\n/**\n * Table row → its cells, joined by a separator that reads as prose.\n *\n * ★ Empty cells are KEPT as empty slots. Filtering them out shifted every later\n * value one column left, so a sparse yield table reported January's blank as\n * February's number — confidently wrong, which is worse than obviously broken.\n */\nfunction flattenTableRow(line: string): string {\n return line\n .trim()\n .replace(/^\\|/, '')\n .replace(/\\|$/, '')\n .split('|')\n .map((cell) => cell.trim())\n .join(' · ');\n}\n\n/**\n * Strip Markdown markers for display, keeping all of the content.\n *\n * Safe on plain text: a reply with no Markdown comes back unchanged.\n */\nexport function toCaptionText(markdown: string): string {\n if (!markdown) return '';\n\n const keep: string[] = [];\n // The sentinel is stripped from input so a reply can never forge one.\n const source = markdown.replace(/\\r\\n/g, '\\n').replace(new RegExp(MARK, 'g'), '');\n const lines = protectSpans(source, keep).split('\\n');\n const tableLines = findTableLines(lines);\n const out: string[] = [];\n\n lines.forEach((raw, index) => {\n // A rule row carries no data — it exists only to declare the header above.\n if (isTableRule(raw)) return;\n if (THEMATIC_BREAK.test(raw)) return;\n // `===` under a line of text is heading chrome; a leading one is content.\n if (SETEXT_UNDERLINE.test(raw) && (out[out.length - 1] ?? '').trim() !== '') return;\n\n let line = raw;\n\n // Block markers, outermost first. Blockquotes nest, hence the loop.\n while (/^\\s*>\\s?/.test(line)) line = line.replace(/^\\s*>\\s?/, '');\n line = line.replace(/^\\s*#{1,6}\\s+/, '');\n line = line.replace(/^(\\s*)[-*+]\\s+/, '$1');\n // ★ One or two digits only. Unbounded, this ate a leading YEAR: \"2026. A\n // record harvest\" lost the year while the voice still spoke it.\n line = line.replace(/^(\\s*)\\d{1,2}[.)]\\s+/, '$1');\n\n if (tableLines.has(index)) line = flattenTableRow(line);\n\n out.push(stripInline(line).replace(/\\s+$/, ''));\n });\n\n // ★ Cosmetic passes run BEFORE the stash is restored, so they cannot reach\n // inside a protected span. Applied after, the newline collapse deleted blank\n // lines from inside fenced code and `trim` de-indented its first line.\n // Placeholders contain no newlines, so the collapse still works here.\n return restoreSpans(\n out\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim(),\n keep\n );\n}\n"],"mappings":";AA4CA,IAAM,IAAO,KAGP,IAAW,WAWX,IAAa,cAGb,IAAiB,gCAGjB,IAAmB;AAGzB,SAAS,EAAY,GAAuB;CAC1C,OAAO,EAAK,SAAS,GAAG,KAAK,EAAK,SAAS,GAAG,KAAK,EAAW,KAAK,CAAI;AACzE;AAUA,SAAS,EAAe,GAAuC;CAC7D,IAAM,oBAAS,IAAI,IAAY;CAW/B,OAVA,EAAM,SAAS,GAAM,MAAU;EAC7B,IAAI,CAAC,EAAY,CAAI,GAAG;EACxB,IAAM,IAAS,EAAM,IAAQ;EAC7B,AAAI,IAAQ,KAAK,MAAW,KAAA,KAAa,EAAO,SAAS,GAAG,KAAG,EAAO,IAAI,IAAQ,CAAC;EACnF,KAAK,IAAI,IAAO,IAAQ,GAAG,IAAO,EAAM,QAAQ,KAAQ,GAAG;GACzD,IAAM,IAAM,EAAM;GAClB,IAAI,MAAQ,KAAA,KAAa,EAAI,KAAK,MAAM,MAAM,CAAC,EAAI,SAAS,GAAG,GAAG;GAClE,EAAO,IAAI,CAAI;EACjB;CACF,CAAC,GACM;AACT;AAYA,SAAS,EAAa,GAAe,GAAwB;CAC3D,IAAM,KAAS,OACb,EAAK,KAAK,CAAK,GACR,GAAG,IAAO,EAAK,SAAS,IAAI;CAErC,OACE,EAEG,QAAQ,oDAAoD,GAAM,MACjE,EAAM,EAAK,QAAQ,OAAO,EAAE,CAAC,CAC/B,EAEC,QAAQ,mCAAmC,GAAM,MAAiB,EAAM,CAAI,CAAC,EAC7E,QAAQ,iBAAiB,GAAM,MAAiB,EAAM,CAAI,CAAC,EAE3D,QAAY,OAAO,gCAAgC,EAAS,OAAO,IAAI,IAAI,GAAM,MAAgB,EAAM,CAAG,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