@burdenoff/microfe-healthybowl 2026.901.13 → 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.
@@ -10,35 +10,36 @@ 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 C } from "./AssistantEmptyState.js";
14
- import { AssistantComposer as w } from "./composer/AssistantComposer.js";
15
- import { AssistantVoiceSession as oe } from "./voice/AssistantVoiceSession.js";
16
- import { useVoiceSession as se } from "../../hooks/useVoiceSession.js";
17
- import { useAssistantApiAccess as ce } from "../../hooks/useAssistantApiAccess.js";
18
- import { isQuotaExhaustedError as le } from "../../utils/quotaUtils.js";
19
- import { dispatchAssistantQuotaExhausted as ue, notifyAiCreditsUpdated as de } from "../../utils/aiCredits.js";
20
- import { buildPromptForMode as fe } from "../../utils/assistantPrompt.js";
21
- import { isMultimodalBodyRejection as pe, isRecoverableAssistantError as me } from "../../utils/assistantTransportErrors.js";
22
- import { pollDelayMs as he } from "../../utils/assistantPollSchedule.js";
23
- import { chatTurns as ge, voiceTurnsOnly as _e } from "../../utils/voiceTurnVisibility.js";
24
- import { createReadinessTracker as ve } from "../../utils/sandboxReadiness.js";
25
- import { useCallback as T, useEffect as E, useMemo as D, useRef as O, useState as ye } from "react";
26
- import { useI18n as be } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
27
- import { jsx as k, jsxs as xe } from "react/jsx-runtime";
28
- import { useGatewayClient as Se } from "@burdenoff/fe-libs/shared/graphql";
29
- import { useAuthToken as Ce } from "@burdenoff/fe-libs/shared/providers/shell";
30
- import { getAssistantMedia as we } from "@burdenoff/fe-libs/shared/assistant";
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 Te = {
33
+ var De = {
33
34
  general: 18e4,
34
35
  assistant: 18e4,
35
36
  "api-calls": 18e4,
36
37
  "vibe-plugins": 6e5
37
- }, Ee = 18e4;
38
- function De() {
38
+ }, Oe = 18e4;
39
+ function ke() {
39
40
  return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
40
41
  }
41
- function Oe(e) {
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
45
  function A(e) {
@@ -53,13 +54,13 @@ function M(e) {
53
54
  return t === "completed" ? `Completed: ${n}` : t === "failed" ? `Failed: ${n}` : `Running: ${n}`;
54
55
  });
55
56
  }
56
- function ke(e, t) {
57
+ function je(e, t) {
57
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 = j(r.parts), a = we(r.parts), o = M(r.parts);
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 Ae(e) {
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,21 +79,21 @@ function Ae(e) {
78
79
  default: return "";
79
80
  }
80
81
  }
81
- var N = ({ visible: we = !0 }) => {
82
- let j = t(), M = Se("workspace"), { getAccessToken: N, getWorkspaceToken: je, userId: Me } = Ce(), { locale: P } = be(), F = e((e) => e.assistantLanguage), Ne = D(() => g(F, P).english, [F, P]), Pe = h(F) !== null, Fe = D(() => g(F, P).code, [F, P]), { conversations: Ie, activeConversationId: I, mode: L, processingByConversationId: Le, setMode: R, setConversationMode: z, setActiveConversation: Re, createConversation: B, addMessage: ze, updateMessage: Be, patchMessage: V, setConversationProcessing: H, clearConversationProcessing: Ve, setBackendSessionId: He, clearBackendSessionId: U, setSandbox: W, clearSandbox: Ue, acknowledgeApiCalls: We } = e(), G = Ie.find((e) => e.id === I)?.messages ?? [], K = I ? Le[I] : void 0, q = _(K?.status), Ge = q ? K?.messageId ?? null : null, Ke = K?.status === "error" ? K.messageId : null, { canUseApiCalls: J, loading: qe } = ce(y()), Je = D(() => S.filter((e) => !e.requiresAdmin || J), [J]), [Ye, Xe] = ye(null), Ze = O({}), Y = O(ve()), Qe = O(/* @__PURE__ */ new Set());
82
+ 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());
83
84
  E(() => {
84
- if (qe) return;
85
+ if (Ye) return;
85
86
  let e = S.find((e) => e.id === L);
86
87
  (!e || e.requiresAdmin && !J) && L !== "assistant" && R("assistant");
87
88
  }, [
88
89
  L,
89
90
  J,
90
- qe,
91
+ Ye,
91
92
  R
92
93
  ]);
93
94
  let X = T((e, t, n, r) => {
94
- H(e, n, t, null), r ? Be(e, t, r) : Be(e, t, Ae(n));
95
- }, [H, Be]), $e = T(async (t, n, a, s, c) => {
95
+ 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
98
  if (Y.current.isFresh(e)) return !0;
98
99
  try {
@@ -118,7 +119,7 @@ var N = ({ visible: we = !0 }) => {
118
119
  } catch {
119
120
  U(t), m = null;
120
121
  }
121
- return m || (X(t, n, "connecting", "Preparing session..."), m = (await i(M, u, s, a, c)).sessionId, He(t, 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
  };
@@ -126,149 +127,153 @@ var N = ({ visible: we = !0 }) => {
126
127
  M,
127
128
  U,
128
129
  N,
129
- He,
130
+ We,
130
131
  W,
131
132
  X
132
133
  ]), Z = T(async (t, r = [], i = {}) => {
133
134
  let o = e.getState(), l = o.activeConversationId ?? I;
134
- if (l && (_(o.processingByConversationId[l]?.status) || Qe.current.has(l))) return;
135
+ if (l && (_(o.processingByConversationId[l]?.status) || et.current.has(l))) return;
135
136
  let f = o.mode, p = I, h = p ? e.getState().conversations.find((e) => e.id === p) : void 0;
136
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;
137
- Ze.current[p] = r;
138
+ $e.current[p] = r;
138
139
  let g = ee(), v = {
139
140
  accessToken: N(),
140
- workspaceToken: je(),
141
- userId: Me,
141
+ workspaceToken: Ne(),
142
+ userId: Pe,
142
143
  organizationId: y()
143
144
  }, b = {
144
- id: De(),
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
- ...i.dictated === !0 ? { voice: !0 } : {}
151
+ ...w(i.dictated)
151
152
  }
152
153
  };
153
- ze(p, b);
154
- let x = De();
155
- ze(p, {
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: Fe,
162
- ...i.dictated === !0 ? { voice: !0 } : {}
162
+ lang: Le,
163
+ ...w(i.dictated)
163
164
  }
164
165
  }), H(p, "provisioning", x, null);
165
- let S = (e, t, n, r, i = Fe) => {
166
+ let S = (e, t, n, r, a = Le) => {
166
167
  V(p, x, {
167
- content: Oe(e),
168
+ content: Ae(e),
168
169
  metadata: {
169
- lang: i,
170
+ lang: a,
170
171
  ...t?.length ? { artifacts: t } : {},
171
172
  ...t?.length || n || r ? { mode: f } : {},
172
173
  ...n ? { sessionId: n } : {},
173
- ...r ? { sandboxId: r } : {}
174
+ ...r ? { sandboxId: r } : {},
175
+ ...w(i.dictated)
174
176
  }
175
177
  });
176
- }, C = async (e = 1) => {
178
+ }, oe = async (e = 1) => {
177
179
  let o = !1;
178
180
  try {
179
181
  await n(M, g, v);
180
182
  } catch (e) {
181
- if (le(e)) {
182
- ue("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);
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);
183
185
  return;
184
186
  }
185
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);
186
188
  }
187
189
  try {
188
- let { sandboxId: e, sessionId: n } = await $e(p, x, f, g, v), l = (await c(M, e, g, n, v, 50).catch(() => [])).reduce((e, t) => Math.max(e, A(t)), 0);
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);
189
191
  X(p, x, "streaming", "Thinking...");
190
- let h = fe(f, ne(t, r), Ne, Pe, i.dictated === !0), _ = te(h, r), y = ie(_), ee = y > 0, ae = m();
192
+ let h = pe(f, ne(t, r), Fe, Ie, i.dictated === !0), _ = te(h, r), y = ie(_), ee = y > 0, ae = m();
191
193
  o = re(r) > y;
192
194
  try {
193
195
  await d(M, e, g, n, h, f, ae, v, _);
194
196
  } catch (t) {
195
- if (!_ || !pe(t)) throw t;
197
+ if (!_ || !me(t)) throw t;
196
198
  await d(M, e, g, n, h, f, ae, v, void 0), o ||= ee;
197
199
  }
198
- let b = ke([], l), C = Date.now() + (Te[f] ?? Ee), w = Date.now(), oe = Date.now();
199
- for (; Date.now() < C && (b = ke(await c(M, e, g, n, v, 50), l), V(p, x, { content: Oe(b.content) }), !b.done);) Date.now() - w > 3e4 && (await a(M, e, g, 600, v).catch(() => void 0), w = Date.now()), await new Promise((e) => setTimeout(e, he(Date.now() - oe)));
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)));
200
202
  if (!b.done && f !== "vibe-plugins") throw Error("Assistant response timed out while streaming progress");
201
- let se = f === "vibe-plugins" ? await s(M, e, g, n, v).catch(() => []) : void 0;
203
+ let ce = f === "vibe-plugins" ? await s(M, e, g, n, v).catch(() => []) : void 0;
202
204
  if (b.done || (b = {
203
205
  ...b,
204
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._`
205
207
  }), o && (b = {
206
208
  ...b,
207
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._")}`
208
- }), S(b.content, se, n, e), b.tokens) {
210
+ }), S(b.content, ce, n, e), b.tokens) {
209
211
  V(p, x, { tokens: b.tokens });
210
212
  try {
211
- await u(M, g, n, b.tokens, v), de();
213
+ await u(M, g, n, b.tokens, v), fe();
212
214
  } catch {}
213
215
  }
214
216
  H(p, "complete", x, null);
215
217
  } catch (t) {
216
- if (e === 1 && me(t)) return U(p), Ue(f), C(2);
218
+ if (e === 1 && he(t)) return U(p), Ge(f), oe(2);
217
219
  throw t;
218
220
  }
219
- }, w = p;
220
- Qe.current.add(w);
221
+ }, C = p;
222
+ et.current.add(C);
221
223
  try {
222
224
  if (!g) throw Error("Assistant backend is unavailable without an active workspace context.");
223
- await C();
225
+ await oe();
224
226
  } catch (t) {
225
- if (Y.current.invalidate(e.getState().sandboxesByMode[f]?.sandboxId ?? null), le(t)) {
226
- ue("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);
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);
227
229
  return;
228
230
  }
229
231
  let n = t instanceof Error ? t.message : "Something went wrong";
230
232
  H(p, "error", x, n), V(p, x, {
231
233
  content: `Sorry, an error occurred: ${n}. Please try again.`,
232
- metadata: { lang: "en" }
234
+ metadata: {
235
+ lang: "en",
236
+ ...w(i.dictated)
237
+ }
233
238
  });
234
239
  } finally {
235
- Qe.current.delete(w);
240
+ et.current.delete(C);
236
241
  }
237
242
  }, [
238
243
  I,
239
- ze,
244
+ Ve,
240
245
  M,
241
246
  U,
242
- Ue,
243
- Ie,
247
+ Ge,
248
+ Re,
244
249
  B,
245
- $e,
250
+ tt,
246
251
  N,
247
- je,
252
+ Ne,
248
253
  V,
249
- Pe,
254
+ Ie,
255
+ Le,
250
256
  Fe,
251
- Ne,
252
- He,
257
+ We,
253
258
  z,
254
259
  H,
255
260
  j,
256
261
  X,
257
- Me
258
- ]), et = T((e) => {
262
+ Pe
263
+ ]), nt = T((e) => {
259
264
  Z(e);
260
- }, [Z]), tt = T(() => {
261
- let e = [...G].reverse().find((e) => e.role === "user"), t = I ? Ze.current[I] ?? [] : [];
265
+ }, [Z]), rt = T(() => {
266
+ let e = [...G].reverse().find((e) => e.role === "user"), t = I ? $e.current[I] ?? [] : [];
262
267
  e && Z(e.content, t);
263
268
  }, [
264
269
  G,
265
270
  Z,
266
271
  I
267
- ]), Q = O(Z);
272
+ ]), it = O(Z);
268
273
  E(() => {
269
- Q.current = Z;
274
+ it.current = Z;
270
275
  }, [Z]);
