@burdenoff/microfe-healthybowl 2026.830.1 → 2026.830.2

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.
@@ -38,7 +38,7 @@ var m = ({ onClose: m, visible: h, docked: g, onToggleDock: _ }) => {
38
38
  onToggleDock: _
39
39
  }),
40
40
  S && /* @__PURE__ */ d(c, {}),
41
- /* @__PURE__ */ d(s, {})
41
+ /* @__PURE__ */ d(s, { visible: h ?? !0 })
42
42
  ]
43
43
  })
44
44
  });
@@ -1 +1 @@
1
- {"version":3,"file":"AIAssistantPanel.js","names":[],"sources":["../../../src/components/assistant/AIAssistantPanel.tsx"],"sourcesContent":["/**\n * AI Assistant Panel — top-level component for the in-page assistant.\n *\n * Layout (v2): a fixed identity header (AssistantHeader) with the brand mark,\n * an availability/context subtitle and icon actions (new conversation, history,\n * export, dock, close), an always-visible transcript, and the composer pinned\n * to the bottom. Conversation history opens as an overlay drawer over the panel\n * — never as an accordion over the transcript.\n *\n * The external prop contract ({ onClose, visible, docked, onToggleDock }) is\n * unchanged; the sandbox/session/transport logic lives in AssistantChatArea.\n */\n\nimport { useMemo, useRef, type FC } from 'react';\nimport type { PanelProps } from '@burdenoff/fe-libs/shared/plugins';\nimport { useFilesServiceWarmup } from '@burdenoff/fe-libs/storage';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { useAssistantKeyboardShortcuts } from '@/hooks/useAssistantKeyboardShortcuts';\nimport { useAssistantHeartbeat } from '@/hooks/useAssistantHeartbeat';\nimport { describeCurrentPage } from '@/utils/pageContext';\nimport { AssistantHeader } from './AssistantHeader';\nimport { AssistantChatArea } from './AssistantChatArea';\nimport { AssistantConversationList } from './AssistantConversationList';\nimport { AssistantSpeechProvider } from './AssistantSpeechProvider';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport type AIAssistantPanelProps = PanelProps & {\n /** When provided, renders a dock/float toggle in the header. */\n docked?: boolean;\n onToggleDock?: () => void;\n};\n\nexport const AIAssistantPanel: FC<AIAssistantPanelProps> = ({ onClose, visible, docked, onToggleDock }) => {\n const tr = useTr();\n const panelRef = useRef<HTMLDivElement>(null);\n\n const { conversations, activeConversationId, conversationListOpen, toggleConversationList, createConversation } =\n useAssistantStore();\n\n const activeConversation = conversations.find((c) => c.id === activeConversationId);\n const activeSessionId = activeConversation?.backendSessionId ?? null;\n\n // Keep sandbox alive while panel is open\n useAssistantHeartbeat(activeSessionId, activeConversation?.mode ?? null, visible ?? true);\n\n // Wake wspace-files-svc the moment the panel opens. It runs at minReplicas 0 and\n // needs >=51s to bind its port (prisma migrate deploy 26.0s + boot ~25.5s) against\n // the gateway's 15s budget, so the first attachment after any quiet period would\n // otherwise fail outright. Firing here means the container boots while the user is\n // still typing. Best-effort by construction: single-flighted, rate-limited, and it\n // never surfaces an error — see fe-libs `warmFilesService`.\n useFilesServiceWarmup(visible ?? true);\n\n const contextLabel = useMemo(() => describeCurrentPage(), []);\n\n useAssistantKeyboardShortcuts({\n panelRef,\n onClose,\n });\n\n return (\n // Speech output (BOFF-6290) is provided at the panel root so that hiding the\n // panel — not only unmounting it — stops the voice, and so the header toggle\n // and every message's speak button share one playback state.\n <AssistantSpeechProvider visible={visible ?? true}>\n <div\n ref={panelRef}\n className=\"relative flex h-full w-full flex-col bg-bg-surface\"\n role=\"complementary\"\n aria-label={tr('healthybowl.assistant.panel.ariaLabel', 'AI Assistant')}\n data-testid=\"ai-assistant-panel\"\n tabIndex={-1}\n >\n <AssistantHeader\n contextLabel={contextLabel}\n onNewConversation={() => createConversation()}\n onOpenHistory={toggleConversationList}\n historyOpen={conversationListOpen}\n onClose={onClose}\n docked={docked}\n onToggleDock={onToggleDock}\n />\n\n {/* Conversation history overlay drawer (switch between chats) */}\n {conversationListOpen && <AssistantConversationList />}\n\n <AssistantChatArea />\n </div>\n </AssistantSpeechProvider>\n );\n};\n"],"mappings":";;;;;;;;;;;;;AAgCA,IAAa,KAA+C,EAAE,YAAS,YAAS,WAAQ,sBAAmB;CACzG,IAAM,IAAK,EAAM,GACX,IAAW,EAAuB,IAAI,GAEtC,EAAE,kBAAe,yBAAsB,yBAAsB,2BAAwB,0BACzF,EAAkB,GAEd,IAAqB,EAAc,MAAM,MAAM,EAAE,OAAO,CAAoB;CAYlF,AARA,EAHwB,GAAoB,oBAAoB,MAGzB,GAAoB,QAAQ,MAAM,KAAW,EAAI,GAQxF,EAAsB,KAAW,EAAI;CAErC,IAAM,IAAe,QAAc,EAAoB,GAAG,CAAC,CAAC;CAO5D,OALA,EAA8B;EAC5B;EACA;CACF,CAAC,GAMC,kBAAC,GAAD;EAAyB,SAAS,KAAW;YAC3C,kBAAC,OAAD;GACE,KAAK;GACL,WAAU;GACV,MAAK;GACL,cAAY,EAAG,yCAAyC,cAAc;GACtE,eAAY;GACZ,UAAU;aANZ;IAQE,kBAAC,GAAD;KACgB;KACd,yBAAyB,EAAmB;KAC5C,eAAe;KACf,aAAa;KACJ;KACD;KACM;IACf,CAAA;IAGA,KAAwB,kBAAC,GAAD,CAA4B,CAAA;IAErD,kBAAC,GAAD,CAAoB,CAAA;GACjB;;CACkB,CAAA;AAE7B"}
1
+ {"version":3,"file":"AIAssistantPanel.js","names":[],"sources":["../../../src/components/assistant/AIAssistantPanel.tsx"],"sourcesContent":["/**\n * AI Assistant Panel — top-level component for the in-page assistant.\n *\n * Layout (v2): a fixed identity header (AssistantHeader) with the brand mark,\n * an availability/context subtitle and icon actions (new conversation, history,\n * export, dock, close), an always-visible transcript, and the composer pinned\n * to the bottom. Conversation history opens as an overlay drawer over the panel\n * — never as an accordion over the transcript.\n *\n * The external prop contract ({ onClose, visible, docked, onToggleDock }) is\n * unchanged; the sandbox/session/transport logic lives in AssistantChatArea.\n */\n\nimport { useMemo, useRef, type FC } from 'react';\nimport type { PanelProps } from '@burdenoff/fe-libs/shared/plugins';\nimport { useFilesServiceWarmup } from '@burdenoff/fe-libs/storage';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { useAssistantKeyboardShortcuts } from '@/hooks/useAssistantKeyboardShortcuts';\nimport { useAssistantHeartbeat } from '@/hooks/useAssistantHeartbeat';\nimport { describeCurrentPage } from '@/utils/pageContext';\nimport { AssistantHeader } from './AssistantHeader';\nimport { AssistantChatArea } from './AssistantChatArea';\nimport { AssistantConversationList } from './AssistantConversationList';\nimport { AssistantSpeechProvider } from './AssistantSpeechProvider';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport type AIAssistantPanelProps = PanelProps & {\n /** When provided, renders a dock/float toggle in the header. */\n docked?: boolean;\n onToggleDock?: () => void;\n};\n\nexport const AIAssistantPanel: FC<AIAssistantPanelProps> = ({ onClose, visible, docked, onToggleDock }) => {\n const tr = useTr();\n const panelRef = useRef<HTMLDivElement>(null);\n\n const { conversations, activeConversationId, conversationListOpen, toggleConversationList, createConversation } =\n useAssistantStore();\n\n const activeConversation = conversations.find((c) => c.id === activeConversationId);\n const activeSessionId = activeConversation?.backendSessionId ?? null;\n\n // Keep sandbox alive while panel is open\n useAssistantHeartbeat(activeSessionId, activeConversation?.mode ?? null, visible ?? true);\n\n // Wake wspace-files-svc the moment the panel opens. It runs at minReplicas 0 and\n // needs >=51s to bind its port (prisma migrate deploy 26.0s + boot ~25.5s) against\n // the gateway's 15s budget, so the first attachment after any quiet period would\n // otherwise fail outright. Firing here means the container boots while the user is\n // still typing. Best-effort by construction: single-flighted, rate-limited, and it\n // never surfaces an error — see fe-libs `warmFilesService`.\n useFilesServiceWarmup(visible ?? true);\n\n const contextLabel = useMemo(() => describeCurrentPage(), []);\n\n useAssistantKeyboardShortcuts({\n panelRef,\n onClose,\n });\n\n return (\n // Speech output (BOFF-6290) is provided at the panel root so that hiding the\n // panel — not only unmounting it — stops the voice, and so the header toggle\n // and every message's speak button share one playback state.\n <AssistantSpeechProvider visible={visible ?? true}>\n <div\n ref={panelRef}\n className=\"relative flex h-full w-full flex-col bg-bg-surface\"\n role=\"complementary\"\n aria-label={tr('healthybowl.assistant.panel.ariaLabel', 'AI Assistant')}\n data-testid=\"ai-assistant-panel\"\n tabIndex={-1}\n >\n <AssistantHeader\n contextLabel={contextLabel}\n onNewConversation={() => createConversation()}\n onOpenHistory={toggleConversationList}\n historyOpen={conversationListOpen}\n onClose={onClose}\n docked={docked}\n onToggleDock={onToggleDock}\n />\n\n {/* Conversation history overlay drawer (switch between chats) */}\n {conversationListOpen && <AssistantConversationList />}\n\n <AssistantChatArea visible={visible ?? true} />\n </div>\n </AssistantSpeechProvider>\n );\n};\n"],"mappings":";;;;;;;;;;;;;AAgCA,IAAa,KAA+C,EAAE,YAAS,YAAS,WAAQ,sBAAmB;CACzG,IAAM,IAAK,EAAM,GACX,IAAW,EAAuB,IAAI,GAEtC,EAAE,kBAAe,yBAAsB,yBAAsB,2BAAwB,0BACzF,EAAkB,GAEd,IAAqB,EAAc,MAAM,MAAM,EAAE,OAAO,CAAoB;CAYlF,AARA,EAHwB,GAAoB,oBAAoB,MAGzB,GAAoB,QAAQ,MAAM,KAAW,EAAI,GAQxF,EAAsB,KAAW,EAAI;CAErC,IAAM,IAAe,QAAc,EAAoB,GAAG,CAAC,CAAC;CAO5D,OALA,EAA8B;EAC5B;EACA;CACF,CAAC,GAMC,kBAAC,GAAD;EAAyB,SAAS,KAAW;YAC3C,kBAAC,OAAD;GACE,KAAK;GACL,WAAU;GACV,MAAK;GACL,cAAY,EAAG,yCAAyC,cAAc;GACtE,eAAY;GACZ,UAAU;aANZ;IAQE,kBAAC,GAAD;KACgB;KACd,yBAAyB,EAAmB;KAC5C,eAAe;KACf,aAAa;KACJ;KACD;KACM;IACf,CAAA;IAGA,KAAwB,kBAAC,GAAD,CAA4B,CAAA;IAErD,kBAAC,GAAD,EAAmB,SAAS,KAAW,GAAO,CAAA;GAC3C;;CACkB,CAAA;AAE7B"}
@@ -5,26 +5,26 @@ import { gatherPageContext as m } from "../../utils/pageContext.js";
5
5
  import { findAssistantLanguage as h, resolveAssistantLanguage as g } from "../../config/assistantLanguages.js";
