@burdenoff/microfe-healthybowl 2026.904.18 → 2026.904.20

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.
@@ -37,19 +37,17 @@ import { jsx as D, jsxs as Fe } from "react/jsx-runtime";
37
37
  import { useGatewayClient as Ie } from "@burdenoff/fe-libs/shared/graphql";
38
38
  import { useAuthToken as Le } from "@burdenoff/fe-libs/shared/providers/shell";
39
39
  import { getAssistantMedia as O, useAssistantTr as Re } from "@burdenoff/fe-libs/shared/assistant";
40
+ import { sanitize as ze } from "@burdenoff/fe-libs/shared/assistant/progress";
40
41
  //#region src/components/assistant/AssistantChatArea.tsx
41
- var ze = {
42
+ var Be = {
42
43
  general: 18e4,
43
44
  assistant: 18e4,
44
45
  "api-calls": 18e4,
45
46
  "vibe-plugins": 6e5
46
- }, Be = 18e4, Ve = 2e4;
47
- function He() {
47
+ }, Ve = 18e4, He = 2e4;
48
+ function Ue() {
48
49
  return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
49
50
  }
50
- function Ue(e) {
51
- return e.replace(/(Authorization\s*:\s*Bearer\s+)[^\s\n]+/gi, "$1[REDACTED]").replace(/(X-Workspace-Authorization\s*:\s*Bearer\s+)[^\s\n]+/gi, "$1[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9._-]+\.[A-Za-z0-9._-]+\b/g, "[REDACTED_JWT]").replace(/\bsk-ant-[A-Za-z0-9-]+\b/g, "[REDACTED_API_KEY]");
52
- }
53
51
  function k(e) {
54
52
  return e.info?.time?.created ?? 0;
55
53
  }
@@ -154,7 +152,7 @@ var Ke = ({ visible: Ee = !0 }) => {
154
152
  userId: qe,
155
153
  organizationId: y()
156
154
  }, _ = {
157
- id: He(),
155
+ id: Ue(),
158
156
  role: "user",
159
157
  content: t,
160
158
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
@@ -164,7 +162,7 @@ var Ke = ({ visible: Ee = !0 }) => {
164
162
  }
165
163
  };
166
164
  L(p, _);
167
- let v = He();
165
+ let v = Ue();
168
166
  L(p, {
169
167
  id: v,
170
168
  role: "assistant",
@@ -176,7 +174,7 @@ var Ke = ({ visible: Ee = !0 }) => {
176
174
  }
177
175
  }), z(p, "provisioning", v, null);
178
176
  let te = (e, t, n, r, a = et) => {
179
- R(p, v, { content: Ue(e) }), at(p, v, {
177
+ R(p, v, { content: ze(e) }), at(p, v, {
180
178
  lang: a,
181
179
  ...t?.length ? { artifacts: t } : {},
182
180
  ...t?.length || n || r ? { mode: f } : {},
@@ -197,8 +195,8 @@ var Ke = ({ visible: Ee = !0 }) => {
197
195
  if (!_ || !xe(t)) throw t;
198
196
  await c(A, e, h, l, m, f, b, g, void 0), i ||= ne;
199
197
  }
200
- let x = We([], u), S = Date.now() + (ze[f] ?? Be), se = Date.now(), ce = Date.now();
201
- for (; Date.now() < S && (x = We(await o(A, e, h, l, g, 50, u), u), R(p, v, { content: Ue(x.content) }), x.pendingWrite && at(p, v, { pendingWrite: x.pendingWrite }), !x.done);) Date.now() - se > 3e4 && (await r(A, e, h, 600, g).catch(() => void 0), se = Date.now()), await new Promise((e) => setTimeout(e, Te(Date.now() - ce)));
198
+ let x = We([], u), S = Date.now() + (Be[f] ?? Ve), se = Date.now(), ce = Date.now();
199
+ for (; Date.now() < S && (x = We(await o(A, e, h, l, g, 50, u), u), R(p, v, { content: ze(x.content) }), x.pendingWrite && at(p, v, { pendingWrite: x.pendingWrite }), !x.done);) Date.now() - se > 3e4 && (await r(A, e, h, 600, g).catch(() => void 0), se = Date.now()), await new Promise((e) => setTimeout(e, Te(Date.now() - ce)));
202
200
  if (!x.done && f !== "vibe-plugins") throw Error("Assistant response timed out while streaming progress");
203
201
  let le = f === "vibe-plugins" ? await a(A, e, h, l, g).catch(() => []) : void 0;
204
202
  if (x.done || (x = {
@@ -312,7 +310,7 @@ var Ke = ({ visible: Ee = !0 }) => {
312
310
  return;
313
311
  }
314
312
  let r = Date.now(), i = window.setInterval(() => {
315
- Q.current.isBusy && Date.now() - r < Ve || (window.clearInterval(i), n());
313
+ Q.current.isBusy && Date.now() - r < He || (window.clearInterval(i), n());
316
314
  }, 200);
317
315
  }, []),
318
316
  latestReply: Et,
@@ -320,7 +318,7 @@ var Ke = ({ visible: Ee = !0 }) => {
320
318
  }), At = C(() => {
321
319
  let t = e.getState().activeConversationId;
322
320
  !t || X.length === 0 || (L(t, {
323
- id: He(),
321
+ id: Ue(),
324
322
  role: "system",
325
323
  content: Oe(X, {
326
324
  intro: O("voiceSession.continuedIntro", "Continued from a voice conversation. You asked about:"),
@@ -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 { resolveAssistantLanguage } from '@/config/assistantLanguages';\nimport { resolveLanguagePair } from '@/config/assistantLanguagePair';\nimport { AssistantMessageList } from './AssistantMessageList';\nimport { AssistantApiCallsConsentDialog } from './AssistantApiCallsConsentDialog';\nimport { AssistantEmptyState } from './AssistantEmptyState';\nimport { AssistantSpokenTurnsNotice } from './AssistantSpokenTurnsNotice';\nimport { VoiceTranscriptDrawer } from './voice/VoiceTranscriptDrawer';\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 { useWorkspaceWriteAccess } from '@/hooks/useWorkspaceWriteAccess';\nimport { useAssistantAttachments } from '@/hooks/useAssistantAttachments';\nimport { useConversationTurns } from '@/hooks/useConversationTurns';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport {\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 { getActorId, 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 getSendableAttachments,\n toMessageAttachment,\n type AssistantAttachment,\n} from '@/utils/assistantAttachments';\nimport { isMultimodalBodyRejection, isRecoverableAssistantError } from '@/utils/assistantTransportErrors';\nimport { isTurnInFlight } from '@/utils/assistantTurnState';\nimport { useAssistantTr } from '@burdenoff/fe-libs/shared/assistant';\nimport { ASSISTANT_MODES } from '@/types/assistant';\nimport type { AssistantArtifact, AssistantConversationStatus, AssistantMode, Message } from '@/types/assistant';\nimport { pollDelayMs } from '../../utils/assistantPollSchedule';\nimport { findPendingWrite, type PendingWrite } from '../../utils/pendingWrite';\nimport { toCaptionText } from '../../utils/captionText';\nimport {\n buildContinuedFromVoiceNote,\n buildVoiceTranscriptMarkdown,\n voiceTranscriptFilename,\n} from '../../utils/voiceTranscript';\nimport { downloadFile } from '@/services/assistantExportService';\nimport { isVoiceTurn, voiceMarker, voiceSessionIdOf } from '../../utils/voiceTurnVisibility';\nimport { createReadinessTracker } from '../../utils/sandboxReadiness';\n\n// How long the client streams progress before giving up on a turn. Chat replies\n// (general / api-calls) finish in seconds; a vibe-plugins build is a multi-step\n// pipeline (read docs → scaffold → bun install → bun build → checklist) that runs\n// for minutes, so it gets a much larger budget. The sandbox TTL is auto-extended\n// every 30s during the poll loop, so a longer budget never outlives the sandbox.\nconst STREAM_BUDGET_MS: Record<AssistantMode, number> = {\n general: 180_000,\n assistant: 180_000,\n 'api-calls': 180_000,\n 'vibe-plugins': 600_000,\n};\nconst DEFAULT_STREAM_BUDGET_MS = 180_000;\n\n/**\n * How long a spoken turn waits for its attachments to finish uploading.\n *\n * Long enough for a photo on a slow rural connection; short enough that a stuck\n * upload does not hold a question hostage. On timeout the turn goes without it\n * and the draft is cleared, so the miss is visible rather than deferred onto the\n * next question.\n */\nconst ATTACHMENT_SETTLE_TIMEOUT_MS = 20_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 /** A write the sandbox refused pending approval, if this turn produced one. */\n pendingWrite?: PendingWrite;\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 // ★ From the SAME message the content came from. Reaching for the last element\n // of `messages` instead is a second, different guess at which message this turn\n // produced — and on a session with trailing history it is the wrong one.\n const pendingWrite = findPendingWrite(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 // ★ Read from the SAME message the content came from. Picking the last\n // element of `messages` instead would be a second, different guess at which\n // message this turn produced — and on a session with trailing history it is\n // the wrong one.\n ...(pendingWrite ? { pendingWrite } : {}),\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 = useAssistantTr();\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 replyLanguage = useAssistantStore((state) => state.replyLanguage);\n const languagePair = useMemo(\n () => resolveLanguagePair(assistantLanguage, replyLanguage, locale),\n [assistantLanguage, replyLanguage, locale]\n );\n const replyLanguageName = languagePair.reply.english;\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 // ★ Whether a HUMAN picked this reply language or it was guessed from the\n // interface — true if EITHER field was pinned, since inheriting from a\n // deliberate input choice is still deliberate. `buildLanguagePreamble` uses it\n // to suppress the \"what they wrote in wins\" clause, which would otherwise make\n // the setting inert for everyone who types rather than dictates.\n const languageIsExplicit = languagePair.replyIsExplicit;\n const replyLanguageCode = languagePair.reply.code;\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 mergeMessageMetadata,\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 // ★ One place decides which turns belong to which surface. `messages` stays\n // available for questions about the CONVERSATION (is it used at all?), but it\n // is readonly, so it cannot reach a component that draws a message list.\n const turns = useConversationTurns(activeConversation);\n const messages = turns.all;\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 /**\n * ★ A SECOND, different question — and deliberately not a second gate.\n *\n * The check above asks whether this person may USE the write mode (org scope).\n * Writes then execute at WORKSPACE scope, where a separate decision is made,\n * so an org owner could plan a change, confirm it, and only then be refused.\n * This asks the execution question up front so the warning arrives before the\n * effort rather than after it.\n *\n * It does NOT hide or disable the mode. Measured against prod on 2026-09-02,\n * workspace scopes have no roles provisioned at all, so gating on this would\n * delete Take-action from the product until an ops task lands — a far worse\n * outcome than the confusion it would fix. It self-corrects with no code\n * change the moment roles exist.\n */\n const writeAccess = useWorkspaceWriteAccess(getActorId(), getWorkspaceId() || null);\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 // Read-only transcript, reachable when NO session is live. The drawer used to\n // be mounted only inside `AssistantVoiceSession`, so pressing End destroyed the\n // only way to read back what was said.\n const [transcriptOpen, setTranscriptOpen] = useState(false);\n\n // Full attachment payload of the last send, kept so Retry can replay it\n // byte-for-byte (see handleRetry).\n const lastSentAttachmentsRef = useRef<Record<string, AssistantAttachment[]>>({});\n\n // Conversations with a turn already dispatched. Synchronous, unlike the store\n // — see the re-entry guard in handleSend for why that matters.\n /**\n * Per-sandbox record of \"last proven reachable\", so a warm sandbox is not\n * re-probed on every turn. Invalidated by any failure — see both catches.\n */\n const sandboxReadiness = useRef(createReadinessTracker());\n const inFlightSendsRef = useRef<Set<string>>(new Set());\n\n // If the active mode is no longer permitted — a non-admin with a persisted\n // api-calls mode, or the master flag turned off — fall back to the read-only\n // `assistant` mode (the default \"Ask\", available to everyone), but only AFTER\n /** The config for the mode in play — read by the reset effect and by render. */\n const activeModeConfig = useMemo(() => ASSISTANT_MODES.find((modeConfig) => modeConfig.id === mode), [mode]);\n\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 blocked = !activeModeConfig || (activeModeConfig.requiresAdmin && !canUseApiCalls);\n if (blocked && mode !== 'assistant') {\n setMode('assistant');\n }\n }, [mode, activeModeConfig, canUseApiCalls, apiAccessLoading, setMode]);\n\n const updateConversationStage = useCallback(\n (conversationId: string, assistantMessageId: string, status: AssistantConversationStatus, content?: string) => {\n setConversationProcessing(conversationId, status, assistantMessageId, null);\n if (content) {\n updateMessage(conversationId, assistantMessageId, content);\n } else {\n updateMessage(conversationId, assistantMessageId, getConversationStatusMessage(status));\n }\n },\n [setConversationProcessing, updateMessage]\n );\n\n const ensureAssistantRuntime = useCallback(\n async (\n conversationId: string,\n assistantMessageId: string,\n currentMode: AssistantMode,\n workspaceId: string,\n authContext: AssistantSandboxAuthContext\n ): Promise<{ sandboxId: string; sessionId: string }> => {\n let currentSandboxId = useAssistantStore.getState().sandboxesByMode[currentMode]?.sandboxId ?? null;\n\n // Validate that a candidate sandbox (remembered locally or found running on\n // the server) is actually reachable before we reuse it. A sandbox can expire\n // (ttlSeconds) or have its backend pod reclaimed while still being briefly\n // reported RUNNING; proxying to such a dead pod fails with a terminal state\n // (\"Backend resource no longer exists\") or a permanent 502 cf-proxy timeout.\n // Returns true only when the in-sandbox agent responds; false means stale.\n const ensureSandboxReachable = async (candidateId: string): Promise<boolean> => {\n // ★ Skip a proof we already have. This ran two network waits before the\n // model saw the prompt on EVERY turn, including turns seconds after the\n // last one succeeded — a constant tax, felt most in voice where it sits\n // between the user finishing a sentence and hearing anything.\n //\n // Safe only because every failure path below invalidates: see the catch\n // here and the turn-level catch. A cache that were only ever written on\n // success would pin a dead sandbox and turn a recoverable error into a\n // loop.\n if (sandboxReadiness.current.isFresh(candidateId)) return true;\n try {\n await waitForSandboxReady(apollo, candidateId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, candidateId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n sandboxReadiness.current.markVerified(candidateId);\n return true;\n } catch {\n // Stale/expired sandbox — drop it so we provision a fresh one below\n // instead of surfacing \"Internal server error\" to the user.\n sandboxReadiness.current.invalidate(candidateId);\n return false;\n }\n };\n\n // 1) Try the locally-remembered sandbox, then 2) any running one on the\n // server. Each is only kept if it's actually reachable.\n if (currentSandboxId) {\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', 'Reusing assistant environment...');\n if (!(await ensureSandboxReachable(currentSandboxId))) {\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = null;\n }\n }\n\n if (!currentSandboxId) {\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Looking for existing environment...'\n );\n const existingId = await findExistingSandbox(apollo, workspaceId, currentMode, authContext);\n\n if (existingId) {\n setSandbox(currentMode, existingId, 'provisioning');\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Reusing assistant environment...'\n );\n if (await ensureSandboxReachable(existingId)) {\n currentSandboxId = existingId;\n } else {\n setSandbox(currentMode, null, 'provisioning');\n }\n }\n }\n\n // 3) No reusable, reachable sandbox — provision a fresh one.\n if (!currentSandboxId) {\n if (currentMode === 'api-calls' && !getAccessToken()) {\n throw new Error('API Calls mode requires an authenticated session. Please sign in again.');\n }\n\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Starting assistant environment...'\n );\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = await createAssistantSandbox(apollo, currentMode, workspaceId, authContext);\n\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n await waitForSandboxReady(apollo, currentSandboxId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, currentSandboxId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n }\n\n setSandbox(currentMode, currentSandboxId, 'running');\n\n let sessionId =\n useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n ?.backendSessionId ?? null;\n\n if (sessionId) {\n try {\n const session = await getAssistantSession(apollo, currentSandboxId, workspaceId, sessionId, authContext);\n if (session.mode !== currentMode) {\n throw new Error(`Session mode mismatch: expected ${currentMode}, received ${session.mode}`);\n }\n } catch {\n clearBackendSessionId(conversationId);\n sessionId = null;\n }\n }\n\n if (!sessionId) {\n updateConversationStage(conversationId, assistantMessageId, 'connecting', 'Preparing session...');\n const result = await createAssistantSession(apollo, currentSandboxId, workspaceId, currentMode, authContext);\n sessionId = result.sessionId;\n setBackendSessionId(conversationId, sessionId);\n }\n\n return {\n sandboxId: currentSandboxId,\n sessionId,\n };\n },\n [apollo, clearBackendSessionId, getAccessToken, setBackendSessionId, setSandbox, updateConversationStage]\n );\n\n const handleSend = useCallback(\n async (\n content: string,\n attachments: AssistantAttachment[] = [],\n // ★ The live voice session's id, present only when this turn was spoken.\n // It replaced a `dictated` boolean: two fields meaning almost the same\n // thing let a turn be marked spoken while recording no session, a state\n // with no meaning that only the transcript would ever notice.\n options: { voiceSessionId?: string } = {}\n ) => {\n // Spoken-ness is now DERIVED, so it cannot disagree with the session.\n const dictated = options.voiceSessionId !== undefined;\n // Only block re-entry while a turn is genuinely in-flight. Earlier code\n // checked for *any* entry in the map, which stuck around as `complete`\n // / `error` after the first turn — making every subsequent message\n // silently disappear (the input cleared but handleSend bailed before\n // adding the user message to the conversation).\n //\n // The store is read LIVE, and that is what makes the guard work. The\n // render-captured `processingByConversationId` is stale by construction —\n // the click that starts a turn and the click that must be rejected can\n // belong to the same render. Reading `activeConversationId` live matters\n // for the same reason: on two racing first-ever sends, the second must see\n // the conversation the first one created a moment ago.\n //\n // Pairs with the synchronous `setConversationProcessing` below: because\n // the status is written before this function ever awaits, a second call —\n // however soon it arrives — always observes 'provisioning'.\n const storeAtEntry = useAssistantStore.getState();\n const guardConversationId = storeAtEntry.activeConversationId ?? activeConversationId;\n if (guardConversationId) {\n if (isTurnInFlight(storeAtEntry.processingByConversationId[guardConversationId]?.status)) return;\n // Second lock, in case a future change moves the status write later:\n // this one cannot be cleared by anything but the turn's own `finally`.\n // Deliberately per-conversation — a global key would keep blocking\n // after the conversation it belonged to was deleted mid-turn, and then\n // silently swallow every subsequent send.\n if (inFlightSendsRef.current.has(guardConversationId)) return;\n }\n\n const selectedMode = storeAtEntry.mode;\n let conversationId = activeConversationId;\n const currentConversation = conversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n : undefined;\n\n if (!conversationId) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (\n currentConversation &&\n currentConversation.mode !== selectedMode &&\n (currentConversation.messages.length > 0 || currentConversation.backendSessionId)\n ) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (currentConversation && currentConversation.mode !== selectedMode) {\n setConversationMode(conversationId, selectedMode);\n }\n\n if (!conversationId) return;\n\n // Keyed by conversation: the ref outlives a conversation switch, and a\n // single global slot meant Retry in one thread replayed another thread's\n // photo onto it.\n lastSentAttachmentsRef.current[conversationId] = attachments;\n\n const workspaceId = getWorkspaceId();\n const authContext: AssistantSandboxAuthContext = {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n };\n\n const userMessage: Message = {\n id: generateId(),\n role: 'user',\n content,\n timestamp: new Date().toISOString(),\n // Slim descriptors only — the bubble re-resolves thumbnails from the\n // file id, so the persisted conversation stays small.\n // ★ `voice` marks a turn that happened in the live voice session, so the\n // chat panel can leave it out. Both surfaces share one conversation, so\n // without it every spoken exchange showed up in the typed thread.\n metadata: {\n ...(attachments.length ? { attachments: attachments.map(toMessageAttachment) } : {}),\n ...voiceMarker(options.voiceSessionId),\n },\n };\n addMessage(conversationId, userMessage);\n\n const assistantMessageId = generateId();\n addMessage(conversationId, {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n timestamp: new Date().toISOString(),\n // Stamped now, not read later: this is the language the reply is being\n // generated in, and the preference may have moved on by the time\n // somebody presses Listen.\n // Carries the voice marker too: a reply to a spoken question belongs to\n // the voice session, not to the typed thread.\n metadata: { lang: replyLanguageCode, ...voiceMarker(options.voiceSessionId) },\n });\n\n // Mark the turn in-flight in the STORE right now, synchronously.\n //\n // Until this line the first status write happened inside\n // `ensureAssistantRuntime`, i.e. one await later. During that window\n // `activeIsProcessing` was false and `failedMessageId` still pointed at\n // the PREVIOUS failure — so the composer stayed enabled and, worse, the\n // Retry button (which has no `disabled` of its own) stayed mounted and\n // clickable on top of a turn that had already started.\n //\n // Status only, deliberately no stage copy: `ensureAssistantRuntime` picks\n // the accurate wording a moment later (\"Reusing...\" vs \"Starting...\"), and\n // guessing here would flash the wrong one on every reused sandbox.\n setConversationProcessing(conversationId, 'provisioning', assistantMessageId, null);\n\n const applyAssistantResponse = (\n response: string,\n artifacts?: AssistantArtifact[],\n sessionId?: string,\n sandboxId?: string,\n // Our own hard-coded copy is English regardless of what the user picked.\n // Stamping it with their language makes playback read an English quota\n // message in a Tamil voice — Latin text cannot be script-detected, so\n // this metadata is trusted absolutely.\n lang: string = replyLanguageCode\n ) => {\n // `patchMessage` REPLACES metadata rather than merging it, so anything\n // omitted here is destroyed — which is how the turn-language stamp set\n // at creation was being wiped the moment the response completed,\n // silently undoing per-message language resolution. Always re-assert it.\n //\n // ★ The voice marker was being lost the same way, and it was worse: this\n // runs on every completed turn, and the reply is only handed to the voice\n // session AFTER it runs, so NO spoken answer could ever stay a voice\n // turn. Each one jumped into the typed thread — under a question that\n // had been correctly hidden, so chat showed orphaned answers — and\n // vanished from the transcript drawer at the same instant.\n // ★ TWO calls, and the split is the point. `patchMessage` REPLACES\n // `metadata`, so rebuilding the object here silently drops every key the\n // turn added along the way. That is not hypothetical: it destroyed the\n // voice marker once (see above), and it then destroyed `pendingWrite` —\n // the poll loop recorded the refused write moments earlier and this line\n // wiped it before the card could ever render, shipping a feature that was\n // inert in production.\n //\n // Re-asserting each marker by hand is what failed twice. Merging cannot\n // fail that way: keys this turn set stay set, and the ones below still\n // win where they overlap.\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n });\n mergeMessageMetadata(conversationId, assistantMessageId, {\n lang,\n ...(artifacts?.length ? { artifacts } : {}),\n ...(artifacts?.length || sessionId || sandboxId ? { mode: selectedMode } : {}),\n ...(sessionId ? { sessionId } : {}),\n ...(sandboxId ? { sandboxId } : {}),\n ...voiceMarker(options.voiceSessionId),\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 // ★★ There is deliberately NO pre-flight AI-credit gate here.\n //\n // This block used to call `checkAssistantAiCredits` inside a try/catch\n // that surfaced the upgrade dialog on a 429 QUOTA_EXHAUSTED. The catch\n // could never run: `services/assistantApi.checkAssistantAiCredits` is a\n // documented no-op returning `Promise.resolve(true)`, so it cannot\n // reject. Thirty-four lines of code and prose described a live quota\n // gate that was structurally unreachable — the most expensive kind of\n // comment, because the next person reads it and believes HealthyBowl\n // gates on credits.\n //\n // The no-op is the RIGHT product decision, not an oversight: HB is\n // metered per input token against a Free allowance of 500, so a real\n // pre-flight gate would refuse ordinary chats. It is recorded in the\n // api adapter, where the decision belongs.\n //\n // The budget IS still enforced, downstream and for real: the wspace\n // gateway's @usage(checkQuota) on createSandbox rejects an over-quota\n // caller with a 429, and the outer catch below turns that into the\n // upgrade dialog. That path is live and reachable.\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 dictated\n );\n // Structured multimodal parts carry the image PIXELS, which no amount\n // of prompt text can. Built from the same `promptText`, so a bridge\n // that ignores `parts` loses nothing; `undefined` for an ordinary text\n // turn keeps the wire body unchanged.\n const promptParts = buildPromptParts(promptText, attachments);\n const inlinedCount = countInlinedImageParts(promptParts);\n const carriesPixels = inlinedCount > 0;\n const pageContext = gatherPageContext();\n\n // `buildPromptParts` may have demoted a photo to a link to keep the\n // body under the gateway's cap — a long message can do that on prompt\n // text alone. That decision is invisible to the user unless we say so,\n // and an answer that reads as if the model looked at a photo it never\n // received is worse than a short note.\n imagesDropped = countInlineImageCandidates(attachments) > inlinedCount;\n\n try {\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n promptParts\n );\n } catch (sendError) {\n // `buildPromptParts` already sizes the PARTS to the gateway's cap\n // (the prompt string itself is not bounded here), so reaching this\n // point means something rejected the body anyway — a tighter proxy\n // than we modelled, or a bridge that will not take `parts` at all.\n // Losing the whole question over that is the worst outcome\n // available: re-send it text-only. Only for errors that provably\n // never reached the agent (see isMultimodalBodyRejection) — a blind\n // retry would ask the same question twice and bill it twice.\n //\n // Gated on `parts` existing at all, NOT on it carrying pixels: the\n // array duplicates the whole prompt in `parts[0]`, so a url-only\n // parts array is itself enough to push a long message over the cap.\n // `carriesPixels` only decides whether the user is told something\n // was lost.\n if (!promptParts || !isMultimodalBodyRejection(sendError)) throw sendError;\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n undefined\n );\n // Only claim a photo was lost if one actually was — a url-only\n // retry loses nothing the prompt block did not already carry.\n imagesDropped = imagesDropped || carriesPixels;\n }\n\n let result = buildAssistantProgress([], priorNewestCreatedMs);\n const timeoutAt = Date.now() + (STREAM_BUDGET_MS[selectedMode] ?? DEFAULT_STREAM_BUDGET_MS);\n let lastTtlExtensionAt = Date.now();\n\n const pollStartedAt = Date.now();\n while (Date.now() < timeoutAt) {\n // ★ Delta poll. `priorNewestCreatedMs` is fixed for the whole turn and\n // is already the floor `buildAssistantProgress` filters on (`>`), so\n // asking the agent for `>=` the same value returns exactly the window\n // that function keeps — and nothing else. The result is identical; what\n // changes is that this stops re-downloading 50 full messages, plus the\n // injected page context, every 600-1500ms for the length of a turn.\n //\n // No merge or high-water bookkeeping is needed precisely BECAUSE the\n // floor is constant and progress is recomputed from scratch each poll.\n // A cursor that advanced would break `done` detection, since the\n // in-flight message would drop out of its own window.\n const sessionMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50,\n priorNewestCreatedMs\n );\n\n result = buildAssistantProgress(sessionMessages, priorNewestCreatedMs);\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(result.content),\n });\n\n // ★ The write the agent REFUSED, taken from its own tool result.\n // Without this the user approves the model's PARAGRAPH about the\n // change — written by the same model that wants the write to go\n // through, and reconciled against the payload by nothing.\n //\n // `mergeMessageMetadata`, never `patchMessage`: the latter REPLACES\n // metadata, and this message already carries `lang` and may carry the\n // voice marker. That exact mistake has shipped here before.\n if (result.pendingWrite) {\n mergeMessageMetadata(conversationId, assistantMessageId, { pendingWrite: result.pendingWrite });\n }\n\n if (result.done) break;\n\n if (Date.now() - lastTtlExtensionAt > 30_000) {\n await extendAssistantSandboxTTL(apollo, sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n // Fast early, backing off after — see assistantPollSchedule. This is\n // the granularity of the whole turn: it bounds how late the answer\n // appears AND how late speech can start, because auto-speak only\n // fires once a poll observes the reply completed.\n await new Promise((resolve) => setTimeout(resolve, pollDelayMs(Date.now() - pollStartedAt)));\n }\n\n // For non-build modes a timeout is a hard failure. For vibe-plugins the\n // prompt runs async server-side (/sessions/:id/prompt-async) and keeps\n // writing artifacts after the poll budget elapses, so we surface whatever\n // it has produced instead of discarding the turn.\n if (!result.done && selectedMode !== 'vibe-plugins') {\n throw new Error('Assistant response timed out while streaming progress');\n }\n\n const artifacts =\n selectedMode === 'vibe-plugins'\n ? await getAssistantArtifacts(apollo, sandboxId, workspaceId, sessionId, authContext).catch(() => [])\n : undefined;\n\n if (!result.done) {\n // vibe-plugins build still running in the background. Append a note so\n // the user knows the answer is partial and the artifacts will finish.\n result = {\n ...result,\n content: `${result.content}\\n\\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`,\n };\n }\n\n if (imagesDropped) {\n // Said plainly, because the alternative is an answer that looks like\n // it examined a photo it never received.\n result = {\n ...result,\n content: `${result.content}\\n\\n${tr(\n 'attachments.imagesNotSent',\n '_Your photo was too large to include with this message, so the answer above is from the text and the file link only. Try a smaller or more tightly cropped photo._'\n )}`,\n };\n }\n\n applyAssistantResponse(result.content, artifacts, sessionId, sandboxId);\n\n if (result.tokens) {\n patchMessage(conversationId, assistantMessageId, { tokens: result.tokens });\n // Charge the real token usage against the AI-credits quota (the\n // gateway records it via @usage(trackUsage)). We AWAIT it before\n // marking the turn complete / re-enabling input: otherwise a rapid\n // follow-up send would run its pre-flight checkAiCredits against a\n // stale balance (this turn's charge still in flight) and could\n // dispatch a prompt that should have been blocked, letting fast\n // sends bypass the credit cap. Still best-effort — a charge failure\n // never blocks the displayed answer.\n try {\n await reportAssistantAiTokenUsage(apollo, workspaceId, sessionId, result.tokens, authContext);\n notifyAiCreditsUpdated();\n } catch {\n // ignore — server-side @usage tracking is the source of truth\n }\n }\n setConversationProcessing(conversationId, 'complete', assistantMessageId, null);\n } catch (error) {\n if (attempt === 1 && isRecoverableAssistantError(error)) {\n clearBackendSessionId(conversationId);\n clearSandbox(selectedMode);\n return sendWithRealBackend(2);\n }\n\n throw error;\n }\n };\n\n // Claim the slot immediately before the first await, and release it in\n // `finally` so every exit — success, quota return, thrown error — frees\n // it. Registering here rather than earlier means a synchronous throw in\n // the setup above can never strand a key and wedge the conversation.\n const turnConversationId = conversationId;\n inFlightSendsRef.current.add(turnConversationId);\n\n try {\n if (!workspaceId) {\n throw new Error('Assistant backend is unavailable without an active workspace context.');\n }\n await sendWithRealBackend();\n } catch (error) {\n // ★ Any failed turn drops the readiness proof for the sandbox it used,\n // so the NEXT turn re-probes instead of trusting a cache entry that a\n // dead pod would otherwise keep alive until the TTL lapsed. This is the\n // half that makes the short-circuit above safe.\n sandboxReadiness.current.invalidate(\n useAssistantStore.getState().sandboxesByMode[selectedMode]?.sandboxId ?? null\n );\n // A quota error reaching here is the sandbox-environment wall hit\n // during runtime provisioning (createSandbox @usage). Surface the\n // upgrade dialog instead of a generic failure (the AI-credit wall is\n // already handled by the pre-flight gate above).\n if (isQuotaExhaustedError(error)) {\n dispatchAssistantQuotaExhausted('sandbox');\n applyAssistantResponse(\n \"You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.\",\n undefined,\n undefined,\n undefined,\n 'en'\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n const errorMessage = error instanceof Error ? error.message : 'Something went wrong';\n setConversationProcessing(conversationId, 'error', assistantMessageId, errorMessage);\n // Same reason: English copy must not inherit the turn's language stamp.\n // The voice marker still has to survive though — a failed spoken turn\n // belongs to the session that asked. Without it the failure surfaced as\n // a bare \"Sorry, an error occurred\" in the typed thread with no question\n // above it, while the voice session showed nothing at all.\n // Same split as the success path, and for the same reason: rebuilding\n // `metadata` here would erase a `pendingWrite` recorded moments earlier,\n // so a turn that failed AFTER the agent refused a write would lose the\n // record of what it had been about to do.\n patchMessage(conversationId, assistantMessageId, {\n content: `Sorry, an error occurred: ${errorMessage}. Please try again.`,\n });\n mergeMessageMetadata(conversationId, assistantMessageId, {\n lang: 'en',\n ...voiceMarker(options.voiceSessionId),\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 // ★ Search the TYPED thread, not the raw array. Retry is a chat-panel\n // affordance, so on a conversation whose last turn was spoken this picked up\n // the spoken prompt and re-sent it WITHOUT `dictated` — quietly converting a\n // voice turn into a chat turn and undoing the separation everywhere else.\n const lastUserMessage = [...turns.chat].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 // ★ SPOKEN replies only. Both consumers of this value are the voice\n // session — the caption it paints and the reply it advances on — so\n // scanning the raw array let a TYPED reply that happened to complete\n // during a live session be captioned and read aloud as the answer to a\n // spoken question. Reachable without the user typing anything: a host\n // page queues work through `pendingPrompt`, which is store-driven and so\n // fires straight past the overlay.\n //\n // `start`'s id-claim was the only thing holding this shut, and it covers\n // just the reply that existed when the session opened — not one that\n // arrives mid-session.\n if (!isVoiceTurn(message)) continue;\n // Tool-activity markup is stripped so the session captions and speaks the\n // answer, not the machinery that produced it.\n const text = parseToolActivity(message.content).text.trim();\n return text ? { id: message.id, text } : null;\n }\n return null;\n }, [messages, activeIsProcessing]);\n\n /**\n * The same reply, with its Markdown markers removed, for the on-screen caption.\n *\n * ★ Deliberately a SEPARATE memo rather than a change to the one above, whose\n * `text` is not just display: it is the echo reference the recogniser compares\n * against while the answer is being spoken, and the payload of the session's\n * `reply` dispatch. Stripping it there would silently shift what counts as an\n * echo of our own voice. The audio path keeps its own transform\n * (`toSpeakableText`) — the two want genuinely different output, which is why\n * they are two functions and not one.\n */\n const voiceCaption = useMemo(\n () => (latestAssistantReply ? toCaptionText(latestAssistantReply.text) : null),\n [latestAssistantReply]\n );\n\n /**\n * The last few exchanges, for the session's on-screen transcript.\n *\n * Voice turns already go through the normal send path, so they are ordinary\n * conversation messages — this only surfaces them INSIDE the session, which\n * is what makes a second question in the same session make sense.\n */\n /**\n * What the CHAT panel shows: everything that was not spoken.\n *\n * Voice and chat share one conversation, so without this split every spoken\n * exchange appeared in the typed thread.\n */\n const chatMessages = turns.chat;\n\n const voiceTurns = useMemo(\n () =>\n // ★ SPOKEN turns only — but this conversation's, not this session's.\n //\n // It used to take the last six messages of the WHOLE conversation, so\n // opening voice on an existing thread painted typed replies: the wall of\n // raw `##` and `**` in the operator's screenshot, because the voice panel\n // renders plain text. Filtering by channel fixed that.\n //\n // What it does NOT do is scope to the current session, and two comments\n // used to claim it did. `metadata.voice` is a boolean, so a second voice\n // session sees the first one's turns. Showing the conversation's whole\n // spoken history is the more useful of the two behaviours, so the wording\n // is what changed — but a genuine session scope needs a session id on the\n // message, not a flag.\n turns.voice\n .filter((message) => message.role === 'user' || message.role === 'assistant')\n .map((message) => ({\n id: message.id,\n role: message.role as 'user' | 'assistant',\n text: parseToolActivity(message.content).text.trim(),\n // Which spoken exchange this belongs to, so the transcript can show\n // where one ended and the next began. `undefined` for turns recorded\n // before session ids existed — real history, just unattributed.\n sessionId: voiceSessionIdOf(message),\n timestamp: message.timestamp,\n }))\n .filter((turn) => turn.text.length > 0),\n [turns.voice]\n );\n\n const handleSaveTranscript = useCallback(() => {\n if (voiceTurns.length === 0) return;\n const now = new Date();\n downloadFile(\n buildVoiceTranscriptMarkdown(\n voiceTurns,\n {\n title: tr('voiceSession.transcript', 'Voice conversation'),\n savedAt: tr('voiceSession.savedAt', 'Saved'),\n session: tr('voiceSession.sessionLabel', 'Session'),\n earlier: tr('voiceSession.earlierLabel', 'Earlier'),\n you: tr('voiceSession.speakerYou', 'You'),\n assistant: tr('voiceSession.speakerAssistant', 'Assistant'),\n },\n now\n ),\n voiceTranscriptFilename(now),\n 'text/markdown'\n );\n }, [voiceTurns, tr]);\n\n /**\n * The attachment draft for the VOICE surface.\n *\n * ★ Its own instance, not the composer's. A photo taken during a spoken\n * exchange belongs to the question about to be asked aloud — not to whatever\n * half-typed message is sitting in the text box behind the overlay, and not\n * the other way round either. Two drafts, two surfaces, same rule as the turns\n * themselves.\n */\n const voiceAttachments = useAssistantAttachments();\n // A ref so `submitVoiceTurn` keeps its stable identity — `useVoiceSession`\n // deliberately does not depend on `onSubmit`, and the same idiom is already\n // used for `handleSendRef` just below.\n const voiceAttachmentsRef = useRef(voiceAttachments);\n voiceAttachmentsRef.current = voiceAttachments;\n\n const submitVoiceTurn = useCallback((text: string, voiceSessionId: string) => {\n // ★ Only the voice SESSION is unambiguously dictated. The composer's\n // microphone also produces a transcript, but the user reads and edits it in\n // the box before sending, so treating that as dictated would tell the model\n // to second-guess words the user had already approved.\n // ★★ WAIT for uploads to settle before sending.\n //\n // The composer can disable its send button while an upload runs\n // (`sendBlocker`). Voice has no button — the turn fires on a silence timer —\n // so without this a photo that is still uploading is simply absent from the\n // question it belongs to, and the assistant answers about a leaf it was never\n // shown. Worse, the upload then finishes and the photo attaches itself to the\n // NEXT, unrelated spoken question.\n //\n // Deferring is the direct analogue of grey-ing out the send button: the turn\n // goes when its attachments are ready.\n const send = () => {\n const draft = voiceAttachmentsRef.current;\n const ready = getSendableAttachments(draft.attachments);\n void handleSendRef.current(text, ready, { voiceSessionId });\n // ★ ALWAYS clear, even when nothing was ready. A leftover attachment does\n // not wait politely for a related question — it rides whatever is asked\n // next. Dropping it is visible (the chip disappears); carrying it forward\n // is not.\n draft.clear();\n };\n\n if (!voiceAttachmentsRef.current.isBusy) {\n send();\n return;\n }\n\n // Polled rather than awaited: the hook exposes `isBusy`, not a promise, and\n // the alternative is threading upload plumbing through the voice session for\n // one caller. Capped, because a cold files service retries for ~51s and a\n // spoken question must not hang on it indefinitely.\n const startedAt = Date.now();\n const poll = window.setInterval(() => {\n const stillBusy = voiceAttachmentsRef.current.isBusy;\n if (stillBusy && Date.now() - startedAt < ATTACHMENT_SETTLE_TIMEOUT_MS) return;\n window.clearInterval(poll);\n send();\n }, 200);\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 /**\n * End the spoken exchange and leave a record of it in the typed thread.\n *\n * ★ The note tells the MODEL nothing, and does not need to: the client sends\n * no history, so the shared backend session already holds every spoken turn.\n * It exists so the HUMAN can see in the thread what was discussed — without\n * it the conversation continues against a page that looks empty.\n *\n * ★ Written as `role: 'system'`, which renders as a centred note. As a user\n * turn it would claim they typed it; as an assistant turn it would claim the\n * model said it. It is neither.\n */\n const handleContinueInChat = useCallback(() => {\n const conversationId = useAssistantStore.getState().activeConversationId;\n if (!conversationId || voiceTurns.length === 0) return;\n\n addMessage(conversationId, {\n id: generateId(),\n role: 'system',\n content: buildContinuedFromVoiceNote(voiceTurns, {\n intro: tr('voiceSession.continuedIntro', 'Continued from a voice conversation. You asked about:'),\n nothing: tr('voiceSession.continuedNothing', 'Continued from a voice conversation.'),\n more: (count) => tr('voiceSession.continuedMore', '…and {{count}} more', { count }),\n }),\n timestamp: new Date().toISOString(),\n // ★ No voice marker: the note belongs to the TYPED thread. That is the\n // whole point of the action — marking it would hide it in the surface the\n // user is leaving.\n });\n\n setTranscriptOpen(false);\n voiceSession.end();\n }, [voiceTurns, addMessage, tr]);\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 /**\n * A photo attached but never spoken does not outlive the session.\n *\n * ★ Otherwise it waits, invisibly, for the NEXT voice conversation and rides\n * along with whatever is asked then — a picture of last week's leaf answering\n * this week's question. Same rule as the turns themselves: a voice draft\n * belongs to the exchange that produced it.\n */\n useEffect(() => {\n if (voiceSession.active) return;\n // ★ UNCONDITIONAL. Guarding on `attachments.length > 0` looked like avoiding\n // pointless work and instead created the exact leak this effect prevents: a\n // photo still inside `prepareFile` (a 12MP downscale takes real time) has no\n // row yet, so the list is empty, so `clear()` was skipped — and `clear()` is\n // the only thing that bumps the epoch that cancels an in-flight prepare. The\n // file then landed in the draft AFTER its session ended and rode the next\n // one. Clearing an already-empty draft costs nothing.\n voiceAttachmentsRef.current.clear();\n }, [voiceSession.active]);\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 {/* ★ Says out loud that this thread is not showing everything the\n assistant remembers. Both surfaces share one backend session, so a\n spoken turn stays in the model's context whether or not it is drawn\n here — silence about that is what produces a reply referring to\n something the user cannot see. Hidden during a live session, where\n the overlay already IS the voice surface. */}\n {voiceTurns.length > 0 && !voiceSession.active ? (\n <AssistantSpokenTurnsNotice count={voiceTurns.length} onOpenTranscript={() => setTranscriptOpen(true)} />\n ) : null}\n\n {/* Transcript is always visible now — the old collapse-by-default accordion\n is gone; conversation history lives behind the header button instead. */}\n {chatMessages.length === 0 ? (\n <AssistantEmptyState mode={mode} onSuggestionClick={handleSuggestionClick} />\n ) : (\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <AssistantMessageList\n messages={chatMessages}\n streamingMessageId={activeStreamingMessageId}\n failedMessageId={failedMessageId}\n onRetry={handleRetry}\n />\n </div>\n )}\n\n <AssistantComposer\n // ★ Ask-mode only, and enforced here rather than merely documented.\n // In `api-calls` mode the assistant WRITES to farm data behind a consent\n // gate, and BOFF-6377 (\"confirm-before-write cannot prove a human\n // approved\") is still open — a spoken \"yes, do it\" is exactly the case\n // that ticket is about. Voice control of writes is the NEXT phase, not\n // this one, so the launcher is simply absent in that mode.\n onStartVoiceSession={voiceSession.available && mode !== 'api-calls' ? voiceSession.start : undefined}\n onSend={(value, attachments) => void handleSend(value, attachments)}\n disabled={activeIsProcessing}\n placeholder={\n mode === 'api-calls'\n ? tr('chatArea.placeholderActions', 'What would you like me to do?')\n : tr('chatArea.placeholderGeneral', 'Ask HealthyBowl anything…')\n }\n mode={mode}\n writeAccessDenied={writeAccess === 'denied' && Boolean(activeModeConfig?.writeCapable)}\n availableModes={availableModes}\n onModeChange={handleModeChange}\n />\n </div>\n\n {/* Read-only, and only when no session is live — a live session mounts its\n own copy inside the overlay. Same component either way, so the two can\n never drift apart. */}\n {transcriptOpen && !voiceSession.active ? (\n <VoiceTranscriptDrawer\n turns={voiceTurns}\n onClose={() => setTranscriptOpen(false)}\n onSave={handleSaveTranscript}\n // No \"continue in chat\" here: this mount opens FROM the chat panel, so\n // the user is already where that button would take them.\n />\n ) : null}\n\n {voiceSession.active && (\n <AssistantVoiceSession\n session={voiceSession.session}\n notice={voiceSession.notice}\n capturing={voiceSession.capturing}\n interrupting={voiceSession.interrupting}\n awaitingEndpoint={voiceSession.awaitingEndpoint}\n turns={voiceTurns}\n spokenChunks={voiceSession.spokenChunks}\n attachments={voiceAttachments.attachments}\n onAttachFiles={voiceAttachments.addFiles}\n onRemoveAttachment={voiceAttachments.remove}\n onRetryAttachment={voiceAttachments.retry}\n canAttachMore={voiceAttachments.canAddMore}\n preparingAttachments={voiceAttachments.preparingCount}\n onSaveTranscript={handleSaveTranscript}\n onContinueInChat={handleContinueInChat}\n onInterrupt={voiceSession.interrupt}\n spoken={voiceCaption}\n onToggleMute={voiceSession.toggleMute}\n onEnd={voiceSession.end}\n />\n )}\n\n <AssistantApiCallsConsentDialog\n open={pendingConsentMode !== null}\n onConfirm={handleConsentConfirm}\n onCancel={handleConsentCancel}\n />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwEA,IAAM,KAAkD;CACtD,SAAS;CACT,WAAW;CACX,aAAa;CACb,gBAAgB;AAClB,GACM,KAA2B,MAU3B,KAA+B;AAErC,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,GAOA;CACA,IAAM,IAAW,EACd,QAAQ,MAAY,EAAQ,MAAM,SAAS,eAAe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,+BAA+B,+BAA+B,IACjE,EAAG,+BAA+B,2BAA2B;MAE7D;MACN,mBAAmB,OAAgB,YAAY,EAAQ,IAAkB;MACzD;MAChB,cAAc;KACf,CAAA;IACE;;GAKJ,MAAkB,CAAC,EAAa,SAC/B,kBAAC,GAAD;IACE,OAAO;IACP,eAAe,GAAkB,EAAK;IACtC,QAAQ;GAGT,CAAA,IACC;GAEH,EAAa,UACZ,kBAAC,IAAD;IACE,SAAS,EAAa;IACtB,QAAQ,EAAa;IACrB,WAAW,EAAa;IACxB,cAAc,EAAa;IAC3B,kBAAkB,EAAa;IAC/B,OAAO;IACP,cAAc,EAAa;IAC3B,aAAa,EAAiB;IAC9B,eAAe,EAAiB;IAChC,oBAAoB,EAAiB;IACrC,mBAAmB,EAAiB;IACpC,eAAe,EAAiB;IAChC,sBAAsB,EAAiB;IACvC,kBAAkB;IAClB,kBAAkB;IAClB,aAAa,EAAa;IAC1B,QAAQ;IACR,cAAc,EAAa;IAC3B,OAAO,EAAa;GACrB,CAAA;GAGH,kBAAC,GAAD;IACE,MAAM,OAAuB;IAC7B,WAAW;IACX,UAAU;GACX,CAAA;EACE;;AAET"}
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 { resolveAssistantLanguage } from '@/config/assistantLanguages';\nimport { resolveLanguagePair } from '@/config/assistantLanguagePair';\nimport { AssistantMessageList } from './AssistantMessageList';\nimport { AssistantApiCallsConsentDialog } from './AssistantApiCallsConsentDialog';\nimport { AssistantEmptyState } from './AssistantEmptyState';\nimport { AssistantSpokenTurnsNotice } from './AssistantSpokenTurnsNotice';\nimport { VoiceTranscriptDrawer } from './voice/VoiceTranscriptDrawer';\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 { useWorkspaceWriteAccess } from '@/hooks/useWorkspaceWriteAccess';\nimport { useAssistantAttachments } from '@/hooks/useAssistantAttachments';\nimport { useConversationTurns } from '@/hooks/useConversationTurns';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport {\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 { getActorId, 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 getSendableAttachments,\n toMessageAttachment,\n type AssistantAttachment,\n} from '@/utils/assistantAttachments';\nimport { isMultimodalBodyRejection, isRecoverableAssistantError } from '@/utils/assistantTransportErrors';\nimport { isTurnInFlight } from '@/utils/assistantTurnState';\nimport { useAssistantTr } from '@burdenoff/fe-libs/shared/assistant';\nimport { ASSISTANT_MODES } from '@/types/assistant';\nimport type { AssistantArtifact, AssistantConversationStatus, AssistantMode, Message } from '@/types/assistant';\nimport { pollDelayMs } from '../../utils/assistantPollSchedule';\nimport { findPendingWrite, type PendingWrite } from '../../utils/pendingWrite';\nimport { toCaptionText } from '../../utils/captionText';\nimport {\n buildContinuedFromVoiceNote,\n buildVoiceTranscriptMarkdown,\n voiceTranscriptFilename,\n} from '../../utils/voiceTranscript';\nimport { downloadFile } from '@/services/assistantExportService';\nimport { isVoiceTurn, voiceMarker, voiceSessionIdOf } from '../../utils/voiceTurnVisibility';\nimport { createReadinessTracker } from '../../utils/sandboxReadiness';\n// ★★ The SHARED credential redactor, not a local copy. The two were byte-identical:\n// the same four patterns stripping Bearer tokens, JWTs and `sk-ant-` keys from model\n// output before it renders. A redactor duplicated across repos is the worst kind of\n// duplicate — add a fifth pattern to one and the other keeps leaking, with nothing\n// failing to say so.\nimport { sanitize as sanitizeAssistantResponse } from '@burdenoff/fe-libs/shared/assistant/progress';\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\n/**\n * How long a spoken turn waits for its attachments to finish uploading.\n *\n * Long enough for a photo on a slow rural connection; short enough that a stuck\n * upload does not hold a question hostage. On timeout the turn goes without it\n * and the draft is cleared, so the miss is visible rather than deferred onto the\n * next question.\n */\nconst ATTACHMENT_SETTLE_TIMEOUT_MS = 20_000;\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\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 /** A write the sandbox refused pending approval, if this turn produced one. */\n pendingWrite?: PendingWrite;\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 // ★ From the SAME message the content came from. Reaching for the last element\n // of `messages` instead is a second, different guess at which message this turn\n // produced — and on a session with trailing history it is the wrong one.\n const pendingWrite = findPendingWrite(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 // ★ Read from the SAME message the content came from. Picking the last\n // element of `messages` instead would be a second, different guess at which\n // message this turn produced — and on a session with trailing history it is\n // the wrong one.\n ...(pendingWrite ? { pendingWrite } : {}),\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 = useAssistantTr();\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 replyLanguage = useAssistantStore((state) => state.replyLanguage);\n const languagePair = useMemo(\n () => resolveLanguagePair(assistantLanguage, replyLanguage, locale),\n [assistantLanguage, replyLanguage, locale]\n );\n const replyLanguageName = languagePair.reply.english;\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 // ★ Whether a HUMAN picked this reply language or it was guessed from the\n // interface — true if EITHER field was pinned, since inheriting from a\n // deliberate input choice is still deliberate. `buildLanguagePreamble` uses it\n // to suppress the \"what they wrote in wins\" clause, which would otherwise make\n // the setting inert for everyone who types rather than dictates.\n const languageIsExplicit = languagePair.replyIsExplicit;\n const replyLanguageCode = languagePair.reply.code;\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 mergeMessageMetadata,\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 // ★ One place decides which turns belong to which surface. `messages` stays\n // available for questions about the CONVERSATION (is it used at all?), but it\n // is readonly, so it cannot reach a component that draws a message list.\n const turns = useConversationTurns(activeConversation);\n const messages = turns.all;\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 /**\n * ★ A SECOND, different question — and deliberately not a second gate.\n *\n * The check above asks whether this person may USE the write mode (org scope).\n * Writes then execute at WORKSPACE scope, where a separate decision is made,\n * so an org owner could plan a change, confirm it, and only then be refused.\n * This asks the execution question up front so the warning arrives before the\n * effort rather than after it.\n *\n * It does NOT hide or disable the mode. Measured against prod on 2026-09-02,\n * workspace scopes have no roles provisioned at all, so gating on this would\n * delete Take-action from the product until an ops task lands — a far worse\n * outcome than the confusion it would fix. It self-corrects with no code\n * change the moment roles exist.\n */\n const writeAccess = useWorkspaceWriteAccess(getActorId(), getWorkspaceId() || null);\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 // Read-only transcript, reachable when NO session is live. The drawer used to\n // be mounted only inside `AssistantVoiceSession`, so pressing End destroyed the\n // only way to read back what was said.\n const [transcriptOpen, setTranscriptOpen] = useState(false);\n\n // Full attachment payload of the last send, kept so Retry can replay it\n // byte-for-byte (see handleRetry).\n const lastSentAttachmentsRef = useRef<Record<string, AssistantAttachment[]>>({});\n\n // Conversations with a turn already dispatched. Synchronous, unlike the store\n // — see the re-entry guard in handleSend for why that matters.\n /**\n * Per-sandbox record of \"last proven reachable\", so a warm sandbox is not\n * re-probed on every turn. Invalidated by any failure — see both catches.\n */\n const sandboxReadiness = useRef(createReadinessTracker());\n const inFlightSendsRef = useRef<Set<string>>(new Set());\n\n // If the active mode is no longer permitted — a non-admin with a persisted\n // api-calls mode, or the master flag turned off — fall back to the read-only\n // `assistant` mode (the default \"Ask\", available to everyone), but only AFTER\n /** The config for the mode in play — read by the reset effect and by render. */\n const activeModeConfig = useMemo(() => ASSISTANT_MODES.find((modeConfig) => modeConfig.id === mode), [mode]);\n\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 blocked = !activeModeConfig || (activeModeConfig.requiresAdmin && !canUseApiCalls);\n if (blocked && mode !== 'assistant') {\n setMode('assistant');\n }\n }, [mode, activeModeConfig, canUseApiCalls, apiAccessLoading, setMode]);\n\n const updateConversationStage = useCallback(\n (conversationId: string, assistantMessageId: string, status: AssistantConversationStatus, content?: string) => {\n setConversationProcessing(conversationId, status, assistantMessageId, null);\n if (content) {\n updateMessage(conversationId, assistantMessageId, content);\n } else {\n updateMessage(conversationId, assistantMessageId, getConversationStatusMessage(status));\n }\n },\n [setConversationProcessing, updateMessage]\n );\n\n const ensureAssistantRuntime = useCallback(\n async (\n conversationId: string,\n assistantMessageId: string,\n currentMode: AssistantMode,\n workspaceId: string,\n authContext: AssistantSandboxAuthContext\n ): Promise<{ sandboxId: string; sessionId: string }> => {\n let currentSandboxId = useAssistantStore.getState().sandboxesByMode[currentMode]?.sandboxId ?? null;\n\n // Validate that a candidate sandbox (remembered locally or found running on\n // the server) is actually reachable before we reuse it. A sandbox can expire\n // (ttlSeconds) or have its backend pod reclaimed while still being briefly\n // reported RUNNING; proxying to such a dead pod fails with a terminal state\n // (\"Backend resource no longer exists\") or a permanent 502 cf-proxy timeout.\n // Returns true only when the in-sandbox agent responds; false means stale.\n const ensureSandboxReachable = async (candidateId: string): Promise<boolean> => {\n // ★ Skip a proof we already have. This ran two network waits before the\n // model saw the prompt on EVERY turn, including turns seconds after the\n // last one succeeded — a constant tax, felt most in voice where it sits\n // between the user finishing a sentence and hearing anything.\n //\n // Safe only because every failure path below invalidates: see the catch\n // here and the turn-level catch. A cache that were only ever written on\n // success would pin a dead sandbox and turn a recoverable error into a\n // loop.\n if (sandboxReadiness.current.isFresh(candidateId)) return true;\n try {\n await waitForSandboxReady(apollo, candidateId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, candidateId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n sandboxReadiness.current.markVerified(candidateId);\n return true;\n } catch {\n // Stale/expired sandbox — drop it so we provision a fresh one below\n // instead of surfacing \"Internal server error\" to the user.\n sandboxReadiness.current.invalidate(candidateId);\n return false;\n }\n };\n\n // 1) Try the locally-remembered sandbox, then 2) any running one on the\n // server. Each is only kept if it's actually reachable.\n if (currentSandboxId) {\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', 'Reusing assistant environment...');\n if (!(await ensureSandboxReachable(currentSandboxId))) {\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = null;\n }\n }\n\n if (!currentSandboxId) {\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Looking for existing environment...'\n );\n const existingId = await findExistingSandbox(apollo, workspaceId, currentMode, authContext);\n\n if (existingId) {\n setSandbox(currentMode, existingId, 'provisioning');\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Reusing assistant environment...'\n );\n if (await ensureSandboxReachable(existingId)) {\n currentSandboxId = existingId;\n } else {\n setSandbox(currentMode, null, 'provisioning');\n }\n }\n }\n\n // 3) No reusable, reachable sandbox — provision a fresh one.\n if (!currentSandboxId) {\n if (currentMode === 'api-calls' && !getAccessToken()) {\n throw new Error('API Calls mode requires an authenticated session. Please sign in again.');\n }\n\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Starting assistant environment...'\n );\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = await createAssistantSandbox(apollo, currentMode, workspaceId, authContext);\n\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n await waitForSandboxReady(apollo, currentSandboxId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, currentSandboxId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n }\n\n setSandbox(currentMode, currentSandboxId, 'running');\n\n let sessionId =\n useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n ?.backendSessionId ?? null;\n\n if (sessionId) {\n try {\n const session = await getAssistantSession(apollo, currentSandboxId, workspaceId, sessionId, authContext);\n if (session.mode !== currentMode) {\n throw new Error(`Session mode mismatch: expected ${currentMode}, received ${session.mode}`);\n }\n } catch {\n clearBackendSessionId(conversationId);\n sessionId = null;\n }\n }\n\n if (!sessionId) {\n updateConversationStage(conversationId, assistantMessageId, 'connecting', 'Preparing session...');\n const result = await createAssistantSession(apollo, currentSandboxId, workspaceId, currentMode, authContext);\n sessionId = result.sessionId;\n setBackendSessionId(conversationId, sessionId);\n }\n\n return {\n sandboxId: currentSandboxId,\n sessionId,\n };\n },\n [apollo, clearBackendSessionId, getAccessToken, setBackendSessionId, setSandbox, updateConversationStage]\n );\n\n const handleSend = useCallback(\n async (\n content: string,\n attachments: AssistantAttachment[] = [],\n // ★ The live voice session's id, present only when this turn was spoken.\n // It replaced a `dictated` boolean: two fields meaning almost the same\n // thing let a turn be marked spoken while recording no session, a state\n // with no meaning that only the transcript would ever notice.\n options: { voiceSessionId?: string } = {}\n ) => {\n // Spoken-ness is now DERIVED, so it cannot disagree with the session.\n const dictated = options.voiceSessionId !== undefined;\n // Only block re-entry while a turn is genuinely in-flight. Earlier code\n // checked for *any* entry in the map, which stuck around as `complete`\n // / `error` after the first turn — making every subsequent message\n // silently disappear (the input cleared but handleSend bailed before\n // adding the user message to the conversation).\n //\n // The store is read LIVE, and that is what makes the guard work. The\n // render-captured `processingByConversationId` is stale by construction —\n // the click that starts a turn and the click that must be rejected can\n // belong to the same render. Reading `activeConversationId` live matters\n // for the same reason: on two racing first-ever sends, the second must see\n // the conversation the first one created a moment ago.\n //\n // Pairs with the synchronous `setConversationProcessing` below: because\n // the status is written before this function ever awaits, a second call —\n // however soon it arrives — always observes 'provisioning'.\n const storeAtEntry = useAssistantStore.getState();\n const guardConversationId = storeAtEntry.activeConversationId ?? activeConversationId;\n if (guardConversationId) {\n if (isTurnInFlight(storeAtEntry.processingByConversationId[guardConversationId]?.status)) return;\n // Second lock, in case a future change moves the status write later:\n // this one cannot be cleared by anything but the turn's own `finally`.\n // Deliberately per-conversation — a global key would keep blocking\n // after the conversation it belonged to was deleted mid-turn, and then\n // silently swallow every subsequent send.\n if (inFlightSendsRef.current.has(guardConversationId)) return;\n }\n\n const selectedMode = storeAtEntry.mode;\n let conversationId = activeConversationId;\n const currentConversation = conversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n : undefined;\n\n if (!conversationId) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (\n currentConversation &&\n currentConversation.mode !== selectedMode &&\n (currentConversation.messages.length > 0 || currentConversation.backendSessionId)\n ) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (currentConversation && currentConversation.mode !== selectedMode) {\n setConversationMode(conversationId, selectedMode);\n }\n\n if (!conversationId) return;\n\n // Keyed by conversation: the ref outlives a conversation switch, and a\n // single global slot meant Retry in one thread replayed another thread's\n // photo onto it.\n lastSentAttachmentsRef.current[conversationId] = attachments;\n\n const workspaceId = getWorkspaceId();\n const authContext: AssistantSandboxAuthContext = {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n };\n\n const userMessage: Message = {\n id: generateId(),\n role: 'user',\n content,\n timestamp: new Date().toISOString(),\n // Slim descriptors only — the bubble re-resolves thumbnails from the\n // file id, so the persisted conversation stays small.\n // ★ `voice` marks a turn that happened in the live voice session, so the\n // chat panel can leave it out. Both surfaces share one conversation, so\n // without it every spoken exchange showed up in the typed thread.\n metadata: {\n ...(attachments.length ? { attachments: attachments.map(toMessageAttachment) } : {}),\n ...voiceMarker(options.voiceSessionId),\n },\n };\n addMessage(conversationId, userMessage);\n\n const assistantMessageId = generateId();\n addMessage(conversationId, {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n timestamp: new Date().toISOString(),\n // Stamped now, not read later: this is the language the reply is being\n // generated in, and the preference may have moved on by the time\n // somebody presses Listen.\n // Carries the voice marker too: a reply to a spoken question belongs to\n // the voice session, not to the typed thread.\n metadata: { lang: replyLanguageCode, ...voiceMarker(options.voiceSessionId) },\n });\n\n // Mark the turn in-flight in the STORE right now, synchronously.\n //\n // Until this line the first status write happened inside\n // `ensureAssistantRuntime`, i.e. one await later. During that window\n // `activeIsProcessing` was false and `failedMessageId` still pointed at\n // the PREVIOUS failure — so the composer stayed enabled and, worse, the\n // Retry button (which has no `disabled` of its own) stayed mounted and\n // clickable on top of a turn that had already started.\n //\n // Status only, deliberately no stage copy: `ensureAssistantRuntime` picks\n // the accurate wording a moment later (\"Reusing...\" vs \"Starting...\"), and\n // guessing here would flash the wrong one on every reused sandbox.\n setConversationProcessing(conversationId, 'provisioning', assistantMessageId, null);\n\n const applyAssistantResponse = (\n response: string,\n artifacts?: AssistantArtifact[],\n sessionId?: string,\n sandboxId?: string,\n // Our own hard-coded copy is English regardless of what the user picked.\n // Stamping it with their language makes playback read an English quota\n // message in a Tamil voice — Latin text cannot be script-detected, so\n // this metadata is trusted absolutely.\n lang: string = replyLanguageCode\n ) => {\n // `patchMessage` REPLACES metadata rather than merging it, so anything\n // omitted here is destroyed — which is how the turn-language stamp set\n // at creation was being wiped the moment the response completed,\n // silently undoing per-message language resolution. Always re-assert it.\n //\n // ★ The voice marker was being lost the same way, and it was worse: this\n // runs on every completed turn, and the reply is only handed to the voice\n // session AFTER it runs, so NO spoken answer could ever stay a voice\n // turn. Each one jumped into the typed thread — under a question that\n // had been correctly hidden, so chat showed orphaned answers — and\n // vanished from the transcript drawer at the same instant.\n // ★ TWO calls, and the split is the point. `patchMessage` REPLACES\n // `metadata`, so rebuilding the object here silently drops every key the\n // turn added along the way. That is not hypothetical: it destroyed the\n // voice marker once (see above), and it then destroyed `pendingWrite` —\n // the poll loop recorded the refused write moments earlier and this line\n // wiped it before the card could ever render, shipping a feature that was\n // inert in production.\n //\n // Re-asserting each marker by hand is what failed twice. Merging cannot\n // fail that way: keys this turn set stay set, and the ones below still\n // win where they overlap.\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n });\n mergeMessageMetadata(conversationId, assistantMessageId, {\n lang,\n ...(artifacts?.length ? { artifacts } : {}),\n ...(artifacts?.length || sessionId || sandboxId ? { mode: selectedMode } : {}),\n ...(sessionId ? { sessionId } : {}),\n ...(sandboxId ? { sandboxId } : {}),\n ...voiceMarker(options.voiceSessionId),\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 // ★★ There is deliberately NO pre-flight AI-credit gate here.\n //\n // This block used to call `checkAssistantAiCredits` inside a try/catch\n // that surfaced the upgrade dialog on a 429 QUOTA_EXHAUSTED. The catch\n // could never run: `services/assistantApi.checkAssistantAiCredits` is a\n // documented no-op returning `Promise.resolve(true)`, so it cannot\n // reject. Thirty-four lines of code and prose described a live quota\n // gate that was structurally unreachable — the most expensive kind of\n // comment, because the next person reads it and believes HealthyBowl\n // gates on credits.\n //\n // The no-op is the RIGHT product decision, not an oversight: HB is\n // metered per input token against a Free allowance of 500, so a real\n // pre-flight gate would refuse ordinary chats. It is recorded in the\n // api adapter, where the decision belongs.\n //\n // The budget IS still enforced, downstream and for real: the wspace\n // gateway's @usage(checkQuota) on createSandbox rejects an over-quota\n // caller with a 429, and the outer catch below turns that into the\n // upgrade dialog. That path is live and reachable.\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 dictated\n );\n // Structured multimodal parts carry the image PIXELS, which no amount\n // of prompt text can. Built from the same `promptText`, so a bridge\n // that ignores `parts` loses nothing; `undefined` for an ordinary text\n // turn keeps the wire body unchanged.\n const promptParts = buildPromptParts(promptText, attachments);\n const inlinedCount = countInlinedImageParts(promptParts);\n const carriesPixels = inlinedCount > 0;\n const pageContext = gatherPageContext();\n\n // `buildPromptParts` may have demoted a photo to a link to keep the\n // body under the gateway's cap — a long message can do that on prompt\n // text alone. That decision is invisible to the user unless we say so,\n // and an answer that reads as if the model looked at a photo it never\n // received is worse than a short note.\n imagesDropped = countInlineImageCandidates(attachments) > inlinedCount;\n\n try {\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n promptParts\n );\n } catch (sendError) {\n // `buildPromptParts` already sizes the PARTS to the gateway's cap\n // (the prompt string itself is not bounded here), so reaching this\n // point means something rejected the body anyway — a tighter proxy\n // than we modelled, or a bridge that will not take `parts` at all.\n // Losing the whole question over that is the worst outcome\n // available: re-send it text-only. Only for errors that provably\n // never reached the agent (see isMultimodalBodyRejection) — a blind\n // retry would ask the same question twice and bill it twice.\n //\n // Gated on `parts` existing at all, NOT on it carrying pixels: the\n // array duplicates the whole prompt in `parts[0]`, so a url-only\n // parts array is itself enough to push a long message over the cap.\n // `carriesPixels` only decides whether the user is told something\n // was lost.\n if (!promptParts || !isMultimodalBodyRejection(sendError)) throw sendError;\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n undefined\n );\n // Only claim a photo was lost if one actually was — a url-only\n // retry loses nothing the prompt block did not already carry.\n imagesDropped = imagesDropped || carriesPixels;\n }\n\n let result = buildAssistantProgress([], priorNewestCreatedMs);\n const timeoutAt = Date.now() + (STREAM_BUDGET_MS[selectedMode] ?? DEFAULT_STREAM_BUDGET_MS);\n let lastTtlExtensionAt = Date.now();\n\n const pollStartedAt = Date.now();\n while (Date.now() < timeoutAt) {\n // ★ Delta poll. `priorNewestCreatedMs` is fixed for the whole turn and\n // is already the floor `buildAssistantProgress` filters on (`>`), so\n // asking the agent for `>=` the same value returns exactly the window\n // that function keeps — and nothing else. The result is identical; what\n // changes is that this stops re-downloading 50 full messages, plus the\n // injected page context, every 600-1500ms for the length of a turn.\n //\n // No merge or high-water bookkeeping is needed precisely BECAUSE the\n // floor is constant and progress is recomputed from scratch each poll.\n // A cursor that advanced would break `done` detection, since the\n // in-flight message would drop out of its own window.\n const sessionMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50,\n priorNewestCreatedMs\n );\n\n result = buildAssistantProgress(sessionMessages, priorNewestCreatedMs);\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(result.content),\n });\n\n // ★ The write the agent REFUSED, taken from its own tool result.\n // Without this the user approves the model's PARAGRAPH about the\n // change — written by the same model that wants the write to go\n // through, and reconciled against the payload by nothing.\n //\n // `mergeMessageMetadata`, never `patchMessage`: the latter REPLACES\n // metadata, and this message already carries `lang` and may carry the\n // voice marker. That exact mistake has shipped here before.\n if (result.pendingWrite) {\n mergeMessageMetadata(conversationId, assistantMessageId, { pendingWrite: result.pendingWrite });\n }\n\n if (result.done) break;\n\n if (Date.now() - lastTtlExtensionAt > 30_000) {\n await extendAssistantSandboxTTL(apollo, sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n // Fast early, backing off after — see assistantPollSchedule. This is\n // the granularity of the whole turn: it bounds how late the answer\n // appears AND how late speech can start, because auto-speak only\n // fires once a poll observes the reply completed.\n await new Promise((resolve) => setTimeout(resolve, pollDelayMs(Date.now() - pollStartedAt)));\n }\n\n // For non-build modes a timeout is a hard failure. For vibe-plugins the\n // prompt runs async server-side (/sessions/:id/prompt-async) and keeps\n // writing artifacts after the poll budget elapses, so we surface whatever\n // it has produced instead of discarding the turn.\n if (!result.done && selectedMode !== 'vibe-plugins') {\n throw new Error('Assistant response timed out while streaming progress');\n }\n\n const artifacts =\n selectedMode === 'vibe-plugins'\n ? await getAssistantArtifacts(apollo, sandboxId, workspaceId, sessionId, authContext).catch(() => [])\n : undefined;\n\n if (!result.done) {\n // vibe-plugins build still running in the background. Append a note so\n // the user knows the answer is partial and the artifacts will finish.\n result = {\n ...result,\n content: `${result.content}\\n\\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`,\n };\n }\n\n if (imagesDropped) {\n // Said plainly, because the alternative is an answer that looks like\n // it examined a photo it never received.\n result = {\n ...result,\n content: `${result.content}\\n\\n${tr(\n 'attachments.imagesNotSent',\n '_Your photo was too large to include with this message, so the answer above is from the text and the file link only. Try a smaller or more tightly cropped photo._'\n )}`,\n };\n }\n\n applyAssistantResponse(result.content, artifacts, sessionId, sandboxId);\n\n if (result.tokens) {\n patchMessage(conversationId, assistantMessageId, { tokens: result.tokens });\n // Charge the real token usage against the AI-credits quota (the\n // gateway records it via @usage(trackUsage)). We AWAIT it before\n // marking the turn complete / re-enabling input: otherwise a rapid\n // follow-up send would run its pre-flight checkAiCredits against a\n // stale balance (this turn's charge still in flight) and could\n // dispatch a prompt that should have been blocked, letting fast\n // sends bypass the credit cap. Still best-effort — a charge failure\n // never blocks the displayed answer.\n try {\n await reportAssistantAiTokenUsage(apollo, workspaceId, sessionId, result.tokens, authContext);\n notifyAiCreditsUpdated();\n } catch {\n // ignore — server-side @usage tracking is the source of truth\n }\n }\n setConversationProcessing(conversationId, 'complete', assistantMessageId, null);\n } catch (error) {\n if (attempt === 1 && isRecoverableAssistantError(error)) {\n clearBackendSessionId(conversationId);\n clearSandbox(selectedMode);\n return sendWithRealBackend(2);\n }\n\n throw error;\n }\n };\n\n // Claim the slot immediately before the first await, and release it in\n // `finally` so every exit — success, quota return, thrown error — frees\n // it. Registering here rather than earlier means a synchronous throw in\n // the setup above can never strand a key and wedge the conversation.\n const turnConversationId = conversationId;\n inFlightSendsRef.current.add(turnConversationId);\n\n try {\n if (!workspaceId) {\n throw new Error('Assistant backend is unavailable without an active workspace context.');\n }\n await sendWithRealBackend();\n } catch (error) {\n // ★ Any failed turn drops the readiness proof for the sandbox it used,\n // so the NEXT turn re-probes instead of trusting a cache entry that a\n // dead pod would otherwise keep alive until the TTL lapsed. This is the\n // half that makes the short-circuit above safe.\n sandboxReadiness.current.invalidate(\n useAssistantStore.getState().sandboxesByMode[selectedMode]?.sandboxId ?? null\n );\n // A quota error reaching here is the sandbox-environment wall hit\n // during runtime provisioning (createSandbox @usage). Surface the\n // upgrade dialog instead of a generic failure (the AI-credit wall is\n // already handled by the pre-flight gate above).\n if (isQuotaExhaustedError(error)) {\n dispatchAssistantQuotaExhausted('sandbox');\n applyAssistantResponse(\n \"You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.\",\n undefined,\n undefined,\n undefined,\n 'en'\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n const errorMessage = error instanceof Error ? error.message : 'Something went wrong';\n setConversationProcessing(conversationId, 'error', assistantMessageId, errorMessage);\n // Same reason: English copy must not inherit the turn's language stamp.\n // The voice marker still has to survive though — a failed spoken turn\n // belongs to the session that asked. Without it the failure surfaced as\n // a bare \"Sorry, an error occurred\" in the typed thread with no question\n // above it, while the voice session showed nothing at all.\n // Same split as the success path, and for the same reason: rebuilding\n // `metadata` here would erase a `pendingWrite` recorded moments earlier,\n // so a turn that failed AFTER the agent refused a write would lose the\n // record of what it had been about to do.\n patchMessage(conversationId, assistantMessageId, {\n content: `Sorry, an error occurred: ${errorMessage}. Please try again.`,\n });\n mergeMessageMetadata(conversationId, assistantMessageId, {\n lang: 'en',\n ...voiceMarker(options.voiceSessionId),\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 // ★ Search the TYPED thread, not the raw array. Retry is a chat-panel\n // affordance, so on a conversation whose last turn was spoken this picked up\n // the spoken prompt and re-sent it WITHOUT `dictated` — quietly converting a\n // voice turn into a chat turn and undoing the separation everywhere else.\n const lastUserMessage = [...turns.chat].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 // ★ SPOKEN replies only. Both consumers of this value are the voice\n // session — the caption it paints and the reply it advances on — so\n // scanning the raw array let a TYPED reply that happened to complete\n // during a live session be captioned and read aloud as the answer to a\n // spoken question. Reachable without the user typing anything: a host\n // page queues work through `pendingPrompt`, which is store-driven and so\n // fires straight past the overlay.\n //\n // `start`'s id-claim was the only thing holding this shut, and it covers\n // just the reply that existed when the session opened — not one that\n // arrives mid-session.\n if (!isVoiceTurn(message)) continue;\n // Tool-activity markup is stripped so the session captions and speaks the\n // answer, not the machinery that produced it.\n const text = parseToolActivity(message.content).text.trim();\n return text ? { id: message.id, text } : null;\n }\n return null;\n }, [messages, activeIsProcessing]);\n\n /**\n * The same reply, with its Markdown markers removed, for the on-screen caption.\n *\n * ★ Deliberately a SEPARATE memo rather than a change to the one above, whose\n * `text` is not just display: it is the echo reference the recogniser compares\n * against while the answer is being spoken, and the payload of the session's\n * `reply` dispatch. Stripping it there would silently shift what counts as an\n * echo of our own voice. The audio path keeps its own transform\n * (`toSpeakableText`) — the two want genuinely different output, which is why\n * they are two functions and not one.\n */\n const voiceCaption = useMemo(\n () => (latestAssistantReply ? toCaptionText(latestAssistantReply.text) : null),\n [latestAssistantReply]\n );\n\n /**\n * The last few exchanges, for the session's on-screen transcript.\n *\n * Voice turns already go through the normal send path, so they are ordinary\n * conversation messages — this only surfaces them INSIDE the session, which\n * is what makes a second question in the same session make sense.\n */\n /**\n * What the CHAT panel shows: everything that was not spoken.\n *\n * Voice and chat share one conversation, so without this split every spoken\n * exchange appeared in the typed thread.\n */\n const chatMessages = turns.chat;\n\n const voiceTurns = useMemo(\n () =>\n // ★ SPOKEN turns only — but this conversation's, not this session's.\n //\n // It used to take the last six messages of the WHOLE conversation, so\n // opening voice on an existing thread painted typed replies: the wall of\n // raw `##` and `**` in the operator's screenshot, because the voice panel\n // renders plain text. Filtering by channel fixed that.\n //\n // What it does NOT do is scope to the current session, and two comments\n // used to claim it did. `metadata.voice` is a boolean, so a second voice\n // session sees the first one's turns. Showing the conversation's whole\n // spoken history is the more useful of the two behaviours, so the wording\n // is what changed — but a genuine session scope needs a session id on the\n // message, not a flag.\n turns.voice\n .filter((message) => message.role === 'user' || message.role === 'assistant')\n .map((message) => ({\n id: message.id,\n role: message.role as 'user' | 'assistant',\n text: parseToolActivity(message.content).text.trim(),\n // Which spoken exchange this belongs to, so the transcript can show\n // where one ended and the next began. `undefined` for turns recorded\n // before session ids existed — real history, just unattributed.\n sessionId: voiceSessionIdOf(message),\n timestamp: message.timestamp,\n }))\n .filter((turn) => turn.text.length > 0),\n [turns.voice]\n );\n\n const handleSaveTranscript = useCallback(() => {\n if (voiceTurns.length === 0) return;\n const now = new Date();\n downloadFile(\n buildVoiceTranscriptMarkdown(\n voiceTurns,\n {\n title: tr('voiceSession.transcript', 'Voice conversation'),\n savedAt: tr('voiceSession.savedAt', 'Saved'),\n session: tr('voiceSession.sessionLabel', 'Session'),\n earlier: tr('voiceSession.earlierLabel', 'Earlier'),\n you: tr('voiceSession.speakerYou', 'You'),\n assistant: tr('voiceSession.speakerAssistant', 'Assistant'),\n },\n now\n ),\n voiceTranscriptFilename(now),\n 'text/markdown'\n );\n }, [voiceTurns, tr]);\n\n /**\n * The attachment draft for the VOICE surface.\n *\n * ★ Its own instance, not the composer's. A photo taken during a spoken\n * exchange belongs to the question about to be asked aloud — not to whatever\n * half-typed message is sitting in the text box behind the overlay, and not\n * the other way round either. Two drafts, two surfaces, same rule as the turns\n * themselves.\n */\n const voiceAttachments = useAssistantAttachments();\n // A ref so `submitVoiceTurn` keeps its stable identity — `useVoiceSession`\n // deliberately does not depend on `onSubmit`, and the same idiom is already\n // used for `handleSendRef` just below.\n const voiceAttachmentsRef = useRef(voiceAttachments);\n voiceAttachmentsRef.current = voiceAttachments;\n\n const submitVoiceTurn = useCallback((text: string, voiceSessionId: string) => {\n // ★ Only the voice SESSION is unambiguously dictated. The composer's\n // microphone also produces a transcript, but the user reads and edits it in\n // the box before sending, so treating that as dictated would tell the model\n // to second-guess words the user had already approved.\n // ★★ WAIT for uploads to settle before sending.\n //\n // The composer can disable its send button while an upload runs\n // (`sendBlocker`). Voice has no button — the turn fires on a silence timer —\n // so without this a photo that is still uploading is simply absent from the\n // question it belongs to, and the assistant answers about a leaf it was never\n // shown. Worse, the upload then finishes and the photo attaches itself to the\n // NEXT, unrelated spoken question.\n //\n // Deferring is the direct analogue of grey-ing out the send button: the turn\n // goes when its attachments are ready.\n const send = () => {\n const draft = voiceAttachmentsRef.current;\n const ready = getSendableAttachments(draft.attachments);\n void handleSendRef.current(text, ready, { voiceSessionId });\n // ★ ALWAYS clear, even when nothing was ready. A leftover attachment does\n // not wait politely for a related question — it rides whatever is asked\n // next. Dropping it is visible (the chip disappears); carrying it forward\n // is not.\n draft.clear();\n };\n\n if (!voiceAttachmentsRef.current.isBusy) {\n send();\n return;\n }\n\n // Polled rather than awaited: the hook exposes `isBusy`, not a promise, and\n // the alternative is threading upload plumbing through the voice session for\n // one caller. Capped, because a cold files service retries for ~51s and a\n // spoken question must not hang on it indefinitely.\n const startedAt = Date.now();\n const poll = window.setInterval(() => {\n const stillBusy = voiceAttachmentsRef.current.isBusy;\n if (stillBusy && Date.now() - startedAt < ATTACHMENT_SETTLE_TIMEOUT_MS) return;\n window.clearInterval(poll);\n send();\n }, 200);\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 /**\n * End the spoken exchange and leave a record of it in the typed thread.\n *\n * ★ The note tells the MODEL nothing, and does not need to: the client sends\n * no history, so the shared backend session already holds every spoken turn.\n * It exists so the HUMAN can see in the thread what was discussed — without\n * it the conversation continues against a page that looks empty.\n *\n * ★ Written as `role: 'system'`, which renders as a centred note. As a user\n * turn it would claim they typed it; as an assistant turn it would claim the\n * model said it. It is neither.\n */\n const handleContinueInChat = useCallback(() => {\n const conversationId = useAssistantStore.getState().activeConversationId;\n if (!conversationId || voiceTurns.length === 0) return;\n\n addMessage(conversationId, {\n id: generateId(),\n role: 'system',\n content: buildContinuedFromVoiceNote(voiceTurns, {\n intro: tr('voiceSession.continuedIntro', 'Continued from a voice conversation. You asked about:'),\n nothing: tr('voiceSession.continuedNothing', 'Continued from a voice conversation.'),\n more: (count) => tr('voiceSession.continuedMore', '…and {{count}} more', { count }),\n }),\n timestamp: new Date().toISOString(),\n // ★ No voice marker: the note belongs to the TYPED thread. That is the\n // whole point of the action — marking it would hide it in the surface the\n // user is leaving.\n });\n\n setTranscriptOpen(false);\n voiceSession.end();\n }, [voiceTurns, addMessage, tr]);\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 /**\n * A photo attached but never spoken does not outlive the session.\n *\n * ★ Otherwise it waits, invisibly, for the NEXT voice conversation and rides\n * along with whatever is asked then — a picture of last week's leaf answering\n * this week's question. Same rule as the turns themselves: a voice draft\n * belongs to the exchange that produced it.\n */\n useEffect(() => {\n if (voiceSession.active) return;\n // ★ UNCONDITIONAL. Guarding on `attachments.length > 0` looked like avoiding\n // pointless work and instead created the exact leak this effect prevents: a\n // photo still inside `prepareFile` (a 12MP downscale takes real time) has no\n // row yet, so the list is empty, so `clear()` was skipped — and `clear()` is\n // the only thing that bumps the epoch that cancels an in-flight prepare. The\n // file then landed in the draft AFTER its session ended and rode the next\n // one. Clearing an already-empty draft costs nothing.\n voiceAttachmentsRef.current.clear();\n }, [voiceSession.active]);\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 {/* ★ Says out loud that this thread is not showing everything the\n assistant remembers. Both surfaces share one backend session, so a\n spoken turn stays in the model's context whether or not it is drawn\n here — silence about that is what produces a reply referring to\n something the user cannot see. Hidden during a live session, where\n the overlay already IS the voice surface. */}\n {voiceTurns.length > 0 && !voiceSession.active ? (\n <AssistantSpokenTurnsNotice count={voiceTurns.length} onOpenTranscript={() => setTranscriptOpen(true)} />\n ) : null}\n\n {/* Transcript is always visible now — the old collapse-by-default accordion\n is gone; conversation history lives behind the header button instead. */}\n {chatMessages.length === 0 ? (\n <AssistantEmptyState mode={mode} onSuggestionClick={handleSuggestionClick} />\n ) : (\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <AssistantMessageList\n messages={chatMessages}\n streamingMessageId={activeStreamingMessageId}\n failedMessageId={failedMessageId}\n onRetry={handleRetry}\n />\n </div>\n )}\n\n <AssistantComposer\n // ★ Ask-mode only, and enforced here rather than merely documented.\n // In `api-calls` mode the assistant WRITES to farm data behind a consent\n // gate, and BOFF-6377 (\"confirm-before-write cannot prove a human\n // approved\") is still open — a spoken \"yes, do it\" is exactly the case\n // that ticket is about. Voice control of writes is the NEXT phase, not\n // this one, so the launcher is simply absent in that mode.\n onStartVoiceSession={voiceSession.available && mode !== 'api-calls' ? voiceSession.start : undefined}\n onSend={(value, attachments) => void handleSend(value, attachments)}\n disabled={activeIsProcessing}\n placeholder={\n mode === 'api-calls'\n ? tr('chatArea.placeholderActions', 'What would you like me to do?')\n : tr('chatArea.placeholderGeneral', 'Ask HealthyBowl anything…')\n }\n mode={mode}\n writeAccessDenied={writeAccess === 'denied' && Boolean(activeModeConfig?.writeCapable)}\n availableModes={availableModes}\n onModeChange={handleModeChange}\n />\n </div>\n\n {/* Read-only, and only when no session is live — a live session mounts its\n own copy inside the overlay. Same component either way, so the two can\n never drift apart. */}\n {transcriptOpen && !voiceSession.active ? (\n <VoiceTranscriptDrawer\n turns={voiceTurns}\n onClose={() => setTranscriptOpen(false)}\n onSave={handleSaveTranscript}\n // No \"continue in chat\" here: this mount opens FROM the chat panel, so\n // the user is already where that button would take them.\n />\n ) : null}\n\n {voiceSession.active && (\n <AssistantVoiceSession\n session={voiceSession.session}\n notice={voiceSession.notice}\n capturing={voiceSession.capturing}\n interrupting={voiceSession.interrupting}\n awaitingEndpoint={voiceSession.awaitingEndpoint}\n turns={voiceTurns}\n spokenChunks={voiceSession.spokenChunks}\n attachments={voiceAttachments.attachments}\n onAttachFiles={voiceAttachments.addFiles}\n onRemoveAttachment={voiceAttachments.remove}\n onRetryAttachment={voiceAttachments.retry}\n canAttachMore={voiceAttachments.canAddMore}\n preparingAttachments={voiceAttachments.preparingCount}\n onSaveTranscript={handleSaveTranscript}\n onContinueInChat={handleContinueInChat}\n onInterrupt={voiceSession.interrupt}\n spoken={voiceCaption}\n onToggleMute={voiceSession.toggleMute}\n onEnd={voiceSession.end}\n />\n )}\n\n <AssistantApiCallsConsentDialog\n open={pendingConsentMode !== null}\n onConfirm={handleConsentConfirm}\n onCancel={handleConsentCancel}\n />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8EA,IAAM,KAAkD;CACtD,SAAS;CACT,WAAW;CACX,aAAa;CACb,gBAAgB;AAClB,GACM,KAA2B,MAU3B,KAA+B;AAErC,SAAS,KAAqB;CAC5B,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC;AAC/D;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,GAO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KAAK,EAAW,GAAO,CAAW;MAClE,UAAU;MACV,aACE,MAAS,cACL,EAAG,+BAA+B,+BAA+B,IACjE,EAAG,+BAA+B,2BAA2B;MAE7D;MACN,mBAAmB,OAAgB,YAAY,EAAQ,IAAkB;MACzD;MAChB,cAAc;KACf,CAAA;IACE;;GAKJ,MAAkB,CAAC,EAAa,SAC/B,kBAAC,GAAD;IACE,OAAO;IACP,eAAe,GAAkB,EAAK;IACtC,QAAQ;GAGT,CAAA,IACC;GAEH,EAAa,UACZ,kBAAC,IAAD;IACE,SAAS,EAAa;IACtB,QAAQ,EAAa;IACrB,WAAW,EAAa;IACxB,cAAc,EAAa;IAC3B,kBAAkB,EAAa;IAC/B,OAAO;IACP,cAAc,EAAa;IAC3B,aAAa,EAAiB;IAC9B,eAAe,EAAiB;IAChC,oBAAoB,EAAiB;IACrC,mBAAmB,EAAiB;IACpC,eAAe,EAAiB;IAChC,sBAAsB,EAAiB;IACvC,kBAAkB;IAClB,kBAAkB;IAClB,aAAa,EAAa;IAC1B,QAAQ;IACR,cAAc,EAAa;IAC3B,OAAO,EAAa;GACrB,CAAA;GAGH,kBAAC,GAAD;IACE,MAAM,OAAuB;IAC7B,WAAW;IACX,UAAU;GACX,CAAA;EACE;;AAET"}
@@ -1,192 +1,2 @@
1
- import { VoiceTranscriptDrawer as e } from "./VoiceTranscriptDrawer.js";
2
- import { AssistantAttachmentButton as t } from "../composer/AssistantAttachmentButton.js";
3
- import { AssistantAttachmentChips as n } from "../composer/AssistantAttachmentChips.js";
4
- import { AssistantVoiceOrb as r } from "./AssistantVoiceOrb.js";
5
- import { VoiceStage as i } from "./VoiceStage.js";
6
- import { VoiceMiniController as ee } from "./VoiceMiniController.js";
7
- import { micIsInterrupt as a, voiceStageState as o } from "../../../utils/voiceStageState.js";
8
- import { spokenSoFar as s } from "../../../utils/voiceSession.js";
9
- import { useCallback as c, useEffect as l, useRef as u, useState as d } from "react";
10
- import { Maximize2 as te, Minimize2 as f, ScrollText as p, X as m } from "lucide-react";
11
- import { jsx as h, jsxs as g } from "react/jsx-runtime";
12
- import { useAssistantTr as ne } from "@burdenoff/fe-libs/shared/assistant/i18n";
13
- //#region src/components/assistant/voice/AssistantVoiceSession.tsx
14
- var _ = ({ session: _, turns: b = [], onSaveTranscript: x, onContinueInChat: S, notice: C = null, spoken: w, onInterrupt: T, onToggleMute: E, attachments: D = [], onAttachFiles: O, onRemoveAttachment: k, onRetryAttachment: A, canAttachMore: re = !0, preparingAttachments: j = 0, spokenChunks: ie = null, onEnd: M, capturing: ae = !0, interrupting: N = !1, awaitingEndpoint: P = !1 }) => {
15
- let F = ne(), { phase: oe, muted: I, error: L } = _, R = u(null), z = u(null), [B, V] = d("mini"), H = B === "full", U = B === "mini", W = B === "mini" ? "panel" : B === "panel" ? "full" : "mini", [G, K] = d(!1), q = u(!1), J = u(E);
16
- J.current = E;
17
- let se = c(() => {
18
- I || q.current || s(_) || (q.current = !0, J.current());
19
- }, [I, _]);
20
- l(() => {
21
- let e = () => {
22
- q.current && (q.current = !1, J.current());
23
- };
24
- return window.addEventListener("focus", e), () => {
25
- window.removeEventListener("focus", e), q.current = !1;
26
- };
27
- }, []), l(() => {
28
- R.current?.focus();
29
- }, []), l(() => {
30
- let e = (e) => {
31
- if (e.key === "Escape") {
32
- if (G) {
33
- K(!1);
34
- return;
35
- }
36
- M();
37
- return;
38
- }
39
- if (e.key !== "Tab" || !H) return;
40
- let t = (G ? z.current?.querySelector("[data-testid=\"assistant-voice-transcript\"]") : z.current)?.querySelectorAll("button:not([disabled])");
41
- if (!t || t.length === 0) return;
42
- let n = t[0], r = t[t.length - 1];
43
- !n || !r || (e.shiftKey && document.activeElement === n ? (e.preventDefault(), r.focus()) : !e.shiftKey && document.activeElement === r && (e.preventDefault(), n.focus()));
44
- };
45
- return window.addEventListener("keydown", e), () => window.removeEventListener("keydown", e);
46
- }, [
47
- M,
48
- H,
49
- G
50
- ]);
51
- let Y = C !== null && L === null, X = s(_), Z = o({
52
- snapshot: _,
53
- capturing: ae,
54
- interrupting: N,
55
- awaitingEndpoint: P
56
- }), Q = (() => {
57
- switch (Z) {
58
- case "connecting": return F("voiceSession.connecting", "Starting the microphone…");
59
- case "endpoint-grace": return F("voiceSession.endpointGrace", "Still listening — take your time");
60
- case "interrupting": return F("voiceSession.interrupting", "Stopped — go ahead");
61
- case "thinking": return F("voiceSession.thinking", "Thinking…");
62
- case "speaking": return F("voiceSession.speaking", "Speaking — tap to stop");
63
- case "mic-error":
64
- case "ended": return "";
65
- case "listening": return I ? F("voiceSession.muted", "Microphone off") : F("voiceSession.listening", "Listening…");
66
- default: return Z;
67
- }
68
- })(), $ = I && Z !== "listening" && Q !== "" ? `${Q} · ${F("voiceSession.muted", "Microphone off")}` : Q;
69
- return /* @__PURE__ */ g("div", {
70
- ref: z,
71
- className: `flex flex-col items-center justify-between bg-bg-sunken ${B === "full" ? "fixed inset-x-0 bottom-0 top-14 z-[60] px-6 py-8" : B === "panel" ? "absolute inset-0 z-20 px-4 py-6" : "absolute inset-x-0 bottom-0 z-20 h-[11.25rem] border-t border-border-subtle px-3 py-3 shadow-lg"}`,
72
- role: "dialog",
73
- "aria-modal": H || void 0,
74
- "aria-label": F("voiceSession.title", "Voice conversation"),
75
- "data-testid": "assistant-voice-session",
76
- children: [
77
- /* @__PURE__ */ g("button", {
78
- ref: R,
79
- type: "button",
80
- onClick: M,
81
- className: `absolute ${H ? "right-6 top-6 h-14 gap-2 px-5 text-base" : U ? "right-2 top-2 size-8" : "right-3 top-3 h-11 gap-2 px-4 text-sm"} flex items-center justify-center rounded-full border border-border-default bg-bg-elevated text-text-secondary hover:bg-bg-sunken transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`,
82
- "aria-label": U ? F("voiceSession.end", "End the voice conversation") : void 0,
83
- "data-testid": "assistant-voice-end",
84
- children: [/* @__PURE__ */ h(m, {
85
- className: H ? "size-6" : U ? "size-4" : "size-5",
86
- "aria-hidden": "true"
87
- }), U ? null : /* @__PURE__ */ h("span", {
88
- className: "max-w-[7rem] truncate whitespace-nowrap font-medium",
89
- children: F("voiceSession.endShort", "End")
90
- })]
91
- }),
92
- /* @__PURE__ */ h("div", {
93
- className: `flex flex-col items-center ${U ? "px-3" : `min-h-[1.5rem] ${Y ? H ? "pt-14" : "pt-10" : ""}`}`,
94
- children: Y ? /* @__PURE__ */ h("p", {
95
- className: "max-w-xs text-center text-xs text-status-warning",
96
- "data-testid": "assistant-voice-notice",
97
- children: v(C, F)
98
- }) : null
99
- }),
100
- (() => {
101
- let e = /* @__PURE__ */ h(r, {
102
- session: _,
103
- compact: U,
104
- connecting: Z === "connecting",
105
- onPress: a(Z) ? T : E,
106
- label: a(Z) ? F("voiceSession.interrupt", "Stop the assistant and speak") : I ? F("voiceSession.unmute", "Turn the microphone on") : F("voiceSession.mute", "Turn the microphone off")
107
- }), t = a(Z) ? w : X || null, n = L === null ? null : y(L, F);
108
- return U ? /* @__PURE__ */ h(ee, {
109
- state: Z,
110
- caption: t,
111
- statusText: $,
112
- errorText: n,
113
- control: e
114
- }) : /* @__PURE__ */ h(i, {
115
- state: Z,
116
- userCaption: X || null,
117
- spokenChunks: ie,
118
- assistantCaption: w,
119
- expanded: H,
120
- statusText: $,
121
- errorText: n,
122
- control: e
123
- });
124
- })(),
125
- G ? /* @__PURE__ */ h(e, {
126
- turns: b,
127
- onClose: () => K(!1),
128
- onSave: x,
129
- onContinueInChat: S
130
- }) : null,
131
- O ? /* @__PURE__ */ h("div", {
132
- className: `absolute ${H ? "left-6 top-6" : U ? "left-11 top-2" : "left-3 top-3"}`,
133
- children: /* @__PURE__ */ h(t, {
134
- onFiles: (e) => {
135
- O(e), V((e) => e === "mini" ? "panel" : e);
136
- },
137
- onPickerOpen: se,
138
- direction: "down",
139
- canAddMore: re
140
- })
141
- }) : null,
142
- (D.length > 0 || j > 0) && !U ? /* @__PURE__ */ h("div", {
143
- className: `absolute ${H ? "bottom-24 left-24 right-24" : "bottom-16 left-16 right-16"}`,
144
- "data-testid": "assistant-voice-attachments",
145
- children: /* @__PURE__ */ h(n, {
146
- attachments: D,
147
- onRemove: k ?? (() => void 0),
148
- onRetry: A ?? (() => void 0),
149
- preparingCount: j
150
- })
151
- }) : null,
152
- /* @__PURE__ */ h("button", {
153
- type: "button",
154
- onClick: () => K((e) => !e),
155
- className: `absolute ${H ? "bottom-6 right-6 size-14" : U ? "right-11 top-2 size-8" : "bottom-3 right-3 size-11"} flex items-center justify-center rounded-full bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`,
156
- "aria-pressed": G,
157
- "aria-label": F("voiceSession.transcript", "Voice transcript"),
158
- "data-testid": "assistant-voice-transcript-toggle",
159
- children: /* @__PURE__ */ h(p, { className: H ? "size-6" : U ? "size-4" : "size-5" })
160
- }),
161
- /* @__PURE__ */ h("button", {
162
- type: "button",
163
- onClick: () => V(W),
164
- className: `absolute ${H ? "bottom-6 left-6 size-14" : U ? "left-2 top-2 size-8" : "bottom-3 left-3 size-11"} flex items-center justify-center rounded-full bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`,
165
- "aria-label": W === "panel" ? F("voiceSession.expandPanel", "Show the conversation in the panel") : W === "full" ? F("voiceSession.expand", "Expand the conversation to full screen") : F("voiceSession.collapse", "Shrink to the compact controller"),
166
- "data-testid": "assistant-voice-expand",
167
- children: H ? /* @__PURE__ */ h(f, { className: "size-5" }) : /* @__PURE__ */ h(te, { className: U ? "size-4" : "size-5" })
168
- })
169
- ]
170
- });
171
- };
172
- function v(e, t) {
173
- switch (e) {
174
- case "network": return t("voiceSession.noticeNetwork", "Speech recognition lost its connection. Check your network — it will retry.");
175
- case "not-capturing": return t("voiceSession.noticeNotCapturing", "The microphone did not start. Check that this site is allowed to use it, then try again.");
176
- case "recognition-failed": return t("voiceSession.noticeRecognitionFailed", "Speech recognition stopped unexpectedly. It will retry — if it keeps happening, reload the page.");
177
- case "nothing-heard": return t("voiceSession.noticeNothingHeard", "Nothing heard yet. Check your microphone is not muted or in use by another app.");
178
- default: return e;
179
- }
180
- }
181
- function y(e, t) {
182
- switch (e) {
183
- case "mic-denied": return t("voiceSession.micDenied", "Microphone access is blocked. Allow it in your browser settings to talk.");
184
- case "no-speech-support": return t("voiceSession.noSpeechSupport", "This browser cannot listen. Try a different browser, or type instead.");
185
- case "no-voice-support": return t("voiceSession.noVoiceSupport", "This device has no voice that can speak this language.");
186
- default: return e;
187
- }
188
- }
189
- //#endregion
190
- export { _ as AssistantVoiceSession };
191
-
192
- //# sourceMappingURL=AssistantVoiceSession.js.map
1
+ import { AssistantVoiceSession as e } from "@burdenoff/fe-libs/shared/assistant/ui/voice/AssistantVoiceSession";
2
+ export { e as AssistantVoiceSession };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/microfe-healthybowl",
3
- "version": "2026.904.18",
3
+ "version": "2026.904.20",
4
4
  "description": "Burdenoff HealthyBowl Microfrontend - Comprehensive organic farming and agro-foods management platform",
5
5
  "type": "module",
6
6
  "files": [
@@ -48,7 +48,7 @@
48
48
  },
49
49
  "dependencies": {
50
50
  "@apollo/client": "^4.0.11",
51
- "@burdenoff/fe-libs": "2026.904.17",
51
+ "@burdenoff/fe-libs": "2026.904.18",
52
52
  "@burdenoff/planmagnet-fe-sdk": "2026.831.1",
53
53
  "@tanstack/react-query": "^5.90.16",
54
54
  "clsx": "^2.1.1",
@@ -1,2 +0,0 @@
1
- import { AssistantVoiceOrb as e } from "@burdenoff/fe-libs/shared/assistant/ui/voice/AssistantVoiceOrb";
2
- export { e as AssistantVoiceOrb };
@@ -1 +0,0 @@
1
- {"version":3,"file":"AssistantVoiceSession.js","names":[],"sources":["../../../../src/components/assistant/voice/AssistantVoiceSession.tsx"],"sourcesContent":["import { useCallback, useEffect, useRef, useState, type FC } from 'react';\nimport { Maximize2, Minimize2, ScrollText, X } from 'lucide-react';\nimport { AssistantAttachmentButton } from '../composer/AssistantAttachmentButton';\nimport { AssistantAttachmentChips } from '../composer/AssistantAttachmentChips';\nimport type { AssistantAttachment } from '@/utils/assistantAttachments';\nimport { AssistantVoiceOrb } from './AssistantVoiceOrb';\nimport { VoiceStage } from './VoiceStage';\nimport { VoiceMiniController } from './VoiceMiniController';\nimport { VoiceTranscriptDrawer } from './VoiceTranscriptDrawer';\nimport { voiceStageState, micIsInterrupt } from '../../../utils/voiceStageState';\nimport { useAssistantTr } from '@burdenoff/fe-libs/shared/assistant/i18n';\nimport { spokenSoFar, type VoiceSessionSnapshot } from '../../../utils/voiceSession';\nimport type { VoiceSessionError } from '../../../utils/voiceSession';\nimport type { VoiceSessionNotice } from '../../../hooks/useVoiceSession';\nimport type { VoiceTranscriptTurn } from '../../../utils/voiceTurnVisibility';\n\n/** How much room the voice session takes: a strip, the panel, or the screen. */\nexport type VoiceView = 'mini' | 'panel' | 'full';\n\ninterface Props {\n session: VoiceSessionSnapshot;\n /** Recent exchanges, oldest first — the running conversation. */\n turns?: ReadonlyArray<VoiceTranscriptTurn>;\n /** Download the spoken conversation. */\n onSaveTranscript?: () => void;\n /** Leave a note in the typed thread, end the session, and carry on there. */\n onContinueInChat?: () => void;\n /** Cut the assistant off mid-reply. */\n onInterrupt?: () => void;\n /** A recoverable problem to surface. Null when the microphone is healthy. */\n notice?: VoiceSessionNotice | null;\n /** The assistant's last reply, captioned while it is spoken. */\n spoken: string | null;\n onToggleMute: () => void;\n /**\n * Files attached to the NEXT spoken turn.\n *\n * ★ Deliberately a separate draft from the composer's. A photo taken during a\n * voice session belongs to the question the user is about to ask aloud, not to\n * whatever half-typed message is sitting in the text box behind the overlay.\n */\n attachments?: AssistantAttachment[];\n onAttachFiles?: (files: FileList | null) => void;\n onRemoveAttachment?: (id: string) => void;\n onRetryAttachment?: (id: string) => void;\n canAttachMore?: boolean;\n /** Files being read — placeholder chips, see AssistantAttachmentChips. */\n preparingAttachments?: number;\n /** Reveals the assistant caption in step with the audio. */\n spokenChunks?: { chunks: string[]; index: number } | null;\n onEnd: () => void;\n /** Is the recogniser actually running? Distinguishes CONNECTING from LISTENING. */\n capturing?: boolean;\n /** The user has cut the assistant off and capture has not resumed yet. */\n interrupting?: boolean;\n /** Quiet has fallen and the two-second correction window is running. */\n awaitingEndpoint?: boolean;\n}\n\n/**\n * Full-screen voice conversation (BOFF-7120).\n *\n * ★ **Voice only, by explicit product decision.** The reference (Gemini Live)\n * also offers camera and screen sharing; those are deliberately absent here.\n * Attaching images is a separate, existing capability of the assistant and\n * stays in the composer, and screen sharing could not work on the primary\n * device anyway — `getDisplayMedia` is unsupported by every iOS browser, so\n * that control would be dead on an iPhone.\n *\n * The controls are therefore the two that a voice conversation actually needs:\n * mute, and end. Anything else would be a button the user has to think about\n * while talking.\n *\n * This component is presentational: every transition is owned by\n * `voiceSessionReducer`, which is pure and tested. That split exists because\n * this file cannot be tested at all in this repo — vitest runs in `node` with\n * no DOM and no audio.\n */\nexport const AssistantVoiceSession: FC<Props> = ({\n session,\n turns = [],\n onSaveTranscript,\n onContinueInChat,\n notice = null,\n spoken,\n onInterrupt,\n onToggleMute,\n attachments = [],\n onAttachFiles,\n onRemoveAttachment,\n onRetryAttachment,\n canAttachMore = true,\n preparingAttachments = 0,\n spokenChunks = null,\n onEnd,\n capturing = true,\n interrupting = false,\n awaitingEndpoint = false,\n}) => {\n const tr = useAssistantTr();\n const { phase, muted, error } = session;\n const endRef = useRef<HTMLButtonElement>(null);\n const dialogRef = useRef<HTMLDivElement>(null);\n /**\n * Docked inside the assistant panel by default; full-screen only on request.\n *\n * A voice conversation is usually a glance-and-listen thing, so taking over\n * the whole screen for it is the wrong default — the user loses the page they\n * were asking about. Expanding is opt-in and per-session: reopening starts\n * docked again, which is the behaviour that matches \"default should be the\n * same size as the assistant\".\n */\n /**\n * ★ THREE sizes, not two.\n *\n * The compact controller was added so voice stops taking over the panel — but\n * making it the only docked size removed the in-panel stage that existed\n * before, which is a genuinely useful middle: big enough to read a reply,\n * without losing the page behind it.\n *\n * mini — a strip at the bottom; the assistant panel stays visible\n * panel — fills the assistant panel (what \"docked\" used to mean)\n * full — full screen\n *\n * One button steps mini → panel → full and wraps, with the label always\n * naming where it goes next, so a single control stays predictable.\n */\n const [view, setView] = useState<VoiceView>('mini');\n const expanded = view === 'full';\n const mini = view === 'mini';\n const nextView: VoiceView = view === 'mini' ? 'panel' : view === 'panel' ? 'full' : 'mini';\n /** History is secondary: the stage shows now, this shows the session. */\n const [transcriptOpen, setTranscriptOpen] = useState(false);\n\n /**\n * Release the microphone while an OS picker owns the screen, then take it back.\n *\n * ★ The camera app claims the mic. Without this the session sits in `listening`\n * with a recogniser that has been stopped underneath it, the reconciliation\n * effect in `useVoiceSession` keeps calling `start()` against a backgrounded\n * page, and the user returns from photographing a leaf to a \"microphone isn't\n * capturing\" warning on a session that looks alive.\n *\n * ★ Resume keys off `focus`, NOT the file `change` event. A CANCELLED picker\n * fires no change event at all — that is the whole reason this is a window\n * listener rather than a callback on the file input. Focus covers both endings:\n * a photo taken and a photo abandoned.\n *\n * ★ Muting is how the session releases the mic legitimately (`isCapturing`\n * returns false when muted), so this reuses the state machine rather than\n * inventing a parallel \"suspended\" phase. And it only ever restores a mute IT\n * applied: a user who muted themselves before reaching for the camera stays\n * muted afterwards.\n */\n const micSuspendedRef = useRef(false);\n const toggleMuteRef = useRef(onToggleMute);\n toggleMuteRef.current = onToggleMute;\n\n const handlePickerOpen = useCallback(() => {\n if (muted || micSuspendedRef.current) return;\n // ★★ Muting WIPES the turn. The reducer drops `pending` and `interim` on mute\n // so a half-heard fragment is never submitted later as a truncated question —\n // right for a mute the user chose, catastrophic for an internal mic-handoff\n // they never asked for. Someone saying \"this leaf has yellow spots, let me\n // show you\" and reaching for the camera would come back to an empty caption\n // and no way to recover the sentence.\n //\n // So the handoff only happens when there is nothing to lose. Mid-sentence,\n // the mic simply keeps its claim: the camera takes it anyway, and the\n // reconciliation effect in `useVoiceSession` restarts the recogniser on\n // return. The worst case there is a transient \"not capturing\" notice, which\n // is a far smaller harm than deleting what the user just said.\n if (spokenSoFar(session)) return;\n micSuspendedRef.current = true;\n toggleMuteRef.current();\n }, [muted, session]);\n\n useEffect(() => {\n const restore = () => {\n if (!micSuspendedRef.current) return;\n micSuspendedRef.current = false;\n toggleMuteRef.current();\n };\n window.addEventListener('focus', restore);\n return () => {\n window.removeEventListener('focus', restore);\n // Ending the session while a picker is open must not leave the ref set for\n // the next one — `end` already resets the mute, so just drop the claim.\n micSuspendedRef.current = false;\n };\n }, []);\n\n // A full-screen `aria-modal` overlay that cannot be dismissed from the\n // keyboard is a trap. Escape ends the session, and focus starts on End so a\n // keyboard or screen-reader user lands somewhere useful rather than behind\n // the overlay.\n // Focus lands on End ONCE, on open. Keeping this in the keydown effect below\n // meant every expand/collapse re-ran it and silently stole focus from the\n // button just pressed — a Space or Enter a beat later would then end the\n // session instead of toggling the size again.\n useEffect(() => {\n endRef.current?.focus();\n }, []);\n\n useEffect(() => {\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n // ★ Escape closes the drawer first. Ending the whole conversation\n // because someone dismissed a panel would be a surprising amount of\n // destruction for one keypress.\n if (transcriptOpen) {\n setTranscriptOpen(false);\n return;\n }\n onEnd();\n return;\n }\n // Trapping focus is only correct when the overlay actually covers\n // everything. Docked, it sits inside the panel and the rest of the page\n // is legitimately reachable, so trapping there would be the bug rather\n // than the fix.\n if (event.key !== 'Tab' || !expanded) return;\n // `aria-modal` only TELLS assistive technology this is modal; it does not\n // make it so. Without this, Tab walks straight out of the overlay into the\n // page behind it, which is still fully interactive underneath — a\n // keyboard user ends up operating a screen they cannot see.\n // ★ Scope the trap to what is actually on screen. With the transcript\n // drawer open, a flat `button` query also collects the controls it covers,\n // so Tab walked into buttons the user could not see — the same class of\n // bug the trap exists to prevent.\n const scope = transcriptOpen\n ? dialogRef.current?.querySelector<HTMLElement>('[data-testid=\"assistant-voice-transcript\"]')\n : dialogRef.current;\n const focusable = scope?.querySelectorAll<HTMLElement>('button:not([disabled])');\n if (!focusable || focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (!first || !last) return;\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n window.addEventListener('keydown', onKeyDown);\n return () => window.removeEventListener('keydown', onKeyDown);\n }, [onEnd, expanded, transcriptOpen]);\n\n // 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 // A notice competes with the error for the same slot; the error owns the\n // stage, so they are never both shown.\n const showNotice = notice !== null && error === null;\n\n const heard = spokenSoFar(session);\n\n // ★ ONE state, derived. The reducer's phase cannot tell \"listening\" from\n // \"the microphone has not started yet\", and the old overlay rendered every\n // signal at once — status, warning, transcript, caption and orb together.\n // ★ Both signals were accepted by `voiceStageState` and passed by nobody, so\n // `endpoint-grace` and `interrupting` were unreachable branches.\n const stage = voiceStageState({ snapshot: session, capturing, interrupting, awaitingEndpoint });\n\n /**\n * The label for the STAGE, not for the phase.\n *\n * ★ This used to read `phase`, which is why three derived stages were\n * invisible even once they were reachable: `connecting`, `endpoint-grace` and\n * `interrupting` are all `phase === 'listening'` underneath, so every one of\n * them said \"Listening…\". The stage exists precisely because the phase cannot\n * make these distinctions — deriving the caption from the phase threw that\n * away again, and told the user we were listening before the recogniser had\n * started, the exact lie `voiceStageState` was written to stop.\n */\n const stageText = (() => {\n switch (stage) {\n case 'connecting':\n return tr('voiceSession.connecting', 'Starting the microphone…');\n case 'endpoint-grace':\n // Reads as an invitation, not a countdown: the window exists so the\n // user can still correct themselves, and hurrying them defeats it.\n return tr('voiceSession.endpointGrace', 'Still listening — take your time');\n case 'interrupting':\n return tr('voiceSession.interrupting', 'Stopped — go ahead');\n case 'thinking':\n return tr('voiceSession.thinking', 'Thinking…');\n case 'speaking':\n return tr('voiceSession.speaking', 'Speaking — tap to stop');\n case 'mic-error':\n case 'ended':\n // Owned by the error branch of the stage, which gets it to itself.\n return '';\n case 'listening':\n return muted ? tr('voiceSession.muted', 'Microphone off') : tr('voiceSession.listening', 'Listening…');\n default: {\n // ★ Exhaustive on purpose, matching `errorMessage` and `noticeMessage`\n // below. A stage with no copy is the exact bug this change fixes, so a\n // new one without a label must fail the BUILD rather than silently\n // inherit \"Listening…\" the way three of them already did.\n const unhandled: never = stage;\n return unhandled;\n }\n }\n })();\n\n // Muted is reported ALONGSIDE the stage, 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 //\n // ★ Gated on the STAGE, not the phase. `connecting`, `endpoint-grace` and\n // `interrupting` are all `phase === 'listening'` underneath, so a phase test\n // dropped the suffix on exactly the three stages this change introduced —\n // leaving \"Stopped — go ahead\" inviting someone to speak into a muted\n // microphone. The `!== ''` guard keeps ended/mic-error from rendering a bare\n // \" · Microphone off\".\n //\n // ★ No `error !== null` arm: `stageText` is already '' for `mic-error`, and\n // the message itself belongs to the stage's alert element. Testing the error\n // here printed the whole sentence TWICE on the one screen this change exists\n // to make visible — truncated in the status line, repeated below it, and\n // announced twice by a screen reader.\n const status =\n muted && stage !== 'listening' && stageText !== ''\n ? `${stageText} · ${tr('voiceSession.muted', 'Microphone off')}`\n : stageText;\n\n return (\n <div\n ref={dialogRef}\n className={`flex flex-col items-center justify-between bg-bg-sunken ${\n view === 'full'\n ? // ★ Below the app header, not behind it. The header is `z-[100]` and\n // this overlay was `z-[60]` at `inset-0`, so the top 56px sat behind\n // it — and the End button did not merely LOOK hidden, it was\n // unclickable (`elementFromPoint` returned the header). Starting at\n // `top-14` means nothing is ever behind the header, and the header\n // stays usable for orientation.\n 'fixed inset-x-0 bottom-0 top-14 z-[60] px-6 py-8'\n : view === 'panel'\n ? // The in-panel stage: covers the assistant panel, keeps the page.\n 'absolute inset-0 z-20 px-4 py-6'\n : // A strip at the bottom, ~180px, so the panel behind stays visible.\n 'absolute inset-x-0 bottom-0 z-20 h-[11.25rem] border-t border-border-subtle px-3 py-3 shadow-lg'\n }`}\n role=\"dialog\"\n // Only modal when it really is: docked, the page behind stays usable.\n // `undefined` rather than `false` — the ARIA default is already false, and\n // some older assistive technology treats an explicit \"false\" on a dialog\n // as still modal.\n aria-modal={expanded || undefined}\n aria-label={tr('voiceSession.title', 'Voice conversation')}\n data-testid=\"assistant-voice-session\"\n >\n {/* End sits top-right and expand bottom-left, out of the centre column.\n Absolute rather than part of the flow so the pill stays optically\n centred at both sizes — the overlay is already a positioning context\n (`fixed` when expanded, `absolute` when docked). */}\n <button\n ref={endRef}\n type=\"button\"\n onClick={onEnd}\n // ★ Height + horizontal padding, never `size-*`. A fixed square cannot\n // grow to fit a word, so a label dropped into one spills outside its own\n // rounded border. The mini strip keeps the square: its transcript toggle\n // sits 4px away at `right-11`, and a wider button there would grow\n // leftward underneath it — which is precisely the defect the previous\n // commit on this file fixed (\"the close button was unclickable\").\n className={`absolute ${\n expanded\n ? 'right-6 top-6 h-14 gap-2 px-5 text-base'\n : mini\n ? 'right-2 top-2 size-8'\n : 'right-3 top-3 h-11 gap-2 px-4 text-sm'\n } flex items-center justify-center rounded-full border border-border-default bg-bg-elevated text-text-secondary hover:bg-bg-sunken transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n // ★ Only when the label is INVISIBLE. With visible text the accessible\n // name comes from that text, which keeps WCAG 2.5.3 (Label in Name)\n // true by construction in every locale — including before `endShort` is\n // seeded. An aria-label here would instead pin a translated sentence\n // against an untranslated visible word, and speech-input users say the\n // word they can see.\n aria-label={mini ? tr('voiceSession.end', 'End the voice conversation') : undefined}\n data-testid=\"assistant-voice-end\"\n >\n <X className={expanded ? 'size-6' : mini ? 'size-4' : 'size-5'} aria-hidden=\"true\" />\n {/* The glyph alone said \"close\" only to people who already knew.\n ★ Bounded: the width is a TRANSLATED string while the layout around\n it is fixed pixels — \"Beenden\" and \"Terminer\" are ~2.4x \"End\". The\n cap turns a future overflow into an ellipsis rather than a control\n that creeps over its neighbour. */}\n {!mini ? (\n <span className=\"max-w-[7rem] truncate whitespace-nowrap font-medium\">\n {tr('voiceSession.endShort', 'End')}\n </span>\n ) : null}\n </button>\n\n {/* ★ The notice is CHROME, not conversation. It used to sit above the\n transcript in the same column as the reply, which is why a microphone\n warning read as part of what the assistant said. The status line moved\n into the stage, where it labels the state it belongs to. */}\n {/* ★ Cleared VERTICALLY, not horizontally. This div is a flex item of a\n `flex flex-col items-center` column, so it is SHRINK-TO-FIT: side\n padding does not reserve space beside the End button, it eats the\n text's own measure — symmetrically, for a control on one side only.\n Widening `px-14` to match a labelled button collapsed the microphone\n warning to a 78px, nine-line column on a phone and in the docked\n panel, because 78px is the min-content width of the longest word in it.\n\n Dropping below the button instead makes the clearance independent of\n both the container width and the label's length — which matters\n because that label is TRANSLATED (\"Beenden\", \"Terminer\") while these\n offsets are fixed pixels. End occupies y=24..80 expanded (top-6 +\n h-14) and y=12..56 docked (top-3 + h-11); the column's own padding\n already starts content at 32 / 24, so these add the rest plus 8px.\n\n ★ NOT true of `mini`, where End, transcript and expand are ALL in the\n top band and this stays `px-3`. A notice there can still be painted\n over by those opaque buttons. Pre-existing and left alone: the strip is\n 180px tall and buying 32px of top padding would squeeze the stage. */}\n <div\n className={`flex flex-col items-center ${\n mini\n ? 'px-3'\n : // ★ The reserve is applied ONLY when there is something to clear.\n // `padding` is not subject to `min-h`, so an unconditional `pt-14`\n // would stand a permanent 56px column above an empty div and take\n // that height out of the `flex-1` stage on every session — paying\n // the cost of a warning that is not there.\n `min-h-[1.5rem] ${showNotice ? (expanded ? 'pt-14' : 'pt-10') : ''}`\n }`}\n >\n {showNotice ? (\n <p className=\"max-w-xs text-center text-xs text-status-warning\" data-testid=\"assistant-voice-notice\">\n {noticeMessage(notice, tr)}\n </p>\n ) : null}\n </div>\n\n {/* ★ Two genuinely different surfaces, not one scaled. Expanded is a\n reading stage; docked is a controller. */}\n {(() => {\n const orb = (\n <AssistantVoiceOrb\n session={session}\n compact={mini}\n connecting={stage === 'connecting'}\n onPress={micIsInterrupt(stage) ? onInterrupt : onToggleMute}\n label={\n micIsInterrupt(stage)\n ? tr('voiceSession.interrupt', 'Stop the assistant and speak')\n : muted\n ? tr('voiceSession.unmute', 'Turn the microphone on')\n : tr('voiceSession.mute', 'Turn the microphone off')\n }\n />\n );\n const caption = micIsInterrupt(stage) ? spoken : heard || null;\n const errorText = error !== null ? errorMessage(error, tr) : null;\n return !mini ? (\n <VoiceStage\n state={stage}\n userCaption={heard || null}\n spokenChunks={spokenChunks}\n assistantCaption={spoken}\n // ★ `expanded` — the JSX shorthand — means `expanded={true}`, not\n // `expanded={expanded}`. This branch serves BOTH the docked panel and\n // full screen, so the panel was being styled as full screen: the\n // full-screen caption measure and clamp applied in a column far\n // too narrow for them, and VoiceCaption's non-expanded branch became\n // unreachable code. The variable it shadowed is right there on line 90.\n expanded={expanded}\n statusText={status}\n errorText={errorText}\n control={orb}\n />\n ) : (\n <VoiceMiniController\n state={stage}\n caption={caption}\n statusText={status}\n errorText={errorText}\n control={orb}\n />\n );\n })()}\n\n {transcriptOpen ? (\n <VoiceTranscriptDrawer\n turns={turns}\n onClose={() => setTranscriptOpen(false)}\n onSave={onSaveTranscript}\n onContinueInChat={onContinueInChat}\n />\n ) : null}\n\n {/* ★ Attach — the SAME source menu the composer uses (Camera, Photos,\n Documents, Files), not a voice-only variant. A farmer standing in a\n field wanting to show a diseased leaf is the most likely attachment\n this product will ever see, and voice was the one surface that could\n not do it.\n\n Top-LEFT: End holds top-right, the transcript bottom-right, expand\n bottom-left.\n\n ★ Shown in `mini` too, at the one free slot (`left-11`, mirroring the\n transcript's `right-11`). It was hidden there on the reasoning that\n attaching deserves the full stage — but `view` initialises to `'mini'`,\n so that hid the control in the view EVERY session opens in. A feature\n reachable only by first tapping expand is a feature almost nobody\n finds. */}\n {onAttachFiles ? (\n <div className={`absolute ${expanded ? 'left-6 top-6' : mini ? 'left-11 top-2' : 'left-3 top-3'}`}>\n <AssistantAttachmentButton\n onFiles={(files) => {\n onAttachFiles(files);\n // ★ Leave `mini` on attach: the chips need room, and a photo the\n // user cannot see is one they will either forget or send twice.\n // Only ever grows the view — it never shrinks one they chose.\n setView((current) => (current === 'mini' ? 'panel' : current));\n }}\n onPickerOpen={handlePickerOpen}\n // DOWN: this control is anchored at the top of the panel, so the\n // composer's upward menu would open outside it and be unreachable.\n direction=\"down\"\n canAddMore={canAttachMore}\n />\n </div>\n ) : null}\n\n {/* Attached files, above the controls and clear of the corner buttons.\n Shown so a photo taken mid-session is visibly WAITING for the question\n about to be asked — an invisible attachment is one the user either\n forgets or sends twice. */}\n {(attachments.length > 0 || preparingAttachments > 0) && !mini ? (\n <div\n className={`absolute ${expanded ? 'bottom-24 left-24 right-24' : 'bottom-16 left-16 right-16'}`}\n data-testid=\"assistant-voice-attachments\"\n >\n <AssistantAttachmentChips\n attachments={attachments}\n onRemove={onRemoveAttachment ?? (() => undefined)}\n onRetry={onRetryAttachment ?? (() => undefined)}\n preparingCount={preparingAttachments}\n />\n </div>\n ) : null}\n\n {/* History is SECONDARY — behind a button, never on the stage. */}\n <button\n type=\"button\"\n onClick={() => setTranscriptOpen((open) => !open)}\n className={`absolute ${expanded ? 'bottom-6 right-6 size-14' : mini ? 'right-11 top-2 size-8' : 'bottom-3 right-3 size-11'} flex items-center justify-center rounded-full bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n aria-pressed={transcriptOpen}\n aria-label={tr('voiceSession.transcript', 'Voice transcript')}\n data-testid=\"assistant-voice-transcript-toggle\"\n >\n <ScrollText className={expanded ? 'size-6' : mini ? 'size-4' : 'size-5'} />\n </button>\n\n <button\n type=\"button\"\n onClick={() => setView(nextView)}\n className={`absolute ${expanded ? 'bottom-6 left-6 size-14' : mini ? 'left-2 top-2 size-8' : 'bottom-3 left-3 size-11'} flex items-center justify-center rounded-full bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n // Not a toggle any more, so `aria-pressed` would be a lie. The label\n // names where the button GOES, which is what a stepping control needs.\n aria-label={\n nextView === 'panel'\n ? tr('voiceSession.expandPanel', 'Show the conversation in the panel')\n : nextView === 'full'\n ? tr('voiceSession.expand', 'Expand the conversation to full screen')\n : tr('voiceSession.collapse', 'Shrink to the compact controller')\n }\n data-testid=\"assistant-voice-expand\"\n >\n {expanded ? <Minimize2 className=\"size-5\" /> : <Maximize2 className={mini ? 'size-4' : 'size-5'} />}\n </button>\n </div>\n );\n};\n\n/**\n * Recoverable problems, shown WITHOUT ending the session.\n *\n * The bug these exist for: the overlay said \"Listening…\" while the recogniser\n * was dead, and nothing anywhere said otherwise.\n */\nfunction noticeMessage(notice: VoiceSessionNotice, tr: ReturnType<typeof useAssistantTr>): string {\n switch (notice) {\n case 'network':\n return tr(\n 'voiceSession.noticeNetwork',\n 'Speech recognition lost its connection. Check your network — it will retry.'\n );\n case 'not-capturing':\n return tr(\n 'voiceSession.noticeNotCapturing',\n 'The microphone did not start. Check that this site is allowed to use it, then try again.'\n );\n case 'recognition-failed':\n return tr(\n 'voiceSession.noticeRecognitionFailed',\n 'Speech recognition stopped unexpectedly. It will retry — if it keeps happening, reload the page.'\n );\n case 'nothing-heard':\n return tr(\n 'voiceSession.noticeNothingHeard',\n 'Nothing heard yet. Check your microphone is not muted or in use by another app.'\n );\n default: {\n const unhandled: never = notice;\n return unhandled;\n }\n }\n}\n\n/**\n * Every failure is explained rather than silently closing the session.\n *\n * A session that just vanishes is the dead-button bug in another shape — the\n * exact defect BOFF-7106 had to fix on the per-message speak control.\n */\nfunction errorMessage(error: VoiceSessionError, tr: ReturnType<typeof useAssistantTr>): string {\n switch (error) {\n case 'mic-denied':\n return tr('voiceSession.micDenied', 'Microphone access is blocked. Allow it in your browser settings to talk.');\n case 'no-speech-support':\n return tr(\n 'voiceSession.noSpeechSupport',\n 'This browser cannot listen. Try a different browser, or type instead.'\n );\n case 'no-voice-support':\n return tr('voiceSession.noVoiceSupport', 'This device has no voice that can speak this language.');\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":";;;;;;;;;;;;;AA8EA,IAAa,KAAoC,EAC/C,YACA,WAAQ,CAAC,GACT,qBACA,qBACA,YAAS,MACT,WACA,gBACA,iBACA,iBAAc,CAAC,GACf,kBACA,uBACA,sBACA,oBAAgB,IAChB,0BAAuB,GACvB,mBAAe,MACf,UACA,gBAAY,IACZ,kBAAe,IACf,sBAAmB,SACf;CACJ,IAAM,IAAK,GAAe,GACpB,EAAE,WAAO,UAAO,aAAU,GAC1B,IAAS,EAA0B,IAAI,GACvC,IAAY,EAAuB,IAAI,GAyBvC,CAAC,GAAM,KAAW,EAAoB,MAAM,GAC5C,IAAW,MAAS,QACpB,IAAO,MAAS,QAChB,IAAsB,MAAS,SAAS,UAAU,MAAS,UAAU,SAAS,QAE9E,CAAC,GAAgB,KAAqB,EAAS,EAAK,GAsBpD,IAAkB,EAAO,EAAK,GAC9B,IAAgB,EAAO,CAAY;CACzC,EAAc,UAAU;CAExB,IAAM,KAAmB,QAAkB;EACrC,KAAS,EAAgB,WAazB,EAAY,CAAO,MACvB,EAAgB,UAAU,IAC1B,EAAc,QAAQ;CACxB,GAAG,CAAC,GAAO,CAAO,CAAC;CA6BnB,AA3BA,QAAgB;EACd,IAAM,UAAgB;GACf,EAAgB,YACrB,EAAgB,UAAU,IAC1B,EAAc,QAAQ;EACxB;EAEA,OADA,OAAO,iBAAiB,SAAS,CAAO,SAC3B;GAIX,AAHA,OAAO,oBAAoB,SAAS,CAAO,GAG3C,EAAgB,UAAU;EAC5B;CACF,GAAG,CAAC,CAAC,GAUL,QAAgB;EACd,EAAO,SAAS,MAAM;CACxB,GAAG,CAAC,CAAC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AA;GAC5F,CAAA;EACL;;AAET;AAQA,SAAS,EAAc,GAA4B,GAA+C;CAChG,QAAQ,GAAR;EACE,KAAK,WACH,OAAO,EACL,8BACA,6EACF;EACF,KAAK,iBACH,OAAO,EACL,mCACA,0FACF;EACF,KAAK,sBACH,OAAO,EACL,wCACA,kGACF;EACF,KAAK,iBACH,OAAO,EACL,mCACA,iFACF;EACF,SAEE,OAAO;CAEX;AACF;AAQA,SAAS,EAAa,GAA0B,GAA+C;CAC7F,QAAQ,GAAR;EACE,KAAK,cACH,OAAO,EAAG,0BAA0B,0EAA0E;EAChH,KAAK,qBACH,OAAO,EACL,gCACA,uEACF;EACF,KAAK,oBACH,OAAO,EAAG,+BAA+B,wDAAwD;EACnG,SAIE,OAAO;CAEX;AACF"}
@@ -1,2 +0,0 @@
1
- import { VoiceMiniController as e } from "@burdenoff/fe-libs/shared/assistant/ui/voice/VoiceMiniController";
2
- export { e as VoiceMiniController };
@@ -1,2 +0,0 @@
1
- import { VoiceStage as e } from "@burdenoff/fe-libs/shared/assistant/ui/voice/VoiceStage";
2
- export { e as VoiceStage };
@@ -1,2 +0,0 @@
1
- import { spokenSoFar as e } from "@burdenoff/fe-libs/shared/assistant/voice/voiceSession";
2
- export { e as spokenSoFar };
@@ -1,2 +0,0 @@
1
- import { micIsInterrupt as e, voiceStageState as t } from "@burdenoff/fe-libs/shared/assistant/voice/voiceStageState";
2
- export { e as micIsInterrupt, t as voiceStageState };