271
- let nt = D(() => {
276
+ let Q = D(() => {
272
277
  if (q) return null;
273
278
  for (let e = G.length - 1; e >= 0; --e) {
274
279
  let t = G[e];
@@ -280,100 +285,100 @@ var N = ({ visible: we = !0 }) => {
280
285
  } : null;
281
286
  }
282
287
  return null;
283
- }, [G, q]), rt = D(() => ge(G), [G]), it = D(() => _e(G).filter((e) => e.role === "user" || e.role === "assistant").map((e) => ({
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) => ({
284
289
  id: e.id,
285
290
  role: e.role,
286
291
  text: v(e.content).text.trim()
287
- })).filter((e) => e.text.length > 0), [G]), $ = se({
292
+ })).filter((e) => e.text.length > 0), [G]), $ = ce({
288
293
  onSubmit: T((e) => {
289
- Q.current(e, [], { dictated: !0 });
294
+ it.current(e, [], { dictated: !0 });
290
295
  }, []),
291
- latestReply: nt,
296
+ latestReply: Q,
292
297
  language: g(F, P).tag
293
298
  });
294
299
  E(() => {
295
- !we && $.active && $.end();
296
- }, [we, $]), E(() => {
300
+ !Ee && $.active && $.end();
301
+ }, [Ee, $]), E(() => {
297
302
  let t = e.getState().consumePendingPrompt();
298
- return t && Q.current(t), e.subscribe((t, n) => {
303
+ return t && it.current(t), e.subscribe((t, n) => {
299
304
  if (t.pendingPrompt && t.pendingPrompt !== n.pendingPrompt) {
300
305
  let t = e.getState().consumePendingPrompt();
301
- t && Q.current(t);
306
+ t && it.current(t);
302
307
  }
303
308
  });
304
309
  }, []);
305
- let at = T((t) => {
310
+ let ct = T((t) => {
306
311
  let n = I ? e.getState().conversations.find((e) => e.id === I) : void 0;
307
312
  if (n && (n.messages.length > 0 || n.backendSessionId)) {
308
313
  if (n.mode !== t) {
309
314
  let n = e.getState().conversations.find((n) => n.mode === t && n.messages.length === 0 && !n.backendSessionId && !e.getState().processingByConversationId[n.id]);
310
- n ? Re(n.id) : B(void 0, t);
315
+ n ? Be(n.id) : B(void 0, t);
311
316
  }
312
317
  } else I && z(I, t);
313
318
  R(t);
314
319
  }, [
315
320
  I,
316
321
  B,
317
- Re,
322
+ Be,
318
323
  z,
319
324
  R
320
- ]), ot = T((t) => {
325
+ ]), lt = T((t) => {
321
326
  if (S.find((e) => e.id === t)?.writeCapable && !e.getState().apiCallsAcknowledged) {
322
- Xe(t);
327
+ Qe(t);
323
328
  return;
324
329
  }
325
- at(t);
326
- }, [at]), st = T(() => {
327
- let e = Ye;
328
- Xe(null), We(), e && at(e);
330
+ ct(t);
331
+ }, [ct]), ut = T(() => {
332
+ let e = Ze;
333
+ Qe(null), Ke(), e && ct(e);
329
334
  }, [
330
- Ye,
331
- We,
332
- at
333
- ]), ct = T(() => {
334
- Xe(null);
335
+ Ze,
336
+ Ke,
337
+ ct
338
+ ]), dt = T(() => {
339
+ Qe(null);
335
340
  }, []);
336
- return /* @__PURE__ */ xe("div", {
341
+ return /* @__PURE__ */ Ce("div", {
337
342
  className: "relative flex flex-1 flex-col overflow-hidden",
338
343
  children: [
339
- /* @__PURE__ */ xe("div", {
344
+ /* @__PURE__ */ Ce("div", {
340
345
  className: "contents",
341
346
  inert: $.active || void 0,
342
- children: [rt.length === 0 ? /* @__PURE__ */ k(C, {
347
+ children: [ot.length === 0 ? /* @__PURE__ */ k(oe, {
343
348
  mode: L,
344
- onSuggestionClick: et
349
+ onSuggestionClick: nt
345
350
  }) : /* @__PURE__ */ k("div", {
346
351
  className: "flex min-h-0 flex-1 flex-col",
347
352
  children: /* @__PURE__ */ k(b, {
348
- messages: rt,
349
- streamingMessageId: Ge,
350
- failedMessageId: Ke,
351
- onRetry: tt
353
+ messages: ot,
354
+ streamingMessageId: qe,
355
+ failedMessageId: Je,
356
+ onRetry: rt
352
357
  })
353
- }), /* @__PURE__ */ k(w, {
358
+ }), /* @__PURE__ */ k(C, {
354
359
  onStartVoiceSession: $.available && L !== "api-calls" ? $.start : void 0,
355
360
  onSend: (e, t) => void Z(e, t),
356
361
  disabled: q,
357
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…"),
358
363
  mode: L,
359
- availableModes: Je,
360
- onModeChange: ot
364
+ availableModes: Xe,
365
+ onModeChange: lt
361
366
  })]
362
367
  }),
363
- $.active && /* @__PURE__ */ k(oe, {
368
+ $.active && /* @__PURE__ */ k(se, {
364
369
  session: $.session,
365
370
  notice: $.notice,
366
371
  capturing: $.capturing,
367
- turns: it,
372
+ turns: st,
368
373
  onInterrupt: $.interrupt,
369
- spoken: nt?.text ?? null,
374
+ spoken: at,
370
375
  onToggleMute: $.toggleMute,
371
376
  onEnd: $.end
372
377
  }),
373
378
  /* @__PURE__ */ k(x, {
374
- open: Ye !== null,
375
- onConfirm: st,
376
- onCancel: ct
379
+ open: Ze !== null,
380
+ onConfirm: ut,
381
+ onCancel: dt
377
382
  })
378
383
  ]
379
384
  });
@@ -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, voiceTurnsOnly } from '../../utils/voiceTurnVisibility';\nimport { createReadinessTracker } from '../../utils/sandboxReadiness';\n\n// How long the client streams progress before giving up on a turn. Chat replies\n// (general / api-calls) finish in seconds; a vibe-plugins build is a multi-step\n// pipeline (read docs → scaffold → bun install → bun build → checklist) that runs\n// for minutes, so it gets a much larger budget. The sandbox TTL is auto-extended\n// every 30s during the poll loop, so a longer budget never outlives the sandbox.\nconst STREAM_BUDGET_MS: Record<AssistantMode, number> = {\n general: 180_000,\n assistant: 180_000,\n 'api-calls': 180_000,\n 'vibe-plugins': 600_000,\n};\nconst DEFAULT_STREAM_BUDGET_MS = 180_000;\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n}\n\nfunction sanitizeAssistantResponse(response: string): string {\n return response\n .replace(/(Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/(X-Workspace-Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9._-]+\\.[A-Za-z0-9._-]+\\b/g, '[REDACTED_JWT]')\n .replace(/\\bsk-ant-[A-Za-z0-9-]+\\b/g, '[REDACTED_API_KEY]');\n}\n\nfunction getRawMessageCreatedAt(message: AssistantRawMessage): number {\n return message.info?.time?.created ?? 0;\n}\n\nfunction getAssistantText(parts: AssistantRawMessage['parts']): string {\n return (parts ?? [])\n .filter((part) => part.type === 'text' && typeof part.text === 'string')\n .map((part) => part.text?.trim() ?? '')\n .filter(Boolean)\n .join('\\n');\n}\n\nfunction getToolProgress(parts: AssistantRawMessage['parts']): string[] {\n return (parts ?? [])\n .filter((part) => part.type === 'tool' && part.tool)\n .map((part) => {\n const status = part.state?.status ?? 'running';\n const tool = part.tool ?? 'tool';\n if (status === 'completed') return `Completed: ${tool}`;\n if (status === 'failed') return `Failed: ${tool}`;\n return `Running: ${tool}`;\n });\n}\n\nfunction buildAssistantProgress(\n messages: AssistantRawMessage[],\n // The `created` timestamp (sandbox clock) of the newest message that already\n // existed in this session BEFORE the prompt was sent. This turn's reply is the\n // assistant message created strictly after it. Crucially this stays WITHIN the\n // sandbox clock domain: the previous code compared the sandbox-stamped\n // `created` against the browser wall-clock (Date#now), so a reply stamped at\n // prompt-time was silently dropped whenever the sandbox clock lagged the\n // browser — the turn then hung on \"Thinking...\" until the stream budget\n // elapsed. A sandbox-domain floor is immune to clock skew and correct for both\n // fresh and reused (per-conversation) sessions, with no message-window gap.\n priorNewestCreatedMs: number\n): {\n content: string;\n done: boolean;\n tokens?: { input: number; output: number };\n} {\n const relevant = messages\n .filter((message) => message.info?.role === 'assistant' && getRawMessageCreatedAt(message) > priorNewestCreatedMs)\n .sort((left, right) => getRawMessageCreatedAt(left) - getRawMessageCreatedAt(right));\n\n if (relevant.length === 0) {\n return { content: 'Thinking...', done: false };\n }\n\n const latest = relevant[relevant.length - 1]!;\n const text = getAssistantText(latest.parts);\n // Inbound image/file parts, rendered to markdown by the shared helper (which\n // escapes the label and allowlists the protocol — this is model output).\n // Without this, HealthyBowl — the one product that SENDS parts — could not\n // read one back: a media-bearing reply would never satisfy `done` and the\n // turn would poll to a false timeout.\n const media = getAssistantMedia(latest.parts);\n const toolProgress = getToolProgress(latest.parts);\n const content = [text, ...media, ...toolProgress].filter(Boolean).join('\\n\\n') || 'Thinking...';\n\n return {\n content,\n done: Boolean(latest.info?.time?.completed) && (Boolean(text) || media.length > 0 || toolProgress.length > 0),\n tokens: latest.info?.tokens,\n };\n}\n\nfunction getConversationStatusMessage(status: AssistantConversationStatus): string {\n switch (status) {\n case 'provisioning':\n return 'Starting assistant environment...';\n case 'connecting':\n return 'Connecting to assistant...';\n case 'streaming':\n return 'Thinking...';\n default:\n return '';\n }\n}\n\n/**\n * `visible` is false when the host HIDES the panel without unmounting it, which\n * is what the supported `visible` prop does. That distinction matters here: a\n * live voice session would otherwise keep the microphone open and the silence\n * timer running behind an invisible panel.\n */\ninterface AssistantChatAreaProps {\n visible?: boolean;\n}\n\nexport const AssistantChatArea: FC<AssistantChatAreaProps> = ({ visible = true }) => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken, userId } = useAuthToken();\n const { locale } = useI18n();\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n // The language the user chose to SPEAK, which is not necessarily the one the\n // interface is in — that is the whole point of the preference (BOFF-7108).\n // Named in ENGLISH deliberately: the preamble around it is English, so\n // \"Answer in Tamil.\" reads as an instruction, where a bare tag (\"ta\") invites\n // the model to answer *about* the code instead of *in* the language.\n const replyLanguageName = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale).english,\n [assistantLanguage, locale]\n );\n // A stored preference is a deliberate choice; `null` is only the interface\n // language standing in as a default. The directive treats the two differently\n // — see `buildLanguagePreamble`.\n //\n // Resolved, not merely non-null: a stale persisted code from a build that\n // offered more languages is DISCARDED by `resolveAssistantLanguage`, and\n // treating that discarded value as deliberate would tell the model the user\n // had chosen the interface language on purpose — suppressing the typed-language\n // override on the strength of a preference the selector does not even show.\n const languageIsExplicit = findAssistantLanguage(assistantLanguage) !== null;\n const replyLanguageCode = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale).code,\n [assistantLanguage, locale]\n );\n\n const {\n conversations,\n activeConversationId,\n mode,\n processingByConversationId,\n setMode,\n setConversationMode,\n setActiveConversation,\n createConversation,\n addMessage,\n updateMessage,\n patchMessage,\n setConversationProcessing,\n clearConversationProcessing,\n setBackendSessionId,\n clearBackendSessionId,\n setSandbox,\n clearSandbox,\n acknowledgeApiCalls,\n } = useAssistantStore();\n\n const activeConversation = conversations.find((conversation) => conversation.id === activeConversationId);\n const messages = activeConversation?.messages ?? [];\n const activeProcessing = activeConversationId ? processingByConversationId[activeConversationId] : undefined;\n // Only while the turn is genuinely in flight. `messageId` outlives the turn\n // (setConversationProcessing keeps it on 'complete'/'error'), so keying off it\n // alone left the transcript's aria-busy latched true forever and screen\n // readers stopped announcing new replies.\n const activeIsProcessing = isTurnInFlight(activeProcessing?.status);\n const activeStreamingMessageId = activeIsProcessing ? (activeProcessing?.messageId ?? null) : null;\n // The assistant message whose turn ended in an error — drives the Retry\n // affordance in the transcript.\n const failedMessageId = activeProcessing?.status === 'error' ? activeProcessing.messageId : null;\n\n // ── api-calls (write) mode gating ──────────────────────────────────\n // Only a global Owner/Admin may use api-calls (it mints an OAuth app under the\n // caller identity). Re-read the org scope every render (a cheap localStorage\n // read) so the admin gate reacts to an org switch without the panel\n // remounting; the value is a stable string, so useAssistantApiAccess only\n // re-fetches myRoles when the org actually changes. An empty scope simply\n // hides the mode (it could not provision the sandbox anyway).\n const apiCallsScopeId = getOrganizationId();\n const { canUseApiCalls, loading: apiAccessLoading } = useAssistantApiAccess(apiCallsScopeId);\n const availableModes = useMemo(\n () => ASSISTANT_MODES.filter((modeConfig) => !modeConfig.requiresAdmin || canUseApiCalls),\n [canUseApiCalls]\n );\n\n // Target mode awaiting the one-time consent dialog (null = dialog closed).\n const [pendingConsentMode, setPendingConsentMode] = useState<AssistantMode | null>(null);\n\n // Full attachment payload of the last send, kept so Retry can replay it\n // byte-for-byte (see handleRetry).\n const lastSentAttachmentsRef = useRef<Record<string, AssistantAttachment[]>>({});\n\n // Conversations with a turn already dispatched. Synchronous, unlike the store\n // — see the re-entry guard in handleSend for why that matters.\n /**\n * Per-sandbox record of \"last proven reachable\", so a warm sandbox is not\n * re-probed on every turn. Invalidated by any failure — see both catches.\n */\n const sandboxReadiness = useRef(createReadinessTracker());\n const inFlightSendsRef = useRef<Set<string>>(new Set());\n\n // If the active mode is no longer permitted — a non-admin with a persisted\n // api-calls mode, or the master flag turned off — fall back to the read-only\n // `assistant` mode (the default \"Ask\", available to everyone), but only AFTER\n // the role check resolves (so an admin's persisted api-calls mode isn't reset\n // during the brief loading window).\n useEffect(() => {\n if (apiAccessLoading) return;\n const activeModeConfig = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === mode);\n const blocked = !activeModeConfig || (activeModeConfig.requiresAdmin && !canUseApiCalls);\n if (blocked && mode !== 'assistant') {\n setMode('assistant');\n }\n }, [mode, canUseApiCalls, apiAccessLoading, setMode]);\n\n const updateConversationStage = useCallback(\n (conversationId: string, assistantMessageId: string, status: AssistantConversationStatus, content?: string) => {\n setConversationProcessing(conversationId, status, assistantMessageId, null);\n if (content) {\n updateMessage(conversationId, assistantMessageId, content);\n } else {\n updateMessage(conversationId, assistantMessageId, getConversationStatusMessage(status));\n }\n },\n [setConversationProcessing, updateMessage]\n );\n\n const ensureAssistantRuntime = useCallback(\n async (\n conversationId: string,\n assistantMessageId: string,\n currentMode: AssistantMode,\n workspaceId: string,\n authContext: AssistantSandboxAuthContext\n ): Promise<{ sandboxId: string; sessionId: string }> => {\n let currentSandboxId = useAssistantStore.getState().sandboxesByMode[currentMode]?.sandboxId ?? null;\n\n // Validate that a candidate sandbox (remembered locally or found running on\n // the server) is actually reachable before we reuse it. A sandbox can expire\n // (ttlSeconds) or have its backend pod reclaimed while still being briefly\n // reported RUNNING; proxying to such a dead pod fails with a terminal state\n // (\"Backend resource no longer exists\") or a permanent 502 cf-proxy timeout.\n // Returns true only when the in-sandbox agent responds; false means stale.\n const ensureSandboxReachable = async (candidateId: string): Promise<boolean> => {\n // ★ Skip a proof we already have. This ran two network waits before the\n // model saw the prompt on EVERY turn, including turns seconds after the\n // last one succeeded — a constant tax, felt most in voice where it sits\n // between the user finishing a sentence and hearing anything.\n //\n // Safe only because every failure path below invalidates: see the catch\n // here and the turn-level catch. A cache that were only ever written on\n // success would pin a dead sandbox and turn a recoverable error into a\n // loop.\n if (sandboxReadiness.current.isFresh(candidateId)) return true;\n try {\n await waitForSandboxReady(apollo, candidateId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, candidateId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n sandboxReadiness.current.markVerified(candidateId);\n return true;\n } catch {\n // Stale/expired sandbox — drop it so we provision a fresh one below\n // instead of surfacing \"Internal server error\" to the user.\n sandboxReadiness.current.invalidate(candidateId);\n return false;\n }\n };\n\n // 1) Try the locally-remembered sandbox, then 2) any running one on the\n // server. Each is only kept if it's actually reachable.\n if (currentSandboxId) {\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', 'Reusing assistant environment...');\n if (!(await ensureSandboxReachable(currentSandboxId))) {\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = null;\n }\n }\n\n if (!currentSandboxId) {\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Looking for existing environment...'\n );\n const existingId = await findExistingSandbox(apollo, workspaceId, currentMode, authContext);\n\n if (existingId) {\n setSandbox(currentMode, existingId, 'provisioning');\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Reusing assistant environment...'\n );\n if (await ensureSandboxReachable(existingId)) {\n currentSandboxId = existingId;\n } else {\n setSandbox(currentMode, null, 'provisioning');\n }\n }\n }\n\n // 3) No reusable, reachable sandbox — provision a fresh one.\n if (!currentSandboxId) {\n if (currentMode === 'api-calls' && !getAccessToken()) {\n throw new Error('API Calls mode requires an authenticated session. Please sign in again.');\n }\n\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Starting assistant environment...'\n );\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = await createAssistantSandbox(apollo, currentMode, workspaceId, authContext);\n\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n await waitForSandboxReady(apollo, currentSandboxId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, currentSandboxId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n }\n\n setSandbox(currentMode, currentSandboxId, 'running');\n\n let sessionId =\n useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n ?.backendSessionId ?? null;\n\n if (sessionId) {\n try {\n const session = await getAssistantSession(apollo, currentSandboxId, workspaceId, sessionId, authContext);\n if (session.mode !== currentMode) {\n throw new Error(`Session mode mismatch: expected ${currentMode}, received ${session.mode}`);\n }\n } catch {\n clearBackendSessionId(conversationId);\n sessionId = null;\n }\n }\n\n if (!sessionId) {\n updateConversationStage(conversationId, assistantMessageId, 'connecting', 'Preparing session...');\n const result = await createAssistantSession(apollo, currentSandboxId, workspaceId, currentMode, authContext);\n sessionId = result.sessionId;\n setBackendSessionId(conversationId, sessionId);\n }\n\n return {\n sandboxId: currentSandboxId,\n sessionId,\n };\n },\n [apollo, clearBackendSessionId, getAccessToken, setBackendSessionId, setSandbox, updateConversationStage]\n );\n\n const handleSend = useCallback(\n async (content: string, attachments: AssistantAttachment[] = [], options: { dictated?: boolean } = {}) => {\n // Only block re-entry while a turn is genuinely in-flight. Earlier code\n // checked for *any* entry in the map, which stuck around as `complete`\n // / `error` after the first turn — making every subsequent message\n // silently disappear (the input cleared but handleSend bailed before\n // adding the user message to the conversation).\n //\n // The store is read LIVE, and that is what makes the guard work. The\n // render-captured `processingByConversationId` is stale by construction —\n // the click that starts a turn and the click that must be rejected can\n // belong to the same render. Reading `activeConversationId` live matters\n // for the same reason: on two racing first-ever sends, the second must see\n // the conversation the first one created a moment ago.\n //\n // Pairs with the synchronous `setConversationProcessing` below: because\n // the status is written before this function ever awaits, a second call —\n // however soon it arrives — always observes 'provisioning'.\n const storeAtEntry = useAssistantStore.getState();\n const guardConversationId = storeAtEntry.activeConversationId ?? activeConversationId;\n if (guardConversationId) {\n if (isTurnInFlight(storeAtEntry.processingByConversationId[guardConversationId]?.status)) return;\n // Second lock, in case a future change moves the status write later:\n // this one cannot be cleared by anything but the turn's own `finally`.\n // Deliberately per-conversation — a global key would keep blocking\n // after the conversation it belonged to was deleted mid-turn, and then\n // silently swallow every subsequent send.\n if (inFlightSendsRef.current.has(guardConversationId)) return;\n }\n\n const selectedMode = storeAtEntry.mode;\n let conversationId = activeConversationId;\n const currentConversation = conversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n : undefined;\n\n if (!conversationId) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (\n currentConversation &&\n currentConversation.mode !== selectedMode &&\n (currentConversation.messages.length > 0 || currentConversation.backendSessionId)\n ) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (currentConversation && currentConversation.mode !== selectedMode) {\n setConversationMode(conversationId, selectedMode);\n }\n\n if (!conversationId) return;\n\n // Keyed by conversation: the ref outlives a conversation switch, and a\n // single global slot meant Retry in one thread replayed another thread's\n // photo onto it.\n lastSentAttachmentsRef.current[conversationId] = attachments;\n\n const workspaceId = getWorkspaceId();\n const authContext: AssistantSandboxAuthContext = {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n };\n\n const userMessage: Message = {\n id: generateId(),\n role: 'user',\n content,\n timestamp: new Date().toISOString(),\n // Slim descriptors only — the bubble re-resolves thumbnails from the\n // file id, so the persisted conversation stays small.\n // ★ `voice` marks a turn that happened in the live voice session, so the\n // chat panel can leave it out. Both surfaces share one conversation, so\n // without it every spoken exchange showed up in the typed thread.\n metadata: {\n ...(attachments.length ? { attachments: attachments.map(toMessageAttachment) } : {}),\n ...(options.dictated === true ? { voice: true } : {}),\n },\n };\n addMessage(conversationId, userMessage);\n\n const assistantMessageId = generateId();\n addMessage(conversationId, {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n timestamp: new Date().toISOString(),\n // Stamped now, not read later: this is the language the reply is being\n // generated in, and the preference may have moved on by the time\n // somebody presses Listen.\n // Carries the voice marker too: a reply to a spoken question belongs to\n // the voice session, not to the typed thread.\n metadata: { lang: replyLanguageCode, ...(options.dictated === true ? { voice: true } : {}) },\n });\n\n // Mark the turn in-flight in the STORE right now, synchronously.\n //\n // Until this line the first status write happened inside\n // `ensureAssistantRuntime`, i.e. one await later. During that window\n // `activeIsProcessing` was false and `failedMessageId` still pointed at\n // the PREVIOUS failure — so the composer stayed enabled and, worse, the\n // Retry button (which has no `disabled` of its own) stayed mounted and\n // clickable on top of a turn that had already started.\n //\n // Status only, deliberately no stage copy: `ensureAssistantRuntime` picks\n // the accurate wording a moment later (\"Reusing...\" vs \"Starting...\"), and\n // guessing here would flash the wrong one on every reused sandbox.\n setConversationProcessing(conversationId, 'provisioning', assistantMessageId, null);\n\n const applyAssistantResponse = (\n response: string,\n artifacts?: AssistantArtifact[],\n sessionId?: string,\n sandboxId?: string,\n // Our own hard-coded copy is English regardless of what the user picked.\n // Stamping it with their language makes playback read an English quota\n // message in a Tamil voice — Latin text cannot be script-detected, so\n // this metadata is trusted absolutely.\n lang: string = replyLanguageCode\n ) => {\n // `patchMessage` REPLACES metadata rather than merging it, so anything\n // omitted here is destroyed — which is how the turn-language stamp set\n // at creation was being wiped the moment the response completed,\n // silently undoing per-message language resolution. Always re-assert it.\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n metadata: {\n lang,\n ...(artifacts?.length ? { artifacts } : {}),\n ...(artifacts?.length || sessionId || sandboxId ? { mode: selectedMode } : {}),\n ...(sessionId ? { sessionId } : {}),\n ...(sandboxId ? { sandboxId } : {}),\n },\n });\n };\n\n const sendWithRealBackend = async (attempt: 1 | 2 = 1): Promise<void> => {\n // Set when this attempt had to re-send without the image bytes, so the\n // answer can say so rather than quietly reading as if the model looked.\n let imagesDropped = false;\n // Pre-flight AI-credit gate. The wspace gateway's @usage(checkQuota)\n // rejects with 429 QUOTA_EXHAUSTED when the monthly token budget is\n // depleted — block the send (don't provision a sandbox or dispatch the\n // prompt) and surface the upgrade dialog instead of a generic error.\n try {\n await checkAssistantAiCredits(apollo, workspaceId, authContext);\n } catch (creditError) {\n if (isQuotaExhaustedError(creditError)) {\n dispatchAssistantQuotaExhausted('ai-credits');\n applyAssistantResponse(\n \"You've run out of AI credits for this billing cycle. Upgrade your plan to keep chatting.\",\n undefined,\n undefined,\n undefined,\n 'en'\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n // The pre-flight gate exists ONLY to catch a genuine QUOTA_EXHAUSTED\n // rejection. Any other failure here is a transient fault in the\n // credit check itself — e.g. the usage subgraph's getUsageSummary /\n // checkAiCredits intermittently 500s (Postgres/Prisma blip) and the\n // gateway masks it as the opaque \"Unexpected error.\". That is NOT\n // proof the user is out of budget, so it must not abort an otherwise\n // valid send. Fail open and proceed: the wspace gateway's\n // @usage(checkQuota) on createSandbox still enforces the real budget\n // downstream (a truly over-quota caller is stopped there with a 429\n // that surfaces the upgrade dialog via the outer catch).\n console.warn(\n '[assistant] AI-credit pre-flight check failed with a non-quota error; proceeding — gateway @usage(checkQuota) still enforces the real budget downstream',\n creditError\n );\n }\n\n try {\n const { sandboxId, sessionId } = await ensureAssistantRuntime(\n conversationId,\n assistantMessageId,\n selectedMode,\n workspaceId,\n authContext\n );\n\n // Snapshot the newest message timestamp already present in this\n // (possibly reused) session BEFORE sending the prompt, so we can\n // recognise THIS turn's reply as the one created after it — never by\n // comparing the browser clock to the sandbox clock (see\n // buildAssistantProgress). The newest-N window always contains the\n // newest message, so this floor is exact regardless of conversation depth.\n const priorMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n ).catch((): AssistantRawMessage[] => []);\n const priorNewestCreatedMs = priorMessages.reduce(\n (newest, message) => Math.max(newest, getRawMessageCreatedAt(message)),\n 0\n );\n\n updateConversationStage(conversationId, assistantMessageId, 'streaming', 'Thinking...');\n // Two agent-only wrappers around the raw content, both invisible in\n // the bubble: the soft confirm-before-mutate guard for api-calls mode,\n // and the attachment block (metadata + URLs, with text-like files\n // inlined) that carries this turn's files to the model.\n // …and the language directive, so the reply comes back in the user's\n // language rather than defaulting to the language of the docs the\n // model grounds on. The FE is the only layer that knows the locale —\n // it is not on the wire and `pageContext` silently drops unknown keys.\n const promptText = buildPromptForMode(\n selectedMode,\n buildPromptWithAttachments(content, attachments),\n replyLanguageName,\n languageIsExplicit,\n options.dictated === true\n );\n // Structured multimodal parts carry the image PIXELS, which no amount\n // of prompt text can. Built from the same `promptText`, so a bridge\n // that ignores `parts` loses nothing; `undefined` for an ordinary text\n // turn keeps the wire body unchanged.\n const promptParts = buildPromptParts(promptText, attachments);\n const inlinedCount = countInlinedImageParts(promptParts);\n const carriesPixels = inlinedCount > 0;\n const pageContext = gatherPageContext();\n\n // `buildPromptParts` may have demoted a photo to a link to keep the\n // body under the gateway's cap — a long message can do that on prompt\n // text alone. That decision is invisible to the user unless we say so,\n // and an answer that reads as if the model looked at a photo it never\n // received is worse than a short note.\n imagesDropped = countInlineImageCandidates(attachments) > inlinedCount;\n\n try {\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n promptParts\n );\n } catch (sendError) {\n // `buildPromptParts` already sizes the PARTS to the gateway's cap\n // (the prompt string itself is not bounded here), so reaching this\n // point means something rejected the body anyway — a tighter proxy\n // than we modelled, or a bridge that will not take `parts` at all.\n // Losing the whole question over that is the worst outcome\n // available: re-send it text-only. Only for errors that provably\n // never reached the agent (see isMultimodalBodyRejection) — a blind\n // retry would ask the same question twice and bill it twice.\n //\n // Gated on `parts` existing at all, NOT on it carrying pixels: the\n // array duplicates the whole prompt in `parts[0]`, so a url-only\n // parts array is itself enough to push a long message over the cap.\n // `carriesPixels` only decides whether the user is told something\n // was lost.\n if (!promptParts || !isMultimodalBodyRejection(sendError)) throw sendError;\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n undefined\n );\n // Only claim a photo was lost if one actually was — a url-only\n // retry loses nothing the prompt block did not already carry.\n imagesDropped = imagesDropped || carriesPixels;\n }\n\n let result = buildAssistantProgress([], priorNewestCreatedMs);\n const timeoutAt = Date.now() + (STREAM_BUDGET_MS[selectedMode] ?? DEFAULT_STREAM_BUDGET_MS);\n let lastTtlExtensionAt = Date.now();\n\n const pollStartedAt = Date.now();\n while (Date.now() < timeoutAt) {\n const sessionMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n );\n\n result = buildAssistantProgress(sessionMessages, priorNewestCreatedMs);\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(result.content),\n });\n\n if (result.done) break;\n\n if (Date.now() - lastTtlExtensionAt > 30_000) {\n await extendAssistantSandboxTTL(apollo, sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n // Fast early, backing off after — see assistantPollSchedule. This is\n // the granularity of the whole turn: it bounds how late the answer\n // appears AND how late speech can start, because auto-speak only\n // fires once a poll observes the reply completed.\n await new Promise((resolve) => setTimeout(resolve, pollDelayMs(Date.now() - pollStartedAt)));\n }\n\n // For non-build modes a timeout is a hard failure. For vibe-plugins the\n // prompt runs async server-side (/sessions/:id/prompt-async) and keeps\n // writing artifacts after the poll budget elapses, so we surface whatever\n // it has produced instead of discarding the turn.\n if (!result.done && selectedMode !== 'vibe-plugins') {\n throw new Error('Assistant response timed out while streaming progress');\n }\n\n const artifacts =\n selectedMode === 'vibe-plugins'\n ? await getAssistantArtifacts(apollo, sandboxId, workspaceId, sessionId, authContext).catch(() => [])\n : undefined;\n\n if (!result.done) {\n // vibe-plugins build still running in the background. Append a note so\n // the user knows the answer is partial and the artifacts will finish.\n result = {\n ...result,\n content: `${result.content}\\n\\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`,\n };\n }\n\n if (imagesDropped) {\n // Said plainly, because the alternative is an answer that looks like\n // it examined a photo it never received.\n result = {\n ...result,\n content: `${result.content}\\n\\n${tr(\n 'healthybowl.assistant.attachments.imagesNotSent',\n '_Your photo was too large to include with this message, so the answer above is from the text and the file link only. Try a smaller or more tightly cropped photo._'\n )}`,\n };\n }\n\n applyAssistantResponse(result.content, artifacts, sessionId, sandboxId);\n\n if (result.tokens) {\n patchMessage(conversationId, assistantMessageId, { tokens: result.tokens });\n // Charge the real token usage against the AI-credits quota (the\n // gateway records it via @usage(trackUsage)). We AWAIT it before\n // marking the turn complete / re-enabling input: otherwise a rapid\n // follow-up send would run its pre-flight checkAiCredits against a\n // stale balance (this turn's charge still in flight) and could\n // dispatch a prompt that should have been blocked, letting fast\n // sends bypass the credit cap. Still best-effort — a charge failure\n // never blocks the displayed answer.\n try {\n await reportAssistantAiTokenUsage(apollo, workspaceId, sessionId, result.tokens, authContext);\n notifyAiCreditsUpdated();\n } catch {\n // ignore — server-side @usage tracking is the source of truth\n }\n }\n setConversationProcessing(conversationId, 'complete', assistantMessageId, null);\n } catch (error) {\n if (attempt === 1 && isRecoverableAssistantError(error)) {\n clearBackendSessionId(conversationId);\n clearSandbox(selectedMode);\n return sendWithRealBackend(2);\n }\n\n throw error;\n }\n };\n\n // Claim the slot immediately before the first await, and release it in\n // `finally` so every exit — success, quota return, thrown error — frees\n // it. Registering here rather than earlier means a synchronous throw in\n // the setup above can never strand a key and wedge the conversation.\n const turnConversationId = conversationId;\n inFlightSendsRef.current.add(turnConversationId);\n\n try {\n if (!workspaceId) {\n throw new Error('Assistant backend is unavailable without an active workspace context.');\n }\n await sendWithRealBackend();\n } catch (error) {\n // ★ Any failed turn drops the readiness proof for the sandbox it used,\n // so the NEXT turn re-probes instead of trusting a cache entry that a\n // dead pod would otherwise keep alive until the TTL lapsed. This is the\n // half that makes the short-circuit above safe.\n sandboxReadiness.current.invalidate(\n useAssistantStore.getState().sandboxesByMode[selectedMode]?.sandboxId ?? null\n );\n // A quota error reaching here is the sandbox-environment wall hit\n // during runtime provisioning (createSandbox @usage). Surface the\n // upgrade dialog instead of a generic failure (the AI-credit wall is\n // already handled by the pre-flight gate above).\n if (isQuotaExhaustedError(error)) {\n dispatchAssistantQuotaExhausted('sandbox');\n applyAssistantResponse(\n \"You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.\",\n undefined,\n undefined,\n undefined,\n 'en'\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n const errorMessage = error instanceof Error ? error.message : 'Something went wrong';\n setConversationProcessing(conversationId, 'error', assistantMessageId, errorMessage);\n // Same reason: English copy must not inherit the turn's language stamp.\n patchMessage(conversationId, assistantMessageId, {\n content: `Sorry, an error occurred: ${errorMessage}. Please try again.`,\n metadata: { lang: 'en' },\n });\n } finally {\n inFlightSendsRef.current.delete(turnConversationId);\n }\n },\n [\n activeConversationId,\n addMessage,\n apollo,\n clearBackendSessionId,\n clearSandbox,\n conversations,\n createConversation,\n ensureAssistantRuntime,\n getAccessToken,\n getWorkspaceToken,\n patchMessage,\n // Without this, switching language mid-conversation keeps sending the\n // previous language's directive until something else re-creates the\n // callback.\n languageIsExplicit,\n replyLanguageCode,\n replyLanguageName,\n setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n tr,\n updateConversationStage,\n userId,\n ]\n );\n\n const handleSuggestionClick = useCallback(\n (suggestion: string) => {\n void handleSend(suggestion);\n },\n [handleSend]\n );\n\n // Retry re-sends the most recent user prompt through the same transport — the\n // failed assistant turn stays in the transcript, a fresh one is appended.\n // The attachments come from the in-memory ref rather than the message\n // metadata: the persisted descriptors deliberately drop the inlined text of\n // text-like files, so rebuilding from them would silently retry a WEAKER\n // prompt than the one that failed.\n const handleRetry = useCallback(() => {\n const lastUserMessage = [...messages].reverse().find((message) => message.role === 'user');\n const replay = activeConversationId ? (lastSentAttachmentsRef.current[activeConversationId] ?? []) : [];\n if (lastUserMessage) void handleSend(lastUserMessage.content, replay);\n }, [messages, handleSend, activeConversationId]);\n\n // Auto-send any prompt that was queued by `useOpenAssistantHelp` (from\n // the shared GetHelpButton). We keep the latest handleSend in a ref so\n // the subscription effect below doesn't need to tear down on every\n // render — the store subscription lives for the component lifetime and\n // always calls the freshest handler.\n const handleSendRef = useRef(handleSend);\n useEffect(() => {\n handleSendRef.current = handleSend;\n }, [handleSend]);\n\n /**\n * The newest assistant reply, as the voice session's advance signal.\n *\n * Keyed on the message ID rather than the text: two consecutive answers can be\n * word-for-word identical, and text alone would then never advance the second\n * turn.\n */\n const latestAssistantReply = useMemo(() => {\n // ★ Only once the turn is COMPLETE. While it is in flight the pending\n // assistant message is patched with progress text — 'Starting assistant\n // environment...', 'Thinking...' — and exposing that would make the voice\n // session consume the message id, enter `speaking` on a placeholder, and\n // then be unable to advance when the real answer replaced it.\n if (activeIsProcessing) return null;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (message?.role !== 'assistant') continue;\n // Tool-activity markup is stripped so the session captions and speaks the\n // answer, not the machinery that produced it.\n const text = parseToolActivity(message.content).text.trim();\n return text ? { id: message.id, text } : null;\n }\n return null;\n }, [messages, activeIsProcessing]);\n\n /**\n * The last few exchanges, for the session's on-screen transcript.\n *\n * Voice turns already go through the normal send path, so they are ordinary\n * conversation messages — this only surfaces them INSIDE the session, which\n * is what makes a second question in the same session make sense.\n */\n /**\n * What the CHAT panel shows: everything that was not spoken.\n *\n * Voice and chat share one conversation, so without this split every spoken\n * exchange appeared in the typed thread.\n */\n const chatMessages = useMemo(() => chatTurns(messages), [messages]);\n\n const voiceTurns = useMemo(\n () =>\n // ★ Only turns from this voice session. It used to take the last six\n // messages of the WHOLE conversation, so opening voice on an existing\n // thread painted typed replies — the wall of raw `##` and `**` the\n // operator screenshotted, because the voice panel renders plain text.\n voiceTurnsOnly(messages)\n .filter((message) => message.role === 'user' || message.role === 'assistant')\n .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,C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c,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,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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KAAK,WAAU;eACb,kBAAC,GAAD;MACE,UAAU;MACV,oBAAoB;MACH;MACjB,SAAS;KACV,CAAA;IACE,CAAA,GAGP,kBAAC,GAAD;KAOE,qBAAqB,EAAa,aAAa,MAAS,cAAc,EAAa,QAAQ,KAAA;KAC3F,SAAS,GAAO,MAAgB,KAAK,EAAW,GAAO,CAAW;KAClE,UAAU;KACV,aACE,MAAS,cACL,EAAG,qDAAqD,+BAA+B,IACvF,EAAG,qDAAqD,2BAA2B;KAEnF;KACU;KAChB,cAAc;IACf,CAAA,CACE;;GAEJ,EAAa,UACZ,kBAAC,IAAD;IACE,SAAS,EAAa;IACtB,QAAQ,EAAa;IACrB,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"}
@@ -81,7 +81,7 @@ var _ = ({ session: _, turns: b = [], notice: x = null, spoken: S, onInterrupt:
81
81
  state: U,
82
82
  userCaption: H || null,
83
83
  assistantCaption: S,
84
- expanded: !0,
84
+ expanded: F,
85
85
  statusText: V,
86
86
  errorText: i,
87
87
  control: e
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantVoiceSession.js","names":[],"sources":["../../../../src/components/assistant/voice/AssistantVoiceSession.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type FC } from 'react';\nimport { Maximize2, Minimize2, ScrollText, X } from 'lucide-react';\nimport { AssistantVoiceOrb } from './AssistantVoiceOrb';\nimport { VoiceStage } from './VoiceStage';\nimport { VoiceMiniController } from './VoiceMiniController';\nimport { VoiceTranscriptDrawer } from './VoiceTranscriptDrawer';\nimport { voiceStageState, micIsInterrupt } from '../../../utils/voiceStageState';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { spokenSoFar, type VoiceSessionSnapshot } from '../../../utils/voiceSession';\nimport type { VoiceSessionError } from '../../../utils/voiceSession';\nimport type { VoiceSessionNotice } from '../../../hooks/useVoiceSession';\n\n/** How much room the voice session takes: a strip, the panel, or the screen. */\nexport type VoiceView = 'mini' | 'panel' | 'full';\n\ninterface Props {\n session: VoiceSessionSnapshot;\n /** Recent exchanges, oldest first — the running conversation. */\n turns?: ReadonlyArray<{ id: string; role: 'user' | 'assistant'; text: string }>;\n /** Cut the assistant off mid-reply. */\n onInterrupt?: () => void;\n /** A recoverable problem to surface. Null when the microphone is healthy. */\n notice?: VoiceSessionNotice | null;\n /** The assistant's last reply, captioned while it is spoken. */\n spoken: string | null;\n onToggleMute: () => void;\n onEnd: () => void;\n /** Is the recogniser actually running? Distinguishes CONNECTING from LISTENING. */\n capturing?: boolean;\n}\n\n/**\n * Full-screen voice conversation (BOFF-7120).\n *\n * ★ **Voice only, by explicit product decision.** The reference (Gemini Live)\n * also offers camera and screen sharing; those are deliberately absent here.\n * Attaching images is a separate, existing capability of the assistant and\n * stays in the composer, and screen sharing could not work on the primary\n * device anyway — `getDisplayMedia` is unsupported by every iOS browser, so\n * that control would be dead on an iPhone.\n *\n * The controls are therefore the two that a voice conversation actually needs:\n * mute, and end. Anything else would be a button the user has to think about\n * while talking.\n *\n * This component is presentational: every transition is owned by\n * `voiceSessionReducer`, which is pure and tested. That split exists because\n * this file cannot be tested at all in this repo — vitest runs in `node` with\n * no DOM and no audio.\n */\nexport const AssistantVoiceSession: FC<Props> = ({\n session,\n turns = [],\n notice = null,\n spoken,\n onInterrupt,\n onToggleMute,\n onEnd,\n capturing = true,\n}) => {\n const tr = useTr();\n const { phase, muted, error } = session;\n const endRef = useRef<HTMLButtonElement>(null);\n const dialogRef = useRef<HTMLDivElement>(null);\n /**\n * Docked inside the assistant panel by default; full-screen only on request.\n *\n * A voice conversation is usually a glance-and-listen thing, so taking over\n * the whole screen for it is the wrong default — the user loses the page they\n * were asking about. Expanding is opt-in and per-session: reopening starts\n * docked again, which is the behaviour that matches \"default should be the\n * same size as the assistant\".\n */\n /**\n * ★ THREE sizes, not two.\n *\n * The compact controller was added so voice stops taking over the panel — but\n * making it the only docked size removed the in-panel stage that existed\n * before, which is a genuinely useful middle: big enough to read a reply,\n * without losing the page behind it.\n *\n * mini — a strip at the bottom; the assistant panel stays visible\n * panel — fills the assistant panel (what \"docked\" used to mean)\n * full — full screen\n *\n * One button steps mini → panel → full and wraps, with the label always\n * naming where it goes next, so a single control stays predictable.\n */\n const [view, setView] = useState<VoiceView>('mini');\n const expanded = view === 'full';\n const mini = view === 'mini';\n const nextView: VoiceView = view === 'mini' ? 'panel' : view === 'panel' ? 'full' : 'mini';\n /** History is secondary: the stage shows now, this shows the session. */\n const [transcriptOpen, setTranscriptOpen] = useState(false);\n\n // A full-screen `aria-modal` overlay that cannot be dismissed from the\n // keyboard is a trap. Escape ends the session, and focus starts on End so a\n // keyboard or screen-reader user lands somewhere useful rather than behind\n // the overlay.\n // Focus lands on End ONCE, on open. Keeping this in the keydown effect below\n // meant every expand/collapse re-ran it and silently stole focus from the\n // button just pressed — a Space or Enter a beat later would then end the\n // session instead of toggling the size again.\n useEffect(() => {\n endRef.current?.focus();\n }, []);\n\n useEffect(() => {\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n // ★ Escape closes the drawer first. Ending the whole conversation\n // because someone dismissed a panel would be a surprising amount of\n // destruction for one keypress.\n if (transcriptOpen) {\n setTranscriptOpen(false);\n return;\n }\n onEnd();\n return;\n }\n // Trapping focus is only correct when the overlay actually covers\n // everything. Docked, it sits inside the panel and the rest of the page\n // is legitimately reachable, so trapping there would be the bug rather\n // than the fix.\n if (event.key !== 'Tab' || !expanded) return;\n // `aria-modal` only TELLS assistive technology this is modal; it does not\n // make it so. Without this, Tab walks straight out of the overlay into the\n // page behind it, which is still fully interactive underneath — a\n // keyboard user ends up operating a screen they cannot see.\n // ★ Scope the trap to what is actually on screen. With the transcript\n // drawer open, a flat `button` query also collects the controls it covers,\n // so Tab walked into buttons the user could not see — the same class of\n // bug the trap exists to prevent.\n const scope = transcriptOpen\n ? dialogRef.current?.querySelector<HTMLElement>('[data-testid=\"assistant-voice-transcript\"]')\n : dialogRef.current;\n const focusable = scope?.querySelectorAll<HTMLElement>('button:not([disabled])');\n if (!focusable || focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (!first || !last) return;\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n window.addEventListener('keydown', onKeyDown);\n return () => window.removeEventListener('keydown', onKeyDown);\n }, [onEnd, expanded, transcriptOpen]);\n\n // Muted is reported ALONGSIDE the phase, not instead of it: the assistant may\n // still be speaking with the microphone off, and saying only \"Microphone off\"\n // would misreport that.\n const phaseText =\n phase === 'thinking'\n ? tr('healthybowl.assistant.voiceSession.thinking', 'Thinking…')\n : phase === 'speaking'\n ? tr('healthybowl.assistant.voiceSession.speaking', 'Speaking — tap to stop')\n : muted\n ? tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')\n : tr('healthybowl.assistant.voiceSession.listening', 'Listening…');\n\n const status =\n error !== null\n ? errorMessage(error, tr)\n : muted && phase !== 'listening'\n ? `${phaseText} · ${tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')}`\n : phaseText;\n\n // While speaking, the caption shows the REPLY; otherwise what we have heard.\n // Showing the stale transcript under the assistant's own voice reads as a\n // mis-transcription of the assistant, which is worse than showing nothing.\n const heard = spokenSoFar(session);\n\n // ★ ONE state, derived. The reducer's phase cannot tell \"listening\" from\n // \"the microphone has not started yet\", and the old overlay rendered every\n // signal at once — status, warning, transcript, caption and orb together.\n const stage = voiceStageState({ snapshot: session, capturing });\n\n return (\n <div\n ref={dialogRef}\n className={`flex flex-col items-center justify-between bg-bg-sunken ${\n view === 'full'\n ? // ★ Below the app header, not behind it. The header is `z-[100]` and\n // this overlay was `z-[60]` at `inset-0`, so the top 56px sat behind\n // it — and the End button did not merely LOOK hidden, it was\n // unclickable (`elementFromPoint` returned the header). Starting at\n // `top-14` means nothing is ever behind the header, and the header\n // stays usable for orientation.\n 'fixed inset-x-0 bottom-0 top-14 z-[60] px-6 py-8'\n : view === 'panel'\n ? // The in-panel stage: covers the assistant panel, keeps the page.\n 'absolute inset-0 z-20 px-4 py-6'\n : // A strip at the bottom, ~180px, so the panel behind stays visible.\n 'absolute inset-x-0 bottom-0 z-20 h-[11.25rem] border-t border-border-subtle px-3 py-3 shadow-lg'\n }`}\n role=\"dialog\"\n // Only modal when it really is: docked, the page behind stays usable.\n // `undefined` rather than `false` — the ARIA default is already false, and\n // some older assistive technology treats an explicit \"false\" on a dialog\n // as still modal.\n aria-modal={expanded || undefined}\n aria-label={tr('healthybowl.assistant.voiceSession.title', 'Voice conversation')}\n data-testid=\"assistant-voice-session\"\n >\n {/* End sits top-right and expand bottom-left, out of the centre column.\n Absolute rather than part of the flow so the pill stays optically\n centred at both sizes — the overlay is already a positioning context\n (`fixed` when expanded, `absolute` when docked). */}\n <button\n ref={endRef}\n type=\"button\"\n onClick={onEnd}\n className={`absolute ${expanded ? 'right-6 top-6 size-14' : mini ? 'right-2 top-2 size-8' : 'right-3 top-3 size-11'} flex items-center justify-center rounded-full border border-border-default bg-bg-elevated text-text-secondary hover:bg-bg-sunken transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n aria-label={tr('healthybowl.assistant.voiceSession.end', 'End the voice conversation')}\n data-testid=\"assistant-voice-end\"\n >\n <X className={expanded ? 'size-6' : mini ? 'size-4' : 'size-5'} />\n </button>\n\n {/* ★ The notice is CHROME, not conversation. It used to sit above the\n transcript in the same column as the reply, which is why a microphone\n warning read as part of what the assistant said. The status line moved\n into the stage, where it labels the state it belongs to. */}\n <div className={`flex flex-col items-center ${mini ? 'px-3' : 'min-h-[1.5rem] px-14'}`}>\n {notice && error === null ? (\n <p className=\"max-w-xs text-center text-xs text-status-warning\" data-testid=\"assistant-voice-notice\">\n {noticeMessage(notice, tr)}\n </p>\n ) : null}\n </div>\n\n {/* ★ Two genuinely different surfaces, not one scaled. Expanded is a\n reading stage; docked is a controller. */}\n {(() => {\n const orb = (\n <AssistantVoiceOrb\n session={session}\n compact={mini}\n onPress={micIsInterrupt(stage) ? onInterrupt : onToggleMute}\n label={\n micIsInterrupt(stage)\n ? tr('healthybowl.assistant.voiceSession.interrupt', 'Stop the assistant and speak')\n : muted\n ? tr('healthybowl.assistant.voiceSession.unmute', 'Turn the microphone on')\n : tr('healthybowl.assistant.voiceSession.mute', 'Turn the microphone off')\n }\n />\n );\n const caption = micIsInterrupt(stage) ? spoken : heard || null;\n const errorText = error !== null ? errorMessage(error, tr) : null;\n return !mini ? (\n <VoiceStage\n state={stage}\n userCaption={heard || null}\n assistantCaption={spoken}\n expanded\n statusText={status}\n errorText={errorText}\n control={orb}\n />\n ) : (\n <VoiceMiniController\n state={stage}\n caption={caption}\n statusText={status}\n errorText={errorText}\n control={orb}\n />\n );\n })()}\n\n {transcriptOpen ? <VoiceTranscriptDrawer turns={turns} onClose={() => setTranscriptOpen(false)} /> : null}\n\n {/* History is SECONDARY — behind a button, never on the stage. */}\n <button\n type=\"button\"\n onClick={() => setTranscriptOpen((open) => !open)}\n className={`absolute ${expanded ? 'bottom-6 right-6 size-14' : mini ? 'right-11 top-2 size-8' : 'bottom-3 right-3 size-11'} flex items-center justify-center rounded-full bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n aria-pressed={transcriptOpen}\n aria-label={tr('healthybowl.assistant.voiceSession.transcript', 'Voice transcript')}\n data-testid=\"assistant-voice-transcript-toggle\"\n >\n <ScrollText className={expanded ? 'size-6' : mini ? 'size-4' : 'size-5'} />\n </button>\n\n <button\n type=\"button\"\n onClick={() => setView(nextView)}\n className={`absolute ${expanded ? 'bottom-6 left-6 size-14' : mini ? 'left-2 top-2 size-8' : 'bottom-3 left-3 size-11'} flex items-center justify-center rounded-full bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n // Not a toggle any more, so `aria-pressed` would be a lie. The label\n // names where the button GOES, which is what a stepping control needs.\n aria-label={\n nextView === 'panel'\n ? tr('healthybowl.assistant.voiceSession.expandPanel', 'Show the conversation in the panel')\n : nextView === 'full'\n ? tr('healthybowl.assistant.voiceSession.expand', 'Expand the conversation to full screen')\n : tr('healthybowl.assistant.voiceSession.collapse', 'Shrink to the compact controller')\n }\n data-testid=\"assistant-voice-expand\"\n >\n {expanded ? <Minimize2 className=\"size-5\" /> : <Maximize2 className={mini ? 'size-4' : 'size-5'} />}\n </button>\n </div>\n );\n};\n\n/**\n * Recoverable problems, shown WITHOUT ending the session.\n *\n * The bug these exist for: the overlay said \"Listening…\" while the recogniser\n * was dead, and nothing anywhere said otherwise.\n */\nfunction noticeMessage(notice: VoiceSessionNotice, tr: ReturnType<typeof useTr>): string {\n switch (notice) {\n case 'network':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNetwork',\n 'Speech recognition lost its connection. Check your network — it will retry.'\n );\n case 'not-capturing':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNotCapturing',\n 'The microphone did not start. Check that this site is allowed to use it, then try again.'\n );\n case 'recognition-failed':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeRecognitionFailed',\n 'Speech recognition stopped unexpectedly. It will retry — if it keeps happening, reload the page.'\n );\n case 'nothing-heard':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNothingHeard',\n 'Nothing heard yet. Check your microphone is not muted or in use by another app.'\n );\n default: {\n const unhandled: never = notice;\n return unhandled;\n }\n }\n}\n\n/**\n * Every failure is explained rather than silently closing the session.\n *\n * A session that just vanishes is the dead-button bug in another shape — the\n * exact defect BOFF-7106 had to fix on the per-message speak control.\n */\nfunction errorMessage(error: VoiceSessionError, tr: ReturnType<typeof useTr>): string {\n switch (error) {\n case 'mic-denied':\n return tr(\n 'healthybowl.assistant.voiceSession.micDenied',\n 'Microphone access is blocked. Allow it in your browser settings to talk.'\n );\n case 'no-speech-support':\n return tr(\n 'healthybowl.assistant.voiceSession.noSpeechSupport',\n 'This browser cannot listen. Try a different browser, or type instead.'\n );\n case 'no-voice-support':\n return tr(\n 'healthybowl.assistant.voiceSession.noVoiceSupport',\n 'This device has no voice that can speak this language.'\n );\n default: {\n // Exhaustive: adding a variant without copy becomes a build error rather\n // than a silently empty status line.\n const unhandled: never = error;\n return unhandled;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAkDA,IAAa,KAAoC,EAC/C,YACA,WAAQ,CAAC,GACT,YAAS,MACT,WACA,gBACA,iBACA,UACA,eAAY,SACR;CACJ,IAAM,IAAK,EAAM,GACX,EAAE,UAAO,UAAO,aAAU,GAC1B,IAAS,EAA0B,IAAI,GACvC,IAAY,EAAuB,IAAI,GAyBvC,CAAC,GAAM,KAAW,EAAoB,MAAM,GAC5C,IAAW,MAAS,QACpB,IAAO,MAAS,QAChB,IAAsB,MAAS,SAAS,UAAU,MAAS,UAAU,SAAS,QAE9E,CAAC,GAAgB,KAAqB,EAAS,EAAK;CAc1D,AAJA,QAAgB;EACd,EAAO,SAAS,MAAM;CACxB,GAAG,CAAC,CAAC,GAEL,QAAgB;EACd,IAAM,KAAa,MAAyB;GAC1C,IAAI,EAAM,QAAQ,UAAU;IAI1B,IAAI,GAAgB;KAClB,EAAkB,EAAK;KACvB;IACF;IACA,EAAM;IACN;GACF;GAKA,IAAI,EAAM,QAAQ,SAAS,CAAC,GAAU;GAYtC,IAAM,KAHQ,IACV,EAAU,SAAS,cAA2B,8CAA4C,IAC1F,EAAU,UACW,iBAA8B,wBAAwB;GAC/E,IAAI,CAAC,KAAa,EAAU,WAAW,GAAG;GAC1C,IAAM,IAAQ,EAAU,IAClB,IAAO,EAAU,EAAU,SAAS;GACtC,CAAC,KAAS,CAAC,MACX,EAAM,YAAY,SAAS,kBAAkB,KAC/C,EAA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ACF;EACF,KAAK,iBACH,OAAO,EACL,yDACA,0FACF;EACF,KAAK,sBACH,OAAO,EACL,8DACA,kGACF;EACF,KAAK,iBACH,OAAO,EACL,yDACA,iFACF;EACF,SAEE,OAAO;CAEX;AACF;AAQA,SAAS,EAAa,GAA0B,GAAsC;CACpF,QAAQ,GAAR;EACE,KAAK,cACH,OAAO,EACL,gDACA,0EACF;EACF,KAAK,qBACH,OAAO,EACL,sDACA,uEACF;EACF,KAAK,oBACH,OAAO,EACL,qDACA,wDACF;EACF,SAIE,OAAO;CAEX;AACF"}
1
+ {"version":3,"file":"AssistantVoiceSession.js","names":[],"sources":["../../../../src/components/assistant/voice/AssistantVoiceSession.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type FC } from 'react';\nimport { Maximize2, Minimize2, ScrollText, X } from 'lucide-react';\nimport { AssistantVoiceOrb } from './AssistantVoiceOrb';\nimport { VoiceStage } from './VoiceStage';\nimport { VoiceMiniController } from './VoiceMiniController';\nimport { VoiceTranscriptDrawer } from './VoiceTranscriptDrawer';\nimport { voiceStageState, micIsInterrupt } from '../../../utils/voiceStageState';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { spokenSoFar, type VoiceSessionSnapshot } from '../../../utils/voiceSession';\nimport type { VoiceSessionError } from '../../../utils/voiceSession';\nimport type { VoiceSessionNotice } from '../../../hooks/useVoiceSession';\n\n/** How much room the voice session takes: a strip, the panel, or the screen. */\nexport type VoiceView = 'mini' | 'panel' | 'full';\n\ninterface Props {\n session: VoiceSessionSnapshot;\n /** Recent exchanges, oldest first — the running conversation. */\n turns?: ReadonlyArray<{ id: string; role: 'user' | 'assistant'; text: string }>;\n /** Cut the assistant off mid-reply. */\n onInterrupt?: () => void;\n /** A recoverable problem to surface. Null when the microphone is healthy. */\n notice?: VoiceSessionNotice | null;\n /** The assistant's last reply, captioned while it is spoken. */\n spoken: string | null;\n onToggleMute: () => void;\n onEnd: () => void;\n /** Is the recogniser actually running? Distinguishes CONNECTING from LISTENING. */\n capturing?: boolean;\n}\n\n/**\n * Full-screen voice conversation (BOFF-7120).\n *\n * ★ **Voice only, by explicit product decision.** The reference (Gemini Live)\n * also offers camera and screen sharing; those are deliberately absent here.\n * Attaching images is a separate, existing capability of the assistant and\n * stays in the composer, and screen sharing could not work on the primary\n * device anyway — `getDisplayMedia` is unsupported by every iOS browser, so\n * that control would be dead on an iPhone.\n *\n * The controls are therefore the two that a voice conversation actually needs:\n * mute, and end. Anything else would be a button the user has to think about\n * while talking.\n *\n * This component is presentational: every transition is owned by\n * `voiceSessionReducer`, which is pure and tested. That split exists because\n * this file cannot be tested at all in this repo — vitest runs in `node` with\n * no DOM and no audio.\n */\nexport const AssistantVoiceSession: FC<Props> = ({\n session,\n turns = [],\n notice = null,\n spoken,\n onInterrupt,\n onToggleMute,\n onEnd,\n capturing = true,\n}) => {\n const tr = useTr();\n const { phase, muted, error } = session;\n const endRef = useRef<HTMLButtonElement>(null);\n const dialogRef = useRef<HTMLDivElement>(null);\n /**\n * Docked inside the assistant panel by default; full-screen only on request.\n *\n * A voice conversation is usually a glance-and-listen thing, so taking over\n * the whole screen for it is the wrong default — the user loses the page they\n * were asking about. Expanding is opt-in and per-session: reopening starts\n * docked again, which is the behaviour that matches \"default should be the\n * same size as the assistant\".\n */\n /**\n * ★ THREE sizes, not two.\n *\n * The compact controller was added so voice stops taking over the panel — but\n * making it the only docked size removed the in-panel stage that existed\n * before, which is a genuinely useful middle: big enough to read a reply,\n * without losing the page behind it.\n *\n * mini — a strip at the bottom; the assistant panel stays visible\n * panel — fills the assistant panel (what \"docked\" used to mean)\n * full — full screen\n *\n * One button steps mini → panel → full and wraps, with the label always\n * naming where it goes next, so a single control stays predictable.\n */\n const [view, setView] = useState<VoiceView>('mini');\n const expanded = view === 'full';\n const mini = view === 'mini';\n const nextView: VoiceView = view === 'mini' ? 'panel' : view === 'panel' ? 'full' : 'mini';\n /** History is secondary: the stage shows now, this shows the session. */\n const [transcriptOpen, setTranscriptOpen] = useState(false);\n\n // A full-screen `aria-modal` overlay that cannot be dismissed from the\n // keyboard is a trap. Escape ends the session, and focus starts on End so a\n // keyboard or screen-reader user lands somewhere useful rather than behind\n // the overlay.\n // Focus lands on End ONCE, on open. Keeping this in the keydown effect below\n // meant every expand/collapse re-ran it and silently stole focus from the\n // button just pressed — a Space or Enter a beat later would then end the\n // session instead of toggling the size again.\n useEffect(() => {\n endRef.current?.focus();\n }, []);\n\n useEffect(() => {\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n // ★ Escape closes the drawer first. Ending the whole conversation\n // because someone dismissed a panel would be a surprising amount of\n // destruction for one keypress.\n if (transcriptOpen) {\n setTranscriptOpen(false);\n return;\n }\n onEnd();\n return;\n }\n // Trapping focus is only correct when the overlay actually covers\n // everything. Docked, it sits inside the panel and the rest of the page\n // is legitimately reachable, so trapping there would be the bug rather\n // than the fix.\n if (event.key !== 'Tab' || !expanded) return;\n // `aria-modal` only TELLS assistive technology this is modal; it does not\n // make it so. Without this, Tab walks straight out of the overlay into the\n // page behind it, which is still fully interactive underneath — a\n // keyboard user ends up operating a screen they cannot see.\n // ★ Scope the trap to what is actually on screen. With the transcript\n // drawer open, a flat `button` query also collects the controls it covers,\n // so Tab walked into buttons the user could not see — the same class of\n // bug the trap exists to prevent.\n const scope = transcriptOpen\n ? dialogRef.current?.querySelector<HTMLElement>('[data-testid=\"assistant-voice-transcript\"]')\n : dialogRef.current;\n const focusable = scope?.querySelectorAll<HTMLElement>('button:not([disabled])');\n if (!focusable || focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (!first || !last) return;\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n window.addEventListener('keydown', onKeyDown);\n return () => window.removeEventListener('keydown', onKeyDown);\n }, [onEnd, expanded, transcriptOpen]);\n\n // Muted is reported ALONGSIDE the phase, not instead of it: the assistant may\n // still be speaking with the microphone off, and saying only \"Microphone off\"\n // would misreport that.\n const phaseText =\n phase === 'thinking'\n ? tr('healthybowl.assistant.voiceSession.thinking', 'Thinking…')\n : phase === 'speaking'\n ? tr('healthybowl.assistant.voiceSession.speaking', 'Speaking — tap to stop')\n : muted\n ? tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')\n : tr('healthybowl.assistant.voiceSession.listening', 'Listening…');\n\n const status =\n error !== null\n ? errorMessage(error, tr)\n : muted && phase !== 'listening'\n ? `${phaseText} · ${tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')}`\n : phaseText;\n\n // While speaking, the caption shows the REPLY; otherwise what we have heard.\n // Showing the stale transcript under the assistant's own voice reads as a\n // mis-transcription of the assistant, which is worse than showing nothing.\n const heard = spokenSoFar(session);\n\n // ★ ONE state, derived. The reducer's phase cannot tell \"listening\" from\n // \"the microphone has not started yet\", and the old overlay rendered every\n // signal at once — status, warning, transcript, caption and orb together.\n const stage = voiceStageState({ snapshot: session, capturing });\n\n return (\n <div\n ref={dialogRef}\n className={`flex flex-col items-center justify-between bg-bg-sunken ${\n view === 'full'\n ? // ★ Below the app header, not behind it. The header is `z-[100]` and\n // this overlay was `z-[60]` at `inset-0`, so the top 56px sat behind\n // it — and the End button did not merely LOOK hidden, it was\n // unclickable (`elementFromPoint` returned the header). Starting at\n // `top-14` means nothing is ever behind the header, and the header\n // stays usable for orientation.\n 'fixed inset-x-0 bottom-0 top-14 z-[60] px-6 py-8'\n : view === 'panel'\n ? // The in-panel stage: covers the assistant panel, keeps the page.\n 'absolute inset-0 z-20 px-4 py-6'\n : // A strip at the bottom, ~180px, so the panel behind stays visible.\n 'absolute inset-x-0 bottom-0 z-20 h-[11.25rem] border-t border-border-subtle px-3 py-3 shadow-lg'\n }`}\n role=\"dialog\"\n // Only modal when it really is: docked, the page behind stays usable.\n // `undefined` rather than `false` — the ARIA default is already false, and\n // some older assistive technology treats an explicit \"false\" on a dialog\n // as still modal.\n aria-modal={expanded || undefined}\n aria-label={tr('healthybowl.assistant.voiceSession.title', 'Voice conversation')}\n data-testid=\"assistant-voice-session\"\n >\n {/* End sits top-right and expand bottom-left, out of the centre column.\n Absolute rather than part of the flow so the pill stays optically\n centred at both sizes — the overlay is already a positioning context\n (`fixed` when expanded, `absolute` when docked). */}\n <button\n ref={endRef}\n type=\"button\"\n onClick={onEnd}\n className={`absolute ${expanded ? 'right-6 top-6 size-14' : mini ? 'right-2 top-2 size-8' : 'right-3 top-3 size-11'} flex items-center justify-center rounded-full border border-border-default bg-bg-elevated text-text-secondary hover:bg-bg-sunken transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n aria-label={tr('healthybowl.assistant.voiceSession.end', 'End the voice conversation')}\n data-testid=\"assistant-voice-end\"\n >\n <X className={expanded ? 'size-6' : mini ? 'size-4' : 'size-5'} />\n </button>\n\n {/* ★ The notice is CHROME, not conversation. It used to sit above the\n transcript in the same column as the reply, which is why a microphone\n warning read as part of what the assistant said. The status line moved\n into the stage, where it labels the state it belongs to. */}\n <div className={`flex flex-col items-center ${mini ? 'px-3' : 'min-h-[1.5rem] px-14'}`}>\n {notice && error === null ? (\n <p className=\"max-w-xs text-center text-xs text-status-warning\" data-testid=\"assistant-voice-notice\">\n {noticeMessage(notice, tr)}\n </p>\n ) : null}\n </div>\n\n {/* ★ Two genuinely different surfaces, not one scaled. Expanded is a\n reading stage; docked is a controller. */}\n {(() => {\n const orb = (\n <AssistantVoiceOrb\n session={session}\n compact={mini}\n onPress={micIsInterrupt(stage) ? onInterrupt : onToggleMute}\n label={\n micIsInterrupt(stage)\n ? tr('healthybowl.assistant.voiceSession.interrupt', 'Stop the assistant and speak')\n : muted\n ? tr('healthybowl.assistant.voiceSession.unmute', 'Turn the microphone on')\n : tr('healthybowl.assistant.voiceSession.mute', 'Turn the microphone off')\n }\n />\n );\n const caption = micIsInterrupt(stage) ? spoken : heard || null;\n const errorText = error !== null ? errorMessage(error, tr) : null;\n return !mini ? (\n <VoiceStage\n state={stage}\n userCaption={heard || null}\n assistantCaption={spoken}\n // ★ `expanded` — the JSX shorthand — means `expanded={true}`, not\n // `expanded={expanded}`. This branch serves BOTH the docked panel and\n // full screen, so the panel was being styled as full screen: the\n // 34rem measure and the 24-34px caption clamp applied in a column far\n // too narrow for them, and VoiceCaption's non-expanded branch became\n // unreachable code. The variable it shadowed is right there on line 90.\n expanded={expanded}\n statusText={status}\n errorText={errorText}\n control={orb}\n />\n ) : (\n <VoiceMiniController\n state={stage}\n caption={caption}\n statusText={status}\n errorText={errorText}\n control={orb}\n />\n );\n })()}\n\n {transcriptOpen ? <VoiceTranscriptDrawer turns={turns} onClose={() => setTranscriptOpen(false)} /> : null}\n\n {/* History is SECONDARY — behind a button, never on the stage. */}\n <button\n type=\"button\"\n onClick={() => setTranscriptOpen((open) => !open)}\n className={`absolute ${expanded ? 'bottom-6 right-6 size-14' : mini ? 'right-11 top-2 size-8' : 'bottom-3 right-3 size-11'} flex items-center justify-center rounded-full bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n aria-pressed={transcriptOpen}\n aria-label={tr('healthybowl.assistant.voiceSession.transcript', 'Voice transcript')}\n data-testid=\"assistant-voice-transcript-toggle\"\n >\n <ScrollText className={expanded ? 'size-6' : mini ? 'size-4' : 'size-5'} />\n </button>\n\n <button\n type=\"button\"\n onClick={() => setView(nextView)}\n className={`absolute ${expanded ? 'bottom-6 left-6 size-14' : mini ? 'left-2 top-2 size-8' : 'bottom-3 left-3 size-11'} flex items-center justify-center rounded-full bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n // Not a toggle any more, so `aria-pressed` would be a lie. The label\n // names where the button GOES, which is what a stepping control needs.\n aria-label={\n nextView === 'panel'\n ? tr('healthybowl.assistant.voiceSession.expandPanel', 'Show the conversation in the panel')\n : nextView === 'full'\n ? tr('healthybowl.assistant.voiceSession.expand', 'Expand the conversation to full screen')\n : tr('healthybowl.assistant.voiceSession.collapse', 'Shrink to the compact controller')\n }\n data-testid=\"assistant-voice-expand\"\n >\n {expanded ? <Minimize2 className=\"size-5\" /> : <Maximize2 className={mini ? 'size-4' : 'size-5'} />}\n </button>\n </div>\n );\n};\n\n/**\n * Recoverable problems, shown WITHOUT ending the session.\n *\n * The bug these exist for: the overlay said \"Listening…\" while the recogniser\n * was dead, and nothing anywhere said otherwise.\n */\nfunction noticeMessage(notice: VoiceSessionNotice, tr: ReturnType<typeof useTr>): string {\n switch (notice) {\n case 'network':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNetwork',\n 'Speech recognition lost its connection. Check your network — it will retry.'\n );\n case 'not-capturing':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNotCapturing',\n 'The microphone did not start. Check that this site is allowed to use it, then try again.'\n );\n case 'recognition-failed':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeRecognitionFailed',\n 'Speech recognition stopped unexpectedly. It will retry — if it keeps happening, reload the page.'\n );\n case 'nothing-heard':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNothingHeard',\n 'Nothing heard yet. Check your microphone is not muted or in use by another app.'\n );\n default: {\n const unhandled: never = notice;\n return unhandled;\n }\n }\n}\n\n/**\n * Every failure is explained rather than silently closing the session.\n *\n * A session that just vanishes is the dead-button bug in another shape — the\n * exact defect BOFF-7106 had to fix on the per-message speak control.\n */\nfunction errorMessage(error: VoiceSessionError, tr: ReturnType<typeof useTr>): string {\n switch (error) {\n case 'mic-denied':\n return tr(\n 'healthybowl.assistant.voiceSession.micDenied',\n 'Microphone access is blocked. Allow it in your browser settings to talk.'\n );\n case 'no-speech-support':\n return tr(\n 'healthybowl.assistant.voiceSession.noSpeechSupport',\n 'This browser cannot listen. Try a different browser, or type instead.'\n );\n case 'no-voice-support':\n return tr(\n 'healthybowl.assistant.voiceSession.noVoiceSupport',\n 'This device has no voice that can speak this language.'\n );\n default: {\n // Exhaustive: adding a variant without copy becomes a build error rather\n // than a silently empty status line.\n const unhandled: never = error;\n return unhandled;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAkDA,IAAa,KAAoC,EAC/C,YACA,WAAQ,CAAC,GACT,YAAS,MACT,WACA,gBACA,iBACA,UACA,eAAY,SACR;CACJ,IAAM,IAAK,EAAM,GACX,EAAE,UAAO,UAAO,aAAU,GAC1B,IAAS,EAA0B,IAAI,GACvC,IAAY,EAAuB,IAAI,GAyBvC,CAAC,GAAM,KAAW,EAAoB,MAAM,GAC5C,IAAW,MAAS,QACpB,IAAO,MAAS,QAChB,IAAsB,MAAS,SAAS,UAAU,MAAS,UAAU,SAAS,QAE9E,CAAC,GAAgB,KAAqB,EAAS,EAAK;CAc1D,AAJA,QAAgB;EACd,EAAO,SAAS,MAAM;CACxB,GAAG,CAAC,CAAC,GAEL,QAAgB;EACd,IAAM,KAAa,MAAyB;GAC1C,IAAI,EAAM,QAAQ,UAAU;IAI1B,IAAI,GAAgB;KAClB,EAAkB,EAAK;KACvB;IACF;IACA,EAAM;IACN;GACF;GAKA,IAAI,EAAM,QAAQ,SAAS,CAAC,GAAU;GAYtC,IAAM,KAHQ,IACV,EAAU,SAAS,cAA2B,8CAA4C,IAC1F,EAAU,UACW,iBAA8B,wBAAwB;GAC/E,IAAI,CAAC,KAAa,EAAU,WAAW,GAAG;GAC1C,IAAM,IAAQ,EAAU,IAClB,IAAO,EAAU,EAAU,SAAS;GACtC,CAAC,KAAS,CAAC,MACX,EAAM,YAAY,SAAS,kBAAkB,KAC/C,EAAM,eAAe,GACrB,EAAK,MAAM,KACF,CAAC,EAAM,YAAY,SAAS,kBAAkB,MACvD,EAAM,eAAe,GACrB,EAAM,MAAM;EAEhB;EAEA,OADA,OAAO,iBAAiB,WAAW,CAAS,SAC/B,OAAO,oBAAoB,WAAW,CAAS;CAC9D,GAAG;EAAC;EAAO;EAAU;CAAc,CAAC;CAKpC,IAAM,IACJ,MAAU,aACN,E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OAAO,EACL,sDACA,uEACF;EACF,KAAK,oBACH,OAAO,EACL,qDACA,wDACF;EACF,SAIE,OAAO;CAEX;AACF"}
@@ -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;IAET;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
+ {"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,CAGT,+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"}
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: `![alt](src)` 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,IAA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AAC,GAMM,EACL,EACG,KAAK,IAAI,EACT,QAAQ,WAAW,MAAM,EACzB,KAAK,GACR,CACF;AACF"}
@@ -2,13 +2,16 @@
2
2
  function e(e) {
3
3
  return e.metadata?.voice === !0;
4
4
  }
5
- function t(t) {
6
- return t.filter((t) => !e(t));
5
+ function t(e) {
6
+ return e === !0 ? { voice: !0 } : {};
7
7
  }
8
8
  function n(t) {
9
+ return t.filter((t) => !e(t));
10
+ }
11
+ function r(t) {
9
12
  return t.filter(e);
10
13
  }
11
14
  //#endregion
12
- export { t as chatTurns, n as voiceTurnsOnly };
15
+ export { n as chatTurns, t as voiceMarker, r as voiceTurnsOnly };
13
16
 
14
17
  //# sourceMappingURL=voiceTurnVisibility.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"voiceTurnVisibility.js","names":[],"sources":["../../src/utils/voiceTurnVisibility.ts"],"sourcesContent":["/**\n * Which surface does a turn belong to?\n *\n * Voice and chat share ONE conversation: the live session was built as an\n * overlay over the chat thread, so `submitVoiceTurn` calls the same `handleSend`\n * the composer does and both write into the same persisted `messages` array.\n * That is why every spoken exchange appeared in the typed thread, and why the\n * voice panel painted the last six messages of the whole conversation —\n * including typed replies full of `##` and `**`, which it renders as literal\n * text.\n *\n * One marker fixes both directions:\n * - the chat panel hides turns that happened in voice\n * - the voice panel shows ONLY turns that happened in voice\n *\n * ★ Deliberately a display split, not separate persistence. It survives a\n * reload because the chat transcript is never rehydrated from the backend — the\n * store is the only source of truth for what either panel shows. The backend\n * session is still shared, so the model keeps full context of the conversation\n * across both surfaces, which is what makes \"carry on where we left off\" work.\n * Genuinely separate backend sessions are a larger change and would cost that.\n */\n\ninterface TurnLike {\n metadata?: ({ voice?: boolean } & Record<string, unknown>) | undefined;\n}\n\n/** True when this turn happened inside a live voice session. */\nexport function isVoiceTurn(message: TurnLike): boolean {\n return message.metadata?.voice === true;\n}\n\n/**\n * The turns the CHAT panel should show: everything that was not spoken.\n *\n * Untagged turns are treated as chat, so every conversation recorded before the\n * marker existed keeps rendering exactly as it did.\n */\nexport function chatTurns<T extends TurnLike>(messages: readonly T[]): T[] {\n return messages.filter((message) => !isVoiceTurn(message));\n}\n\n/**\n * The turns the VOICE panel should show: only what was spoken.\n *\n * This is also what scopes the voice transcript to the session. Previously it\n * took the last six messages of the whole conversation, so opening voice on an\n * existing thread immediately painted typed replies — the wall of raw markdown\n * in the operator's screenshot.\n */\nexport function voiceTurnsOnly<T extends TurnLike>(messages: readonly T[]): T[] {\n return messages.filter(isVoiceTurn);\n}\n"],"mappings":";AA4BA,SAAgB,EAAY,GAA4B;CACtD,OAAO,EAAQ,UAAU,UAAU;AACrC;AAQA,SAAgB,EAA8B,GAA6B;CACzE,OAAO,EAAS,QAAQ,MAAY,CAAC,EAAY,CAAO,CAAC;AAC3D;AAUA,SAAgB,EAAmC,GAA6B;CAC9E,OAAO,EAAS,OAAO,CAAW;AACpC"}
1
+ {"version":3,"file":"voiceTurnVisibility.js","names":[],"sources":["../../src/utils/voiceTurnVisibility.ts"],"sourcesContent":["/**\n * Which surface does a turn belong to?\n *\n * Voice and chat share ONE conversation: the live session was built as an\n * overlay over the chat thread, so `submitVoiceTurn` calls the same `handleSend`\n * the composer does and both write into the same persisted `messages` array.\n * That is why every spoken exchange appeared in the typed thread, and why the\n * voice panel painted the last six messages of the whole conversation —\n * including typed replies full of `##` and `**`, which it renders as literal\n * text.\n *\n * One marker fixes both directions:\n * - the chat panel hides turns that happened in voice\n * - the voice panel shows ONLY turns that happened in voice\n *\n * ★ Deliberately a display split, not separate persistence. It survives a\n * reload because the chat transcript is never rehydrated from the backend — the\n * store is the only source of truth for what either panel shows. The backend\n * session is still shared, so the model keeps full context of the conversation\n * across both surfaces, which is what makes \"carry on where we left off\" work.\n * Genuinely separate backend sessions are a larger change and would cost that.\n */\n\ninterface TurnLike {\n metadata?: ({ voice?: boolean } & Record<string, unknown>) | undefined;\n}\n\n/** True when this turn happened inside a live voice session. */\nexport function isVoiceTurn(message: TurnLike): boolean {\n return message.metadata?.voice === true;\n}\n\n/**\n * The marker as a fragment to spread into a message's `metadata`.\n *\n * ★ `patchMessage` REPLACES `metadata` instead of merging it, so every write\n * that rebuilds the object has to re-assert this or the turn silently demotes\n * itself to a chat turn. That is exactly what shipped: the marker was stamped\n * at creation and destroyed the instant the reply completed, so a spoken answer\n * appeared in the typed thread AND disappeared from the voice transcript at the\n * same moment — the transcript could only ever show the user's questions.\n *\n * Spreading one helper at all four sites is what keeps them from drifting;\n * `voiceMarkerCallSitesAreComplete` in the test file fails the build if a new\n * metadata write forgets it.\n *\n * Takes the raw `dictated` flag rather than a boolean so call sites can pass\n * `options.dictated` straight through — an explicit `=== true` here means an\n * absent flag can never be mistaken for a voice turn.\n */\nexport function voiceMarker(dictated: boolean | undefined): { voice?: true } {\n return dictated === true ? { voice: true } : {};\n}\n\n/**\n * The turns the CHAT panel should show: everything that was not spoken.\n *\n * Untagged turns are treated as chat, so every conversation recorded before the\n * marker existed keeps rendering exactly as it did.\n */\nexport function chatTurns<T extends TurnLike>(messages: readonly T[]): T[] {\n return messages.filter((message) => !isVoiceTurn(message));\n}\n\n/**\n * The turns the VOICE panel should show: only what was spoken.\n *\n * This is also what scopes the voice transcript to the session. Previously it\n * took the last six messages of the whole conversation, so opening voice on an\n * existing thread immediately painted typed replies — the wall of raw markdown\n * in the operator's screenshot.\n */\nexport function voiceTurnsOnly<T extends TurnLike>(messages: readonly T[]): T[] {\n return messages.filter(isVoiceTurn);\n}\n"],"mappings":";AA4BA,SAAgB,EAAY,GAA4B;CACtD,OAAO,EAAQ,UAAU,UAAU;AACrC;AAoBA,SAAgB,EAAY,GAAiD;CAC3E,OAAO,MAAa,KAAO,EAAE,OAAO,GAAK,IAAI,CAAC;AAChD;AAQA,SAAgB,EAA8B,GAA6B;CACzE,OAAO,EAAS,QAAQ,MAAY,CAAC,EAAY,CAAO,CAAC;AAC3D;AAUA,SAAgB,EAAmC,GAA6B;CAC9E,OAAO,EAAS,OAAO,CAAW;AACpC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/microfe-healthybowl",
3
- "version": "2026.901.13",
3
+ "version": "2026.901.15",
4
4
  "description": "Burdenoff HealthyBowl Microfrontend - Comprehensive organic farming and agro-foods management platform",
5
5
  "type": "module",
6
6
  "files": [