@burdenoff/microfe-healthybowl 2026.901.17 → 2026.902.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -198,7 +198,7 @@ var N = ({ visible: Ee = !0 }) => {
198
198
  await d(M, e, g, n, h, f, ae, v, void 0), o ||= ee;
199
199
  }
200
200
  let b = je([], l), oe = Date.now() + (De[f] ?? Oe), C = Date.now(), se = Date.now();
201
- for (; Date.now() < oe && (b = je(await c(M, e, g, n, v, 50), l), V(p, x, { content: Ae(b.content) }), !b.done);) Date.now() - C > 3e4 && (await a(M, e, g, 600, v).catch(() => void 0), C = Date.now()), await new Promise((e) => setTimeout(e, ge(Date.now() - se)));
201
+ for (; Date.now() < oe && (b = je(await c(M, e, g, n, v, 50, l), l), V(p, x, { content: Ae(b.content) }), !b.done);) Date.now() - C > 3e4 && (await a(M, e, g, 600, v).catch(() => void 0), C = Date.now()), await new Promise((e) => setTimeout(e, ge(Date.now() - se)));
202
202
  if (!b.done && f !== "vibe-plugins") throw Error("Assistant response timed out while streaming progress");
203
203
  let ce = f === "vibe-plugins" ? await s(M, e, g, n, v).catch(() => []) : void 0;