6
6
  import { isTurnInFlight as _ } from "../../utils/assistantTurnState.js";
7
7
  import { parseToolActivity as v } from "./AssistantToolActivity.js";
8
- import { getOrganizationId as ee, getWorkspaceId as te } from "../../utils/assistantContext.js";
9
- import { buildPromptParts as ne, buildPromptWithAttachments as re, countInlineImageCandidates as ie, countInlinedImageParts as ae, toMessageAttachment as y } from "../../utils/assistantAttachments.js";
10
- import { AssistantMessageList as b } from "./AssistantMessageList.js";
11
- import { AssistantApiCallsConsentDialog as x } from "./AssistantApiCallsConsentDialog.js";
12
- import { ASSISTANT_MODES as S } from "../../types/assistant.js";
13
- import { AssistantEmptyState as C } from "./AssistantEmptyState.js";
14
- import { AssistantComposer as oe } from "./composer/AssistantComposer.js";
15
- import { AssistantVoiceSession as se } from "./voice/AssistantVoiceSession.js";
16
- import { useVoiceSession as ce } from "../../hooks/useVoiceSession.js";
17
- import { useAssistantApiAccess as le } from "../../hooks/useAssistantApiAccess.js";
18
- import { isQuotaExhaustedError as ue } from "../../utils/quotaUtils.js";
19
- import { dispatchAssistantQuotaExhausted as de, notifyAiCreditsUpdated as fe } from "../../utils/aiCredits.js";
20
- import { buildPromptForMode as pe } from "../../utils/assistantPrompt.js";
21
- import { isMultimodalBodyRejection as me, isRecoverableAssistantError as he } from "../../utils/assistantTransportErrors.js";
22
- import { useCallback as w, useEffect as ge, useMemo as T, useRef as E, useState as _e } from "react";
23
- import { useI18n as ve } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
24
- import { jsx as D, jsxs as ye } from "react/jsx-runtime";
25
- import { useGatewayClient as be } from "@burdenoff/fe-libs/shared/graphql";
26
- import { useAuthToken as xe } from "@burdenoff/fe-libs/shared/providers/shell";
27
- import { getAssistantMedia as O } from "@burdenoff/fe-libs/shared/assistant";
8
+ import { getOrganizationId as ee, getWorkspaceId as y } from "../../utils/assistantContext.js";
9
+ import { buildPromptParts as te, buildPromptWithAttachments as ne, countInlineImageCandidates as re, countInlinedImageParts as ie, toMessageAttachment as b } from "../../utils/assistantAttachments.js";
10
+ import { AssistantMessageList as x } from "./AssistantMessageList.js";
11
+ import { AssistantApiCallsConsentDialog as S } from "./AssistantApiCallsConsentDialog.js";
12
+ import { ASSISTANT_MODES as C } from "../../types/assistant.js";
13
+ import { AssistantEmptyState as w } from "./AssistantEmptyState.js";
14
+ import { AssistantComposer as ae } from "./composer/AssistantComposer.js";
15
+ import { AssistantVoiceSession as oe } from "./voice/AssistantVoiceSession.js";
16
+ import { useVoiceSession as se } from "../../hooks/useVoiceSession.js";
17
+ import { useAssistantApiAccess as ce } from "../../hooks/useAssistantApiAccess.js";
18
+ import { isQuotaExhaustedError as le } from "../../utils/quotaUtils.js";
19
+ import { dispatchAssistantQuotaExhausted as ue, notifyAiCreditsUpdated as de } from "../../utils/aiCredits.js";
20
+ import { buildPromptForMode as fe } from "../../utils/assistantPrompt.js";
21
+ import { isMultimodalBodyRejection as pe, isRecoverableAssistantError as me } from "../../utils/assistantTransportErrors.js";
22
+ import { useCallback as T, useEffect as E, useMemo as D, useRef as he, useState as ge } from "react";
23
+ import { useI18n as _e } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
24
+ import { jsx as O, jsxs as ve } from "react/jsx-runtime";
25
+ import { useGatewayClient as ye } from "@burdenoff/fe-libs/shared/graphql";
26
+ import { useAuthToken as be } from "@burdenoff/fe-libs/shared/providers/shell";
27
+ import { getAssistantMedia as xe } from "@burdenoff/fe-libs/shared/assistant";
28
28
  //#region src/components/assistant/AssistantChatArea.tsx
