@burdenoff/microfe-healthybowl 2026.901.2 → 2026.901.4

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.
@@ -20,9 +20,10 @@ import { dispatchAssistantQuotaExhausted as ue, notifyAiCreditsUpdated as de } f
20
20
  import { buildPromptForMode as fe } from "../../utils/assistantPrompt.js";
21
21
  import { isMultimodalBodyRejection as pe, isRecoverableAssistantError as me } from "../../utils/assistantTransportErrors.js";
22
22
  import { pollDelayMs as he } from "../../utils/assistantPollSchedule.js";
23
- import { useCallback as T, useEffect as E, useMemo as D, useRef as ge, useState as _e } from "react";
23
+ import { createReadinessTracker as ge } from "../../utils/sandboxReadiness.js";
24
+ import { useCallback as T, useEffect as E, useMemo as D, useRef as O, useState as _e } from "react";
24
25
  import { useI18n as ve } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
25
- import { jsx as O, jsxs as ye } from "react/jsx-runtime";
26
+ import { jsx as k, jsxs as ye } from "react/jsx-runtime";
26
27
  import { useGatewayClient as be } from "@burdenoff/fe-libs/shared/graphql";
27
28
  import { useAuthToken as xe } from "@burdenoff/fe-libs/shared/providers/shell";
28
29
  import { getAssistantMedia as Se } from "@burdenoff/fe-libs/shared/assistant";
@@ -39,25 +40,25 @@ function Te() {
39
40
  function Ee(e) {
40
41
  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]");
41
42
  }