204
204
  if (b.done || (b = {
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantChatArea.js","names":[],"sources":["../../../src/components/assistant/AssistantChatArea.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState, type FC } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { findAssistantLanguage, resolveAssistantLanguage } from '@/config/assistantLanguages';\nimport { AssistantMessageList } from './AssistantMessageList';\nimport { AssistantApiCallsConsentDialog } from './AssistantApiCallsConsentDialog';\nimport { AssistantEmptyState } from './AssistantEmptyState';\nimport { AssistantComposer } from './composer/AssistantComposer';\nimport { AssistantVoiceSession } from './voice/AssistantVoiceSession';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useVoiceSession } from '../../hooks/useVoiceSession';\nimport { useAssistantApiAccess } from '@/hooks/useAssistantApiAccess';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport {\n checkAssistantAiCredits,\n createAssistantSandbox,\n createAssistantSession,\n extendAssistantSandboxTTL,\n findExistingSandbox,\n getAssistantArtifacts,\n getAssistantMessages,\n getAssistantSession,\n reportAssistantAiTokenUsage,\n sendAssistantPromptAsync,\n waitForAssistantServiceReady,\n waitForSandboxReady,\n type AssistantRawMessage,\n type AssistantSandboxAuthContext,\n} from '@/services/assistantApi';\nimport { getAssistantMedia } from '@burdenoff/fe-libs/shared/assistant';\nimport { gatherPageContext } from '@/utils/pageContext';\nimport { getOrganizationId, getWorkspaceId } from '@/utils/assistantContext';\nimport { dispatchAssistantQuotaExhausted, notifyAiCreditsUpdated } from '@/utils/aiCredits';\nimport { isQuotaExhaustedError } from '@/utils/quotaUtils';\nimport { buildPromptForMode } from '@/utils/assistantPrompt';\nimport {\n buildPromptParts,\n buildPromptWithAttachments,\n countInlineImageCandidates,\n countInlinedImageParts,\n toMessageAttachment,\n type AssistantAttachment,\n} from '@/utils/assistantAttachments';\nimport { isMultimodalBodyRejection, isRecoverableAssistantError } from '@/utils/assistantTransportErrors';\nimport { isTurnInFlight } from '@/utils/assistantTurnState';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { ASSISTANT_MODES } from '@/types/assistant';\nimport type { AssistantArtifact, AssistantConversationStatus, AssistantMode, Message } from '@/types/assistant';\nimport { pollDelayMs } from '../../utils/assistantPollSchedule';\nimport { toCaptionText } from '../../utils/captionText';\nimport { chatTurns, voiceMarker, voiceTurnsOnly } from '../../utils/voiceTurnVisibility';\nimport { createReadinessTracker } from '../../utils/sandboxReadiness';\n\n// How long the client streams progress before giving up on a turn. Chat replies\n// (general / api-calls) finish in seconds; a vibe-plugins build is a multi-step\n// pipeline (read docs → scaffold → bun install → bun build → checklist) that runs\n// for minutes, so it gets a much larger budget. The sandbox TTL is auto-extended\n// every 30s during the poll loop, so a longer budget never outlives the sandbox.\nconst STREAM_BUDGET_MS: Record<AssistantMode, number> = {\n general: 180_000,\n assistant: 180_000,\n 'api-calls': 180_000,\n 'vibe-plugins': 600_000,\n};\nconst DEFAULT_STREAM_BUDGET_MS = 180_000;\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n}\n\nfunction sanitizeAssistantResponse(response: string): string {\n return response\n .replace(/(Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/(X-Workspace-Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9._-]+\\.[A-Za-z0-9._-]+\\b/g, '[REDACTED_JWT]')\n .replace(/\\bsk-ant-[A-Za-z0-9-]+\\b/g, '[REDACTED_API_KEY]');\n}\n\nfunction getRawMessageCreatedAt(message: AssistantRawMessage): number {\n return message.info?.time?.created ?? 0;\n}\n\nfunction getAssistantText(parts: AssistantRawMessage['parts']): string {\n return (parts ?? [])\n .filter((part) => part.type === 'text' && typeof part.text === 'string')\n .map((part) => part.text?.trim() ?? '')\n .filter(Boolean)\n .join('\\n');\n}\n\nfunction getToolProgress(parts: AssistantRawMessage['parts']): string[] {\n return (parts ?? [])\n .filter((part) => part.type === 'tool' && part.tool)\n .map((part) => {\n const status = part.state?.status ?? 'running';\n const tool = part.tool ?? 'tool';\n if (status === 'completed') return `Completed: ${tool}`;\n if (status === 'failed') return `Failed: ${tool}`;\n return `Running: ${tool}`;\n });\n}\n\nfunction buildAssistantProgress(\n messages: AssistantRawMessage[],\n // The `created` timestamp (sandbox clock) of the newest message that already\n // existed in this session BEFORE the prompt was sent. This turn's reply is the\n // assistant message created strictly after it. Crucially this stays WITHIN the\n // sandbox clock domain: the previous code compared the sandbox-stamped\n // `created` against the browser wall-clock (Date#now), so a reply stamped at\n // prompt-time was silently dropped whenever the sandbox clock lagged the\n // browser — the turn then hung on \"Thinking...\" until the stream budget\n // elapsed. A sandbox-domain floor is immune to clock skew and correct for both\n // fresh and reused (per-conversation) sessions, with no message-window gap.\n priorNewestCreatedMs: number\n): {\n content: string;\n done: boolean;\n tokens?: { input: number; output: number };\n} {\n const relevant = messages\n .filter((message) => message.info?.role === 'assistant' && getRawMessageCreatedAt(message) > priorNewestCreatedMs)\n .sort((left, right) => getRawMessageCreatedAt(left) - getRawMessageCreatedAt(right));\n\n if (relevant.length === 0) {\n return { content: 'Thinking...', done: false };\n }\n\n const latest = relevant[relevant.length - 1]!;\n const text = getAssistantText(latest.parts);\n // Inbound image/file parts, rendered to markdown by the shared helper (which\n // escapes the label and allowlists the protocol — this is model output).\n // Without this, HealthyBowl — the one product that SENDS parts — could not\n // read one back: a media-bearing reply would never satisfy `done` and the\n // turn would poll to a false timeout.\n const media = getAssistantMedia(latest.parts);\n const toolProgress = getToolProgress(latest.parts);\n const content = [text, ...media, ...toolProgress].filter(Boolean).join('\\n\\n') || 'Thinking...';\n\n return {\n content,\n done: Boolean(latest.info?.time?.completed) && (Boolean(text) || media.length > 0 || toolProgress.length > 0),\n tokens: latest.info?.tokens,\n };\n}\n\nfunction getConversationStatusMessage(status: AssistantConversationStatus): string {\n switch (status) {\n case 'provisioning':\n return 'Starting assistant environment...';\n case 'connecting':\n return 'Connecting to assistant...';\n case 'streaming':\n return 'Thinking...';\n default:\n return '';\n }\n}\n\n/**\n * `visible` is false when the host HIDES the panel without unmounting it, which\n * is what the supported `visible` prop does. That distinction matters here: a\n * live voice session would otherwise keep the microphone open and the silence\n * timer running behind an invisible panel.\n */\ninterface AssistantChatAreaProps {\n visible?: boolean;\n}\n\nexport const AssistantChatArea: FC<AssistantChatAreaProps> = ({ visible = true }) => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken, userId } = useAuthToken();\n const { locale } = useI18n();\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n // The language the user chose to SPEAK, which is not necessarily the one the\n // interface is in — that is the whole point of the preference (BOFF-7108).\n // Named in ENGLISH deliberately: the preamble around it is English, so\n // \"Answer in Tamil.\" reads as an instruction, where a bare tag (\"ta\") invites\n // the model to answer *about* the code instead of *in* the language.\n const replyLanguageName = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale).english,\n [assistantLanguage, locale]\n );\n // A stored preference is a deliberate choice; `null` is only the interface\n // language standing in as a default. The directive treats the two differently\n // — see `buildLanguagePreamble`.\n //\n // Resolved, not merely non-null: a stale persisted code from a build that\n // offered more languages is DISCARDED by `resolveAssistantLanguage`, and\n // treating that discarded value as deliberate would tell the model the user\n // had chosen the interface language on purpose — suppressing the typed-language\n // override on the strength of a preference the selector does not even show.\n const languageIsExplicit = findAssistantLanguage(assistantLanguage) !== null;\n const replyLanguageCode = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale).code,\n [assistantLanguage, locale]\n );\n\n const {\n conversations,\n activeConversationId,\n mode,\n processingByConversationId,\n setMode,\n setConversationMode,\n setActiveConversation,\n createConversation,\n addMessage,\n updateMessage,\n patchMessage,\n setConversationProcessing,\n clearConversationProcessing,\n setBackendSessionId,\n clearBackendSessionId,\n setSandbox,\n clearSandbox,\n acknowledgeApiCalls,\n } = useAssistantStore();\n\n const activeConversation = conversations.find((conversation) => conversation.id === activeConversationId);\n const messages = activeConversation?.messages ?? [];\n const activeProcessing = activeConversationId ? processingByConversationId[activeConversationId] : undefined;\n // Only while the turn is genuinely in flight. `messageId` outlives the turn\n // (setConversationProcessing keeps it on 'complete'/'error'), so keying off it\n // alone left the transcript's aria-busy latched true forever and screen\n // readers stopped announcing new replies.\n const activeIsProcessing = isTurnInFlight(activeProcessing?.status);\n const activeStreamingMessageId = activeIsProcessing ? (activeProcessing?.messageId ?? null) : null;\n // The assistant message whose turn ended in an error — drives the Retry\n // affordance in the transcript.\n const failedMessageId = activeProcessing?.status === 'error' ? activeProcessing.messageId : null;\n\n // ── api-calls (write) mode gating ──────────────────────────────────\n // Only a global Owner/Admin may use api-calls (it mints an OAuth app under the\n // caller identity). Re-read the org scope every render (a cheap localStorage\n // read) so the admin gate reacts to an org switch without the panel\n // remounting; the value is a stable string, so useAssistantApiAccess only\n // re-fetches myRoles when the org actually changes. An empty scope simply\n // hides the mode (it could not provision the sandbox anyway).\n const apiCallsScopeId = getOrganizationId();\n const { canUseApiCalls, loading: apiAccessLoading } = useAssistantApiAccess(apiCallsScopeId);\n const availableModes = useMemo(\n () => ASSISTANT_MODES.filter((modeConfig) => !modeConfig.requiresAdmin || canUseApiCalls),\n [canUseApiCalls]\n );\n\n // Target mode awaiting the one-time consent dialog (null = dialog closed).\n const [pendingConsentMode, setPendingConsentMode] = useState<AssistantMode | null>(null);\n\n // Full attachment payload of the last send, kept so Retry can replay it\n // byte-for-byte (see handleRetry).\n const lastSentAttachmentsRef = useRef<Record<string, AssistantAttachment[]>>({});\n\n // Conversations with a turn already dispatched. Synchronous, unlike the store\n // — see the re-entry guard in handleSend for why that matters.\n /**\n * Per-sandbox record of \"last proven reachable\", so a warm sandbox is not\n * re-probed on every turn. Invalidated by any failure — see both catches.\n */\n const sandboxReadiness = useRef(createReadinessTracker());\n const inFlightSendsRef = useRef<Set<string>>(new Set());\n\n // If the active mode is no longer permitted — a non-admin with a persisted\n // api-calls mode, or the master flag turned off — fall back to the read-only\n // `assistant` mode (the default \"Ask\", available to everyone), but only AFTER\n // the role check resolves (so an admin's persisted api-calls mode isn't reset\n // during the brief loading window).\n useEffect(() => {\n if (apiAccessLoading) return;\n const activeModeConfig = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === mode);\n const blocked = !activeModeConfig || (activeModeConfig.requiresAdmin && !canUseApiCalls);\n if (blocked && mode !== 'assistant') {\n setMode('assistant');\n }\n }, [mode, canUseApiCalls, apiAccessLoading, setMode]);\n\n const updateConversationStage = useCallback(\n (conversationId: string, assistantMessageId: string, status: AssistantConversationStatus, content?: string) => {\n setConversationProcessing(conversationId, status, assistantMessageId, null);\n if (content) {\n updateMessage(conversationId, assistantMessageId, content);\n } else {\n updateMessage(conversationId, assistantMessageId, getConversationStatusMessage(status));\n }\n },\n [setConversationProcessing, updateMessage]\n );\n\n const ensureAssistantRuntime = useCallback(\n async (\n conversationId: string,\n assistantMessageId: string,\n currentMode: AssistantMode,\n workspaceId: string,\n authContext: AssistantSandboxAuthContext\n ): Promise<{ sandboxId: string; sessionId: string }> => {\n let currentSandboxId = useAssistantStore.getState().sandboxesByMode[currentMode]?.sandboxId ?? null;\n\n // Validate that a candidate sandbox (remembered locally or found running on\n // the server) is actually reachable before we reuse it. A sandbox can expire\n // (ttlSeconds) or have its backend pod reclaimed while still being briefly\n // reported RUNNING; proxying to such a dead pod fails with a terminal state\n // (\"Backend resource no longer exists\") or a permanent 502 cf-proxy timeout.\n // Returns true only when the in-sandbox agent responds; false means stale.\n const ensureSandboxReachable = async (candidateId: string): Promise<boolean> => {\n // ★ Skip a proof we already have. This ran two network waits before the\n // model saw the prompt on EVERY turn, including turns seconds after the\n // last one succeeded — a constant tax, felt most in voice where it sits\n // between the user finishing a sentence and hearing anything.\n //\n // Safe only because every failure path below invalidates: see the catch\n // here and the turn-level catch. A cache that were only ever written on\n // success would pin a dead sandbox and turn a recoverable error into a\n // loop.\n if (sandboxReadiness.current.isFresh(candidateId)) return true;\n try {\n await waitForSandboxReady(apollo, candidateId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, candidateId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n sandboxReadiness.current.markVerified(candidateId);\n return true;\n } catch {\n // Stale/expired sandbox — drop it so we provision a fresh one below\n // instead of surfacing \"Internal server error\" to the user.\n sandboxReadiness.current.invalidate(candidateId);\n return false;\n }\n };\n\n // 1) Try the locally-remembered sandbox, then 2) any running one on the\n // server. Each is only kept if it's actually reachable.\n if (currentSandboxId) {\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', 'Reusing assistant environment...');\n if (!(await ensureSandboxReachable(currentSandboxId))) {\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = null;\n }\n }\n\n if (!currentSandboxId) {\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Looking for existing environment...'\n );\n const existingId = await findExistingSandbox(apollo, workspaceId, currentMode, authContext);\n\n if (existingId) {\n setSandbox(currentMode, existingId, 'provisioning');\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Reusing assistant environment...'\n );\n if (await ensureSandboxReachable(existingId)) {\n currentSandboxId = existingId;\n } else {\n setSandbox(currentMode, null, 'provisioning');\n }\n }\n }\n\n // 3) No reusable, reachable sandbox — provision a fresh one.\n if (!currentSandboxId) {\n if (currentMode === 'api-calls' && !getAccessToken()) {\n throw new Error('API Calls mode requires an authenticated session. Please sign in again.');\n }\n\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Starting assistant environment...'\n );\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = await createAssistantSandbox(apollo, currentMode, workspaceId, authContext);\n\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n await waitForSandboxReady(apollo, currentSandboxId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, currentSandboxId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n }\n\n setSandbox(currentMode, currentSandboxId, 'running');\n\n let sessionId =\n useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n ?.backendSessionId ?? null;\n\n if (sessionId) {\n try {\n const session = await getAssistantSession(apollo, currentSandboxId, workspaceId, sessionId, authContext);\n if (session.mode !== currentMode) {\n throw new Error(`Session mode mismatch: expected ${currentMode}, received ${session.mode}`);\n }\n } catch {\n clearBackendSessionId(conversationId);\n sessionId = null;\n }\n }\n\n if (!sessionId) {\n updateConversationStage(conversationId, assistantMessageId, 'connecting', 'Preparing session...');\n const result = await createAssistantSession(apollo, currentSandboxId, workspaceId, currentMode, authContext);\n sessionId = result.sessionId;\n setBackendSessionId(conversationId, sessionId);\n }\n\n return {\n sandboxId: currentSandboxId,\n sessionId,\n };\n },\n [apollo, clearBackendSessionId, getAccessToken, setBackendSessionId, setSandbox, updateConversationStage]\n );\n\n const handleSend = useCallback(\n async (content: string, attachments: AssistantAttachment[] = [], options: { dictated?: boolean } = {}) => {\n // Only block re-entry while a turn is genuinely in-flight. Earlier code\n // checked for *any* entry in the map, which stuck around as `complete`\n // / `error` after the first turn — making every subsequent message\n // silently disappear (the input cleared but handleSend bailed before\n // adding the user message to the conversation).\n //\n // The store is read LIVE, and that is what makes the guard work. The\n // render-captured `processingByConversationId` is stale by construction —\n // the click that starts a turn and the click that must be rejected can\n // belong to the same render. Reading `activeConversationId` live matters\n // for the same reason: on two racing first-ever sends, the second must see\n // the conversation the first one created a moment ago.\n //\n // Pairs with the synchronous `setConversationProcessing` below: because\n // the status is written before this function ever awaits, a second call —\n // however soon it arrives — always observes 'provisioning'.\n const storeAtEntry = useAssistantStore.getState();\n const guardConversationId = storeAtEntry.activeConversationId ?? activeConversationId;\n if (guardConversationId) {\n if (isTurnInFlight(storeAtEntry.processingByConversationId[guardConversationId]?.status)) return;\n // Second lock, in case a future change moves the status write later:\n // this one cannot be cleared by anything but the turn's own `finally`.\n // Deliberately per-conversation — a global key would keep blocking\n // after the conversation it belonged to was deleted mid-turn, and then\n // silently swallow every subsequent send.\n if (inFlightSendsRef.current.has(guardConversationId)) return;\n }\n\n const selectedMode = storeAtEntry.mode;\n let conversationId = activeConversationId;\n const currentConversation = conversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n : undefined;\n\n if (!conversationId) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (\n currentConversation &&\n currentConversation.mode !== selectedMode &&\n (currentConversation.messages.length > 0 || currentConversation.backendSessionId)\n ) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (currentConversation && currentConversation.mode !== selectedMode) {\n setConversationMode(conversationId, selectedMode);\n }\n\n if (!conversationId) return;\n\n // Keyed by conversation: the ref outlives a conversation switch, and a\n // single global slot meant Retry in one thread replayed another thread's\n // photo onto it.\n lastSentAttachmentsRef.current[conversationId] = attachments;\n\n const workspaceId = getWorkspaceId();\n const authContext: AssistantSandboxAuthContext = {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n };\n\n const userMessage: Message = {\n id: generateId(),\n role: 'user',\n content,\n timestamp: new Date().toISOString(),\n // Slim descriptors only — the bubble re-resolves thumbnails from the\n // file id, so the persisted conversation stays small.\n // ★ `voice` marks a turn that happened in the live voice session, so the\n // chat panel can leave it out. Both surfaces share one conversation, so\n // without it every spoken exchange showed up in the typed thread.\n metadata: {\n ...(attachments.length ? { attachments: attachments.map(toMessageAttachment) } : {}),\n ...voiceMarker(options.dictated),\n },\n };\n addMessage(conversationId, userMessage);\n\n const assistantMessageId = generateId();\n addMessage(conversationId, {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n timestamp: new Date().toISOString(),\n // Stamped now, not read later: this is the language the reply is being\n // generated in, and the preference may have moved on by the time\n // somebody presses Listen.\n // Carries the voice marker too: a reply to a spoken question belongs to\n // the voice session, not to the typed thread.\n metadata: { lang: replyLanguageCode, ...voiceMarker(options.dictated) },\n });\n\n // Mark the turn in-flight in the STORE right now, synchronously.\n //\n // Until this line the first status write happened inside\n // `ensureAssistantRuntime`, i.e. one await later. During that window\n // `activeIsProcessing` was false and `failedMessageId` still pointed at\n // the PREVIOUS failure — so the composer stayed enabled and, worse, the\n // Retry button (which has no `disabled` of its own) stayed mounted and\n // clickable on top of a turn that had already started.\n //\n // Status only, deliberately no stage copy: `ensureAssistantRuntime` picks\n // the accurate wording a moment later (\"Reusing...\" vs \"Starting...\"), and\n // guessing here would flash the wrong one on every reused sandbox.\n setConversationProcessing(conversationId, 'provisioning', assistantMessageId, null);\n\n const applyAssistantResponse = (\n response: string,\n artifacts?: AssistantArtifact[],\n sessionId?: string,\n sandboxId?: string,\n // Our own hard-coded copy is English regardless of what the user picked.\n // Stamping it with their language makes playback read an English quota\n // message in a Tamil voice — Latin text cannot be script-detected, so\n // this metadata is trusted absolutely.\n lang: string = replyLanguageCode\n ) => {\n // `patchMessage` REPLACES metadata rather than merging it, so anything\n // omitted here is destroyed — which is how the turn-language stamp set\n // at creation was being wiped the moment the response completed,\n // silently undoing per-message language resolution. Always re-assert it.\n //\n // ★ The voice marker was being lost the same way, and it was worse: this\n // runs on every completed turn, and the reply is only handed to the voice\n // session AFTER it runs, so NO spoken answer could ever stay a voice\n // turn. Each one jumped into the typed thread — under a question that\n // had been correctly hidden, so chat showed orphaned answers — and\n // vanished from the transcript drawer at the same instant.\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n metadata: {\n lang,\n ...(artifacts?.length ? { artifacts } : {}),\n ...(artifacts?.length || sessionId || sandboxId ? { mode: selectedMode } : {}),\n ...(sessionId ? { sessionId } : {}),\n ...(sandboxId ? { sandboxId } : {}),\n ...voiceMarker(options.dictated),\n },\n });\n };\n\n const sendWithRealBackend = async (attempt: 1 | 2 = 1): Promise<void> => {\n // Set when this attempt had to re-send without the image bytes, so the\n // answer can say so rather than quietly reading as if the model looked.\n let imagesDropped = false;\n // Pre-flight AI-credit gate. The wspace gateway's @usage(checkQuota)\n // rejects with 429 QUOTA_EXHAUSTED when the monthly token budget is\n // depleted — block the send (don't provision a sandbox or dispatch the\n // prompt) and surface the upgrade dialog instead of a generic error.\n try {\n await checkAssistantAiCredits(apollo, workspaceId, authContext);\n } catch (creditError) {\n if (isQuotaExhaustedError(creditError)) {\n dispatchAssistantQuotaExhausted('ai-credits');\n applyAssistantResponse(\n \"You've run out of AI credits for this billing cycle. Upgrade your plan to keep chatting.\",\n undefined,\n undefined,\n undefined,\n 'en'\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n // The pre-flight gate exists ONLY to catch a genuine QUOTA_EXHAUSTED\n // rejection. Any other failure here is a transient fault in the\n // credit check itself — e.g. the usage subgraph's getUsageSummary /\n // checkAiCredits intermittently 500s (Postgres/Prisma blip) and the\n // gateway masks it as the opaque \"Unexpected error.\". That is NOT\n // proof the user is out of budget, so it must not abort an otherwise\n // valid send. Fail open and proceed: the wspace gateway's\n // @usage(checkQuota) on createSandbox still enforces the real budget\n // downstream (a truly over-quota caller is stopped there with a 429\n // that surfaces the upgrade dialog via the outer catch).\n console.warn(\n '[assistant] AI-credit pre-flight check failed with a non-quota error; proceeding — gateway @usage(checkQuota) still enforces the real budget downstream',\n creditError\n );\n }\n\n try {\n const { sandboxId, sessionId } = await ensureAssistantRuntime(\n conversationId,\n assistantMessageId,\n selectedMode,\n workspaceId,\n authContext\n );\n\n // Snapshot the newest message timestamp already present in this\n // (possibly reused) session BEFORE sending the prompt, so we can\n // recognise THIS turn's reply as the one created after it — never by\n // comparing the browser clock to the sandbox clock (see\n // buildAssistantProgress). The newest-N window always contains the\n // newest message, so this floor is exact regardless of conversation depth.\n const priorMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n ).catch((): AssistantRawMessage[] => []);\n const priorNewestCreatedMs = priorMessages.reduce(\n (newest, message) => Math.max(newest, getRawMessageCreatedAt(message)),\n 0\n );\n\n updateConversationStage(conversationId, assistantMessageId, 'streaming', 'Thinking...');\n // Two agent-only wrappers around the raw content, both invisible in\n // the bubble: the soft confirm-before-mutate guard for api-calls mode,\n // and the attachment block (metadata + URLs, with text-like files\n // inlined) that carries this turn's files to the model.\n // …and the language directive, so the reply comes back in the user's\n // language rather than defaulting to the language of the docs the\n // model grounds on. The FE is the only layer that knows the locale —\n // it is not on the wire and `pageContext` silently drops unknown keys.\n const promptText = buildPromptForMode(\n selectedMode,\n buildPromptWithAttachments(content, attachments),\n replyLanguageName,\n languageIsExplicit,\n options.dictated === true\n );\n // Structured multimodal parts carry the image PIXELS, which no amount\n // of prompt text can. Built from the same `promptText`, so a bridge\n // that ignores `parts` loses nothing; `undefined` for an ordinary text\n // turn keeps the wire body unchanged.\n const promptParts = buildPromptParts(promptText, attachments);\n const inlinedCount = countInlinedImageParts(promptParts);\n const carriesPixels = inlinedCount > 0;\n const pageContext = gatherPageContext();\n\n // `buildPromptParts` may have demoted a photo to a link to keep the\n // body under the gateway's cap — a long message can do that on prompt\n // text alone. That decision is invisible to the user unless we say so,\n // and an answer that reads as if the model looked at a photo it never\n // received is worse than a short note.\n imagesDropped = countInlineImageCandidates(attachments) > inlinedCount;\n\n try {\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n promptParts\n );\n } catch (sendError) {\n // `buildPromptParts` already sizes the PARTS to the gateway's cap\n // (the prompt string itself is not bounded here), so reaching this\n // point means something rejected the body anyway — a tighter proxy\n // than we modelled, or a bridge that will not take `parts` at all.\n // Losing the whole question over that is the worst outcome\n // available: re-send it text-only. Only for errors that provably\n // never reached the agent (see isMultimodalBodyRejection) — a blind\n // retry would ask the same question twice and bill it twice.\n //\n // Gated on `parts` existing at all, NOT on it carrying pixels: the\n // array duplicates the whole prompt in `parts[0]`, so a url-only\n // parts array is itself enough to push a long message over the cap.\n // `carriesPixels` only decides whether the user is told something\n // was lost.\n if (!promptParts || !isMultimodalBodyRejection(sendError)) throw sendError;\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n undefined\n );\n // Only claim a photo was lost if one actually was — a url-only\n // retry loses nothing the prompt block did not already carry.\n imagesDropped = imagesDropped || carriesPixels;\n }\n\n let result = buildAssistantProgress([], priorNewestCreatedMs);\n const timeoutAt = Date.now() + (STREAM_BUDGET_MS[selectedMode] ?? DEFAULT_STREAM_BUDGET_MS);\n let lastTtlExtensionAt = Date.now();\n\n const pollStartedAt = Date.now();\n while (Date.now() < timeoutAt) {\n const sessionMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n );\n\n result = buildAssistantProgress(sessionMessages, priorNewestCreatedMs);\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(result.content),\n });\n\n if (result.done) break;\n\n if (Date.now() - lastTtlExtensionAt > 30_000) {\n await extendAssistantSandboxTTL(apollo, sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n // Fast early, backing off after — see assistantPollSchedule. This is\n // the granularity of the whole turn: it bounds how late the answer\n // appears AND how late speech can start, because auto-speak only\n // fires once a poll observes the reply completed.\n await new Promise((resolve) => setTimeout(resolve, pollDelayMs(Date.now() - pollStartedAt)));\n }\n\n // For non-build modes a timeout is a hard failure. For vibe-plugins the\n // prompt runs async server-side (/sessions/:id/prompt-async) and keeps\n // writing artifacts after the poll budget elapses, so we surface whatever\n // it has produced instead of discarding the turn.\n if (!result.done && selectedMode !== 'vibe-plugins') {\n throw new Error('Assistant response timed out while streaming progress');\n }\n\n const artifacts =\n selectedMode === 'vibe-plugins'\n ? await getAssistantArtifacts(apollo, sandboxId, workspaceId, sessionId, authContext).catch(() => [])\n : undefined;\n\n if (!result.done) {\n // vibe-plugins build still running in the background. Append a note so\n // the user knows the answer is partial and the artifacts will finish.\n result = {\n ...result,\n content: `${result.content}\\n\\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`,\n };\n }\n\n if (imagesDropped) {\n // Said plainly, because the alternative is an answer that looks like\n // it examined a photo it never received.\n result = {\n ...result,\n content: `${result.content}\\n\\n${tr(\n 'healthybowl.assistant.attachments.imagesNotSent',\n '_Your photo was too large to include with this message, so the answer above is from the text and the file link only. Try a smaller or more tightly cropped photo._'\n )}`,\n };\n }\n\n applyAssistantResponse(result.content, artifacts, sessionId, sandboxId);\n\n if (result.tokens) {\n patchMessage(conversationId, assistantMessageId, { tokens: result.tokens });\n // Charge the real token usage against the AI-credits quota (the\n // gateway records it via @usage(trackUsage)). We AWAIT it before\n // marking the turn complete / re-enabling input: otherwise a rapid\n // follow-up send would run its pre-flight checkAiCredits against a\n // stale balance (this turn's charge still in flight) and could\n // dispatch a prompt that should have been blocked, letting fast\n // sends bypass the credit cap. Still best-effort — a charge failure\n // never blocks the displayed answer.\n try {\n await reportAssistantAiTokenUsage(apollo, workspaceId, sessionId, result.tokens, authContext);\n notifyAiCreditsUpdated();\n } catch {\n // ignore — server-side @usage tracking is the source of truth\n }\n }\n setConversationProcessing(conversationId, 'complete', assistantMessageId, null);\n } catch (error) {\n if (attempt === 1 && isRecoverableAssistantError(error)) {\n clearBackendSessionId(conversationId);\n clearSandbox(selectedMode);\n return sendWithRealBackend(2);\n }\n\n throw error;\n }\n };\n\n // Claim the slot immediately before the first await, and release it in\n // `finally` so every exit — success, quota return, thrown error — frees\n // it. Registering here rather than earlier means a synchronous throw in\n // the setup above can never strand a key and wedge the conversation.\n const turnConversationId = conversationId;\n inFlightSendsRef.current.add(turnConversationId);\n\n try {\n if (!workspaceId) {\n throw new Error('Assistant backend is unavailable without an active workspace context.');\n }\n await sendWithRealBackend();\n } catch (error) {\n // ★ Any failed turn drops the readiness proof for the sandbox it used,\n // so the NEXT turn re-probes instead of trusting a cache entry that a\n // dead pod would otherwise keep alive until the TTL lapsed. This is the\n // half that makes the short-circuit above safe.\n sandboxReadiness.current.invalidate(\n useAssistantStore.getState().sandboxesByMode[selectedMode]?.sandboxId ?? null\n );\n // A quota error reaching here is the sandbox-environment wall hit\n // during runtime provisioning (createSandbox @usage). Surface the\n // upgrade dialog instead of a generic failure (the AI-credit wall is\n // already handled by the pre-flight gate above).\n if (isQuotaExhaustedError(error)) {\n dispatchAssistantQuotaExhausted('sandbox');\n applyAssistantResponse(\n \"You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.\",\n undefined,\n undefined,\n undefined,\n 'en'\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n const errorMessage = error instanceof Error ? error.message : 'Something went wrong';\n setConversationProcessing(conversationId, 'error', assistantMessageId, errorMessage);\n // Same reason: English copy must not inherit the turn's language stamp.\n // The voice marker still has to survive though — a failed spoken turn\n // belongs to the session that asked. Without it the failure surfaced as\n // a bare \"Sorry, an error occurred\" in the typed thread with no question\n // above it, while the voice session showed nothing at all.\n patchMessage(conversationId, assistantMessageId, {\n content: `Sorry, an error occurred: ${errorMessage}. Please try again.`,\n metadata: { lang: 'en', ...voiceMarker(options.dictated) },\n });\n } finally {\n inFlightSendsRef.current.delete(turnConversationId);\n }\n },\n [\n activeConversationId,\n addMessage,\n apollo,\n clearBackendSessionId,\n clearSandbox,\n conversations,\n createConversation,\n ensureAssistantRuntime,\n getAccessToken,\n getWorkspaceToken,\n patchMessage,\n // Without this, switching language mid-conversation keeps sending the\n // previous language's directive until something else re-creates the\n // callback.\n languageIsExplicit,\n replyLanguageCode,\n replyLanguageName,\n setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n tr,\n updateConversationStage,\n userId,\n ]\n );\n\n const handleSuggestionClick = useCallback(\n (suggestion: string) => {\n void handleSend(suggestion);\n },\n [handleSend]\n );\n\n // Retry re-sends the most recent user prompt through the same transport — the\n // failed assistant turn stays in the transcript, a fresh one is appended.\n // The attachments come from the in-memory ref rather than the message\n // metadata: the persisted descriptors deliberately drop the inlined text of\n // text-like files, so rebuilding from them would silently retry a WEAKER\n // prompt than the one that failed.\n const handleRetry = useCallback(() => {\n const lastUserMessage = [...messages].reverse().find((message) => message.role === 'user');\n const replay = activeConversationId ? (lastSentAttachmentsRef.current[activeConversationId] ?? []) : [];\n if (lastUserMessage) void handleSend(lastUserMessage.content, replay);\n }, [messages, handleSend, activeConversationId]);\n\n // Auto-send any prompt that was queued by `useOpenAssistantHelp` (from\n // the shared GetHelpButton). We keep the latest handleSend in a ref so\n // the subscription effect below doesn't need to tear down on every\n // render — the store subscription lives for the component lifetime and\n // always calls the freshest handler.\n const handleSendRef = useRef(handleSend);\n useEffect(() => {\n handleSendRef.current = handleSend;\n }, [handleSend]);\n\n /**\n * The newest assistant reply, as the voice session's advance signal.\n *\n * Keyed on the message ID rather than the text: two consecutive answers can be\n * word-for-word identical, and text alone would then never advance the second\n * turn.\n */\n const latestAssistantReply = useMemo(() => {\n // ★ Only once the turn is COMPLETE. While it is in flight the pending\n // assistant message is patched with progress text — 'Starting assistant\n // environment...', 'Thinking...' — and exposing that would make the voice\n // session consume the message id, enter `speaking` on a placeholder, and\n // then be unable to advance when the real answer replaced it.\n if (activeIsProcessing) return null;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (message?.role !== 'assistant') continue;\n // Tool-activity markup is stripped so the session captions and speaks the\n // answer, not the machinery that produced it.\n const text = parseToolActivity(message.content).text.trim();\n return text ? { id: message.id, text } : null;\n }\n return null;\n }, [messages, activeIsProcessing]);\n\n /**\n * The same reply, with its Markdown markers removed, for the on-screen caption.\n *\n * ★ Deliberately a SEPARATE memo rather than a change to the one above, whose\n * `text` is not just display: it is the echo reference the recogniser compares\n * against while the answer is being spoken, and the payload of the session's\n * `reply` dispatch. Stripping it there would silently shift what counts as an\n * echo of our own voice. The audio path keeps its own transform\n * (`toSpeakableText`) — the two want genuinely different output, which is why\n * they are two functions and not one.\n */\n const voiceCaption = useMemo(\n () => (latestAssistantReply ? toCaptionText(latestAssistantReply.text) : null),\n [latestAssistantReply]\n );\n\n /**\n * The last few exchanges, for the session's on-screen transcript.\n *\n * Voice turns already go through the normal send path, so they are ordinary\n * conversation messages — this only surfaces them INSIDE the session, which\n * is what makes a second question in the same session make sense.\n */\n /**\n * What the CHAT panel shows: everything that was not spoken.\n *\n * Voice and chat share one conversation, so without this split every spoken\n * exchange appeared in the typed thread.\n */\n const chatMessages = useMemo(() => chatTurns(messages), [messages]);\n\n const voiceTurns = useMemo(\n () =>\n // ★ Only turns from this voice session. It used to take the last six\n // messages of the WHOLE conversation, so opening voice on an existing\n // thread painted typed replies — the wall of raw `##` and `**` the\n // operator screenshotted, because the voice panel renders plain text.\n voiceTurnsOnly(messages)\n .filter((message) => message.role === 'user' || message.role === 'assistant')\n .map((message) => ({\n id: message.id,\n role: message.role as 'user' | 'assistant',\n text: parseToolActivity(message.content).text.trim(),\n }))\n .filter((turn) => turn.text.length > 0),\n [messages]\n );\n\n const submitVoiceTurn = useCallback((text: string) => {\n // ★ Only the voice SESSION is unambiguously dictated. The composer's\n // microphone also produces a transcript, but the user reads and edits it in\n // the box before sending, so treating that as dictated would tell the model\n // to second-guess words the user had already approved.\n void handleSendRef.current(text, [], { dictated: true });\n }, []);\n\n const voiceSession = useVoiceSession({\n onSubmit: submitVoiceTurn,\n latestReply: latestAssistantReply,\n // The language the user SPEAKS, not the interface language — the same\n // preference the composer's dictation and the reply language already use.\n language: resolveAssistantLanguage(assistantLanguage, locale).tag,\n });\n\n // Hiding the panel must end a live voice session. The host may set `visible`\n // false WITHOUT unmounting, and an unmount-only cleanup would then leave the\n // microphone recording behind an invisible panel — a privacy problem, not\n // just a leak.\n useEffect(() => {\n if (!visible && voiceSession.active) voiceSession.end();\n }, [visible, voiceSession]);\n\n useEffect(() => {\n // Flush any prompt that was queued before this component mounted.\n const initial = useAssistantStore.getState().consumePendingPrompt();\n if (initial) {\n void handleSendRef.current(initial);\n }\n\n // Watch for new prompts queued while we're already mounted.\n const unsubscribe = useAssistantStore.subscribe((state, prev) => {\n if (state.pendingPrompt && state.pendingPrompt !== prev.pendingPrompt) {\n const queued = useAssistantStore.getState().consumePendingPrompt();\n if (queued) {\n void handleSendRef.current(queued);\n }\n }\n });\n return unsubscribe;\n }, []);\n\n const performModeChange = useCallback(\n (newMode: AssistantMode) => {\n const currentConversation = activeConversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === activeConversationId)\n : undefined;\n\n if (currentConversation && (currentConversation.messages.length > 0 || currentConversation.backendSessionId)) {\n if (currentConversation.mode !== newMode) {\n const reusableDraft = useAssistantStore\n .getState()\n .conversations.find(\n (conversation) =>\n conversation.mode === newMode &&\n conversation.messages.length === 0 &&\n !conversation.backendSessionId &&\n !useAssistantStore.getState().processingByConversationId[conversation.id]\n );\n\n if (reusableDraft) {\n setActiveConversation(reusableDraft.id);\n } else {\n createConversation(undefined, newMode);\n }\n }\n } else if (activeConversationId) {\n setConversationMode(activeConversationId, newMode);\n }\n\n setMode(newMode);\n },\n [activeConversationId, createConversation, setActiveConversation, setConversationMode, setMode]\n );\n\n const handleModeChange = useCallback(\n (newMode: AssistantMode) => {\n const target = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === newMode);\n // Gate the FIRST switch into a write-capable mode behind the one-time\n // consent dialog — the dependable confirm-before-mutate guardrail.\n if (target?.writeCapable && !useAssistantStore.getState().apiCallsAcknowledged) {\n setPendingConsentMode(newMode);\n return;\n }\n performModeChange(newMode);\n },\n [performModeChange]\n );\n\n const handleConsentConfirm = useCallback(() => {\n const target = pendingConsentMode;\n setPendingConsentMode(null);\n acknowledgeApiCalls();\n if (target) performModeChange(target);\n }, [pendingConsentMode, acknowledgeApiCalls, performModeChange]);\n\n const handleConsentCancel = useCallback(() => {\n setPendingConsentMode(null);\n }, []);\n\n return (\n // `relative` so the DOCKED voice session can position itself against the\n // assistant panel rather than the viewport. Without it the docked overlay\n // would anchor to the page and cover the whole app, which is the very thing\n // docking exists to avoid.\n <div className=\"relative flex flex-1 flex-col overflow-hidden\">\n {/* Everything the voice overlay covers is made `inert` while a session is\n open. Docked, the overlay hides the transcript and composer but does\n NOT cover the page, so a full focus trap would wrongly imprison the\n user — yet leaving these focusable lets them Shift+Tab into controls\n they cannot see and operate them blind. `inert` is the precise tool:\n the page stays reachable, the covered controls do not. */}\n <div className=\"contents\" inert={voiceSession.active || undefined}>\n {/* Transcript is always visible now — the old collapse-by-default accordion\n is gone; conversation history lives behind the header button instead. */}\n {chatMessages.length === 0 ? (\n <AssistantEmptyState mode={mode} onSuggestionClick={handleSuggestionClick} />\n ) : (\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <AssistantMessageList\n messages={chatMessages}\n streamingMessageId={activeStreamingMessageId}\n failedMessageId={failedMessageId}\n onRetry={handleRetry}\n />\n </div>\n )}\n\n <AssistantComposer\n // ★ Ask-mode only, and enforced here rather than merely documented.\n // In `api-calls` mode the assistant WRITES to farm data behind a consent\n // gate, and BOFF-6377 (\"confirm-before-write cannot prove a human\n // approved\") is still open — a spoken \"yes, do it\" is exactly the case\n // that ticket is about. Voice control of writes is the NEXT phase, not\n // this one, so the launcher is simply absent in that mode.\n onStartVoiceSession={voiceSession.available && mode !== 'api-calls' ? voiceSession.start : undefined}\n onSend={(value, attachments) => void handleSend(value, attachments)}\n disabled={activeIsProcessing}\n placeholder={\n mode === 'api-calls'\n ? tr('healthybowl.assistant.chatArea.placeholderActions', 'What would you like me to do?')\n : tr('healthybowl.assistant.chatArea.placeholderGeneral', 'Ask HealthyBowl anything…')\n }\n mode={mode}\n availableModes={availableModes}\n onModeChange={handleModeChange}\n />\n </div>\n\n {voiceSession.active && (\n <AssistantVoiceSession\n session={voiceSession.session}\n notice={voiceSession.notice}\n capturing={voiceSession.capturing}\n interrupting={voiceSession.interrupting}\n awaitingEndpoint={voiceSession.awaitingEndpoint}\n turns={voiceTurns}\n onInterrupt={voiceSession.interrupt}\n spoken={voiceCaption}\n onToggleMute={voiceSession.toggleMute}\n onEnd={voiceSession.end}\n />\n )}\n\n <AssistantApiCallsConsentDialog\n open={pendingConsentMode !== null}\n onConfirm={handleConsentConfirm}\n onCancel={handleConsentCancel}\n />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,IAAM,KAAkD;CACtD,SAAS;CACT,WAAW;CACX,aAAa;CACb,gBAAgB;AAClB,GACM,KAA2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ChB,KAAQ,GAAkB,CAAM;CACtC,GAAG;EAAC;EAAoB;EAAqB;CAAiB,CAAC,GAEzD,KAAsB,QAAkB;EAC5C,GAAsB,IAAI;CAC5B,GAAG,CAAC,CAAC;CAEL,OAKE,mBAAC,OAAD;EAAK,WAAU;YAAf;GAOE,mBAAC,OAAD;IAAK,WAAU;IAAW,OAAO,EAAa,UAAU,KAAA;cAAxD,CAGG,GAAa,WAAW,IACvB,kBAAC,IAAD;KAA2B;KAAM,mBAAmB;IAAwB,CAAA,IAE5E,kBAAC,OAAD;KAAK,WAAU;eACb,kBAAC,GAAD;MACE,UAAU;MACV,oBAAoB;MACH;MACjB,SAAS;KACV,CAAA;IACE,CAAA,GAGP,kBAAC,GAAD;KAOE,qBAAqB,EAAa,aAAa,MAAS,cAAc,EAAa,QAAQ,KAAA;KAC3F,SAAS,GAAO,MAAgB,KAAK,EAAW,GAAO,CAAW;KAClE,UAAU;KACV,aACE,MAAS,cACL,EAAG,qDAAqD,+BAA+B,IACvF,EAAG,qDAAqD,2BAA2B;KAEnF;KACU;KAChB,cAAc;IACf,CAAA,CACE;;GAEJ,EAAa,UACZ,kBAAC,IAAD;IACE,SAAS,EAAa;IACtB,QAAQ,EAAa;IACrB,WAAW,EAAa;IACxB,cAAc,EAAa;IAC3B,kBAAkB,EAAa;IAC/B,OAAO;IACP,aAAa,EAAa;IAC1B,QAAQ;IACR,cAAc,EAAa;IAC3B,OAAO,EAAa;GACrB,CAAA;GAGH,kBAAC,GAAD;IACE,MAAM,OAAuB;IAC7B,WAAW;IACX,UAAU;GACX,CAAA;EACE;;AAET"}
1
+ {"version":3,"file":"AssistantChatArea.js","names":[],"sources":["../../../src/components/assistant/AssistantChatArea.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState, type FC } from 'react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { findAssistantLanguage, resolveAssistantLanguage } from '@/config/assistantLanguages';\nimport { AssistantMessageList } from './AssistantMessageList';\nimport { AssistantApiCallsConsentDialog } from './AssistantApiCallsConsentDialog';\nimport { AssistantEmptyState } from './AssistantEmptyState';\nimport { AssistantComposer } from './composer/AssistantComposer';\nimport { AssistantVoiceSession } from './voice/AssistantVoiceSession';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useVoiceSession } from '../../hooks/useVoiceSession';\nimport { useAssistantApiAccess } from '@/hooks/useAssistantApiAccess';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport {\n checkAssistantAiCredits,\n createAssistantSandbox,\n createAssistantSession,\n extendAssistantSandboxTTL,\n findExistingSandbox,\n getAssistantArtifacts,\n getAssistantMessages,\n getAssistantSession,\n reportAssistantAiTokenUsage,\n sendAssistantPromptAsync,\n waitForAssistantServiceReady,\n waitForSandboxReady,\n type AssistantRawMessage,\n type AssistantSandboxAuthContext,\n} from '@/services/assistantApi';\nimport { getAssistantMedia } from '@burdenoff/fe-libs/shared/assistant';\nimport { gatherPageContext } from '@/utils/pageContext';\nimport { getOrganizationId, getWorkspaceId } from '@/utils/assistantContext';\nimport { dispatchAssistantQuotaExhausted, notifyAiCreditsUpdated } from '@/utils/aiCredits';\nimport { isQuotaExhaustedError } from '@/utils/quotaUtils';\nimport { buildPromptForMode } from '@/utils/assistantPrompt';\nimport {\n buildPromptParts,\n buildPromptWithAttachments,\n countInlineImageCandidates,\n countInlinedImageParts,\n toMessageAttachment,\n type AssistantAttachment,\n} from '@/utils/assistantAttachments';\nimport { isMultimodalBodyRejection, isRecoverableAssistantError } from '@/utils/assistantTransportErrors';\nimport { isTurnInFlight } from '@/utils/assistantTurnState';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { ASSISTANT_MODES } from '@/types/assistant';\nimport type { AssistantArtifact, AssistantConversationStatus, AssistantMode, Message } from '@/types/assistant';\nimport { pollDelayMs } from '../../utils/assistantPollSchedule';\nimport { toCaptionText } from '../../utils/captionText';\nimport { chatTurns, voiceMarker, voiceTurnsOnly } from '../../utils/voiceTurnVisibility';\nimport { createReadinessTracker } from '../../utils/sandboxReadiness';\n\n// How long the client streams progress before giving up on a turn. Chat replies\n// (general / api-calls) finish in seconds; a vibe-plugins build is a multi-step\n// pipeline (read docs → scaffold → bun install → bun build → checklist) that runs\n// for minutes, so it gets a much larger budget. The sandbox TTL is auto-extended\n// every 30s during the poll loop, so a longer budget never outlives the sandbox.\nconst STREAM_BUDGET_MS: Record<AssistantMode, number> = {\n general: 180_000,\n assistant: 180_000,\n 'api-calls': 180_000,\n 'vibe-plugins': 600_000,\n};\nconst DEFAULT_STREAM_BUDGET_MS = 180_000;\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;\n}\n\nfunction sanitizeAssistantResponse(response: string): string {\n return response\n .replace(/(Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/(X-Workspace-Authorization\\s*:\\s*Bearer\\s+)[^\\s\\n]+/gi, '$1[REDACTED]')\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9._-]+\\.[A-Za-z0-9._-]+\\b/g, '[REDACTED_JWT]')\n .replace(/\\bsk-ant-[A-Za-z0-9-]+\\b/g, '[REDACTED_API_KEY]');\n}\n\nfunction getRawMessageCreatedAt(message: AssistantRawMessage): number {\n return message.info?.time?.created ?? 0;\n}\n\nfunction getAssistantText(parts: AssistantRawMessage['parts']): string {\n return (parts ?? [])\n .filter((part) => part.type === 'text' && typeof part.text === 'string')\n .map((part) => part.text?.trim() ?? '')\n .filter(Boolean)\n .join('\\n');\n}\n\nfunction getToolProgress(parts: AssistantRawMessage['parts']): string[] {\n return (parts ?? [])\n .filter((part) => part.type === 'tool' && part.tool)\n .map((part) => {\n const status = part.state?.status ?? 'running';\n const tool = part.tool ?? 'tool';\n if (status === 'completed') return `Completed: ${tool}`;\n if (status === 'failed') return `Failed: ${tool}`;\n return `Running: ${tool}`;\n });\n}\n\nfunction buildAssistantProgress(\n messages: AssistantRawMessage[],\n // The `created` timestamp (sandbox clock) of the newest message that already\n // existed in this session BEFORE the prompt was sent. This turn's reply is the\n // assistant message created strictly after it. Crucially this stays WITHIN the\n // sandbox clock domain: the previous code compared the sandbox-stamped\n // `created` against the browser wall-clock (Date#now), so a reply stamped at\n // prompt-time was silently dropped whenever the sandbox clock lagged the\n // browser — the turn then hung on \"Thinking...\" until the stream budget\n // elapsed. A sandbox-domain floor is immune to clock skew and correct for both\n // fresh and reused (per-conversation) sessions, with no message-window gap.\n priorNewestCreatedMs: number\n): {\n content: string;\n done: boolean;\n tokens?: { input: number; output: number };\n} {\n const relevant = messages\n .filter((message) => message.info?.role === 'assistant' && getRawMessageCreatedAt(message) > priorNewestCreatedMs)\n .sort((left, right) => getRawMessageCreatedAt(left) - getRawMessageCreatedAt(right));\n\n if (relevant.length === 0) {\n return { content: 'Thinking...', done: false };\n }\n\n const latest = relevant[relevant.length - 1]!;\n const text = getAssistantText(latest.parts);\n // Inbound image/file parts, rendered to markdown by the shared helper (which\n // escapes the label and allowlists the protocol — this is model output).\n // Without this, HealthyBowl — the one product that SENDS parts — could not\n // read one back: a media-bearing reply would never satisfy `done` and the\n // turn would poll to a false timeout.\n const media = getAssistantMedia(latest.parts);\n const toolProgress = getToolProgress(latest.parts);\n const content = [text, ...media, ...toolProgress].filter(Boolean).join('\\n\\n') || 'Thinking...';\n\n return {\n content,\n done: Boolean(latest.info?.time?.completed) && (Boolean(text) || media.length > 0 || toolProgress.length > 0),\n tokens: latest.info?.tokens,\n };\n}\n\nfunction getConversationStatusMessage(status: AssistantConversationStatus): string {\n switch (status) {\n case 'provisioning':\n return 'Starting assistant environment...';\n case 'connecting':\n return 'Connecting to assistant...';\n case 'streaming':\n return 'Thinking...';\n default:\n return '';\n }\n}\n\n/**\n * `visible` is false when the host HIDES the panel without unmounting it, which\n * is what the supported `visible` prop does. That distinction matters here: a\n * live voice session would otherwise keep the microphone open and the silence\n * timer running behind an invisible panel.\n */\ninterface AssistantChatAreaProps {\n visible?: boolean;\n}\n\nexport const AssistantChatArea: FC<AssistantChatAreaProps> = ({ visible = true }) => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken, userId } = useAuthToken();\n const { locale } = useI18n();\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n // The language the user chose to SPEAK, which is not necessarily the one the\n // interface is in — that is the whole point of the preference (BOFF-7108).\n // Named in ENGLISH deliberately: the preamble around it is English, so\n // \"Answer in Tamil.\" reads as an instruction, where a bare tag (\"ta\") invites\n // the model to answer *about* the code instead of *in* the language.\n const replyLanguageName = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale).english,\n [assistantLanguage, locale]\n );\n // A stored preference is a deliberate choice; `null` is only the interface\n // language standing in as a default. The directive treats the two differently\n // — see `buildLanguagePreamble`.\n //\n // Resolved, not merely non-null: a stale persisted code from a build that\n // offered more languages is DISCARDED by `resolveAssistantLanguage`, and\n // treating that discarded value as deliberate would tell the model the user\n // had chosen the interface language on purpose — suppressing the typed-language\n // override on the strength of a preference the selector does not even show.\n const languageIsExplicit = findAssistantLanguage(assistantLanguage) !== null;\n const replyLanguageCode = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale).code,\n [assistantLanguage, locale]\n );\n\n const {\n conversations,\n activeConversationId,\n mode,\n processingByConversationId,\n setMode,\n setConversationMode,\n setActiveConversation,\n createConversation,\n addMessage,\n updateMessage,\n patchMessage,\n setConversationProcessing,\n clearConversationProcessing,\n setBackendSessionId,\n clearBackendSessionId,\n setSandbox,\n clearSandbox,\n acknowledgeApiCalls,\n } = useAssistantStore();\n\n const activeConversation = conversations.find((conversation) => conversation.id === activeConversationId);\n const messages = activeConversation?.messages ?? [];\n const activeProcessing = activeConversationId ? processingByConversationId[activeConversationId] : undefined;\n // Only while the turn is genuinely in flight. `messageId` outlives the turn\n // (setConversationProcessing keeps it on 'complete'/'error'), so keying off it\n // alone left the transcript's aria-busy latched true forever and screen\n // readers stopped announcing new replies.\n const activeIsProcessing = isTurnInFlight(activeProcessing?.status);\n const activeStreamingMessageId = activeIsProcessing ? (activeProcessing?.messageId ?? null) : null;\n // The assistant message whose turn ended in an error — drives the Retry\n // affordance in the transcript.\n const failedMessageId = activeProcessing?.status === 'error' ? activeProcessing.messageId : null;\n\n // ── api-calls (write) mode gating ──────────────────────────────────\n // Only a global Owner/Admin may use api-calls (it mints an OAuth app under the\n // caller identity). Re-read the org scope every render (a cheap localStorage\n // read) so the admin gate reacts to an org switch without the panel\n // remounting; the value is a stable string, so useAssistantApiAccess only\n // re-fetches myRoles when the org actually changes. An empty scope simply\n // hides the mode (it could not provision the sandbox anyway).\n const apiCallsScopeId = getOrganizationId();\n const { canUseApiCalls, loading: apiAccessLoading } = useAssistantApiAccess(apiCallsScopeId);\n const availableModes = useMemo(\n () => ASSISTANT_MODES.filter((modeConfig) => !modeConfig.requiresAdmin || canUseApiCalls),\n [canUseApiCalls]\n );\n\n // Target mode awaiting the one-time consent dialog (null = dialog closed).\n const [pendingConsentMode, setPendingConsentMode] = useState<AssistantMode | null>(null);\n\n // Full attachment payload of the last send, kept so Retry can replay it\n // byte-for-byte (see handleRetry).\n const lastSentAttachmentsRef = useRef<Record<string, AssistantAttachment[]>>({});\n\n // Conversations with a turn already dispatched. Synchronous, unlike the store\n // — see the re-entry guard in handleSend for why that matters.\n /**\n * Per-sandbox record of \"last proven reachable\", so a warm sandbox is not\n * re-probed on every turn. Invalidated by any failure — see both catches.\n */\n const sandboxReadiness = useRef(createReadinessTracker());\n const inFlightSendsRef = useRef<Set<string>>(new Set());\n\n // If the active mode is no longer permitted — a non-admin with a persisted\n // api-calls mode, or the master flag turned off — fall back to the read-only\n // `assistant` mode (the default \"Ask\", available to everyone), but only AFTER\n // the role check resolves (so an admin's persisted api-calls mode isn't reset\n // during the brief loading window).\n useEffect(() => {\n if (apiAccessLoading) return;\n const activeModeConfig = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === mode);\n const blocked = !activeModeConfig || (activeModeConfig.requiresAdmin && !canUseApiCalls);\n if (blocked && mode !== 'assistant') {\n setMode('assistant');\n }\n }, [mode, canUseApiCalls, apiAccessLoading, setMode]);\n\n const updateConversationStage = useCallback(\n (conversationId: string, assistantMessageId: string, status: AssistantConversationStatus, content?: string) => {\n setConversationProcessing(conversationId, status, assistantMessageId, null);\n if (content) {\n updateMessage(conversationId, assistantMessageId, content);\n } else {\n updateMessage(conversationId, assistantMessageId, getConversationStatusMessage(status));\n }\n },\n [setConversationProcessing, updateMessage]\n );\n\n const ensureAssistantRuntime = useCallback(\n async (\n conversationId: string,\n assistantMessageId: string,\n currentMode: AssistantMode,\n workspaceId: string,\n authContext: AssistantSandboxAuthContext\n ): Promise<{ sandboxId: string; sessionId: string }> => {\n let currentSandboxId = useAssistantStore.getState().sandboxesByMode[currentMode]?.sandboxId ?? null;\n\n // Validate that a candidate sandbox (remembered locally or found running on\n // the server) is actually reachable before we reuse it. A sandbox can expire\n // (ttlSeconds) or have its backend pod reclaimed while still being briefly\n // reported RUNNING; proxying to such a dead pod fails with a terminal state\n // (\"Backend resource no longer exists\") or a permanent 502 cf-proxy timeout.\n // Returns true only when the in-sandbox agent responds; false means stale.\n const ensureSandboxReachable = async (candidateId: string): Promise<boolean> => {\n // ★ Skip a proof we already have. This ran two network waits before the\n // model saw the prompt on EVERY turn, including turns seconds after the\n // last one succeeded — a constant tax, felt most in voice where it sits\n // between the user finishing a sentence and hearing anything.\n //\n // Safe only because every failure path below invalidates: see the catch\n // here and the turn-level catch. A cache that were only ever written on\n // success would pin a dead sandbox and turn a recoverable error into a\n // loop.\n if (sandboxReadiness.current.isFresh(candidateId)) return true;\n try {\n await waitForSandboxReady(apollo, candidateId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, candidateId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n sandboxReadiness.current.markVerified(candidateId);\n return true;\n } catch {\n // Stale/expired sandbox — drop it so we provision a fresh one below\n // instead of surfacing \"Internal server error\" to the user.\n sandboxReadiness.current.invalidate(candidateId);\n return false;\n }\n };\n\n // 1) Try the locally-remembered sandbox, then 2) any running one on the\n // server. Each is only kept if it's actually reachable.\n if (currentSandboxId) {\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', 'Reusing assistant environment...');\n if (!(await ensureSandboxReachable(currentSandboxId))) {\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = null;\n }\n }\n\n if (!currentSandboxId) {\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Looking for existing environment...'\n );\n const existingId = await findExistingSandbox(apollo, workspaceId, currentMode, authContext);\n\n if (existingId) {\n setSandbox(currentMode, existingId, 'provisioning');\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Reusing assistant environment...'\n );\n if (await ensureSandboxReachable(existingId)) {\n currentSandboxId = existingId;\n } else {\n setSandbox(currentMode, null, 'provisioning');\n }\n }\n }\n\n // 3) No reusable, reachable sandbox — provision a fresh one.\n if (!currentSandboxId) {\n if (currentMode === 'api-calls' && !getAccessToken()) {\n throw new Error('API Calls mode requires an authenticated session. Please sign in again.');\n }\n\n updateConversationStage(\n conversationId,\n assistantMessageId,\n 'provisioning',\n 'Starting assistant environment...'\n );\n setSandbox(currentMode, null, 'provisioning');\n currentSandboxId = await createAssistantSandbox(apollo, currentMode, workspaceId, authContext);\n\n setSandbox(currentMode, currentSandboxId, 'provisioning');\n await waitForSandboxReady(apollo, currentSandboxId, workspaceId, authContext, 300_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'provisioning', message)\n );\n await waitForAssistantServiceReady(apollo, currentSandboxId, workspaceId, authContext, 90_000, (message) =>\n updateConversationStage(conversationId, assistantMessageId, 'connecting', message)\n );\n }\n\n setSandbox(currentMode, currentSandboxId, 'running');\n\n let sessionId =\n useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n ?.backendSessionId ?? null;\n\n if (sessionId) {\n try {\n const session = await getAssistantSession(apollo, currentSandboxId, workspaceId, sessionId, authContext);\n if (session.mode !== currentMode) {\n throw new Error(`Session mode mismatch: expected ${currentMode}, received ${session.mode}`);\n }\n } catch {\n clearBackendSessionId(conversationId);\n sessionId = null;\n }\n }\n\n if (!sessionId) {\n updateConversationStage(conversationId, assistantMessageId, 'connecting', 'Preparing session...');\n const result = await createAssistantSession(apollo, currentSandboxId, workspaceId, currentMode, authContext);\n sessionId = result.sessionId;\n setBackendSessionId(conversationId, sessionId);\n }\n\n return {\n sandboxId: currentSandboxId,\n sessionId,\n };\n },\n [apollo, clearBackendSessionId, getAccessToken, setBackendSessionId, setSandbox, updateConversationStage]\n );\n\n const handleSend = useCallback(\n async (content: string, attachments: AssistantAttachment[] = [], options: { dictated?: boolean } = {}) => {\n // Only block re-entry while a turn is genuinely in-flight. Earlier code\n // checked for *any* entry in the map, which stuck around as `complete`\n // / `error` after the first turn — making every subsequent message\n // silently disappear (the input cleared but handleSend bailed before\n // adding the user message to the conversation).\n //\n // The store is read LIVE, and that is what makes the guard work. The\n // render-captured `processingByConversationId` is stale by construction —\n // the click that starts a turn and the click that must be rejected can\n // belong to the same render. Reading `activeConversationId` live matters\n // for the same reason: on two racing first-ever sends, the second must see\n // the conversation the first one created a moment ago.\n //\n // Pairs with the synchronous `setConversationProcessing` below: because\n // the status is written before this function ever awaits, a second call —\n // however soon it arrives — always observes 'provisioning'.\n const storeAtEntry = useAssistantStore.getState();\n const guardConversationId = storeAtEntry.activeConversationId ?? activeConversationId;\n if (guardConversationId) {\n if (isTurnInFlight(storeAtEntry.processingByConversationId[guardConversationId]?.status)) return;\n // Second lock, in case a future change moves the status write later:\n // this one cannot be cleared by anything but the turn's own `finally`.\n // Deliberately per-conversation — a global key would keep blocking\n // after the conversation it belonged to was deleted mid-turn, and then\n // silently swallow every subsequent send.\n if (inFlightSendsRef.current.has(guardConversationId)) return;\n }\n\n const selectedMode = storeAtEntry.mode;\n let conversationId = activeConversationId;\n const currentConversation = conversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === conversationId)\n : undefined;\n\n if (!conversationId) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (\n currentConversation &&\n currentConversation.mode !== selectedMode &&\n (currentConversation.messages.length > 0 || currentConversation.backendSessionId)\n ) {\n conversationId = createConversation(undefined, selectedMode);\n } else if (currentConversation && currentConversation.mode !== selectedMode) {\n setConversationMode(conversationId, selectedMode);\n }\n\n if (!conversationId) return;\n\n // Keyed by conversation: the ref outlives a conversation switch, and a\n // single global slot meant Retry in one thread replayed another thread's\n // photo onto it.\n lastSentAttachmentsRef.current[conversationId] = attachments;\n\n const workspaceId = getWorkspaceId();\n const authContext: AssistantSandboxAuthContext = {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n userId,\n organizationId: getOrganizationId(),\n };\n\n const userMessage: Message = {\n id: generateId(),\n role: 'user',\n content,\n timestamp: new Date().toISOString(),\n // Slim descriptors only — the bubble re-resolves thumbnails from the\n // file id, so the persisted conversation stays small.\n // ★ `voice` marks a turn that happened in the live voice session, so the\n // chat panel can leave it out. Both surfaces share one conversation, so\n // without it every spoken exchange showed up in the typed thread.\n metadata: {\n ...(attachments.length ? { attachments: attachments.map(toMessageAttachment) } : {}),\n ...voiceMarker(options.dictated),\n },\n };\n addMessage(conversationId, userMessage);\n\n const assistantMessageId = generateId();\n addMessage(conversationId, {\n id: assistantMessageId,\n role: 'assistant',\n content: '',\n timestamp: new Date().toISOString(),\n // Stamped now, not read later: this is the language the reply is being\n // generated in, and the preference may have moved on by the time\n // somebody presses Listen.\n // Carries the voice marker too: a reply to a spoken question belongs to\n // the voice session, not to the typed thread.\n metadata: { lang: replyLanguageCode, ...voiceMarker(options.dictated) },\n });\n\n // Mark the turn in-flight in the STORE right now, synchronously.\n //\n // Until this line the first status write happened inside\n // `ensureAssistantRuntime`, i.e. one await later. During that window\n // `activeIsProcessing` was false and `failedMessageId` still pointed at\n // the PREVIOUS failure — so the composer stayed enabled and, worse, the\n // Retry button (which has no `disabled` of its own) stayed mounted and\n // clickable on top of a turn that had already started.\n //\n // Status only, deliberately no stage copy: `ensureAssistantRuntime` picks\n // the accurate wording a moment later (\"Reusing...\" vs \"Starting...\"), and\n // guessing here would flash the wrong one on every reused sandbox.\n setConversationProcessing(conversationId, 'provisioning', assistantMessageId, null);\n\n const applyAssistantResponse = (\n response: string,\n artifacts?: AssistantArtifact[],\n sessionId?: string,\n sandboxId?: string,\n // Our own hard-coded copy is English regardless of what the user picked.\n // Stamping it with their language makes playback read an English quota\n // message in a Tamil voice — Latin text cannot be script-detected, so\n // this metadata is trusted absolutely.\n lang: string = replyLanguageCode\n ) => {\n // `patchMessage` REPLACES metadata rather than merging it, so anything\n // omitted here is destroyed — which is how the turn-language stamp set\n // at creation was being wiped the moment the response completed,\n // silently undoing per-message language resolution. Always re-assert it.\n //\n // ★ The voice marker was being lost the same way, and it was worse: this\n // runs on every completed turn, and the reply is only handed to the voice\n // session AFTER it runs, so NO spoken answer could ever stay a voice\n // turn. Each one jumped into the typed thread — under a question that\n // had been correctly hidden, so chat showed orphaned answers — and\n // vanished from the transcript drawer at the same instant.\n patchMessage(conversationId, assistantMessageId, {\n content: sanitizeAssistantResponse(response),\n metadata: {\n lang,\n ...(artifacts?.length ? { artifacts } : {}),\n ...(artifacts?.length || sessionId || sandboxId ? { mode: selectedMode } : {}),\n ...(sessionId ? { sessionId } : {}),\n ...(sandboxId ? { sandboxId } : {}),\n ...voiceMarker(options.dictated),\n },\n });\n };\n\n const sendWithRealBackend = async (attempt: 1 | 2 = 1): Promise<void> => {\n // Set when this attempt had to re-send without the image bytes, so the\n // answer can say so rather than quietly reading as if the model looked.\n let imagesDropped = false;\n // Pre-flight AI-credit gate. The wspace gateway's @usage(checkQuota)\n // rejects with 429 QUOTA_EXHAUSTED when the monthly token budget is\n // depleted — block the send (don't provision a sandbox or dispatch the\n // prompt) and surface the upgrade dialog instead of a generic error.\n try {\n await checkAssistantAiCredits(apollo, workspaceId, authContext);\n } catch (creditError) {\n if (isQuotaExhaustedError(creditError)) {\n dispatchAssistantQuotaExhausted('ai-credits');\n applyAssistantResponse(\n \"You've run out of AI credits for this billing cycle. Upgrade your plan to keep chatting.\",\n undefined,\n undefined,\n undefined,\n 'en'\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n // The pre-flight gate exists ONLY to catch a genuine QUOTA_EXHAUSTED\n // rejection. Any other failure here is a transient fault in the\n // credit check itself — e.g. the usage subgraph's getUsageSummary /\n // checkAiCredits intermittently 500s (Postgres/Prisma blip) and the\n // gateway masks it as the opaque \"Unexpected error.\". That is NOT\n // proof the user is out of budget, so it must not abort an otherwise\n // valid send. Fail open and proceed: the wspace gateway's\n // @usage(checkQuota) on createSandbox still enforces the real budget\n // downstream (a truly over-quota caller is stopped there with a 429\n // that surfaces the upgrade dialog via the outer catch).\n console.warn(\n '[assistant] AI-credit pre-flight check failed with a non-quota error; proceeding — gateway @usage(checkQuota) still enforces the real budget downstream',\n creditError\n );\n }\n\n try {\n const { sandboxId, sessionId } = await ensureAssistantRuntime(\n conversationId,\n assistantMessageId,\n selectedMode,\n workspaceId,\n authContext\n );\n\n // Snapshot the newest message timestamp already present in this\n // (possibly reused) session BEFORE sending the prompt, so we can\n // recognise THIS turn's reply as the one created after it — never by\n // comparing the browser clock to the sandbox clock (see\n // buildAssistantProgress). The newest-N window always contains the\n // newest message, so this floor is exact regardless of conversation depth.\n const priorMessages = await getAssistantMessages(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n authContext,\n 50\n ).catch((): AssistantRawMessage[] => []);\n const priorNewestCreatedMs = priorMessages.reduce(\n (newest, message) => Math.max(newest, getRawMessageCreatedAt(message)),\n 0\n );\n\n updateConversationStage(conversationId, assistantMessageId, 'streaming', 'Thinking...');\n // Two agent-only wrappers around the raw content, both invisible in\n // the bubble: the soft confirm-before-mutate guard for api-calls mode,\n // and the attachment block (metadata + URLs, with text-like files\n // inlined) that carries this turn's files to the model.\n // …and the language directive, so the reply comes back in the user's\n // language rather than defaulting to the language of the docs the\n // model grounds on. The FE is the only layer that knows the locale —\n // it is not on the wire and `pageContext` silently drops unknown keys.\n const promptText = buildPromptForMode(\n selectedMode,\n buildPromptWithAttachments(content, attachments),\n replyLanguageName,\n languageIsExplicit,\n options.dictated === true\n );\n // Structured multimodal parts carry the image PIXELS, which no amount\n // of prompt text can. Built from the same `promptText`, so a bridge\n // that ignores `parts` loses nothing; `undefined` for an ordinary text\n // turn keeps the wire body unchanged.\n const promptParts = buildPromptParts(promptText, attachments);\n const inlinedCount = countInlinedImageParts(promptParts);\n const carriesPixels = inlinedCount > 0;\n const pageContext = gatherPageContext();\n\n // `buildPromptParts` may have demoted a photo to a link to keep the\n // body under the gateway's cap — a long message can do that on prompt\n // text alone. That decision is invisible to the user unless we say so,\n // and an answer that reads as if the model looked at a photo it never\n // received is worse than a short note.\n imagesDropped = countInlineImageCandidates(attachments) > inlinedCount;\n\n try {\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n promptParts\n );\n } catch (sendError) {\n // `buildPromptParts` already sizes the PARTS to the gateway's cap\n // (the prompt string itself is not bounded here), so reaching this\n // point means something rejected the body anyway — a tighter proxy\n // than we modelled, or a bridge that will not take `parts` at all.\n // Losing the whole question over that is the worst outcome\n // available: re-send it text-only. Only for errors that provably\n // never reached the agent (see isMultimodalBodyRejection) — a blind\n // retry would ask the same question twice and bill it twice.\n //\n // Gated on `parts` existing at all, NOT on it carrying pixels: the\n // array duplicates the whole prompt in `parts[0]`, so a url-only\n // parts array is itself enough to push a long message over the cap.\n // `carriesPixels` only decides whether the user is told something\n // was lost.\n if (!promptParts || !isMultimodalBodyRejection(sendError)) throw sendError;\n await sendAssistantPromptAsync(\n apollo,\n sandboxId,\n workspaceId,\n sessionId,\n promptText,\n selectedMode,\n pageContext,\n authContext,\n undefined\n );\n // Only claim a photo was lost if one actually was — a url-only\n // retry loses nothing the prompt block did not already carry.\n imagesDropped = imagesDropped || carriesPixels;\n }\n\n let result = buildAssistantProgress([], priorNewestCreatedMs);\n const timeoutAt = Date.now() + (STREAM_BUDGET_MS[selectedMode] ?? DEFAULT_STREAM_BUDGET_MS);\n let lastTtlExtensionAt = Date.now();\n\n const pollStartedAt = Date.now();\n while (Date.now() < timeoutAt) {\n // ★ 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 if (result.done) break;\n\n if (Date.now() - lastTtlExtensionAt > 30_000) {\n await extendAssistantSandboxTTL(apollo, sandboxId, workspaceId, 600, authContext).catch(() => undefined);\n lastTtlExtensionAt = Date.now();\n }\n\n // Fast early, backing off after — see assistantPollSchedule. This is\n // the granularity of the whole turn: it bounds how late the answer\n // appears AND how late speech can start, because auto-speak only\n // fires once a poll observes the reply completed.\n await new Promise((resolve) => setTimeout(resolve, pollDelayMs(Date.now() - pollStartedAt)));\n }\n\n // For non-build modes a timeout is a hard failure. For vibe-plugins the\n // prompt runs async server-side (/sessions/:id/prompt-async) and keeps\n // writing artifacts after the poll budget elapses, so we surface whatever\n // it has produced instead of discarding the turn.\n if (!result.done && selectedMode !== 'vibe-plugins') {\n throw new Error('Assistant response timed out while streaming progress');\n }\n\n const artifacts =\n selectedMode === 'vibe-plugins'\n ? await getAssistantArtifacts(apollo, sandboxId, workspaceId, sessionId, authContext).catch(() => [])\n : undefined;\n\n if (!result.done) {\n // vibe-plugins build still running in the background. Append a note so\n // the user knows the answer is partial and the artifacts will finish.\n result = {\n ...result,\n content: `${result.content}\\n\\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`,\n };\n }\n\n if (imagesDropped) {\n // Said plainly, because the alternative is an answer that looks like\n // it examined a photo it never received.\n result = {\n ...result,\n content: `${result.content}\\n\\n${tr(\n 'healthybowl.assistant.attachments.imagesNotSent',\n '_Your photo was too large to include with this message, so the answer above is from the text and the file link only. Try a smaller or more tightly cropped photo._'\n )}`,\n };\n }\n\n applyAssistantResponse(result.content, artifacts, sessionId, sandboxId);\n\n if (result.tokens) {\n patchMessage(conversationId, assistantMessageId, { tokens: result.tokens });\n // Charge the real token usage against the AI-credits quota (the\n // gateway records it via @usage(trackUsage)). We AWAIT it before\n // marking the turn complete / re-enabling input: otherwise a rapid\n // follow-up send would run its pre-flight checkAiCredits against a\n // stale balance (this turn's charge still in flight) and could\n // dispatch a prompt that should have been blocked, letting fast\n // sends bypass the credit cap. Still best-effort — a charge failure\n // never blocks the displayed answer.\n try {\n await reportAssistantAiTokenUsage(apollo, workspaceId, sessionId, result.tokens, authContext);\n notifyAiCreditsUpdated();\n } catch {\n // ignore — server-side @usage tracking is the source of truth\n }\n }\n setConversationProcessing(conversationId, 'complete', assistantMessageId, null);\n } catch (error) {\n if (attempt === 1 && isRecoverableAssistantError(error)) {\n clearBackendSessionId(conversationId);\n clearSandbox(selectedMode);\n return sendWithRealBackend(2);\n }\n\n throw error;\n }\n };\n\n // Claim the slot immediately before the first await, and release it in\n // `finally` so every exit — success, quota return, thrown error — frees\n // it. Registering here rather than earlier means a synchronous throw in\n // the setup above can never strand a key and wedge the conversation.\n const turnConversationId = conversationId;\n inFlightSendsRef.current.add(turnConversationId);\n\n try {\n if (!workspaceId) {\n throw new Error('Assistant backend is unavailable without an active workspace context.');\n }\n await sendWithRealBackend();\n } catch (error) {\n // ★ Any failed turn drops the readiness proof for the sandbox it used,\n // so the NEXT turn re-probes instead of trusting a cache entry that a\n // dead pod would otherwise keep alive until the TTL lapsed. This is the\n // half that makes the short-circuit above safe.\n sandboxReadiness.current.invalidate(\n useAssistantStore.getState().sandboxesByMode[selectedMode]?.sandboxId ?? null\n );\n // A quota error reaching here is the sandbox-environment wall hit\n // during runtime provisioning (createSandbox @usage). Surface the\n // upgrade dialog instead of a generic failure (the AI-credit wall is\n // already handled by the pre-flight gate above).\n if (isQuotaExhaustedError(error)) {\n dispatchAssistantQuotaExhausted('sandbox');\n applyAssistantResponse(\n \"You've reached your sandbox limit on the current plan. Upgrade to start the AI assistant.\",\n undefined,\n undefined,\n undefined,\n 'en'\n );\n setConversationProcessing(conversationId, 'error', assistantMessageId, null);\n return;\n }\n const errorMessage = error instanceof Error ? error.message : 'Something went wrong';\n setConversationProcessing(conversationId, 'error', assistantMessageId, errorMessage);\n // Same reason: English copy must not inherit the turn's language stamp.\n // The voice marker still has to survive though — a failed spoken turn\n // belongs to the session that asked. Without it the failure surfaced as\n // a bare \"Sorry, an error occurred\" in the typed thread with no question\n // above it, while the voice session showed nothing at all.\n patchMessage(conversationId, assistantMessageId, {\n content: `Sorry, an error occurred: ${errorMessage}. Please try again.`,\n metadata: { lang: 'en', ...voiceMarker(options.dictated) },\n });\n } finally {\n inFlightSendsRef.current.delete(turnConversationId);\n }\n },\n [\n activeConversationId,\n addMessage,\n apollo,\n clearBackendSessionId,\n clearSandbox,\n conversations,\n createConversation,\n ensureAssistantRuntime,\n getAccessToken,\n getWorkspaceToken,\n patchMessage,\n // Without this, switching language mid-conversation keeps sending the\n // previous language's directive until something else re-creates the\n // callback.\n languageIsExplicit,\n replyLanguageCode,\n replyLanguageName,\n setBackendSessionId,\n setConversationMode,\n setConversationProcessing,\n tr,\n updateConversationStage,\n userId,\n ]\n );\n\n const handleSuggestionClick = useCallback(\n (suggestion: string) => {\n void handleSend(suggestion);\n },\n [handleSend]\n );\n\n // Retry re-sends the most recent user prompt through the same transport — the\n // failed assistant turn stays in the transcript, a fresh one is appended.\n // The attachments come from the in-memory ref rather than the message\n // metadata: the persisted descriptors deliberately drop the inlined text of\n // text-like files, so rebuilding from them would silently retry a WEAKER\n // prompt than the one that failed.\n const handleRetry = useCallback(() => {\n const lastUserMessage = [...messages].reverse().find((message) => message.role === 'user');\n const replay = activeConversationId ? (lastSentAttachmentsRef.current[activeConversationId] ?? []) : [];\n if (lastUserMessage) void handleSend(lastUserMessage.content, replay);\n }, [messages, handleSend, activeConversationId]);\n\n // Auto-send any prompt that was queued by `useOpenAssistantHelp` (from\n // the shared GetHelpButton). We keep the latest handleSend in a ref so\n // the subscription effect below doesn't need to tear down on every\n // render — the store subscription lives for the component lifetime and\n // always calls the freshest handler.\n const handleSendRef = useRef(handleSend);\n useEffect(() => {\n handleSendRef.current = handleSend;\n }, [handleSend]);\n\n /**\n * The newest assistant reply, as the voice session's advance signal.\n *\n * Keyed on the message ID rather than the text: two consecutive answers can be\n * word-for-word identical, and text alone would then never advance the second\n * turn.\n */\n const latestAssistantReply = useMemo(() => {\n // ★ Only once the turn is COMPLETE. While it is in flight the pending\n // assistant message is patched with progress text — 'Starting assistant\n // environment...', 'Thinking...' — and exposing that would make the voice\n // session consume the message id, enter `speaking` on a placeholder, and\n // then be unable to advance when the real answer replaced it.\n if (activeIsProcessing) return null;\n for (let i = messages.length - 1; i >= 0; i -= 1) {\n const message = messages[i];\n if (message?.role !== 'assistant') continue;\n // Tool-activity markup is stripped so the session captions and speaks the\n // answer, not the machinery that produced it.\n const text = parseToolActivity(message.content).text.trim();\n return text ? { id: message.id, text } : null;\n }\n return null;\n }, [messages, activeIsProcessing]);\n\n /**\n * The same reply, with its Markdown markers removed, for the on-screen caption.\n *\n * ★ Deliberately a SEPARATE memo rather than a change to the one above, whose\n * `text` is not just display: it is the echo reference the recogniser compares\n * against while the answer is being spoken, and the payload of the session's\n * `reply` dispatch. Stripping it there would silently shift what counts as an\n * echo of our own voice. The audio path keeps its own transform\n * (`toSpeakableText`) — the two want genuinely different output, which is why\n * they are two functions and not one.\n */\n const voiceCaption = useMemo(\n () => (latestAssistantReply ? toCaptionText(latestAssistantReply.text) : null),\n [latestAssistantReply]\n );\n\n /**\n * The last few exchanges, for the session's on-screen transcript.\n *\n * Voice turns already go through the normal send path, so they are ordinary\n * conversation messages — this only surfaces them INSIDE the session, which\n * is what makes a second question in the same session make sense.\n */\n /**\n * What the CHAT panel shows: everything that was not spoken.\n *\n * Voice and chat share one conversation, so without this split every spoken\n * exchange appeared in the typed thread.\n */\n const chatMessages = useMemo(() => chatTurns(messages), [messages]);\n\n const voiceTurns = useMemo(\n () =>\n // ★ Only turns from this voice session. It used to take the last six\n // messages of the WHOLE conversation, so opening voice on an existing\n // thread painted typed replies — the wall of raw `##` and `**` the\n // operator screenshotted, because the voice panel renders plain text.\n voiceTurnsOnly(messages)\n .filter((message) => message.role === 'user' || message.role === 'assistant')\n .map((message) => ({\n id: message.id,\n role: message.role as 'user' | 'assistant',\n text: parseToolActivity(message.content).text.trim(),\n }))\n .filter((turn) => turn.text.length > 0),\n [messages]\n );\n\n const submitVoiceTurn = useCallback((text: string) => {\n // ★ Only the voice SESSION is unambiguously dictated. The composer's\n // microphone also produces a transcript, but the user reads and edits it in\n // the box before sending, so treating that as dictated would tell the model\n // to second-guess words the user had already approved.\n void handleSendRef.current(text, [], { dictated: true });\n }, []);\n\n const voiceSession = useVoiceSession({\n onSubmit: submitVoiceTurn,\n latestReply: latestAssistantReply,\n // The language the user SPEAKS, not the interface language — the same\n // preference the composer's dictation and the reply language already use.\n language: resolveAssistantLanguage(assistantLanguage, locale).tag,\n });\n\n // Hiding the panel must end a live voice session. The host may set `visible`\n // false WITHOUT unmounting, and an unmount-only cleanup would then leave the\n // microphone recording behind an invisible panel — a privacy problem, not\n // just a leak.\n useEffect(() => {\n if (!visible && voiceSession.active) voiceSession.end();\n }, [visible, voiceSession]);\n\n useEffect(() => {\n // Flush any prompt that was queued before this component mounted.\n const initial = useAssistantStore.getState().consumePendingPrompt();\n if (initial) {\n void handleSendRef.current(initial);\n }\n\n // Watch for new prompts queued while we're already mounted.\n const unsubscribe = useAssistantStore.subscribe((state, prev) => {\n if (state.pendingPrompt && state.pendingPrompt !== prev.pendingPrompt) {\n const queued = useAssistantStore.getState().consumePendingPrompt();\n if (queued) {\n void handleSendRef.current(queued);\n }\n }\n });\n return unsubscribe;\n }, []);\n\n const performModeChange = useCallback(\n (newMode: AssistantMode) => {\n const currentConversation = activeConversationId\n ? useAssistantStore.getState().conversations.find((conversation) => conversation.id === activeConversationId)\n : undefined;\n\n if (currentConversation && (currentConversation.messages.length > 0 || currentConversation.backendSessionId)) {\n if (currentConversation.mode !== newMode) {\n const reusableDraft = useAssistantStore\n .getState()\n .conversations.find(\n (conversation) =>\n conversation.mode === newMode &&\n conversation.messages.length === 0 &&\n !conversation.backendSessionId &&\n !useAssistantStore.getState().processingByConversationId[conversation.id]\n );\n\n if (reusableDraft) {\n setActiveConversation(reusableDraft.id);\n } else {\n createConversation(undefined, newMode);\n }\n }\n } else if (activeConversationId) {\n setConversationMode(activeConversationId, newMode);\n }\n\n setMode(newMode);\n },\n [activeConversationId, createConversation, setActiveConversation, setConversationMode, setMode]\n );\n\n const handleModeChange = useCallback(\n (newMode: AssistantMode) => {\n const target = ASSISTANT_MODES.find((modeConfig) => modeConfig.id === newMode);\n // Gate the FIRST switch into a write-capable mode behind the one-time\n // consent dialog — the dependable confirm-before-mutate guardrail.\n if (target?.writeCapable && !useAssistantStore.getState().apiCallsAcknowledged) {\n setPendingConsentMode(newMode);\n return;\n }\n performModeChange(newMode);\n },\n [performModeChange]\n );\n\n const handleConsentConfirm = useCallback(() => {\n const target = pendingConsentMode;\n setPendingConsentMode(null);\n acknowledgeApiCalls();\n if (target) performModeChange(target);\n }, [pendingConsentMode, acknowledgeApiCalls, performModeChange]);\n\n const handleConsentCancel = useCallback(() => {\n setPendingConsentMode(null);\n }, []);\n\n return (\n // `relative` so the DOCKED voice session can position itself against the\n // assistant panel rather than the viewport. Without it the docked overlay\n // would anchor to the page and cover the whole app, which is the very thing\n // docking exists to avoid.\n <div className=\"relative flex flex-1 flex-col overflow-hidden\">\n {/* Everything the voice overlay covers is made `inert` while a session is\n open. Docked, the overlay hides the transcript and composer but does\n NOT cover the page, so a full focus trap would wrongly imprison the\n user — yet leaving these focusable lets them Shift+Tab into controls\n they cannot see and operate them blind. `inert` is the precise tool:\n the page stays reachable, the covered controls do not. */}\n <div className=\"contents\" inert={voiceSession.active || undefined}>\n {/* Transcript is always visible now — the old collapse-by-default accordion\n is gone; conversation history lives behind the header button instead. */}\n {chatMessages.length === 0 ? (\n <AssistantEmptyState mode={mode} onSuggestionClick={handleSuggestionClick} />\n ) : (\n <div className=\"flex min-h-0 flex-1 flex-col\">\n <AssistantMessageList\n messages={chatMessages}\n streamingMessageId={activeStreamingMessageId}\n failedMessageId={failedMessageId}\n onRetry={handleRetry}\n />\n </div>\n )}\n\n <AssistantComposer\n // ★ Ask-mode only, and enforced here rather than merely documented.\n // In `api-calls` mode the assistant WRITES to farm data behind a consent\n // gate, and BOFF-6377 (\"confirm-before-write cannot prove a human\n // approved\") is still open — a spoken \"yes, do it\" is exactly the case\n // that ticket is about. Voice control of writes is the NEXT phase, not\n // this one, so the launcher is simply absent in that mode.\n onStartVoiceSession={voiceSession.available && mode !== 'api-calls' ? voiceSession.start : undefined}\n onSend={(value, attachments) => void handleSend(value, attachments)}\n disabled={activeIsProcessing}\n placeholder={\n mode === 'api-calls'\n ? tr('healthybowl.assistant.chatArea.placeholderActions', 'What would you like me to do?')\n : tr('healthybowl.assistant.chatArea.placeholderGeneral', 'Ask HealthyBowl anything…')\n }\n mode={mode}\n availableModes={availableModes}\n onModeChange={handleModeChange}\n />\n </div>\n\n {voiceSession.active && (\n <AssistantVoiceSession\n session={voiceSession.session}\n notice={voiceSession.notice}\n capturing={voiceSession.capturing}\n interrupting={voiceSession.interrupting}\n awaitingEndpoint={voiceSession.awaitingEndpoint}\n turns={voiceTurns}\n onInterrupt={voiceSession.interrupt}\n spoken={voiceCaption}\n onToggleMute={voiceSession.toggleMute}\n onEnd={voiceSession.end}\n />\n )}\n\n <AssistantApiCallsConsentDialog\n open={pendingConsentMode !== null}\n onConfirm={handleConsentConfirm}\n onCancel={handleConsentCancel}\n />\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,IAAM,KAAkD;CACtD,SAAS;CACT,WAAW;CACX,aAAa;CACb,gBAAgB;AAClB,GACM,KAA2B;AAEjC,SAAS,KAAqB;CAC5B,OAAO,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC;AAC/D;AAEA,SAAS,GAA0B,GAA0B;CAC3D,OAAO,EACJ,QAAQ,6CAA6C,cAAc,EACnE,QAAQ,yDAAyD,cAAc,EAC/E,QAAQ,4DAA4D,gBAAgB,EACpF,QAAQ,6BAA6B,oBAAoB;AAC9D;AAEA,SAAS,EAAuB,GAAsC;CACpE,OAAO,EAAQ,MAAM,MAAM,WAAW;AACxC;AAEA,SAAS,EAAiB,GAA6C;CACrE,QAAQ,KAAS,CAAC,GACf,QAAQ,MAAS,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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AAA,CACE;;GAEJ,EAAa,UACZ,kBAAC,IAAD;IACE,SAAS,EAAa;IACtB,QAAQ,EAAa;IACrB,WAAW,EAAa;IACxB,cAAc,EAAa;IAC3B,kBAAkB,EAAa;IAC/B,OAAO;IACP,aAAa,EAAa;IAC1B,QAAQ;IACR,cAAc,EAAa;IAC3B,OAAO,EAAa;GACrB,CAAA;GAGH,kBAAC,GAAD;IACE,MAAM,OAAuB;IAC7B,WAAW;IACX,UAAU;GACX,CAAA;EACE;;AAET"}
@@ -1,147 +1,152 @@
1
1
  import { useAssistantStore as e } from "../../store/assistantStore.js";
2
2
  import { useTr as t } from "../../shared/hooks/useTr.js";
3
3
  import { ASSISTANT_MODES as n } from "../../types/assistant.js";
4
- import { useState as r } from "react";
5
- import { Check as i, MessageSquare as a, PanelLeftClose as o, Pencil as s, Plus as c, Trash2 as l } from "lucide-react";
6
- import { Fragment as u, jsx as d, jsxs as f } from "react/jsx-runtime";
4
+ import { chatTurns as r } from "../../utils/voiceTurnVisibility.js";
5
+ import { useState as i } from "react";
6
+ import { Check as a, MessageSquare as o, PanelLeftClose as s, Pencil as c, Plus as l, Trash2 as u } from "lucide-react";
7
+ import { Fragment as d, jsx as f, jsxs as p } from "react/jsx-runtime";
7
8
  //#region src/components/assistant/AssistantConversationList.tsx
8
- var p = () => {
9
- let p = t(), { conversations: m, activeConversationId: h, processingByConversationId: g, setActiveConversation: _, setMode: v, createConversation: y, deleteConversation: b, renameConversation: x, setConversationListOpen: S } = e(), [C, w] = r(null), [T, E] = r(""), D = () => {
10
- y(), S(!1);
11
- }, O = (e) => {
12
- let t = m.find((t) => t.id === e);
13
- _(e), t && v(t.mode), S(!1);
14
- }, k = (e, t) => {
15
- w(e), E(t);
16
- }, A = () => {
17
- C && T.trim() && x(C, T.trim()), w(null);
18
- }, j = (e, t) => {
19
- e.stopPropagation(), b(t);
9
+ var m = () => {
10
+ let m = t(), { conversations: h, activeConversationId: g, processingByConversationId: _, setActiveConversation: v, setMode: y, createConversation: b, deleteConversation: x, renameConversation: S, setConversationListOpen: C } = e(), [w, T] = i(null), [E, D] = i(""), O = () => {
11
+ b(), C(!1);
12
+ }, k = (e) => {
13
+ let t = h.find((t) => t.id === e);
14
+ v(e), t && y(t.mode), C(!1);
15
+ }, A = (e, t) => {
16
+ T(e), D(t);
17
+ }, j = () => {
18
+ w && E.trim() && S(w, E.trim()), T(null);
19
+ }, M = (e, t) => {
20
+ e.stopPropagation(), x(t);
20
21
  };
21
- return /* @__PURE__ */ f("div", {
22
+ return /* @__PURE__ */ p("div", {
22
23
  className: "absolute inset-0 z-10 flex flex-col bg-bg-surface animate-in slide-in-from-left-2 fade-in duration-200",
23
24
  "data-testid": "conversation-list",
24
- children: [/* @__PURE__ */ f("div", {
25
+ children: [/* @__PURE__ */ p("div", {
25
26
  className: "flex items-center justify-between px-4 py-3 border-b border-border-default bg-bg-elevated",
26
- children: [/* @__PURE__ */ d("span", {
27
+ children: [/* @__PURE__ */ f("span", {
27
28
  className: "text-[13px] font-semibold text-text-primary",
28
- children: p("healthybowl.assistant.conversations.title", "History")
29
- }), /* @__PURE__ */ f("div", {
29
+ children: m("healthybowl.assistant.conversations.title", "History")
30
+ }), /* @__PURE__ */ p("div", {
30
31
  className: "flex items-center gap-0.5",
31
- children: [/* @__PURE__ */ d("button", {
32
+ children: [/* @__PURE__ */ f("button", {
32
33
  type: "button",
33
- onClick: D,
34
+ onClick: O,
34
35
  className: "p-1.5 rounded-lg text-text-secondary hover:bg-bg-sunken transition-colors",
35
- "aria-label": p("healthybowl.assistant.conversations.new", "New conversation"),
36
+ "aria-label": m("healthybowl.assistant.conversations.new", "New conversation"),
36
37
  "data-testid": "new-conversation",
37
- children: /* @__PURE__ */ d(c, { className: "size-4" })
38
- }), /* @__PURE__ */ f("button", {
38
+ children: /* @__PURE__ */ f(l, { className: "size-4" })
39
+ }), /* @__PURE__ */ p("button", {
39
40
  type: "button",
40
- onClick: () => S(!1),
41
+ onClick: () => C(!1),
41
42
  className: "flex items-center gap-1 px-2 py-1.5 rounded-lg text-text-secondary hover:bg-bg-sunken transition-colors",
42
- "aria-label": p("healthybowl.assistant.conversations.collapse", "Collapse history"),
43
+ "aria-label": m("healthybowl.assistant.conversations.collapse", "Collapse history"),
43
44
  "data-testid": "collapse-conversation-list",
44
- children: [/* @__PURE__ */ d(o, { className: "size-4" }), /* @__PURE__ */ d("span", {
45
+ children: [/* @__PURE__ */ f(s, { className: "size-4" }), /* @__PURE__ */ f("span", {
45
46
  className: "text-[11px] font-medium",
46
- children: p("healthybowl.assistant.conversations.collapseLabel", "Collapse")
47
+ children: m("healthybowl.assistant.conversations.collapseLabel", "Collapse")
47
48
  })]
48
49
  })]
49
50
  })]
50
- }), /* @__PURE__ */ d("div", {
51
+ }), /* @__PURE__ */ f("div", {
51
52
  className: "flex-1 overflow-y-auto",
52
- children: m.length === 0 ? /* @__PURE__ */ f("div", {
53
+ children: h.length === 0 ? /* @__PURE__ */ p("div", {
53
54
  className: "flex flex-col items-center justify-center h-full text-center px-4",
54
55
  children: [
55
- /* @__PURE__ */ d(a, { className: "size-6 text-text-muted mb-2" }),
56
- /* @__PURE__ */ d("p", {
56
+ /* @__PURE__ */ f(o, { className: "size-6 text-text-muted mb-2" }),
57
+ /* @__PURE__ */ f("p", {
57
58
  className: "text-xs text-text-muted",
58
- children: p("healthybowl.assistant.conversations.empty", "No conversations yet")
59
+ children: m("healthybowl.assistant.conversations.empty", "No conversations yet")
59
60
  }),
60
- /* @__PURE__ */ d("button", {
61
+ /* @__PURE__ */ f("button", {
61
62
  type: "button",
62
- onClick: D,
63
+ onClick: O,
63
64
  className: "mt-2 text-xs text-action-primary-bg hover:underline",
64
- children: p("healthybowl.assistant.conversations.startNew", "Start a new conversation")
65
+ children: m("healthybowl.assistant.conversations.startNew", "Start a new conversation")
65
66
  })
66
67
  ]
67
- }) : /* @__PURE__ */ d("div", {
68
+ }) : /* @__PURE__ */ f("div", {
68
69
  className: "py-1",
69
- children: m.map((e) => {
70
- let t = e.id === h, r = e.id === C, a = n.find((t) => t.id === e.mode), o = e.messages[e.messages.length - 1], c = g[e.id];
71
- return /* @__PURE__ */ d("div", {
70
+ children: h.map((e) => {
71
+ let t = e.id === g, i = e.id === w, o = n.find((t) => t.id === e.mode), s = r(e.messages), l = s[s.length - 1], h = s.length === 0 && e.messages.length > 0, v = _[e.id];
72
+ return /* @__PURE__ */ f("div", {
72
73
  role: "button",
73
74
  tabIndex: 0,
74
75
  onKeyDown: (t) => {
75
- (t.key === "Enter" || t.key === " ") && (t.preventDefault(), !r && O(e.id));
76
+ (t.key === "Enter" || t.key === " ") && (t.preventDefault(), !i && k(e.id));
76
77
  },
77
- onClick: () => !r && O(e.id),
78
+ onClick: () => !i && k(e.id),
78
79
  className: `group px-3 py-2 cursor-pointer hover:bg-bg-elevated transition-colors ${t ? "bg-bg-elevated border-l-2 border-action-primary-bg" : ""}`,
79
- children: r ? /* @__PURE__ */ f("div", {
80
+ children: i ? /* @__PURE__ */ p("div", {
80
81
  className: "flex items-center gap-1",
81
- children: [/* @__PURE__ */ d("input", {
82
- "aria-label": p("healthybowl.assistant.conversations.renameLabel", "Conversation title"),
83
- value: T,
84
- onChange: (e) => E(e.target.value),
82
+ children: [/* @__PURE__ */ f("input", {
83
+ "aria-label": m("healthybowl.assistant.conversations.renameLabel", "Conversation title"),
84
+ value: E,
85
+ onChange: (e) => D(e.target.value),
85
86
  onKeyDown: (e) => {
86
- e.key === "Enter" && A(), e.key === "Escape" && w(null);
87
+ e.key === "Enter" && j(), e.key === "Escape" && T(null);
87
88
  },
88
89
  className: "flex-1 text-xs bg-bg-sunken border border-border-default rounded px-2 py-1 text-text-primary focus:outline-none focus:border-action-primary-bg",
89
90
  onClick: (e) => e.stopPropagation()
90
- }), /* @__PURE__ */ d("button", {
91
+ }), /* @__PURE__ */ f("button", {
91
92
  type: "button",
92
93
  onClick: (e) => {
93
- e.stopPropagation(), A();
94
+ e.stopPropagation(), j();
94
95
  },
95
96
  className: "p-1 hover:bg-bg-sunken rounded",
96
- "aria-label": p("healthybowl.assistant.conversations.saveTitle", "Save title"),
97
- children: /* @__PURE__ */ d(i, { className: "size-3 text-status-success-text" })
97
+ "aria-label": m("healthybowl.assistant.conversations.saveTitle", "Save title"),
98
+ children: /* @__PURE__ */ f(a, { className: "size-3 text-status-success-text" })
98
99
  })]
99
- }) : /* @__PURE__ */ f(u, { children: [
100
- /* @__PURE__ */ f("div", {
100
+ }) : /* @__PURE__ */ p(d, { children: [
101
+ /* @__PURE__ */ p("div", {
101
102
  className: "flex items-center justify-between",
102
- children: [/* @__PURE__ */ d("span", {
103
+ children: [/* @__PURE__ */ f("span", {
103
104
  className: "text-xs font-medium text-text-primary truncate flex-1",
104
105
  children: e.title
105
- }), /* @__PURE__ */ f("div", {
106
+ }), /* @__PURE__ */ p("div", {
106
107
  className: "hidden group-hover:flex group-focus-within:flex items-center gap-0.5 ml-1",
107
- children: [/* @__PURE__ */ d("button", {
108
+ children: [/* @__PURE__ */ f("button", {
108
109
  type: "button",
109
110
  onClick: (t) => {
110
- t.stopPropagation(), k(e.id, e.title);
111
+ t.stopPropagation(), A(e.id, e.title);
111
112
  },
112
113
  className: "p-0.5 hover:bg-bg-sunken rounded",
113
- "aria-label": p("healthybowl.assistant.conversations.rename", "Rename conversation"),
114
- children: /* @__PURE__ */ d(s, { className: "size-3 text-text-muted" })
115
- }), /* @__PURE__ */ d("button", {
114
+ "aria-label": m("healthybowl.assistant.conversations.rename", "Rename conversation"),
115
+ children: /* @__PURE__ */ f(c, { className: "size-3 text-text-muted" })
116
+ }), /* @__PURE__ */ f("button", {
116
117
  type: "button",
117
- onClick: (t) => j(t, e.id),
118
+ onClick: (t) => M(t, e.id),
118
119
  className: "p-0.5 hover:bg-bg-sunken rounded",
119
- "aria-label": p("healthybowl.assistant.conversations.delete", "Delete conversation"),
120
+ "aria-label": m("healthybowl.assistant.conversations.delete", "Delete conversation"),
120
121
  "data-testid": "delete-conversation",
121
- children: /* @__PURE__ */ d(l, { className: "size-3 text-status-error-text" })
122
+ children: /* @__PURE__ */ f(u, { className: "size-3 text-status-error-text" })
122
123
  })]
123
124
  })]
124
125
  }),
125
- /* @__PURE__ */ f("div", {
126
+ /* @__PURE__ */ p("div", {
126
127
  className: "flex items-center gap-1.5 mt-0.5",
127
128
  children: [
128
- /* @__PURE__ */ d("span", {
129
+ /* @__PURE__ */ f("span", {
129
130
  className: "text-[10px] text-text-muted px-1 py-0.5 bg-bg-sunken rounded",
130
- children: a?.label ?? e.mode
131
+ children: o?.label ?? e.mode
131
132
  }),
132
- /* @__PURE__ */ f("span", {
133
+ /* @__PURE__ */ p("span", {
133
134
  className: "text-[10px] text-text-muted",
134
- children: [e.messages.length, " msgs"]
135
+ children: [s.length, " msgs"]
135
136
  }),
136
- c && c.status !== "idle" && /* @__PURE__ */ d("span", {
137
+ v && v.status !== "idle" && /* @__PURE__ */ f("span", {
137
138
  className: "text-[10px] text-action-primary-bg px-1 py-0.5 bg-bg-sunken rounded",
138
- children: c.status
139
+ children: v.status
139
140
  })
140
141
  ]
141
142
  }),
142
- o && /* @__PURE__ */ d("p", {
143
+ l && /* @__PURE__ */ f("p", {
144
+ className: "text-[10px] text-text-muted truncate mt-0.5",
145
+ children: l.content.slice(0, 60)
146
+ }),
147
+ h && /* @__PURE__ */ f("p", {
143
148
  className: "text-[10px] text-text-muted truncate mt-0.5",
144
- children: o.content.slice(0, 60)
149
+ children: m("healthybowl.assistant.conversationList.voiceOnly", "Spoken conversation")
145
150
  })
146
151
  ] })
147
152
  }, e.id);
@@ -151,6 +156,6 @@ var p = () => {
151
156
  });
152
157
  };
153
158
  //#endregion
154
- export { p as AssistantConversationList };
159
+ export { m as AssistantConversationList };
155
160
 
156
161
  //# sourceMappingURL=AssistantConversationList.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantConversationList.js","names":[],"sources":["../../../src/components/assistant/AssistantConversationList.tsx"],"sourcesContent":["import { useState, type FC } from 'react';\nimport { Plus, Trash2, MessageSquare, PanelLeftClose, Pencil, Check } from 'lucide-react';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { ASSISTANT_MODES } from '@/types/assistant';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport const AssistantConversationList: FC = () => {\n const tr = useTr();\n const {\n conversations,\n activeConversationId,\n processingByConversationId,\n setActiveConversation,\n setMode,\n createConversation,\n deleteConversation,\n renameConversation,\n setConversationListOpen,\n } = useAssistantStore();\n\n const [editingId, setEditingId] = useState<string | null>(null);\n const [editTitle, setEditTitle] = useState('');\n\n const handleCreate = () => {\n createConversation();\n setConversationListOpen(false);\n };\n\n const handleSelect = (id: string) => {\n const selectedConversation = conversations.find((conversation) => conversation.id === id);\n setActiveConversation(id);\n if (selectedConversation) {\n setMode(selectedConversation.mode);\n }\n setConversationListOpen(false);\n };\n\n const handleStartRename = (id: string, currentTitle: string) => {\n setEditingId(id);\n setEditTitle(currentTitle);\n };\n\n const handleConfirmRename = () => {\n if (editingId && editTitle.trim()) {\n renameConversation(editingId, editTitle.trim());\n }\n setEditingId(null);\n };\n\n const handleDelete = (e: React.MouseEvent, id: string) => {\n e.stopPropagation();\n deleteConversation(id);\n };\n\n return (\n <div\n className=\"absolute inset-0 z-10 flex flex-col bg-bg-surface animate-in slide-in-from-left-2 fade-in duration-200\"\n data-testid=\"conversation-list\"\n >\n {/* Header */}\n <div className=\"flex items-center justify-between px-4 py-3 border-b border-border-default bg-bg-elevated\">\n <span className=\"text-[13px] font-semibold text-text-primary\">\n {tr('healthybowl.assistant.conversations.title', 'History')}\n </span>\n <div className=\"flex items-center gap-0.5\">\n <button\n type=\"button\"\n onClick={handleCreate}\n className=\"p-1.5 rounded-lg text-text-secondary hover:bg-bg-sunken transition-colors\"\n aria-label={tr('healthybowl.assistant.conversations.new', 'New conversation')}\n data-testid=\"new-conversation\"\n >\n <Plus className=\"size-4\" />\n </button>\n <button\n type=\"button\"\n onClick={() => setConversationListOpen(false)}\n className=\"flex items-center gap-1 px-2 py-1.5 rounded-lg text-text-secondary hover:bg-bg-sunken transition-colors\"\n aria-label={tr('healthybowl.assistant.conversations.collapse', 'Collapse history')}\n data-testid=\"collapse-conversation-list\"\n >\n <PanelLeftClose className=\"size-4\" />\n <span className=\"text-[11px] font-medium\">\n {tr('healthybowl.assistant.conversations.collapseLabel', 'Collapse')}\n </span>\n </button>\n </div>\n </div>\n\n {/* List */}\n <div className=\"flex-1 overflow-y-auto\">\n {conversations.length === 0 ? (\n <div className=\"flex flex-col items-center justify-center h-full text-center px-4\">\n <MessageSquare className=\"size-6 text-text-muted mb-2\" />\n <p className=\"text-xs text-text-muted\">\n {tr('healthybowl.assistant.conversations.empty', 'No conversations yet')}\n </p>\n <button\n type=\"button\"\n onClick={handleCreate}\n className=\"mt-2 text-xs text-action-primary-bg hover:underline\"\n >\n {tr('healthybowl.assistant.conversations.startNew', 'Start a new conversation')}\n </button>\n </div>\n ) : (\n <div className=\"py-1\">\n {conversations.map((conv) => {\n const isActive = conv.id === activeConversationId;\n const isEditing = conv.id === editingId;\n const modeConfig = ASSISTANT_MODES.find((m) => m.id === conv.mode);\n const lastMessage = conv.messages[conv.messages.length - 1];\n const processing = processingByConversationId[conv.id];\n\n return (\n <div\n role=\"button\"\n tabIndex={0}\n onKeyDown={(e) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault();\n (() => !isEditing && handleSelect(conv.id))();\n }\n }}\n key={conv.id}\n onClick={() => !isEditing && handleSelect(conv.id)}\n className={`group px-3 py-2 cursor-pointer hover:bg-bg-elevated transition-colors ${\n isActive ? 'bg-bg-elevated border-l-2 border-action-primary-bg' : ''\n }`}\n >\n {isEditing ? (\n <div className=\"flex items-center gap-1\">\n <input\n aria-label={tr('healthybowl.assistant.conversations.renameLabel', 'Conversation title')}\n value={editTitle}\n onChange={(e) => setEditTitle(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter') handleConfirmRename();\n if (e.key === 'Escape') setEditingId(null);\n }}\n className=\"flex-1 text-xs bg-bg-sunken border border-border-default rounded px-2 py-1 text-text-primary focus:outline-none focus:border-action-primary-bg\"\n onClick={(e) => e.stopPropagation()}\n />\n <button\n type=\"button\"\n onClick={(e) => {\n e.stopPropagation();\n handleConfirmRename();\n }}\n className=\"p-1 hover:bg-bg-sunken rounded\"\n aria-label={tr('healthybowl.assistant.conversations.saveTitle', 'Save title')}\n >\n <Check className=\"size-3 text-status-success-text\" />\n </button>\n </div>\n ) : (\n <>\n <div className=\"flex items-center justify-between\">\n <span className=\"text-xs font-medium text-text-primary truncate flex-1\">{conv.title}</span>\n <div className=\"hidden group-hover:flex group-focus-within:flex items-center gap-0.5 ml-1\">\n <button\n type=\"button\"\n onClick={(e) => {\n e.stopPropagation();\n handleStartRename(conv.id, conv.title);\n }}\n className=\"p-0.5 hover:bg-bg-sunken rounded\"\n aria-label={tr('healthybowl.assistant.conversations.rename', 'Rename conversation')}\n >\n <Pencil className=\"size-3 text-text-muted\" />\n </button>\n <button\n type=\"button\"\n onClick={(e) => handleDelete(e, conv.id)}\n className=\"p-0.5 hover:bg-bg-sunken rounded\"\n aria-label={tr('healthybowl.assistant.conversations.delete', 'Delete conversation')}\n data-testid=\"delete-conversation\"\n >\n <Trash2 className=\"size-3 text-status-error-text\" />\n </button>\n </div>\n </div>\n <div className=\"flex items-center gap-1.5 mt-0.5\">\n <span className=\"text-[10px] text-text-muted px-1 py-0.5 bg-bg-sunken rounded\">\n {modeConfig?.label ?? conv.mode}\n </span>\n <span className=\"text-[10px] text-text-muted\">{conv.messages.length} msgs</span>\n {processing && processing.status !== 'idle' && (\n <span className=\"text-[10px] text-action-primary-bg px-1 py-0.5 bg-bg-sunken rounded\">\n {processing.status}\n </span>\n )}\n </div>\n {lastMessage && (\n <p className=\"text-[10px] text-text-muted truncate mt-0.5\">\n {lastMessage.content.slice(0, 60)}\n </p>\n )}\n </>\n )}\n </div>\n );\n })}\n </div>\n )}\n </div>\n </div>\n );\n};\n"],"mappings":";;;;;;;AAMA,IAAa,UAAsC;CACjD,IAAM,IAAK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AD,EAAO,WAAU,kCAAmC,CAAA;OAC9C,CAAA,CACL;WAEL,kBAAA,GAAA,EAAA,UAAA;OACE,kBAAC,OAAD;QAAK,WAAU;kBAAf,CACE,kBAAC,QAAD;SAAM,WAAU;mBAAyD,EAAK;QAAY,CAAA,GAC1F,kBAAC,OAAD;SAAK,WAAU;mBAAf,CACE,kBAAC,UAAD;UACE,MAAK;UACL,UAAU,MAAM;WAEd,AADA,EAAE,gBAAgB,GAClB,EAAkB,EAAK,IAAI,EAAK,KAAK;UACvC;UACA,WAAU;UACV,cAAY,EAAG,8CAA8C,qBAAqB;oBAElF,kBAAC,GAAD,EAAQ,WAAU,yBAA0B,CAAA;SACtC,CAAA,GACR,kBAAC,UAAD;UACE,MAAK;UACL,UAAU,MAAM,EAAa,GAAG,EAAK,EAAE;UACvC,WAAU;UACV,cAAY,EAAG,8CAA8C,qBAAqB;UAClF,eAAY;oBAEZ,kBAAC,GAAD,EAAQ,WAAU,gCAAiC,CAAA;SAC7C,CAAA,CACL;UACF;;OACL,kBAAC,OAAD;QAAK,WAAU;kBAAf;SACE,kBAAC,QAAD;UAAM,WAAU;oBACb,GAAY,SAAS,EAAK;SACvB,CAAA;SACN,kBAAC,QAAD;UAAM,WAAU;oBAAhB,CAA+C,EAAK,SAAS,QAAO,OAAW;;SAC9E,KAAc,EAAW,WAAW,UACnC,kBAAC,QAAD;UAAM,WAAU;oBACb,EAAW;SACR,CAAA;QAEL;;OACJ,KACC,kBAAC,KAAD;QAAG,WAAU;kBACV,EAAY,QAAQ,MAAM,GAAG,EAAE;OAC/B,CAAA;MAEL,EAAA,CAAA;KAED,GA5EE,EAAK,EA4EP;IAET,CAAC;GACE,CAAA;EAEJ,CAAA,CACF;;AAET"}
1
+ {"version":3,"file":"AssistantConversationList.js","names":[],"sources":["../../../src/components/assistant/AssistantConversationList.tsx"],"sourcesContent":["import { useState, type FC } from 'react';\nimport { Plus, Trash2, MessageSquare, PanelLeftClose, Pencil, Check } from 'lucide-react';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { ASSISTANT_MODES } from '@/types/assistant';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { chatTurns } from '../../utils/voiceTurnVisibility';\n\nexport const AssistantConversationList: FC = () => {\n const tr = useTr();\n const {\n conversations,\n activeConversationId,\n processingByConversationId,\n setActiveConversation,\n setMode,\n createConversation,\n deleteConversation,\n renameConversation,\n setConversationListOpen,\n } = useAssistantStore();\n\n const [editingId, setEditingId] = useState<string | null>(null);\n const [editTitle, setEditTitle] = useState('');\n\n const handleCreate = () => {\n createConversation();\n setConversationListOpen(false);\n };\n\n const handleSelect = (id: string) => {\n const selectedConversation = conversations.find((conversation) => conversation.id === id);\n setActiveConversation(id);\n if (selectedConversation) {\n setMode(selectedConversation.mode);\n }\n setConversationListOpen(false);\n };\n\n const handleStartRename = (id: string, currentTitle: string) => {\n setEditingId(id);\n setEditTitle(currentTitle);\n };\n\n const handleConfirmRename = () => {\n if (editingId && editTitle.trim()) {\n renameConversation(editingId, editTitle.trim());\n }\n setEditingId(null);\n };\n\n const handleDelete = (e: React.MouseEvent, id: string) => {\n e.stopPropagation();\n deleteConversation(id);\n };\n\n return (\n <div\n className=\"absolute inset-0 z-10 flex flex-col bg-bg-surface animate-in slide-in-from-left-2 fade-in duration-200\"\n data-testid=\"conversation-list\"\n >\n {/* Header */}\n <div className=\"flex items-center justify-between px-4 py-3 border-b border-border-default bg-bg-elevated\">\n <span className=\"text-[13px] font-semibold text-text-primary\">\n {tr('healthybowl.assistant.conversations.title', 'History')}\n </span>\n <div className=\"flex items-center gap-0.5\">\n <button\n type=\"button\"\n onClick={handleCreate}\n className=\"p-1.5 rounded-lg text-text-secondary hover:bg-bg-sunken transition-colors\"\n aria-label={tr('healthybowl.assistant.conversations.new', 'New conversation')}\n data-testid=\"new-conversation\"\n >\n <Plus className=\"size-4\" />\n </button>\n <button\n type=\"button\"\n onClick={() => setConversationListOpen(false)}\n className=\"flex items-center gap-1 px-2 py-1.5 rounded-lg text-text-secondary hover:bg-bg-sunken transition-colors\"\n aria-label={tr('healthybowl.assistant.conversations.collapse', 'Collapse history')}\n data-testid=\"collapse-conversation-list\"\n >\n <PanelLeftClose className=\"size-4\" />\n <span className=\"text-[11px] font-medium\">\n {tr('healthybowl.assistant.conversations.collapseLabel', 'Collapse')}\n </span>\n </button>\n </div>\n </div>\n\n {/* List */}\n <div className=\"flex-1 overflow-y-auto\">\n {conversations.length === 0 ? (\n <div className=\"flex flex-col items-center justify-center h-full text-center px-4\">\n <MessageSquare className=\"size-6 text-text-muted mb-2\" />\n <p className=\"text-xs text-text-muted\">\n {tr('healthybowl.assistant.conversations.empty', 'No conversations yet')}\n </p>\n <button\n type=\"button\"\n onClick={handleCreate}\n className=\"mt-2 text-xs text-action-primary-bg hover:underline\"\n >\n {tr('healthybowl.assistant.conversations.startNew', 'Start a new conversation')}\n </button>\n </div>\n ) : (\n <div className=\"py-1\">\n {conversations.map((conv) => {\n const isActive = conv.id === activeConversationId;\n const isEditing = conv.id === editingId;\n const modeConfig = ASSISTANT_MODES.find((m) => m.id === conv.mode);\n // ★ Preview the turns the thread will actually SHOW. Spoken turns\n // are deliberately kept out of the typed thread, so previewing the\n // raw array promised content the conversation then withheld: a\n // voice-only row displayed a title and a snippet, and opened onto\n // an empty screen. Filtering makes the row honest, and the badge\n // below says where the missing content went.\n const typedTurns = chatTurns(conv.messages);\n const lastMessage = typedTurns[typedTurns.length - 1];\n const spokenOnly = typedTurns.length === 0 && conv.messages.length > 0;\n const processing = processingByConversationId[conv.id];\n\n return (\n <div\n role=\"button\"\n tabIndex={0}\n onKeyDown={(e) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault();\n (() => !isEditing && handleSelect(conv.id))();\n }\n }}\n key={conv.id}\n onClick={() => !isEditing && handleSelect(conv.id)}\n className={`group px-3 py-2 cursor-pointer hover:bg-bg-elevated transition-colors ${\n isActive ? 'bg-bg-elevated border-l-2 border-action-primary-bg' : ''\n }`}\n >\n {isEditing ? (\n <div className=\"flex items-center gap-1\">\n <input\n aria-label={tr('healthybowl.assistant.conversations.renameLabel', 'Conversation title')}\n value={editTitle}\n onChange={(e) => setEditTitle(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === 'Enter') handleConfirmRename();\n if (e.key === 'Escape') setEditingId(null);\n }}\n className=\"flex-1 text-xs bg-bg-sunken border border-border-default rounded px-2 py-1 text-text-primary focus:outline-none focus:border-action-primary-bg\"\n onClick={(e) => e.stopPropagation()}\n />\n <button\n type=\"button\"\n onClick={(e) => {\n e.stopPropagation();\n handleConfirmRename();\n }}\n className=\"p-1 hover:bg-bg-sunken rounded\"\n aria-label={tr('healthybowl.assistant.conversations.saveTitle', 'Save title')}\n >\n <Check className=\"size-3 text-status-success-text\" />\n </button>\n </div>\n ) : (\n <>\n <div className=\"flex items-center justify-between\">\n <span className=\"text-xs font-medium text-text-primary truncate flex-1\">{conv.title}</span>\n <div className=\"hidden group-hover:flex group-focus-within:flex items-center gap-0.5 ml-1\">\n <button\n type=\"button\"\n onClick={(e) => {\n e.stopPropagation();\n handleStartRename(conv.id, conv.title);\n }}\n className=\"p-0.5 hover:bg-bg-sunken rounded\"\n aria-label={tr('healthybowl.assistant.conversations.rename', 'Rename conversation')}\n >\n <Pencil className=\"size-3 text-text-muted\" />\n </button>\n <button\n type=\"button\"\n onClick={(e) => handleDelete(e, conv.id)}\n className=\"p-0.5 hover:bg-bg-sunken rounded\"\n aria-label={tr('healthybowl.assistant.conversations.delete', 'Delete conversation')}\n data-testid=\"delete-conversation\"\n >\n <Trash2 className=\"size-3 text-status-error-text\" />\n </button>\n </div>\n </div>\n <div className=\"flex items-center gap-1.5 mt-0.5\">\n <span className=\"text-[10px] text-text-muted px-1 py-0.5 bg-bg-sunken rounded\">\n {modeConfig?.label ?? conv.mode}\n </span>\n <span className=\"text-[10px] text-text-muted\">{typedTurns.length} msgs</span>\n {processing && processing.status !== 'idle' && (\n <span className=\"text-[10px] text-action-primary-bg px-1 py-0.5 bg-bg-sunken rounded\">\n {processing.status}\n </span>\n )}\n </div>\n {lastMessage && (\n <p className=\"text-[10px] text-text-muted truncate mt-0.5\">\n {lastMessage.content.slice(0, 60)}\n </p>\n )}\n {spokenOnly && (\n <p className=\"text-[10px] text-text-muted truncate mt-0.5\">\n {tr('healthybowl.assistant.conversationList.voiceOnly', 'Spoken conversation')}\n </p>\n )}\n </>\n )}\n </div>\n );\n })}\n </div>\n )}\n </div>\n </div>\n );\n};\n"],"mappings":";;;;;;;;AAOA,IAAa,UAAsC;CACjD,IAAM,IAAK,EAAM,GACX,EACJ,kBACA,yBACA,+BACA,0BACA,YACA,uBACA,uBACA,uBACA,+BACE,EAAkB,GAEhB,CAAC,GAAW,KAAgB,EAAwB,IAAI,GACxD,CAAC,GAAW,KAAgB,EAAS,EAAE,GAEvC,UAAqB;EAEzB,AADA,EAAmB,GACnB,EAAwB,EAAK;CAC/B,GAEM,KAAgB,MAAe;EACnC,IAAM,IAAuB,EAAc,MAAM,MAAiB,EAAa,OAAO,CAAE;EAKxF,AAJA,EAAsB,CAAE,GACpB,KACF,EAAQ,EAAqB,IAAI,GAEnC,EAAwB,EAAK;CAC/B,GAEM,KAAqB,GAAY,MAAyB;EAE9D,AADA,EAAa,CAAE,GACf,EAAa,CAAY;CAC3B,GAEM,UAA4B;EAIhC,AAHI,KAAa,EAAU,KAAK,KAC9B,EAAmB,GAAW,EAAU,KAAK,CAAC,GAEhD,EAAa,IAAI;CACnB,GAEM,KAAgB,GAAqB,MAAe;EAExD,AADA,EAAE,gBAAgB,GAClB,EAAmB,CAAE;CACvB;CAEA,OACE,kBAAC,OAAD;EACE,WAAU;EACV,eAAY;YAFd,CAKE,kBAAC,OAAD;GAAK,WAAU;aAAf,CACE,kBAAC,QAAD;IAAM,WAAU;cACb,EAAG,6CAA6C,SAAS;GACtD,CAAA,GACN,kBAAC,OAAD;IAAK,WAAU;cAAf,CACE,kBAAC,UAAD;KACE,MAAK;KACL,SAAS;KACT,WAAU;KACV,cAAY,EA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AW,UACnC,kBAAC,QAAD;UAAM,WAAU;oBACb,EAAW;SACR,CAAA;QAEL;;OACJ,KACC,kBAAC,KAAD;QAAG,WAAU;kBACV,EAAY,QAAQ,MAAM,GAAG,EAAE;OAC/B,CAAA;OAEJ,KACC,kBAAC,KAAD;QAAG,WAAU;kBACV,EAAG,oDAAoD,qBAAqB;OAC5E,CAAA;MAEL,EAAA,CAAA;KAED,GAjFE,EAAK,EAiFP;IAET,CAAC;GACE,CAAA;EAEJ,CAAA,CACF;;AAET"}
@@ -6,7 +6,7 @@ var t = ({ text: t, role: n, expanded: r, testId: i }) => {
6
6
  className: "flex w-full justify-center",
7
7
  children: /* @__PURE__ */ e("p", {
8
8
  className: [
9
- "w-full whitespace-pre-wrap text-left",
9
+ "w-full whitespace-pre-wrap break-words text-left",
10
10
  r ? "max-w-[45rem]" : "max-w-md",
11
11
  a ? "font-semibold text-text-primary" : "font-medium text-text-secondary",
12
12
  r ? a ? "text-[clamp(1.625rem,2.5vw,2.25rem)] leading-[1.5]" : "text-[clamp(1.125rem,1.8vw,1.375rem)] leading-[1.5]" : a ? "text-lg leading-relaxed" : "text-base leading-relaxed"
@@ -1 +1 @@
1
- {"version":3,"file":"VoiceCaption.js","names":[],"sources":["../../../../src/components/assistant/voice/VoiceCaption.tsx"],"sourcesContent":["import type { FC } from 'react';\n\n/**\n * One live caption — either what the user is saying or what the assistant is.\n *\n * Replaces the message-bubble list the voice overlay used to render. That list\n * was the chat transcript squeezed into a modal: bubbles, the whole scrollback,\n * and raw `##`/`**` because it printed the model's markdown as plain text.\n *\n * Three things here are deliberate and were all wrong before:\n *\n * ★ **Left-aligned, not centred.** Centring is fine for one short line and\n * unreadable for four — every line starts in a different place, so the eye has\n * to hunt for each beginning. Tamil/English mixed text makes it worse, because\n * the line lengths vary wildly. The BLOCK is centred on the stage; the text\n * inside it is not.\n *\n * ★ **Responsive type, not one fixed size.** `clamp()` so the same component is\n * legible in a 380px docked panel and from arm's length on a maximised desktop\n * window, without a second component or a transform.\n *\n * ★ **Bounded width.** A caption spanning a 1440px window is one long line the\n * eye cannot track back from, so the measure is capped — 45rem / 720px on the\n * full-screen stage, the middle of the 680-760px the design calls for.\n *\n * ★ That measure is deliberately NOT the 60-75 characters typography usually\n * aims at: at 36px type 720px carries roughly 40. A voice caption is glanced at\n * from arm's length while someone is talking, not read as prose, and the size\n * is what makes it glanceable — so the two constraints are set independently\n * and the width follows the spec rather than the usual reading rule.\n */\n\ninterface Props {\n text: string;\n /** Who is speaking. The assistant's caption is the loud one. */\n role: 'user' | 'assistant';\n /** Full-screen rather than docked in the panel. */\n expanded: boolean;\n testId?: string;\n}\n\nexport const VoiceCaption: FC<Props> = ({ text, role, expanded, testId }) => {\n const assistant = role === 'assistant';\n return (\n <div className=\"flex w-full justify-center\">\n <p\n className={[\n // Left-aligned inside a centred block — see above.\n // ★ `toCaptionText` PRESERVES newlines; without pre-wrap they collapse\n // and a multi-paragraph answer renders as one wall of text.\n 'w-full whitespace-pre-wrap text-left',\n // 45rem = 720px, mid-band. Arbitrary value on purpose: Tailwind's\n // max-w-2xl is 672px and max-w-3xl 768px, so neither preset lands\n // inside 680-760.\n expanded ? 'max-w-[45rem]' : 'max-w-md',\n assistant ? 'font-semibold text-text-primary' : 'font-medium text-text-secondary',\n expanded\n ? assistant\n ? // 26-36px. ★ The floor is coupled to VoiceStage's empty-caption\n // reserve, which is 3x this value (two lines at 1.5 leading) so\n // the control does not jump when the first words arrive — move\n // one and the other has to move with it.\n 'text-[clamp(1.625rem,2.5vw,2.25rem)] leading-[1.5]'\n : // The USER caption is deliberately quieter and is not part of\n // the 26-36px band, which specifies the assistant's line.\n 'text-[clamp(1.125rem,1.8vw,1.375rem)] leading-[1.5]'\n : assistant\n ? 'text-lg leading-relaxed'\n : 'text-base leading-relaxed',\n ].join(' ')}\n // The stage's live region: the caption is what actually changes, so a\n // screen reader should hear it rather than only the status word.\n role=\"status\"\n aria-live=\"polite\"\n data-testid={testId}\n >\n {text}\n </p>\n </div>\n );\n};\n"],"mappings":";;AAyCA,IAAa,KAA2B,EAAE,SAAM,SAAM,aAAU,gBAAa;CAC3E,IAAM,IAAY,MAAS;CAC3B,OACE,kBAAC,OAAD;EAAK,WAAU;YACb,kBAAC,KAAD;GACE,WAAW;IAIT;IAIA,IAAW,kBAAkB;IAC7B,IAAY,oCAAoC;IAChD,IACI,IAKE,uDAGA,wDACF,IACE,4BACA;GACR,EAAE,KAAK,GAAG;GAGV,MAAK;GACL,aAAU;GACV,eAAa;aAEZ;EACA,CAAA;CACA,CAAA;AAET"}
1
+ {"version":3,"file":"VoiceCaption.js","names":[],"sources":["../../../../src/components/assistant/voice/VoiceCaption.tsx"],"sourcesContent":["import type { FC } from 'react';\n\n/**\n * One live caption — either what the user is saying or what the assistant is.\n *\n * Replaces the message-bubble list the voice overlay used to render. That list\n * was the chat transcript squeezed into a modal: bubbles, the whole scrollback,\n * and raw `##`/`**` because it printed the model's markdown as plain text.\n *\n * Three things here are deliberate and were all wrong before:\n *\n * ★ **Left-aligned, not centred.** Centring is fine for one short line and\n * unreadable for four — every line starts in a different place, so the eye has\n * to hunt for each beginning. Tamil/English mixed text makes it worse, because\n * the line lengths vary wildly. The BLOCK is centred on the stage; the text\n * inside it is not.\n *\n * ★ **Responsive type, not one fixed size.** `clamp()` so the same component is\n * legible in a 380px docked panel and from arm's length on a maximised desktop\n * window, without a second component or a transform.\n *\n * ★ **Bounded width.** A caption spanning a 1440px window is one long line the\n * eye cannot track back from, so the measure is capped — 45rem / 720px on the\n * full-screen stage, the middle of the 680-760px the design calls for.\n *\n * ★ That measure is deliberately NOT the 60-75 characters typography usually\n * aims at: at 36px type 720px carries roughly 40. A voice caption is glanced at\n * from arm's length while someone is talking, not read as prose, and the size\n * is what makes it glanceable — so the two constraints are set independently\n * and the width follows the spec rather than the usual reading rule.\n */\n\ninterface Props {\n text: string;\n /** Who is speaking. The assistant's caption is the loud one. */\n role: 'user' | 'assistant';\n /** Full-screen rather than docked in the panel. */\n expanded: boolean;\n testId?: string;\n}\n\nexport const VoiceCaption: FC<Props> = ({ text, role, expanded, testId }) => {\n const assistant = role === 'assistant';\n return (\n <div className=\"flex w-full justify-center\">\n <p\n className={[\n // Left-aligned inside a centred block — see above.\n // ★ `toCaptionText` PRESERVES newlines; without pre-wrap they collapse\n // and a multi-paragraph answer renders as one wall of text.\n // ★ `break-words` because nothing else may break a long unbroken run\n // — a URL, or a Tamil compound — and `pre-wrap` alone will not. The\n // chat renderer already carries it; the caption did not.\n 'w-full whitespace-pre-wrap break-words text-left',\n // 45rem = 720px, mid-band. Arbitrary value on purpose: Tailwind's\n // max-w-2xl is 672px and max-w-3xl 768px, so neither preset lands\n // inside 680-760.\n expanded ? 'max-w-[45rem]' : 'max-w-md',\n assistant ? 'font-semibold text-text-primary' : 'font-medium text-text-secondary',\n expanded\n ? assistant\n ? // 26-36px. ★ The floor is coupled to VoiceStage's empty-caption\n // reserve, which is 3x this value (two lines at 1.5 leading) so\n // the control does not jump when the first words arrive — move\n // one and the other has to move with it.\n 'text-[clamp(1.625rem,2.5vw,2.25rem)] leading-[1.5]'\n : // The USER caption is deliberately quieter and is not part of\n // the 26-36px band, which specifies the assistant's line.\n 'text-[clamp(1.125rem,1.8vw,1.375rem)] leading-[1.5]'\n : assistant\n ? 'text-lg leading-relaxed'\n : 'text-base leading-relaxed',\n ].join(' ')}\n // The stage's live region: the caption is what actually changes, so a\n // screen reader should hear it rather than only the status word.\n role=\"status\"\n aria-live=\"polite\"\n data-testid={testId}\n >\n {text}\n </p>\n </div>\n );\n};\n"],"mappings":";;AAyCA,IAAa,KAA2B,EAAE,SAAM,SAAM,aAAU,gBAAa;CAC3E,IAAM,IAAY,MAAS;CAC3B,OACE,kBAAC,OAAD;EAAK,WAAU;YACb,kBAAC,KAAD;GACE,WAAW;IAOT;IAIA,IAAW,kBAAkB;IAC7B,IAAY,oCAAoC;IAChD,IACI,IAKE,uDAGA,wDACF,IACE,4BACA;GACR,EAAE,KAAK,GAAG;GAGV,MAAK;GACL,aAAU;GACV,eAAa;aAEZ;EACA,CAAA;CACA,CAAA;AAET"}
@@ -38,7 +38,7 @@ var l = ({ state: l, userCaption: u, assistantCaption: d, expanded: f, statusTex
38
38
  expanded: f
39
39
  })
40
40
  }), g ? /* @__PURE__ */ s("div", {
41
- className: f ? "mb-12 max-h-[46vh] w-full overflow-y-auto" : "mb-6 w-full",
41
+ className: f ? "mb-12 max-h-[46vh] w-full overflow-y-auto" : "mb-6 max-h-[38vh] w-full overflow-y-auto",
42
42
  children: /* @__PURE__ */ s(e, {
43
43
  text: g,
44
44
  role: n(l) ? "assistant" : "user",
@@ -1 +1 @@
1
- {"version":3,"file":"VoiceStage.js","names":[],"sources":["../../../../src/components/assistant/voice/VoiceStage.tsx"],"sourcesContent":["import type { FC, ReactNode } from 'react';\nimport { VoiceCaption } from './VoiceCaption';\nimport { VoiceWaveform } from './VoiceWaveform';\nimport {\n waveformIsActive,\n waveformIsSettled,\n showsAssistantCaption,\n showsUserCaption,\n type VoiceStageState,\n} from '../../../utils/voiceStageState';\n\n/**\n * The middle of the voice panel: exactly ONE state, rendered as itself.\n *\n * What this replaces is the whole problem the operator screenshotted. The old\n * overlay showed, simultaneously: \"Listening…\", a microphone warning, the last\n * six messages of the chat conversation as bubbles (markdown syntax and all),\n * the assistant's answer AGAIN as a caption, and the orb. Five things competing,\n * none of them readable.\n *\n * ★ A stage shows one thing because the session IS one thing at a time. The\n * state is derived in `voiceStageState`, which is pure and tested; this file is\n * presentational and cannot be tested in this repo (vitest runs in `node`, no\n * DOM), so it deliberately contains no logic worth testing.\n *\n * The microphone warning is NOT rendered here. Mixing a system message into the\n * conversation area is what made it read as part of the reply; it belongs to\n * the chrome around the stage.\n */\n\ninterface Props {\n state: VoiceStageState;\n /** What the user is saying (live) or last said. */\n userCaption: string | null;\n /** What the assistant is saying. */\n assistantCaption: string | null;\n expanded: boolean;\n /** Status words — already localised by the caller. */\n statusText: string;\n /** The microphone / interrupt control. */\n control: ReactNode;\n /** Shown in the mic-error state instead of a caption. */\n errorText?: string | null;\n}\n\nexport const VoiceStage: FC<Props> = ({\n state,\n userCaption,\n assistantCaption,\n expanded,\n statusText,\n control,\n errorText = null,\n}) => {\n const caption = showsAssistantCaption(state) ? assistantCaption : showsUserCaption(state) ? userCaption : null;\n\n return (\n <div\n className={[\n 'flex min-h-0 w-full flex-1 flex-col items-center',\n expanded ? 'px-8' : 'px-14',\n // ★ Expanded, the group is anchored just above the optical centre\n // rather than centred in the whole box. Measured at 1440x900 the\n // content was 314px of a 756px stage with 221px of dead air above AND\n // below — technically centred, visually adrift. Docked the box is\n // small enough that centring is right.\n expanded ? 'justify-start pt-[16vh]' : 'justify-center',\n ].join(' ')}\n data-testid=\"assistant-voice-stage\"\n data-state={state}\n >\n {/* Status first and small: it is the label for the state, not the content. */}\n <p\n className={[\n 'text-center text-text-muted',\n expanded ? 'text-base' : 'text-sm',\n // The status LABELS the waveform, so it sits close to it. A uniform\n // gap made status, waveform, caption and control read as four\n // items of equal weight, with no hierarchy at all.\n expanded ? 'mb-3' : 'mb-2',\n ].join(' ')}\n // The stage change IS the feedback; without this a screen-reader user\n // is told nothing when connecting becomes listening becomes thinking.\n aria-live=\"polite\"\n data-testid=\"assistant-voice-status\"\n >\n {statusText}\n </p>\n\n {state === 'mic-error' ? (\n // A failure gets the stage to itself — no caption, no waveform. It is\n // not part of the conversation and must not look like it.\n <p\n className={`max-w-md text-center text-status-warning ${expanded ? 'text-lg' : 'text-sm'}`}\n role=\"alert\"\n data-testid=\"assistant-voice-stage-error\"\n >\n {errorText}\n </p>\n ) : (\n <>\n <div className={expanded ? 'mb-10' : 'mb-5'}>\n <VoiceWaveform\n // ★ `endpoint-grace` keeps the waveform ALIVE. It is the two-second\n // window in which the user may still correct themselves, so it has\n // to look like a microphone that is still open — a frozen waveform\n // would read as \"it stopped listening\", which is the opposite of\n // what the window is for. `interrupting` stays still on purpose:\n // the assistant has just been cut off and capture has not resumed.\n active={waveformIsActive(state)}\n settled={waveformIsSettled(state)}\n tone={state === 'speaking' ? 'speaking' : 'listening'}\n expanded={expanded}\n />\n </div>\n\n {caption ? (\n <div\n className={\n expanded\n ? // ★ A long reply used to run off the bottom of the screen with\n // no way to reach it. The model is asked for one to four\n // sentences, but that is guidance, not a guarantee — so the\n // caption is bounded and scrolls rather than being lost.\n 'mb-12 max-h-[46vh] w-full overflow-y-auto'\n : 'mb-6 w-full'\n }\n >\n <VoiceCaption\n text={caption}\n role={showsAssistantCaption(state) ? 'assistant' : 'user'}\n expanded={expanded}\n testId=\"assistant-voice-caption\"\n />\n </div>\n ) : (\n // Reserve the caption's space so the control does not jump when the\n // first words arrive. Two lines' worth at each size, matching what\n // a typical utterance actually occupies.\n //\n // ★ 4.875rem is 3x the assistant caption's MINIMUM (1.625rem at 1.5\n // leading = two lines), tracking the type floor as the old 4.5rem\n // tracked 1.5rem. Honest about what that does and does not buy: it\n // removes the jump only while the clamp is at its floor, i.e. up to\n // ~1040px viewport, and the reserve is sized to the ASSISTANT\n // caption while the common transition out of it is to the smaller\n // USER caption. It is a compromise between two captions of\n // different sizes, not a guarantee.\n <div className={expanded ? 'mb-12 h-[4.875rem]' : 'mb-6 h-12'} aria-hidden=\"true\" />\n )}\n </>\n )}\n\n {control}\n </div>\n );\n};\n"],"mappings":";;;;;AA6CA,IAAa,KAAyB,EACpC,UACA,gBACA,qBACA,aACA,eACA,YACA,eAAY,WACR;CACJ,IAAM,IAAU,EAAsB,CAAK,IAAI,IAAmB,EAAiB,CAAK,IAAI,IAAc;CAE1G,OACE,kBAAC,OAAD;EACE,WAAW;GACT;GACA,IAAW,SAAS;GAMpB,IAAW,4BAA4B;EACzC,EAAE,KAAK,GAAG;EACV,eAAY;EACZ,cAAY;YAZd;GAeE,kBAAC,KAAD;IACE,WAAW;KACT;KACA,IAAW,cAAc;KAIzB,IAAW,SAAS;IACtB,EAAE,KAAK,GAAG;IAGV,aAAU;IACV,eAAY;cAEX;GACA,CAAA;GAEF,MAAU,cAGT,kBAAC,KAAD;IACE,WAAW,4CAA4C,IAAW,YAAY;IAC9E,MAAK;IACL,eAAY;cAEX;GACA,CAAA,IAEH,kBAAA,GAAA,EAAA,UAAA,CACE,kBAAC,OAAD;IAAK,WAAW,IAAW,UAAU;cACnC,kBAAC,GAAD;KAOE,QAAQ,EAAiB,CAAK;KAC9B,SAAS,EAAkB,CAAK;KAChC,MAAM,MAAU,aAAa,aAAa;KAChC;IACX,CAAA;GACE,CAAA,GAEJ,IACC,kBAAC,OAAD;IACE,WACE,IAKI,8CACA;cAGN,kBAAC,GAAD;KACE,MAAM;KACN,MAAM,EAAsB,CAAK,IAAI,cAAc;KACzC;KACV,QAAO;IACR,CAAA;GACE,CAAA,IAcL,kBAAC,OAAD;IAAK,WAAW,IAAW,uBAAuB;IAAa,eAAY;GAAQ,CAAA,CAErF,EAAA,CAAA;GAGH;EACE;;AAET"}
1
+ {"version":3,"file":"VoiceStage.js","names":[],"sources":["../../../../src/components/assistant/voice/VoiceStage.tsx"],"sourcesContent":["import type { FC, ReactNode } from 'react';\nimport { VoiceCaption } from './VoiceCaption';\nimport { VoiceWaveform } from './VoiceWaveform';\nimport {\n waveformIsActive,\n waveformIsSettled,\n showsAssistantCaption,\n showsUserCaption,\n type VoiceStageState,\n} from '../../../utils/voiceStageState';\n\n/**\n * The middle of the voice panel: exactly ONE state, rendered as itself.\n *\n * What this replaces is the whole problem the operator screenshotted. The old\n * overlay showed, simultaneously: \"Listening…\", a microphone warning, the last\n * six messages of the chat conversation as bubbles (markdown syntax and all),\n * the assistant's answer AGAIN as a caption, and the orb. Five things competing,\n * none of them readable.\n *\n * ★ A stage shows one thing because the session IS one thing at a time. The\n * state is derived in `voiceStageState`, which is pure and tested; this file is\n * presentational and cannot be tested in this repo (vitest runs in `node`, no\n * DOM), so it deliberately contains no logic worth testing.\n *\n * The microphone warning is NOT rendered here. Mixing a system message into the\n * conversation area is what made it read as part of the reply; it belongs to\n * the chrome around the stage.\n */\n\ninterface Props {\n state: VoiceStageState;\n /** What the user is saying (live) or last said. */\n userCaption: string | null;\n /** What the assistant is saying. */\n assistantCaption: string | null;\n expanded: boolean;\n /** Status words — already localised by the caller. */\n statusText: string;\n /** The microphone / interrupt control. */\n control: ReactNode;\n /** Shown in the mic-error state instead of a caption. */\n errorText?: string | null;\n}\n\nexport const VoiceStage: FC<Props> = ({\n state,\n userCaption,\n assistantCaption,\n expanded,\n statusText,\n control,\n errorText = null,\n}) => {\n const caption = showsAssistantCaption(state) ? assistantCaption : showsUserCaption(state) ? userCaption : null;\n\n return (\n <div\n className={[\n 'flex min-h-0 w-full flex-1 flex-col items-center',\n expanded ? 'px-8' : 'px-14',\n // ★ Expanded, the group is anchored just above the optical centre\n // rather than centred in the whole box. Measured at 1440x900 the\n // content was 314px of a 756px stage with 221px of dead air above AND\n // below — technically centred, visually adrift. Docked the box is\n // small enough that centring is right.\n expanded ? 'justify-start pt-[16vh]' : 'justify-center',\n ].join(' ')}\n data-testid=\"assistant-voice-stage\"\n data-state={state}\n >\n {/* Status first and small: it is the label for the state, not the content. */}\n <p\n className={[\n 'text-center text-text-muted',\n expanded ? 'text-base' : 'text-sm',\n // The status LABELS the waveform, so it sits close to it. A uniform\n // gap made status, waveform, caption and control read as four\n // items of equal weight, with no hierarchy at all.\n expanded ? 'mb-3' : 'mb-2',\n ].join(' ')}\n // The stage change IS the feedback; without this a screen-reader user\n // is told nothing when connecting becomes listening becomes thinking.\n aria-live=\"polite\"\n data-testid=\"assistant-voice-status\"\n >\n {statusText}\n </p>\n\n {state === 'mic-error' ? (\n // A failure gets the stage to itself — no caption, no waveform. It is\n // not part of the conversation and must not look like it.\n <p\n className={`max-w-md text-center text-status-warning ${expanded ? 'text-lg' : 'text-sm'}`}\n role=\"alert\"\n data-testid=\"assistant-voice-stage-error\"\n >\n {errorText}\n </p>\n ) : (\n <>\n <div className={expanded ? 'mb-10' : 'mb-5'}>\n <VoiceWaveform\n // ★ `endpoint-grace` keeps the waveform ALIVE. It is the two-second\n // window in which the user may still correct themselves, so it has\n // to look like a microphone that is still open — a frozen waveform\n // would read as \"it stopped listening\", which is the opposite of\n // what the window is for. `interrupting` stays still on purpose:\n // the assistant has just been cut off and capture has not resumed.\n active={waveformIsActive(state)}\n settled={waveformIsSettled(state)}\n tone={state === 'speaking' ? 'speaking' : 'listening'}\n expanded={expanded}\n />\n </div>\n\n {caption ? (\n <div\n className={\n expanded\n ? // ★ A long reply used to run off the bottom of the screen with\n // no way to reach it. The model is asked for one to four\n // sentences, but that is guidance, not a guarantee — so the\n // caption is bounded and scrolls rather than being lost.\n 'mb-12 max-h-[46vh] w-full overflow-y-auto'\n : // ★ The SAME bound, which the docked panel never got. It is the\n // shorter surface of the two, so an unbounded caption there\n // pushed the orb — the only in-flow control — out of view and\n // clipped the rest of the answer with no way to scroll to it.\n 'mb-6 max-h-[38vh] w-full overflow-y-auto'\n }\n >\n <VoiceCaption\n text={caption}\n role={showsAssistantCaption(state) ? 'assistant' : 'user'}\n expanded={expanded}\n testId=\"assistant-voice-caption\"\n />\n </div>\n ) : (\n // Reserve the caption's space so the control does not jump when the\n // first words arrive. Two lines' worth at each size, matching what\n // a typical utterance actually occupies.\n //\n // ★ 4.875rem is 3x the assistant caption's MINIMUM (1.625rem at 1.5\n // leading = two lines), tracking the type floor as the old 4.5rem\n // tracked 1.5rem. Honest about what that does and does not buy: it\n // removes the jump only while the clamp is at its floor, i.e. up to\n // ~1040px viewport, and the reserve is sized to the ASSISTANT\n // caption while the common transition out of it is to the smaller\n // USER caption. It is a compromise between two captions of\n // different sizes, not a guarantee.\n <div className={expanded ? 'mb-12 h-[4.875rem]' : 'mb-6 h-12'} aria-hidden=\"true\" />\n )}\n </>\n )}\n\n {control}\n </div>\n );\n};\n"],"mappings":";;;;;AA6CA,IAAa,KAAyB,EACpC,UACA,gBACA,qBACA,aACA,eACA,YACA,eAAY,WACR;CACJ,IAAM,IAAU,EAAsB,CAAK,IAAI,IAAmB,EAAiB,CAAK,IAAI,IAAc;CAE1G,OACE,kBAAC,OAAD;EACE,WAAW;GACT;GACA,IAAW,SAAS;GAMpB,IAAW,4BAA4B;EACzC,EAAE,KAAK,GAAG;EACV,eAAY;EACZ,cAAY;YAZd;GAeE,kBAAC,KAAD;IACE,WAAW;KACT;KACA,IAAW,cAAc;KAIzB,IAAW,SAAS;IACtB,EAAE,KAAK,GAAG;IAGV,aAAU;IACV,eAAY;cAEX;GACA,CAAA;GAEF,MAAU,cAGT,kBAAC,KAAD;IACE,WAAW,4CAA4C,IAAW,YAAY;IAC9E,MAAK;IACL,eAAY;cAEX;GACA,CAAA,IAEH,kBAAA,GAAA,EAAA,UAAA,CACE,kBAAC,OAAD;IAAK,WAAW,IAAW,UAAU;cACnC,kBAAC,GAAD;KAOE,QAAQ,EAAiB,CAAK;KAC9B,SAAS,EAAkB,CAAK;KAChC,MAAM,MAAU,aAAa,aAAa;KAChC;IACX,CAAA;GACE,CAAA,GAEJ,IACC,kBAAC,OAAD;IACE,WACE,IAKI,8CAKA;cAGN,kBAAC,GAAD;KACE,MAAM;KACN,MAAM,EAAsB,CAAK,IAAI,cAAc;KACzC;KACV,QAAO;IACR,CAAA;GACE,CAAA,IAcL,kBAAC,OAAD;IAAK,WAAW,IAAW,uBAAuB;IAAa,eAAY;GAAQ,CAAA,CAErF,EAAA,CAAA;GAGH;EACE;;AAET"}
@@ -8,7 +8,7 @@ var a = ({ turns: a, onClose: o }) => {
8
8
  return /* @__PURE__ */ i("div", {
9
9
  className: "absolute inset-0 z-30 flex flex-col bg-bg-sunken/95 backdrop-blur-sm",
10
10
  role: "dialog",
11
- "aria-label": s("healthybowl.assistant.voiceSession.transcript", "Voice transcript"),
11
+ "aria-label": s("healthybowl.assistant.voiceSession.transcriptTitle", "Voice transcript"),
12
12
  "data-testid": "assistant-voice-transcript",
13
13
  children: [/* @__PURE__ */ i("div", {
14
14
  className: "flex items-center justify-between border-b border-border-subtle px-4 py-3",
@@ -19,7 +19,7 @@ var a = ({ turns: a, onClose: o }) => {
19
19
  children: s("healthybowl.assistant.voiceSession.transcript", "Voice conversation")
20
20
  }), /* @__PURE__ */ r("p", {
21
21
  className: "truncate text-xs text-text-muted",
22
- children: s("healthybowl.assistant.voiceSession.transcriptHint", "This session only — kept out of your typed chat.")
22
+ children: s("healthybowl.assistant.voiceSession.transcriptHint", "Spoken turns in this conversation — kept out of your typed chat.")
23
23
  })]
24
24
  }), /* @__PURE__ */ r("button", {
25
25
  type: "button",
@@ -1 +1 @@
1
- {"version":3,"file":"VoiceTranscriptDrawer.js","names":[],"sources":["../../../../src/components/assistant/voice/VoiceTranscriptDrawer.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { X } from 'lucide-react';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { VoiceConversationView } from './VoiceConversationView';\n\n/**\n * This session's spoken turns, on demand.\n *\n * The stage shows only what is happening NOW, which is right for a live\n * conversation and would otherwise mean the history is simply gone. This is\n * where it goes: secondary, behind a button, and explicitly a VOICE transcript\n * rather than the chat thread.\n *\n * ★ `z-30` is not decoration: the session container is `z-20` docked and\n * `z-[60]` expanded, and a child at `z-10` painted BEHIND its own parent — the\n * drawer opened and was invisible. Stacking contexts are per-parent, so this\n * only has to beat its siblings, not the overlay itself.\n *\n * ★ Session-scoped and ephemeral by design. It renders the turns it is handed —\n * which are already filtered to this voice session — so it can never resurrect\n * the typed conversation the old overlay used to paint.\n */\n\ninterface Props {\n turns: ReadonlyArray<{ id: string; role: 'user' | 'assistant'; text: string }>;\n onClose: () => void;\n}\n\nexport const VoiceTranscriptDrawer: FC<Props> = ({ turns, onClose }) => {\n const tr = useTr();\n return (\n <div\n className=\"absolute inset-0 z-30 flex flex-col bg-bg-sunken/95 backdrop-blur-sm\"\n role=\"dialog\"\n aria-label={tr('healthybowl.assistant.voiceSession.transcript', 'Voice transcript')}\n data-testid=\"assistant-voice-transcript\"\n >\n <div className=\"flex items-center justify-between border-b border-border-subtle px-4 py-3\">\n <div className=\"min-w-0\">\n <h2 className=\"text-sm font-semibold text-text-primary\">\n {tr('healthybowl.assistant.voiceSession.transcript', 'Voice conversation')}\n </h2>\n {/* Say plainly that this is NOT the typed thread, so nobody wonders\n why it is not in their chat history. */}\n <p className=\"truncate text-xs text-text-muted\">\n {tr(\n 'healthybowl.assistant.voiceSession.transcriptHint',\n 'This session only — kept out of your typed chat.'\n )}\n </p>\n </div>\n <button\n type=\"button\"\n onClick={onClose}\n className=\"flex size-8 items-center justify-center rounded-full 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-label={tr('healthybowl.assistant.voiceSession.transcriptClose', 'Close the transcript')}\n data-testid=\"assistant-voice-transcript-close\"\n >\n <X className=\"size-4\" />\n </button>\n </div>\n\n <VoiceConversationView turns={turns} />\n </div>\n );\n};\n"],"mappings":";;;;;AA4BA,IAAa,KAAoC,EAAE,UAAO,iBAAc;CACtE,IAAM,IAAK,EAAM;CACjB,OACE,kBAAC,OAAD;EACE,WAAU;EACV,MAAK;EACL,cAAY,EAAG,iDAAiD,kBAAkB;EAClF,eAAY;YAJd,CAME,kBAAC,OAAD;GAAK,WAAU;aAAf,CACE,kBAAC,OAAD;IAAK,WAAU;cAAf,CACE,kBAAC,MAAD;KAAI,WAAU;eACX,EAAG,iDAAiD,oBAAoB;IACvE,CAAA,GAGJ,kBAAC,KAAD;KAAG,WAAU;eACV,EACC,qDACA,kDACF;IACC,CAAA,CACA;OACL,kBAAC,UAAD;IACE,MAAK;IACL,SAAS;IACT,WAAU;IACV,cAAY,EAAG,sDAAsD,sBAAsB;IAC3F,eAAY;cAEZ,kBAAC,GAAD,EAAG,WAAU,SAAU,CAAA;GACjB,CAAA,CACL;MAEL,kBAAC,GAAD,EAA8B,SAAQ,CAAA,CACnC;;AAET"}
1
+ {"version":3,"file":"VoiceTranscriptDrawer.js","names":[],"sources":["../../../../src/components/assistant/voice/VoiceTranscriptDrawer.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { X } from 'lucide-react';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { VoiceConversationView } from './VoiceConversationView';\n\n/**\n * This session's spoken turns, on demand.\n *\n * The stage shows only what is happening NOW, which is right for a live\n * conversation and would otherwise mean the history is simply gone. This is\n * where it goes: secondary, behind a button, and explicitly a VOICE transcript\n * rather than the chat thread.\n *\n * ★ `z-30` is not decoration: the session container is `z-20` docked and\n * `z-[60]` expanded, and a child at `z-10` painted BEHIND its own parent — the\n * drawer opened and was invisible. Stacking contexts are per-parent, so this\n * only has to beat its siblings, not the overlay itself.\n *\n * ★ Session-scoped and ephemeral by design. It renders the turns it is handed —\n * which are already filtered to this voice session — so it can never resurrect\n * the typed conversation the old overlay used to paint.\n */\n\ninterface Props {\n turns: ReadonlyArray<{ id: string; role: 'user' | 'assistant'; text: string }>;\n onClose: () => void;\n}\n\nexport const VoiceTranscriptDrawer: FC<Props> = ({ turns, onClose }) => {\n const tr = useTr();\n return (\n <div\n className=\"absolute inset-0 z-30 flex flex-col bg-bg-sunken/95 backdrop-blur-sm\"\n role=\"dialog\"\n // ★ Its OWN key. This shared `…voiceSession.transcript` with the heading\n // below while giving it a different English default, so once the key is\n // seeded one of the two silently changes to the other's wording.\n aria-label={tr('healthybowl.assistant.voiceSession.transcriptTitle', 'Voice transcript')}\n data-testid=\"assistant-voice-transcript\"\n >\n <div className=\"flex items-center justify-between border-b border-border-subtle px-4 py-3\">\n <div className=\"min-w-0\">\n <h2 className=\"text-sm font-semibold text-text-primary\">\n {tr('healthybowl.assistant.voiceSession.transcript', 'Voice conversation')}\n </h2>\n {/* Say plainly that this is NOT the typed thread, so nobody wonders\n why it is not in their chat history.\n\n ★ It used to say \"This session only\", which was not true:\n `voiceTurnsOnly` filters on a per-message marker, so it returns every\n spoken turn in the CONVERSATION, and a second voice session showed the\n first one's turns under a promise that it would not. Showing the whole\n conversation's spoken history is the more useful behaviour of the two,\n so the wording changed rather than the filter. */}\n <p className=\"truncate text-xs text-text-muted\">\n {tr(\n 'healthybowl.assistant.voiceSession.transcriptHint',\n 'Spoken turns in this conversation — kept out of your typed chat.'\n )}\n </p>\n </div>\n <button\n type=\"button\"\n onClick={onClose}\n className=\"flex size-8 items-center justify-center rounded-full 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-label={tr('healthybowl.assistant.voiceSession.transcriptClose', 'Close the transcript')}\n data-testid=\"assistant-voice-transcript-close\"\n >\n <X className=\"size-4\" />\n </button>\n </div>\n\n <VoiceConversationView turns={turns} />\n </div>\n );\n};\n"],"mappings":";;;;;AA4BA,IAAa,KAAoC,EAAE,UAAO,iBAAc;CACtE,IAAM,IAAK,EAAM;CACjB,OACE,kBAAC,OAAD;EACE,WAAU;EACV,MAAK;EAIL,cAAY,EAAG,sDAAsD,kBAAkB;EACvF,eAAY;YAPd,CASE,kBAAC,OAAD;GAAK,WAAU;aAAf,CACE,kBAAC,OAAD;IAAK,WAAU;cAAf,CACE,kBAAC,MAAD;KAAI,WAAU;eACX,EAAG,iDAAiD,oBAAoB;IACvE,CAAA,GAUJ,kBAAC,KAAD;KAAG,WAAU;eACV,EACC,qDACA,kEACF;IACC,CAAA,CACA;OACL,kBAAC,UAAD;IACE,MAAK;IACL,SAAS;IACT,WAAU;IACV,cAAY,EAAG,sDAAsD,sBAAsB;IAC3F,eAAY;cAEZ,kBAAC,GAAD,EAAG,WAAU,SAAU,CAAA;GACjB,CAAA,CACL;MAEL,kBAAC,GAAD,EAA8B,SAAQ,CAAA,CACnC;;AAET"}
@@ -1,5 +1,15 @@
1
1
  //#region src/config/speechLabels.ts
2
2
  var e = {
3
+ en: {
4
+ codeBlock: "Code block",
5
+ image: "image",
6
+ link: "link",
7
+ largeTable: "Table with {{rows}} rows and {{columns}} columns",
8
+ truncated: "The rest of this message is not read aloud",
9
+ nestedItem: "Sub-item {{ordinal}}",
10
+ emailAt: "at",
11
+ emailDot: "dot"
12
+ },
3
13
  ta: {
4
14
  codeBlock: "நிரல் தொகுதி",
5
15
  image: "படம்",
@@ -1 +1 @@
1
- {"version":3,"file":"speechLabels.js","names":[],"sources":["../../src/config/speechLabels.ts"],"sourcesContent":["import type { SpeakableLabels } from '../utils/speakableText';\n\n/**\n * The spoken stand-ins, in the language of the REPLY (BOFF-7120).\n *\n * When a reply contains something that cannot be read aloud — an image, a link,\n * a fenced code block, a wide table — the reader substitutes a word. Those words\n * used to come from `tr()`, which resolves against the INTERFACE language. So an\n * English interface reading a Tamil answer said \"Code block\" and \"image\" in\n * English, dropped into the middle of a Tamil sentence. Exactly the complaint\n * that produced the translatable `at`/`dot` for email addresses; that fix was\n * applied there and nowhere else.\n *\n * ★ Why a static table rather than `tr()` with a locale argument: the i18n\n * provider only ever FETCHES the active locale. `I18nContextValue.translations`\n * holds that one dictionary, so there is nothing to ask for Tamil while the\n * interface is English — the strings simply are not in the client. These eight\n * are short, stable, and needed synchronously mid-utterance, so they are carried\n * here instead.\n *\n * Anything not listed falls back to the interface-language label, which is what\n * happens today — so this can only improve on the current behaviour, never\n * regress it.\n */\ntype PartialLabels = Partial<SpeakableLabels>;\n\n/** Keyed by primary language subtag, since the reply locale may carry a region. */\nconst LABELS_BY_LANGUAGE: Record<string, PartialLabels> = {\n ta: {\n codeBlock: 'நிரல் தொகுதி',\n image: 'படம்',\n link: 'இணைப்பு',\n largeTable: '{{rows}} வரிசைகள் மற்றும் {{columns}} நெடுவரிசைகள் கொண்ட அட்டவணை',\n truncated: 'இந்தச் செய்தியின் மீதமுள்ள பகுதி வாசிக்கப்படவில்லை',\n nestedItem: 'துணை உருப்படி {{ordinal}}',\n emailAt: 'அட்',\n emailDot: 'புள்ளி',\n },\n hi: {\n codeBlock: 'कोड ब्लॉक',\n image: 'छवि',\n link: 'लिंक',\n largeTable: '{{rows}} पंक्तियों और {{columns}} स्तंभों वाली तालिका',\n truncated: 'इस संदेश का शेष भाग नहीं पढ़ा जाता',\n nestedItem: 'उप-आइटम {{ordinal}}',\n emailAt: 'ऐट',\n emailDot: 'डॉट',\n },\n ar: {\n codeBlock: 'كتلة برمجية',\n image: 'صورة',\n link: 'رابط',\n largeTable: 'جدول من {{rows}} صفوف و {{columns}} أعمدة',\n truncated: 'لا تتم قراءة بقية هذه الرسالة بصوت عالٍ',\n nestedItem: 'عنصر فرعي {{ordinal}}',\n emailAt: 'أت',\n emailDot: 'نقطة',\n },\n es: {\n codeBlock: 'Bloque de código',\n image: 'imagen',\n link: 'enlace',\n largeTable: 'Tabla con {{rows}} filas y {{columns}} columnas',\n truncated: 'El resto de este mensaje no se lee en voz alta',\n nestedItem: 'Subelemento {{ordinal}}',\n emailAt: 'arroba',\n emailDot: 'punto',\n },\n zh: {\n codeBlock: '代码块',\n image: '图片',\n link: '链接',\n largeTable: '包含 {{rows}} 行 {{columns}} 列的表格',\n truncated: '此消息的其余部分不会朗读',\n nestedItem: '子项 {{ordinal}}',\n emailAt: 'at',\n emailDot: '点',\n },\n};\n\n/**\n * Labels to read a reply in `locale` with.\n *\n * `uiLabels` is the interface-language set, used both as the base and as the\n * fallback for any language not carried here — so English replies, and any\n * language we have no table for, behave exactly as before.\n */\nexport function speechLabelsFor(locale: string, uiLabels: SpeakableLabels): SpeakableLabels {\n const primary = locale.trim().toLowerCase().split(/[-_]/)[0];\n if (!primary) return uiLabels;\n const overrides = LABELS_BY_LANGUAGE[primary];\n return overrides ? { ...uiLabels, ...overrides } : uiLabels;\n}\n\n/** Exposed for tests: which languages have their own spoken labels. */\nexport const SPOKEN_LABEL_LANGUAGES = Object.keys(LABELS_BY_LANGUAGE);\n"],"mappings":";AA2BA,IAAM,IAAoD;CACxD,IAAI;EACF,WAAW;EACX,OAAO;EACP,MAAM;EACN,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS;EACT,UAAU;CACZ;CACA,IAAI;EACF,WAAW;EACX,OAAO;EACP,MAAM;EACN,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS;EACT,UAAU;CACZ;CACA,IAAI;EACF,WAAW;EACX,OAAO;EACP,MAAM;EACN,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS;EACT,UAAU;CACZ;CACA,IAAI;EACF,WAAW;EACX,OAAO;EACP,MAAM;EACN,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS;EACT,UAAU;CACZ;CACA,IAAI;EACF,WAAW;EACX,OAAO;EACP,MAAM;EACN,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS;EACT,UAAU;CACZ;AACF;AASA,SAAgB,EAAgB,GAAgB,GAA4C;CAC1F,IAAM,IAAU,EAAO,KAAK,EAAE,YAAY,EAAE,MAAM,MAAM,EAAE;CAC1D,IAAI,CAAC,GAAS,OAAO;CACrB,IAAM,IAAY,EAAmB;CACrC,OAAO,IAAY;EAAE,GAAG;EAAU,GAAG;CAAU,IAAI;AACrD"}
1
+ {"version":3,"file":"speechLabels.js","names":[],"sources":["../../src/config/speechLabels.ts"],"sourcesContent":["import type { SpeakableLabels } from '../utils/speakableText';\n\n/**\n * The spoken stand-ins, in the language of the REPLY (BOFF-7120).\n *\n * When a reply contains something that cannot be read aloud — an image, a link,\n * a fenced code block, a wide table — the reader substitutes a word. Those words\n * used to come from `tr()`, which resolves against the INTERFACE language. So an\n * English interface reading a Tamil answer said \"Code block\" and \"image\" in\n * English, dropped into the middle of a Tamil sentence. Exactly the complaint\n * that produced the translatable `at`/`dot` for email addresses; that fix was\n * applied there and nowhere else.\n *\n * ★ Why a static table rather than `tr()` with a locale argument: the i18n\n * provider only ever FETCHES the active locale. `I18nContextValue.translations`\n * holds that one dictionary, so there is nothing to ask for Tamil while the\n * interface is English — the strings simply are not in the client. These eight\n * are short, stable, and needed synchronously mid-utterance, so they are carried\n * here instead.\n *\n * Anything not listed falls back to the interface-language label, which is what\n * happens today — so this can only improve on the current behaviour, never\n * regress it.\n */\ntype PartialLabels = Partial<SpeakableLabels>;\n\n/** Keyed by primary language subtag, since the reply locale may carry a region. */\nconst LABELS_BY_LANGUAGE: Record<string, PartialLabels> = {\n /**\n * ★ English is carried explicitly, and it is not redundant.\n *\n * The fallback below is the INTERFACE language, so a language with no table of\n * its own inherits whatever the menu is set to. That is right for an unlisted\n * language, and exactly wrong for English: with a Tamil interface and an\n * English reply, `tr()` returned the Tamil words and spliced \"நிரல் தொகுதி\"\n * into an English sentence — the very defect this table exists to prevent,\n * running the other way. Naming English pins it regardless of the menu.\n *\n * These are the same strings as the English defaults in `speakableText.ts`;\n * unlike the others they need no translator, which is why this one entry is\n * here while the remaining locales are not.\n */\n en: {\n codeBlock: 'Code block',\n image: 'image',\n link: 'link',\n largeTable: 'Table with {{rows}} rows and {{columns}} columns',\n truncated: 'The rest of this message is not read aloud',\n nestedItem: 'Sub-item {{ordinal}}',\n emailAt: 'at',\n emailDot: 'dot',\n },\n ta: {\n codeBlock: 'நிரல் தொகுதி',\n image: 'படம்',\n link: 'இணைப்பு',\n largeTable: '{{rows}} வரிசைகள் மற்றும் {{columns}} நெடுவரிசைகள் கொண்ட அட்டவணை',\n truncated: 'இந்தச் செய்தியின் மீதமுள்ள பகுதி வாசிக்கப்படவில்லை',\n nestedItem: 'துணை உருப்படி {{ordinal}}',\n emailAt: 'அட்',\n emailDot: 'புள்ளி',\n },\n hi: {\n codeBlock: 'कोड ब्लॉक',\n image: 'छवि',\n link: 'लिंक',\n largeTable: '{{rows}} पंक्तियों और {{columns}} स्तंभों वाली तालिका',\n truncated: 'इस संदेश का शेष भाग नहीं पढ़ा जाता',\n nestedItem: 'उप-आइटम {{ordinal}}',\n emailAt: 'ऐट',\n emailDot: 'डॉट',\n },\n ar: {\n codeBlock: 'كتلة برمجية',\n image: 'صورة',\n link: 'رابط',\n largeTable: 'جدول من {{rows}} صفوف و {{columns}} أعمدة',\n truncated: 'لا تتم قراءة بقية هذه الرسالة بصوت عالٍ',\n nestedItem: 'عنصر فرعي {{ordinal}}',\n emailAt: 'أت',\n emailDot: 'نقطة',\n },\n es: {\n codeBlock: 'Bloque de código',\n image: 'imagen',\n link: 'enlace',\n largeTable: 'Tabla con {{rows}} filas y {{columns}} columnas',\n truncated: 'El resto de este mensaje no se lee en voz alta',\n nestedItem: 'Subelemento {{ordinal}}',\n emailAt: 'arroba',\n emailDot: 'punto',\n },\n zh: {\n codeBlock: '代码块',\n image: '图片',\n link: '链接',\n largeTable: '包含 {{rows}} 行 {{columns}} 列的表格',\n truncated: '此消息的其余部分不会朗读',\n nestedItem: '子项 {{ordinal}}',\n emailAt: 'at',\n emailDot: '点',\n },\n};\n\n/**\n * Labels to read a reply in `locale` with.\n *\n * `uiLabels` is the interface-language set, used both as the base and as the\n * fallback for any language not carried here — so English replies, and any\n * language we have no table for, behave exactly as before.\n */\nexport function speechLabelsFor(locale: string, uiLabels: SpeakableLabels): SpeakableLabels {\n const primary = locale.trim().toLowerCase().split(/[-_]/)[0];\n if (!primary) return uiLabels;\n const overrides = LABELS_BY_LANGUAGE[primary];\n return overrides ? { ...uiLabels, ...overrides } : uiLabels;\n}\n\n/** Exposed for tests: which languages have their own spoken labels. */\nexport const SPOKEN_LABEL_LANGUAGES = Object.keys(LABELS_BY_LANGUAGE);\n"],"mappings":";AA2BA,IAAM,IAAoD;CAexD,IAAI;EACF,WAAW;EACX,OAAO;EACP,MAAM;EACN,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS;EACT,UAAU;CACZ;CACA,IAAI;EACF,WAAW;EACX,OAAO;EACP,MAAM;EACN,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS;EACT,UAAU;CACZ;CACA,IAAI;EACF,WAAW;EACX,OAAO;EACP,MAAM;EACN,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS;EACT,UAAU;CACZ;CACA,IAAI;EACF,WAAW;EACX,OAAO;EACP,MAAM;EACN,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS;EACT,UAAU;CACZ;CACA,IAAI;EACF,WAAW;EACX,OAAO;EACP,MAAM;EACN,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS;EACT,UAAU;CACZ;CACA,IAAI;EACF,WAAW;EACX,OAAO;EACP,MAAM;EACN,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS;EACT,UAAU;CACZ;AACF;AASA,SAAgB,EAAgB,GAAgB,GAA4C;CAC1F,IAAM,IAAU,EAAO,KAAK,EAAE,YAAY,EAAE,MAAM,MAAM,EAAE;CAC1D,IAAI,CAAC,GAAS,OAAO;CACrB,IAAM,IAAY,EAAmB;CACrC,OAAO,IAAY;EAAE,GAAG;EAAU,GAAG;CAAU,IAAI;AACrD"}
@@ -57,6 +57,8 @@ function c({ onFinalize: c, language: l }) {
57
57
  t !== "no-speech" && g(t);
58
58
  }, t.onend = () => {
59
59
  n === v.current && (_.current = null, f(!1), m(""));
60
+ }, t.onstart = () => {
61
+ n === v.current && f(!0);
60
62
  };
61
63
  try {
62
64
  t.start();
@@ -64,7 +66,7 @@ function c({ onFinalize: c, language: l }) {
64
66
  _.current = null, f(!1);
65
67
  return;
66
68
  }
67
- _.current = t, g(null), m(""), f(!0);
69
+ _.current = t, g(null), m("");
68
70
  }, [x]), C = e(() => {
69
71
  let e = _.current;
70
72
  _.current = null, v.current += 1, e?.stop(), f(!1), m("");
@@ -1 +1 @@
1
- {"version":3,"file":"useVoiceInput.js","names":[],"sources":["../../src/hooks/useVoiceInput.ts"],"sourcesContent":["/**\n * Speech-to-text for the assistant composer (Workstream 2 of the AI Assistant\n * V2 multimodal effort).\n *\n * Input-only, browser-native (Web Speech API). It degrades gracefully:\n * `isSupported` is false on engines without SpeechRecognition (notably Firefox),\n * and the composer hides the mic entirely in that case rather than showing a\n * dead control.\n *\n * ⚠️ This does NOT mean the audio stays on the device. Chrome's\n * `webkitSpeechRecognition` is a NETWORK service — the audio is streamed to the\n * browser vendor for recognition, and the supported language list is theirs, not\n * ours. We neither receive nor store it, which is all an earlier version of this\n * comment (\"no audio ever leaves the device through us\") actually claimed; read\n * literally it implied something stronger and untrue. Whether recording farmers'\n * speech this way needs disclosure or consent is a product/legal call, not a\n * code one.\n *\n * Output (reading replies aloud) is a separate concern and lives in\n * `AssistantSpeechProvider`; an earlier version of this note said the assistant\n * does not speak, which stopped being true when BOFF-6290 shipped.\n *\n * Differences from the fe-libs `assistantWidget/useVoiceInput` this is modelled\n * on, all of which the composer needs:\n * - **interim results are exposed**, so the user sees words appear while\n * speaking instead of staring at a silent button until a phrase finalises;\n * - **errors are surfaced** (`error`) so a denied mic permission can be\n * explained rather than looking like a no-op;\n * - **the recogniser language follows the app locale** (a Tamil or Hindi\n * farmer dictating into an `en-US` recogniser gets garbage);\n * - **`stop()` resolves the final transcript** through `onFinalize`, so the\n * composer can commit exactly once when the user stops.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport type { Locale } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\n\ninterface SpeechRecognitionEventLike extends Event {\n results: SpeechRecognitionResultList;\n resultIndex: number;\n}\n\ninterface SpeechRecognitionErrorEventLike extends Event {\n error: string;\n message: string;\n}\n\ninterface SpeechRecognitionInstance extends EventTarget {\n continuous: boolean;\n interimResults: boolean;\n lang: string;\n start(): void;\n stop(): void;\n abort(): void;\n onresult: ((event: SpeechRecognitionEventLike) => void) | null;\n onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;\n onend: (() => void) | null;\n}\n\ntype SpeechRecognitionConstructor = new () => SpeechRecognitionInstance;\n\n/**\n * BCP-47 tag for the recogniser, per app locale. Regional choices follow where\n * HealthyBowl actually operates (India for ta/hi) rather than a generic tag,\n * because the recogniser's acoustic model is region-specific.\n */\nconst RECOGNITION_LANG: Record<Locale, string> = {\n en: 'en-US',\n es: 'es-ES',\n fr: 'fr-FR',\n de: 'de-DE',\n ja: 'ja-JP',\n zh: 'zh-CN',\n ta: 'ta-IN',\n hi: 'hi-IN',\n ar: 'ar-SA',\n};\n\nfunction getSpeechRecognitionConstructor(): SpeechRecognitionConstructor | null {\n if (typeof window === 'undefined') return null;\n const win = window as unknown as Record<string, unknown>;\n return (\n (win.SpeechRecognition as SpeechRecognitionConstructor | undefined) ??\n (win.webkitSpeechRecognition as SpeechRecognitionConstructor | undefined) ??\n null\n );\n}\n\nexport type VoiceInputError =\n 'not-allowed' | 'no-speech' | 'audio-capture' | 'network' | 'language-not-supported' | 'unknown';\n\n/**\n * Map the spec's `SpeechRecognitionErrorEvent.error` codes onto the cases the UI\n * actually distinguishes. Anything else is 'unknown' (generic copy).\n *\n * `language-not-supported` is called out separately because it is the single\n * most likely failure for the users this feature exists for: the recogniser's\n * language list belongs to the browser vendor, not to us, so a Tamil or Hindi\n * speaker can hit it on a browser that simply does not offer their language.\n * Folding it into 'unknown' produced \"Dictation stopped unexpectedly\", which\n * tells them nothing and reads like a bug in HealthyBowl.\n */\nfunction toVoiceInputError(code: string): VoiceInputError {\n switch (code) {\n case 'not-allowed':\n case 'service-not-allowed':\n return 'not-allowed';\n case 'no-speech':\n return 'no-speech';\n case 'audio-capture':\n return 'audio-capture';\n case 'network':\n return 'network';\n case 'language-not-supported':\n return 'language-not-supported';\n default:\n return 'unknown';\n }\n}\n\nexport interface UseVoiceInputOptions {\n /**\n * Called with each newly finalised phrase. The composer appends it to the\n * draft; keeping the committed text in the caller (rather than accumulating\n * here) means the user can freely edit while dictation continues.\n */\n onFinalize: (text: string) => void;\n /**\n * BCP-47 tag to listen for. Omit to follow the app locale, which is what this\n * hook did unconditionally before (BOFF-7108).\n *\n * The two are genuinely independent: a farmer whose interface is English may\n * well speak Tamil, and deriving the recogniser language from the UI meant the\n * only way to dictate Tamil was to translate the entire app.\n */\n language?: string;\n}\n\nexport interface UseVoiceInputResult {\n isSupported: boolean;\n isListening: boolean;\n /** Words recognised but not yet finalised — render as a live hint. */\n interim: string;\n error: VoiceInputError | null;\n /**\n * BCP-47 tag the recogniser was asked for. Exposed so error copy can name the\n * language that failed (\"Tamil dictation is not supported…\") rather than\n * leaving the user to guess which language the browser rejected.\n */\n language: string;\n start: () => void;\n stop: () => void;\n /** Start if idle, stop if listening — what the mic button binds to. */\n toggle: () => void;\n clearError: () => void;\n}\n\nexport function useVoiceInput({ onFinalize, language: requested }: UseVoiceInputOptions): UseVoiceInputResult {\n const { locale } = useI18n();\n const [isListening, setIsListening] = useState(false);\n const [interim, setInterim] = useState('');\n const [error, setError] = useState<VoiceInputError | null>(null);\n const recognitionRef = useRef<SpeechRecognitionInstance | null>(null);\n // Incremented on every stop. Handlers capture the session they were created\n // under and ignore events that arrive after it ends.\n const sessionRef = useRef(0);\n\n // Keep the newest callback reachable from the recogniser's long-lived event\n // handlers without re-creating the recogniser on every parent render.\n const onFinalizeRef = useRef(onFinalize);\n useEffect(() => {\n onFinalizeRef.current = onFinalize;\n }, [onFinalize]);\n\n const isSupported = getSpeechRecognitionConstructor() !== null;\n const language = requested ?? RECOGNITION_LANG[locale] ?? 'en-US';\n\n // Abort (not stop) on unmount: the panel is closing, so a trailing final\n // result would be committed into a draft nobody can see.\n useEffect(() => {\n return () => {\n recognitionRef.current?.abort();\n recognitionRef.current = null;\n };\n }, []);\n\n const start = useCallback(() => {\n const Ctor = getSpeechRecognitionConstructor();\n if (!Ctor || recognitionRef.current) return;\n\n const recognition = new Ctor();\n recognition.continuous = true;\n recognition.interimResults = true;\n recognition.lang = language;\n\n const session = sessionRef.current;\n\n recognition.onresult = (event) => {\n if (session !== sessionRef.current) return;\n let finalText = '';\n let interimText = '';\n for (let index = event.resultIndex; index < event.results.length; index += 1) {\n const result = event.results[index];\n const alternative = result[0]?.transcript ?? '';\n if (result.isFinal) {\n finalText += alternative;\n } else {\n interimText += alternative;\n }\n }\n if (finalText.trim()) onFinalizeRef.current(finalText.trim());\n setInterim(interimText.trim());\n };\n\n recognition.onerror = (event) => {\n if (session !== sessionRef.current) return;\n const mapped = toVoiceInputError(event.error);\n // 'no-speech' fires routinely during a natural pause and the recogniser\n // keeps running — surfacing it would flash a scary message mid-sentence.\n if (mapped !== 'no-speech') setError(mapped);\n };\n\n recognition.onend = () => {\n if (session !== sessionRef.current) return;\n recognitionRef.current = null;\n setIsListening(false);\n setInterim('');\n };\n\n try {\n recognition.start();\n } catch {\n // start() throws if a recogniser is somehow already running — treat the\n // session as not started rather than leaving the button stuck \"live\".\n recognitionRef.current = null;\n setIsListening(false);\n return;\n }\n\n recognitionRef.current = recognition;\n setError(null);\n setInterim('');\n setIsListening(true);\n }, [language]);\n\n const stop = useCallback(() => {\n // Detach BEFORE stopping. `onend` is what used to clear this ref, but it\n // arrives asynchronously — so a user who tapped stop and immediately tapped\n // the mic again hit `start()`'s `if (recognitionRef.current) return` guard\n // and got a silent no-op. Bumping the session also makes any trailing final\n // phrase the engine flushes on stop land on a dead session, instead of\n // reappearing in a draft the composer has already sent and cleared.\n const recognition = recognitionRef.current;\n recognitionRef.current = null;\n sessionRef.current += 1;\n recognition?.stop();\n setIsListening(false);\n setInterim('');\n }, []);\n\n // Changing language must END the session it no longer describes.\n //\n // A running recogniser keeps the `lang` it was constructed with, so after a\n // switch the in-flight session is still listening in the OLD language while\n // this hook already reports the new one. A late `language-not-supported` from\n // that session would then be rendered as though the browser had rejected the\n // language the user just picked. Clearing the error is not enough — the\n // session producing it has to go too.\n const languageRef = useRef(language);\n useEffect(() => {\n if (languageRef.current === language) return;\n languageRef.current = language;\n stop();\n setError(null);\n }, [language, stop]);\n\n const toggle = useCallback(() => {\n if (isListening) stop();\n else start();\n }, [isListening, start, stop]);\n\n const clearError = useCallback(() => setError(null), []);\n\n return { isSupported, isListening, interim, error, language, start, stop, toggle, clearError };\n}\n"],"mappings":";;;AAmEA,IAAM,IAA2C;CAC/C,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;AACN;AAEA,SAAS,IAAuE;CAC9E,IAAI,OAAO,SAAW,KAAa,OAAO;CAC1C,IAAM,IAAM;CACZ,OACG,EAAI,qBACJ,EAAI,2BACL;AAEJ;AAgBA,SAAS,EAAkB,G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AC;EAC/B,GAEA,EAAY,WAAW,MAAU;GAC/B,IAAI,MAAY,EAAW,SAAS;GACpC,IAAM,IAAS,EAAkB,EAAM,KAAK;GAG5C,AAAI,MAAW,eAAa,EAAS,CAAM;EAC7C,GAEA,EAAY,cAAc;GACpB,MAAY,EAAW,YAC3B,EAAe,UAAU,MACzB,EAAe,EAAK,GACpB,EAAW,EAAE;EACf;EAEA,IAAI;GACF,EAAY,MAAM;EACpB,QAAQ;GAIN,AADA,EAAe,UAAU,MACzB,EAAe,EAAK;GACpB;EACF;EAKA,AAHA,EAAe,UAAU,GACzB,EAAS,IAAI,GACb,EAAW,EAAE,GACb,EAAe,EAAI;CACrB,GAAG,CAAC,CAAQ,CAAC,GAEP,IAAO,QAAkB;EAO7B,IAAM,IAAc,EAAe;EAKnC,AAJA,EAAe,UAAU,MACzB,EAAW,WAAW,GACtB,GAAa,KAAK,GAClB,EAAe,EAAK,GACpB,EAAW,EAAE;CACf,GAAG,CAAC,CAAC,GAUC,IAAc,EAAO,CAAQ;CAenC,OAdA,QAAgB;EACV,EAAY,YAAY,MAC5B,EAAY,UAAU,GACtB,EAAK,GACL,EAAS,IAAI;CACf,GAAG,CAAC,GAAU,CAAI,CAAC,GASZ;EAAE;EAAa;EAAa;EAAS;EAAO;EAAU;EAAO;EAAM,QAP3D,QAAkB;GAC/B,AAAI,IAAa,EAAK,IACjB,EAAM;EACb,GAAG;GAAC;GAAa;GAAO;EAAI,CAI8C;EAAQ,YAF/D,QAAkB,EAAS,IAAI,GAAG,CAAC,CAE4B;CAAW;AAC/F"}
1
+ {"version":3,"file":"useVoiceInput.js","names":[],"sources":["../../src/hooks/useVoiceInput.ts"],"sourcesContent":["/**\n * Speech-to-text for the assistant composer (Workstream 2 of the AI Assistant\n * V2 multimodal effort).\n *\n * Input-only, browser-native (Web Speech API). It degrades gracefully:\n * `isSupported` is false on engines without SpeechRecognition (notably Firefox),\n * and the composer hides the mic entirely in that case rather than showing a\n * dead control.\n *\n * ⚠️ This does NOT mean the audio stays on the device. Chrome's\n * `webkitSpeechRecognition` is a NETWORK service — the audio is streamed to the\n * browser vendor for recognition, and the supported language list is theirs, not\n * ours. We neither receive nor store it, which is all an earlier version of this\n * comment (\"no audio ever leaves the device through us\") actually claimed; read\n * literally it implied something stronger and untrue. Whether recording farmers'\n * speech this way needs disclosure or consent is a product/legal call, not a\n * code one.\n *\n * Output (reading replies aloud) is a separate concern and lives in\n * `AssistantSpeechProvider`; an earlier version of this note said the assistant\n * does not speak, which stopped being true when BOFF-6290 shipped.\n *\n * Differences from the fe-libs `assistantWidget/useVoiceInput` this is modelled\n * on, all of which the composer needs:\n * - **interim results are exposed**, so the user sees words appear while\n * speaking instead of staring at a silent button until a phrase finalises;\n * - **errors are surfaced** (`error`) so a denied mic permission can be\n * explained rather than looking like a no-op;\n * - **the recogniser language follows the app locale** (a Tamil or Hindi\n * farmer dictating into an `en-US` recogniser gets garbage);\n * - **`stop()` resolves the final transcript** through `onFinalize`, so the\n * composer can commit exactly once when the user stops.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport type { Locale } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\n\ninterface SpeechRecognitionEventLike extends Event {\n results: SpeechRecognitionResultList;\n resultIndex: number;\n}\n\ninterface SpeechRecognitionErrorEventLike extends Event {\n error: string;\n message: string;\n}\n\ninterface SpeechRecognitionInstance extends EventTarget {\n continuous: boolean;\n interimResults: boolean;\n lang: string;\n start(): void;\n stop(): void;\n abort(): void;\n onresult: ((event: SpeechRecognitionEventLike) => void) | null;\n onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;\n onend: (() => void) | null;\n /**\n * Fires when the service has actually begun listening — the only honest\n * \"capture has started\" signal. Absent from this declaration until now, which\n * is part of why capture was inferred from `start()` returning instead.\n */\n onstart: (() => void) | null;\n}\n\ntype SpeechRecognitionConstructor = new () => SpeechRecognitionInstance;\n\n/**\n * BCP-47 tag for the recogniser, per app locale. Regional choices follow where\n * HealthyBowl actually operates (India for ta/hi) rather than a generic tag,\n * because the recogniser's acoustic model is region-specific.\n */\nconst RECOGNITION_LANG: Record<Locale, string> = {\n en: 'en-US',\n es: 'es-ES',\n fr: 'fr-FR',\n de: 'de-DE',\n ja: 'ja-JP',\n zh: 'zh-CN',\n ta: 'ta-IN',\n hi: 'hi-IN',\n ar: 'ar-SA',\n};\n\nfunction getSpeechRecognitionConstructor(): SpeechRecognitionConstructor | null {\n if (typeof window === 'undefined') return null;\n const win = window as unknown as Record<string, unknown>;\n return (\n (win.SpeechRecognition as SpeechRecognitionConstructor | undefined) ??\n (win.webkitSpeechRecognition as SpeechRecognitionConstructor | undefined) ??\n null\n );\n}\n\nexport type VoiceInputError =\n 'not-allowed' | 'no-speech' | 'audio-capture' | 'network' | 'language-not-supported' | 'unknown';\n\n/**\n * Map the spec's `SpeechRecognitionErrorEvent.error` codes onto the cases the UI\n * actually distinguishes. Anything else is 'unknown' (generic copy).\n *\n * `language-not-supported` is called out separately because it is the single\n * most likely failure for the users this feature exists for: the recogniser's\n * language list belongs to the browser vendor, not to us, so a Tamil or Hindi\n * speaker can hit it on a browser that simply does not offer their language.\n * Folding it into 'unknown' produced \"Dictation stopped unexpectedly\", which\n * tells them nothing and reads like a bug in HealthyBowl.\n */\nfunction toVoiceInputError(code: string): VoiceInputError {\n switch (code) {\n case 'not-allowed':\n case 'service-not-allowed':\n return 'not-allowed';\n case 'no-speech':\n return 'no-speech';\n case 'audio-capture':\n return 'audio-capture';\n case 'network':\n return 'network';\n case 'language-not-supported':\n return 'language-not-supported';\n default:\n return 'unknown';\n }\n}\n\nexport interface UseVoiceInputOptions {\n /**\n * Called with each newly finalised phrase. The composer appends it to the\n * draft; keeping the committed text in the caller (rather than accumulating\n * here) means the user can freely edit while dictation continues.\n */\n onFinalize: (text: string) => void;\n /**\n * BCP-47 tag to listen for. Omit to follow the app locale, which is what this\n * hook did unconditionally before (BOFF-7108).\n *\n * The two are genuinely independent: a farmer whose interface is English may\n * well speak Tamil, and deriving the recogniser language from the UI meant the\n * only way to dictate Tamil was to translate the entire app.\n */\n language?: string;\n}\n\nexport interface UseVoiceInputResult {\n isSupported: boolean;\n isListening: boolean;\n /** Words recognised but not yet finalised — render as a live hint. */\n interim: string;\n error: VoiceInputError | null;\n /**\n * BCP-47 tag the recogniser was asked for. Exposed so error copy can name the\n * language that failed (\"Tamil dictation is not supported…\") rather than\n * leaving the user to guess which language the browser rejected.\n */\n language: string;\n start: () => void;\n stop: () => void;\n /** Start if idle, stop if listening — what the mic button binds to. */\n toggle: () => void;\n clearError: () => void;\n}\n\nexport function useVoiceInput({ onFinalize, language: requested }: UseVoiceInputOptions): UseVoiceInputResult {\n const { locale } = useI18n();\n const [isListening, setIsListening] = useState(false);\n const [interim, setInterim] = useState('');\n const [error, setError] = useState<VoiceInputError | null>(null);\n const recognitionRef = useRef<SpeechRecognitionInstance | null>(null);\n // Incremented on every stop. Handlers capture the session they were created\n // under and ignore events that arrive after it ends.\n const sessionRef = useRef(0);\n\n // Keep the newest callback reachable from the recogniser's long-lived event\n // handlers without re-creating the recogniser on every parent render.\n const onFinalizeRef = useRef(onFinalize);\n useEffect(() => {\n onFinalizeRef.current = onFinalize;\n }, [onFinalize]);\n\n const isSupported = getSpeechRecognitionConstructor() !== null;\n const language = requested ?? RECOGNITION_LANG[locale] ?? 'en-US';\n\n // Abort (not stop) on unmount: the panel is closing, so a trailing final\n // result would be committed into a draft nobody can see.\n useEffect(() => {\n return () => {\n recognitionRef.current?.abort();\n recognitionRef.current = null;\n };\n }, []);\n\n const start = useCallback(() => {\n const Ctor = getSpeechRecognitionConstructor();\n if (!Ctor || recognitionRef.current) return;\n\n const recognition = new Ctor();\n recognition.continuous = true;\n recognition.interimResults = true;\n recognition.lang = language;\n\n const session = sessionRef.current;\n\n recognition.onresult = (event) => {\n if (session !== sessionRef.current) return;\n let finalText = '';\n let interimText = '';\n for (let index = event.resultIndex; index < event.results.length; index += 1) {\n const result = event.results[index];\n const alternative = result[0]?.transcript ?? '';\n if (result.isFinal) {\n finalText += alternative;\n } else {\n interimText += alternative;\n }\n }\n if (finalText.trim()) onFinalizeRef.current(finalText.trim());\n setInterim(interimText.trim());\n };\n\n recognition.onerror = (event) => {\n if (session !== sessionRef.current) return;\n const mapped = toVoiceInputError(event.error);\n // 'no-speech' fires routinely during a natural pause and the recogniser\n // keeps running — surfacing it would flash a scary message mid-sentence.\n if (mapped !== 'no-speech') setError(mapped);\n };\n\n recognition.onend = () => {\n if (session !== sessionRef.current) return;\n recognitionRef.current = null;\n setIsListening(false);\n setInterim('');\n };\n\n /**\n * ★ The TRUE capture signal.\n *\n * This was set optimistically on the line after `start()` returned — which\n * is synchronous, and says only that the request was accepted, not that the\n * microphone is open. Everything downstream then believed capture had begun\n * while the permission prompt was still up: the stage showed \"Listening…\"\n * over a microphone that could not yet hear, so a user who started talking\n * immediately lost the first word or two; the `connecting` stage lasted a\n * single commit; and the 5s \"we aren't hearing your microphone\" notice\n * could never fire, because `capturing` was already true.\n */\n recognition.onstart = () => {\n if (session !== sessionRef.current) return;\n setIsListening(true);\n };\n\n try {\n recognition.start();\n } catch {\n // start() throws if a recogniser is somehow already running — treat the\n // session as not started rather than leaving the button stuck \"live\".\n recognitionRef.current = null;\n setIsListening(false);\n return;\n }\n\n recognitionRef.current = recognition;\n setError(null);\n setInterim('');\n }, [language]);\n\n const stop = useCallback(() => {\n // Detach BEFORE stopping. `onend` is what used to clear this ref, but it\n // arrives asynchronously — so a user who tapped stop and immediately tapped\n // the mic again hit `start()`'s `if (recognitionRef.current) return` guard\n // and got a silent no-op. Bumping the session also makes any trailing final\n // phrase the engine flushes on stop land on a dead session, instead of\n // reappearing in a draft the composer has already sent and cleared.\n const recognition = recognitionRef.current;\n recognitionRef.current = null;\n sessionRef.current += 1;\n recognition?.stop();\n setIsListening(false);\n setInterim('');\n }, []);\n\n // Changing language must END the session it no longer describes.\n //\n // A running recogniser keeps the `lang` it was constructed with, so after a\n // switch the in-flight session is still listening in the OLD language while\n // this hook already reports the new one. A late `language-not-supported` from\n // that session would then be rendered as though the browser had rejected the\n // language the user just picked. Clearing the error is not enough — the\n // session producing it has to go too.\n const languageRef = useRef(language);\n useEffect(() => {\n if (languageRef.current === language) return;\n languageRef.current = language;\n stop();\n setError(null);\n }, [language, stop]);\n\n const toggle = useCallback(() => {\n if (isListening) stop();\n else start();\n }, [isListening, start, stop]);\n\n const clearError = useCallback(() => setError(null), []);\n\n return { isSupported, isListening, interim, error, language, start, stop, toggle, clearError };\n}\n"],"mappings":";;;AAyEA,IAAM,IAA2C;CAC/C,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;AACN;AAEA,SAAS,IAAuE;CAC9E,IAAI,OAAO,SAAW,KAAa,OAAO;CAC1C,IAAM,IAAM;CACZ,OACG,EAAI,qBACJ,EAAI,2BACL;AAEJ;AAgBA,SAAS,EAAkB,GAA+B;CACxD,QAAQ,GAAR;EACE,KAAK;EACL,KAAK,uBACH,OAAO;EACT,KAAK,aACH,OAAO;EACT,KAAK,iBACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,0BACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAuCA,SAAgB,EAAc,EAAE,eAAY,UAAU,KAAwD;CAC5G,IAAM,EAAE,cAAW,EAAQ,GACrB,CAAC,GAAa,KAAkB,EAAS,EAAK,GAC9C,CAAC,GAAS,KAAc,EAAS,EAAE,GACnC,CAAC,GAAO,KAAY,EAAiC,IAAI,GACzD,IAAiB,EAAyC,IAAI,GAG9D,IAAa,EAAO,CAAC,GAIrB,IAAgB,EAAO,CAAU;CACvC,QAAgB;EACd,EAAc,UAAU;CAC1B,GAAG,CAAC,CAAU,CAAC;CAEf,IAAM,IAAc,EAAgC,MAAM,MACpD,IAAW,KAAa,EAAiB,MAAW;CAI1D,cACe;EAEX,AADA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Aa,KAAK,GAClB,EAAe,EAAK,GACpB,EAAW,EAAE;CACf,GAAG,CAAC,CAAC,GAUC,IAAc,EAAO,CAAQ;CAenC,OAdA,QAAgB;EACV,EAAY,YAAY,MAC5B,EAAY,UAAU,GACtB,EAAK,GACL,EAAS,IAAI;CACf,GAAG,CAAC,GAAU,CAAI,CAAC,GASZ;EAAE;EAAa;EAAa;EAAS;EAAO;EAAU;EAAO;EAAM,QAP3D,QAAkB;GAC/B,AAAI,IAAa,EAAK,IACjB,EAAM;EACb,GAAG;GAAC;GAAa;GAAO;EAAI,CAI8C;EAAQ,YAF/D,QAAkB,EAAS,IAAI,GAAG,CAAC,CAE4B;CAAW;AAC/F"}
@@ -26,8 +26,11 @@ function x(e, t, n, r, i) {
26
26
  function S(e, t, n, r, i, a, o, s, l) {
27
27
  return c(t, n, r, i, a, o, h(s), l?.length ? { parts: l } : void 0).then(() => void 0);
28
28
  }
29
- function C(e, t, n, r, i, a = 50) {
30
- return o(t, n, r, h(i), { limit: a });
29
+ function C(e, t, n, r, i, a = 50, s) {
30
+ return o(t, n, r, h(i), {
31
+ limit: a,
32
+ sinceMs: s
33
+ });
31
34
  }
32
35
  function w(e, t, n) {
33
36
  return Promise.resolve(!0);
@@ -1 +1 @@
1
- {"version":3,"file":"assistantApi.js","names":[],"sources":["../../src/services/assistantApi.ts"],"sourcesContent":["/**\n * AI Assistant API — thin adapter over @burdenoff/fe-libs/shared/assistant.\n *\n * The legacy slide-in panel (AssistantChatArea / AssistantMessageItem /\n * useAssistantHeartbeat) calls these with the historical (apollo-first)\n * signatures. The real implementation now lives once in fe-libs; this file only\n * maps the old signatures onto it, retiring ~726 lines of duplicated logic. The\n * `apollo` argument is vestigial (the shared layer uses graphqlFetch) and is\n * ignored; the product id + prod-runtime + TTL the shared functions need are\n * supplied here.\n *\n * HealthyBowl-specific: `checkAssistantAiCredits` / `reportAssistantAiTokenUsage`\n * remain **deliberate no-ops** — the wspace checkAiCredits / reportAiTokenUsage\n * mutations live in the VibeControls subgraph and bill the `vibecontrols`\n * product, so an HB chat must NOT gate on (or charge against) VibeControls'\n * credit quota. The coarse createSandbox `@usage(sandboxes-created)` limit still\n * applies downstream. These two functions therefore do NOT delegate to the\n * shared credit calls.\n *\n * Also HealthyBowl-specific: `sendAssistantPromptAsync` takes an optional\n * multimodal `parts` array (Workstream 4) and forwards it to the shared\n * transport, which carries it in the JSON-scalar proxy body alongside the\n * unchanged `prompt`.\n */\n\nimport {\n findExistingSandbox as sharedFindExisting,\n createAssistantSandbox as sharedCreate,\n waitForSandboxRunning as sharedWaitRunning,\n waitForAssistantServiceReady as sharedWaitService,\n createAssistantSession as sharedCreateSession,\n getAssistantSession as sharedGetSession,\n sendAssistantPromptAsync as sharedSendAsync,\n getAssistantMessages as sharedGetMessages,\n extendAssistantSandboxTTL as sharedExtendTtl,\n sendHeartbeat as sharedHeartbeat,\n getAssistantArtifacts as sharedGetArtifacts,\n downloadAssistantArtifact as sharedDownloadArtifact,\n} from '@burdenoff/fe-libs/shared/assistant';\nimport type {\n AssistantRawMessage as SharedRawMessage,\n AssistantSandboxAuthContext as SharedAuthContext,\n AssistantSessionInfo as SharedSessionInfo,\n DownloadedAssistantArtifact,\n} from '@burdenoff/fe-libs/shared/assistant';\nimport type { AssistantArtifact as LocalAssistantArtifact, AssistantMode } from '@/types/assistant';\nimport type { AssistantPromptPart } from '@/utils/assistantAttachments';\nimport type { PageContext } from '@/utils/pageContext';\n\n// Re-export the shared types under the names the panel already imports.\nexport type AssistantRawMessage = SharedRawMessage;\nexport type AssistantSandboxAuthContext = SharedAuthContext;\nexport type AssistantSessionInfo = SharedSessionInfo;\n\n// Vestigial Apollo arg — accepted for signature compatibility, ignored.\ntype ApolloClientLike = unknown;\n\nconst PRODUCT = 'healthybowl';\n// Matches the original panel behavior: create at 600s, kept warm while open by\n// useAssistantHeartbeat's +600s extend.\nconst DEFAULT_TTL_SECONDS = 600;\n\n// Build-time env parity with the original `assistantApi.ts` image-tag selection\n// (VITE_APP_ENV === 'prod' → prod image tag). Drives getImageTagForMode.\nfunction isProdRuntime(): boolean {\n return import.meta.env.VITE_APP_ENV === 'prod';\n}\n\nconst ctx = (a?: SharedAuthContext): SharedAuthContext => a ?? {};\n\nexport function findExistingSandbox(\n _apollo: ApolloClientLike,\n workspaceId: string,\n mode: AssistantMode,\n authContext?: SharedAuthContext\n): Promise<string | null> {\n return sharedFindExisting(workspaceId, mode, isProdRuntime(), ctx(authContext));\n}\n\nexport function createAssistantSandbox(\n _apollo: ApolloClientLike,\n mode: AssistantMode,\n workspaceId: string,\n authContext?: SharedAuthContext\n): Promise<string> {\n return sharedCreate(PRODUCT, mode, workspaceId, isProdRuntime(), DEFAULT_TTL_SECONDS, ctx(authContext));\n}\n\nexport function waitForSandboxReady(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n authContext?: SharedAuthContext,\n maxWaitMs = 300_000,\n _onProgress?: (message: string) => void\n): Promise<void> {\n return sharedWaitRunning(sandboxId, workspaceId, ctx(authContext), maxWaitMs);\n}\n\nexport function waitForAssistantServiceReady(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n authContext?: SharedAuthContext,\n maxWaitMs = 90_000,\n _onProgress?: (message: string) => void\n): Promise<void> {\n return sharedWaitService(sandboxId, workspaceId, ctx(authContext), maxWaitMs);\n}\n\nexport function createAssistantSession(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n mode: AssistantMode,\n authContext?: SharedAuthContext\n): Promise<{ sessionId: string }> {\n return sharedCreateSession(sandboxId, workspaceId, mode, ctx(authContext));\n}\n\nexport function getAssistantSession(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n sessionId: string,\n authContext?: SharedAuthContext\n): Promise<SharedSessionInfo> {\n return sharedGetSession(sandboxId, workspaceId, sessionId, ctx(authContext));\n}\n\nexport function sendAssistantPromptAsync(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n sessionId: string,\n prompt: string,\n mode: AssistantMode,\n pageContext?: PageContext,\n authContext?: SharedAuthContext,\n /**\n * Optional multimodal turn (Workstream 4). `prompt` is still ALWAYS sent, so a\n * bridge that predates `parts` answers from the text exactly as before, and a\n * text-only turn produces a byte-identical body.\n *\n * The local `AssistantPromptPart` is a structural mirror of the fe-libs type\n * (kept local so the pure attachment utils need no transport import); passing\n * it here is what proves the two stay in step at compile time.\n */\n parts?: AssistantPromptPart[]\n): Promise<void> {\n return sharedSendAsync(\n sandboxId,\n workspaceId,\n sessionId,\n prompt,\n mode,\n pageContext as Record<string, unknown> | undefined,\n ctx(authContext),\n parts?.length ? { parts } : undefined\n ).then(() => undefined);\n}\n\nexport function getAssistantMessages(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n sessionId: string,\n authContext?: SharedAuthContext,\n limit = 50\n): Promise<SharedRawMessage[]> {\n return sharedGetMessages(sandboxId, workspaceId, sessionId, ctx(authContext), { limit });\n}\n\n/**\n * Deliberate no-op for HealthyBowl (see file header): always report budget\n * available; never gate an HB chat on VibeControls' credit quota.\n */\nexport function checkAssistantAiCredits(\n _apollo: ApolloClientLike,\n _workspaceId: string,\n _authContext?: SharedAuthContext\n): Promise<boolean> {\n return Promise.resolve(true);\n}\n\n/**\n * Deliberate no-op for HealthyBowl (see file header): per-token charging routes\n * to the VibeControls AI-credit quota, which HB does not bill against.\n */\nexport function reportAssistantAiTokenUsage(\n _apollo: ApolloClientLike,\n _workspaceId: string,\n _sessionId: string,\n _tokens: { input: number; output: number },\n _authContext?: SharedAuthContext\n): Promise<void> {\n return Promise.resolve();\n}\n\nexport function getAssistantArtifacts(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n sessionId: string,\n authContext?: SharedAuthContext\n): Promise<LocalAssistantArtifact[]> {\n // The shared surface widens `type` to `string`; at runtime the agent only ever\n // returns 'file' | 'directory', so the array is structurally the local type.\n return sharedGetArtifacts(sandboxId, workspaceId, sessionId, ctx(authContext)).then(\n (artifacts) => artifacts as unknown as LocalAssistantArtifact[]\n );\n}\n\nexport function downloadAssistantArtifact(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n sessionId: string,\n artifactPath: string,\n authContext?: SharedAuthContext\n): Promise<DownloadedAssistantArtifact> {\n return sharedDownloadArtifact(sandboxId, workspaceId, sessionId, artifactPath, ctx(authContext));\n}\n\nexport function sendHeartbeat(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n sessionId: string,\n authContext?: SharedAuthContext\n): Promise<void> {\n return sharedHeartbeat(sandboxId, workspaceId, sessionId, ctx(authContext));\n}\n\nexport function extendAssistantSandboxTTL(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n additionalSeconds = 600,\n authContext?: SharedAuthContext\n): Promise<void> {\n return sharedExtendTtl(sandboxId, workspaceId, additionalSeconds, ctx(authContext));\n}\n"],"mappings":";;AAyDA,IAAM,IAAU,eAGV,IAAsB;AAI5B,SAAS,IAAyB;CAChC,OAAO;AACT;AAEA,IAAM,KAAO,MAA6C,KAAK,CAAC;AAEhE,SAAgB,EACd,GACA,GACA,GACA,GACwB;CACxB,OAAO,EAAmB,GAAa,GAAM,EAAc,GAAG,EAAI,CAAW,CAAC;AAChF;AAEA,SAAgB,EACd,GACA,GACA,GACA,GACiB;CACjB,OAAO,EAAa,GAAS,GAAM,GAAa,EAAc,GAAG,GAAqB,EAAI,CAAW,CAAC;AACxG;AAEA,SAAgB,EACd,GACA,GACA,GACA,GACA,IAAY,KACZ,GACe;CACf,OAAO,EAAkB,GAAW,GAAa,EAAI,CAAW,GAAG,CAAS;AAC9E;AAEA,SAAgB,EACd,GACA,GACA,GACA,GACA,IAAY,KACZ,GACe;CACf,OAAO,EAAkB,GAAW,GAAa,EAAI,CAAW,GAAG,CAAS;AAC9E;AAEA,SAAgB,EACd,GACA,GACA,GACA,GACA,GACgC;CAChC,OAAO,EAAoB,GAAW,GAAa,GAAM,EAAI,CAAW,CAAC;AAC3E;AAEA,SAAgB,EACd,GACA,GACA,GACA,GACA,GAC4B;CAC5B,OAAO,EAAiB,GAAW,GAAa,GAAW,EAAI,CAAW,CAAC;AAC7E;AAEA,SAAgB,EACd,GACA,GACA,GACA,GACA,GACA,GACA,GACA,GAUA,GACe;CACf,OAAO,EACL,GACA,GACA,GACA,GACA,GACA,GACA,EAAI,CAAW,GACf,GAAO,SAAS,EAAE,SAAM,IAAI,KAAA,CAC9B,EAAE,WAAW,KAAA,CAAS;AACxB;AAEA,SAAgB,EACd,GACA,GACA,GACA,GACA,GACA,IAAQ,IACqB;CAC7B,OAAO,EAAkB,GAAW,GAAa,GAAW,EAAI,CAAW,GAAG,EAAE,SAAM,CAAC;AACzF;AAMA,SAAgB,EACd,GACA,GACA,GACkB;CAClB,OAAO,QAAQ,QAAQ,EAAI;AAC7B;AAMA,SAAgB,EACd,GACA,GACA,GACA,GACA,GACe;CACf,OAAO,QAAQ,QAAQ;AACzB;AAEA,SAAgB,EACd,GACA,GACA,GACA,GACA,GACmC;CAGnC,OAAO,EAAmB,GAAW,GAAa,GAAW,EAAI,CAAW,CAAC,EAAE,MAC5E,MAAc,CACjB;AACF;AAEA,SAAgB,EACd,GACA,GACA,GACA,GACA,GACA,GACsC;CACtC,OAAO,EAAuB,GAAW,GAAa,GAAW,GAAc,EAAI,CAAW,CAAC;AACjG;AAEA,SAAgB,EACd,GACA,GACA,GACA,GACA,GACe;CACf,OAAO,EAAgB,GAAW,GAAa,GAAW,EAAI,CAAW,CAAC;AAC5E;AAEA,SAAgB,EACd,GACA,GACA,GACA,IAAoB,KACpB,GACe;CACf,OAAO,EAAgB,GAAW,GAAa,GAAmB,EAAI,CAAW,CAAC;AACpF"}
1
+ {"version":3,"file":"assistantApi.js","names":[],"sources":["../../src/services/assistantApi.ts"],"sourcesContent":["/**\n * AI Assistant API — thin adapter over @burdenoff/fe-libs/shared/assistant.\n *\n * The legacy slide-in panel (AssistantChatArea / AssistantMessageItem /\n * useAssistantHeartbeat) calls these with the historical (apollo-first)\n * signatures. The real implementation now lives once in fe-libs; this file only\n * maps the old signatures onto it, retiring ~726 lines of duplicated logic. The\n * `apollo` argument is vestigial (the shared layer uses graphqlFetch) and is\n * ignored; the product id + prod-runtime + TTL the shared functions need are\n * supplied here.\n *\n * HealthyBowl-specific: `checkAssistantAiCredits` / `reportAssistantAiTokenUsage`\n * remain **deliberate no-ops** — the wspace checkAiCredits / reportAiTokenUsage\n * mutations live in the VibeControls subgraph and bill the `vibecontrols`\n * product, so an HB chat must NOT gate on (or charge against) VibeControls'\n * credit quota. The coarse createSandbox `@usage(sandboxes-created)` limit still\n * applies downstream. These two functions therefore do NOT delegate to the\n * shared credit calls.\n *\n * Also HealthyBowl-specific: `sendAssistantPromptAsync` takes an optional\n * multimodal `parts` array (Workstream 4) and forwards it to the shared\n * transport, which carries it in the JSON-scalar proxy body alongside the\n * unchanged `prompt`.\n */\n\nimport {\n findExistingSandbox as sharedFindExisting,\n createAssistantSandbox as sharedCreate,\n waitForSandboxRunning as sharedWaitRunning,\n waitForAssistantServiceReady as sharedWaitService,\n createAssistantSession as sharedCreateSession,\n getAssistantSession as sharedGetSession,\n sendAssistantPromptAsync as sharedSendAsync,\n getAssistantMessages as sharedGetMessages,\n extendAssistantSandboxTTL as sharedExtendTtl,\n sendHeartbeat as sharedHeartbeat,\n getAssistantArtifacts as sharedGetArtifacts,\n downloadAssistantArtifact as sharedDownloadArtifact,\n} from '@burdenoff/fe-libs/shared/assistant';\nimport type {\n AssistantRawMessage as SharedRawMessage,\n AssistantSandboxAuthContext as SharedAuthContext,\n AssistantSessionInfo as SharedSessionInfo,\n DownloadedAssistantArtifact,\n} from '@burdenoff/fe-libs/shared/assistant';\nimport type { AssistantArtifact as LocalAssistantArtifact, AssistantMode } from '@/types/assistant';\nimport type { AssistantPromptPart } from '@/utils/assistantAttachments';\nimport type { PageContext } from '@/utils/pageContext';\n\n// Re-export the shared types under the names the panel already imports.\nexport type AssistantRawMessage = SharedRawMessage;\nexport type AssistantSandboxAuthContext = SharedAuthContext;\nexport type AssistantSessionInfo = SharedSessionInfo;\n\n// Vestigial Apollo arg — accepted for signature compatibility, ignored.\ntype ApolloClientLike = unknown;\n\nconst PRODUCT = 'healthybowl';\n// Matches the original panel behavior: create at 600s, kept warm while open by\n// useAssistantHeartbeat's +600s extend.\nconst DEFAULT_TTL_SECONDS = 600;\n\n// Build-time env parity with the original `assistantApi.ts` image-tag selection\n// (VITE_APP_ENV === 'prod' → prod image tag). Drives getImageTagForMode.\nfunction isProdRuntime(): boolean {\n return import.meta.env.VITE_APP_ENV === 'prod';\n}\n\nconst ctx = (a?: SharedAuthContext): SharedAuthContext => a ?? {};\n\nexport function findExistingSandbox(\n _apollo: ApolloClientLike,\n workspaceId: string,\n mode: AssistantMode,\n authContext?: SharedAuthContext\n): Promise<string | null> {\n return sharedFindExisting(workspaceId, mode, isProdRuntime(), ctx(authContext));\n}\n\nexport function createAssistantSandbox(\n _apollo: ApolloClientLike,\n mode: AssistantMode,\n workspaceId: string,\n authContext?: SharedAuthContext\n): Promise<string> {\n return sharedCreate(PRODUCT, mode, workspaceId, isProdRuntime(), DEFAULT_TTL_SECONDS, ctx(authContext));\n}\n\nexport function waitForSandboxReady(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n authContext?: SharedAuthContext,\n maxWaitMs = 300_000,\n _onProgress?: (message: string) => void\n): Promise<void> {\n return sharedWaitRunning(sandboxId, workspaceId, ctx(authContext), maxWaitMs);\n}\n\nexport function waitForAssistantServiceReady(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n authContext?: SharedAuthContext,\n maxWaitMs = 90_000,\n _onProgress?: (message: string) => void\n): Promise<void> {\n return sharedWaitService(sandboxId, workspaceId, ctx(authContext), maxWaitMs);\n}\n\nexport function createAssistantSession(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n mode: AssistantMode,\n authContext?: SharedAuthContext\n): Promise<{ sessionId: string }> {\n return sharedCreateSession(sandboxId, workspaceId, mode, ctx(authContext));\n}\n\nexport function getAssistantSession(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n sessionId: string,\n authContext?: SharedAuthContext\n): Promise<SharedSessionInfo> {\n return sharedGetSession(sandboxId, workspaceId, sessionId, ctx(authContext));\n}\n\nexport function sendAssistantPromptAsync(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n sessionId: string,\n prompt: string,\n mode: AssistantMode,\n pageContext?: PageContext,\n authContext?: SharedAuthContext,\n /**\n * Optional multimodal turn (Workstream 4). `prompt` is still ALWAYS sent, so a\n * bridge that predates `parts` answers from the text exactly as before, and a\n * text-only turn produces a byte-identical body.\n *\n * The local `AssistantPromptPart` is a structural mirror of the fe-libs type\n * (kept local so the pure attachment utils need no transport import); passing\n * it here is what proves the two stay in step at compile time.\n */\n parts?: AssistantPromptPart[]\n): Promise<void> {\n return sharedSendAsync(\n sandboxId,\n workspaceId,\n sessionId,\n prompt,\n mode,\n pageContext as Record<string, unknown> | undefined,\n ctx(authContext),\n parts?.length ? { parts } : undefined\n ).then(() => undefined);\n}\n\n/**\n * Messages for a session.\n *\n * ★ `sinceMs` is a DELTA cursor: the agent returns only messages created at or\n * after it (`>=`, deliberately, so an in-progress reply whose parts are still\n * growing keeps coming back). Without it every poll re-downloaded all `limit`\n * messages plus the injected page context — up to twice a second, for the whole\n * length of a turn. `assistantPollSchedule.ts` names this as the fix.\n *\n * Pass it ONLY for polling within a turn. The pre-prompt call that establishes\n * the floor must stay a full fetch, or there is nothing to compute a floor from.\n *\n * Degrades on its own: the shared client drops `&since=` if the backend reports\n * the capability unsupported, and `0` is falsy on both sides — so a brand-new\n * session with no prior messages naturally asks for everything.\n */\nexport function getAssistantMessages(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n sessionId: string,\n authContext?: SharedAuthContext,\n limit = 50,\n sinceMs?: number\n): Promise<SharedRawMessage[]> {\n return sharedGetMessages(sandboxId, workspaceId, sessionId, ctx(authContext), { limit, sinceMs });\n}\n\n/**\n * Deliberate no-op for HealthyBowl (see file header): always report budget\n * available; never gate an HB chat on VibeControls' credit quota.\n */\nexport function checkAssistantAiCredits(\n _apollo: ApolloClientLike,\n _workspaceId: string,\n _authContext?: SharedAuthContext\n): Promise<boolean> {\n return Promise.resolve(true);\n}\n\n/**\n * Deliberate no-op for HealthyBowl (see file header): per-token charging routes\n * to the VibeControls AI-credit quota, which HB does not bill against.\n */\nexport function reportAssistantAiTokenUsage(\n _apollo: ApolloClientLike,\n _workspaceId: string,\n _sessionId: string,\n _tokens: { input: number; output: number },\n _authContext?: SharedAuthContext\n): Promise<void> {\n return Promise.resolve();\n}\n\nexport function getAssistantArtifacts(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n sessionId: string,\n authContext?: SharedAuthContext\n): Promise<LocalAssistantArtifact[]> {\n // The shared surface widens `type` to `string`; at runtime the agent only ever\n // returns 'file' | 'directory', so the array is structurally the local type.\n return sharedGetArtifacts(sandboxId, workspaceId, sessionId, ctx(authContext)).then(\n (artifacts) => artifacts as unknown as LocalAssistantArtifact[]\n );\n}\n\nexport function downloadAssistantArtifact(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n sessionId: string,\n artifactPath: string,\n authContext?: SharedAuthContext\n): Promise<DownloadedAssistantArtifact> {\n return sharedDownloadArtifact(sandboxId, workspaceId, sessionId, artifactPath, ctx(authContext));\n}\n\nexport function sendHeartbeat(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n sessionId: string,\n authContext?: SharedAuthContext\n): Promise<void> {\n return sharedHeartbeat(sandboxId, workspaceId, sessionId, ctx(authContext));\n}\n\nexport function extendAssistantSandboxTTL(\n _apollo: ApolloClientLike,\n sandboxId: string,\n workspaceId: string,\n additionalSeconds = 600,\n authContext?: SharedAuthContext\n): Promise<void> {\n return sharedExtendTtl(sandboxId, workspaceId, additionalSeconds, ctx(authContext));\n}\n"],"m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GACA,GACA,GACe;CACf,OAAO,QAAQ,QAAQ;AACzB;AAEA,SAAgB,EACd,GACA,GACA,GACA,GACA,GACmC;CAGnC,OAAO,EAAmB,GAAW,GAAa,GAAW,EAAI,CAAW,CAAC,EAAE,MAC5E,MAAc,CACjB;AACF;AAEA,SAAgB,EACd,GACA,GACA,GACA,GACA,GACA,GACsC;CACtC,OAAO,EAAuB,GAAW,GAAa,GAAW,GAAc,EAAI,CAAW,CAAC;AACjG;AAEA,SAAgB,EACd,GACA,GACA,GACA,GACA,GACe;CACf,OAAO,EAAgB,GAAW,GAAa,GAAW,EAAI,CAAW,CAAC;AAC5E;AAEA,SAAgB,EACd,GACA,GACA,GACA,IAAoB,KACpB,GACe;CACf,OAAO,EAAgB,GAAW,GAAa,GAAmB,EAAI,CAAW,CAAC;AACpF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/microfe-healthybowl",
3
- "version": "2026.901.17",
3
+ "version": "2026.902.2",
4
4
  "description": "Burdenoff HealthyBowl Microfrontend - Comprehensive organic farming and agro-foods management platform",
5
5
  "type": "module",
6
6
  "files": [