29
29
  var Se = {
30
30
  general: 18e4,
@@ -56,7 +56,7 @@ function Ee(e, t) {
56
56
  content: "Thinking...",
57
57
  done: !1
58
58
  };
59
- let r = n[n.length - 1], i = A(r.parts), a = O(r.parts), o = j(r.parts);
59
+ let r = n[n.length - 1], i = A(r.parts), a = xe(r.parts), o = j(r.parts);
60
60
  return {
61
61
  content: [
62
62
  i,
@@ -75,64 +75,64 @@ function De(e) {
75
75
  default: return "";
76
76
  }
77
77
  }
78
- var Oe = () => {
79
- let O = t(), A = be("workspace"), { getAccessToken: j, getWorkspaceToken: Oe, userId: ke } = xe(), { locale: M } = ve(), N = e((e) => e.assistantLanguage), Ae = T(() => g(N, M).english, [N, M]), je = h(N) !== null, Me = T(() => g(N, M).code, [N, M]), { conversations: Ne, activeConversationId: P, mode: F, processingByConversationId: Pe, setMode: I, setConversationMode: L, setActiveConversation: Fe, createConversation: R, addMessage: z, updateMessage: B, patchMessage: V, setConversationProcessing: H, clearConversationProcessing: Ie, setBackendSessionId: Le, clearBackendSessionId: U, setSandbox: W, clearSandbox: Re, acknowledgeApiCalls: ze } = e(), G = Ne.find((e) => e.id === P)?.messages ?? [], K = P ? Pe[P] : void 0, q = _(K?.status), Be = q ? K?.messageId ?? null : null, Ve = K?.status === "error" ? K.messageId : null, { canUseApiCalls: J, loading: He } = le(ee()), Ue = T(() => S.filter((e) => !e.requiresAdmin || J), [J]), [We, Ge] = _e(null), Ke = E({}), qe = E(/* @__PURE__ */ new Set());
80
- ge(() => {
81
- if (He) return;
82
- let e = S.find((e) => e.id === F);
83
- (!e || e.requiresAdmin && !J) && F !== "assistant" && I("assistant");
78
+ var M = ({ visible: xe = !0 }) => {
79
+ let A = t(), j = ye("workspace"), { getAccessToken: M, getWorkspaceToken: Oe, userId: ke } = be(), { locale: N } = _e(), P = e((e) => e.assistantLanguage), Ae = D(() => g(P, N).english, [P, N]), je = h(P) !== null, F = D(() => g(P, N).code, [P, N]), { conversations: Me, activeConversationId: I, mode: L, processingByConversationId: Ne, setMode: R, setConversationMode: z, setActiveConversation: Pe, createConversation: B, addMessage: Fe, updateMessage: Ie, patchMessage: V, setConversationProcessing: H, clearConversationProcessing: Le, setBackendSessionId: Re, clearBackendSessionId: U, setSandbox: W, clearSandbox: ze, acknowledgeApiCalls: Be } = e(), G = Me.find((e) => e.id === I)?.messages ?? [], K = I ? Ne[I] : void 0, q = _(K?.status), Ve = q ? K?.messageId ?? null : null, He = K?.status === "error" ? K.messageId : null, { canUseApiCalls: J, loading: Ue } = ce(ee()), We = D(() => C.filter((e) => !e.requiresAdmin || J), [J]), [Ge, Ke] = ge(null), qe = he({}), Je = he(/* @__PURE__ */ new Set());
80
+ E(() => {
81
+ if (Ue) return;
82
+ let e = C.find((e) => e.id === L);
83
+ (!e || e.requiresAdmin && !J) && L !== "assistant" && R("assistant");
84
84
  }, [
85
- F,
85
+ L,
86
86
  J,
87
- He,
88
- I
87
+ Ue,
88
+ R
89
89
  ]);
90
- let Y = w((e, t, n, r) => {
91
- H(e, n, t, null), r ? B(e, t, r) : B(e, t, De(n));
92
- }, [H, B]), Je = w(async (t, n, a, s, c) => {
90
+ let Y = T((e, t, n, r) => {
91
+ H(e, n, t, null), r ? Ie(e, t, r) : Ie(e, t, De(n));
92
+ }, [H, Ie]), Ye = T(async (t, n, a, s, c) => {
93
93
  let u = e.getState().sandboxesByMode[a]?.sandboxId ?? null, d = async (e) => {
94
94
  try {
95
- return await p(A, e, s, c, 3e5, (e) => Y(t, n, "provisioning", e)), await f(A, e, s, c, 9e4, (e) => Y(t, n, "connecting", e)), !0;
95
+ 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;
96
96
  } catch {
97
97
  return !1;
98
98
  }
99
99
  };
100
100
  if (u && (W(a, u, "provisioning"), Y(t, n, "provisioning", "Reusing assistant environment..."), await d(u) || (W(a, null, "provisioning"), u = null)), !u) {
101
101
  Y(t, n, "provisioning", "Looking for existing environment...");
102
- let e = await o(A, s, a, c);
102
+ let e = await o(j, s, a, c);
103
103
  e && (W(a, e, "provisioning"), Y(t, n, "provisioning", "Reusing assistant environment..."), await d(e) ? u = e : W(a, null, "provisioning"));
104
104
  }
105
105
  if (!u) {
106
- if (a === "api-calls" && !j()) throw Error("API Calls mode requires an authenticated session. Please sign in again.");
107
- Y(t, n, "provisioning", "Starting assistant environment..."), W(a, null, "provisioning"), u = await r(A, a, s, c), W(a, u, "provisioning"), await p(A, u, s, c, 3e5, (e) => Y(t, n, "provisioning", e)), await f(A, u, s, c, 9e4, (e) => Y(t, n, "connecting", e));
106
+ if (a === "api-calls" && !M()) throw Error("API Calls mode requires an authenticated session. Please sign in again.");
107
+ 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));
108
108
  }
109
109
  W(a, u, "running");
110
110
  let m = e.getState().conversations.find((e) => e.id === t)?.backendSessionId ?? null;
111
111
  if (m) try {
112
- let e = await l(A, u, s, m, c);
112
+ let e = await l(j, u, s, m, c);
113
113
  if (e.mode !== a) throw Error(`Session mode mismatch: expected ${a}, received ${e.mode}`);
114
114
  } catch {
115
115
  U(t), m = null;
116
116
  }
117
- return m || (Y(t, n, "connecting", "Preparing session..."), m = (await i(A, u, s, a, c)).sessionId, Le(t, m)), {
117
+ return m || (Y(t, n, "connecting", "Preparing session..."), m = (await i(j, u, s, a, c)).sessionId, Re(t, m)), {
118
118
  sandboxId: u,
119
119
  sessionId: m
120
120
  };
121
121
  }, [
122
- A,
123
- U,
124
122
  j,
125
- Le,
123
+ U,
124
+ M,
125
+ Re,
126
126
  W,
127
127
  Y
128
- ]), X = w(async (t, r = []) => {
129
- let i = e.getState(), o = i.activeConversationId ?? P;
130
- if (o && (_(i.processingByConversationId[o]?.status) || qe.current.has(o))) return;
131
- let l = i.mode, f = P, p = f ? e.getState().conversations.find((e) => e.id === f) : void 0;
132
- if (f ? p && p.mode !== l && (p.messages.length > 0 || p.backendSessionId) ? f = R(void 0, l) : p && p.mode !== l && L(f, l) : f = R(void 0, l), !f) return;
133
- Ke.current[f] = r;
134
- let h = te(), g = {
135
- accessToken: j(),
128
+ ]), X = T(async (t, r = []) => {
129
+ let i = e.getState(), o = i.activeConversationId ?? I;
130
+ if (o && (_(i.processingByConversationId[o]?.status) || Je.current.has(o))) return;
131
+ let l = i.mode, f = I, p = f ? e.getState().conversations.find((e) => e.id === f) : void 0;
132
+ if (f ? p && p.mode !== l && (p.messages.length > 0 || p.backendSessionId) ? f = B(void 0, l) : p && p.mode !== l && z(f, l) : f = B(void 0, l), !f) return;
133
+ qe.current[f] = r;
134
+ let h = y(), g = {
135
+ accessToken: M(),
136
136
  workspaceToken: Oe(),
137
137
  userId: ke,
138
138
  organizationId: ee()
@@ -141,19 +141,19 @@ var Oe = () => {
141
141
  role: "user",
142
142
  content: t,
143
143
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
144
- metadata: r.length ? { attachments: r.map(y) } : void 0
144
+ metadata: r.length ? { attachments: r.map(b) } : void 0
145
145
  };
146
- z(f, v);
147
- let b = we();
148
- z(f, {
149
- id: b,
146
+ Fe(f, v);
147
+ let x = we();
148
+ Fe(f, {
149
+ id: x,
150
150
  role: "assistant",
151
151
  content: "",
152
152
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
153
- metadata: { lang: Me }
154
- }), H(f, "provisioning", b, null);
155
- let x = (e, t, n, r, i = Me) => {
156
- V(f, b, {
153
+ metadata: { lang: F }
154
+ }), H(f, "provisioning", x, null);
155
+ let S = (e, t, n, r, i = F) => {
156
+ V(f, x, {
157
157
  content: Te(e),
158
158
  metadata: {
159
159
  lang: i,
@@ -163,102 +163,102 @@ var Oe = () => {
163
163
  ...r ? { sandboxId: r } : {}
164
164
  }
165
165
  });
166
- }, S = async (e = 1) => {
166
+ }, C = async (e = 1) => {
167
167
  let i = !1;
168
168
  try {
169
- await n(A, h, g);
169
+ await n(j, h, g);
170
170
  } catch (e) {
171
- if (ue(e)) {
172
- de("ai-credits"), x("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(f, "error", b, null);
171
+ if (le(e)) {
172
+ 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(f, "error", x, null);
173
173
  return;
174
174
  }
175
175
  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);
176
176
  }
177
177
  try {
178
- let { sandboxId: e, sessionId: n } = await Je(f, b, l, h, g), o = (await c(A, e, h, n, g, 50).catch(() => [])).reduce((e, t) => Math.max(e, k(t)), 0);
179
- Y(f, b, "streaming", "Thinking...");
180
- let p = pe(l, re(t, r), Ae, je), _ = ne(p, r), v = ae(_), ee = v > 0, te = m();
181
- i = ie(r) > v;
178
+ let { sandboxId: e, sessionId: n } = await Ye(f, x, l, h, g), o = (await c(j, e, h, n, g, 50).catch(() => [])).reduce((e, t) => Math.max(e, k(t)), 0);
179
+ Y(f, x, "streaming", "Thinking...");
180
+ let p = fe(l, ne(t, r), Ae, je), _ = te(p, r), v = ie(_), ee = v > 0, y = m();
181
+ i = re(r) > v;
182
182
  try {
183
- await d(A, e, h, n, p, l, te, g, _);
183
+ await d(j, e, h, n, p, l, y, g, _);
184
184
  } catch (t) {
185
- if (!_ || !me(t)) throw t;
186
- await d(A, e, h, n, p, l, te, g, void 0), i ||= ee;
185
+ if (!_ || !pe(t)) throw t;
186
+ await d(j, e, h, n, p, l, y, g, void 0), i ||= ee;
187
187
  }
188
- let y = Ee([], o), S = Date.now() + (Se[l] ?? Ce), C = Date.now();
189
- for (; Date.now() < S && (y = Ee(await c(A, e, h, n, g, 50), o), V(f, b, { content: Te(y.content) }), !y.done);) Date.now() - C > 3e4 && (await a(A, e, h, 600, g).catch(() => void 0), C = Date.now()), await new Promise((e) => setTimeout(e, 1500));
190
- if (!y.done && l !== "vibe-plugins") throw Error("Assistant response timed out while streaming progress");
191
- let oe = l === "vibe-plugins" ? await s(A, e, h, n, g).catch(() => []) : void 0;
192
- if (y.done || (y = {
193
- ...y,
194
- content: `${y.content}\n\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`
195
- }), i && (y = {
196
- ...y,
197
- content: `${y.content}\n\n${O("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._")}`
198
- }), x(y.content, oe, n, e), y.tokens) {
199
- V(f, b, { tokens: y.tokens });
188
+ let b = Ee([], o), C = Date.now() + (Se[l] ?? Ce), w = Date.now();
189
+ for (; Date.now() < C && (b = Ee(await c(j, e, h, n, g, 50), o), V(f, x, { content: Te(b.content) }), !b.done);) Date.now() - w > 3e4 && (await a(j, e, h, 600, g).catch(() => void 0), w = Date.now()), await new Promise((e) => setTimeout(e, 1500));
190
+ if (!b.done && l !== "vibe-plugins") throw Error("Assistant response timed out while streaming progress");
191
+ let ae = l === "vibe-plugins" ? await s(j, e, h, n, g).catch(() => []) : void 0;
192
+ if (b.done || (b = {
193
+ ...b,
194
+ 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._`
195
+ }), i && (b = {
196
+ ...b,
197
+ 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._")}`
198
+ }), S(b.content, ae, n, e), b.tokens) {
199
+ V(f, x, { tokens: b.tokens });
200
200
  try {
201
- await u(A, h, n, y.tokens, g), fe();
201
+ await u(j, h, n, b.tokens, g), de();
202
202
  } catch {}
203
203
  }
204
- H(f, "complete", b, null);
204
+ H(f, "complete", x, null);
205
205
  } catch (t) {
206
- if (e === 1 && he(t)) return U(f), Re(l), S(2);
206
+ if (e === 1 && me(t)) return U(f), ze(l), C(2);
207
207
  throw t;
208
208
  }
209
- }, C = f;
210
- qe.current.add(C);
209
+ }, w = f;
210
+ Je.current.add(w);
211
211
  try {
212
212
  if (!h) throw Error("Assistant backend is unavailable without an active workspace context.");
213
- await S();
213
+ await C();
214
214
  } catch (e) {
215
- if (ue(e)) {
216
- de("sandbox"), x("You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.", void 0, void 0, void 0, "en"), H(f, "error", b, null);
215
+ if (le(e)) {
216
+ 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(f, "error", x, null);
217
217
  return;
218
218
  }
219
219
  let t = e instanceof Error ? e.message : "Something went wrong";
220
- H(f, "error", b, t), V(f, b, {
220
+ H(f, "error", x, t), V(f, x, {
221
221
  content: `Sorry, an error occurred: ${t}. Please try again.`,
222
222
  metadata: { lang: "en" }
223
223
  });
224
224
  } finally {
225
- qe.current.delete(C);
225
+ Je.current.delete(w);
226
226
  }
227
227
  }, [
228
- P,
229
- z,
230
- A,
231
- U,
232
- Re,
233
- Ne,
234
- R,
235
- Je,
228
+ I,
229
+ Fe,
236
230
  j,
231
+ U,
232
+ ze,
233
+ Me,
234
+ B,
235
+ Ye,
236
+ M,
237
237
  Oe,
238
238
  V,
239
239
  je,
240
- Me,
240
+ F,
241
241
  Ae,
242
- Le,
243
- L,
242
+ Re,
243
+ z,
244
244
  H,
245
- O,
245
+ A,
246
246
  Y,
247
247
  ke
248
- ]), Ye = w((e) => {
248
+ ]), Xe = T((e) => {
249
249
  X(e);
250
- }, [X]), Xe = w(() => {
251
- let e = [...G].reverse().find((e) => e.role === "user"), t = P ? Ke.current[P] ?? [] : [];
250
+ }, [X]), Ze = T(() => {
251
+ let e = [...G].reverse().find((e) => e.role === "user"), t = I ? qe.current[I] ?? [] : [];
252
252
  e && X(e.content, t);
253
253
  }, [
254
254
  G,
255
255
  X,
256
- P
257
- ]), Z = E(X);
258
- ge(() => {
256
+ I
257
+ ]), Z = he(X);
258
+ E(() => {
259
259
  Z.current = X;
260
260
  }, [X]);
261
- let Ze = T(() => {
261
+ let Qe = D(() => {
262
262
  if (q) return null;
263
263
  for (let e = G.length - 1; e >= 0; --e) {
264
264
  let t = G[e];
@@ -270,14 +270,16 @@ var Oe = () => {
270
270
  } : null;
271
271
  }
272
272
  return null;
273
- }, [G, q]), Q = ce({
274
- onSubmit: w((e) => {
273
+ }, [G, q]), Q = se({
274
+ onSubmit: T((e) => {
275
275
  Z.current(e);
276
276
  }, []),
277
- latestReply: Ze,
278
- language: g(N, M).tag
277
+ latestReply: Qe,
278
+ language: g(P, N).tag
279
279
  });
280
- ge(() => {
280
+ E(() => {
281
+ !xe && Q.active && Q.end();
282
+ }, [xe, Q]), E(() => {
281
283
  let t = e.getState().consumePendingPrompt();
282
284
  return t && Z.current(t), e.subscribe((t, n) => {
283
285
  if (t.pendingPrompt && t.pendingPrompt !== n.pendingPrompt) {
@@ -286,76 +288,79 @@ var Oe = () => {
286
288
  }
287
289
  });
288
290
  }, []);
289
- let $ = w((t) => {
290
- let n = P ? e.getState().conversations.find((e) => e.id === P) : void 0;
291
+ let $ = T((t) => {
292
+ let n = I ? e.getState().conversations.find((e) => e.id === I) : void 0;
291
293
  if (n && (n.messages.length > 0 || n.backendSessionId)) {
292
294
  if (n.mode !== t) {
293
295
  let n = e.getState().conversations.find((n) => n.mode === t && n.messages.length === 0 && !n.backendSessionId && !e.getState().processingByConversationId[n.id]);
294
- n ? Fe(n.id) : R(void 0, t);
296
+ n ? Pe(n.id) : B(void 0, t);
295
297
  }
296
- } else P && L(P, t);
297
- I(t);
298
+ } else I && z(I, t);
299
+ R(t);
298
300
  }, [
299
- P,
300
- R,
301
- Fe,
302
- L,
303
- I
304
- ]), Qe = w((t) => {
305
- if (S.find((e) => e.id === t)?.writeCapable && !e.getState().apiCallsAcknowledged) {
306
- Ge(t);
301
+ I,
302
+ B,
303
+ Pe,
304
+ z,
305
+ R
306
+ ]), $e = T((t) => {
307
+ if (C.find((e) => e.id === t)?.writeCapable && !e.getState().apiCallsAcknowledged) {
308
+ Ke(t);
307
309
  return;
308
310
  }
309
311
  $(t);
310
- }, [$]), $e = w(() => {
311
- let e = We;
312
- Ge(null), ze(), e && $(e);
312
+ }, [$]), et = T(() => {
313
+ let e = Ge;
314
+ Ke(null), Be(), e && $(e);
313
315
  }, [
314
- We,
315
- ze,
316
+ Ge,
317
+ Be,
316
318
  $
317
- ]), et = w(() => {
318
- Ge(null);
319
+ ]), tt = T(() => {
320
+ Ke(null);
319
321
  }, []);
320
- return /* @__PURE__ */ ye("div", {
321
- className: "flex flex-1 flex-col overflow-hidden",
322
+ return /* @__PURE__ */ ve("div", {
323
+ className: "relative flex flex-1 flex-col overflow-hidden",
322
324
  children: [
323
- G.length === 0 ? /* @__PURE__ */ D(C, {
324
- mode: F,
325
- onSuggestionClick: Ye
326
- }) : /* @__PURE__ */ D("div", {
327
- className: "flex min-h-0 flex-1 flex-col",
328
- children: /* @__PURE__ */ D(b, {
329
- messages: G,
330
- streamingMessageId: Be,
331
- failedMessageId: Ve,
332
- onRetry: Xe
333
- })
334
- }),
335
- /* @__PURE__ */ D(oe, {
336
- onStartVoiceSession: Q.available && F !== "api-calls" ? Q.start : void 0,
337
- onSend: (e, t) => void X(e, t),
338
- disabled: q,
339
- placeholder: F === "api-calls" ? O("healthybowl.assistant.chatArea.placeholderActions", "What would you like me to do?") : O("healthybowl.assistant.chatArea.placeholderGeneral", "Ask HealthyBowl anything…"),
340
- mode: F,
341
- availableModes: Ue,
342
- onModeChange: Qe
325
+ /* @__PURE__ */ ve("div", {
326
+ className: "contents",
327
+ inert: Q.active || void 0,
328
+ children: [G.length === 0 ? /* @__PURE__ */ O(w, {
329
+ mode: L,
330
+ onSuggestionClick: Xe
331
+ }) : /* @__PURE__ */ O("div", {
332
+ className: "flex min-h-0 flex-1 flex-col",
333
+ children: /* @__PURE__ */ O(x, {
334
+ messages: G,
335
+ streamingMessageId: Ve,
336
+ failedMessageId: He,
337
+ onRetry: Ze
338
+ })
339
+ }), /* @__PURE__ */ O(ae, {
340
+ onStartVoiceSession: Q.available && L !== "api-calls" ? Q.start : void 0,
341
+ onSend: (e, t) => void X(e, t),
342
+ disabled: q,
343
+ placeholder: L === "api-calls" ? A("healthybowl.assistant.chatArea.placeholderActions", "What would you like me to do?") : A("healthybowl.assistant.chatArea.placeholderGeneral", "Ask HealthyBowl anything…"),
344
+ mode: L,
345
+ availableModes: We,
346
+ onModeChange: $e
347
+ })]
343
348
  }),
344
- Q.active && /* @__PURE__ */ D(se, {
349
+ Q.active && /* @__PURE__ */ O(oe, {
345
350
  session: Q.session,
346
- spoken: Ze?.text ?? null,
351
+ spoken: Qe?.text ?? null,
347
352
  onToggleMute: Q.toggleMute,
348
353
  onEnd: Q.end
349
354
  }),
350
- /* @__PURE__ */ D(x, {
351
- open: We !== null,
352
- onConfirm: $e,
353
- onCancel: et
355
+ /* @__PURE__ */ O(S, {
356
+ open: Ge !== null,
357
+ onConfirm: et,
358
+ onCancel: tt
354
359
  })
355
360
  ]
356
361
  });
357
362
  };
358
363
  //#endregion
359
- export { Oe as AssistantChatArea };
364
+ export { M as AssistantChatArea };
360
365
 
361
366
  //# 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';\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\nexport const AssistantChatArea: FC = () => {\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[] = []) => {\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 );\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 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 await new Promise((resolve) => setTimeout(resolve, 1500));\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 const submitVoiceTurn = useCallback((text: string) => {\n void handleSendRef.current(text);\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 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 <div className=\"flex flex-1 flex-col overflow-hidden\">\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\n {voiceSession.active && (\n <AssistantVoiceSession\n session={voiceSession.session}\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={handleConsentCanc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esContent":["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';\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[] = []) => {\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 );\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 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 await new Promise((resolve) => setTimeout(resolve, 1500));\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 const submitVoiceTurn = useCallback((text: string) => {\n void handleSendRef.current(text);\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 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuDA,IAAM,KAAkD;CACtD,SAAS;CACT,WAAW;CACX,aAAa;CACb,gBAAgB;AAClB,GACM,KAA2B;AAEjC,SAAS,KAAqB;CAC5B,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC;AAC/D;AAEA,SAAS,GAA0B,GAA0B;CAC3D,OAAO,EACJ,QAAQ,6CAA6C,cAAc,EACnE,QAAQ,yDAAyD,cAAc,EAC/E,QAAQ,4DAA4D,gBAAgB,EACpF,QAAQ,6BAA6B,oBAAoB;AAC9D;AAEA,SAAS,EAAuB,GAAsC;CACpE,OAAO,EAAQ,MAAM,MAAM,WAAW;AACxC;AAEA,SAAS,EAAiB,GAA6C;CACrE,QAAQ,KAAS,CAAC,GACf,QAAQ,MAAS,EAAK,SAAS,UAAU,OAAO,EAAK,QAAS,QAAQ,EACtE,KAAK,MAAS,EAAK,MAAM,KAAK,KAAK,EAAE,EACrC,OAAO,OAAO,EACd,KAAK,IAAI;AACd;AAEA,SAAS,EAAgB,GAA+C;CACtE,QAAQ,KAAS,CAAC,GACf,QAAQ,MAAS,EAAK,SAAS,UAAU,EAAK,IAAI,EAClD,KAAK,MAAS;EACb,IAAM,IAAS,EAAK,OAAO,UAAU,WAC/B,IAAO,EAAK,QAAQ;EAG1B,OAFI,MAAW,cAAoB,cAAc,MAC7C,MAAW,WAAiB,WAAW,MACpC,YAAY;CACrB,CAAC;AACL;AAEA,SAAS,GACP,GAUA,GAKA;CACA,IAAM,IAAW,EACd,QAAQ,MAAY,EAAQ,MAAM,SAAS,eAAe,EAAuB,CAAO,IAAI,CAAoB,EAChH,MAAM,GAAM,MAAU,EAAu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ChB,cAAc;IACf,CAAA,CACE;;GAEJ,EAAa,UACZ,kBAAC,IAAD;IACE,SAAS,EAAa;IACtB,QAAQ,IAAsB,QAAQ;IACtC,cAAc,EAAa;IAC3B,OAAO,EAAa;GACrB,CAAA;GAGH,kBAAC,GAAD;IACE,MAAM,OAAuB;IAC7B,WAAW;IACX,UAAU;GACX,CAAA;EACE;;AAET"}
@@ -1,15 +1,15 @@
1
1
  import { orbMode as e } from "../../../utils/voiceSession.js";
2
2
  import { jsx as t } from "react/jsx-runtime";
3
3
  //#region src/components/assistant/voice/AssistantVoiceOrb.tsx
4
- var n = ({ session: n }) => {
5
- let r = e(n);
4
+ var n = ({ session: n, compact: r = !1 }) => {
5
+ let i = e(n);
6
6
  return /* @__PURE__ */ t("div", {
7
7
  className: "flex items-center justify-center",
8
8
  "aria-hidden": "true",
9
9
  "data-testid": "assistant-voice-orb",
10
- "data-state": r,
10
+ "data-state": i,
11
11
  children: /* @__PURE__ */ t("div", {
12
- className: `size-40 rounded-full bg-gradient-to-b ${r === "listening" ? "from-action-primary-bg/80 to-action-primary-bg/20" : r === "thinking" ? "from-text-muted/60 to-text-muted/10" : r === "speaking" ? "from-action-primary-bg to-action-primary-bg/40" : "from-bg-elevated to-bg-elevated/40"} ${r === "listening" ? "motion-safe:animate-pulse" : r === "thinking" ? "motion-safe:animate-[spin_2.4s_linear_infinite]" : r === "speaking" ? "motion-safe:animate-[pulse_0.9s_ease-in-out_infinite]" : ""} shadow-lg transition-colors duration-300`,
12
+ className: `${r ? "size-24" : "size-40"} rounded-full bg-gradient-to-b ${i === "listening" ? "from-action-primary-bg/80 to-action-primary-bg/20" : i === "thinking" ? "from-text-muted/60 to-text-muted/10" : i === "speaking" ? "from-action-primary-bg to-action-primary-bg/40" : "from-bg-elevated to-bg-elevated/40"} ${i === "listening" ? "motion-safe:animate-pulse" : i === "thinking" ? "motion-safe:animate-[spin_2.4s_linear_infinite]" : i === "speaking" ? "motion-safe:animate-[pulse_0.9s_ease-in-out_infinite]" : ""} shadow-lg transition-colors duration-300`,
13
13
  "aria-hidden": "true"
14
14
  })
15
15
  });
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantVoiceOrb.js","names":[],"sources":["../../../../src/components/assistant/voice/AssistantVoiceOrb.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport type { VoiceSessionSnapshot } from '../../../utils/voiceSession';\nimport { orbMode } from '../../../utils/voiceSession';\n\n/**\n * The animated state indicator at the centre of a voice session (BOFF-7120).\n *\n * Its whole job is to answer \"is it hearing me, thinking, or talking?\" without\n * words — which matters more here than in a chat panel, because the user is\n * looking at a screen with no transcript scrolling past and needs to know\n * whether to keep speaking.\n *\n * The `thinking` state is deliberately conspicuous. Our pipeline is turn-based,\n * so there is a real 2-5s gap between the user finishing and the reply starting;\n * hiding that would just make the session feel broken rather than busy.\n *\n * Animation is pure CSS so it costs nothing while idle and keeps working under\n * `prefers-reduced-motion`, where the pulse is replaced by a static ring rather\n * than removed entirely — the state still has to be readable.\n */\nexport const AssistantVoiceOrb: FC<{ session: VoiceSessionSnapshot }> = ({ session }) => {\n const mode = orbMode(session);\n\n // Colour carries the state for anyone who cannot perceive the motion; the\n // animation is a second, redundant channel rather than the only one.\n const tone =\n mode === 'listening'\n ? 'from-action-primary-bg/80 to-action-primary-bg/20'\n : mode === 'thinking'\n ? 'from-text-muted/60 to-text-muted/10'\n : mode === 'speaking'\n ? 'from-action-primary-bg to-action-primary-bg/40'\n : 'from-bg-elevated to-bg-elevated/40';\n\n const motion =\n mode === 'listening'\n ? 'motion-safe:animate-pulse'\n : mode === 'thinking'\n ? 'motion-safe:animate-[spin_2.4s_linear_infinite]'\n : mode === 'speaking'\n ? 'motion-safe:animate-[pulse_0.9s_ease-in-out_infinite]'\n : '';\n\n return (\n <div\n className=\"flex items-center justify-center\"\n // Purely decorative. A `role=\"status\"` here would announce nothing at all,\n // because the only child is aria-hidden and the orb carries no text — the\n // session's status paragraph is the live region, and it has real words.\n aria-hidden=\"true\"\n data-testid=\"assistant-voice-orb\"\n data-state={mode}\n >\n <div\n className={`size-40 rounded-full bg-gradient-to-b ${tone} ${motion} shadow-lg transition-colors duration-300`}\n aria-hidden=\"true\"\n />\n </div>\n );\n};\n"],"mappings":";;;AAoBA,IAAa,KAA4D,EAAE,iBAAc;CACvF,IAAM,IAAO,EAAQ,CAAO;CAsB5B,OACE,kBAAC,OAAD;EACE,WAAU;EAIV,eAAY;EACZ,eAAY;EACZ,cAAY;YAEZ,kBAAC,OAAD;GACE,WAAW,yCA5Bf,MAAS,cACL,sDACA,MAAS,aACP,wCACA,MAAS,aACP,mDACA,qCAsBqD,GAnB7D,MAAS,cACL,8BACA,MAAS,aACP,oDACA,MAAS,aACP,0DACA,GAa+D;GACnE,eAAY;EACb,CAAA;CACE,CAAA;AAET"}
1
+ {"version":3,"file":"AssistantVoiceOrb.js","names":[],"sources":["../../../../src/components/assistant/voice/AssistantVoiceOrb.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport type { VoiceSessionSnapshot } from '../../../utils/voiceSession';\nimport { orbMode } from '../../../utils/voiceSession';\n\n/**\n * The animated state indicator at the centre of a voice session (BOFF-7120).\n *\n * Its whole job is to answer \"is it hearing me, thinking, or talking?\" without\n * words — which matters more here than in a chat panel, because the user is\n * looking at a screen with no transcript scrolling past and needs to know\n * whether to keep speaking.\n *\n * The `thinking` state is deliberately conspicuous. Our pipeline is turn-based,\n * so there is a real 2-5s gap between the user finishing and the reply starting;\n * hiding that would just make the session feel broken rather than busy.\n *\n * Animation is pure CSS so it costs nothing while idle and keeps working under\n * `prefers-reduced-motion`, where the pulse is replaced by a static ring rather\n * than removed entirely — the state still has to be readable.\n */\nexport const AssistantVoiceOrb: FC<{ session: VoiceSessionSnapshot; compact?: boolean }> = ({\n session,\n compact = false,\n}) => {\n const mode = orbMode(session);\n\n // Colour carries the state for anyone who cannot perceive the motion; the\n // animation is a second, redundant channel rather than the only one.\n const tone =\n mode === 'listening'\n ? 'from-action-primary-bg/80 to-action-primary-bg/20'\n : mode === 'thinking'\n ? 'from-text-muted/60 to-text-muted/10'\n : mode === 'speaking'\n ? 'from-action-primary-bg to-action-primary-bg/40'\n : 'from-bg-elevated to-bg-elevated/40';\n\n const motion =\n mode === 'listening'\n ? 'motion-safe:animate-pulse'\n : mode === 'thinking'\n ? 'motion-safe:animate-[spin_2.4s_linear_infinite]'\n : mode === 'speaking'\n ? 'motion-safe:animate-[pulse_0.9s_ease-in-out_infinite]'\n : '';\n\n return (\n <div\n className=\"flex items-center justify-center\"\n // Purely decorative. A `role=\"status\"` here would announce nothing at all,\n // because the only child is aria-hidden and the orb carries no text — the\n // session's status paragraph is the live region, and it has real words.\n aria-hidden=\"true\"\n data-testid=\"assistant-voice-orb\"\n data-state={mode}\n >\n <div\n // Smaller when docked inside the assistant panel: at 160px the orb\n // crowds out the caption in a panel that is only a few hundred px wide.\n className={`${compact ? 'size-24' : 'size-40'} rounded-full bg-gradient-to-b ${tone} ${motion} shadow-lg transition-colors duration-300`}\n aria-hidden=\"true\"\n />\n </div>\n );\n};\n"],"mappings":";;;AAoBA,IAAa,KAA+E,EAC1F,YACA,aAAU,SACN;CACJ,IAAM,IAAO,EAAQ,CAAO;CAsB5B,OACE,kBAAC,OAAD;EACE,WAAU;EAIV,eAAY;EACZ,eAAY;EACZ,cAAY;YAEZ,kBAAC,OAAD;GAGE,WAAW,GAAG,IAAU,YAAY,UAAU,iCA9BlD,MAAS,cACL,sDACA,MAAS,aACP,wCACA,MAAS,aACP,mDACA,qCAwBgF,GArBxF,MAAS,cACL,8BACA,MAAS,aACP,oDACA,MAAS,aACP,0DACA,GAe0F;GAC9F,eAAY;EACb,CAAA;CACE,CAAA;AAET"}
@@ -1,75 +1,91 @@
1
1
  import { useTr as e } from "../../../shared/hooks/useTr.js";
2
2
  import { spokenSoFar as t } from "../../../utils/voiceSession.js";
3
3
  import { AssistantVoiceOrb as n } from "./AssistantVoiceOrb.js";
4
- import { useEffect as r, useRef as i } from "react";
5
- import { Mic as a, MicOff as o, X as s } from "lucide-react";
6
- import { jsx as c, jsxs as l } from "react/jsx-runtime";
4
+ import { useEffect as r, useRef as i, useState as a } from "react";
5
+ import { Maximize2 as o, Mic as s, MicOff as c, Minimize2 as l, X as u } from "lucide-react";
6
+ import { jsx as d, jsxs as f } from "react/jsx-runtime";
7
7
  //#region src/components/assistant/voice/AssistantVoiceSession.tsx
8
- var u = ({ session: u, spoken: f, onToggleMute: p, onEnd: m }) => {
9
- let h = e(), { phase: g, muted: _, error: v } = u, y = i(null), b = i(null);
8
+ var p = ({ session: p, spoken: h, onToggleMute: g, onEnd: _ }) => {
9
+ let v = e(), { phase: y, muted: b, error: x } = p, S = i(null), C = i(null), [w, T] = a(!1);
10
10
  r(() => {
11
- y.current?.focus();
11
+ S.current?.focus();
12
+ }, []), r(() => {
12
13
  let e = (e) => {
13
14
  if (e.key === "Escape") {
14
- m();
15
+ _();
15
16
  return;
16
17
  }
17
- if (e.key !== "Tab") return;
18
- let t = b.current?.querySelectorAll("button:not([disabled])");
18
+ if (e.key !== "Tab" || !w) return;
19
+ let t = C.current?.querySelectorAll("button:not([disabled])");
19
20
  if (!t || t.length === 0) return;
20
21
  let n = t[0], r = t[t.length - 1];
21
22
  !n || !r || (e.shiftKey && document.activeElement === n ? (e.preventDefault(), r.focus()) : !e.shiftKey && document.activeElement === r && (e.preventDefault(), n.focus()));
22
23
  };
23
24
  return window.addEventListener("keydown", e), () => window.removeEventListener("keydown", e);
24
- }, [m]);
25
- let x = g === "thinking" ? h("healthybowl.assistant.voiceSession.thinking", "Thinking…") : g === "speaking" ? h("healthybowl.assistant.voiceSession.speaking", "Speaking — talk to interrupt") : _ ? h("healthybowl.assistant.voiceSession.muted", "Microphone off") : h("healthybowl.assistant.voiceSession.listening", "Listening…"), S = v === null ? _ && g !== "listening" ? `${x} · ${h("healthybowl.assistant.voiceSession.muted", "Microphone off")}` : x : d(v, h), C = g === "speaking" ? f : t(u);
26
- return /* @__PURE__ */ l("div", {
27
- ref: b,
28
- className: "fixed inset-0 z-[60] flex flex-col items-center justify-between bg-bg-sunken px-6 py-10",
25
+ }, [_, w]);
26
+ let E = y === "thinking" ? v("healthybowl.assistant.voiceSession.thinking", "Thinking…") : y === "speaking" ? v("healthybowl.assistant.voiceSession.speaking", "Speaking — talk to interrupt") : b ? v("healthybowl.assistant.voiceSession.muted", "Microphone off") : v("healthybowl.assistant.voiceSession.listening", "Listening…"), D = x === null ? b && y !== "listening" ? `${E} · ${v("healthybowl.assistant.voiceSession.muted", "Microphone off")}` : E : m(x, v), O = y === "speaking" ? h : t(p);
27
+ return /* @__PURE__ */ f("div", {
28
+ ref: C,
29
+ className: `flex flex-col items-center justify-between bg-bg-sunken ${w ? "fixed inset-0 z-[60] px-6 py-10" : "absolute inset-0 z-20 px-4 py-6"}`,
29
30
  role: "dialog",
30
- "aria-modal": "true",
31
- "aria-label": h("healthybowl.assistant.voiceSession.title", "Voice conversation"),
31
+ "aria-modal": w || void 0,
32
+ "aria-label": v("healthybowl.assistant.voiceSession.title", "Voice conversation"),
32
33
  "data-testid": "assistant-voice-session",
33
34
  children: [
34
- /* @__PURE__ */ c("p", {
35
+ /* @__PURE__ */ d("p", {
35
36
  className: "text-sm text-text-muted",
36
37
  role: "status",
37
38
  "aria-live": "polite",
38
39
  "data-testid": "assistant-voice-status",
39
- children: S
40
+ children: D
40
41
  }),
41
- /* @__PURE__ */ l("div", {
42
+ /* @__PURE__ */ f("div", {
42
43
  className: "flex flex-1 flex-col items-center justify-center gap-8",
43
- children: [/* @__PURE__ */ c(n, { session: u }), C ? /* @__PURE__ */ c("p", {
44
+ children: [/* @__PURE__ */ d(n, {
45
+ session: p,
46
+ compact: !w
47
+ }), O ? /* @__PURE__ */ d("p", {
44
48
  className: "line-clamp-3 max-w-md text-center text-base leading-relaxed text-text-secondary",
45
49
  "data-testid": "assistant-voice-caption",
46
- children: C
50
+ children: O
47
51
  }) : null]
48
52
  }),
49
- /* @__PURE__ */ l("div", {
50
- className: "flex items-center gap-6",
51
- children: [/* @__PURE__ */ c("button", {
52
- type: "button",
53
- onClick: p,
54
- className: "flex size-14 items-center justify-center rounded-full bg-bg-elevated text-text-primary transition-colors hover:bg-bg-raised focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong",
55
- "aria-pressed": _,
56
- "aria-label": _ ? h("healthybowl.assistant.voiceSession.unmute", "Turn the microphone on") : h("healthybowl.assistant.voiceSession.mute", "Turn the microphone off"),
57
- "data-testid": "assistant-voice-mute",
58
- children: c(_ ? o : a, { className: "size-6" })
59
- }), /* @__PURE__ */ c("button", {
60
- ref: y,
61
- type: "button",
62
- onClick: m,
63
- className: "flex size-14 items-center justify-center rounded-full bg-action-danger-bg text-action-danger-text transition-colors hover:bg-action-danger-bg-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong",
64
- "aria-label": h("healthybowl.assistant.voiceSession.end", "End the voice conversation"),
65
- "data-testid": "assistant-voice-end",
66
- children: /* @__PURE__ */ c(s, { className: "size-6" })
67
- })]
53
+ /* @__PURE__ */ f("div", {
54
+ className: `flex items-center ${w ? "gap-6" : "gap-4"}`,
55
+ children: [
56
+ /* @__PURE__ */ d("button", {
57
+ type: "button",
58
+ onClick: () => T((e) => !e),
59
+ className: `flex ${w ? "size-14" : "size-11"} items-center justify-center rounded-full bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`,
60
+ "aria-pressed": w,
61
+ "aria-label": w ? v("healthybowl.assistant.voiceSession.collapse", "Fit the conversation back into the panel") : v("healthybowl.assistant.voiceSession.expand", "Expand the conversation to full screen"),
62
+ "data-testid": "assistant-voice-expand",
63
+ children: d(w ? l : o, { className: "size-5" })
64
+ }),
65
+ /* @__PURE__ */ d("button", {
66
+ type: "button",
67
+ onClick: g,
68
+ className: `flex ${w ? "size-14" : "size-11"} items-center justify-center rounded-full bg-bg-elevated text-text-primary transition-colors hover:bg-bg-raised focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`,
69
+ "aria-pressed": b,
70
+ "aria-label": b ? v("healthybowl.assistant.voiceSession.unmute", "Turn the microphone on") : v("healthybowl.assistant.voiceSession.mute", "Turn the microphone off"),
71
+ "data-testid": "assistant-voice-mute",
72
+ children: d(b ? c : s, { className: w ? "size-6" : "size-5" })
73
+ }),
74
+ /* @__PURE__ */ d("button", {
75
+ ref: S,
76
+ type: "button",
77
+ onClick: _,
78
+ className: `flex ${w ? "size-14" : "size-11"} items-center justify-center rounded-full bg-action-danger-bg text-action-danger-text transition-colors hover:bg-action-danger-bg-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`,
79
+ "aria-label": v("healthybowl.assistant.voiceSession.end", "End the voice conversation"),
80
+ "data-testid": "assistant-voice-end",
81
+ children: /* @__PURE__ */ d(u, { className: w ? "size-6" : "size-5" })
82
+ })
83
+ ]
68
84
  })
69
85
  ]
70
86
  });
71
87
  };
72
- function d(e, t) {
88
+ function m(e, t) {
73
89
  switch (e) {
74
90
  case "mic-denied": return t("healthybowl.assistant.voiceSession.micDenied", "Microphone access is blocked. Allow it in your browser settings to talk.");
75
91
  case "no-speech-support": return t("healthybowl.assistant.voiceSession.noSpeechSupport", "This browser cannot listen. Try a different browser, or type instead.");
@@ -78,6 +94,6 @@ function d(e, t) {
78
94
  }
79
95
  }
80
96
  //#endregion
81
- export { u as AssistantVoiceSession };
97
+ export { p as AssistantVoiceSession };
82
98
 
83
99
  //# sourceMappingURL=AssistantVoiceSession.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantVoiceSession.js","names":[],"sources":["../../../../src/components/assistant/voice/AssistantVoiceSession.tsx"],"sourcesContent":["import { useEffect, useRef, type FC } from 'react';\nimport { Mic, MicOff, X } from 'lucide-react';\nimport { AssistantVoiceOrb } from './AssistantVoiceOrb';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { spokenSoFar, type VoiceSessionSnapshot } from '../../../utils/voiceSession';\nimport type { VoiceSessionError } from '../../../utils/voiceSession';\n\ninterface Props {\n session: VoiceSessionSnapshot;\n /** The assistant's last reply, captioned while it is spoken. */\n spoken: string | null;\n onToggleMute: () => void;\n onEnd: () => void;\n}\n\n/**\n * Full-screen voice conversation (BOFF-7120).\n *\n * ★ **Voice only, by explicit product decision.** The reference (Gemini Live)\n * also offers camera and screen sharing; those are deliberately absent here.\n * Attaching images is a separate, existing capability of the assistant and\n * stays in the composer, and screen sharing could not work on the primary\n * device anyway — `getDisplayMedia` is unsupported by every iOS browser, so\n * that control would be dead on an iPhone.\n *\n * The controls are therefore the two that a voice conversation actually needs:\n * mute, and end. Anything else would be a button the user has to think about\n * while talking.\n *\n * This component is presentational: every transition is owned by\n * `voiceSessionReducer`, which is pure and tested. That split exists because\n * this file cannot be tested at all in this repo — vitest runs in `node` with\n * no DOM and no audio.\n */\nexport const AssistantVoiceSession: FC<Props> = ({ session, spoken, onToggleMute, onEnd }) => {\n const tr = useTr();\n const { phase, muted, error } = session;\n const endRef = useRef<HTMLButtonElement>(null);\n const dialogRef = useRef<HTMLDivElement>(null);\n\n // A full-screen `aria-modal` overlay that cannot be dismissed from the\n // keyboard is a trap. Escape ends the session, and focus starts on End so a\n // keyboard or screen-reader user lands somewhere useful rather than behind\n // the overlay.\n useEffect(() => {\n endRef.current?.focus();\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n onEnd();\n return;\n }\n if (event.key !== 'Tab') return;\n // `aria-modal` only TELLS assistive technology this is modal; it does not\n // make it so. Without this, Tab walks straight out of the overlay into the\n // page behind it, which is still fully interactive underneath — a\n // keyboard user ends up operating a screen they cannot see.\n const focusable = dialogRef.current?.querySelectorAll<HTMLElement>('button:not([disabled])');\n if (!focusable || focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (!first || !last) return;\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n window.addEventListener('keydown', onKeyDown);\n return () => window.removeEventListener('keydown', onKeyDown);\n }, [onEnd]);\n\n // Muted is reported ALONGSIDE the phase, not instead of it: the assistant may\n // still be speaking with the microphone off, and saying only \"Microphone off\"\n // would misreport that.\n const phaseText =\n phase === 'thinking'\n ? tr('healthybowl.assistant.voiceSession.thinking', 'Thinking…')\n : phase === 'speaking'\n ? tr('healthybowl.assistant.voiceSession.speaking', 'Speaking — talk to interrupt')\n : muted\n ? tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')\n : tr('healthybowl.assistant.voiceSession.listening', 'Listening…');\n\n const status =\n error !== null\n ? errorMessage(error, tr)\n : muted && phase !== 'listening'\n ? `${phaseText} · ${tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')}`\n : phaseText;\n\n // While speaking, the caption shows the REPLY; otherwise what we have heard.\n // Showing the stale transcript under the assistant's own voice reads as a\n // mis-transcription of the assistant, which is worse than showing nothing.\n const caption = phase === 'speaking' ? spoken : spokenSoFar(session);\n\n return (\n <div\n ref={dialogRef}\n className=\"fixed inset-0 z-[60] flex flex-col items-center justify-between bg-bg-sunken px-6 py-10\"\n role=\"dialog\"\n aria-modal=\"true\"\n aria-label={tr('healthybowl.assistant.voiceSession.title', 'Voice conversation')}\n data-testid=\"assistant-voice-session\"\n >\n {/* The session's single live region. It has real words, unlike the orb. */}\n <p className=\"text-sm text-text-muted\" role=\"status\" aria-live=\"polite\" data-testid=\"assistant-voice-status\">\n {status}\n </p>\n\n <div className=\"flex flex-1 flex-col items-center justify-center gap-8\">\n <AssistantVoiceOrb session={session} />\n {caption ? (\n // Capped rather than scrolled: a long reply should not turn the\n // session into a wall of text the user reads instead of listens to.\n <p\n className=\"line-clamp-3 max-w-md text-center text-base leading-relaxed text-text-secondary\"\n data-testid=\"assistant-voice-caption\"\n >\n {caption}\n </p>\n ) : null}\n </div>\n\n <div className=\"flex items-center gap-6\">\n <button\n type=\"button\"\n onClick={onToggleMute}\n className=\"flex size-14 items-center justify-center rounded-full bg-bg-elevated text-text-primary transition-colors hover:bg-bg-raised focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong\"\n aria-pressed={muted}\n aria-label={\n muted\n ? tr('healthybowl.assistant.voiceSession.unmute', 'Turn the microphone on')\n : tr('healthybowl.assistant.voiceSession.mute', 'Turn the microphone off')\n }\n data-testid=\"assistant-voice-mute\"\n >\n {muted ? <MicOff className=\"size-6\" /> : <Mic className=\"size-6\" />}\n </button>\n\n <button\n ref={endRef}\n type=\"button\"\n onClick={onEnd}\n className=\"flex size-14 items-center justify-center rounded-full bg-action-danger-bg text-action-danger-text transition-colors hover:bg-action-danger-bg-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong\"\n aria-label={tr('healthybowl.assistant.voiceSession.end', 'End the voice conversation')}\n data-testid=\"assistant-voice-end\"\n >\n <X className=\"size-6\" />\n </button>\n </div>\n </div>\n );\n};\n\n/**\n * Every failure is explained rather than silently closing the session.\n *\n * A session that just vanishes is the dead-button bug in another shape — the\n * exact defect BOFF-7106 had to fix on the per-message speak control.\n */\nfunction errorMessage(error: VoiceSessionError, tr: ReturnType<typeof useTr>): string {\n switch (error) {\n case 'mic-denied':\n return tr(\n 'healthybowl.assistant.voiceSession.micDenied',\n 'Microphone access is blocked. Allow it in your browser settings to talk.'\n );\n case 'no-speech-support':\n return tr(\n 'healthybowl.assistant.voiceSession.noSpeechSupport',\n 'This browser cannot listen. Try a different browser, or type instead.'\n );\n case 'no-voice-support':\n return tr(\n 'healthybowl.assistant.voiceSession.noVoiceSupport',\n 'This device has no voice that can speak this language.'\n );\n default: {\n // Exhaustive: adding a variant without copy becomes a build error rather\n // than a silently empty status line.\n const unhandled: never = error;\n return unhandled;\n }\n }\n}\n"],"mappings":";;;;;;;AAkCA,IAAa,KAAoC,EAAE,YAAS,WAAQ,iBAAc,eAAY;CAC5F,IAAM,IAAK,EAAM,GACX,EAAE,UAAO,UAAO,aAAU,GAC1B,IAAS,EAA0B,IAAI,GACvC,IAAY,EAAuB,IAAI;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;;GAEL,kBAAC,OAAD;IAAK,WAAU;cAAf,CACE,kBAAC,UAAD;KACE,MAAK;KACL,SAAS;KACT,WAAU;KACV,gBAAc;KACd,cACE,IACI,EAAG,6CAA6C,wBAAwB,IACxE,EAAG,2CAA2C,yBAAyB;KAE7E,eAAY;eAEH,EAAR,IAAS,IAAgC,GAAjC,EAAQ,WAAU,SAAU,CAA6B;IAC5D,CAAA,GAER,kBAAC,UAAD;KACE,KAAK;KACL,MAAK;KACL,SAAS;KACT,WAAU;KACV,cAAY,EAAG,0CAA0C,4BAA4B;KACrF,eAAY;eAEZ,kBAAC,GAAD,EAAG,WAAU,SAAU,CAAA;IACjB,CAAA,CACL;;EACF;;AAET;AAQA,SAAS,EAAa,GAA0B,GAAsC;CACpF,QAAQ,GAAR;EACE,KAAK,cACH,OAAO,EACL,gDACA,0EACF;EACF,KAAK,qBACH,OAAO,EACL,sDACA,uEACF;EACF,KAAK,oBACH,OAAO,EACL,qDACA,wDACF;EACF,SAIE,OAAO;CAEX;AACF"}
1
+ {"version":3,"file":"AssistantVoiceSession.js","names":[],"sources":["../../../../src/components/assistant/voice/AssistantVoiceSession.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type FC } from 'react';\nimport { Maximize2, Mic, MicOff, Minimize2, X } from 'lucide-react';\nimport { AssistantVoiceOrb } from './AssistantVoiceOrb';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { spokenSoFar, type VoiceSessionSnapshot } from '../../../utils/voiceSession';\nimport type { VoiceSessionError } from '../../../utils/voiceSession';\n\ninterface Props {\n session: VoiceSessionSnapshot;\n /** The assistant's last reply, captioned while it is spoken. */\n spoken: string | null;\n onToggleMute: () => void;\n onEnd: () => void;\n}\n\n/**\n * Full-screen voice conversation (BOFF-7120).\n *\n * ★ **Voice only, by explicit product decision.** The reference (Gemini Live)\n * also offers camera and screen sharing; those are deliberately absent here.\n * Attaching images is a separate, existing capability of the assistant and\n * stays in the composer, and screen sharing could not work on the primary\n * device anyway — `getDisplayMedia` is unsupported by every iOS browser, so\n * that control would be dead on an iPhone.\n *\n * The controls are therefore the two that a voice conversation actually needs:\n * mute, and end. Anything else would be a button the user has to think about\n * while talking.\n *\n * This component is presentational: every transition is owned by\n * `voiceSessionReducer`, which is pure and tested. That split exists because\n * this file cannot be tested at all in this repo — vitest runs in `node` with\n * no DOM and no audio.\n */\nexport const AssistantVoiceSession: FC<Props> = ({ session, spoken, onToggleMute, onEnd }) => {\n const tr = useTr();\n const { phase, muted, error } = session;\n const endRef = useRef<HTMLButtonElement>(null);\n const dialogRef = useRef<HTMLDivElement>(null);\n /**\n * Docked inside the assistant panel by default; full-screen only on request.\n *\n * A voice conversation is usually a glance-and-listen thing, so taking over\n * the whole screen for it is the wrong default — the user loses the page they\n * were asking about. Expanding is opt-in and per-session: reopening starts\n * docked again, which is the behaviour that matches \"default should be the\n * same size as the assistant\".\n */\n const [expanded, setExpanded] = useState(false);\n\n // A full-screen `aria-modal` overlay that cannot be dismissed from the\n // keyboard is a trap. Escape ends the session, and focus starts on End so a\n // keyboard or screen-reader user lands somewhere useful rather than behind\n // the overlay.\n // Focus lands on End ONCE, on open. Keeping this in the keydown effect below\n // meant every expand/collapse re-ran it and silently stole focus from the\n // button just pressed — a Space or Enter a beat later would then end the\n // session instead of toggling the size again.\n useEffect(() => {\n endRef.current?.focus();\n }, []);\n\n useEffect(() => {\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n onEnd();\n return;\n }\n // Trapping focus is only correct when the overlay actually covers\n // everything. Docked, it sits inside the panel and the rest of the page\n // is legitimately reachable, so trapping there would be the bug rather\n // than the fix.\n if (event.key !== 'Tab' || !expanded) return;\n // `aria-modal` only TELLS assistive technology this is modal; it does not\n // make it so. Without this, Tab walks straight out of the overlay into the\n // page behind it, which is still fully interactive underneath — a\n // keyboard user ends up operating a screen they cannot see.\n const focusable = dialogRef.current?.querySelectorAll<HTMLElement>('button:not([disabled])');\n if (!focusable || focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (!first || !last) return;\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n window.addEventListener('keydown', onKeyDown);\n return () => window.removeEventListener('keydown', onKeyDown);\n }, [onEnd, expanded]);\n\n // Muted is reported ALONGSIDE the phase, not instead of it: the assistant may\n // still be speaking with the microphone off, and saying only \"Microphone off\"\n // would misreport that.\n const phaseText =\n phase === 'thinking'\n ? tr('healthybowl.assistant.voiceSession.thinking', 'Thinking…')\n : phase === 'speaking'\n ? tr('healthybowl.assistant.voiceSession.speaking', 'Speaking — talk to interrupt')\n : muted\n ? tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')\n : tr('healthybowl.assistant.voiceSession.listening', 'Listening…');\n\n const status =\n error !== null\n ? errorMessage(error, tr)\n : muted && phase !== 'listening'\n ? `${phaseText} · ${tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')}`\n : phaseText;\n\n // While speaking, the caption shows the REPLY; otherwise what we have heard.\n // Showing the stale transcript under the assistant's own voice reads as a\n // mis-transcription of the assistant, which is worse than showing nothing.\n const caption = phase === 'speaking' ? spoken : spokenSoFar(session);\n\n return (\n <div\n ref={dialogRef}\n className={`flex flex-col items-center justify-between bg-bg-sunken ${\n expanded ? 'fixed inset-0 z-[60] px-6 py-10' : 'absolute inset-0 z-20 px-4 py-6'\n }`}\n role=\"dialog\"\n // Only modal when it really is: docked, the page behind stays usable.\n // `undefined` rather than `false` — the ARIA default is already false, and\n // some older assistive technology treats an explicit \"false\" on a dialog\n // as still modal.\n aria-modal={expanded || undefined}\n aria-label={tr('healthybowl.assistant.voiceSession.title', 'Voice conversation')}\n data-testid=\"assistant-voice-session\"\n >\n {/* The session's single live region. It has real words, unlike the orb. */}\n <p className=\"text-sm text-text-muted\" role=\"status\" aria-live=\"polite\" data-testid=\"assistant-voice-status\">\n {status}\n </p>\n\n <div className=\"flex flex-1 flex-col items-center justify-center gap-8\">\n <AssistantVoiceOrb session={session} compact={!expanded} />\n {caption ? (\n // Capped rather than scrolled: a long reply should not turn the\n // session into a wall of text the user reads instead of listens to.\n <p\n className=\"line-clamp-3 max-w-md text-center text-base leading-relaxed text-text-secondary\"\n data-testid=\"assistant-voice-caption\"\n >\n {caption}\n </p>\n ) : null}\n </div>\n\n <div className={`flex items-center ${expanded ? 'gap-6' : 'gap-4'}`}>\n <button\n type=\"button\"\n onClick={() => setExpanded((current) => !current)}\n className={`flex ${expanded ? 'size-14' : 'size-11'} items-center justify-center rounded-full bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n aria-pressed={expanded}\n aria-label={\n expanded\n ? tr('healthybowl.assistant.voiceSession.collapse', 'Fit the conversation back into the panel')\n : tr('healthybowl.assistant.voiceSession.expand', 'Expand the conversation to full screen')\n }\n data-testid=\"assistant-voice-expand\"\n >\n {expanded ? <Minimize2 className=\"size-5\" /> : <Maximize2 className=\"size-5\" />}\n </button>\n\n <button\n type=\"button\"\n onClick={onToggleMute}\n className={`flex ${expanded ? 'size-14' : 'size-11'} items-center justify-center rounded-full bg-bg-elevated text-text-primary transition-colors hover:bg-bg-raised focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n aria-pressed={muted}\n aria-label={\n muted\n ? tr('healthybowl.assistant.voiceSession.unmute', 'Turn the microphone on')\n : tr('healthybowl.assistant.voiceSession.mute', 'Turn the microphone off')\n }\n data-testid=\"assistant-voice-mute\"\n >\n {muted ? (\n <MicOff className={expanded ? 'size-6' : 'size-5'} />\n ) : (\n <Mic className={expanded ? 'size-6' : 'size-5'} />\n )}\n </button>\n\n <button\n ref={endRef}\n type=\"button\"\n onClick={onEnd}\n className={`flex ${expanded ? 'size-14' : 'size-11'} items-center justify-center rounded-full bg-action-danger-bg text-action-danger-text transition-colors hover:bg-action-danger-bg-hover focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n aria-label={tr('healthybowl.assistant.voiceSession.end', 'End the voice conversation')}\n data-testid=\"assistant-voice-end\"\n >\n <X className={expanded ? 'size-6' : 'size-5'} />\n </button>\n </div>\n </div>\n );\n};\n\n/**\n * Every failure is explained rather than silently closing the session.\n *\n * A session that just vanishes is the dead-button bug in another shape — the\n * exact defect BOFF-7106 had to fix on the per-message speak control.\n */\nfunction errorMessage(error: VoiceSessionError, tr: ReturnType<typeof useTr>): string {\n switch (error) {\n case 'mic-denied':\n return tr(\n 'healthybowl.assistant.voiceSession.micDenied',\n 'Microphone access is blocked. Allow it in your browser settings to talk.'\n );\n case 'no-speech-support':\n return tr(\n 'healthybowl.assistant.voiceSession.noSpeechSupport',\n 'This browser cannot listen. Try a different browser, or type instead.'\n );\n case 'no-voice-support':\n return tr(\n 'healthybowl.assistant.voiceSession.noVoiceSupport',\n 'This device has no voice that can speak this language.'\n );\n default: {\n // Exhaustive: adding a variant without copy becomes a build error rather\n // than a silently empty status line.\n const unhandled: never = error;\n return unhandled;\n }\n }\n}\n"],"mappings":";;;;;;;AAkCA,IAAa,KAAoC,EAAE,YAAS,WAAQ,iBAAc,eAAY;CAC5F,IAAM,IAAK,EAAM,GACX,EAAE,UAAO,UAAO,aAAU,GAC1B,IAAS,EAA0B,IAAI,GACvC,IAAY,EAAuB,IAAI,GAUvC,CAAC,GAAU,KAAe,EAAS,EAAK;CAc9C,AAJA,QAAgB;EACd,EAAO,SAAS,MAAM;CACxB,GAAG,CAAC,CAAC,GAEL,QAAgB;EACd,IAAM,KAAa,MAAyB;GAC1C,IAAI,EAAM,QAAQ,UAAU;IAC1B,EAAM;IACN;GACF;GAKA,IAAI,EAAM,QAAQ,SAAS,CAAC,GAAU;GAKtC,IAAM,IAAY,EAAU,SAAS,iBAA8B,wBAAwB;GAC3F,IAAI,CAAC,KAAa,EAAU,WAAW,GAAG;GAC1C,IAAM,IAAQ,EAAU,IAClB,IAAO,EAAU,EAAU,SAAS;GACt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,wCAAwC;MAE9F,eAAY;gBAEA,EAAX,IAAY,IAAmC,GAApC,EAAW,WAAU,SAAU,CAAmC;KACxE,CAAA;KAER,kBAAC,UAAD;MACE,MAAK;MACL,SAAS;MACT,WAAW,QAAQ,IAAW,YAAY,UAAU;MACpD,gBAAc;MACd,cACE,IACI,EAAG,6CAA6C,wBAAwB,IACxE,EAAG,2CAA2C,yBAAyB;MAE7E,eAAY;gBAGV,EADD,IACE,IAEA,GAFD,EAAQ,WAAW,IAAW,WAAW,SAAW,CAEH;KAE7C,CAAA;KAER,kBAAC,UAAD;MACE,KAAK;MACL,MAAK;MACL,SAAS;MACT,WAAW,QAAQ,IAAW,YAAY,UAAU;MACpD,cAAY,EAAG,0CAA0C,4BAA4B;MACrF,eAAY;gBAEZ,kBAAC,GAAD,EAAG,WAAW,IAAW,WAAW,SAAW,CAAA;KACzC,CAAA;IACL;;EACF;;AAET;AAQA,SAAS,EAAa,GAA0B,GAAsC;CACpF,QAAQ,GAAR;EACE,KAAK,cACH,OAAO,EACL,gDACA,0EACF;EACF,KAAK,qBACH,OAAO,EACL,sDACA,uEACF;EACF,KAAK,oBACH,OAAO,EACL,qDACA,wDACF;EACF,SAIE,OAAO;CAEX;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/microfe-healthybowl",
3
- "version": "2026.830.1",
3
+ "version": "2026.830.2",
4
4
  "description": "Burdenoff HealthyBowl Microfrontend - Comprehensive organic farming and agro-foods management platform",
5
5
  "type": "module",
6
6
  "files": [