@burdenoff/microfe-healthybowl 2026.902.2 → 2026.902.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/assistant/AssistantChatArea.js +116 -116
- package/dist/components/assistant/AssistantChatArea.js.map +1 -1
- package/dist/components/assistant/AssistantConversationList.js +3 -3
- package/dist/components/assistant/composer/AssistantComposer.js +5 -1
- package/dist/components/assistant/composer/AssistantComposer.js.map +1 -1
- package/dist/components/assistant/voice/AssistantVoiceOrb.js +9 -9
- package/dist/components/assistant/voice/AssistantVoiceOrb.js.map +1 -1
- package/dist/components/assistant/voice/AssistantVoiceSession.js +1 -0
- package/dist/components/assistant/voice/AssistantVoiceSession.js.map +1 -1
- package/dist/components/assistant/voice/VoiceConversationView.js +1 -1
- package/dist/components/assistant/voice/VoiceConversationView.js.map +1 -1
- package/dist/components/assistant/voice/VoiceMiniController.js +1 -1
- package/dist/components/assistant/voice/VoiceMiniController.js.map +1 -1
- package/dist/healthybowl/HealthyBowlRoot.js +34 -26
- package/dist/healthybowl/HealthyBowlRoot.js.map +1 -1
- package/dist/healthybowl/HealthyBowlRoutes.js +105 -97
- package/dist/healthybowl/HealthyBowlRoutes.js.map +1 -1
- package/dist/healthybowl/hooks/useHealthyBowlLabour.js +297 -0
- package/dist/healthybowl/hooks/useHealthyBowlLabour.js.map +1 -0
- package/dist/healthybowl/pages/labour/CrewTimesheetPage.js +174 -0
- package/dist/healthybowl/pages/labour/CrewTimesheetPage.js.map +1 -0
- package/dist/healthybowl/pages/labour/LabourRosterPage.js +654 -0
- package/dist/healthybowl/pages/labour/LabourRosterPage.js.map +1 -0
- package/dist/hooks/useVoiceInput.js +34 -33
- package/dist/hooks/useVoiceInput.js.map +1 -1
- package/dist/hooks/useVoiceSession.js.map +1 -1
- package/dist/services/assistantExportService.js +29 -23
- package/dist/services/assistantExportService.js.map +1 -1
- package/dist/utils/voiceSession.js.map +1 -1
- package/dist/utils/voiceTurnVisibility.js +1 -1
- package/package.json +1 -1
|
@@ -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 // ★ 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;CAC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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 // ★ Search the TYPED thread, not the raw array. Retry is a chat-panel\n // affordance, so on a conversation whose last turn was spoken this picked up\n // the spoken prompt and re-sent it WITHOUT `dictated` — quietly converting a\n // voice turn into a chat turn and undoing the separation everywhere else.\n const lastUserMessage = [...chatTurns(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,GAAuB,GAAsC;CACpE,OAAO,EAAQ,MAAM,MAAM,WAAW;AACxC;AAEA,SAAS,EAAiB,GAA6C;CACrE,QAAQ,KAAS,CAAC,GACf,QAAQ,MAAS,EAAK,SAAS,UAAU,OAAO,EAAK,QAAS,QAAQ,EACtE,KAAK,MAAS,EAAK,MAAM,KAAK,KAAK,EAAE,EACrC,OAAO,OAAO,EACd,KAAK,IAAI;AACd;AAEA,SAAS,EAAgB,GAA+C;CACtE,QAAQ,KAAS,CAAC,GACf,QAAQ,MAAS,EAAK,SAAS,UAAU,EAAK,IAAI,EAClD,KAAK,MAAS;EACb,IAAM,IAAS,EAAK,OAAO,UAAU,WAC/B,IAAO,EAAK,QAAQ;EAG1B,OAFI,MAAW,cAAoB,cAAc,MAC7C,MAAW,WAAiB,WAAW,MACpC,YAAY;CACrB,CAAC;AACL;AAEA,SAAS,GACP,GAUA,GAKA;CACA,IAAM,IAAW,EACd,QAAQ,MAAY,EAAQ,MAAM,SA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,EAAa;GACrB,CAAA;GAGH,kBAAC,GAAD;IACE,MAAM,OAAuB;IAC7B,WAAW;IACX,UAAU;GACX,CAAA;EACE;;AAET"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { useAssistantStore as e } from "../../store/assistantStore.js";
|
|
2
2
|
import { useTr as t } from "../../shared/hooks/useTr.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
3
|
+
import { chatTurns as n } from "../../utils/voiceTurnVisibility.js";
|
|
4
|
+
import { ASSISTANT_MODES as r } from "../../types/assistant.js";
|
|
5
5
|
import { useState as i } from "react";
|
|
6
6
|
import { Check as a, MessageSquare as o, PanelLeftClose as s, Pencil as c, Plus as l, Trash2 as u } from "lucide-react";
|
|
7
7
|
import { Fragment as d, jsx as f, jsxs as p } from "react/jsx-runtime";
|
|
@@ -68,7 +68,7 @@ var m = () => {
|
|
|
68
68
|
}) : /* @__PURE__ */ f("div", {
|
|
69
69
|
className: "py-1",
|
|
70
70
|
children: h.map((e) => {
|
|
71
|
-
let t = e.id === g, i = e.id === w, o =
|
|
71
|
+
let t = e.id === g, i = e.id === w, o = r.find((t) => t.id === e.mode), s = n(e.messages), l = s[s.length - 1], h = s.length === 0 && e.messages.length > 0, v = _[e.id];
|
|
72
72
|
return /* @__PURE__ */ f("div", {
|
|
73
73
|
role: "button",
|
|
74
74
|
tabIndex: 0,
|
|
@@ -142,7 +142,11 @@ var _ = 200, v = ({ onSend: v, disabled: y = !1, placeholder: b, mode: oe, avail
|
|
|
142
142
|
}), /* @__PURE__ */ h("div", {
|
|
143
143
|
className: "mt-1.5 px-1 text-center text-[11px]",
|
|
144
144
|
"aria-live": "polite",
|
|
145
|
-
children: G.isListening ? /* @__PURE__ */
|
|
145
|
+
children: G.isStarting && !G.isListening ? /* @__PURE__ */ h("p", {
|
|
146
|
+
className: "text-text-muted",
|
|
147
|
+
"data-testid": "assistant-voice-starting",
|
|
148
|
+
children: C("healthybowl.assistant.voice.starting", "Starting the microphone…")
|
|
149
|
+
}) : G.isListening ? /* @__PURE__ */ g("p", {
|
|
146
150
|
className: "text-status-error-text",
|
|
147
151
|
"data-testid": "assistant-voice-status",
|
|
148
152
|
children: [/* @__PURE__ */ h("span", { className: "mr-1 inline-block size-1.5 rounded-full bg-status-error-text align-middle motion-safe:animate-pulse" }), G.interim || C("healthybowl.assistant.voice.listening", "Listening… speak now, tap the square to stop")]
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantComposer.js","names":[],"sources":["../../../../src/components/assistant/composer/AssistantComposer.tsx"],"sourcesContent":["import {\n useCallback,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type ClipboardEvent,\n type DragEvent,\n type FC,\n type KeyboardEvent,\n} from 'react';\nimport { ArrowUp, Loader2 } from 'lucide-react';\nimport type { AssistantMode, AssistantModeConfig } from '@/types/assistant';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { languageDisplayName } from '@/utils/speechVoices';\nimport { resolveAssistantLanguage } from '@/config/assistantLanguages';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { useVoiceInput } from '@/hooks/useVoiceInput';\nimport { useAssistantAttachments } from '@/hooks/useAssistantAttachments';\nimport {\n MAX_ATTACHMENTS,\n getSendableAttachments,\n type AssistantAttachment,\n type AttachmentRejection,\n} from '@/utils/assistantAttachments';\nimport { AssistantAttachmentButton } from './AssistantAttachmentButton';\nimport { AssistantAttachmentChips } from './AssistantAttachmentChips';\nimport { AssistantVoiceButton } from './AssistantVoiceButton';\nimport { AssistantLanguageSelector } from './AssistantLanguageSelector';\nimport { AssistantVoiceSessionButton } from '../voice/AssistantVoiceSessionButton';\nimport { AssistantModeSelector } from './AssistantModeSelector';\n\ninterface Props {\n /**\n * Send the message. `attachments` are already uploaded and ready; the chat\n * area folds them into the prompt and onto the user bubble.\n */\n onSend: (message: string, attachments: AssistantAttachment[]) => void;\n /** True while a turn is in-flight (assistant busy) — disables send + shows the spinner. */\n disabled?: boolean;\n placeholder?: string;\n mode: AssistantMode;\n /** Role-filtered list of modes the user may pick. */\n availableModes: AssistantModeConfig[];\n onModeChange: (mode: AssistantMode) => void;\n /**\n * Opens the hands-free voice conversation. Omitted where a voice session\n * cannot work at all (no speech input, or nothing able to speak the reply),\n * which is what hides the control rather than offering a dead button.\n */\n onStartVoiceSession?: () => void;\n}\n\nconst MAX_TEXTAREA_HEIGHT = 200;\n\n/**\n * AssistantComposer — the v2 input surface (per the ai-assistant-v2 mockups).\n *\n * A rounded card with, on the input row: a leading circular \"+\" attach control,\n * an auto-growing textarea, a microphone, and a prominent filled forest-green\n * circular send button. BELOW the input sit the mode pills (\"Ask\" active-green /\n * \"Take action\" outline); ABOVE it, chips for any pending attachments.\n *\n * Multimodal input (Workstreams 2–3) arrives through three converging paths —\n * the attach button, drag-and-drop onto the card, and paste (a screenshot from\n * the clipboard is the single most common way a user shares one) — plus voice\n * dictation, which appends recognised speech to the draft so it can still be\n * edited before sending.\n *\n * Fully controlled (React state for the text) with auto-grow via a layout\n * effect. Enter sends, Shift+Enter inserts a newline.\n */\nexport const AssistantComposer: FC<Props> = ({\n onSend,\n disabled = false,\n placeholder,\n mode,\n availableModes,\n onModeChange,\n onStartVoiceSession,\n}) => {\n const tr = useTr();\n const { locale } = useI18n();\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const [text, setText] = useState('');\n const [isDraggingOver, setIsDraggingOver] = useState(false);\n // Nested drag-enter/leave pairs fire for every child element; count them so\n // the highlight survives dragging across the textarea and buttons.\n const dragDepthRef = useRef(0);\n\n const {\n attachments,\n isBusy: attachmentsBusy,\n sendBlocker,\n rejection,\n addFiles,\n remove,\n retry,\n clear,\n clearRejection,\n canAddMore,\n } = useAssistantAttachments();\n\n const appendTranscript = useCallback((phrase: string) => {\n setText((current) => (current ? `${current.replace(/\\s+$/, '')} ${phrase}` : phrase));\n }, []);\n\n // One selection drives the recogniser, the reply language and the voice —\n // see `assistantLanguages`. `null` follows the interface language, which is\n // what this did unconditionally before.\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const setAssistantLanguage = useAssistantStore((state) => state.setAssistantLanguage);\n const spokenLanguage = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale),\n [assistantLanguage, locale]\n );\n\n const voice = useVoiceInput({ onFinalize: appendTranscript, language: spokenLanguage.tag });\n\n const resolvedPlaceholder =\n placeholder ?? tr('healthybowl.assistant.composer.placeholder', 'Ask HealthyBowl anything…');\n const trimmed = text.trim();\n // Exactly what the model will be given — see `getSendableAttachments`.\n const sendableAttachments = getSendableAttachments(attachments);\n const failedAttachments = attachments.filter((attachment) => attachment.status === 'error');\n // A message may be attachments-only (\"what's wrong with this leaf?\" is often\n // just the photo), but never sends while an upload is in flight OR has failed:\n // `sendBlocker` covers both. Gating on the blocker rather than on\n // `attachmentsBusy` is what stops a turn going out that quietly omits a file\n // the user can still see attached — the chips are cleared by `clear()` below,\n // so the evidence would disappear at the same instant.\n const canSend = (trimmed.length > 0 || sendableAttachments.length > 0) && !disabled && sendBlocker === null;\n\n // Auto-grow the textarea to fit its content (capped), re-measured after every\n // value change so the card breathes as the user types.\n useLayoutEffect(() => {\n const textarea = textareaRef.current;\n if (!textarea) return;\n textarea.style.height = 'auto';\n textarea.style.height = `${Math.min(textarea.scrollHeight, MAX_TEXTAREA_HEIGHT)}px`;\n }, [text]);\n\n const handleSend = useCallback(() => {\n if (!canSend) return;\n // Dictation left running into a send would keep appending to a cleared\n // draft; stop it so the mic state matches what the user sees.\n if (voice.isListening) voice.stop();\n onSend(text.trim(), sendableAttachments);\n setText('');\n clear();\n }, [canSend, onSend, text, sendableAttachments, clear, voice]);\n\n const handleKeyDown = useCallback(\n (event: KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n handleSend();\n }\n },\n [handleSend]\n );\n\n const handlePaste = useCallback(\n (event: ClipboardEvent<HTMLTextAreaElement>) => {\n const files = Array.from(event.clipboardData?.files ?? []);\n if (files.length === 0) return;\n // Only claim the paste when it carried files; a normal text paste (which\n // also exposes an empty `files`) must still land in the textarea.\n event.preventDefault();\n addFiles(files);\n },\n [addFiles]\n );\n\n const handleDragEnter = useCallback((event: DragEvent<HTMLDivElement>) => {\n if (!Array.from(event.dataTransfer?.types ?? []).includes('Files')) return;\n dragDepthRef.current += 1;\n setIsDraggingOver(true);\n }, []);\n\n const handleDragLeave = useCallback(() => {\n dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);\n if (dragDepthRef.current === 0) setIsDraggingOver(false);\n }, []);\n\n const handleDragOver = useCallback((event: DragEvent<HTMLDivElement>) => {\n if (!Array.from(event.dataTransfer?.types ?? []).includes('Files')) return;\n // Required for a drop to fire at all, and stops the browser from navigating\n // away to the dropped file.\n event.preventDefault();\n }, []);\n\n const handleDrop = useCallback(\n (event: DragEvent<HTMLDivElement>) => {\n event.preventDefault();\n dragDepthRef.current = 0;\n setIsDraggingOver(false);\n addFiles(event.dataTransfer?.files ?? null);\n },\n [addFiles]\n );\n\n const rejectionMessage = (reason: AttachmentRejection): string => {\n switch (reason) {\n case 'too-many':\n return tr('healthybowl.assistant.attachments.tooMany', 'You can attach up to {{max}} files per message.', {\n max: MAX_ATTACHMENTS,\n });\n case 'too-large':\n return tr('healthybowl.assistant.attachments.tooLarge', 'That file is larger than 10 MB.');\n case 'empty':\n return tr('healthybowl.assistant.attachments.empty', 'That file is empty.');\n case 'unreadable':\n return tr('healthybowl.assistant.attachments.unreadable', 'That file could not be read.');\n case 'unsupported-image':\n return tr(\n 'healthybowl.assistant.attachments.unsupportedImage',\n \"This device can't read that image format, so it can't be resized to send. Save it as JPEG and try again.\"\n );\n }\n };\n\n const voiceErrorMessage = (): string | null => {\n switch (voice.error) {\n case 'not-allowed':\n return tr(\n 'healthybowl.assistant.voice.denied',\n 'Microphone access is blocked. Allow it in your browser settings to dictate.'\n );\n case 'audio-capture':\n return tr('healthybowl.assistant.voice.noMic', 'No microphone was found.');\n case 'network':\n return tr('healthybowl.assistant.voice.network', 'Speech recognition is offline right now.');\n case 'language-not-supported':\n // The recogniser's language list is the browser vendor's, not ours, so\n // name the language and point at the browser rather than implying the\n // assistant is broken.\n return tr(\n 'healthybowl.assistant.voice.languageNotSupported',\n 'This browser cannot recognise spoken {{language}}. Try a different browser, or type instead.',\n { language: languageDisplayName(voice.language, locale) }\n );\n case 'unknown':\n return tr('healthybowl.assistant.voice.failed', 'Dictation stopped unexpectedly.');\n default:\n return null;\n }\n };\n\n const voiceError = voiceErrorMessage();\n\n return (\n <div className=\"flex-shrink-0 px-3 pb-3 pt-1.5\">\n <div\n onDragEnter={handleDragEnter}\n onDragLeave={handleDragLeave}\n onDragOver={handleDragOver}\n onDrop={handleDrop}\n className={`rounded-2xl border p-2 shadow-sm transition-colors focus-within:border-action-primary-bg focus-within:ring-2 focus-within:ring-action-primary-bg/15 ${\n isDraggingOver\n ? 'border-action-primary-bg border-dashed bg-action-primary-bg/5'\n : 'border-border-default bg-bg-sunken'\n }`}\n data-testid=\"assistant-composer\"\n >\n <AssistantAttachmentChips attachments={attachments} onRemove={remove} onRetry={retry} disabled={disabled} />\n\n {/* Input row: attach · textarea · mic · send */}\n <div className=\"flex items-end gap-2\">\n <AssistantAttachmentButton onFiles={addFiles} canAddMore={canAddMore} disabled={disabled} />\n\n <textarea\n ref={textareaRef}\n value={text}\n onChange={(event) => setText(event.target.value)}\n onKeyDown={handleKeyDown}\n onPaste={handlePaste}\n disabled={disabled}\n placeholder={\n isDraggingOver\n ? tr('healthybowl.assistant.composer.dropHere', 'Drop files to attach')\n : resolvedPlaceholder\n }\n rows={1}\n className=\"min-h-[36px] flex-1 resize-none self-center bg-transparent px-1 py-2 text-[15px] leading-relaxed text-text-primary placeholder:text-text-muted focus:outline-none disabled:opacity-50\"\n aria-label={tr('healthybowl.assistant.chatInput.ariaLabel', 'Message input')}\n data-testid=\"assistant-input\"\n />\n\n {/* Outside the dictation guard on purpose: this preference also\n decides what language the assistant REPLIES in, which works\n perfectly well on a browser with no speech recognition at all.\n Hiding it there left Firefox users unable to choose a reply\n language, which is most of what it is for. */}\n <AssistantLanguageSelector\n current={spokenLanguage}\n selected={assistantLanguage}\n onChange={setAssistantLanguage}\n disabled={disabled || voice.isListening}\n />\n\n {voice.isSupported && (\n <AssistantVoiceButton isListening={voice.isListening} onToggle={voice.toggle} disabled={disabled} />\n )}\n\n {/* The voice button takes the send slot while there is nothing to\n send — see AssistantVoiceSessionButton for why swapping rather\n than adding is the only option that fits. */}\n {/* Genuinely empty, NOT merely unsendable: `canSend` is also false\n while an attachment uploads or a turn is in flight, so keying off\n it would replace send even with a draft typed and ready. */}\n {onStartVoiceSession && trimmed.length === 0 && attachments.length === 0 && !voice.isListening ? (\n <AssistantVoiceSessionButton onStart={onStartVoiceSession} disabled={disabled} />\n ) : (\n <button\n type=\"button\"\n onClick={handleSend}\n disabled={!canSend}\n className={`flex size-9 flex-shrink-0 items-center justify-center rounded-full shadow-sm transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong ${\n canSend\n ? 'bg-action-primary-bg text-action-primary-text hover:scale-105 hover:bg-action-primary-bg-hover'\n : 'bg-bg-elevated text-text-muted'\n }`}\n aria-label={tr('healthybowl.assistant.chatInput.send', 'Send message')}\n data-testid=\"assistant-send\"\n >\n {disabled || attachmentsBusy ? (\n <Loader2 className=\"size-4 animate-spin\" />\n ) : (\n <ArrowUp className=\"size-4\" />\n )}\n </button>\n )}\n </div>\n\n {/* Mode pills */}\n {availableModes.length > 1 && (\n <div className=\"mt-2 px-0.5\">\n <AssistantModeSelector\n mode={mode}\n availableModes={availableModes}\n onModeChange={onModeChange}\n disabled={disabled}\n />\n </div>\n )}\n </div>\n\n {/* One status line under the card: live dictation > voice error >\n attachment rejection > failed upload > the keyboard hint. Announced\n politely so a screen-reader user hears dictation land without losing\n their place.\n\n The failed-upload line ranks below `rejection` (which is transient and\n describes the file the user just picked) but above the hint, because a\n disabled send button with no stated reason is the thing this whole\n change exists to avoid. */}\n <div className=\"mt-1.5 px-1 text-center text-[11px]\" aria-live=\"polite\">\n {voice.isListening ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-voice-status\">\n <span className=\"mr-1 inline-block size-1.5 rounded-full bg-status-error-text align-middle motion-safe:animate-pulse\" />\n {voice.interim ||\n tr('healthybowl.assistant.voice.listening', 'Listening… speak now, tap the square to stop')}\n </p>\n ) : voiceError ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-voice-error\">\n {voiceError}\n </p>\n ) : rejection ? (\n <button\n type=\"button\"\n onClick={clearRejection}\n className=\"text-status-error-text underline-offset-2 hover:underline\"\n data-testid=\"assistant-attachment-rejection\"\n >\n {rejectionMessage(rejection)}\n </button>\n ) : sendBlocker === 'failed' ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-attachment-blocked\">\n {failedAttachments.length === 1\n ? tr(\n 'healthybowl.assistant.attachments.blockedOne',\n \"{{name}} didn't upload. Retry or remove it before sending.\",\n { name: failedAttachments[0].filename }\n )\n : tr(\n 'healthybowl.assistant.attachments.blockedMany',\n \"{{count}} attachments didn't upload. Retry or remove them before sending.\",\n { count: failedAttachments.length }\n )}\n </p>\n ) : (\n <p className=\"text-text-muted\">\n {tr(\n 'healthybowl.assistant.composer.hint',\n 'Enter to send · Shift+Enter for newline · drag or paste files to attach'\n )}\n </p>\n )}\n </div>\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsDA,IAAM,IAAsB,KAmBf,KAAgC,EAC3C,WACA,cAAW,IACX,gBACA,UACA,mBACA,kBACA,6BACI;CACJ,IAAM,IAAK,EAAM,GACX,EAAE,cAAW,EAAQ,GACrB,IAAc,EAA4B,IAAI,GAC9C,CAAC,GAAM,KAAW,EAAS,EAAE,GAC7B,CAAC,GAAgB,KAAqB,EAAS,EAAK,GAGpD,IAAe,EAAO,CAAC,GAEvB,EACJ,gBACA,QAAQ,GACR,gBACA,cACA,aACA,WACA,UACA,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kBAAC,OAAD;GAAK,WAAU;GAAsC,aAAU;aAC5D,EAAM,cACL,kBAAC,KAAD;IAAG,WAAU;IAAyB,eAAY;cAAlD,CACE,kBAAC,QAAD,EAAM,WAAU,sGAAuG,CAAA,GACtH,EAAM,WACL,EAAG,yCAAyC,8CAA8C,CAC3F;QACD,IACF,kBAAC,KAAD;IAAG,WAAU;IAAyB,eAAY;cAC/C;GACA,CAAA,IACD,IACF,kBAAC,UAAD;IACE,MAAK;IACL,SAAS;IACT,WAAU;IACV,eAAY;cAEX,GAAiB,CAAS;GACrB,CAAA,IACN,MAAgB,WAClB,kBAAC,KAAD;IAAG,WAAU;IAAyB,eAAY;cAC/C,EAAkB,WAAW,IAC1B,EACE,gDACA,8DACA,EAAE,MAAM,EAAkB,GAAG,SAAS,CACxC,IACA,EACE,iDACA,6EACA,EAAE,OAAO,EAAkB,OAAO,CACpC;GACH,CAAA,IAEH,kBAAC,KAAD;IAAG,WAAU;cACV,EACC,uCACA,yEACF;GACC,CAAA;EAEF,CAAA,CACF;;AAET"}
|
|
1
|
+
{"version":3,"file":"AssistantComposer.js","names":[],"sources":["../../../../src/components/assistant/composer/AssistantComposer.tsx"],"sourcesContent":["import {\n useCallback,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type ClipboardEvent,\n type DragEvent,\n type FC,\n type KeyboardEvent,\n} from 'react';\nimport { ArrowUp, Loader2 } from 'lucide-react';\nimport type { AssistantMode, AssistantModeConfig } from '@/types/assistant';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { languageDisplayName } from '@/utils/speechVoices';\nimport { resolveAssistantLanguage } from '@/config/assistantLanguages';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { useVoiceInput } from '@/hooks/useVoiceInput';\nimport { useAssistantAttachments } from '@/hooks/useAssistantAttachments';\nimport {\n MAX_ATTACHMENTS,\n getSendableAttachments,\n type AssistantAttachment,\n type AttachmentRejection,\n} from '@/utils/assistantAttachments';\nimport { AssistantAttachmentButton } from './AssistantAttachmentButton';\nimport { AssistantAttachmentChips } from './AssistantAttachmentChips';\nimport { AssistantVoiceButton } from './AssistantVoiceButton';\nimport { AssistantLanguageSelector } from './AssistantLanguageSelector';\nimport { AssistantVoiceSessionButton } from '../voice/AssistantVoiceSessionButton';\nimport { AssistantModeSelector } from './AssistantModeSelector';\n\ninterface Props {\n /**\n * Send the message. `attachments` are already uploaded and ready; the chat\n * area folds them into the prompt and onto the user bubble.\n */\n onSend: (message: string, attachments: AssistantAttachment[]) => void;\n /** True while a turn is in-flight (assistant busy) — disables send + shows the spinner. */\n disabled?: boolean;\n placeholder?: string;\n mode: AssistantMode;\n /** Role-filtered list of modes the user may pick. */\n availableModes: AssistantModeConfig[];\n onModeChange: (mode: AssistantMode) => void;\n /**\n * Opens the hands-free voice conversation. Omitted where a voice session\n * cannot work at all (no speech input, or nothing able to speak the reply),\n * which is what hides the control rather than offering a dead button.\n */\n onStartVoiceSession?: () => void;\n}\n\nconst MAX_TEXTAREA_HEIGHT = 200;\n\n/**\n * AssistantComposer — the v2 input surface (per the ai-assistant-v2 mockups).\n *\n * A rounded card with, on the input row: a leading circular \"+\" attach control,\n * an auto-growing textarea, a microphone, and a prominent filled forest-green\n * circular send button. BELOW the input sit the mode pills (\"Ask\" active-green /\n * \"Take action\" outline); ABOVE it, chips for any pending attachments.\n *\n * Multimodal input (Workstreams 2–3) arrives through three converging paths —\n * the attach button, drag-and-drop onto the card, and paste (a screenshot from\n * the clipboard is the single most common way a user shares one) — plus voice\n * dictation, which appends recognised speech to the draft so it can still be\n * edited before sending.\n *\n * Fully controlled (React state for the text) with auto-grow via a layout\n * effect. Enter sends, Shift+Enter inserts a newline.\n */\nexport const AssistantComposer: FC<Props> = ({\n onSend,\n disabled = false,\n placeholder,\n mode,\n availableModes,\n onModeChange,\n onStartVoiceSession,\n}) => {\n const tr = useTr();\n const { locale } = useI18n();\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const [text, setText] = useState('');\n const [isDraggingOver, setIsDraggingOver] = useState(false);\n // Nested drag-enter/leave pairs fire for every child element; count them so\n // the highlight survives dragging across the textarea and buttons.\n const dragDepthRef = useRef(0);\n\n const {\n attachments,\n isBusy: attachmentsBusy,\n sendBlocker,\n rejection,\n addFiles,\n remove,\n retry,\n clear,\n clearRejection,\n canAddMore,\n } = useAssistantAttachments();\n\n const appendTranscript = useCallback((phrase: string) => {\n setText((current) => (current ? `${current.replace(/\\s+$/, '')} ${phrase}` : phrase));\n }, []);\n\n // One selection drives the recogniser, the reply language and the voice —\n // see `assistantLanguages`. `null` follows the interface language, which is\n // what this did unconditionally before.\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const setAssistantLanguage = useAssistantStore((state) => state.setAssistantLanguage);\n const spokenLanguage = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale),\n [assistantLanguage, locale]\n );\n\n const voice = useVoiceInput({ onFinalize: appendTranscript, language: spokenLanguage.tag });\n\n const resolvedPlaceholder =\n placeholder ?? tr('healthybowl.assistant.composer.placeholder', 'Ask HealthyBowl anything…');\n const trimmed = text.trim();\n // Exactly what the model will be given — see `getSendableAttachments`.\n const sendableAttachments = getSendableAttachments(attachments);\n const failedAttachments = attachments.filter((attachment) => attachment.status === 'error');\n // A message may be attachments-only (\"what's wrong with this leaf?\" is often\n // just the photo), but never sends while an upload is in flight OR has failed:\n // `sendBlocker` covers both. Gating on the blocker rather than on\n // `attachmentsBusy` is what stops a turn going out that quietly omits a file\n // the user can still see attached — the chips are cleared by `clear()` below,\n // so the evidence would disappear at the same instant.\n const canSend = (trimmed.length > 0 || sendableAttachments.length > 0) && !disabled && sendBlocker === null;\n\n // Auto-grow the textarea to fit its content (capped), re-measured after every\n // value change so the card breathes as the user types.\n useLayoutEffect(() => {\n const textarea = textareaRef.current;\n if (!textarea) return;\n textarea.style.height = 'auto';\n textarea.style.height = `${Math.min(textarea.scrollHeight, MAX_TEXTAREA_HEIGHT)}px`;\n }, [text]);\n\n const handleSend = useCallback(() => {\n if (!canSend) return;\n // Dictation left running into a send would keep appending to a cleared\n // draft; stop it so the mic state matches what the user sees.\n if (voice.isListening) voice.stop();\n onSend(text.trim(), sendableAttachments);\n setText('');\n clear();\n }, [canSend, onSend, text, sendableAttachments, clear, voice]);\n\n const handleKeyDown = useCallback(\n (event: KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n handleSend();\n }\n },\n [handleSend]\n );\n\n const handlePaste = useCallback(\n (event: ClipboardEvent<HTMLTextAreaElement>) => {\n const files = Array.from(event.clipboardData?.files ?? []);\n if (files.length === 0) return;\n // Only claim the paste when it carried files; a normal text paste (which\n // also exposes an empty `files`) must still land in the textarea.\n event.preventDefault();\n addFiles(files);\n },\n [addFiles]\n );\n\n const handleDragEnter = useCallback((event: DragEvent<HTMLDivElement>) => {\n if (!Array.from(event.dataTransfer?.types ?? []).includes('Files')) return;\n dragDepthRef.current += 1;\n setIsDraggingOver(true);\n }, []);\n\n const handleDragLeave = useCallback(() => {\n dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);\n if (dragDepthRef.current === 0) setIsDraggingOver(false);\n }, []);\n\n const handleDragOver = useCallback((event: DragEvent<HTMLDivElement>) => {\n if (!Array.from(event.dataTransfer?.types ?? []).includes('Files')) return;\n // Required for a drop to fire at all, and stops the browser from navigating\n // away to the dropped file.\n event.preventDefault();\n }, []);\n\n const handleDrop = useCallback(\n (event: DragEvent<HTMLDivElement>) => {\n event.preventDefault();\n dragDepthRef.current = 0;\n setIsDraggingOver(false);\n addFiles(event.dataTransfer?.files ?? null);\n },\n [addFiles]\n );\n\n const rejectionMessage = (reason: AttachmentRejection): string => {\n switch (reason) {\n case 'too-many':\n return tr('healthybowl.assistant.attachments.tooMany', 'You can attach up to {{max}} files per message.', {\n max: MAX_ATTACHMENTS,\n });\n case 'too-large':\n return tr('healthybowl.assistant.attachments.tooLarge', 'That file is larger than 10 MB.');\n case 'empty':\n return tr('healthybowl.assistant.attachments.empty', 'That file is empty.');\n case 'unreadable':\n return tr('healthybowl.assistant.attachments.unreadable', 'That file could not be read.');\n case 'unsupported-image':\n return tr(\n 'healthybowl.assistant.attachments.unsupportedImage',\n \"This device can't read that image format, so it can't be resized to send. Save it as JPEG and try again.\"\n );\n }\n };\n\n const voiceErrorMessage = (): string | null => {\n switch (voice.error) {\n case 'not-allowed':\n return tr(\n 'healthybowl.assistant.voice.denied',\n 'Microphone access is blocked. Allow it in your browser settings to dictate.'\n );\n case 'audio-capture':\n return tr('healthybowl.assistant.voice.noMic', 'No microphone was found.');\n case 'network':\n return tr('healthybowl.assistant.voice.network', 'Speech recognition is offline right now.');\n case 'language-not-supported':\n // The recogniser's language list is the browser vendor's, not ours, so\n // name the language and point at the browser rather than implying the\n // assistant is broken.\n return tr(\n 'healthybowl.assistant.voice.languageNotSupported',\n 'This browser cannot recognise spoken {{language}}. Try a different browser, or type instead.',\n { language: languageDisplayName(voice.language, locale) }\n );\n case 'unknown':\n return tr('healthybowl.assistant.voice.failed', 'Dictation stopped unexpectedly.');\n default:\n return null;\n }\n };\n\n const voiceError = voiceErrorMessage();\n\n return (\n <div className=\"flex-shrink-0 px-3 pb-3 pt-1.5\">\n <div\n onDragEnter={handleDragEnter}\n onDragLeave={handleDragLeave}\n onDragOver={handleDragOver}\n onDrop={handleDrop}\n className={`rounded-2xl border p-2 shadow-sm transition-colors focus-within:border-action-primary-bg focus-within:ring-2 focus-within:ring-action-primary-bg/15 ${\n isDraggingOver\n ? 'border-action-primary-bg border-dashed bg-action-primary-bg/5'\n : 'border-border-default bg-bg-sunken'\n }`}\n data-testid=\"assistant-composer\"\n >\n <AssistantAttachmentChips attachments={attachments} onRemove={remove} onRetry={retry} disabled={disabled} />\n\n {/* Input row: attach · textarea · mic · send */}\n <div className=\"flex items-end gap-2\">\n <AssistantAttachmentButton onFiles={addFiles} canAddMore={canAddMore} disabled={disabled} />\n\n <textarea\n ref={textareaRef}\n value={text}\n onChange={(event) => setText(event.target.value)}\n onKeyDown={handleKeyDown}\n onPaste={handlePaste}\n disabled={disabled}\n placeholder={\n isDraggingOver\n ? tr('healthybowl.assistant.composer.dropHere', 'Drop files to attach')\n : resolvedPlaceholder\n }\n rows={1}\n className=\"min-h-[36px] flex-1 resize-none self-center bg-transparent px-1 py-2 text-[15px] leading-relaxed text-text-primary placeholder:text-text-muted focus:outline-none disabled:opacity-50\"\n aria-label={tr('healthybowl.assistant.chatInput.ariaLabel', 'Message input')}\n data-testid=\"assistant-input\"\n />\n\n {/* Outside the dictation guard on purpose: this preference also\n decides what language the assistant REPLIES in, which works\n perfectly well on a browser with no speech recognition at all.\n Hiding it there left Firefox users unable to choose a reply\n language, which is most of what it is for. */}\n <AssistantLanguageSelector\n current={spokenLanguage}\n selected={assistantLanguage}\n onChange={setAssistantLanguage}\n disabled={disabled || voice.isListening}\n />\n\n {voice.isSupported && (\n <AssistantVoiceButton isListening={voice.isListening} onToggle={voice.toggle} disabled={disabled} />\n )}\n\n {/* The voice button takes the send slot while there is nothing to\n send — see AssistantVoiceSessionButton for why swapping rather\n than adding is the only option that fits. */}\n {/* Genuinely empty, NOT merely unsendable: `canSend` is also false\n while an attachment uploads or a turn is in flight, so keying off\n it would replace send even with a draft typed and ready. */}\n {onStartVoiceSession && trimmed.length === 0 && attachments.length === 0 && !voice.isListening ? (\n <AssistantVoiceSessionButton onStart={onStartVoiceSession} disabled={disabled} />\n ) : (\n <button\n type=\"button\"\n onClick={handleSend}\n disabled={!canSend}\n className={`flex size-9 flex-shrink-0 items-center justify-center rounded-full shadow-sm transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong ${\n canSend\n ? 'bg-action-primary-bg text-action-primary-text hover:scale-105 hover:bg-action-primary-bg-hover'\n : 'bg-bg-elevated text-text-muted'\n }`}\n aria-label={tr('healthybowl.assistant.chatInput.send', 'Send message')}\n data-testid=\"assistant-send\"\n >\n {disabled || attachmentsBusy ? (\n <Loader2 className=\"size-4 animate-spin\" />\n ) : (\n <ArrowUp className=\"size-4\" />\n )}\n </button>\n )}\n </div>\n\n {/* Mode pills */}\n {availableModes.length > 1 && (\n <div className=\"mt-2 px-0.5\">\n <AssistantModeSelector\n mode={mode}\n availableModes={availableModes}\n onModeChange={onModeChange}\n disabled={disabled}\n />\n </div>\n )}\n </div>\n\n {/* One status line under the card: live dictation > voice error >\n attachment rejection > failed upload > the keyboard hint. Announced\n politely so a screen-reader user hears dictation land without losing\n their place.\n\n The failed-upload line ranks below `rejection` (which is transient and\n describes the file the user just picked) but above the hint, because a\n disabled send button with no stated reason is the thing this whole\n change exists to avoid. */}\n <div className=\"mt-1.5 px-1 text-center text-[11px]\" aria-live=\"polite\">\n {/* ★ Three states, not two. `isListening` now waits for the recogniser's\n own `onstart`, which is the honest signal — but it left this line\n showing the idle hint after the user had already tapped the\n microphone, for the whole permission-prompt window. */}\n {voice.isStarting && !voice.isListening ? (\n <p className=\"text-text-muted\" data-testid=\"assistant-voice-starting\">\n {tr('healthybowl.assistant.voice.starting', 'Starting the microphone…')}\n </p>\n ) : voice.isListening ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-voice-status\">\n <span className=\"mr-1 inline-block size-1.5 rounded-full bg-status-error-text align-middle motion-safe:animate-pulse\" />\n {voice.interim ||\n tr('healthybowl.assistant.voice.listening', 'Listening… speak now, tap the square to stop')}\n </p>\n ) : voiceError ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-voice-error\">\n {voiceError}\n </p>\n ) : rejection ? (\n <button\n type=\"button\"\n onClick={clearRejection}\n className=\"text-status-error-text underline-offset-2 hover:underline\"\n data-testid=\"assistant-attachment-rejection\"\n >\n {rejectionMessage(rejection)}\n </button>\n ) : sendBlocker === 'failed' ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-attachment-blocked\">\n {failedAttachments.length === 1\n ? tr(\n 'healthybowl.assistant.attachments.blockedOne',\n \"{{name}} didn't upload. Retry or remove it before sending.\",\n { name: failedAttachments[0].filename }\n )\n : tr(\n 'healthybowl.assistant.attachments.blockedMany',\n \"{{count}} attachments didn't upload. Retry or remove them before sending.\",\n { count: failedAttachments.length }\n )}\n </p>\n ) : (\n <p className=\"text-text-muted\">\n {tr(\n 'healthybowl.assistant.composer.hint',\n 'Enter to send · Shift+Enter for newline · drag or paste files to attach'\n )}\n </p>\n )}\n </div>\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsDA,IAAM,IAAsB,KAmBf,KAAgC,EAC3C,WACA,cAAW,IACX,gBACA,UACA,mBACA,kBACA,6BACI;CACJ,IAAM,IAAK,EAAM,GACX,EAAE,cAAW,EAAQ,GACrB,IAAc,EAA4B,IAAI,GAC9C,CAAC,GAAM,KAAW,EAAS,EAAE,GAC7B,CAAC,GAAgB,KAAqB,EAAS,EAAK,GAGpD,IAAe,EAAO,CAAC,GAEvB,EACJ,gBACA,QAAQ,GACR,gBACA,cACA,aACA,WACA,UACA,UACA,mBACA,kBACE,EAAwB,GAEtB,IAAmB,GAAa,MAAmB;EACvD,GAAS,MAAa,IAAU,GAAG,EAAQ,QAAQ,QAAQ,EAAE,EAAE,GAAG,MAAW,CAAO;CACtF,GAAG,CAAC,CAAC,GAKC,IAAoB,GAAmB,MAAU,EAAM,iBAAiB,GACxE,IAAuB,GAAmB,MAAU,EAAM,oBAAoB,GAC9E,IAAiB,QACf,EAAyB,GAAmB,CAAM,GACxD,CAAC,GAAmB,CAAM,CAC5B,GAEM,IAAQ,EAAc;EAAE,YAAY;EAAkB,UAAU,EAAe;CAAI,CAAC,GAEpF,IACJ,KAAe,EAAG,8CAA8C,2BAA2B,GACvF,IAAU,EAAK,KAAK,GAEpB,IAAsB,EAAuB,CAAW,GACxD,IAAoB,EAAY,QAAQ,MAAe,EAAW,WAAW,OAAO,GAOpF,KAAW,EAAQ,SAAS,KAAK,EAAoB,SAAS,MAAM,CAAC,KAAY,MAAgB;CAIvG,QAAsB;EACpB,IAAM,IAAW,EAAY;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EACA,EAAE,OAAO,EAAkB,OAAO,CACpC;GACH,CAAA,IAEH,kBAAC,KAAD;IAAG,WAAU;cACV,EACC,uCACA,yEACF;GACC,CAAA;EAEF,CAAA,CACF;;AAET"}
|
|
@@ -2,20 +2,20 @@ import { orbMode as e } from "../../../utils/voiceSession.js";
|
|
|
2
2
|
import { Mic as t, MicOff as n, Square as r } from "lucide-react";
|
|
3
3
|
import { jsx as i } from "react/jsx-runtime";
|
|
4
4
|
//#region src/components/assistant/voice/AssistantVoiceOrb.tsx
|
|
5
|
-
var a = ({ session: a, compact: o = !1, onPress: s, label: c }) => {
|
|
6
|
-
let
|
|
5
|
+
var a = ({ session: a, compact: o = !1, onPress: s, label: c, connecting: l = !1 }) => {
|
|
6
|
+
let u = e(a), { muted: d, phase: f, error: p } = a, m = f === "thinking" || f === "idle" || f === "ended" || p !== null || l, h = d && f !== "speaking" ? "from-bg-elevated to-bg-elevated" : u === "listening" ? "from-action-primary-bg/80 to-action-primary-bg/20" : u === "thinking" ? "from-text-muted/60 to-text-muted/10" : u === "speaking" ? "from-action-primary-bg to-action-primary-bg/40" : "from-bg-elevated to-bg-elevated/40", g = d && f !== "speaking" ? "" : u === "listening" ? "motion-safe:animate-pulse" : u === "thinking" ? "motion-safe:animate-[pulse_1.6s_ease-in-out_infinite]" : u === "speaking" ? "motion-safe:animate-[pulse_0.9s_ease-in-out_infinite]" : "", _ = o ? "h-16 w-40" : "h-24 w-56", v = o ? "size-6" : "size-8", y = f === "speaking" ? r : d ? n : t;
|
|
7
7
|
return /* @__PURE__ */ i("button", {
|
|
8
8
|
type: "button",
|
|
9
9
|
onClick: s,
|
|
10
|
-
disabled:
|
|
11
|
-
className: `flex ${
|
|
10
|
+
disabled: m || !s,
|
|
11
|
+
className: `flex ${_} items-center justify-center rounded-full bg-gradient-to-b ${h} ${g} text-text-primary shadow-lg transition-colors duration-300 focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-default`,
|
|
12
12
|
"aria-label": c,
|
|
13
|
-
"aria-pressed":
|
|
13
|
+
"aria-pressed": f === "speaking" ? void 0 : d,
|
|
14
14
|
"data-testid": "assistant-voice-orb",
|
|
15
|
-
"data-state":
|
|
16
|
-
"data-muted":
|
|
17
|
-
children: /* @__PURE__ */ i(
|
|
18
|
-
className:
|
|
15
|
+
"data-state": u,
|
|
16
|
+
"data-muted": d || void 0,
|
|
17
|
+
children: /* @__PURE__ */ i(y, {
|
|
18
|
+
className: v,
|
|
19
19
|
"aria-hidden": "true"
|
|
20
20
|
})
|
|
21
21
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantVoiceOrb.js","names":[],"sources":["../../../../src/components/assistant/voice/AssistantVoiceOrb.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { Mic, MicOff, Square } from 'lucide-react';\nimport type { VoiceSessionSnapshot } from '../../../utils/voiceSession';\nimport { orbMode } from '../../../utils/voiceSession';\n\n/**\n * The session's single animated control (BOFF-7120).\n *\n * It was a decorative round orb with a separate mic button beneath it. Now it is\n * one pill that both SHOWS the state and IS the control, because two elements\n * were saying the same thing: the orb pulsed to mean \"listening\" while the mic\n * button sat next to it meaning \"the microphone\". Merging them leaves a single\n * large target, which matters when the user is talking rather than looking.\n *\n * What tapping it does depends on the phase, and the icon always says which:\n * - listening -> mute (Mic)\n * - muted -> unmute (MicOff)\n * - speaking -> interrupt (Square — the stop glyph, not a microphone)\n * - thinking -> nothing (disabled; there is nothing to stop or mute yet)\n *\n * Interruption living here is deliberate: it is the biggest target on screen,\n * and it replaced barge-in when the microphone had to be closed during playback\n * to stop the assistant transcribing its own voice.\n */\ninterface Props {\n session: VoiceSessionSnapshot;\n compact?: boolean;\n onPress?: () => void;\n /** Accessible name — the caller knows the translated strings. */\n label: string;\n}\n\nexport const AssistantVoiceOrb: FC<Props> = ({ session, compact = false, onPress, label }) => {\n const mode = orbMode(session);\n const { muted, phase, error } = session;\n // Nothing to mute and nothing to stop: a press here would be a no-op, and a\n // control that does nothing is worse than one that is visibly unavailable.\n // ★ `ended`/`error` included. A failed session now STAYS MOUNTED so it can say\n // why it failed, which promotes this from an invisible dead button to the\n // largest control on a screen users actually reach. The reducer swallows\n // `mute` once ended, so leaving it enabled would offer to turn off a\n // microphone that was refused, and do nothing when pressed.\n const disabled = phase === 'thinking' || phase === 'idle' || phase === 'ended' || error !== null;\n\n // Colour carries the state for anyone who cannot perceive the motion; the\n // animation is a second, redundant channel rather than the only one.\n const tone =\n muted && phase !== 'speaking'\n ? 'from-bg-elevated to-bg-elevated'\n : mode === 'listening'\n ? 'from-action-primary-bg/80 to-action-primary-bg/20'\n : mode === 'thinking'\n ? 'from-text-muted/60 to-text-muted/10'\n : mode === 'speaking'\n ? 'from-action-primary-bg to-action-primary-bg/40'\n : 'from-bg-elevated to-bg-elevated/40';\n\n const motion =\n muted && phase !== 'speaking'\n ? ''\n : mode === 'listening'\n ? 'motion-safe:animate-pulse'\n : mode === 'thinking'\n ? 'motion-safe:animate-[pulse_1.6s_ease-in-out_infinite]'\n : mode === 'speaking'\n ? 'motion-safe:animate-[pulse_0.9s_ease-in-out_infinite]'\n : '';\n\n // Pill, not a circle: wide enough to read as a control rather than an\n // ornament, and it leaves room for the icon to sit centred at any size.\n const size = compact ? 'h-16 w-40' : 'h-24 w-56';\n const icon = compact ? 'size-6' : 'size-8';\n\n const Glyph = phase === 'speaking' ? Square : muted ? MicOff : Mic;\n\n return (\n <button\n type=\"button\"\n onClick={onPress}\n disabled={disabled || !onPress}\n className={`flex ${size} items-center justify-center rounded-full bg-gradient-to-b ${tone} ${motion} text-text-primary shadow-lg transition-colors duration-300 focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-default`}\n aria-label={label}\n // A toggle in the listening/muted phases, so its state is announced as\n // one. Omitted while speaking, where the press is a one-shot stop rather\n // than a toggle and `aria-pressed` would misdescribe it.\n aria-pressed={phase === 'speaking' ? undefined : muted}\n data-testid=\"assistant-voice-orb\"\n data-state={mode}\n data-muted={muted || undefined}\n >\n <Glyph className={icon} aria-hidden=\"true\" />\n </button>\n );\n};\n"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"AssistantVoiceOrb.js","names":[],"sources":["../../../../src/components/assistant/voice/AssistantVoiceOrb.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { Mic, MicOff, Square } from 'lucide-react';\nimport type { VoiceSessionSnapshot } from '../../../utils/voiceSession';\nimport { orbMode } from '../../../utils/voiceSession';\n\n/**\n * The session's single animated control (BOFF-7120).\n *\n * It was a decorative round orb with a separate mic button beneath it. Now it is\n * one pill that both SHOWS the state and IS the control, because two elements\n * were saying the same thing: the orb pulsed to mean \"listening\" while the mic\n * button sat next to it meaning \"the microphone\". Merging them leaves a single\n * large target, which matters when the user is talking rather than looking.\n *\n * What tapping it does depends on the phase, and the icon always says which:\n * - listening -> mute (Mic)\n * - muted -> unmute (MicOff)\n * - speaking -> interrupt (Square — the stop glyph, not a microphone)\n * - thinking -> nothing (disabled; there is nothing to stop or mute yet)\n *\n * Interruption living here is deliberate: it is the biggest target on screen,\n * and it replaced barge-in when the microphone had to be closed during playback\n * to stop the assistant transcribing its own voice.\n */\ninterface Props {\n session: VoiceSessionSnapshot;\n compact?: boolean;\n onPress?: () => void;\n /** Accessible name — the caller knows the translated strings. */\n label: string;\n /** Start-up window: the recogniser has been asked but is not capturing yet. */\n connecting?: boolean;\n}\n\nexport const AssistantVoiceOrb: FC<Props> = ({ session, compact = false, onPress, label, connecting = false }) => {\n const mode = orbMode(session);\n const { muted, phase, error } = session;\n // Nothing to mute and nothing to stop: a press here would be a no-op, and a\n // control that does nothing is worse than one that is visibly unavailable.\n // ★ `ended`/`error` included. A failed session now STAYS MOUNTED so it can say\n // why it failed, which promotes this from an invisible dead button to the\n // largest control on a screen users actually reach. The reducer swallows\n // `mute` once ended, so leaving it enabled would offer to turn off a\n // microphone that was refused, and do nothing when pressed.\n // ★ `connecting` included. The only thing a tap does here is toggle mute, and\n // `voiceStageState` treats a muted non-capturing session as `listening` — so\n // tapping during start-up flipped the stage into claiming it was listening at a\n // microphone that was not open yet. Disabling closes that, and matches the rule\n // this file already follows: a control that does nothing is worse than one that\n // is visibly unavailable.\n const disabled = phase === 'thinking' || phase === 'idle' || phase === 'ended' || error !== null || connecting;\n\n // Colour carries the state for anyone who cannot perceive the motion; the\n // animation is a second, redundant channel rather than the only one.\n const tone =\n muted && phase !== 'speaking'\n ? 'from-bg-elevated to-bg-elevated'\n : mode === 'listening'\n ? 'from-action-primary-bg/80 to-action-primary-bg/20'\n : mode === 'thinking'\n ? 'from-text-muted/60 to-text-muted/10'\n : mode === 'speaking'\n ? 'from-action-primary-bg to-action-primary-bg/40'\n : 'from-bg-elevated to-bg-elevated/40';\n\n const motion =\n muted && phase !== 'speaking'\n ? ''\n : mode === 'listening'\n ? 'motion-safe:animate-pulse'\n : mode === 'thinking'\n ? 'motion-safe:animate-[pulse_1.6s_ease-in-out_infinite]'\n : mode === 'speaking'\n ? 'motion-safe:animate-[pulse_0.9s_ease-in-out_infinite]'\n : '';\n\n // Pill, not a circle: wide enough to read as a control rather than an\n // ornament, and it leaves room for the icon to sit centred at any size.\n const size = compact ? 'h-16 w-40' : 'h-24 w-56';\n const icon = compact ? 'size-6' : 'size-8';\n\n const Glyph = phase === 'speaking' ? Square : muted ? MicOff : Mic;\n\n return (\n <button\n type=\"button\"\n onClick={onPress}\n disabled={disabled || !onPress}\n className={`flex ${size} items-center justify-center rounded-full bg-gradient-to-b ${tone} ${motion} text-text-primary shadow-lg transition-colors duration-300 focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-default`}\n aria-label={label}\n // A toggle in the listening/muted phases, so its state is announced as\n // one. Omitted while speaking, where the press is a one-shot stop rather\n // than a toggle and `aria-pressed` would misdescribe it.\n aria-pressed={phase === 'speaking' ? undefined : muted}\n data-testid=\"assistant-voice-orb\"\n data-state={mode}\n data-muted={muted || undefined}\n >\n <Glyph className={icon} aria-hidden=\"true\" />\n </button>\n );\n};\n"],"mappings":";;;;AAkCA,IAAa,KAAgC,EAAE,YAAS,aAAU,IAAO,YAAS,UAAO,gBAAa,SAAY;CAChH,IAAM,IAAO,EAAQ,CAAO,GACtB,EAAE,UAAO,UAAO,aAAU,GAc1B,IAAW,MAAU,cAAc,MAAU,UAAU,MAAU,WAAW,MAAU,QAAQ,GAI9F,IACJ,KAAS,MAAU,aACf,oCACA,MAAS,cACP,sDACA,MAAS,aACP,wCACA,MAAS,aACP,mDACA,sCAEN,IACJ,KAAS,MAAU,aACf,KACA,MAAS,cACP,8BACA,MAAS,aACP,0DACA,MAAS,aACP,0DACA,IAIN,IAAO,IAAU,cAAc,aAC/B,IAAO,IAAU,WAAW,UAE5B,IAAQ,MAAU,aAAa,IAAS,IAAQ,IAAS;CAE/D,OACE,kBAAC,UAAD;EACE,MAAK;EACL,SAAS;EACT,UAAU,KAAY,CAAC;EACvB,WAAW,QAAQ,EAAK,6DAA6D,EAAK,GAAG,EAAO;EACpG,cAAY;EAIZ,gBAAc,MAAU,aAAa,KAAA,IAAY;EACjD,eAAY;EACZ,cAAY;EACZ,cAAY,KAAS,KAAA;YAErB,kBAAC,GAAD;GAAO,WAAW;GAAM,eAAY;EAAQ,CAAA;CACtC,CAAA;AAEZ"}
|
|
@@ -88,6 +88,7 @@ var _ = ({ session: _, turns: b = [], notice: x = null, spoken: S, onInterrupt:
|
|
|
88
88
|
let e = /* @__PURE__ */ h(n, {
|
|
89
89
|
session: _,
|
|
90
90
|
compact: R,
|
|
91
|
+
connecting: W === "connecting",
|
|
91
92
|
onPress: r(W) ? C : w,
|
|
92
93
|
label: r(W) ? k("healthybowl.assistant.voiceSession.interrupt", "Stop the assistant and speak") : j ? k("healthybowl.assistant.voiceSession.unmute", "Turn the microphone on") : k("healthybowl.assistant.voiceSession.mute", "Turn the microphone off")
|
|
93
94
|
}), t = r(W) ? S : U || null, i = M === null ? null : y(M, k);
|