42
- function k(e) {
43
+ function A(e) {
43
44
  return e.info?.time?.created ?? 0;
44
45
  }
45
- function A(e) {
46
+ function j(e) {
46
47
  return (e ?? []).filter((e) => e.type === "text" && typeof e.text == "string").map((e) => e.text?.trim() ?? "").filter(Boolean).join("\n");
47
48
  }
48
- function j(e) {
49
+ function M(e) {
49
50
  return (e ?? []).filter((e) => e.type === "tool" && e.tool).map((e) => {
50
51
  let t = e.state?.status ?? "running", n = e.tool ?? "tool";
51
52
  return t === "completed" ? `Completed: ${n}` : t === "failed" ? `Failed: ${n}` : `Running: ${n}`;
52
53
  });
53
54
  }
54
55
  function De(e, t) {
55
- let n = e.filter((e) => e.info?.role === "assistant" && k(e) > t).sort((e, t) => k(e) - k(t));
56
+ let n = e.filter((e) => e.info?.role === "assistant" && A(e) > t).sort((e, t) => A(e) - A(t));
56
57
  if (n.length === 0) return {
57
58
  content: "Thinking...",
58
59
  done: !1
59
60
  };
60
- let r = n[n.length - 1], i = A(r.parts), a = Se(r.parts), o = j(r.parts);
61
+ let r = n[n.length - 1], i = j(r.parts), a = Se(r.parts), o = M(r.parts);
61
62
  return {
62
63
  content: [
63
64
  i,
@@ -76,64 +77,65 @@ function Oe(e) {
76
77
  default: return "";
77
78
  }
78
79
  }
79
- var M = ({ visible: Se = !0 }) => {
80
- let A = t(), j = be("workspace"), { getAccessToken: M, getWorkspaceToken: ke, userId: Ae } = xe(), { locale: N } = ve(), P = e((e) => e.assistantLanguage), je = D(() => g(P, N).english, [P, N]), Me = h(P) !== null, Ne = D(() => g(P, N).code, [P, N]), { conversations: Pe, activeConversationId: F, mode: I, processingByConversationId: Fe, setMode: L, setConversationMode: R, setActiveConversation: Ie, createConversation: z, addMessage: B, updateMessage: Le, patchMessage: V, setConversationProcessing: H, clearConversationProcessing: Re, setBackendSessionId: ze, clearBackendSessionId: U, setSandbox: W, clearSandbox: Be, acknowledgeApiCalls: Ve } = e(), G = Pe.find((e) => e.id === F)?.messages ?? [], K = F ? Fe[F] : void 0, q = _(K?.status), He = q ? K?.messageId ?? null : null, Ue = K?.status === "error" ? K.messageId : null, { canUseApiCalls: J, loading: We } = ce(y()), Ge = D(() => S.filter((e) => !e.requiresAdmin || J), [J]), [Ke, qe] = _e(null), Je = ge({}), Ye = ge(/* @__PURE__ */ new Set());
80
+ var N = ({ visible: Se = !0 }) => {
81
+ let j = t(), M = be("workspace"), { getAccessToken: N, getWorkspaceToken: ke, userId: Ae } = xe(), { locale: P } = ve(), F = e((e) => e.assistantLanguage), je = D(() => g(F, P).english, [F, P]), Me = h(F) !== null, Ne = D(() => g(F, P).code, [F, P]), { conversations: Pe, activeConversationId: I, mode: L, processingByConversationId: Fe, setMode: R, setConversationMode: z, setActiveConversation: Ie, createConversation: B, addMessage: Le, updateMessage: Re, patchMessage: V, setConversationProcessing: H, clearConversationProcessing: ze, setBackendSessionId: Be, clearBackendSessionId: U, setSandbox: W, clearSandbox: Ve, acknowledgeApiCalls: He } = e(), G = Pe.find((e) => e.id === I)?.messages ?? [], K = I ? Fe[I] : void 0, q = _(K?.status), Ue = q ? K?.messageId ?? null : null, We = K?.status === "error" ? K.messageId : null, { canUseApiCalls: J, loading: Ge } = ce(y()), Ke = D(() => S.filter((e) => !e.requiresAdmin || J), [J]), [qe, Je] = _e(null), Ye = O({}), Y = O(ge()), Xe = O(/* @__PURE__ */ new Set());
81
82
  E(() => {
82
- if (We) return;
83
- let e = S.find((e) => e.id === I);
84
- (!e || e.requiresAdmin && !J) && I !== "assistant" && L("assistant");
83
+ if (Ge) return;
84
+ let e = S.find((e) => e.id === L);
85
+ (!e || e.requiresAdmin && !J) && L !== "assistant" && R("assistant");
85
86
  }, [
86
- I,
87
+ L,
87
88
  J,
88
- We,
89
- L
89
+ Ge,
90
+ R
90
91
  ]);
91
- let Y = T((e, t, n, r) => {
92
- H(e, n, t, null), r ? Le(e, t, r) : Le(e, t, Oe(n));
93
- }, [H, Le]), Xe = T(async (t, n, a, s, c) => {
92
+ let X = T((e, t, n, r) => {
93
+ H(e, n, t, null), r ? Re(e, t, r) : Re(e, t, Oe(n));
94
+ }, [H, Re]), Ze = T(async (t, n, a, s, c) => {
94
95
  let u = e.getState().sandboxesByMode[a]?.sandboxId ?? null, d = async (e) => {
96
+ if (Y.current.isFresh(e)) return !0;
95
97
  try {
96
- return await p(j, e, s, c, 3e5, (e) => Y(t, n, "provisioning", e)), await f(j, e, s, c, 9e4, (e) => Y(t, n, "connecting", e)), !0;
98
+ return await p(M, e, s, c, 3e5, (e) => X(t, n, "provisioning", e)), await f(M, e, s, c, 9e4, (e) => X(t, n, "connecting", e)), Y.current.markVerified(e), !0;
97
99
  } catch {
98
- return !1;
100
+ return Y.current.invalidate(e), !1;
99
101
  }
100
102
  };
101
- if (u && (W(a, u, "provisioning"), Y(t, n, "provisioning", "Reusing assistant environment..."), await d(u) || (W(a, null, "provisioning"), u = null)), !u) {
102
- Y(t, n, "provisioning", "Looking for existing environment...");
103
- let e = await o(j, s, a, c);
104
- e && (W(a, e, "provisioning"), Y(t, n, "provisioning", "Reusing assistant environment..."), await d(e) ? u = e : W(a, null, "provisioning"));
103
+ if (u && (W(a, u, "provisioning"), X(t, n, "provisioning", "Reusing assistant environment..."), await d(u) || (W(a, null, "provisioning"), u = null)), !u) {
104
+ X(t, n, "provisioning", "Looking for existing environment...");
105
+ let e = await o(M, s, a, c);
106
+ e && (W(a, e, "provisioning"), X(t, n, "provisioning", "Reusing assistant environment..."), await d(e) ? u = e : W(a, null, "provisioning"));
105
107
  }
106
108
  if (!u) {
107
- if (a === "api-calls" && !M()) throw Error("API Calls mode requires an authenticated session. Please sign in again.");
108
- Y(t, n, "provisioning", "Starting assistant environment..."), W(a, null, "provisioning"), u = await r(j, a, s, c), W(a, u, "provisioning"), await p(j, u, s, c, 3e5, (e) => Y(t, n, "provisioning", e)), await f(j, u, s, c, 9e4, (e) => Y(t, n, "connecting", e));
109
+ if (a === "api-calls" && !N()) throw Error("API Calls mode requires an authenticated session. Please sign in again.");
110
+ X(t, n, "provisioning", "Starting assistant environment..."), W(a, null, "provisioning"), u = await r(M, a, s, c), W(a, u, "provisioning"), await p(M, u, s, c, 3e5, (e) => X(t, n, "provisioning", e)), await f(M, u, s, c, 9e4, (e) => X(t, n, "connecting", e));
109
111
  }
110
112
  W(a, u, "running");
111
113
  let m = e.getState().conversations.find((e) => e.id === t)?.backendSessionId ?? null;
112
114
  if (m) try {
113
- let e = await l(j, u, s, m, c);
115
+ let e = await l(M, u, s, m, c);
114
116
  if (e.mode !== a) throw Error(`Session mode mismatch: expected ${a}, received ${e.mode}`);
115
117
  } catch {
116
118
  U(t), m = null;
117
119
  }
118
- return m || (Y(t, n, "connecting", "Preparing session..."), m = (await i(j, u, s, a, c)).sessionId, ze(t, m)), {
120
+ return m || (X(t, n, "connecting", "Preparing session..."), m = (await i(M, u, s, a, c)).sessionId, Be(t, m)), {
119
121
  sandboxId: u,
120
122
  sessionId: m
121
123
  };
122
124
  }, [
123
- j,
124
- U,
125
125
  M,
126
- ze,
126
+ U,
127
+ N,
128
+ Be,
127
129
  W,
128
- Y
129
- ]), X = T(async (t, r = [], i = {}) => {
130
- let o = e.getState(), l = o.activeConversationId ?? F;
131
- if (l && (_(o.processingByConversationId[l]?.status) || Ye.current.has(l))) return;
132
- let f = o.mode, p = F, h = p ? e.getState().conversations.find((e) => e.id === p) : void 0;
133
- if (p ? h && h.mode !== f && (h.messages.length > 0 || h.backendSessionId) ? p = z(void 0, f) : h && h.mode !== f && R(p, f) : p = z(void 0, f), !p) return;
134
- Je.current[p] = r;
130
+ X
131
+ ]), Z = T(async (t, r = [], i = {}) => {
132
+ let o = e.getState(), l = o.activeConversationId ?? I;
133
+ if (l && (_(o.processingByConversationId[l]?.status) || Xe.current.has(l))) return;
134
+ let f = o.mode, p = I, h = p ? e.getState().conversations.find((e) => e.id === p) : void 0;
135
+ if (p ? h && h.mode !== f && (h.messages.length > 0 || h.backendSessionId) ? p = B(void 0, f) : h && h.mode !== f && z(p, f) : p = B(void 0, f), !p) return;
136
+ Ye.current[p] = r;
135
137
  let g = ee(), v = {
136
- accessToken: M(),
138
+ accessToken: N(),
137
139
  workspaceToken: ke(),
138
140
  userId: Ae,
139
141
  organizationId: y()
@@ -144,9 +146,9 @@ var M = ({ visible: Se = !0 }) => {
144
146
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
145
147
  metadata: r.length ? { attachments: r.map(ae) } : void 0
146
148
  };
147
- B(p, b);
149
+ Le(p, b);
148
150
  let x = Te();
149
- B(p, {
151
+ Le(p, {
150
152
  id: x,
151
153
  role: "assistant",
152
154
  content: "",
@@ -167,7 +169,7 @@ var M = ({ visible: Se = !0 }) => {
167
169
  }, C = async (e = 1) => {
168
170
  let o = !1;
169
171
  try {
170
- await n(j, g, v);
172
+ await n(M, g, v);
171
173
  } catch (e) {
172
174
  if (le(e)) {
173
175
  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);
@@ -176,90 +178,90 @@ var M = ({ visible: Se = !0 }) => {
176
178
  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);
177
179
  }
178
180
  try {
179
- let { sandboxId: e, sessionId: n } = await Xe(p, x, f, g, v), l = (await c(j, e, g, n, v, 50).catch(() => [])).reduce((e, t) => Math.max(e, k(t)), 0);
180
- Y(p, x, "streaming", "Thinking...");
181
+ let { sandboxId: e, sessionId: n } = await Ze(p, x, f, g, v), l = (await c(M, e, g, n, v, 50).catch(() => [])).reduce((e, t) => Math.max(e, A(t)), 0);
182
+ X(p, x, "streaming", "Thinking...");
181
183
  let h = fe(f, ne(t, r), je, Me, i.dictated === !0), _ = te(h, r), y = ie(_), ee = y > 0, ae = m();
182
184
  o = re(r) > y;
183
185
  try {
184
- await d(j, e, g, n, h, f, ae, v, _);
186
+ await d(M, e, g, n, h, f, ae, v, _);
185
187
  } catch (t) {
186
188
  if (!_ || !pe(t)) throw t;
187
- await d(j, e, g, n, h, f, ae, v, void 0), o ||= ee;
189
+ await d(M, e, g, n, h, f, ae, v, void 0), o ||= ee;
188
190
  }
189
191
  let b = De([], l), C = Date.now() + (Ce[f] ?? we), w = Date.now(), oe = Date.now();
190
- for (; Date.now() < C && (b = De(await c(j, e, g, n, v, 50), l), V(p, x, { content: Ee(b.content) }), !b.done);) Date.now() - w > 3e4 && (await a(j, e, g, 600, v).catch(() => void 0), w = Date.now()), await new Promise((e) => setTimeout(e, he(Date.now() - oe)));
192
+ for (; Date.now() < C && (b = De(await c(M, e, g, n, v, 50), l), V(p, x, { content: Ee(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)));
191
193
  if (!b.done && f !== "vibe-plugins") throw Error("Assistant response timed out while streaming progress");
192
- let se = f === "vibe-plugins" ? await s(j, e, g, n, v).catch(() => []) : void 0;
194
+ let se = f === "vibe-plugins" ? await s(M, e, g, n, v).catch(() => []) : void 0;
193
195
  if (b.done || (b = {
194
196
  ...b,
195
197
  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._`
196
198
  }), o && (b = {
197
199
  ...b,
198
- content: `${b.content}\n\n${A("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._")}`
200
+ 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._")}`
199
201
  }), S(b.content, se, n, e), b.tokens) {
200
202
  V(p, x, { tokens: b.tokens });
201
203
  try {
202
- await u(j, g, n, b.tokens, v), de();
204
+ await u(M, g, n, b.tokens, v), de();
203
205
  } catch {}
204
206
  }
205
207
  H(p, "complete", x, null);
206
208
  } catch (t) {
207
- if (e === 1 && me(t)) return U(p), Be(f), C(2);
209
+ if (e === 1 && me(t)) return U(p), Ve(f), C(2);
208
210
  throw t;
209
211
  }
210
212
  }, w = p;
211
- Ye.current.add(w);
213
+ Xe.current.add(w);
212
214
  try {
213
215
  if (!g) throw Error("Assistant backend is unavailable without an active workspace context.");
214
216
  await C();
215
- } catch (e) {
216
- if (le(e)) {
217
+ } catch (t) {
218
+ if (Y.current.invalidate(e.getState().sandboxesByMode[f]?.sandboxId ?? null), le(t)) {
217
219
  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);
218
220
  return;
219
221
  }
220
- let t = e instanceof Error ? e.message : "Something went wrong";
221
- H(p, "error", x, t), V(p, x, {
222
- content: `Sorry, an error occurred: ${t}. Please try again.`,
222
+ let n = t instanceof Error ? t.message : "Something went wrong";
223
+ H(p, "error", x, n), V(p, x, {
224
+ content: `Sorry, an error occurred: ${n}. Please try again.`,
223
225
  metadata: { lang: "en" }
224
226
  });
225
227
  } finally {
226
- Ye.current.delete(w);
228
+ Xe.current.delete(w);
227
229
  }
228
230
  }, [
229
- F,
230
- B,
231
- j,
231
+ I,
232
+ Le,
233
+ M,
232
234
  U,
233
- Be,
235
+ Ve,
234
236
  Pe,
235
- z,
236
- Xe,
237
- M,
237
+ B,
238
+ Ze,
239
+ N,
238
240
  ke,
239
241
  V,
240
242
  Me,
241
243
  Ne,
242
244
  je,
243
- ze,
244
- R,
245
+ Be,
246
+ z,
245
247
  H,
246
- A,
247
- Y,
248
+ j,
249
+ X,
248
250
  Ae
249
- ]), Ze = T((e) => {
250
- X(e);
251
- }, [X]), Qe = T(() => {
252
- let e = [...G].reverse().find((e) => e.role === "user"), t = F ? Je.current[F] ?? [] : [];
253
- e && X(e.content, t);
251
+ ]), Qe = T((e) => {
252
+ Z(e);
253
+ }, [Z]), $e = T(() => {
254
+ let e = [...G].reverse().find((e) => e.role === "user"), t = I ? Ye.current[I] ?? [] : [];
255
+ e && Z(e.content, t);
254
256
  }, [
255
257
  G,
256
- X,
257
- F
258
- ]), Z = ge(X);
258
+ Z,
259
+ I
260
+ ]), Q = O(Z);
259
261
  E(() => {
260
- Z.current = X;
261
- }, [X]);
262
- let $e = D(() => {
262
+ Q.current = Z;
263
+ }, [Z]);
264
+ let et = D(() => {
263
265
  if (q) return null;
264
266
  for (let e = G.length - 1; e >= 0; --e) {
265
267
  let t = G[e];
@@ -271,104 +273,104 @@ var M = ({ visible: Se = !0 }) => {
271
273
  } : null;
272
274
  }
273
275
  return null;
274
- }, [G, q]), et = D(() => G.filter((e) => e.role === "user" || e.role === "assistant").slice(-6).map((e) => ({
276
+ }, [G, q]), tt = D(() => G.filter((e) => e.role === "user" || e.role === "assistant").slice(-6).map((e) => ({
275
277
  id: e.id,
276
278
  role: e.role,
277
279
  text: v(e.content).text.trim()
278
- })).filter((e) => e.text.length > 0), [G]), Q = se({
280
+ })).filter((e) => e.text.length > 0), [G]), $ = se({
279
281
  onSubmit: T((e) => {
280
- Z.current(e, [], { dictated: !0 });
282
+ Q.current(e, [], { dictated: !0 });
281
283
  }, []),
282
- latestReply: $e,
283
- language: g(P, N).tag
284
+ latestReply: et,
285
+ language: g(F, P).tag
284
286
  });
285
287
  E(() => {
286
- !Se && Q.active && Q.end();
287
- }, [Se, Q]), E(() => {
288
+ !Se && $.active && $.end();
289
+ }, [Se, $]), E(() => {
288
290
  let t = e.getState().consumePendingPrompt();
289
- return t && Z.current(t), e.subscribe((t, n) => {
291
+ return t && Q.current(t), e.subscribe((t, n) => {
290
292
  if (t.pendingPrompt && t.pendingPrompt !== n.pendingPrompt) {
291
293
  let t = e.getState().consumePendingPrompt();
292
- t && Z.current(t);
294
+ t && Q.current(t);
293
295
  }
294
296
  });
295
297
  }, []);
296
- let $ = T((t) => {
297
- let n = F ? e.getState().conversations.find((e) => e.id === F) : void 0;
298
+ let nt = T((t) => {
299
+ let n = I ? e.getState().conversations.find((e) => e.id === I) : void 0;
298
300
  if (n && (n.messages.length > 0 || n.backendSessionId)) {
299
301
  if (n.mode !== t) {
300
302
  let n = e.getState().conversations.find((n) => n.mode === t && n.messages.length === 0 && !n.backendSessionId && !e.getState().processingByConversationId[n.id]);
301
- n ? Ie(n.id) : z(void 0, t);
303
+ n ? Ie(n.id) : B(void 0, t);
302
304
  }
303
- } else F && R(F, t);
304
- L(t);
305
+ } else I && z(I, t);
306
+ R(t);
305
307
  }, [
306
- F,
307
- z,
308
+ I,
309
+ B,
308
310
  Ie,
309
- R,
310
- L
311
- ]), tt = T((t) => {
311
+ z,
312
+ R
313
+ ]), rt = T((t) => {
312
314
  if (S.find((e) => e.id === t)?.writeCapable && !e.getState().apiCallsAcknowledged) {
313
- qe(t);
315
+ Je(t);
314
316
  return;
315
317
  }
316
- $(t);
317
- }, [$]), nt = T(() => {
318
- let e = Ke;
319
- qe(null), Ve(), e && $(e);
318
+ nt(t);
319
+ }, [nt]), it = T(() => {
320
+ let e = qe;
321
+ Je(null), He(), e && nt(e);
320
322
  }, [
321
- Ke,
322
- Ve,
323
- $
324
- ]), rt = T(() => {
325
- qe(null);
323
+ qe,
324
+ He,
325
+ nt
326
+ ]), at = T(() => {
327
+ Je(null);
326
328
  }, []);
327
329
  return /* @__PURE__ */ ye("div", {
328
330
  className: "relative flex flex-1 flex-col overflow-hidden",
329
331
  children: [
330
332
  /* @__PURE__ */ ye("div", {
331
333
  className: "contents",
332
- inert: Q.active || void 0,
333
- children: [G.length === 0 ? /* @__PURE__ */ O(C, {
334
- mode: I,
335
- onSuggestionClick: Ze
336
- }) : /* @__PURE__ */ O("div", {
334
+ inert: $.active || void 0,
335
+ children: [G.length === 0 ? /* @__PURE__ */ k(C, {
336
+ mode: L,
337
+ onSuggestionClick: Qe
338
+ }) : /* @__PURE__ */ k("div", {
337
339
  className: "flex min-h-0 flex-1 flex-col",
338
- children: /* @__PURE__ */ O(b, {
340
+ children: /* @__PURE__ */ k(b, {
339
341
  messages: G,
340
- streamingMessageId: He,
341
- failedMessageId: Ue,
342
- onRetry: Qe
342
+ streamingMessageId: Ue,
343
+ failedMessageId: We,
344
+ onRetry: $e
343
345
  })
344
- }), /* @__PURE__ */ O(w, {
345
- onStartVoiceSession: Q.available && I !== "api-calls" ? Q.start : void 0,
346
- onSend: (e, t) => void X(e, t),
346
+ }), /* @__PURE__ */ k(w, {
347
+ onStartVoiceSession: $.available && L !== "api-calls" ? $.start : void 0,
348
+ onSend: (e, t) => void Z(e, t),
347
349
  disabled: q,
348
- placeholder: I === "api-calls" ? A("healthybowl.assistant.chatArea.placeholderActions", "What would you like me to do?") : A("healthybowl.assistant.chatArea.placeholderGeneral", "Ask HealthyBowl anything…"),
349
- mode: I,
350
- availableModes: Ge,
351
- onModeChange: tt
350
+ placeholder: L === "api-calls" ? j("healthybowl.assistant.chatArea.placeholderActions", "What would you like me to do?") : j("healthybowl.assistant.chatArea.placeholderGeneral", "Ask HealthyBowl anything…"),
351
+ mode: L,
352
+ availableModes: Ke,
353
+ onModeChange: rt
352
354
  })]
353
355
  }),
354
- Q.active && /* @__PURE__ */ O(oe, {
355
- session: Q.session,
356
- notice: Q.notice,
357
- turns: et,
358
- onInterrupt: Q.interrupt,
359
- spoken: $e?.text ?? null,
360
- onToggleMute: Q.toggleMute,
361
- onEnd: Q.end
356
+ $.active && /* @__PURE__ */ k(oe, {
357
+ session: $.session,
358
+ notice: $.notice,
359
+ turns: tt,
360
+ onInterrupt: $.interrupt,
361
+ spoken: et?.text ?? null,
362
+ onToggleMute: $.toggleMute,
363
+ onEnd: $.end
362
364
  }),
363
- /* @__PURE__ */ O(x, {
364
- open: Ke !== null,
365
- onConfirm: nt,
366
- onCancel: rt
365
+ /* @__PURE__ */ k(x, {
366
+ open: qe !== null,
367
+ onConfirm: it,
368
+ onCancel: at
367
369
  })
368
370
  ]
369
371
  });
370
372
  };
371
373
  //#endregion
372
- export { M as AssistantChatArea };
374
+ export { N as AssistantChatArea };
373
375
 
374
376
  //# sourceMappingURL=AssistantChatArea.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantChatArea.js","names":[],"sources":["../../../src/components/assistant/AssistantChatArea.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState, type FC } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { findAssistantLanguage, resolveAssistantLanguage } from '@/config/assistantLanguages';\nimport { AssistantMessageList } from './AssistantMessageList';\nimport { AssistantApiCallsConsentDialog } from './AssistantApiCallsConsentDialog';\nimport { AssistantEmptyState } from './AssistantEmptyState';\nimport { AssistantComposer } from './composer/AssistantComposer';\nimport { AssistantVoiceSession } from './voice/AssistantVoiceSession';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useVoiceSession } from '../../hooks/useVoiceSession';\nimport { useAssistantApiAccess } from '@/hooks/useAssistantApiAccess';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport {\n checkAssistantAiCredits,\n createAssistantSandbox,\n createAssistantSession,\n extendAssistantSandboxTTL,\n findExistingSandbox,\n getAssistantArtifacts,\n getAssistantMessages,\n getAssistantSession,\n reportAssistantAiTokenUsage,\n sendAssistantPromptAsync,\n waitForAssistantServiceReady,\n waitForSandboxReady,\n type AssistantRawMessage,\n type AssistantSandboxAuthContext,\n} from '@/services/assistantApi';\nimport { getAssistantMedia } from '@burdenoff/fe-libs/shared/assistant';\nimport { gatherPageContext } from '@/utils/pageContext';\nimport { getOrganizationId, getWorkspaceId } from '@/utils/assistantContext';\nimport { dispatchAssistantQuotaExhausted, notifyAiCreditsUpdated } from '@/utils/aiCredits';\nimport { isQuotaExhaustedError } from '@/utils/quotaUtils';\nimport { buildPromptForMode } from '@/utils/assistantPrompt';\nimport {\n buildPromptParts,\n buildPromptWithAttachments,\n countInlineImageCandidates,\n countInlinedImageParts,\n toMessageAttachment,\n type AssistantAttachment,\n} from '@/utils/assistantAttachments';\nimport { isMultimodalBodyRejection, isRecoverableAssistantError } from '@/utils/assistantTransportErrors';\nimport { isTurnInFlight } from '@/utils/assistantTurnState';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { ASSISTANT_MODES } from '@/types/assistant';\nimport type { AssistantArtifact, AssistantConversationStatus, AssistantMode, Message } from '@/types/assistant';\nimport { pollDelayMs } from '../../utils/assistantPollSchedule';\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 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 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 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 return false;\n }\n };\n\n // 1) Try the locally-remembered sandbox, then 2) any running one on the\n // server. Each is only kept if it's actually reachable.\n if (currentSandboxId) {\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', 'Reusing assistant environment...');\n if (!(await ensureSandboxReachable(currentSandboxId))) {\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = null;\n }\n }\n\n if (!currentSandboxId) {\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Looking for existing environment...'\n );\n const existingId = await findExistingSandbox(apollo, workspaceId, currentMode, authContext);\n\n if (existingId) {\n setSandbox(currentMode, existingId, 'provisioning');\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Reusing assistant environment...'\n );\n if (await ensureSandboxReachable(existingId)) {\n currentSandboxId = existingId;\n } else {\n setSandbox(currentMode, null, 'provisioning');\n }\n }\n }\n\n // 3) No reusable, reachable sandbox — provision a fresh one.\n if (!currentSandboxId) {\n if (currentMode === 'api-calls' && !getAccessToken()) {\n throw new Error('API Calls mode requires an authenticated session. Please sign in again.');\n }\n\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Starting assistant environment...'\n );\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = await createAssistantSandbox(apollo, currentMode, workspaceId, authContext);\n\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n await waitForSandboxReady(apollo, currentSandboxId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, currentSandboxId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n }\n\n setSandbox(currentMode, currentSandboxId, 'running');\n\n let sessionId =\n useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n ?.backendSessionId ?? null;\n\n if (sessionId) {\n try {\n const session = await getAssistantSession(apollo, currentSandboxId, workspaceId, sessionId, authContext);\n if (session.mode !== currentMode) {\n throw new Error(`Session mode mismatch: expected ${currentMode}, received ${session.mode}`);\n }\n } catch {\n clearBackendSessionId(conversationId);\n sessionId = null;\n }\n }\n\n if (!sessionId) {\n updateConversationStage(conversationId, assistantMessageId, 'connecting', 'Preparing session...');\n const result = await createAssistantSession(apollo, currentSandboxId, workspaceId, currentMode, authContext);\n sessionId = result.sessionId;\n setBackendSessionId(conversationId, sessionId);\n }\n\n return {\n sandboxId: currentSandboxId,\n sessionId,\n };\n },\n [apollo, clearBackendSessionId, getAccessToken, setBackendSessionId, setSandbox, updateConversationStage]\n );\n\n const handleSend = useCallback(\n async (content: string, attachments: AssistantAttachment[] = [], options: { dictated?: boolean } = {}) => {\n // Only block re-entry while a turn is genuinely in-flight. Earlier code\n // checked for *any* entry in the map, which stuck around as `complete`\n // / `error` after the first turn — making every subsequent message\n // silently disappear (the input cleared but handleSend bailed before\n // adding the user message to the conversation).\n //\n // The store is read LIVE, and that is what makes the guard work. The\n // render-captured `processingByConversationId` is stale by construction —\n // the click that starts a turn and the click that must be rejected can\n // belong to the same render. Reading `activeConversationId` live matters\n // for the same reason: on two racing first-ever sends, the second must see\n // the conversation the first one created a moment ago.\n //\n // Pairs with the synchronous `setConversationProcessing` below: because\n // the status is written before this function ever awaits, a second call —\n // however soon it arrives — always observes 'provisioning'.\n const storeAtEntry = useAssistantStore.getState();\n const guardConversationId = storeAtEntry.activeConversationId ?? activeConversationId;\n if (guardConversationId) {\n if (isTurnInFlight(storeAtEntry.processingByConversationId[guardConversationId]?.status)) return;\n // Second lock, in case a future change moves the status write later:\n // this one cannot be cleared by anything but the turn's own `finally`.\n // Deliberately per-conversation — a global key would keep blocking\n // after the conversation it belonged to was deleted mid-turn, and then\n // silently swallow every subsequent send.\n if (inFlightSendsRef.current.has(guardConversationId)) return;\n }\n\n const selectedMode = storeAtEntry.mode;\n let conversationId = activeConversationId;\n const currentConversation = conversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n : undefined;\n\n if (!conversationId) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (\n currentConversation &&\n currentConversation.mode !== selectedMode &&\n (currentConversation.messages.length > 0 || currentConversation.backendSessionId)\n ) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (currentConversation && currentConversation.mode !== selectedMode) {\n setConversationMode(conversationId, selectedMode);\n }\n\n if (!conversationId) return;\n\n // Keyed by conversation: the ref outlives a conversation switch, and a\n // single global slot meant Retry in one thread replayed another thread's\n // photo onto it.\n lastSentAttachmentsRef.current[conversationId] = attachments;\n\n const workspaceId = getWorkspaceId();\n const authContext: AssistantSandboxAuthContext = {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n };\n\n const userMessage: Message = {\n id: generateId(),\n role: 'user',\n content,\n timestamp: new Date().toISOString(),\n // Slim descriptors only — the bubble re-resolves thumbnails from the\n // file id, so the persisted conversation stays small.\n metadata: attachments.length ? { attachments: attachments.map(toMessageAttachment) } : undefined,\n };\n addMessage(conversationId, userMessage);\n\n const assistantMessageId = generateId();\n addMessage(conversationId, {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n timestamp: new Date().toISOString(),\n // Stamped now, not read later: this is the language the reply is being\n // generated in, and the preference may have moved on by the time\n // somebody presses Listen.\n metadata: { lang: replyLanguageCode },\n });\n\n // Mark the turn in-flight in the STORE right now, synchronously.\n //\n // Until this line the first status write happened inside\n // `ensureAssistantRuntime`, i.e. one await later. During that window\n // `activeIsProcessing` was false and `failedMessageId` still pointed at\n // the PREVIOUS failure — so the composer stayed enabled and, worse, the\n // Retry button (which has no `disabled` of its own) stayed mounted and\n // clickable on top of a turn that had already started.\n //\n // Status only, deliberately no stage copy: `ensureAssistantRuntime` picks\n // the accurate wording a moment later (\"Reusing...\" vs \"Starting...\"), and\n // guessing here would flash the wrong one on every reused sandbox.\n setConversationProcessing(conversationId, 'provisioning', assistantMessageId, null);\n\n const applyAssistantResponse = (\n response: string,\n artifacts?: AssistantArtifact[],\n sessionId?: string,\n sandboxId?: string,\n // Our own hard-coded copy is English regardless of what the user picked.\n // Stamping it with their language makes playback read an English quota\n // message in a Tamil voice — Latin text cannot be script-detected, so\n // this metadata is trusted absolutely.\n lang: string = replyLanguageCode\n ) => {\n // `patchMessage` REPLACES metadata rather than merging it, so anything\n // omitted here is destroyed — which is how the turn-language stamp set\n // at creation was being wiped the moment the response completed,\n // silently undoing per-message language resolution. Always re-assert it.\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n metadata: {\n lang,\n ...(artifacts?.length ? { artifacts } : {}),\n ...(artifacts?.length || sessionId || sandboxId ? { mode: selectedMode } : {}),\n ...(sessionId ? { sessionId } : {}),\n ...(sandboxId ? { sandboxId } : {}),\n },\n });\n };\n\n const sendWithRealBackend = async (attempt: 1 | 2 = 1): Promise<void> => {\n // Set when this attempt had to re-send without the image bytes, so the\n // answer can say so rather than quietly reading as if the model looked.\n let imagesDropped = false;\n // Pre-flight AI-credit gate. The wspace gateway's @usage(checkQuota)\n // rejects with 429 QUOTA_EXHAUSTED when the monthly token budget is\n // depleted — block the send (don't provision a sandbox or dispatch the\n // prompt) and surface the upgrade dialog instead of a generic error.\n try {\n await checkAssistantAiCredits(apollo, workspaceId, authContext);\n } catch (creditError) {\n if (isQuotaExhaustedError(creditError)) {\n dispatchAssistantQuotaExhausted('ai-credits');\n applyAssistantResponse(\n \"You've run out of AI credits for this billing cycle. Upgrade your plan to keep chatting.\",\n undefined,\n undefined,\n undefined,\n 'en'\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n // The pre-flight gate exists ONLY to catch a genuine QUOTA_EXHAUSTED\n // rejection. Any other failure here is a transient fault in the\n // credit check itself — e.g. the usage subgraph's getUsageSummary /\n // checkAiCredits intermittently 500s (Postgres/Prisma blip) and the\n // gateway masks it as the opaque \"Unexpected error.\". That is NOT\n // proof the user is out of budget, so it must not abort an otherwise\n // valid send. Fail open and proceed: the wspace gateway's\n // @usage(checkQuota) on createSandbox still enforces the real budget\n // downstream (a truly over-quota caller is stopped there with a 429\n // that surfaces the upgrade dialog via the outer catch).\n console.warn(\n '[assistant] AI-credit pre-flight check failed with a non-quota error; proceeding — gateway @usage(checkQuota) still enforces the real budget downstream',\n creditError\n );\n }\n\n try {\n const { sandboxId, sessionId } = await ensureAssistantRuntime(\n conversationId,\n assistantMessageId,\n selectedMode,\n workspaceId,\n authContext\n );\n\n // Snapshot the newest message timestamp already present in this\n // (possibly reused) session BEFORE sending the prompt, so we can\n // recognise THIS turn's reply as the one created after it — never by\n // comparing the browser clock to the sandbox clock (see\n // buildAssistantProgress). The newest-N window always contains the\n // newest message, so this floor is exact regardless of conversation depth.\n const priorMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n ).catch((): AssistantRawMessage[] => []);\n const priorNewestCreatedMs = priorMessages.reduce(\n (newest, message) => Math.max(newest, getRawMessageCreatedAt(message)),\n 0\n );\n\n updateConversationStage(conversationId, assistantMessageId, 'streaming', 'Thinking...');\n // Two agent-only wrappers around the raw content, both invisible in\n // the bubble: the soft confirm-before-mutate guard for api-calls mode,\n // and the attachment block (metadata + URLs, with text-like files\n // inlined) that carries this turn's files to the model.\n // …and the language directive, so the reply comes back in the user's\n // language rather than defaulting to the language of the docs the\n // model grounds on. The FE is the only layer that knows the locale —\n // it is not on the wire and `pageContext` silently drops unknown keys.\n const promptText = buildPromptForMode(\n selectedMode,\n buildPromptWithAttachments(content, attachments),\n replyLanguageName,\n languageIsExplicit,\n options.dictated === true\n );\n // Structured multimodal parts carry the image PIXELS, which no amount\n // of prompt text can. Built from the same `promptText`, so a bridge\n // that ignores `parts` loses nothing; `undefined` for an ordinary text\n // turn keeps the wire body unchanged.\n const promptParts = buildPromptParts(promptText, attachments);\n const inlinedCount = countInlinedImageParts(promptParts);\n const carriesPixels = inlinedCount > 0;\n const pageContext = gatherPageContext();\n\n // `buildPromptParts` may have demoted a photo to a link to keep the\n // body under the gateway's cap — a long message can do that on prompt\n // text alone. That decision is invisible to the user unless we say so,\n // and an answer that reads as if the model looked at a photo it never\n // received is worse than a short note.\n imagesDropped = countInlineImageCandidates(attachments) > inlinedCount;\n\n try {\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n promptParts\n );\n } catch (sendError) {\n // `buildPromptParts` already sizes the PARTS to the gateway's cap\n // (the prompt string itself is not bounded here), so reaching this\n // point means something rejected the body anyway — a tighter proxy\n // than we modelled, or a bridge that will not take `parts` at all.\n // Losing the whole question over that is the worst outcome\n // available: re-send it text-only. Only for errors that provably\n // never reached the agent (see isMultimodalBodyRejection) — a blind\n // retry would ask the same question twice and bill it twice.\n //\n // Gated on `parts` existing at all, NOT on it carrying pixels: the\n // array duplicates the whole prompt in `parts[0]`, so a url-only\n // parts array is itself enough to push a long message over the cap.\n // `carriesPixels` only decides whether the user is told something\n // was lost.\n if (!promptParts || !isMultimodalBodyRejection(sendError)) throw sendError;\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n undefined\n );\n // Only claim a photo was lost if one actually was — a url-only\n // retry loses nothing the prompt block did not already carry.\n imagesDropped = imagesDropped || carriesPixels;\n }\n\n let result = buildAssistantProgress([], priorNewestCreatedMs);\n const timeoutAt = Date.now() + (STREAM_BUDGET_MS[selectedMode] ?? DEFAULT_STREAM_BUDGET_MS);\n let lastTtlExtensionAt = Date.now();\n\n const pollStartedAt = Date.now();\n while (Date.now() < timeoutAt) {\n const sessionMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n );\n\n result = buildAssistantProgress(sessionMessages, priorNewestCreatedMs);\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(result.content),\n });\n\n if (result.done) break;\n\n if (Date.now() - lastTtlExtensionAt > 30_000) {\n await extendAssistantSandboxTTL(apollo, sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n // Fast early, backing off after — see assistantPollSchedule. This is\n // the granularity of the whole turn: it bounds how late the answer\n // appears AND how late speech can start, because auto-speak only\n // fires once a poll observes the reply completed.\n await new Promise((resolve) => setTimeout(resolve, pollDelayMs(Date.now() - pollStartedAt)));\n }\n\n // For non-build modes a timeout is a hard failure. For vibe-plugins the\n // prompt runs async server-side (/sessions/:id/prompt-async) and keeps\n // writing artifacts after the poll budget elapses, so we surface whatever\n // it has produced instead of discarding the turn.\n if (!result.done && selectedMode !== 'vibe-plugins') {\n throw new Error('Assistant response timed out while streaming progress');\n }\n\n const artifacts =\n selectedMode === 'vibe-plugins'\n ? await getAssistantArtifacts(apollo, sandboxId, workspaceId, sessionId, authContext).catch(() => [])\n : undefined;\n\n if (!result.done) {\n // vibe-plugins build still running in the background. Append a note so\n // the user knows the answer is partial and the artifacts will finish.\n result = {\n ...result,\n content: `${result.content}\\n\\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`,\n };\n }\n\n if (imagesDropped) {\n // Said plainly, because the alternative is an answer that looks like\n // it examined a photo it never received.\n result = {\n ...result,\n content: `${result.content}\\n\\n${tr(\n 'healthybowl.assistant.attachments.imagesNotSent',\n '_Your photo was too large to include with this message, so the answer above is from the text and the file link only. Try a smaller or more tightly cropped photo._'\n )}`,\n };\n }\n\n applyAssistantResponse(result.content, artifacts, sessionId, sandboxId);\n\n if (result.tokens) {\n patchMessage(conversationId, assistantMessageId, { tokens: result.tokens });\n // Charge the real token usage against the AI-credits quota (the\n // gateway records it via @usage(trackUsage)). We AWAIT it before\n // marking the turn complete / re-enabling input: otherwise a rapid\n // follow-up send would run its pre-flight checkAiCredits against a\n // stale balance (this turn's charge still in flight) and could\n // dispatch a prompt that should have been blocked, letting fast\n // sends bypass the credit cap. Still best-effort — a charge failure\n // never blocks the displayed answer.\n try {\n await reportAssistantAiTokenUsage(apollo, workspaceId, sessionId, result.tokens, authContext);\n notifyAiCreditsUpdated();\n } catch {\n // ignore — server-side @usage tracking is the source of truth\n }\n }\n setConversationProcessing(conversationId, 'complete', assistantMessageId, null);\n } catch (error) {\n if (attempt === 1 && isRecoverableAssistantError(error)) {\n clearBackendSessionId(conversationId);\n clearSandbox(selectedMode);\n return sendWithRealBackend(2);\n }\n\n throw error;\n }\n };\n\n // Claim the slot immediately before the first await, and release it in\n // `finally` so every exit — success, quota return, thrown error — frees\n // it. Registering here rather than earlier means a synchronous throw in\n // the setup above can never strand a key and wedge the conversation.\n const turnConversationId = conversationId;\n inFlightSendsRef.current.add(turnConversationId);\n\n try {\n if (!workspaceId) {\n throw new Error('Assistant backend is unavailable without an active workspace context.');\n }\n await sendWithRealBackend();\n } catch (error) {\n // A quota error reaching here is the sandbox-environment wall hit\n // during runtime provisioning (createSandbox @usage). Surface the\n // upgrade dialog instead of a generic failure (the AI-credit wall is\n // already handled by the pre-flight gate above).\n if (isQuotaExhaustedError(error)) {\n dispatchAssistantQuotaExhausted('sandbox');\n applyAssistantResponse(\n \"You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.\",\n undefined,\n undefined,\n undefined,\n 'en'\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n const errorMessage = error instanceof Error ? error.message : 'Something went wrong';\n setConversationProcessing(conversationId, 'error', assistantMessageId, errorMessage);\n // Same reason: English copy must not inherit the turn's language stamp.\n patchMessage(conversationId, assistantMessageId, {\n content: `Sorry, an error occurred: ${errorMessage}. Please try again.`,\n metadata: { lang: 'en' },\n });\n } finally {\n inFlightSendsRef.current.delete(turnConversationId);\n }\n },\n [\n activeConversationId,\n addMessage,\n apollo,\n clearBackendSessionId,\n clearSandbox,\n conversations,\n createConversation,\n ensureAssistantRuntime,\n getAccessToken,\n getWorkspaceToken,\n patchMessage,\n // Without this, switching language mid-conversation keeps sending the\n // previous language's directive until something else re-creates the\n // callback.\n languageIsExplicit,\n replyLanguageCode,\n replyLanguageName,\n setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n tr,\n updateConversationStage,\n userId,\n ]\n );\n\n const handleSuggestionClick = useCallback(\n (suggestion: string) => {\n void handleSend(suggestion);\n },\n [handleSend]\n );\n\n // Retry re-sends the most recent user prompt through the same transport — the\n // failed assistant turn stays in the transcript, a fresh one is appended.\n // The attachments come from the in-memory ref rather than the message\n // metadata: the persisted descriptors deliberately drop the inlined text of\n // text-like files, so rebuilding from them would silently retry a WEAKER\n // prompt than the one that failed.\n const handleRetry = useCallback(() => {\n const lastUserMessage = [...messages].reverse().find((message) => message.role === 'user');\n const replay = activeConversationId ? (lastSentAttachmentsRef.current[activeConversationId] ?? []) : [];\n if (lastUserMessage) void handleSend(lastUserMessage.content, replay);\n }, [messages, handleSend, activeConversationId]);\n\n // Auto-send any prompt that was queued by `useOpenAssistantHelp` (from\n // the shared GetHelpButton). We keep the latest handleSend in a ref so\n // the subscription effect below doesn't need to tear down on every\n // render — the store subscription lives for the component lifetime and\n // always calls the freshest handler.\n const handleSendRef = useRef(handleSend);\n useEffect(() => {\n handleSendRef.current = handleSend;\n }, [handleSend]);\n\n /**\n * The newest assistant reply, as the voice session's advance signal.\n *\n * Keyed on the message ID rather than the text: two consecutive answers can be\n * word-for-word identical, and text alone would then never advance the second\n * turn.\n */\n const latestAssistantReply = useMemo(() => {\n // ★ Only once the turn is COMPLETE. While it is in flight the pending\n // assistant message is patched with progress text — 'Starting assistant\n // environment...', 'Thinking...' — and exposing that would make the voice\n // session consume the message id, enter `speaking` on a placeholder, and\n // then be unable to advance when the real answer replaced it.\n if (activeIsProcessing) return null;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (message?.role !== 'assistant') continue;\n // Tool-activity markup is stripped so the session captions and speaks the\n // answer, not the machinery that produced it.\n const text = parseToolActivity(message.content).text.trim();\n return text ? { id: message.id, text } : null;\n }\n return null;\n }, [messages, activeIsProcessing]);\n\n /**\n * The last few exchanges, for the session's on-screen transcript.\n *\n * Voice turns already go through the normal send path, so they are ordinary\n * conversation messages — this only surfaces them INSIDE the session, which\n * is what makes a second question in the same session make sense.\n */\n const voiceTurns = useMemo(\n () =>\n messages\n .filter((message) => message.role === 'user' || message.role === 'assistant')\n .slice(-6)\n .map((message) => ({\n id: message.id,\n role: message.role as 'user' | 'assistant',\n text: parseToolActivity(message.content).text.trim(),\n }))\n .filter((turn) => turn.text.length > 0),\n [messages]\n );\n\n const submitVoiceTurn = useCallback((text: string) => {\n // ★ Only the voice SESSION is unambiguously dictated. The composer's\n // microphone also produces a transcript, but the user reads and edits it in\n // the box before sending, so treating that as dictated would tell the model\n // to second-guess words the user had already approved.\n void handleSendRef.current(text, [], { dictated: true });\n }, []);\n\n const voiceSession = useVoiceSession({\n onSubmit: submitVoiceTurn,\n latestReply: latestAssistantReply,\n // The language the user SPEAKS, not the interface language — the same\n // preference the composer's dictation and the reply language already use.\n language: resolveAssistantLanguage(assistantLanguage, locale).tag,\n });\n\n // Hiding the panel must end a live voice session. The host may set `visible`\n // false WITHOUT unmounting, and an unmount-only cleanup would then leave the\n // microphone recording behind an invisible panel — a privacy problem, not\n // just a leak.\n useEffect(() => {\n if (!visible && voiceSession.active) voiceSession.end();\n }, [visible, voiceSession]);\n\n useEffect(() => {\n // Flush any prompt that was queued before this component mounted.\n const initial = useAssistantStore.getState().consumePendingPrompt();\n if (initial) {\n void handleSendRef.current(initial);\n }\n\n // Watch for new prompts queued while we're already mounted.\n const unsubscribe = useAssistantStore.subscribe((state, prev) => {\n if (state.pendingPrompt && state.pendingPrompt !== prev.pendingPrompt) {\n const queued = useAssistantStore.getState().consumePendingPrompt();\n if (queued) {\n void handleSendRef.current(queued);\n }\n }\n });\n return unsubscribe;\n }, []);\n\n const performModeChange = useCallback(\n (newMode: AssistantMode) => {\n const currentConversation = activeConversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === activeConversationId)\n : undefined;\n\n if (currentConversation && (currentConversation.messages.length > 0 || currentConversation.backendSessionId)) {\n if (currentConversation.mode !== newMode) {\n const reusableDraft = useAssistantStore\n .getState()\n .conversations.find(\n (conversation) =>\n conversation.mode === newMode &&\n conversation.messages.length === 0 &&\n !conversation.backendSessionId &&\n !useAssistantStore.getState().processingByConversationId[conversation.id]\n );\n\n if (reusableDraft) {\n setActiveConversation(reusableDraft.id);\n } else {\n createConversation(undefined, newMode);\n }\n }\n } else if (activeConversationId) {\n setConversationMode(activeConversationId, newMode);\n }\n\n setMode(newMode);\n },\n [activeConversationId, createConversation, setActiveConversation, setConversationMode, setMode]\n );\n\n const handleModeChange = useCallback(\n (newMode: AssistantMode) => {\n const target = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === newMode);\n // Gate the FIRST switch into a write-capable mode behind the one-time\n // consent dialog — the dependable confirm-before-mutate guardrail.\n if (target?.writeCapable && !useAssistantStore.getState().apiCallsAcknowledged) {\n setPendingConsentMode(newMode);\n return;\n }\n performModeChange(newMode);\n },\n [performModeChange]\n );\n\n const handleConsentConfirm = useCallback(() => {\n const target = pendingConsentMode;\n setPendingConsentMode(null);\n acknowledgeApiCalls();\n if (target) performModeChange(target);\n }, [pendingConsentMode, acknowledgeApiCalls, performModeChange]);\n\n const handleConsentCancel = useCallback(() => {\n setPendingConsentMode(null);\n }, []);\n\n return (\n // `relative` so the DOCKED voice session can position itself against the\n // assistant panel rather than the viewport. Without it the docked overlay\n // would anchor to the page and cover the whole app, which is the very thing\n // docking exists to avoid.\n <div className=\"relative flex flex-1 flex-col overflow-hidden\">\n {/* Everything the voice overlay covers is made `inert` while a session is\n open. Docked, the overlay hides the transcript and composer but does\n NOT cover the page, so a full focus trap would wrongly imprison the\n user — yet leaving these focusable lets them Shift+Tab into controls\n they cannot see and operate them blind. `inert` is the precise tool:\n the page stays reachable, the covered controls do not. */}\n <div className=\"contents\" inert={voiceSession.active || undefined}>\n {/* Transcript is always visible now — the old collapse-by-default accordion\n is gone; conversation history lives behind the header button instead. */}\n {messages.length === 0 ? (\n <AssistantEmptyState mode={mode} onSuggestionClick={handleSuggestionClick} />\n ) : (\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <AssistantMessageList\n messages={messages}\n streamingMessageId={activeStreamingMessageId}\n failedMessageId={failedMessageId}\n onRetry={handleRetry}\n />\n </div>\n )}\n\n <AssistantComposer\n // ★ Ask-mode only, and enforced here rather than merely documented.\n // In `api-calls` mode the assistant WRITES to farm data behind a consent\n // gate, and BOFF-6377 (\"confirm-before-write cannot prove a human\n // approved\") is still open — a spoken \"yes, do it\" is exactly the case\n // that ticket is about. Voice control of writes is the NEXT phase, not\n // this one, so the launcher is simply absent in that mode.\n onStartVoiceSession={voiceSession.available && mode !== 'api-calls' ? voiceSession.start : undefined}\n onSend={(value, attachments) => void handleSend(value, attachments)}\n disabled={activeIsProcessing}\n placeholder={\n mode === 'api-calls'\n ? tr('healthybowl.assistant.chatArea.placeholderActions', 'What would you like me to do?')\n : tr('healthybowl.assistant.chatArea.placeholderGeneral', 'Ask HealthyBowl anything…')\n }\n mode={mode}\n availableModes={availableModes}\n onModeChange={handleModeChange}\n />\n </div>\n\n {voiceSession.active && (\n <AssistantVoiceSession\n session={voiceSession.session}\n notice={voiceSession.notice}\n turns={voiceTurns}\n onInterrupt={voiceSession.interrupt}\n spoken={latestAssistantReply?.text ?? null}\n onToggleMute={voiceSession.toggleMute}\n onEnd={voiceSession.end}\n />\n )}\n\n <AssistantApiCallsConsentDialog\n open={pendingConsentMode !== null}\n onConfirm={handleConsentConfirm}\n onCancel={handleConsentCancel}\n />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,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;AAC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H,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 { createReadinessTracker } from '../../utils/sandboxReadiness';\n\n// How long the client streams progress before giving up on a turn. Chat replies\n// (general / api-calls) finish in seconds; a vibe-plugins build is a multi-step\n// pipeline (read docs → scaffold → bun install → bun build → checklist) that runs\n// for minutes, so it gets a much larger budget. The sandbox TTL is auto-extended\n// every 30s during the poll loop, so a longer budget never outlives the sandbox.\nconst STREAM_BUDGET_MS: Record<AssistantMode, number> = {\n general: 180_000,\n assistant: 180_000,\n 'api-calls': 180_000,\n 'vibe-plugins': 600_000,\n};\nconst DEFAULT_STREAM_BUDGET_MS = 180_000;\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n}\n\nfunction sanitizeAssistantResponse(response: string): string {\n return response\n .replace(/(Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/(X-Workspace-Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9._-]+\\.[A-Za-z0-9._-]+\\b/g, '[REDACTED_JWT]')\n .replace(/\\bsk-ant-[A-Za-z0-9-]+\\b/g, '[REDACTED_API_KEY]');\n}\n\nfunction getRawMessageCreatedAt(message: AssistantRawMessage): number {\n return message.info?.time?.created ?? 0;\n}\n\nfunction getAssistantText(parts: AssistantRawMessage['parts']): string {\n return (parts ?? [])\n .filter((part) => part.type === 'text' && typeof part.text === 'string')\n .map((part) => part.text?.trim() ?? '')\n .filter(Boolean)\n .join('\\n');\n}\n\nfunction getToolProgress(parts: AssistantRawMessage['parts']): string[] {\n return (parts ?? [])\n .filter((part) => part.type === 'tool' && part.tool)\n .map((part) => {\n const status = part.state?.status ?? 'running';\n const tool = part.tool ?? 'tool';\n if (status === 'completed') return `Completed: ${tool}`;\n if (status === 'failed') return `Failed: ${tool}`;\n return `Running: ${tool}`;\n });\n}\n\nfunction buildAssistantProgress(\n messages: AssistantRawMessage[],\n // The `created` timestamp (sandbox clock) of the newest message that already\n // existed in this session BEFORE the prompt was sent. This turn's reply is the\n // assistant message created strictly after it. Crucially this stays WITHIN the\n // sandbox clock domain: the previous code compared the sandbox-stamped\n // `created` against the browser wall-clock (Date#now), so a reply stamped at\n // prompt-time was silently dropped whenever the sandbox clock lagged the\n // browser — the turn then hung on \"Thinking...\" until the stream budget\n // elapsed. A sandbox-domain floor is immune to clock skew and correct for both\n // fresh and reused (per-conversation) sessions, with no message-window gap.\n priorNewestCreatedMs: number\n): {\n content: string;\n done: boolean;\n tokens?: { input: number; output: number };\n} {\n const relevant = messages\n .filter((message) => message.info?.role === 'assistant' && getRawMessageCreatedAt(message) > priorNewestCreatedMs)\n .sort((left, right) => getRawMessageCreatedAt(left) - getRawMessageCreatedAt(right));\n\n if (relevant.length === 0) {\n return { content: 'Thinking...', done: false };\n }\n\n const latest = relevant[relevant.length - 1]!;\n const text = getAssistantText(latest.parts);\n // Inbound image/file parts, rendered to markdown by the shared helper (which\n // escapes the label and allowlists the protocol — this is model output).\n // Without this, HealthyBowl — the one product that SENDS parts — could not\n // read one back: a media-bearing reply would never satisfy `done` and the\n // turn would poll to a false timeout.\n const media = getAssistantMedia(latest.parts);\n const toolProgress = getToolProgress(latest.parts);\n const content = [text, ...media, ...toolProgress].filter(Boolean).join('\\n\\n') || 'Thinking...';\n\n return {\n content,\n done: Boolean(latest.info?.time?.completed) && (Boolean(text) || media.length > 0 || toolProgress.length > 0),\n tokens: latest.info?.tokens,\n };\n}\n\nfunction getConversationStatusMessage(status: AssistantConversationStatus): string {\n switch (status) {\n case 'provisioning':\n return 'Starting assistant environment...';\n case 'connecting':\n return 'Connecting to assistant...';\n case 'streaming':\n return 'Thinking...';\n default:\n return '';\n }\n}\n\n/**\n * `visible` is false when the host HIDES the panel without unmounting it, which\n * is what the supported `visible` prop does. That distinction matters here: a\n * live voice session would otherwise keep the microphone open and the silence\n * timer running behind an invisible panel.\n */\ninterface AssistantChatAreaProps {\n visible?: boolean;\n}\n\nexport const AssistantChatArea: FC<AssistantChatAreaProps> = ({ visible = true }) => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken, userId } = useAuthToken();\n const { locale } = useI18n();\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n // The language the user chose to SPEAK, which is not necessarily the one the\n // interface is in — that is the whole point of the preference (BOFF-7108).\n // Named in ENGLISH deliberately: the preamble around it is English, so\n // \"Answer in Tamil.\" reads as an instruction, where a bare tag (\"ta\") invites\n // the model to answer *about* the code instead of *in* the language.\n const replyLanguageName = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale).english,\n [assistantLanguage, locale]\n );\n // A stored preference is a deliberate choice; `null` is only the interface\n // language standing in as a default. The directive treats the two differently\n // — see `buildLanguagePreamble`.\n //\n // Resolved, not merely non-null: a stale persisted code from a build that\n // offered more languages is DISCARDED by `resolveAssistantLanguage`, and\n // treating that discarded value as deliberate would tell the model the user\n // had chosen the interface language on purpose — suppressing the typed-language\n // override on the strength of a preference the selector does not even show.\n const languageIsExplicit = findAssistantLanguage(assistantLanguage) !== null;\n const replyLanguageCode = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale).code,\n [assistantLanguage, locale]\n );\n\n const {\n conversations,\n activeConversationId,\n mode,\n processingByConversationId,\n setMode,\n setConversationMode,\n setActiveConversation,\n createConversation,\n addMessage,\n updateMessage,\n patchMessage,\n setConversationProcessing,\n clearConversationProcessing,\n setBackendSessionId,\n clearBackendSessionId,\n setSandbox,\n clearSandbox,\n acknowledgeApiCalls,\n } = useAssistantStore();\n\n const activeConversation = conversations.find((conversation) => conversation.id === activeConversationId);\n const messages = activeConversation?.messages ?? [];\n const activeProcessing = activeConversationId ? processingByConversationId[activeConversationId] : undefined;\n // Only while the turn is genuinely in flight. `messageId` outlives the turn\n // (setConversationProcessing keeps it on 'complete'/'error'), so keying off it\n // alone left the transcript's aria-busy latched true forever and screen\n // readers stopped announcing new replies.\n const activeIsProcessing = isTurnInFlight(activeProcessing?.status);\n const activeStreamingMessageId = activeIsProcessing ? (activeProcessing?.messageId ?? null) : null;\n // The assistant message whose turn ended in an error — drives the Retry\n // affordance in the transcript.\n const failedMessageId = activeProcessing?.status === 'error' ? activeProcessing.messageId : null;\n\n // ── api-calls (write) mode gating ──────────────────────────────────\n // Only a global Owner/Admin may use api-calls (it mints an OAuth app under the\n // caller identity). Re-read the org scope every render (a cheap localStorage\n // read) so the admin gate reacts to an org switch without the panel\n // remounting; the value is a stable string, so useAssistantApiAccess only\n // re-fetches myRoles when the org actually changes. An empty scope simply\n // hides the mode (it could not provision the sandbox anyway).\n const apiCallsScopeId = getOrganizationId();\n const { canUseApiCalls, loading: apiAccessLoading } = useAssistantApiAccess(apiCallsScopeId);\n const availableModes = useMemo(\n () => ASSISTANT_MODES.filter((modeConfig) => !modeConfig.requiresAdmin || canUseApiCalls),\n [canUseApiCalls]\n );\n\n // Target mode awaiting the one-time consent dialog (null = dialog closed).\n const [pendingConsentMode, setPendingConsentMode] = useState<AssistantMode | null>(null);\n\n // Full attachment payload of the last send, kept so Retry can replay it\n // byte-for-byte (see handleRetry).\n const lastSentAttachmentsRef = useRef<Record<string, AssistantAttachment[]>>({});\n\n // Conversations with a turn already dispatched. Synchronous, unlike the store\n // — see the re-entry guard in handleSend for why that matters.\n /**\n * Per-sandbox record of \"last proven reachable\", so a warm sandbox is not\n * re-probed on every turn. Invalidated by any failure — see both catches.\n */\n const sandboxReadiness = useRef(createReadinessTracker());\n const inFlightSendsRef = useRef<Set<string>>(new Set());\n\n // If the active mode is no longer permitted — a non-admin with a persisted\n // api-calls mode, or the master flag turned off — fall back to the read-only\n // `assistant` mode (the default \"Ask\", available to everyone), but only AFTER\n // the role check resolves (so an admin's persisted api-calls mode isn't reset\n // during the brief loading window).\n useEffect(() => {\n if (apiAccessLoading) return;\n const activeModeConfig = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === mode);\n const blocked = !activeModeConfig || (activeModeConfig.requiresAdmin && !canUseApiCalls);\n if (blocked && mode !== 'assistant') {\n setMode('assistant');\n }\n }, [mode, canUseApiCalls, apiAccessLoading, setMode]);\n\n const updateConversationStage = useCallback(\n (conversationId: string, assistantMessageId: string, status: AssistantConversationStatus, content?: string) => {\n setConversationProcessing(conversationId, status, assistantMessageId, null);\n if (content) {\n updateMessage(conversationId, assistantMessageId, content);\n } else {\n updateMessage(conversationId, assistantMessageId, getConversationStatusMessage(status));\n }\n },\n [setConversationProcessing, updateMessage]\n );\n\n const ensureAssistantRuntime = useCallback(\n async (\n conversationId: string,\n assistantMessageId: string,\n currentMode: AssistantMode,\n workspaceId: string,\n authContext: AssistantSandboxAuthContext\n ): Promise<{ sandboxId: string; sessionId: string }> => {\n let currentSandboxId = useAssistantStore.getState().sandboxesByMode[currentMode]?.sandboxId ?? null;\n\n // Validate that a candidate sandbox (remembered locally or found running on\n // the server) is actually reachable before we reuse it. A sandbox can expire\n // (ttlSeconds) or have its backend pod reclaimed while still being briefly\n // reported RUNNING; proxying to such a dead pod fails with a terminal state\n // (\"Backend resource no longer exists\") or a permanent 502 cf-proxy timeout.\n // Returns true only when the in-sandbox agent responds; false means stale.\n const ensureSandboxReachable = async (candidateId: string): Promise<boolean> => {\n // ★ Skip a proof we already have. This ran two network waits before the\n // model saw the prompt on EVERY turn, including turns seconds after the\n // last one succeeded — a constant tax, felt most in voice where it sits\n // between the user finishing a sentence and hearing anything.\n //\n // Safe only because every failure path below invalidates: see the catch\n // here and the turn-level catch. A cache that were only ever written on\n // success would pin a dead sandbox and turn a recoverable error into a\n // loop.\n if (sandboxReadiness.current.isFresh(candidateId)) return true;\n try {\n await waitForSandboxReady(apollo, candidateId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, candidateId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n sandboxReadiness.current.markVerified(candidateId);\n return true;\n } catch {\n // Stale/expired sandbox — drop it so we provision a fresh one below\n // instead of surfacing \"Internal server error\" to the user.\n sandboxReadiness.current.invalidate(candidateId);\n return false;\n }\n };\n\n // 1) Try the locally-remembered sandbox, then 2) any running one on the\n // server. Each is only kept if it's actually reachable.\n if (currentSandboxId) {\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', 'Reusing assistant environment...');\n if (!(await ensureSandboxReachable(currentSandboxId))) {\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = null;\n }\n }\n\n if (!currentSandboxId) {\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Looking for existing environment...'\n );\n const existingId = await findExistingSandbox(apollo, workspaceId, currentMode, authContext);\n\n if (existingId) {\n setSandbox(currentMode, existingId, 'provisioning');\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Reusing assistant environment...'\n );\n if (await ensureSandboxReachable(existingId)) {\n currentSandboxId = existingId;\n } else {\n setSandbox(currentMode, null, 'provisioning');\n }\n }\n }\n\n // 3) No reusable, reachable sandbox — provision a fresh one.\n if (!currentSandboxId) {\n if (currentMode === 'api-calls' && !getAccessToken()) {\n throw new Error('API Calls mode requires an authenticated session. Please sign in again.');\n }\n\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Starting assistant environment...'\n );\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = await createAssistantSandbox(apollo, currentMode, workspaceId, authContext);\n\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n await waitForSandboxReady(apollo, currentSandboxId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, currentSandboxId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n }\n\n setSandbox(currentMode, currentSandboxId, 'running');\n\n let sessionId =\n useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n ?.backendSessionId ?? null;\n\n if (sessionId) {\n try {\n const session = await getAssistantSession(apollo, currentSandboxId, workspaceId, sessionId, authContext);\n if (session.mode !== currentMode) {\n throw new Error(`Session mode mismatch: expected ${currentMode}, received ${session.mode}`);\n }\n } catch {\n clearBackendSessionId(conversationId);\n sessionId = null;\n }\n }\n\n if (!sessionId) {\n updateConversationStage(conversationId, assistantMessageId, 'connecting', 'Preparing session...');\n const result = await createAssistantSession(apollo, currentSandboxId, workspaceId, currentMode, authContext);\n sessionId = result.sessionId;\n setBackendSessionId(conversationId, sessionId);\n }\n\n return {\n sandboxId: currentSandboxId,\n sessionId,\n };\n },\n [apollo, clearBackendSessionId, getAccessToken, setBackendSessionId, setSandbox, updateConversationStage]\n );\n\n const handleSend = useCallback(\n async (content: string, attachments: AssistantAttachment[] = [], options: { dictated?: boolean } = {}) => {\n // Only block re-entry while a turn is genuinely in-flight. Earlier code\n // checked for *any* entry in the map, which stuck around as `complete`\n // / `error` after the first turn — making every subsequent message\n // silently disappear (the input cleared but handleSend bailed before\n // adding the user message to the conversation).\n //\n // The store is read LIVE, and that is what makes the guard work. The\n // render-captured `processingByConversationId` is stale by construction —\n // the click that starts a turn and the click that must be rejected can\n // belong to the same render. Reading `activeConversationId` live matters\n // for the same reason: on two racing first-ever sends, the second must see\n // the conversation the first one created a moment ago.\n //\n // Pairs with the synchronous `setConversationProcessing` below: because\n // the status is written before this function ever awaits, a second call —\n // however soon it arrives — always observes 'provisioning'.\n const storeAtEntry = useAssistantStore.getState();\n const guardConversationId = storeAtEntry.activeConversationId ?? activeConversationId;\n if (guardConversationId) {\n if (isTurnInFlight(storeAtEntry.processingByConversationId[guardConversationId]?.status)) return;\n // Second lock, in case a future change moves the status write later:\n // this one cannot be cleared by anything but the turn's own `finally`.\n // Deliberately per-conversation — a global key would keep blocking\n // after the conversation it belonged to was deleted mid-turn, and then\n // silently swallow every subsequent send.\n if (inFlightSendsRef.current.has(guardConversationId)) return;\n }\n\n const selectedMode = storeAtEntry.mode;\n let conversationId = activeConversationId;\n const currentConversation = conversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n : undefined;\n\n if (!conversationId) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (\n currentConversation &&\n currentConversation.mode !== selectedMode &&\n (currentConversation.messages.length > 0 || currentConversation.backendSessionId)\n ) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (currentConversation && currentConversation.mode !== selectedMode) {\n setConversationMode(conversationId, selectedMode);\n }\n\n if (!conversationId) return;\n\n // Keyed by conversation: the ref outlives a conversation switch, and a\n // single global slot meant Retry in one thread replayed another thread's\n // photo onto it.\n lastSentAttachmentsRef.current[conversationId] = attachments;\n\n const workspaceId = getWorkspaceId();\n const authContext: AssistantSandboxAuthContext = {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n };\n\n const userMessage: Message = {\n id: generateId(),\n role: 'user',\n content,\n timestamp: new Date().toISOString(),\n // Slim descriptors only — the bubble re-resolves thumbnails from the\n // file id, so the persisted conversation stays small.\n metadata: attachments.length ? { attachments: attachments.map(toMessageAttachment) } : undefined,\n };\n addMessage(conversationId, userMessage);\n\n const assistantMessageId = generateId();\n addMessage(conversationId, {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n timestamp: new Date().toISOString(),\n // Stamped now, not read later: this is the language the reply is being\n // generated in, and the preference may have moved on by the time\n // somebody presses Listen.\n metadata: { lang: replyLanguageCode },\n });\n\n // Mark the turn in-flight in the STORE right now, synchronously.\n //\n // Until this line the first status write happened inside\n // `ensureAssistantRuntime`, i.e. one await later. During that window\n // `activeIsProcessing` was false and `failedMessageId` still pointed at\n // the PREVIOUS failure — so the composer stayed enabled and, worse, the\n // Retry button (which has no `disabled` of its own) stayed mounted and\n // clickable on top of a turn that had already started.\n //\n // Status only, deliberately no stage copy: `ensureAssistantRuntime` picks\n // the accurate wording a moment later (\"Reusing...\" vs \"Starting...\"), and\n // guessing here would flash the wrong one on every reused sandbox.\n setConversationProcessing(conversationId, 'provisioning', assistantMessageId, null);\n\n const applyAssistantResponse = (\n response: string,\n artifacts?: AssistantArtifact[],\n sessionId?: string,\n sandboxId?: string,\n // Our own hard-coded copy is English regardless of what the user picked.\n // Stamping it with their language makes playback read an English quota\n // message in a Tamil voice — Latin text cannot be script-detected, so\n // this metadata is trusted absolutely.\n lang: string = replyLanguageCode\n ) => {\n // `patchMessage` REPLACES metadata rather than merging it, so anything\n // omitted here is destroyed — which is how the turn-language stamp set\n // at creation was being wiped the moment the response completed,\n // silently undoing per-message language resolution. Always re-assert it.\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n metadata: {\n lang,\n ...(artifacts?.length ? { artifacts } : {}),\n ...(artifacts?.length || sessionId || sandboxId ? { mode: selectedMode } : {}),\n ...(sessionId ? { sessionId } : {}),\n ...(sandboxId ? { sandboxId } : {}),\n },\n });\n };\n\n const sendWithRealBackend = async (attempt: 1 | 2 = 1): Promise<void> => {\n // Set when this attempt had to re-send without the image bytes, so the\n // answer can say so rather than quietly reading as if the model looked.\n let imagesDropped = false;\n // Pre-flight AI-credit gate. The wspace gateway's @usage(checkQuota)\n // rejects with 429 QUOTA_EXHAUSTED when the monthly token budget is\n // depleted — block the send (don't provision a sandbox or dispatch the\n // prompt) and surface the upgrade dialog instead of a generic error.\n try {\n await checkAssistantAiCredits(apollo, workspaceId, authContext);\n } catch (creditError) {\n if (isQuotaExhaustedError(creditError)) {\n dispatchAssistantQuotaExhausted('ai-credits');\n applyAssistantResponse(\n \"You've run out of AI credits for this billing cycle. Upgrade your plan to keep chatting.\",\n undefined,\n undefined,\n undefined,\n 'en'\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n // The pre-flight gate exists ONLY to catch a genuine QUOTA_EXHAUSTED\n // rejection. Any other failure here is a transient fault in the\n // credit check itself — e.g. the usage subgraph's getUsageSummary /\n // checkAiCredits intermittently 500s (Postgres/Prisma blip) and the\n // gateway masks it as the opaque \"Unexpected error.\". That is NOT\n // proof the user is out of budget, so it must not abort an otherwise\n // valid send. Fail open and proceed: the wspace gateway's\n // @usage(checkQuota) on createSandbox still enforces the real budget\n // downstream (a truly over-quota caller is stopped there with a 429\n // that surfaces the upgrade dialog via the outer catch).\n console.warn(\n '[assistant] AI-credit pre-flight check failed with a non-quota error; proceeding — gateway @usage(checkQuota) still enforces the real budget downstream',\n creditError\n );\n }\n\n try {\n const { sandboxId, sessionId } = await ensureAssistantRuntime(\n conversationId,\n assistantMessageId,\n selectedMode,\n workspaceId,\n authContext\n );\n\n // Snapshot the newest message timestamp already present in this\n // (possibly reused) session BEFORE sending the prompt, so we can\n // recognise THIS turn's reply as the one created after it — never by\n // comparing the browser clock to the sandbox clock (see\n // buildAssistantProgress). The newest-N window always contains the\n // newest message, so this floor is exact regardless of conversation depth.\n const priorMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n ).catch((): AssistantRawMessage[] => []);\n const priorNewestCreatedMs = priorMessages.reduce(\n (newest, message) => Math.max(newest, getRawMessageCreatedAt(message)),\n 0\n );\n\n updateConversationStage(conversationId, assistantMessageId, 'streaming', 'Thinking...');\n // Two agent-only wrappers around the raw content, both invisible in\n // the bubble: the soft confirm-before-mutate guard for api-calls mode,\n // and the attachment block (metadata + URLs, with text-like files\n // inlined) that carries this turn's files to the model.\n // …and the language directive, so the reply comes back in the user's\n // language rather than defaulting to the language of the docs the\n // model grounds on. The FE is the only layer that knows the locale —\n // it is not on the wire and `pageContext` silently drops unknown keys.\n const promptText = buildPromptForMode(\n selectedMode,\n buildPromptWithAttachments(content, attachments),\n replyLanguageName,\n languageIsExplicit,\n options.dictated === true\n );\n // Structured multimodal parts carry the image PIXELS, which no amount\n // of prompt text can. Built from the same `promptText`, so a bridge\n // that ignores `parts` loses nothing; `undefined` for an ordinary text\n // turn keeps the wire body unchanged.\n const promptParts = buildPromptParts(promptText, attachments);\n const inlinedCount = countInlinedImageParts(promptParts);\n const carriesPixels = inlinedCount > 0;\n const pageContext = gatherPageContext();\n\n // `buildPromptParts` may have demoted a photo to a link to keep the\n // body under the gateway's cap — a long message can do that on prompt\n // text alone. That decision is invisible to the user unless we say so,\n // and an answer that reads as if the model looked at a photo it never\n // received is worse than a short note.\n imagesDropped = countInlineImageCandidates(attachments) > inlinedCount;\n\n try {\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n promptParts\n );\n } catch (sendError) {\n // `buildPromptParts` already sizes the PARTS to the gateway's cap\n // (the prompt string itself is not bounded here), so reaching this\n // point means something rejected the body anyway — a tighter proxy\n // than we modelled, or a bridge that will not take `parts` at all.\n // Losing the whole question over that is the worst outcome\n // available: re-send it text-only. Only for errors that provably\n // never reached the agent (see isMultimodalBodyRejection) — a blind\n // retry would ask the same question twice and bill it twice.\n //\n // Gated on `parts` existing at all, NOT on it carrying pixels: the\n // array duplicates the whole prompt in `parts[0]`, so a url-only\n // parts array is itself enough to push a long message over the cap.\n // `carriesPixels` only decides whether the user is told something\n // was lost.\n if (!promptParts || !isMultimodalBodyRejection(sendError)) throw sendError;\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n undefined\n );\n // Only claim a photo was lost if one actually was — a url-only\n // retry loses nothing the prompt block did not already carry.\n imagesDropped = imagesDropped || carriesPixels;\n }\n\n let result = buildAssistantProgress([], priorNewestCreatedMs);\n const timeoutAt = Date.now() + (STREAM_BUDGET_MS[selectedMode] ?? DEFAULT_STREAM_BUDGET_MS);\n let lastTtlExtensionAt = Date.now();\n\n const pollStartedAt = Date.now();\n while (Date.now() < timeoutAt) {\n const sessionMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n );\n\n result = buildAssistantProgress(sessionMessages, priorNewestCreatedMs);\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(result.content),\n });\n\n if (result.done) break;\n\n if (Date.now() - lastTtlExtensionAt > 30_000) {\n await extendAssistantSandboxTTL(apollo, sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n // Fast early, backing off after — see assistantPollSchedule. This is\n // the granularity of the whole turn: it bounds how late the answer\n // appears AND how late speech can start, because auto-speak only\n // fires once a poll observes the reply completed.\n await new Promise((resolve) => setTimeout(resolve, pollDelayMs(Date.now() - pollStartedAt)));\n }\n\n // For non-build modes a timeout is a hard failure. For vibe-plugins the\n // prompt runs async server-side (/sessions/:id/prompt-async) and keeps\n // writing artifacts after the poll budget elapses, so we surface whatever\n // it has produced instead of discarding the turn.\n if (!result.done && selectedMode !== 'vibe-plugins') {\n throw new Error('Assistant response timed out while streaming progress');\n }\n\n const artifacts =\n selectedMode === 'vibe-plugins'\n ? await getAssistantArtifacts(apollo, sandboxId, workspaceId, sessionId, authContext).catch(() => [])\n : undefined;\n\n if (!result.done) {\n // vibe-plugins build still running in the background. Append a note so\n // the user knows the answer is partial and the artifacts will finish.\n result = {\n ...result,\n content: `${result.content}\\n\\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`,\n };\n }\n\n if (imagesDropped) {\n // Said plainly, because the alternative is an answer that looks like\n // it examined a photo it never received.\n result = {\n ...result,\n content: `${result.content}\\n\\n${tr(\n 'healthybowl.assistant.attachments.imagesNotSent',\n '_Your photo was too large to include with this message, so the answer above is from the text and the file link only. Try a smaller or more tightly cropped photo._'\n )}`,\n };\n }\n\n applyAssistantResponse(result.content, artifacts, sessionId, sandboxId);\n\n if (result.tokens) {\n patchMessage(conversationId, assistantMessageId, { tokens: result.tokens });\n // Charge the real token usage against the AI-credits quota (the\n // gateway records it via @usage(trackUsage)). We AWAIT it before\n // marking the turn complete / re-enabling input: otherwise a rapid\n // follow-up send would run its pre-flight checkAiCredits against a\n // stale balance (this turn's charge still in flight) and could\n // dispatch a prompt that should have been blocked, letting fast\n // sends bypass the credit cap. Still best-effort — a charge failure\n // never blocks the displayed answer.\n try {\n await reportAssistantAiTokenUsage(apollo, workspaceId, sessionId, result.tokens, authContext);\n notifyAiCreditsUpdated();\n } catch {\n // ignore — server-side @usage tracking is the source of truth\n }\n }\n setConversationProcessing(conversationId, 'complete', assistantMessageId, null);\n } catch (error) {\n if (attempt === 1 && isRecoverableAssistantError(error)) {\n clearBackendSessionId(conversationId);\n clearSandbox(selectedMode);\n return sendWithRealBackend(2);\n }\n\n throw error;\n }\n };\n\n // Claim the slot immediately before the first await, and release it in\n // `finally` so every exit — success, quota return, thrown error — frees\n // it. Registering here rather than earlier means a synchronous throw in\n // the setup above can never strand a key and wedge the conversation.\n const turnConversationId = conversationId;\n inFlightSendsRef.current.add(turnConversationId);\n\n try {\n if (!workspaceId) {\n throw new Error('Assistant backend is unavailable without an active workspace context.');\n }\n await sendWithRealBackend();\n } catch (error) {\n // ★ Any failed turn drops the readiness proof for the sandbox it used,\n // so the NEXT turn re-probes instead of trusting a cache entry that a\n // dead pod would otherwise keep alive until the TTL lapsed. This is the\n // half that makes the short-circuit above safe.\n sandboxReadiness.current.invalidate(\n useAssistantStore.getState().sandboxesByMode[selectedMode]?.sandboxId ?? null\n );\n // A quota error reaching here is the sandbox-environment wall hit\n // during runtime provisioning (createSandbox @usage). Surface the\n // upgrade dialog instead of a generic failure (the AI-credit wall is\n // already handled by the pre-flight gate above).\n if (isQuotaExhaustedError(error)) {\n dispatchAssistantQuotaExhausted('sandbox');\n applyAssistantResponse(\n \"You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.\",\n undefined,\n undefined,\n undefined,\n 'en'\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n const errorMessage = error instanceof Error ? error.message : 'Something went wrong';\n setConversationProcessing(conversationId, 'error', assistantMessageId, errorMessage);\n // Same reason: English copy must not inherit the turn's language stamp.\n patchMessage(conversationId, assistantMessageId, {\n content: `Sorry, an error occurred: ${errorMessage}. Please try again.`,\n metadata: { lang: 'en' },\n });\n } finally {\n inFlightSendsRef.current.delete(turnConversationId);\n }\n },\n [\n activeConversationId,\n addMessage,\n apollo,\n clearBackendSessionId,\n clearSandbox,\n conversations,\n createConversation,\n ensureAssistantRuntime,\n getAccessToken,\n getWorkspaceToken,\n patchMessage,\n // Without this, switching language mid-conversation keeps sending the\n // previous language's directive until something else re-creates the\n // callback.\n languageIsExplicit,\n replyLanguageCode,\n replyLanguageName,\n setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n tr,\n updateConversationStage,\n userId,\n ]\n );\n\n const handleSuggestionClick = useCallback(\n (suggestion: string) => {\n void handleSend(suggestion);\n },\n [handleSend]\n );\n\n // Retry re-sends the most recent user prompt through the same transport — the\n // failed assistant turn stays in the transcript, a fresh one is appended.\n // The attachments come from the in-memory ref rather than the message\n // metadata: the persisted descriptors deliberately drop the inlined text of\n // text-like files, so rebuilding from them would silently retry a WEAKER\n // prompt than the one that failed.\n const handleRetry = useCallback(() => {\n const lastUserMessage = [...messages].reverse().find((message) => message.role === 'user');\n const replay = activeConversationId ? (lastSentAttachmentsRef.current[activeConversationId] ?? []) : [];\n if (lastUserMessage) void handleSend(lastUserMessage.content, replay);\n }, [messages, handleSend, activeConversationId]);\n\n // Auto-send any prompt that was queued by `useOpenAssistantHelp` (from\n // the shared GetHelpButton). We keep the latest handleSend in a ref so\n // the subscription effect below doesn't need to tear down on every\n // render — the store subscription lives for the component lifetime and\n // always calls the freshest handler.\n const handleSendRef = useRef(handleSend);\n useEffect(() => {\n handleSendRef.current = handleSend;\n }, [handleSend]);\n\n /**\n * The newest assistant reply, as the voice session's advance signal.\n *\n * Keyed on the message ID rather than the text: two consecutive answers can be\n * word-for-word identical, and text alone would then never advance the second\n * turn.\n */\n const latestAssistantReply = useMemo(() => {\n // ★ Only once the turn is COMPLETE. While it is in flight the pending\n // assistant message is patched with progress text — 'Starting assistant\n // environment...', 'Thinking...' — and exposing that would make the voice\n // session consume the message id, enter `speaking` on a placeholder, and\n // then be unable to advance when the real answer replaced it.\n if (activeIsProcessing) return null;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (message?.role !== 'assistant') continue;\n // Tool-activity markup is stripped so the session captions and speaks the\n // answer, not the machinery that produced it.\n const text = parseToolActivity(message.content).text.trim();\n return text ? { id: message.id, text } : null;\n }\n return null;\n }, [messages, activeIsProcessing]);\n\n /**\n * The last few exchanges, for the session's on-screen transcript.\n *\n * Voice turns already go through the normal send path, so they are ordinary\n * conversation messages — this only surfaces them INSIDE the session, which\n * is what makes a second question in the same session make sense.\n */\n const voiceTurns = useMemo(\n () =>\n messages\n .filter((message) => message.role === 'user' || message.role === 'assistant')\n .slice(-6)\n .map((message) => ({\n id: message.id,\n role: message.role as 'user' | 'assistant',\n text: parseToolActivity(message.content).text.trim(),\n }))\n .filter((turn) => turn.text.length > 0),\n [messages]\n );\n\n const submitVoiceTurn = useCallback((text: string) => {\n // ★ Only the voice SESSION is unambiguously dictated. The composer's\n // microphone also produces a transcript, but the user reads and edits it in\n // the box before sending, so treating that as dictated would tell the model\n // to second-guess words the user had already approved.\n void handleSendRef.current(text, [], { dictated: true });\n }, []);\n\n const voiceSession = useVoiceSession({\n onSubmit: submitVoiceTurn,\n latestReply: latestAssistantReply,\n // The language the user SPEAKS, not the interface language — the same\n // preference the composer's dictation and the reply language already use.\n language: resolveAssistantLanguage(assistantLanguage, locale).tag,\n });\n\n // Hiding the panel must end a live voice session. The host may set `visible`\n // false WITHOUT unmounting, and an unmount-only cleanup would then leave the\n // microphone recording behind an invisible panel — a privacy problem, not\n // just a leak.\n useEffect(() => {\n if (!visible && voiceSession.active) voiceSession.end();\n }, [visible, voiceSession]);\n\n useEffect(() => {\n // Flush any prompt that was queued before this component mounted.\n const initial = useAssistantStore.getState().consumePendingPrompt();\n if (initial) {\n void handleSendRef.current(initial);\n }\n\n // Watch for new prompts queued while we're already mounted.\n const unsubscribe = useAssistantStore.subscribe((state, prev) => {\n if (state.pendingPrompt && state.pendingPrompt !== prev.pendingPrompt) {\n const queued = useAssistantStore.getState().consumePendingPrompt();\n if (queued) {\n void handleSendRef.current(queued);\n }\n }\n });\n return unsubscribe;\n }, []);\n\n const performModeChange = useCallback(\n (newMode: AssistantMode) => {\n const currentConversation = activeConversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === activeConversationId)\n : undefined;\n\n if (currentConversation && (currentConversation.messages.length > 0 || currentConversation.backendSessionId)) {\n if (currentConversation.mode !== newMode) {\n const reusableDraft = useAssistantStore\n .getState()\n .conversations.find(\n (conversation) =>\n conversation.mode === newMode &&\n conversation.messages.length === 0 &&\n !conversation.backendSessionId &&\n !useAssistantStore.getState().processingByConversationId[conversation.id]\n );\n\n if (reusableDraft) {\n setActiveConversation(reusableDraft.id);\n } else {\n createConversation(undefined, newMode);\n }\n }\n } else if (activeConversationId) {\n setConversationMode(activeConversationId, newMode);\n }\n\n setMode(newMode);\n },\n [activeConversationId, createConversation, setActiveConversation, setConversationMode, setMode]\n );\n\n const handleModeChange = useCallback(\n (newMode: AssistantMode) => {\n const target = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === newMode);\n // Gate the FIRST switch into a write-capable mode behind the one-time\n // consent dialog — the dependable confirm-before-mutate guardrail.\n if (target?.writeCapable && !useAssistantStore.getState().apiCallsAcknowledged) {\n setPendingConsentMode(newMode);\n return;\n }\n performModeChange(newMode);\n },\n [performModeChange]\n );\n\n const handleConsentConfirm = useCallback(() => {\n const target = pendingConsentMode;\n setPendingConsentMode(null);\n acknowledgeApiCalls();\n if (target) performModeChange(target);\n }, [pendingConsentMode, acknowledgeApiCalls, performModeChange]);\n\n const handleConsentCancel = useCallback(() => {\n setPendingConsentMode(null);\n }, []);\n\n return (\n // `relative` so the DOCKED voice session can position itself against the\n // assistant panel rather than the viewport. Without it the docked overlay\n // would anchor to the page and cover the whole app, which is the very thing\n // docking exists to avoid.\n <div className=\"relative flex flex-1 flex-col overflow-hidden\">\n {/* Everything the voice overlay covers is made `inert` while a session is\n open. Docked, the overlay hides the transcript and composer but does\n NOT cover the page, so a full focus trap would wrongly imprison the\n user — yet leaving these focusable lets them Shift+Tab into controls\n they cannot see and operate them blind. `inert` is the precise tool:\n the page stays reachable, the covered controls do not. */}\n <div className=\"contents\" inert={voiceSession.active || undefined}>\n {/* Transcript is always visible now — the old collapse-by-default accordion\n is gone; conversation history lives behind the header button instead. */}\n {messages.length === 0 ? (\n <AssistantEmptyState mode={mode} onSuggestionClick={handleSuggestionClick} />\n ) : (\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <AssistantMessageList\n messages={messages}\n streamingMessageId={activeStreamingMessageId}\n failedMessageId={failedMessageId}\n onRetry={handleRetry}\n />\n </div>\n )}\n\n <AssistantComposer\n // ★ Ask-mode only, and enforced here rather than merely documented.\n // In `api-calls` mode the assistant WRITES to farm data behind a consent\n // gate, and BOFF-6377 (\"confirm-before-write cannot prove a human\n // approved\") is still open — a spoken \"yes, do it\" is exactly the case\n // that ticket is about. Voice control of writes is the NEXT phase, not\n // this one, so the launcher is simply absent in that mode.\n onStartVoiceSession={voiceSession.available && mode !== 'api-calls' ? voiceSession.start : undefined}\n onSend={(value, attachments) => void handleSend(value, attachments)}\n disabled={activeIsProcessing}\n placeholder={\n mode === 'api-calls'\n ? tr('healthybowl.assistant.chatArea.placeholderActions', 'What would you like me to do?')\n : tr('healthybowl.assistant.chatArea.placeholderGeneral', 'Ask HealthyBowl anything…')\n }\n mode={mode}\n availableModes={availableModes}\n onModeChange={handleModeChange}\n />\n </div>\n\n {voiceSession.active && (\n <AssistantVoiceSession\n session={voiceSession.session}\n notice={voiceSession.notice}\n turns={voiceTurns}\n onInterrupt={voiceSession.interrupt}\n spoken={latestAssistantReply?.text ?? null}\n onToggleMute={voiceSession.toggleMute}\n onEnd={voiceSession.end}\n />\n )}\n\n <AssistantApiCallsConsentDialog\n open={pendingConsentMode !== null}\n onConfirm={handleConsentConfirm}\n onCancel={handleConsentCancel}\n />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,IAAM,KAAkD;CACtD,SAAS;CACT,WAAW;CACX,aAAa;CACb,gBAAgB;AAClB,GACM,KAA2B;AAEjC,SAAS,KAAqB;CAC5B,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC;AAC/D;AAEA,SAAS,GAA0B,GAA0B;CAC3D,OAAO,EACJ,QAAQ,6CAA6C,cAAc,EACnE,QAAQ,yDAAyD,cAAc,EAC/E,QAAQ,4DAA4D,gBAAgB,EACpF,QAAQ,6BAA6B,oBAAoB;AAC9D;AAEA,SAAS,EAAuB,GAAsC;CACpE,OAAO,EAAQ,MAAM,MAAM,WAAW;AACxC;AAEA,SAAS,EAAiB,GAA6C;CACrE,QAAQ,KAAS,CAAC,GACf,QAAQ,MAAS,EAAK,SAAS,UAAU,OAAO,EAAK,QAAS,QAAQ,EACtE,KAAK,MAAS,EAAK,MAAM,KAAK,KAAK,EAAE,EACrC,OAAO,OAAO,EACd,KAAK,IAAI;AACd;AAEA,SAAS,EAAgB,GAA+C;CACtE,QAAQ,KAAS,CAAC,GACf,QAAQ,MAAS,EAAK,SAAS,UAAU,EAAK,IAAI,EAClD,KAAK,MAAS;EACb,IAAM,IAAS,EAAK,OA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edTtsProtocol.ts
2
- var e = 2e3;
3
- function t(e, t, n, r, i) {
2
+ function e(e, t) {
3
+ return t ? !1 : e === "not-allowed" || e === "unsupported";
4
+ }
5
+ var t = 2e3;
6
+ function n(e, t, n, r, i) {
4
7
  let a = {
5
8
  text: e,
6
9
  languageCode: t,
@@ -8,27 +11,27 @@ function t(e, t, n, r, i) {
8
11
  };
9
12
  return r && r.toLowerCase().startsWith(t.toLowerCase()) && (a.voiceName = r), i !== void 0 && (a.speakingRate = i), a;
10
13
  }
11
- function n(e) {
14
+ function r(e) {
12
15
  return e === 401 || e === 403 ? "not-allowed" : e === 404 || e === 501 ? "unsupported" : "unknown";
13
16
  }
14
- function r(e) {
17
+ function i(e) {
15
18
  let t = globalThis.Buffer, n = typeof atob == "function" ? atob(e) : t?.from(e, "base64").toString("binary") ?? "", r = new Uint8Array(n.length);
16
19
  for (let e = 0; e < n.length; e += 1) r[e] = n.charCodeAt(e);
17
20
  return r;
18
21
  }
19
- function i(e, t) {
22
+ function a(e, t) {
20
23
  if (t instanceof ArrayBuffer) return t.byteLength > 0 ? new Uint8Array(t) : null;
21
24
  if (e?.includes("json") || typeof t == "object") {
22
25
  let e = t.audioContent;
23
26
  if (!e) return null;
24
- let n = r(e);
27
+ let n = i(e);
25
28
  return n.length > 0 ? n : null;
26
29
  }
27
30
  return null;
28
31
  }
29
- function a(t, n = e) {
30
- if (t.length <= n) return [t];
31
- let r = [], i = t;
32
+ function o(e, n = t) {
33
+ if (e.length <= n) return [e];
34
+ let r = [], i = e;
32
35
  for (; i.length > n;) {
33
36
  let e = i.slice(0, n).lastIndexOf(" "), t = e > n * .5 ? e : n;
34
37
  r.push(i.slice(0, t).trim()), i = i.slice(t).trim();
@@ -36,6 +39,6 @@ function a(t, n = e) {
36
39
  return i && r.push(i), r.filter((e) => e.length > 0);
37
40
  }
38
41
  //#endregion
39
- export { t as buildRequest, n as classifyHttpFailure, i as decodeAudioResponse, a as splitForVendor };
42
+ export { n as buildRequest, r as classifyHttpFailure, a as decodeAudioResponse, e as shouldDisableEngine, o as splitForVendor };
40
43
 
41
44
  //# sourceMappingURL=hostedTtsProtocol.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hostedTtsProtocol.js","names":[],"sources":["../../../src/services/speech/hostedTtsProtocol.ts"],"sourcesContent":["/**\n * The wire contract for the hosted TTS proxy, kept pure so it can be tested\n * (BOFF-7111).\n *\n * `browserSpeechEngine` carries a note explaining that it is untestable in this\n * repo — vitest runs in the `node` environment with no DOM and no audio — and\n * that the testable logic was deliberately kept out of it. Same discipline\n * here: request building, response decoding and error classification live in\n * this file with no `window`, `Audio` or `fetch` reference, and the engine file\n * holds only the parts that genuinely need a browser.\n *\n * The browser never talks to the vendor directly. A Google Cloud service-account\n * key cannot be shipped to a client, so every request goes to our own proxy,\n * which holds the credential and does the vendor call.\n */\n\nimport type { SpeechErrorReason } from './types';\n\n/** What the client sends per chunk. */\nexport interface HostedTtsRequest {\n text: string;\n /** BCP-47, e.g. `ta-IN`. The vendor needs the region, not a bare subtag. */\n languageCode: string;\n /** Vendor voice id, e.g. `ta-IN-Chirp3-HD-Kore`. Omitted = server default. */\n voiceName?: string;\n /** Vendor voice tier, so the backend need not infer it from the name. */\n tier: string;\n /**\n * The same knob the device engine calls `rate`.\n *\n * ★ The accepted range depends on which vendor ENDPOINT the proxy calls, not\n * on the voice tier — see `SPEAKING_RATE_MAX_SYNC` below. Values in use are\n * 0.9, and 0.85 for Indic scripts and Arabic, comfortably inside every\n * variant, so this has never affected playback.\n */\n speakingRate?: number;\n}\n\n/**\n * Google's synthesize response is `{ audioContent: <base64 mp3> }`. We accept\n * that shape directly so the proxy can be a thin pass-through, but the proxy is\n * also free to return raw audio bytes — see `decodeAudioResponse`.\n */\nexport interface HostedTtsJsonResponse {\n audioContent?: string;\n error?: { message?: string };\n}\n\n/**\n * The accepted speaking-rate bounds, for any caller that clamps.\n *\n * ★ The ceiling is a property of the ENDPOINT, not of the voice tier, and the\n * vendor's own rejection message says both numbers out loud:\n *\n * \"Unable to adjust speaking rate. Please ensure that speaking_rate is in the\n * range [0.25, 4.0] for sync synthesis and in the range [0.25, 2.0] for\n * streaming synthesis.\"\n *\n * Measured against the live API on 2026-08-31 with `en-IN-Chirp3-HD-Puck` and a\n * fixed sentence, reading the returned LINEAR16 duration rather than trusting\n * the HTTP status — 4.0 synthesises and is genuinely ~4x faster (21.93s at 0.25\n * down to 1.37s at 4.0); 4.1, 5.0 and 0.2 are all rejected with the message\n * above.\n *\n * This corrects a previous edit of this file which narrowed the ceiling to 2.0\n * and attributed 4.0 to \"the older Standard/WaveNet tiers\". That reading was\n * wrong: 2.0 is the STREAMING limit, and the tier has nothing to do with it.\n *\n * `SPEAKING_RATE_MAX` is the sync ceiling because the proxy calls\n * `v1/text:synthesize`. Moving it to `v1/text:streamingSynthesize` — tempting,\n * since that is how you cut time-to-first-audio — halves the ceiling, and rates\n * the client had treated as valid would start returning 400. That switch has to\n * change this alias in the same commit, which is why both bounds are named\n * rather than one being a magic number.\n */\nexport const SPEAKING_RATE_MIN = 0.25;\nexport const SPEAKING_RATE_MAX_SYNC = 4.0;\nexport const SPEAKING_RATE_MAX_STREAMING = 2.0;\nexport const SPEAKING_RATE_MAX = SPEAKING_RATE_MAX_SYNC;\n\n/** Vendor limit is 5000 bytes per request; stay well inside it. */\nexport const HOSTED_TTS_MAX_CHARS = 2000;\n\nexport function buildRequest(\n text: string,\n languageCode: string,\n tier: string,\n voiceName?: string | null,\n speakingRate?: number\n): HostedTtsRequest {\n const request: HostedTtsRequest = { text, languageCode, tier };\n // A voice name from ANOTHER language must never be forwarded: the vendor\n // would either error or, worse, read the text with the wrong phoneme model.\n // The caller resolves the voice, but this is the last line of defence.\n if (voiceName && voiceName.toLowerCase().startsWith(languageCode.toLowerCase())) {\n request.voiceName = voiceName;\n }\n if (speakingRate !== undefined) request.speakingRate = speakingRate;\n return request;\n}\n\n/**\n * Map a transport failure onto the reasons the UI already knows how to explain.\n *\n * `cancelled` is deliberately NOT produced here — an aborted request is the\n * caller's own doing and the engine reports it, exactly as the browser engine\n * swallows its own `canceled` utterance errors.\n */\nexport function classifyHttpFailure(status: number): SpeechErrorReason {\n // 401/403 mean the proxy rejected us; there is nothing the user can do and\n // \"unsupported\" is what disables the control rather than showing a retry\n // that will fail identically.\n if (status === 401 || status === 403) return 'not-allowed';\n if (status === 404 || status === 501) return 'unsupported';\n return 'unknown';\n}\n\n/** Base64 → bytes, without assuming a DOM (`atob` is not in node). */\nexport function base64ToBytes(base64: string): Uint8Array {\n // `Buffer` only exists under node (the test environment); typed rather than\n // cast through `any`, which this repo's conventions forbid.\n const nodeBuffer = (\n globalThis as unknown as {\n Buffer?: { from(input: string, encoding: string): { toString(encoding: string): string } };\n }\n ).Buffer;\n const binary =\n typeof atob === 'function' ? atob(base64) : (nodeBuffer?.from(base64, 'base64').toString('binary') ?? '');\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\n/**\n * Accept either shape the proxy may return: a JSON body carrying base64\n * (the vendor's own shape, so the proxy can pass it straight through) or raw\n * audio bytes.\n *\n * Returns null when the payload carries no audio at all — which must be treated\n * as a failure, not as silence. A zero-byte \"success\" that plays nothing is the\n * dead-button bug this feature already fixed once.\n */\nexport function decodeAudioResponse(\n contentType: string | null,\n body: ArrayBuffer | HostedTtsJsonResponse\n): Uint8Array | null {\n if (body instanceof ArrayBuffer) {\n return body.byteLength > 0 ? new Uint8Array(body) : null;\n }\n if (contentType?.includes('json') || typeof body === 'object') {\n const encoded = body.audioContent;\n if (!encoded) return null;\n const bytes = base64ToBytes(encoded);\n return bytes.length > 0 ? bytes : null;\n }\n return null;\n}\n\n/**\n * Split text the hosted vendor would reject for length.\n *\n * `chunkForSpeech` already splits for the browser engine's ~15s utterance\n * ceiling, and those chunks are normally far under the vendor limit — this is a\n * backstop for a single pathological sentence, and it splits on whitespace so a\n * word is never cut in half.\n */\nexport function splitForVendor(text: string, limit = HOSTED_TTS_MAX_CHARS): string[] {\n if (text.length <= limit) return [text];\n const out: string[] = [];\n let rest = text;\n while (rest.length > limit) {\n const window = rest.slice(0, limit);\n const cut = window.lastIndexOf(' ');\n // No space at all (CJK, or one enormous token): hard-cut at the limit\n // rather than sending something the vendor will reject outright.\n const at = cut > limit * 0.5 ? cut : limit;\n out.push(rest.slice(0, at).trim());\n rest = rest.slice(at).trim();\n }\n if (rest) out.push(rest);\n return out.filter((part) => part.length > 0);\n}\n"],"mappings":";AAiFA,IAAa,IAAuB;AAEpC,SAAgB,EACd,GACA,GACA,GACA,GACA,GACkB;CAClB,IAAM,IAA4B;EAAE;EAAM;EAAc;CAAK;CAQ7D,OAJI,KAAa,EAAU,YAAY,EAAE,WAAW,EAAa,YAAY,CAAC,MAC5E,EAAQ,YAAY,IAElB,MAAiB,KAAA,MAAW,EAAQ,eAAe,IAChD;AACT;AASA,SAAgB,EAAoB,GAAmC;CAMrE,OAFI,MAAW,OAAO,MAAW,MAAY,gBACzC,MAAW,OAAO,MAAW,MAAY,gBACtC;AACT;AAGA,SAAgB,EAAc,GAA4B;CAGxD,IAAM,IACJ,WAGA,QACI,IACJ,OAAO,QAAS,aAAa,KAAK,CAAM,IAAK,GAAY,KAAK,GAAQ,QAAQ,EAAE,SAAS,QAAQ,KAAK,IAClG,IAAQ,IAAI,WAAW,EAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,EAAO,QAAQ,KAAK,GAAG,EAAM,KAAK,EAAO,WAAW,CAAC;CACzE,OAAO;AACT;AAWA,SAAgB,EACd,GACA,GACmB;CACnB,IAAI,aAAgB,aAClB,OAAO,EAAK,aAAa,IAAI,IAAI,WAAW,CAAI,IAAI;CAEtD,IAAI,GAAa,SAAS,MAAM,KAAK,OAAO,KAAS,UAAU;EAC7D,IAAM,IAAU,EAAK;EACrB,IAAI,CAAC,GAAS,OAAO;EACrB,IAAM,IAAQ,EAAc,CAAO;EACnC,OAAO,EAAM,SAAS,IAAI,IAAQ;CACpC;CACA,OAAO;AACT;AAUA,SAAgB,EAAe,GAAc,IAAQ,GAAgC;CACnF,IAAI,EAAK,UAAU,GAAO,OAAO,CAAC,CAAI;CACtC,IAAM,IAAgB,CAAC,GACnB,IAAO;CACX,OAAO,EAAK,SAAS,IAAO;EAE1B,IAAM,IADS,EAAK,MAAM,GAAG,CACjB,EAAO,YAAY,GAAG,GAG5B,IAAK,IAAM,IAAQ,KAAM,IAAM;EAErC,AADA,EAAI,KAAK,EAAK,MAAM,GAAG,CAAE,EAAE,KAAK,CAAC,GACjC,IAAO,EAAK,MAAM,CAAE,EAAE,KAAK;CAC7B;CAEA,OADI,KAAM,EAAI,KAAK,CAAI,GAChB,EAAI,QAAQ,MAAS,EAAK,SAAS,CAAC;AAC7C"}
1
+ {"version":3,"file":"hostedTtsProtocol.js","names":[],"sources":["../../../src/services/speech/hostedTtsProtocol.ts"],"sourcesContent":["/**\n * The wire contract for the hosted TTS proxy, kept pure so it can be tested\n * (BOFF-7111).\n *\n * `browserSpeechEngine` carries a note explaining that it is untestable in this\n * repo — vitest runs in the `node` environment with no DOM and no audio — and\n * that the testable logic was deliberately kept out of it. Same discipline\n * here: request building, response decoding and error classification live in\n * this file with no `window`, `Audio` or `fetch` reference, and the engine file\n * holds only the parts that genuinely need a browser.\n *\n * The browser never talks to the vendor directly. A Google Cloud service-account\n * key cannot be shipped to a client, so every request goes to our own proxy,\n * which holds the credential and does the vendor call.\n */\n\nimport type { SpeechErrorReason } from './types';\n\n/** What the client sends per chunk. */\nexport interface HostedTtsRequest {\n text: string;\n /** BCP-47, e.g. `ta-IN`. The vendor needs the region, not a bare subtag. */\n languageCode: string;\n /** Vendor voice id, e.g. `ta-IN-Chirp3-HD-Kore`. Omitted = server default. */\n voiceName?: string;\n /** Vendor voice tier, so the backend need not infer it from the name. */\n tier: string;\n /**\n * The same knob the device engine calls `rate`.\n *\n * ★ The accepted range depends on which vendor ENDPOINT the proxy calls, not\n * on the voice tier — see `SPEAKING_RATE_MAX_SYNC` below. Values in use are\n * 0.9, and 0.85 for Indic scripts and Arabic, comfortably inside every\n * variant, so this has never affected playback.\n */\n speakingRate?: number;\n}\n\n/**\n * Google's synthesize response is `{ audioContent: <base64 mp3> }`. We accept\n * that shape directly so the proxy can be a thin pass-through, but the proxy is\n * also free to return raw audio bytes — see `decodeAudioResponse`.\n */\nexport interface HostedTtsJsonResponse {\n audioContent?: string;\n error?: { message?: string };\n}\n\n/**\n * The accepted speaking-rate bounds, for any caller that clamps.\n *\n * ★ The ceiling is a property of the ENDPOINT, not of the voice tier, and the\n * vendor's own rejection message says both numbers out loud:\n *\n * \"Unable to adjust speaking rate. Please ensure that speaking_rate is in the\n * range [0.25, 4.0] for sync synthesis and in the range [0.25, 2.0] for\n * streaming synthesis.\"\n *\n * Measured against the live API on 2026-08-31 with `en-IN-Chirp3-HD-Puck` and a\n * fixed sentence, reading the returned LINEAR16 duration rather than trusting\n * the HTTP status — 4.0 synthesises and is genuinely ~4x faster (21.93s at 0.25\n * down to 1.37s at 4.0); 4.1, 5.0 and 0.2 are all rejected with the message\n * above.\n *\n * This corrects a previous edit of this file which narrowed the ceiling to 2.0\n * and attributed 4.0 to \"the older Standard/WaveNet tiers\". That reading was\n * wrong: 2.0 is the STREAMING limit, and the tier has nothing to do with it.\n *\n * `SPEAKING_RATE_MAX` is the sync ceiling because the proxy calls\n * `v1/text:synthesize`. Moving it to `v1/text:streamingSynthesize` — tempting,\n * since that is how you cut time-to-first-audio — halves the ceiling, and rates\n * the client had treated as valid would start returning 400. That switch has to\n * change this alias in the same commit, which is why both bounds are named\n * rather than one being a magic number.\n */\nexport const SPEAKING_RATE_MIN = 0.25;\nexport const SPEAKING_RATE_MAX_SYNC = 4.0;\nexport const SPEAKING_RATE_MAX_STREAMING = 2.0;\nexport const SPEAKING_RATE_MAX = SPEAKING_RATE_MAX_SYNC;\n\n/**\n * Should a failure stop the engine claiming support for the rest of the page?\n *\n * ★ `not-allowed` has TWO producers and only one of them is terminal:\n *\n * - `classifyHttpFailure` maps HTTP 401/403 to it — the proxy refuses us, and\n * every later request will be refused identically. Latching is right: it\n * makes `routingSpeechEngine` fall back to device voices instead of\n * repeating a request that cannot succeed.\n * - the engine maps the browser's `NotAllowedError` to it — the autoplay\n * policy declining to play audio that was not started by a user gesture.\n * That is PER-GESTURE and entirely transient; the very next tap works.\n *\n * Latching on the second silently deleted the hosted voice for the whole page\n * after a single refusal — and auto-speak is precisely the path that triggers\n * it, because an arriving reply is not a gesture. The user would hear Chirp 3\n * once, be refused once, and get device voices for the rest of the session with\n * nothing explaining why.\n *\n * Pure and exported because the engine itself cannot be unit-tested here (no\n * DOM, no Audio), so the decision is kept where it CAN be.\n */\nexport function shouldDisableEngine(reason: string | undefined, transient: boolean): boolean {\n if (transient) return false;\n return reason === 'not-allowed' || reason === 'unsupported';\n}\n\n/** Vendor limit is 5000 bytes per request; stay well inside it. */\nexport const HOSTED_TTS_MAX_CHARS = 2000;\n\nexport function buildRequest(\n text: string,\n languageCode: string,\n tier: string,\n voiceName?: string | null,\n speakingRate?: number\n): HostedTtsRequest {\n const request: HostedTtsRequest = { text, languageCode, tier };\n // A voice name from ANOTHER language must never be forwarded: the vendor\n // would either error or, worse, read the text with the wrong phoneme model.\n // The caller resolves the voice, but this is the last line of defence.\n if (voiceName && voiceName.toLowerCase().startsWith(languageCode.toLowerCase())) {\n request.voiceName = voiceName;\n }\n if (speakingRate !== undefined) request.speakingRate = speakingRate;\n return request;\n}\n\n/**\n * Map a transport failure onto the reasons the UI already knows how to explain.\n *\n * `cancelled` is deliberately NOT produced here — an aborted request is the\n * caller's own doing and the engine reports it, exactly as the browser engine\n * swallows its own `canceled` utterance errors.\n */\nexport function classifyHttpFailure(status: number): SpeechErrorReason {\n // 401/403 mean the proxy rejected us; there is nothing the user can do and\n // \"unsupported\" is what disables the control rather than showing a retry\n // that will fail identically.\n if (status === 401 || status === 403) return 'not-allowed';\n if (status === 404 || status === 501) return 'unsupported';\n return 'unknown';\n}\n\n/** Base64 → bytes, without assuming a DOM (`atob` is not in node). */\nexport function base64ToBytes(base64: string): Uint8Array {\n // `Buffer` only exists under node (the test environment); typed rather than\n // cast through `any`, which this repo's conventions forbid.\n const nodeBuffer = (\n globalThis as unknown as {\n Buffer?: { from(input: string, encoding: string): { toString(encoding: string): string } };\n }\n ).Buffer;\n const binary =\n typeof atob === 'function' ? atob(base64) : (nodeBuffer?.from(base64, 'base64').toString('binary') ?? '');\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\n/**\n * Accept either shape the proxy may return: a JSON body carrying base64\n * (the vendor's own shape, so the proxy can pass it straight through) or raw\n * audio bytes.\n *\n * Returns null when the payload carries no audio at all — which must be treated\n * as a failure, not as silence. A zero-byte \"success\" that plays nothing is the\n * dead-button bug this feature already fixed once.\n */\nexport function decodeAudioResponse(\n contentType: string | null,\n body: ArrayBuffer | HostedTtsJsonResponse\n): Uint8Array | null {\n if (body instanceof ArrayBuffer) {\n return body.byteLength > 0 ? new Uint8Array(body) : null;\n }\n if (contentType?.includes('json') || typeof body === 'object') {\n const encoded = body.audioContent;\n if (!encoded) return null;\n const bytes = base64ToBytes(encoded);\n return bytes.length > 0 ? bytes : null;\n }\n return null;\n}\n\n/**\n * Split text the hosted vendor would reject for length.\n *\n * `chunkForSpeech` already splits for the browser engine's ~15s utterance\n * ceiling, and those chunks are normally far under the vendor limit — this is a\n * backstop for a single pathological sentence, and it splits on whitespace so a\n * word is never cut in half.\n */\nexport function splitForVendor(text: string, limit = HOSTED_TTS_MAX_CHARS): string[] {\n if (text.length <= limit) return [text];\n const out: string[] = [];\n let rest = text;\n while (rest.length > limit) {\n const window = rest.slice(0, limit);\n const cut = window.lastIndexOf(' ');\n // No space at all (CJK, or one enormous token): hard-cut at the limit\n // rather than sending something the vendor will reject outright.\n const at = cut > limit * 0.5 ? cut : limit;\n out.push(rest.slice(0, at).trim());\n rest = rest.slice(at).trim();\n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AAS,IAAO;EAE1B,IAAM,IADS,EAAK,MAAM,GAAG,CACjB,EAAO,YAAY,GAAG,GAG5B,IAAK,IAAM,IAAQ,KAAM,IAAM;EAErC,AADA,EAAI,KAAK,EAAK,MAAM,GAAG,CAAE,EAAE,KAAK,CAAC,GACjC,IAAO,EAAK,MAAM,CAAE,EAAE,KAAK;CAC7B;CAEA,OADI,KAAM,EAAI,KAAK,CAAI,GAChB,EAAI,QAAQ,MAAS,EAAK,SAAS,CAAC;AAC7C"}
@@ -1,26 +1,26 @@
1
1
  import { HOSTED_TTS_TIER as e, HOSTED_VOICES as t, hostedLocaleFor as n } from "./hostedVoiceCatalogue.js";
2
- import { buildRequest as r, classifyHttpFailure as i, decodeAudioResponse as a, splitForVendor as o } from "./hostedTtsProtocol.js";
2
+ import { buildRequest as r, classifyHttpFailure as i, decodeAudioResponse as a, shouldDisableEngine as o, splitForVendor as s } from "./hostedTtsProtocol.js";
3
3
  //#region src/services/speech/hostedTtsSpeechEngine.ts
4
- function s(s) {
5
- let c = s.fetchImpl ?? ((...e) => fetch(...e)), l = null, u = null, d = 0, f = null, p = !1, m = () => {
6
- u &&= (URL.revokeObjectURL(u), null);
7
- }, h = () => {
8
- if (l) {
9
- l.onended = null, l.onerror = null;
4
+ function c(c) {
5
+ let l = c.fetchImpl ?? ((...e) => fetch(...e)), u = null, d = null, f = 0, p = null, m = !1, h = () => {
6
+ d &&= (URL.revokeObjectURL(d), null);
7
+ }, g = () => {
8
+ if (u) {
9
+ u.onended = null, u.onerror = null;
10
10
  try {
11
- l.pause();
11
+ u.pause();
12
12
  } catch {}
13
- l = null;
13
+ u = null;
14
14
  }
15
- m();
15
+ h();
16
16
  };
17
- async function g(t, o, l) {
18
- let u = r(t, n(o.lang) ?? o.lang, e, o.voice?.name ?? null, o.rate), d = await c(s.endpoint, {
17
+ async function _(t, o, s) {
18
+ let u = r(t, n(o.lang) ?? o.lang, e, o.voice?.name ?? null, o.rate), d = await l(c.endpoint, {
19
19
  method: "POST",
20
- signal: l,
20
+ signal: s,
21
21
  headers: {
22
22
  "content-type": "application/json",
23
- ...s.getHeaders?.() ?? {}
23
+ ...c.getHeaders?.() ?? {}
24
24
  },
25
25
  body: JSON.stringify(u)
26
26
  });
@@ -35,40 +35,40 @@ function s(s) {
35
35
  }
36
36
  return p;
37
37
  }
38
- function _(e, t, n) {
38
+ function v(e, t, n) {
39
39
  return new Promise((r, i) => {
40
- if (t !== d) {
40
+ if (t !== f) {
41
41
  r();
42
42
  return;
43
43
  }
44
44
  let a = new Blob([e.slice().buffer], { type: "audio/mpeg" });
45
- m(), u = URL.createObjectURL(a);
46
- let o = new Audio(u);
47
- l = o, o.onended = () => {
48
- t === d && r();
45
+ h(), d = URL.createObjectURL(a);
46
+ let o = new Audio(d);
47
+ u = o, o.onended = () => {
48
+ t === f && r();
49
49
  }, o.onerror = () => {
50
- if (t !== d) {
50
+ if (t !== f) {
51
51
  r();
52
52
  return;
53
53
  }
54
54
  let e = /* @__PURE__ */ Error("audio playback failed");
55
55
  e.reason = "unknown", i(e);
56
56
  }, o.play().then(() => {
57
- t === d && n?.();
57
+ t === f && n?.();
58
58
  }, (e) => {
59
- if (t !== d) {
59
+ if (t !== f) {
60
60
  r();
61
61
  return;
62
62
  }
63
- let n = /* @__PURE__ */ Error("audio play rejected");
64
- n.reason = e?.name === "NotAllowedError" ? "not-allowed" : "unknown", i(n);
63
+ let n = /* @__PURE__ */ Error("audio play rejected"), a = e?.name === "NotAllowedError";
64
+ n.reason = a ? "not-allowed" : "unknown", n.transient = a, i(n);
65
65
  });
66
66
  });
67
67
  }
68
68
  return {
69
69
  id: "hosted-tts",
70
70
  isSupported() {
71
- return p ? !1 : typeof window < "u" && typeof window.Audio == "function" && typeof fetch == "function";
71
+ return m ? !1 : typeof window < "u" && typeof window.Audio == "function" && typeof fetch == "function";
72
72
  },
73
73
  listVoices() {
74
74
  return [...t];
@@ -77,47 +77,47 @@ function s(s) {
77
77
  return () => {};
78
78
  },
79
79
  speak(e, t, n = {}) {
80
- let r = e.filter((e) => e.trim().length > 0).flatMap((e) => o(e));
80
+ let r = e.filter((e) => e.trim().length > 0).flatMap((e) => s(e));
81
81
  if (r.length === 0) {
82
82
  n.onEnd?.();
83
83
  return;
84
84
  }
85
- d += 1;
86
- let i = d;
87
- h();
85
+ f += 1;
86
+ let i = f;
87
+ g();
88
88
  let a = new AbortController();
89
- f = a;
90
- let s = !1, c = () => {
91
- s || (s = !0, n.onStart?.());
92
- }, l = (e) => {
93
- let n = g(e, t, a.signal);
89
+ p = a;
90
+ let c = !1, l = () => {
91
+ c || (c = !0, n.onStart?.());
92
+ }, u = (e) => {
93
+ let n = _(e, t, a.signal);
94
94
  return n.catch(() => {}), n;
95
95
  };
96
96
  (async () => {
97
97
  try {
98
- let e = l(r[0]);
98
+ let e = u(r[0]);
99
99
  for (let t = 0; t < r.length; t += 1) {
100
- if (i !== d) return;
100
+ if (i !== f) return;
101
101
  let n = await e;
102
- if (i !== d) return;
102
+ if (i !== f) return;
103
103
  let a = r[t + 1];
104
- a !== void 0 && (e = l(a)), await _(n, i, c);
104
+ a !== void 0 && (e = u(a)), await v(n, i, l);
105
105
  }
106
- i === d && n.onEnd?.();
106
+ i === f && n.onEnd?.();
107
107
  } catch (e) {
108
- if (a.abort(), i !== d) return;
109
- d += 1, h();
108
+ if (a.abort(), i !== f) return;
109
+ f += 1, g();
110
110
  let t = e?.reason;
111
- (t === "not-allowed" || t === "unsupported") && (p = !0), n.onError?.(t === "not-allowed" || t === "unsupported" || t === "cancelled" ? t : "unknown");
111
+ o(t, e?.transient === !0) && (m = !0), n.onError?.(t === "not-allowed" || t === "unsupported" || t === "cancelled" ? t : "unknown");
112
112
  }
113
113
  })();
114
114
  },
115
115
  cancel() {
116
- d += 1, f?.abort(), f = null, h();
116
+ f += 1, p?.abort(), p = null, g();
117
117
  }
118
118
  };
119
119
  }
120
120
  //#endregion
121
- export { s as createHostedTtsEngine };
121
+ export { c as createHostedTtsEngine };
122
122
 
123
123
  //# sourceMappingURL=hostedTtsSpeechEngine.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"hostedTtsSpeechEngine.js","names":[],"sources":["../../../src/services/speech/hostedTtsSpeechEngine.ts"],"sourcesContent":["/**\n * Hosted (server-side) implementation of the `SpeechEngine` seam (BOFF-7111).\n *\n * The device-voice engine is as good as it is ever going to get: the Web Speech\n * API can only play voices the OS has installed, and on the devices that matter\n * here those are compact voices that do not sound human. Every knob was already\n * turned — rate, voice ranking, punctuation — and the result is still not close\n * to Assistant quality. The remaining gap IS the synthesiser, so this engine\n * replaces it.\n *\n * Structure mirrors `browserSpeechEngine` deliberately:\n * - **A generation counter.** `cancel()` bumps it; any fetch or `ended` event\n * from an older batch is dropped rather than clearing the state of a\n * playback that has already started.\n * - **Chunks played in order**, with the NEXT chunk fetched while the current\n * one plays. Without that prefetch every chunk boundary costs a full network\n * round trip and the reply sounds stuttered — worse than the device voice it\n * replaces.\n * - **Everything testable lives elsewhere** (`hostedTtsProtocol.ts`,\n * `hostedVoiceCatalogue.ts`) because this repo's vitest has no DOM and no\n * audio, so this file cannot be unit-tested.\n *\n * Failure is never silent: any error surfaces through `onError`, and the caller\n * (`createSpeechEngine`) is what decides to fall back to the device engine.\n */\n\nimport { HOSTED_TTS_TIER, HOSTED_VOICES, hostedLocaleFor } from './hostedVoiceCatalogue';\nimport { buildRequest, classifyHttpFailure, decodeAudioResponse, splitForVendor } from './hostedTtsProtocol';\nimport type { SpeechEngine, SpeechSpeakHandlers, SpeechSpeakOptions, SpeechVoiceLike } from './types';\n\nexport interface HostedTtsOptions {\n /** Absolute or same-origin path of OUR proxy. Never the vendor directly. */\n endpoint: string;\n /** Extra headers per request (auth). Called fresh each time so a rotated token is picked up. */\n getHeaders?: () => Record<string, string>;\n fetchImpl?: typeof fetch;\n}\n\nexport function createHostedTtsEngine(options: HostedTtsOptions): SpeechEngine {\n const doFetch = options.fetchImpl ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n let audio: HTMLAudioElement | null = null;\n let objectUrl: string | null = null;\n /**\n * Bumped on every `speak`/`cancel`; anything from an older batch is ignored.\n *\n * Per INSTANCE, not per module. `browserSpeechEngine` can keep this at module\n * scope because it is a singleton object; this is a factory, so a shared\n * counter would let one engine's `cancel()` silently invalidate another\n * engine's in-flight playback.\n */\n let generation = 0;\n /** The in-flight batch's controller, so `cancel()` can actually abort it. */\n let active: AbortController | null = null;\n /**\n * Set after a terminal proxy failure (401/403/404/501). Retrying cannot\n * succeed, and leaving the engine \"supported\" means every later press repeats\n * the same failing request. Reporting unsupported makes the routing engine\n * fall back to device voices, which still work.\n */\n let disabled = false;\n\n const releaseUrl = () => {\n if (objectUrl) {\n URL.revokeObjectURL(objectUrl);\n objectUrl = null;\n }\n };\n\n const stopAudio = () => {\n if (audio) {\n audio.onended = null;\n audio.onerror = null;\n try {\n audio.pause();\n } catch {\n /* pausing an already-dead element is harmless */\n }\n audio = null;\n }\n releaseUrl();\n };\n\n /** One chunk of text -> audio bytes. Throws with a `reason` the engine maps. */\n async function synthesise(text: string, opts: SpeechSpeakOptions, signal: AbortSignal): Promise<Uint8Array> {\n // The vendor's locale, not the app's: the app says `ar-SA`, Google only has\n // `ar-XA`. Sending the app tag would be an unsupported locale AND would\n // make `buildRequest` drop the chosen `ar-XA` voice as a mismatch.\n const languageCode = hostedLocaleFor(opts.lang) ?? opts.lang;\n const body = buildRequest(text, languageCode, HOSTED_TTS_TIER, opts.voice?.name ?? null, opts.rate);\n const response = await doFetch(options.endpoint, {\n method: 'POST',\n signal,\n headers: { 'content-type': 'application/json', ...(options.getHeaders?.() ?? {}) },\n body: JSON.stringify(body),\n });\n if (!response.ok) {\n const err = new Error(`hosted tts ${response.status}`) as Error & { reason?: string };\n err.reason = classifyHttpFailure(response.status);\n throw err;\n }\n const contentType = response.headers.get('content-type');\n const payload = contentType?.includes('json') ? await response.json() : await response.arrayBuffer();\n const bytes = decodeAudioResponse(contentType, payload);\n if (!bytes) {\n // A 200 carrying no audio is a failure, not silence. Treating it as\n // success is exactly the dead-button bug this feature already fixed once.\n const err = new Error('hosted tts returned no audio') as Error & { reason?: string };\n err.reason = 'unknown';\n throw err;\n }\n return bytes;\n }\n\n /**\n * `onBegin` fires when audio genuinely starts, not when it is requested, and\n * not when the chunk ends. The distinction matters to the routing engine: a\n * failure before any sound reached the user can be retried on the device\n * engine, and a failure after it cannot without repeating words.\n */\n function play(bytes: Uint8Array, batch: number, onBegin?: () => void): Promise<void> {\n return new Promise((resolve, reject) => {\n if (batch !== generation) {\n resolve();\n return;\n }\n // Copy into a fresh ArrayBuffer: the Uint8Array may be a view over a\n // larger buffer, and Blob would then include the neighbouring bytes.\n const blob = new Blob([bytes.slice().buffer as ArrayBuffer], { type: 'audio/mpeg' });\n releaseUrl();\n objectUrl = URL.createObjectURL(blob);\n const element = new Audio(objectUrl);\n audio = element;\n element.onended = () => {\n if (batch !== generation) return;\n resolve();\n };\n element.onerror = () => {\n if (batch !== generation) {\n resolve();\n return;\n }\n const err = new Error('audio playback failed') as Error & { reason?: string };\n err.reason = 'unknown';\n reject(err);\n };\n element.play().then(\n () => {\n if (batch === generation) onBegin?.();\n },\n (cause: unknown) => {\n if (batch !== generation) {\n resolve();\n return;\n }\n // Autoplay policy: playback needs a user gesture. Every path that\n // starts speech here is a button press, but an auto-speak triggered\n // by an arriving reply is not, and that is the case this reports.\n const err = new Error('audio play rejected') as Error & { reason?: string };\n err.reason = (cause as DOMException)?.name === 'NotAllowedError' ? 'not-allowed' : 'unknown';\n reject(err);\n }\n );\n });\n }\n\n return {\n id: 'hosted-tts',\n\n isSupported(): boolean {\n if (disabled) return false;\n return typeof window !== 'undefined' && typeof window.Audio === 'function' && typeof fetch === 'function';\n },\n\n listVoices(): SpeechVoiceLike[] {\n // A hosted catalogue is known up front, so unlike the browser engine\n // there is never an empty-then-populated race: `voiceAvailability` sees a\n // full list on the first read and never reports `pending`.\n return [...HOSTED_VOICES];\n },\n\n subscribeVoices(): () => void {\n // The catalogue is static — nothing to subscribe to. Returning a no-op\n // unsubscribe keeps the caller identical for both engines.\n return () => {};\n },\n\n speak(chunks: readonly string[], opts: SpeechSpeakOptions, handlers: SpeechSpeakHandlers = {}): void {\n const speakable = chunks.filter((chunk) => chunk.trim().length > 0).flatMap((chunk) => splitForVendor(chunk));\n if (speakable.length === 0) {\n handlers.onEnd?.();\n return;\n }\n\n generation += 1;\n const batch = generation;\n stopAudio();\n const controller = new AbortController();\n active = controller;\n\n // Announced at most once per batch: the caller only needs to know that\n // sound reached the user, not how many chunks did.\n let announcedStart = false;\n const notifyStarted = (): void => {\n if (announcedStart) return;\n announcedStart = true;\n handlers.onStart?.();\n };\n\n /**\n * Start a request and neutralise it as an unhandled rejection.\n *\n * A prefetched chunk is abandoned whenever the batch is cancelled\n * mid-loop. Attaching a swallow handler here does NOT consume the\n * rejection for the real `await` — `.catch` returns a NEW promise and the\n * original still rejects — so the error is still reported if we get that\n * far, and is silent if we never do.\n */\n const start = (text: string): Promise<Uint8Array> => {\n const request = synthesise(text, opts, controller.signal);\n request.catch(() => {});\n return request;\n };\n\n void (async () => {\n try {\n // Fetch the first chunk, then keep exactly one chunk in flight ahead\n // of playback so a boundary never costs a whole round trip.\n let pending: Promise<Uint8Array> = start(speakable[0] as string);\n for (let i = 0; i < speakable.length; i += 1) {\n if (batch !== generation) return;\n const current = await pending;\n if (batch !== generation) return;\n const next = speakable[i + 1];\n // On the last chunk nothing new is queued; `pending` keeps its\n // already-settled value and the loop simply ends.\n if (next !== undefined) pending = start(next);\n await play(current, batch, notifyStarted);\n }\n if (batch === generation) handlers.onEnd?.();\n } catch (cause) {\n controller.abort();\n if (batch !== generation) return; // cancelled — the caller already knows\n generation += 1; // abandon the rest of this batch\n stopAudio();\n const reason = (cause as { reason?: string })?.reason;\n // Terminal: the proxy is missing or refuses us, and retrying cannot\n // succeed. Stop claiming support so the routing engine falls back to\n // device voices from now on, instead of every later press repeating\n // the same failing request.\n if (reason === 'not-allowed' || reason === 'unsupported') disabled = true;\n handlers.onError?.(\n reason === 'not-allowed' || reason === 'unsupported' || reason === 'cancelled' ? reason : 'unknown'\n );\n }\n })();\n },\n\n cancel(): void {\n generation += 1;\n // Abort the in-flight synthesis too. Without this a cancelled reply keeps\n // downloading — and keeps costing billable vendor characters — until it\n // completes into a batch nobody is listening to.\n active?.abort();\n active = null;\n stopAudio();\n },\n };\n}\n"],"mappings":";;;AAsCA,SAAgB,EAAsB,GAAyC;CAC7E,IAAM,IAAU,EAAQ,eAAe,GAAG,MAAmC,MAAM,GAAG,CAAI,IACtF,IAAiC,MACjC,IAA2B,MAS3B,IAAa,GAEb,IAAiC,MAOjC,IAAW,IAET,UAAmB;EACvB,AAEE,OADA,IAAI,gBAAgB,CAAS,GACjB;CAEhB,GAEM,UAAkB;EACtB,IAAI,GAAO;GAET,AADA,EAAM,UAAU,MAChB,EAAM,UAAU;GAChB,IAAI;IACF,EAAM,MAAM;GACd,QAAQ,CAER;GACA,IAAQ;EACV;EACA,EAAW;CACb;CAGA,eAAe,EAAW,GAAc,GAA0B,GAA0C;EAK1G,IAAM,IAAO,EAAa,GADL,EAAgB,EAAK,IAAI,KAAK,EAAK,MACV,GAAiB,EAAK,OAAO,QAAQ,MAAM,EAAK,IAAI,GAC5F,IAAW,MAAM,EAAQ,EAAQ,UAAU;GAC/C,QAAQ;GACR;GACA,SAAS;IAAE,gBAAgB;IAAoB,GAAI,EAAQ,aAAa,KAAK,CAAC;GAAG;GACjF,MAAM,KAAK,UAAU,CAAI;EAC3B,CAAC;EACD,IAAI,CAAC,EAAS,IAAI;GAChB,IAAM,IAAM,gBAAI,MAAM,cAAc,EAAS,QAAQ;GAErD,MADA,EAAI,SAAS,EAAoB,EAAS,MAAM,GAC1C;EACR;EACA,IAAM,IAAc,EAAS,QAAQ,IAAI,cAAc,GAEjD,IAAQ,EAAoB,GADlB,GAAa,SAAS,MAAM,IAAI,MAAM,EAAS,KAAK,IAAI,MAAM,EAAS,YAAY,CAC7C;EACtD,IAAI,CAAC,GAAO;GAGV,IA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AAI,EAAU,WAAW,GAAG;IAC1B,EAAS,QAAQ;IACjB;GACF;GAEA,KAAc;GACd,IAAM,IAAQ;GACd,EAAU;GACV,IAAM,IAAa,IAAI,gBAAgB;GACvC,IAAS;GAIT,IAAI,IAAiB,IACf,UAA4B;IAC5B,MACJ,IAAiB,IACjB,EAAS,UAAU;GACrB,GAWM,KAAS,MAAsC;IACnD,IAAM,IAAU,EAAW,GAAM,GAAM,EAAW,MAAM;IAExD,OADA,EAAQ,YAAY,CAAC,CAAC,GACf;GACT;GAEA,CAAM,YAAY;IAChB,IAAI;KAGF,IAAI,IAA+B,EAAM,EAAU,EAAY;KAC/D,KAAK,IAAI,IAAI,GAAG,IAAI,EAAU,QAAQ,KAAK,GAAG;MAC5C,IAAI,MAAU,GAAY;MAC1B,IAAM,IAAU,MAAM;MACtB,IAAI,MAAU,GAAY;MAC1B,IAAM,IAAO,EAAU,IAAI;MAI3B,AADI,MAAS,KAAA,MAAW,IAAU,EAAM,CAAI,IAC5C,MAAM,EAAK,GAAS,GAAO,CAAa;KAC1C;KACA,AAAI,MAAU,KAAY,EAAS,QAAQ;IAC7C,SAAS,GAAO;KAEd,IADA,EAAW,MAAM,GACb,MAAU,GAAY;KAE1B,AADA,KAAc,GACd,EAAU;KACV,IAAM,IAAU,GAA+B;KAM/C,CADI,MAAW,iBAAiB,MAAW,mBAAe,IAAW,KACrE,EAAS,UACP,MAAW,iBAAiB,MAAW,iBAAiB,MAAW,cAAc,IAAS,SAC5F;IACF;GACF,GAAG;EACL;EAEA,SAAe;GAOb,AANA,KAAc,GAId,GAAQ,MAAM,GACd,IAAS,MACT,EAAU;EACZ;CACF;AACF"}
1
+ {"version":3,"file":"hostedTtsSpeechEngine.js","names":[],"sources":["../../../src/services/speech/hostedTtsSpeechEngine.ts"],"sourcesContent":["/**\n * Hosted (server-side) implementation of the `SpeechEngine` seam (BOFF-7111).\n *\n * The device-voice engine is as good as it is ever going to get: the Web Speech\n * API can only play voices the OS has installed, and on the devices that matter\n * here those are compact voices that do not sound human. Every knob was already\n * turned — rate, voice ranking, punctuation — and the result is still not close\n * to Assistant quality. The remaining gap IS the synthesiser, so this engine\n * replaces it.\n *\n * Structure mirrors `browserSpeechEngine` deliberately:\n * - **A generation counter.** `cancel()` bumps it; any fetch or `ended` event\n * from an older batch is dropped rather than clearing the state of a\n * playback that has already started.\n * - **Chunks played in order**, with the NEXT chunk fetched while the current\n * one plays. Without that prefetch every chunk boundary costs a full network\n * round trip and the reply sounds stuttered — worse than the device voice it\n * replaces.\n * - **Everything testable lives elsewhere** (`hostedTtsProtocol.ts`,\n * `hostedVoiceCatalogue.ts`) because this repo's vitest has no DOM and no\n * audio, so this file cannot be unit-tested.\n *\n * Failure is never silent: any error surfaces through `onError`, and the caller\n * (`createSpeechEngine`) is what decides to fall back to the device engine.\n */\n\nimport { HOSTED_TTS_TIER, HOSTED_VOICES, hostedLocaleFor } from './hostedVoiceCatalogue';\nimport {\n buildRequest,\n classifyHttpFailure,\n decodeAudioResponse,\n shouldDisableEngine,\n splitForVendor,\n} from './hostedTtsProtocol';\nimport type { SpeechEngine, SpeechSpeakHandlers, SpeechSpeakOptions, SpeechVoiceLike } from './types';\n\nexport interface HostedTtsOptions {\n /** Absolute or same-origin path of OUR proxy. Never the vendor directly. */\n endpoint: string;\n /** Extra headers per request (auth). Called fresh each time so a rotated token is picked up. */\n getHeaders?: () => Record<string, string>;\n fetchImpl?: typeof fetch;\n}\n\nexport function createHostedTtsEngine(options: HostedTtsOptions): SpeechEngine {\n const doFetch = options.fetchImpl ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n let audio: HTMLAudioElement | null = null;\n let objectUrl: string | null = null;\n /**\n * Bumped on every `speak`/`cancel`; anything from an older batch is ignored.\n *\n * Per INSTANCE, not per module. `browserSpeechEngine` can keep this at module\n * scope because it is a singleton object; this is a factory, so a shared\n * counter would let one engine's `cancel()` silently invalidate another\n * engine's in-flight playback.\n */\n let generation = 0;\n /** The in-flight batch's controller, so `cancel()` can actually abort it. */\n let active: AbortController | null = null;\n /**\n * Set after a terminal proxy failure (401/403/404/501). Retrying cannot\n * succeed, and leaving the engine \"supported\" means every later press repeats\n * the same failing request. Reporting unsupported makes the routing engine\n * fall back to device voices, which still work.\n */\n let disabled = false;\n\n const releaseUrl = () => {\n if (objectUrl) {\n URL.revokeObjectURL(objectUrl);\n objectUrl = null;\n }\n };\n\n const stopAudio = () => {\n if (audio) {\n audio.onended = null;\n audio.onerror = null;\n try {\n audio.pause();\n } catch {\n /* pausing an already-dead element is harmless */\n }\n audio = null;\n }\n releaseUrl();\n };\n\n /** One chunk of text -> audio bytes. Throws with a `reason` the engine maps. */\n async function synthesise(text: string, opts: SpeechSpeakOptions, signal: AbortSignal): Promise<Uint8Array> {\n // The vendor's locale, not the app's: the app says `ar-SA`, Google only has\n // `ar-XA`. Sending the app tag would be an unsupported locale AND would\n // make `buildRequest` drop the chosen `ar-XA` voice as a mismatch.\n const languageCode = hostedLocaleFor(opts.lang) ?? opts.lang;\n const body = buildRequest(text, languageCode, HOSTED_TTS_TIER, opts.voice?.name ?? null, opts.rate);\n const response = await doFetch(options.endpoint, {\n method: 'POST',\n signal,\n headers: { 'content-type': 'application/json', ...(options.getHeaders?.() ?? {}) },\n body: JSON.stringify(body),\n });\n if (!response.ok) {\n const err = new Error(`hosted tts ${response.status}`) as Error & { reason?: string };\n err.reason = classifyHttpFailure(response.status);\n throw err;\n }\n const contentType = response.headers.get('content-type');\n const payload = contentType?.includes('json') ? await response.json() : await response.arrayBuffer();\n const bytes = decodeAudioResponse(contentType, payload);\n if (!bytes) {\n // A 200 carrying no audio is a failure, not silence. Treating it as\n // success is exactly the dead-button bug this feature already fixed once.\n const err = new Error('hosted tts returned no audio') as Error & { reason?: string };\n err.reason = 'unknown';\n throw err;\n }\n return bytes;\n }\n\n /**\n * `onBegin` fires when audio genuinely starts, not when it is requested, and\n * not when the chunk ends. The distinction matters to the routing engine: a\n * failure before any sound reached the user can be retried on the device\n * engine, and a failure after it cannot without repeating words.\n */\n function play(bytes: Uint8Array, batch: number, onBegin?: () => void): Promise<void> {\n return new Promise((resolve, reject) => {\n if (batch !== generation) {\n resolve();\n return;\n }\n // Copy into a fresh ArrayBuffer: the Uint8Array may be a view over a\n // larger buffer, and Blob would then include the neighbouring bytes.\n const blob = new Blob([bytes.slice().buffer as ArrayBuffer], { type: 'audio/mpeg' });\n releaseUrl();\n objectUrl = URL.createObjectURL(blob);\n const element = new Audio(objectUrl);\n audio = element;\n element.onended = () => {\n if (batch !== generation) return;\n resolve();\n };\n element.onerror = () => {\n if (batch !== generation) {\n resolve();\n return;\n }\n const err = new Error('audio playback failed') as Error & { reason?: string };\n err.reason = 'unknown';\n reject(err);\n };\n element.play().then(\n () => {\n if (batch === generation) onBegin?.();\n },\n (cause: unknown) => {\n if (batch !== generation) {\n resolve();\n return;\n }\n // Autoplay policy: playback needs a user gesture. Every path that\n // starts speech here is a button press, but an auto-speak triggered\n // by an arriving reply is not, and that is the case this reports.\n const err = new Error('audio play rejected') as Error & { reason?: string; transient?: boolean };\n const autoplayBlocked = (cause as DOMException)?.name === 'NotAllowedError';\n err.reason = autoplayBlocked ? 'not-allowed' : 'unknown';\n // ★ Marked transient so it cannot latch the engine off. An autoplay\n // refusal is per-gesture; the next tap plays. See shouldDisableEngine.\n err.transient = autoplayBlocked;\n reject(err);\n }\n );\n });\n }\n\n return {\n id: 'hosted-tts',\n\n isSupported(): boolean {\n if (disabled) return false;\n return typeof window !== 'undefined' && typeof window.Audio === 'function' && typeof fetch === 'function';\n },\n\n listVoices(): SpeechVoiceLike[] {\n // A hosted catalogue is known up front, so unlike the browser engine\n // there is never an empty-then-populated race: `voiceAvailability` sees a\n // full list on the first read and never reports `pending`.\n return [...HOSTED_VOICES];\n },\n\n subscribeVoices(): () => void {\n // The catalogue is static — nothing to subscribe to. Returning a no-op\n // unsubscribe keeps the caller identical for both engines.\n return () => {};\n },\n\n speak(chunks: readonly string[], opts: SpeechSpeakOptions, handlers: SpeechSpeakHandlers = {}): void {\n const speakable = chunks.filter((chunk) => chunk.trim().length > 0).flatMap((chunk) => splitForVendor(chunk));\n if (speakable.length === 0) {\n handlers.onEnd?.();\n return;\n }\n\n generation += 1;\n const batch = generation;\n stopAudio();\n const controller = new AbortController();\n active = controller;\n\n // Announced at most once per batch: the caller only needs to know that\n // sound reached the user, not how many chunks did.\n let announcedStart = false;\n const notifyStarted = (): void => {\n if (announcedStart) return;\n announcedStart = true;\n handlers.onStart?.();\n };\n\n /**\n * Start a request and neutralise it as an unhandled rejection.\n *\n * A prefetched chunk is abandoned whenever the batch is cancelled\n * mid-loop. Attaching a swallow handler here does NOT consume the\n * rejection for the real `await` — `.catch` returns a NEW promise and the\n * original still rejects — so the error is still reported if we get that\n * far, and is silent if we never do.\n */\n const start = (text: string): Promise<Uint8Array> => {\n const request = synthesise(text, opts, controller.signal);\n request.catch(() => {});\n return request;\n };\n\n void (async () => {\n try {\n // Fetch the first chunk, then keep exactly one chunk in flight ahead\n // of playback so a boundary never costs a whole round trip.\n let pending: Promise<Uint8Array> = start(speakable[0] as string);\n for (let i = 0; i < speakable.length; i += 1) {\n if (batch !== generation) return;\n const current = await pending;\n if (batch !== generation) return;\n const next = speakable[i + 1];\n // On the last chunk nothing new is queued; `pending` keeps its\n // already-settled value and the loop simply ends.\n if (next !== undefined) pending = start(next);\n await play(current, batch, notifyStarted);\n }\n if (batch === generation) handlers.onEnd?.();\n } catch (cause) {\n controller.abort();\n if (batch !== generation) return; // cancelled — the caller already knows\n generation += 1; // abandon the rest of this batch\n stopAudio();\n const reason = (cause as { reason?: string })?.reason;\n // Terminal: the proxy is missing or refuses us, and retrying cannot\n // succeed. Stop claiming support so the routing engine falls back to\n // device voices from now on, instead of every later press repeating\n // the same failing request.\n //\n // ★ A browser autoplay refusal reports the SAME reason and must not\n // latch — it is per-gesture, and auto-speak is exactly the path that\n // triggers it.\n if (shouldDisableEngine(reason, (cause as { transient?: boolean })?.transient === true)) disabled = true;\n handlers.onError?.(\n reason === 'not-allowed' || reason === 'unsupported' || reason === 'cancelled' ? reason : 'unknown'\n );\n }\n })();\n },\n\n cancel(): void {\n generation += 1;\n // Abort the in-flight synthesis too. Without this a cancelled reply keeps\n // downloading — and keeps costing billable vendor characters — until it\n // completes into a batch nobody is listening to.\n active?.abort();\n active = null;\n stopAudio();\n },\n };\n}\n"],"mappings":";;;AA4CA,SAAgB,EAAsB,GAAyC;CAC7E,IAAM,IAAU,EAAQ,eAAe,GAAG,MAAmC,MAAM,GAAG,CAAI,IACtF,IAAiC,MACjC,IAA2B,MAS3B,IAAa,GAEb,IAAiC,MAOjC,IAAW,IAET,UAAmB;EACvB,AAEE,OADA,IAAI,gBAAgB,CAAS,GACjB;CAEhB,GAEM,UAAkB;EACtB,IAAI,GAAO;GAET,AADA,EAAM,UAAU,MAChB,EAAM,UAAU;GAChB,IAAI;IACF,EAAM,MAAM;GACd,QAAQ,CAER;GACA,IAAQ;EACV;EACA,EAAW;CACb;CAGA,eAAe,EAAW,GAAc,GAA0B,GAA0C;EAK1G,IAAM,IAAO,EAAa,GADL,EAAgB,EAAK,IAAI,KAAK,EAAK,MACV,GAAiB,EAAK,OAAO,QAAQ,MAAM,EAAK,IAAI,GAC5F,IAAW,MAAM,EAAQ,EAAQ,UAAU;GAC/C,QAAQ;GACR;GACA,SAAS;IAAE,gBAAgB;IAAoB,GAAI,EAAQ,aAAa,KAAK,CAAC;GAAG;GACjF,MAAM,KAAK,UAAU,CAAI;EAC3B,CAAC;EACD,IAAI,CAAC,EAAS,IAAI;GAChB,IAAM,IAAM,gBAAI,MAAM,cAAc,EAAS,QAAQ;GAErD,MADA,EAAI,SAAS,EAAoB,EAAS,MAAM,GAC1C;EACR;EACA,IAAM,IAAc,EAAS,QAAQ,IAAI,cAAc,GAEjD,IAAQ,EAAoB,GADlB,GAAa,SAAS,MAAM,IAAI,MAAM,EAAS,KAAK,IAAI,MAAM,EAAS,YAAY,CAC7C;EACtD,IAAI,CAAC,GAAO;GAGV,IAAM,IAA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AAe,CAAK,CAAC;GAC5G,IAAI,EAAU,WAAW,GAAG;IAC1B,EAAS,QAAQ;IACjB;GACF;GAEA,KAAc;GACd,IAAM,IAAQ;GACd,EAAU;GACV,IAAM,IAAa,IAAI,gBAAgB;GACvC,IAAS;GAIT,IAAI,IAAiB,IACf,UAA4B;IAC5B,MACJ,IAAiB,IACjB,EAAS,UAAU;GACrB,GAWM,KAAS,MAAsC;IACnD,IAAM,IAAU,EAAW,GAAM,GAAM,EAAW,MAAM;IAExD,OADA,EAAQ,YAAY,CAAC,CAAC,GACf;GACT;GAEA,CAAM,YAAY;IAChB,IAAI;KAGF,IAAI,IAA+B,EAAM,EAAU,EAAY;KAC/D,KAAK,IAAI,IAAI,GAAG,IAAI,EAAU,QAAQ,KAAK,GAAG;MAC5C,IAAI,MAAU,GAAY;MAC1B,IAAM,IAAU,MAAM;MACtB,IAAI,MAAU,GAAY;MAC1B,IAAM,IAAO,EAAU,IAAI;MAI3B,AADI,MAAS,KAAA,MAAW,IAAU,EAAM,CAAI,IAC5C,MAAM,EAAK,GAAS,GAAO,CAAa;KAC1C;KACA,AAAI,MAAU,KAAY,EAAS,QAAQ;IAC7C,SAAS,GAAO;KAEd,IADA,EAAW,MAAM,GACb,MAAU,GAAY;KAE1B,AADA,KAAc,GACd,EAAU;KACV,IAAM,IAAU,GAA+B;KAU/C,AADI,EAAoB,GAAS,GAAmC,cAAc,EAAI,MAAG,IAAW,KACpG,EAAS,UACP,MAAW,iBAAiB,MAAW,iBAAiB,MAAW,cAAc,IAAS,SAC5F;IACF;GACF,GAAG;EACL;EAEA,SAAe;GAOb,AANA,KAAc,GAId,GAAQ,MAAM,GACd,IAAS,MACT,EAAU;EACZ;CACF;AACF"}
@@ -0,0 +1,24 @@
1
+ //#region src/utils/sandboxReadiness.ts
2
+ var e = 6e4;
3
+ function t(t, n, r = e) {
4
+ return t == null || t > n ? !1 : n - t < r;
5
+ }
6
+ var n = 32;
7
+ function r(e = Date.now) {
8
+ let r = /* @__PURE__ */ new Map();
9
+ return {
10
+ isFresh(n) {
11
+ return t(r.get(n), e());
12
+ },
13
+ markVerified(t) {
14
+ r.size >= n && !r.has(t) && r.clear(), r.set(t, e());
15
+ },
16
+ invalidate(e) {
17
+ e && r.delete(e);
18
+ }
19
+ };
20
+ }
21
+ //#endregion
22
+ export { r as createReadinessTracker };
23
+
24
+ //# sourceMappingURL=sandboxReadiness.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sandboxReadiness.js","names":[],"sources":["../../src/utils/sandboxReadiness.ts"],"sourcesContent":["/**\n * Was this sandbox proven reachable recently enough to skip re-proving it?\n *\n * Every turn re-ran two network waits before the model saw the prompt — a\n * `WaitForSandboxRunning` long-poll and a `/health` GET through the cf-proxy —\n * even when the previous turn had finished seconds earlier. That is a constant\n * tax on the hot path, paid most visibly in voice, where it sits between the\n * user finishing a sentence and hearing anything at all.\n *\n * The probe is not pointless: a sandbox can expire on its TTL or have its pod\n * reclaimed while still briefly reporting RUNNING, and proxying to a dead pod\n * fails in ways that are worse to surface than a re-provision. So this does not\n * remove the check — it stops repeating a check that just passed.\n *\n * ★ The TTL is deliberately far shorter than the sandbox's own lifetime. Each\n * turn extends the sandbox by 600s, so a 60s readiness window can never outlive\n * the thing it describes; the worst case is that a sandbox dies inside the\n * window and one turn fails, which is exactly what happens today when it dies\n * mid-turn — and the caller already handles that by dropping it and\n * provisioning a fresh one.\n *\n * Correctness rests on the caller invalidating on failure. A cache that only\n * ever gets written on success, and never cleared, would pin a dead sandbox and\n * turn a recoverable error into a loop.\n */\n\n/** How long a successful reachability proof stays good for. */\nexport const SANDBOX_READY_TTL_MS = 60_000;\n\n/**\n * `now` is injected rather than read so the rule is testable and a clock skew\n * cannot make a passing check fail mysteriously.\n */\nexport function isRecentlyVerified(\n lastVerifiedAt: number | null | undefined,\n now: number,\n ttlMs: number = SANDBOX_READY_TTL_MS\n): boolean {\n if (lastVerifiedAt == null) return false;\n // A timestamp from the future is a broken clock, not a fresh proof.\n if (lastVerifiedAt > now) return false;\n return now - lastVerifiedAt < ttlMs;\n}\n\n/**\n * A tiny per-sandbox record of \"last proven reachable\".\n *\n * Bounded, because a long session cycling through sandboxes should not grow a\n * map forever — and the bound is generous enough that it never evicts anything\n * a real conversation is using.\n */\nconst MAX_TRACKED = 32;\n\nexport function createReadinessTracker(clock: () => number = Date.now) {\n const verifiedAt = new Map<string, number>();\n\n return {\n /** True when this sandbox was proven reachable inside the TTL. */\n isFresh(sandboxId: string): boolean {\n return isRecentlyVerified(verifiedAt.get(sandboxId), clock());\n },\n /** Record a successful proof. */\n markVerified(sandboxId: string): void {\n if (verifiedAt.size >= MAX_TRACKED && !verifiedAt.has(sandboxId)) verifiedAt.clear();\n verifiedAt.set(sandboxId, clock());\n },\n /**\n * Drop a proof. MUST be called whenever a turn fails against this sandbox,\n * so a dead one is re-probed rather than trusted until the TTL lapses.\n */\n invalidate(sandboxId: string | null | undefined): void {\n if (sandboxId) verifiedAt.delete(sandboxId);\n },\n };\n}\n\nexport type ReadinessTracker = ReturnType<typeof createReadinessTracker>;\n"],"mappings":";AA2BA,IAAa,IAAuB;AAMpC,SAAgB,EACd,GACA,GACA,IAAgB,GACP;CAIT,OAHI,KAAkB,QAElB,IAAiB,IAAY,KAC1B,IAAM,IAAiB;AAChC;AASA,IAAM,IAAc;AAEpB,SAAgB,EAAuB,IAAsB,KAAK,KAAK;CACrE,IAAM,oBAAa,IAAI,IAAoB;CAE3C,OAAO;EAEL,QAAQ,GAA4B;GAClC,OAAO,EAAmB,EAAW,IAAI,CAAS,GAAG,EAAM,CAAC;EAC9D;EAEA,aAAa,GAAyB;GAEpC,AADI,EAAW,QAAQ,KAAe,CAAC,EAAW,IAAI,CAAS,KAAG,EAAW,MAAM,GACnF,EAAW,IAAI,GAAW,EAAM,CAAC;EACnC;EAKA,WAAW,GAA4C;GACrD,AAAI,KAAW,EAAW,OAAO,CAAS;EAC5C;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/microfe-healthybowl",
3
- "version": "2026.901.2",
3
+ "version": "2026.901.4",
4
4
  "description": "Burdenoff HealthyBowl Microfrontend - Comprehensive organic farming and agro-foods management platform",
5
5
  "type": "module",
6
6
  "files": [