@burdenoff/microfe-healthybowl 2026.902.21 → 2026.902.23

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.
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantSpeechProvider.js","names":[],"sources":["../../../src/components/assistant/AssistantSpeechProvider.tsx"],"sourcesContent":["/**\n * Speech-output context for the assistant panel (BOFF-6290).\n *\n * The assistant could already hear (`useVoiceInput`); this is the other half —\n * it can now answer out loud. That matters for a farming product where the user\n * is outdoors with dirty hands, a phone in a pocket and sun on the screen, and\n * it is a plain accessibility win everywhere else.\n *\n * Everything stateful about playback lives here, once, so that:\n *\n * - **playback is never orphaned.** A voice that keeps talking after the UI is\n * gone is a bug, so speech is cancelled when the panel hides, when the\n * conversation changes, on unmount, and on `pagehide` (Chrome keeps speaking\n * across a navigation otherwise);\n * - **only one message speaks at a time.** Starting a new playback cancels the\n * previous one — enforced by the engine and by the request-id guard in\n * `speechPlaybackReducer`;\n * - **nothing ever autoplays.** Playback starts from a button press. The\n * persisted auto-speak preference defaults OFF and is opt-in from the header.\n *\n * Components consume this through `useAssistantSpeech()`, which falls back to an\n * inert value when there is no provider (Storybook, a header rendered on its\n * own) rather than throwing.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type FC,\n type ReactNode,\n} from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { voicePreviewText } from '@/utils/voicePreview';\nimport { getSpeechEngine } from '../../services/speech';\nimport type { SpeechEngine, SpeechVoiceLike } from '../../services/speech';\nimport { chunkForSpeech, toSpeakableText, type SpeakableLabels } from '../../utils/speakableText';\nimport { speechLabelsFor } from '../../config/speechLabels';\n\n/**\n * The speakable transformation with nothing of ours added — used ONLY to decide\n * the reply's language.\n *\n * Detection needs the prose that will be spoken: code blocks and URLs stripped\n * (they are never read aloud, and their Latin identifiers would outvote short\n * non-Latin prose), but no substitute wording introduced either (that would let\n * our own app-locale words vote instead).\n */\nconst SILENT_LABELS: SpeakableLabels = {\n codeBlock: '',\n image: '',\n link: '',\n largeTable: '',\n truncated: '',\n emailAt: 'at',\n emailDot: 'dot',\n nestedItem: '',\n};\nimport {\n VOICE_LIST_TIMEOUT_MS,\n languageDisplayName,\n selectVoiceForLocale,\n voicesForLocale,\n speechGate,\n speechLangForLocale,\n voiceAvailability,\n type VoiceAvailability,\n} from '../../utils/speechVoices';\nimport { resolveSpeechLocale } from '../../utils/replyLanguage';\nimport { DEFAULT_SPEECH_RATE, findAssistantLanguage } from '../../config/assistantLanguages';\nimport { resolveLanguagePair } from '../../config/assistantLanguagePair';\nimport { IDLE_PLAYBACK, isSpeakingMessage, speechPlaybackReducer } from '../../utils/speechPlayback';\nimport { isTurnInFlight } from '../../utils/assistantTurnState';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport interface AssistantSpeechContextValue {\n /** False when the platform has no speech output — hide the control entirely. */\n isSupported: boolean;\n availability: VoiceAvailability;\n /**\n * True when nothing can be spoken in the app language, so every control that\n * starts playback — the per-message button AND the header toggle — must be\n * inert. `pending` is not blocked: see `speechGate`.\n */\n isBlocked: boolean;\n /** Explains a disabled control (no installed voice for the app language). */\n disabledReason: string | null;\n /**\n * Why THIS message cannot be spoken, when the app language is fine but the\n * reply is not in it — a Tamil answer in an English UI on a device with no\n * Tamil voice. `isBlocked` cannot see that: it is computed before any reply\n * exists. Without this the control looks enabled and silently refuses, which\n * is the dead-button bug all over again (BOFF-7106).\n */\n blockedFor: (messageId: string) => string | null;\n /**\n * Every installed voice that can read the language the user speaks, best\n * first. Empty when there is no choice to offer — the picker hides itself\n * rather than showing a one-item dropdown.\n */\n voiceChoices: readonly SpeechVoiceLike[];\n /** The voice that will actually be used, resolved from the pick + ranking. */\n activeVoiceName: string | null;\n /**\n * The RAW stored pick: `null` means \"use the ranked default\".\n *\n * The picker must be driven by this rather than by `activeVoiceName`, or the\n * two states collapse — with nothing stored, the ranked winner is already the\n * shown option, so choosing it fires no change event and the pick can never\n * be made. The user's voice would then silently move the next time the device\n * installs a higher-ranked one. Same trap as the language selector.\n */\n preferredVoiceName: string | null;\n /** `null` restores the ranked default for the current language. */\n setVoice: (voiceName: string | null) => void;\n /** The message currently being spoken, if any. */\n speakingMessageId: string | null;\n isSpeaking: (messageId: string) => boolean;\n /**\n * Speak this message, or stop if it is already the one speaking.\n *\n * `turnLocale` is the language the reply was GENERATED under, from the\n * message's own metadata. It matters because script detection cannot separate\n * Latin-script languages, so without it an old French reply would be read\n * with whatever voice the CURRENT preference selects.\n */\n toggle: (messageId: string, markdown: string, turnLocale?: string) => void;\n stop: () => void;\n autoSpeakEnabled: boolean;\n setAutoSpeak: (enabled: boolean) => void;\n /**\n * Speak replies for the duration of a live voice session, WITHOUT touching the\n * user's saved preference.\n *\n * ★ Live Voice used to force `autoSpeakEnabled` true and restore it on exit.\n * That field is PERSISTED (assistantStore partialize), and the restore only\n * ran on a clean `end()` — so a reload, a closed tab or a backgrounded webview\n * during a session left auto-speak switched ON for the user permanently, in\n * normal typed chat, with the toggle showing a state they never chose. The\n * default was never wrong; the session was overwriting it.\n *\n * Session-scoped React state instead: it cannot outlive the page, so there is\n * nothing to restore and nothing to leak.\n */\n sessionSpeaking: boolean;\n setSessionSpeaking: (enabled: boolean) => void;\n /** Play a short sample in a named voice. No model call, no message, no tokens. */\n previewVoice: (voiceName: string) => void;\n}\n\nconst INERT_SPEECH: AssistantSpeechContextValue = {\n isSupported: false,\n availability: 'unsupported',\n isBlocked: true,\n disabledReason: null,\n blockedFor: () => null,\n voiceChoices: [],\n activeVoiceName: null,\n preferredVoiceName: null,\n setVoice: () => {},\n speakingMessageId: null,\n isSpeaking: () => false,\n toggle: () => {},\n stop: () => {},\n autoSpeakEnabled: false,\n setAutoSpeak: () => {},\n sessionSpeaking: false,\n setSessionSpeaking: () => {},\n previewVoice: () => {},\n};\n\nconst AssistantSpeechContext = createContext<AssistantSpeechContextValue>(INERT_SPEECH);\n\nexport function useAssistantSpeech(): AssistantSpeechContextValue {\n return useContext(AssistantSpeechContext);\n}\n\ninterface Props {\n children: ReactNode;\n /** Panel visibility. Hiding the panel stops the voice. */\n visible?: boolean;\n /**\n * Injectable for tests and local experiments. The default routes between the\n * device engine and the hosted one; with hosted TTS unconfigured it IS the\n * device engine, unchanged.\n */\n engine?: SpeechEngine;\n}\n\nexport const AssistantSpeechProvider: FC<Props> = ({ children, visible = true, engine = getSpeechEngine() }) => {\n const tr = useTr();\n const { locale } = useI18n();\n const [playback, dispatch] = useReducer(speechPlaybackReducer, IDLE_PLAYBACK);\n const [voices, setVoices] = useState<SpeechVoiceLike[]>(() => engine.listVoices());\n /**\n * True once we have waited out the voice list and it was still empty.\n *\n * Turns an indefinite `pending` into a terminal `no-voices`, which is what\n * lets the control be disabled with a reason instead of silently doing\n * nothing on every press.\n */\n const [voiceProbeSettled, setVoiceProbeSettled] = useState(false);\n /**\n * Every message we have refused, and why — keyed by id (see `blockedFor`).\n *\n * A single record could only describe one refusal: refusing a second reply\n * silently re-enabled the first, whose voice was still just as missing, so\n * pressing the buttons walked the disabled state around the transcript.\n */\n const [unspeakable, setUnspeakable] = useState<ReadonlyMap<string, string>>(() => new Map());\n const requestRef = useRef(0);\n /** Cancels a playback that is waiting for the engine's voice list, if any. */\n const pendingRef = useRef<(() => void) | null>(null);\n const speakWithRef = useRef<\n (messageId: string, text: string, voices: readonly SpeechVoiceLike[], speechLocale: string) => void\n >(() => {});\n\n const cancelPending = useCallback(() => {\n pendingRef.current?.();\n pendingRef.current = null;\n }, []);\n\n const autoSpeakEnabled = useAssistantStore((state) => state.autoSpeakEnabled);\n const setAutoSpeak = useAssistantStore((state) => state.setAutoSpeak);\n // Not in the store on purpose — see `sessionSpeaking` on the context type.\n const [sessionSpeaking, setSessionSpeaking] = useState(false);\n const activeConversationId = useAssistantStore((state) => state.activeConversationId);\n\n const isSupported = useMemo(() => engine.isSupported(), [engine]);\n\n // getVoices() is empty on the first call in Chrome and only fills in when\n // 'voiceschanged' fires; Safari populates it synchronously and may never fire\n // the event. Read eagerly AND subscribe, so both engines end up correct.\n useEffect(() => {\n if (!isSupported) return;\n const sync = () => {\n setVoices(engine.listVoices());\n // Every recorded refusal was \"no voice for this language\". A new voice\n // list may well have supplied one — most likely because the user just\n // followed our instructions and installed it. Keeping the refusals would\n // leave those buttons disabled with no way back except a reload.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n sync();\n return engine.subscribeVoices(sync);\n }, [engine, isSupported]);\n\n // The language being SPOKEN ALOUD — which is the language of the reply, not\n // of the input and not of the interface. The two were one field until the\n // reply language was split out (BOFF-7108).\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const replyLanguage = useAssistantStore((state) => state.replyLanguage);\n const preferredVoices = useAssistantStore((state) => state.preferredVoices);\n const setPreferredVoice = useAssistantStore((state) => state.setPreferredVoice);\n const spokenLanguage = useMemo(\n // ★ The REPLY language, not the input. This is the language of the text\n // being spoken, so wiring it to the input would give a Tamil voice reading\n // an English answer the moment the two are set differently — the single\n // worst outcome available here, and the reason they were split at all.\n () => resolveLanguagePair(assistantLanguage, replyLanguage, locale).reply,\n [assistantLanguage, replyLanguage, locale]\n );\n const spokenLocale = spokenLanguage.code;\n\n /**\n * BCP-47 tag to ask the engine for, given a resolved language CODE.\n *\n * Resolved through the catalogue for ANY known code, not merely the currently\n * selected one — a historical Bengali reply must still get `bn-IN` after the\n * user switches to Tamil, or with both `bn-IN` and `bn-BD` installed the\n * engine's own order decides, and picks the wrong country.\n *\n * Falls back to the generic table for codes the catalogue does not carry.\n */\n const tagFor = useCallback((code: string) => findAssistantLanguage(code)?.tag ?? speechLangForLocale(code), []);\n\n /** Speaking rate for a resolved language code — see `AssistantLanguage.rate`. */\n const rateFor = useCallback((code: string) => findAssistantLanguage(code)?.rate ?? DEFAULT_SPEECH_RATE, []);\n\n const availability = useMemo(\n () => voiceAvailability(isSupported, voices, spokenLanguage.tag, voiceProbeSettled),\n [isSupported, voices, spokenLanguage, voiceProbeSettled]\n );\n\n // Spoken placeholders follow the app locale like the rest of the copy; the\n // transformation itself stays a pure function by taking them as arguments.\n const labels = useMemo<SpeakableLabels>(\n () => ({\n codeBlock: tr('healthybowl.assistant.speech.codeBlock', 'Code block'),\n image: tr('healthybowl.assistant.speech.image', 'image'),\n link: tr('healthybowl.assistant.speech.link', 'link'),\n largeTable: tr('healthybowl.assistant.speech.largeTable', 'Table with {{rows}} rows and {{columns}} columns'),\n truncated: tr('healthybowl.assistant.speech.truncated', 'The rest of this message is not read aloud'),\n nestedItem: tr('healthybowl.assistant.speech.nestedItem', 'Sub-item {{ordinal}}'),\n emailAt: tr('healthybowl.assistant.speech.emailAt', 'at'),\n emailDot: tr('healthybowl.assistant.speech.emailDot', 'dot'),\n }),\n [tr]\n );\n\n const stop = useCallback(() => {\n cancelPending();\n engine.cancel();\n dispatch({ type: 'stop' });\n }, [cancelPending, engine]);\n\n /**\n * Audition a voice — no model call, no message, no tokens.\n *\n * ★ Speaks through the engine DIRECTLY rather than through `speakWith`. That\n * path is built around a message: it resolves the reply's language, records\n * per-message \"cannot speak this\" state, and drives `speakingMessageId` so a\n * Listen button can light up. A preview has no message, so borrowing it would\n * mean inventing a fake id and then teaching every consumer to ignore it.\n *\n * Consequently it deliberately does NOT touch playback state: auditioning a\n * voice must not make a Listen button in the thread appear to be playing.\n *\n * Speaks the sample in the language being spoken, not the interface language —\n * the listener is judging how this voice reads THAT language.\n */\n const previewVoice = useCallback(\n (voiceName: string) => {\n const voice = engine.listVoices().find((candidate) => candidate.name === voiceName) ?? null;\n // An unknown name means the list changed under us (a download finished, a\n // profile switched). Silence is the right answer — better than falling\n // back to some other voice and auditioning the wrong one.\n if (!voice) return;\n // Whatever is speaking now is not what the user asked to hear.\n stop();\n engine.speak([voicePreviewText(spokenLocale)], { voice, lang: tagFor(spokenLocale) });\n },\n [engine, spokenLocale, stop, tagFor]\n );\n\n const blockedFor = useCallback((messageId: string) => unspeakable.get(messageId) ?? null, [unspeakable]);\n\n /**\n * Hold one playback until the engine publishes its voice list.\n *\n * Bounded: on timeout we take one last look and decide with whatever is\n * there, so an engine that never fires `voiceschanged` costs a two-second\n * wait rather than a control that is disabled forever. Nothing is spoken from\n * here unless a list actually arrives — an empty list means the engine would\n * pick its own default voice, which is the cross-language read this feature\n * promises never to do.\n */\n const waitForVoices = useCallback(\n (messageId: string, text: string, speechLocale: string) => {\n cancelPending();\n\n let settled = false;\n let unsubscribe = () => {};\n const finish = (available: SpeechVoiceLike[]) => {\n if (settled) return;\n settled = true;\n pendingRef.current = null;\n clearTimeout(timer);\n unsubscribe();\n if (available.length === 0) {\n // We waited and looked again: this device has no voices at all.\n // Record it so `availability` becomes `no-voices` and the control\n // explains itself, instead of returning silently every press.\n setVoiceProbeSettled(true);\n return;\n }\n setVoices(available);\n speakWithRef.current(messageId, text, available, speechLocale);\n };\n\n const timer = setTimeout(() => finish(engine.listVoices()), VOICE_LIST_TIMEOUT_MS);\n unsubscribe = engine.subscribeVoices(() => finish(engine.listVoices()));\n\n pendingRef.current = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n unsubscribe();\n pendingRef.current = null;\n };\n },\n [cancelPending, engine]\n );\n\n /**\n * Speak text against a KNOWN voice list.\n *\n * Every playback path funnels through here — the per-message button, the\n * header toggle's auto-speak, the store subscription — so the language gate\n * cannot be bypassed by any of them. Reading a Tamil reply with an English\n * voice is confident nonsense; it has to be impossible, not merely unlikely.\n */\n const speakWith = useCallback(\n (messageId: string, text: string, available: readonly SpeechVoiceLike[], speechLocale: string) => {\n let known = available;\n\n // Chrome answers the FIRST getVoices() with [] and fills the list in\n // asynchronously. One more synchronous read usually settles it.\n if (known.length === 0) {\n const refreshed = engine.listVoices();\n if (refreshed.length > 0) {\n known = refreshed;\n setVoices(refreshed);\n }\n }\n\n const speechLang = tagFor(speechLocale);\n\n const gate = speechGate(voiceAvailability(true, known, speechLocale, voiceProbeSettled));\n if (gate === 'block') {\n // Recorded for THIS message, always. Availability is resolved per reply\n // now, so a global \"your language has no voice\" cannot stand in for it:\n // the language the user chose to converse in says nothing about the one\n // this particular reply came back in.\n const reason = tr(\n 'healthybowl.assistant.speech.noVoiceForReply',\n 'This reply is in {{language}}, and no {{language}} voice is installed on this device.',\n { language: languageDisplayName(speechLang, locale) }\n );\n setUnspeakable((current) => new Map(current).set(messageId, reason));\n return;\n }\n if (gate === 'wait-for-voices') {\n waitForVoices(messageId, text, speechLocale);\n return;\n }\n\n setUnspeakable((current) => {\n if (!current.has(messageId)) return current;\n const next = new Map(current);\n next.delete(messageId);\n return next;\n });\n\n const requestId = requestRef.current + 1;\n requestRef.current = requestId;\n dispatch({ type: 'start', messageId, requestId });\n\n engine.speak(\n chunkForSpeech(text),\n // The TAG, not the code — so exact regional matching gets its chance\n // before the same-language fallback. `rate` had never been passed at\n // all, so every reply was read at the engine default.\n {\n voice: selectVoiceForLocale(known, speechLang, preferredVoices[speechLocale]),\n lang: speechLang,\n rate: rateFor(speechLocale),\n },\n {\n onEnd: () => dispatch({ type: 'finished', requestId }),\n // Includes the 'cancelled' every queued utterance reports when we\n // pre-empt a batch; the request-id guard drops those as stale.\n onError: () => dispatch({ type: 'failed', requestId }),\n }\n );\n },\n [engine, locale, preferredVoices, rateFor, tagFor, tr, voiceProbeSettled, waitForVoices]\n );\n\n // `waitForVoices` resumes through this ref, so the two do not become a\n // circular hook dependency.\n useEffect(() => {\n speakWithRef.current = speakWith;\n }, [speakWith]);\n\n const speak = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (!isSupported) return;\n\n // Resolve the reply's language BEFORE building the spoken text, because\n // the stand-in words must be in that language. Detection deliberately runs\n // on a SILENT_LABELS pass — our own words must not vote on which language\n // the reply is in — so it does not depend on the labels chosen here.\n const replyLocale = resolveSpeechLocale(\n toSpeakableText(markdown, { labels: SILENT_LABELS }),\n turnLocale ?? spokenLocale\n );\n\n // ★ Labels in the REPLY's language, not the interface's. An English\n // interface reading a Tamil answer used to say \"Code block\" and \"image\" in\n // English, mid-Tamil-sentence — the same defect the email `at`/`dot` fix\n // addressed and did not generalise.\n const text = toSpeakableText(markdown, { labels: speechLabelsFor(replyLocale, labels) });\n if (!text) return;\n\n // Detect on the text that will actually be SPOKEN, with our own words\n // removed — neither the raw markdown nor the finished transformation.\n //\n // The transformation injects app-locale placeholders (\"Code block\"), which\n // let English chrome outvote short non-Latin prose. The raw markdown keeps\n // fenced code, whose Latin identifiers do the same thing — and that code is\n // never spoken at all. Running the same transformation with EMPTY labels\n // strips the unspoken constructs while contributing no words of its own,\n // which is exactly the denominator the decision needs.\n // The turn's OWN language first — the preference is only a stand-in for\n // replies that predate it. Resolved above, and reused rather than\n // recomputed.\n speakWith(messageId, text, voices, replyLocale);\n },\n [isSupported, labels, spokenLocale, speakWith, voices]\n );\n\n const toggle = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (isSpeakingMessage(playback, messageId)) {\n stop();\n return;\n }\n speak(messageId, markdown, turnLocale);\n },\n [playback, speak, stop]\n );\n\n // ── Never leave a voice talking to an empty room ─────────────────────────\n useEffect(() => {\n if (!visible) stop();\n }, [visible, stop]);\n\n useEffect(() => {\n // Switching (or creating) a conversation abandons the reply being read —\n // and the refusal explained a message that is no longer on screen.\n stop();\n setUnspeakable(new Map());\n }, [activeConversationId, stop]);\n\n useEffect(() => {\n // Every refusal was decided against the locale in force at the time, which\n // is what a Latin-script reply falls back to. Change the locale and those\n // verdicts may simply be wrong — an English reply refused on a\n // Spanish-only device would stay disabled forever after switching the UI to\n // Spanish, with the voice that could read it already installed.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n // And stop anything mid-sentence. The new language can make this message\n // unspeakable, which disables its button — leaving it reading \"Stop\" with no\n // way to actually stop, short of closing the panel.\n stop();\n }, [spokenLocale, stop]);\n\n useEffect(() => {\n return () => {\n pendingRef.current?.();\n pendingRef.current = null;\n engine.cancel();\n };\n }, [engine]);\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n // Chrome carries speech across a same-tab navigation and a bfcache restore\n // would otherwise come back mid-sentence.\n const handlePageHide = () => engine.cancel();\n window.addEventListener('pagehide', handlePageHide);\n return () => window.removeEventListener('pagehide', handlePageHide);\n }, [engine]);\n\n // ── One timeout is not a life sentence ───────────────────────────────────\n //\n // `no-voices` disables the control, and a disabled control can never reach\n // `speakWith` — the only path that re-reads `engine.listVoices()`. So without\n // this, a user who follows our own advice, leaves to install a voice and comes\n // back stays blocked until a reload: we would be telling them how to fix it\n // and then refusing to notice that they had.\n //\n // Returning to the tab is exactly when that happens, and it costs one\n // synchronous read of an already-populated list.\n useEffect(() => {\n if (typeof document === 'undefined' || !isSupported) return;\n const reprobe = () => {\n if (document.visibilityState !== 'visible') return;\n // Adopt the list UNCONDITIONALLY, including an empty one. Keeping the old\n // cache on an empty read means a user who uninstalled their last voice\n // stays `ready`, and playback then hands the engine a voice object that no\n // longer exists instead of explaining the problem.\n //\n // Safe to accept an empty read here precisely because the probe verdict is\n // cleared on the next line: empty + unsettled is `pending`, which leaves\n // the control ENABLED and defers the real decision to the next press.\n const available = engine.listVoices();\n // A Listen press may still be inside its two-second wait. Adopting voices\n // here flips the control to `ready`, so the user can press again and start\n // playback — and then the original timer fires, calls back into\n // `speakWith` for the same message, and the engine cancels and restarts it\n // mid-sentence. Retire the waiter as part of adopting the list.\n if (available.length > 0) cancelPending();\n setVoices(available);\n setVoiceProbeSettled(false);\n // Same reason the `voiceschanged` path clears them: every refusal meant\n // \"no voice for this language\", and this is the moment a user who went\n // away to install one comes back. `subscribeVoices` does not fire on an\n // eventless engine, which is precisely why this re-probe exists — so it\n // has to expire the refusals too.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n document.addEventListener('visibilitychange', reprobe);\n window.addEventListener('focus', reprobe);\n return () => {\n document.removeEventListener('visibilitychange', reprobe);\n window.removeEventListener('focus', reprobe);\n };\n }, [cancelPending, engine, isSupported]);\n\n // ── Opt-in auto-speak ────────────────────────────────────────────────────\n const speakRef = useRef(speak);\n useEffect(() => {\n speakRef.current = speak;\n }, [speak]);\n\n useEffect(() => {\n // `isBlocked` is the same gate the per-message button uses. Without it the\n // subscription fires on a device with no voice for the app language and the\n // engine reads a Tamil reply in English — the one thing this feature says\n // it will never do. `pending` is allowed through because `speakWith` waits\n // for the list before deciding.\n // NOT gated on `isSpeechBlocked(availability)` any more: that is the APP\n // language's availability, and it would suppress auto-speak for a reply in\n // a language this device CAN speak. `speakWith` resolves the reply's own\n // language and refuses safely there, which is the only place that can know.\n // Either the user's own preference, or a live voice session — which speaks\n // by definition and must not have to change that preference to do it.\n if ((!autoSpeakEnabled && !sessionSpeaking) || !visible || !isSupported) return;\n\n // Deliberately a store subscription keyed on the processing TRANSITION\n // rather than an effect over the message list: it fires only on the\n // in-flight → complete edge of the active conversation, so mounting the\n // panel, loading history or switching chats can never start talking.\n return useAssistantStore.subscribe((next, previous) => {\n const conversationId = next.activeConversationId;\n if (!conversationId || conversationId !== previous.activeConversationId) return;\n\n const current = next.processingByConversationId[conversationId];\n const before = previous.processingByConversationId[conversationId];\n if (current?.status !== 'complete' || !isTurnInFlight(before?.status)) return;\n\n const messageId = current.messageId ?? before?.messageId ?? null;\n if (!messageId) return;\n\n const message = next.conversations\n .find((conversation) => conversation.id === conversationId)\n ?.messages.find((candidate) => candidate.id === messageId);\n if (!message || message.role !== 'assistant') return;\n\n // Same split the transcript uses: speak the prose, not the tool log.\n const { text } = parseToolActivity(message.content);\n if (!text.trim()) return;\n\n speakRef.current(messageId, text, (message.metadata as { lang?: string } | undefined)?.lang);\n });\n }, [autoSpeakEnabled, sessionSpeaking, isSupported, visible]);\n\n // The candidates for the language the user SPEAKS — the picker is a setting,\n // so it must not follow whatever language the last reply happened to be in.\n const voiceChoices = useMemo(() => voicesForLocale(voices, spokenLanguage.tag), [voices, spokenLanguage]);\n const activeVoice = useMemo(\n () => selectVoiceForLocale(voices, spokenLanguage.tag, preferredVoices[spokenLocale]),\n [voices, spokenLanguage, preferredVoices, spokenLocale]\n );\n\n const value = useMemo<AssistantSpeechContextValue>(\n () => ({\n isSupported,\n availability,\n // ONLY `no-voices` — a device with no voices at all can never speak\n // anything. `missing-voice` means the APP language has none, which says\n // nothing about the language a given reply came back in; that case is\n // resolved per message by `blockedFor`.\n isBlocked: availability === 'no-voices',\n // Both blocked states are the user's device, not our bug — so the copy\n // names the language and says where to fix it. \"Nothing happened\" was\n // the old behaviour and it read as a broken feature.\n disabledReason:\n availability === 'no-voices'\n ? tr(\n 'healthybowl.assistant.speech.noVoicesOnDevice',\n 'This device has no speech voices installed. Add one in your device speech or accessibility settings.'\n )\n : null,\n blockedFor,\n voiceChoices,\n activeVoiceName: activeVoice?.name ?? null,\n preferredVoiceName: preferredVoices[spokenLocale] ?? null,\n setVoice: (voiceName: string | null) => setPreferredVoice(spokenLocale, voiceName),\n speakingMessageId: playback.status === 'speaking' ? playback.messageId : null,\n isSpeaking: (messageId: string) => isSpeakingMessage(playback, messageId),\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n setSessionSpeaking,\n previewVoice,\n }),\n [\n isSupported,\n availability,\n blockedFor,\n voiceChoices,\n activeVoice,\n preferredVoices,\n setPreferredVoice,\n spokenLocale,\n playback,\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n previewVoice,\n tr,\n ]\n );\n\n return <AssistantSpeechContext.Provider value={value}>{children}</AssistantSpeechContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsDA,IAAM,KAAiC;CACrC,WAAW;CACX,OAAO;CACP,MAAM;CACN,YAAY;CACZ,WAAW;CACX,SAAS;CACT,UAAU;CACV,YAAY;AACd,GAmHM,IAAyB,EAA2C;CApBxE,aAAa;CACb,cAAc;CACd,WAAW;CACX,gBAAgB;CAChB,kBAAkB;CAClB,cAAc,CAAC;CACf,i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AG;GAEvE,IAAM,IAAY,EAAQ,aAAa,GAAQ,aAAa;GAC5D,IAAI,CAAC,GAAW;GAEhB,IAAM,IAAU,EAAK,cAClB,MAAM,MAAiB,EAAa,OAAO,CAAc,GACxD,SAAS,MAAM,MAAc,EAAU,OAAO,CAAS;GAC3D,IAAI,CAAC,KAAW,EAAQ,SAAS,aAAa;GAG9C,IAAM,EAAE,YAAS,GAAkB,EAAQ,OAAO;GAC7C,EAAK,KAAK,KAEf,GAAS,QAAQ,GAAW,GAAO,EAAQ,UAA4C,IAAI;EAC7F,CAAC;CACH,GAAG;EAAC;EAAkB;EAAiB;EAAa;CAAO,CAAC;CAI5D,IAAM,KAAe,QAAc,GAAgB,GAAQ,EAAe,GAAG,GAAG,CAAC,GAAQ,CAAc,CAAC,GAClG,IAAc,QACZ,EAAqB,GAAQ,EAAe,KAAK,EAAgB,EAAa,GACpF;EAAC;EAAQ;EAAgB;EAAiB;CAAY,CACxD,GAEM,KAAQ,SACL;EACL;EACA;EAKA,WAAW,MAAiB;EAI5B,gBACE,MAAiB,cACb,EACE,iDACA,sGACF,IACA;EACN;EACA;EACA,iBAAiB,GAAa,QAAQ;EACtC,oBAAoB,EAAgB,MAAiB;EACrD,WAAW,MAA6B,EAAkB,GAAc,CAAS;EACjF,mBAAmB,EAAS,WAAW,aAAa,EAAS,YAAY;EACzE,aAAa,MAAsB,EAAkB,GAAU,CAAS;EACxE;EACA;EACA;EACA;EACA;EACA;EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,OAAO,mBAAC,EAAuB,UAAxB;EAAwC;EAAQ;CAA0C,CAAA;AACnG"}
1
+ {"version":3,"file":"AssistantSpeechProvider.js","names":[],"sources":["../../../src/components/assistant/AssistantSpeechProvider.tsx"],"sourcesContent":["/**\n * Speech-output context for the assistant panel (BOFF-6290).\n *\n * The assistant could already hear (`useVoiceInput`); this is the other half —\n * it can now answer out loud. That matters for a farming product where the user\n * is outdoors with dirty hands, a phone in a pocket and sun on the screen, and\n * it is a plain accessibility win everywhere else.\n *\n * Everything stateful about playback lives here, once, so that:\n *\n * - **playback is never orphaned.** A voice that keeps talking after the UI is\n * gone is a bug, so speech is cancelled when the panel hides, when the\n * conversation changes, on unmount, and on `pagehide` (Chrome keeps speaking\n * across a navigation otherwise);\n * - **only one message speaks at a time.** Starting a new playback cancels the\n * previous one — enforced by the engine and by the request-id guard in\n * `speechPlaybackReducer`;\n * - **nothing ever autoplays.** Playback starts from a button press. The\n * persisted auto-speak preference defaults OFF and is opt-in from the header.\n *\n * Components consume this through `useAssistantSpeech()`, which falls back to an\n * inert value when there is no provider (Storybook, a header rendered on its\n * own) rather than throwing.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type FC,\n type ReactNode,\n} from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { voicePreviewText } from '@/utils/voicePreview';\nimport { getSpeechEngine } from '../../services/speech';\nimport type { SpeechEngine, SpeechVoiceLike } from '../../services/speech';\nimport { chunkForSpeech, toSpeakableText, type SpeakableLabels } from '../../utils/speakableText';\nimport { speechLabelsFor } from '../../config/speechLabels';\n\n/**\n * The speakable transformation with nothing of ours added — used ONLY to decide\n * the reply's language.\n *\n * Detection needs the prose that will be spoken: code blocks and URLs stripped\n * (they are never read aloud, and their Latin identifiers would outvote short\n * non-Latin prose), but no substitute wording introduced either (that would let\n * our own app-locale words vote instead).\n */\nconst SILENT_LABELS: SpeakableLabels = {\n codeBlock: '',\n image: '',\n link: '',\n largeTable: '',\n truncated: '',\n emailAt: 'at',\n emailDot: 'dot',\n nestedItem: '',\n};\nimport {\n VOICE_LIST_TIMEOUT_MS,\n languageDisplayName,\n selectVoiceForLocale,\n voicesForLocale,\n speechGate,\n speechLangForLocale,\n voiceAvailability,\n type VoiceAvailability,\n} from '../../utils/speechVoices';\nimport { resolveSpeechLocale } from '../../utils/replyLanguage';\nimport { DEFAULT_SPEECH_RATE, findAssistantLanguage } from '../../config/assistantLanguages';\nimport { resolveLanguagePair } from '../../config/assistantLanguagePair';\nimport { IDLE_PLAYBACK, isSpeakingMessage, speechPlaybackReducer } from '../../utils/speechPlayback';\nimport { isVoiceTurn } from '../../utils/voiceTurnVisibility';\nimport { isTurnInFlight } from '../../utils/assistantTurnState';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport interface AssistantSpeechContextValue {\n /** False when the platform has no speech output — hide the control entirely. */\n isSupported: boolean;\n availability: VoiceAvailability;\n /**\n * True when nothing can be spoken in the app language, so every control that\n * starts playback — the per-message button AND the header toggle — must be\n * inert. `pending` is not blocked: see `speechGate`.\n */\n isBlocked: boolean;\n /** Explains a disabled control (no installed voice for the app language). */\n disabledReason: string | null;\n /**\n * Why THIS message cannot be spoken, when the app language is fine but the\n * reply is not in it — a Tamil answer in an English UI on a device with no\n * Tamil voice. `isBlocked` cannot see that: it is computed before any reply\n * exists. Without this the control looks enabled and silently refuses, which\n * is the dead-button bug all over again (BOFF-7106).\n */\n blockedFor: (messageId: string) => string | null;\n /**\n * Every installed voice that can read the language the user speaks, best\n * first. Empty when there is no choice to offer — the picker hides itself\n * rather than showing a one-item dropdown.\n */\n voiceChoices: readonly SpeechVoiceLike[];\n /** The voice that will actually be used, resolved from the pick + ranking. */\n activeVoiceName: string | null;\n /**\n * The RAW stored pick: `null` means \"use the ranked default\".\n *\n * The picker must be driven by this rather than by `activeVoiceName`, or the\n * two states collapse — with nothing stored, the ranked winner is already the\n * shown option, so choosing it fires no change event and the pick can never\n * be made. The user's voice would then silently move the next time the device\n * installs a higher-ranked one. Same trap as the language selector.\n */\n preferredVoiceName: string | null;\n /** `null` restores the ranked default for the current language. */\n setVoice: (voiceName: string | null) => void;\n /** The message currently being spoken, if any. */\n speakingMessageId: string | null;\n isSpeaking: (messageId: string) => boolean;\n /**\n * Speak this message, or stop if it is already the one speaking.\n *\n * `turnLocale` is the language the reply was GENERATED under, from the\n * message's own metadata. It matters because script detection cannot separate\n * Latin-script languages, so without it an old French reply would be read\n * with whatever voice the CURRENT preference selects.\n */\n toggle: (messageId: string, markdown: string, turnLocale?: string) => void;\n stop: () => void;\n autoSpeakEnabled: boolean;\n setAutoSpeak: (enabled: boolean) => void;\n /**\n * Speak replies for the duration of a live voice session, WITHOUT touching the\n * user's saved preference.\n *\n * ★ Live Voice used to force `autoSpeakEnabled` true and restore it on exit.\n * That field is PERSISTED (assistantStore partialize), and the restore only\n * ran on a clean `end()` — so a reload, a closed tab or a backgrounded webview\n * during a session left auto-speak switched ON for the user permanently, in\n * normal typed chat, with the toggle showing a state they never chose. The\n * default was never wrong; the session was overwriting it.\n *\n * Session-scoped React state instead: it cannot outlive the page, so there is\n * nothing to restore and nothing to leak.\n */\n sessionSpeaking: boolean;\n setSessionSpeaking: (enabled: boolean) => void;\n /** Play a short sample in a named voice. No model call, no message, no tokens. */\n previewVoice: (voiceName: string) => void;\n}\n\nconst INERT_SPEECH: AssistantSpeechContextValue = {\n isSupported: false,\n availability: 'unsupported',\n isBlocked: true,\n disabledReason: null,\n blockedFor: () => null,\n voiceChoices: [],\n activeVoiceName: null,\n preferredVoiceName: null,\n setVoice: () => {},\n speakingMessageId: null,\n isSpeaking: () => false,\n toggle: () => {},\n stop: () => {},\n autoSpeakEnabled: false,\n setAutoSpeak: () => {},\n sessionSpeaking: false,\n setSessionSpeaking: () => {},\n previewVoice: () => {},\n};\n\nconst AssistantSpeechContext = createContext<AssistantSpeechContextValue>(INERT_SPEECH);\n\nexport function useAssistantSpeech(): AssistantSpeechContextValue {\n return useContext(AssistantSpeechContext);\n}\n\ninterface Props {\n children: ReactNode;\n /** Panel visibility. Hiding the panel stops the voice. */\n visible?: boolean;\n /**\n * Injectable for tests and local experiments. The default routes between the\n * device engine and the hosted one; with hosted TTS unconfigured it IS the\n * device engine, unchanged.\n */\n engine?: SpeechEngine;\n}\n\nexport const AssistantSpeechProvider: FC<Props> = ({ children, visible = true, engine = getSpeechEngine() }) => {\n const tr = useTr();\n const { locale } = useI18n();\n const [playback, dispatch] = useReducer(speechPlaybackReducer, IDLE_PLAYBACK);\n const [voices, setVoices] = useState<SpeechVoiceLike[]>(() => engine.listVoices());\n /**\n * True once we have waited out the voice list and it was still empty.\n *\n * Turns an indefinite `pending` into a terminal `no-voices`, which is what\n * lets the control be disabled with a reason instead of silently doing\n * nothing on every press.\n */\n const [voiceProbeSettled, setVoiceProbeSettled] = useState(false);\n /**\n * Every message we have refused, and why — keyed by id (see `blockedFor`).\n *\n * A single record could only describe one refusal: refusing a second reply\n * silently re-enabled the first, whose voice was still just as missing, so\n * pressing the buttons walked the disabled state around the transcript.\n */\n const [unspeakable, setUnspeakable] = useState<ReadonlyMap<string, string>>(() => new Map());\n const requestRef = useRef(0);\n /** Cancels a playback that is waiting for the engine's voice list, if any. */\n const pendingRef = useRef<(() => void) | null>(null);\n const speakWithRef = useRef<\n (messageId: string, text: string, voices: readonly SpeechVoiceLike[], speechLocale: string) => void\n >(() => {});\n\n const cancelPending = useCallback(() => {\n pendingRef.current?.();\n pendingRef.current = null;\n }, []);\n\n const autoSpeakEnabled = useAssistantStore((state) => state.autoSpeakEnabled);\n const setAutoSpeak = useAssistantStore((state) => state.setAutoSpeak);\n // Not in the store on purpose — see `sessionSpeaking` on the context type.\n const [sessionSpeaking, setSessionSpeaking] = useState(false);\n const activeConversationId = useAssistantStore((state) => state.activeConversationId);\n\n const isSupported = useMemo(() => engine.isSupported(), [engine]);\n\n // getVoices() is empty on the first call in Chrome and only fills in when\n // 'voiceschanged' fires; Safari populates it synchronously and may never fire\n // the event. Read eagerly AND subscribe, so both engines end up correct.\n useEffect(() => {\n if (!isSupported) return;\n const sync = () => {\n setVoices(engine.listVoices());\n // Every recorded refusal was \"no voice for this language\". A new voice\n // list may well have supplied one — most likely because the user just\n // followed our instructions and installed it. Keeping the refusals would\n // leave those buttons disabled with no way back except a reload.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n sync();\n return engine.subscribeVoices(sync);\n }, [engine, isSupported]);\n\n // The language being SPOKEN ALOUD — which is the language of the reply, not\n // of the input and not of the interface. The two were one field until the\n // reply language was split out (BOFF-7108).\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const replyLanguage = useAssistantStore((state) => state.replyLanguage);\n const preferredVoices = useAssistantStore((state) => state.preferredVoices);\n const setPreferredVoice = useAssistantStore((state) => state.setPreferredVoice);\n const spokenLanguage = useMemo(\n // ★ The REPLY language, not the input. This is the language of the text\n // being spoken, so wiring it to the input would give a Tamil voice reading\n // an English answer the moment the two are set differently — the single\n // worst outcome available here, and the reason they were split at all.\n () => resolveLanguagePair(assistantLanguage, replyLanguage, locale).reply,\n [assistantLanguage, replyLanguage, locale]\n );\n const spokenLocale = spokenLanguage.code;\n\n /**\n * BCP-47 tag to ask the engine for, given a resolved language CODE.\n *\n * Resolved through the catalogue for ANY known code, not merely the currently\n * selected one — a historical Bengali reply must still get `bn-IN` after the\n * user switches to Tamil, or with both `bn-IN` and `bn-BD` installed the\n * engine's own order decides, and picks the wrong country.\n *\n * Falls back to the generic table for codes the catalogue does not carry.\n */\n const tagFor = useCallback((code: string) => findAssistantLanguage(code)?.tag ?? speechLangForLocale(code), []);\n\n /** Speaking rate for a resolved language code — see `AssistantLanguage.rate`. */\n const rateFor = useCallback((code: string) => findAssistantLanguage(code)?.rate ?? DEFAULT_SPEECH_RATE, []);\n\n const availability = useMemo(\n () => voiceAvailability(isSupported, voices, spokenLanguage.tag, voiceProbeSettled),\n [isSupported, voices, spokenLanguage, voiceProbeSettled]\n );\n\n // Spoken placeholders follow the app locale like the rest of the copy; the\n // transformation itself stays a pure function by taking them as arguments.\n const labels = useMemo<SpeakableLabels>(\n () => ({\n codeBlock: tr('healthybowl.assistant.speech.codeBlock', 'Code block'),\n image: tr('healthybowl.assistant.speech.image', 'image'),\n link: tr('healthybowl.assistant.speech.link', 'link'),\n largeTable: tr('healthybowl.assistant.speech.largeTable', 'Table with {{rows}} rows and {{columns}} columns'),\n truncated: tr('healthybowl.assistant.speech.truncated', 'The rest of this message is not read aloud'),\n nestedItem: tr('healthybowl.assistant.speech.nestedItem', 'Sub-item {{ordinal}}'),\n emailAt: tr('healthybowl.assistant.speech.emailAt', 'at'),\n emailDot: tr('healthybowl.assistant.speech.emailDot', 'dot'),\n }),\n [tr]\n );\n\n const stop = useCallback(() => {\n cancelPending();\n engine.cancel();\n dispatch({ type: 'stop' });\n }, [cancelPending, engine]);\n\n /**\n * Audition a voice — no model call, no message, no tokens.\n *\n * ★ Speaks through the engine DIRECTLY rather than through `speakWith`. That\n * path is built around a message: it resolves the reply's language, records\n * per-message \"cannot speak this\" state, and drives `speakingMessageId` so a\n * Listen button can light up. A preview has no message, so borrowing it would\n * mean inventing a fake id and then teaching every consumer to ignore it.\n *\n * Consequently it deliberately does NOT touch playback state: auditioning a\n * voice must not make a Listen button in the thread appear to be playing.\n *\n * Speaks the sample in the language being spoken, not the interface language —\n * the listener is judging how this voice reads THAT language.\n */\n const previewVoice = useCallback(\n (voiceName: string) => {\n const voice = engine.listVoices().find((candidate) => candidate.name === voiceName) ?? null;\n // An unknown name means the list changed under us (a download finished, a\n // profile switched). Silence is the right answer — better than falling\n // back to some other voice and auditioning the wrong one.\n if (!voice) return;\n // Whatever is speaking now is not what the user asked to hear.\n stop();\n engine.speak([voicePreviewText(spokenLocale)], { voice, lang: tagFor(spokenLocale) });\n },\n [engine, spokenLocale, stop, tagFor]\n );\n\n const blockedFor = useCallback((messageId: string) => unspeakable.get(messageId) ?? null, [unspeakable]);\n\n /**\n * Hold one playback until the engine publishes its voice list.\n *\n * Bounded: on timeout we take one last look and decide with whatever is\n * there, so an engine that never fires `voiceschanged` costs a two-second\n * wait rather than a control that is disabled forever. Nothing is spoken from\n * here unless a list actually arrives — an empty list means the engine would\n * pick its own default voice, which is the cross-language read this feature\n * promises never to do.\n */\n const waitForVoices = useCallback(\n (messageId: string, text: string, speechLocale: string) => {\n cancelPending();\n\n let settled = false;\n let unsubscribe = () => {};\n const finish = (available: SpeechVoiceLike[]) => {\n if (settled) return;\n settled = true;\n pendingRef.current = null;\n clearTimeout(timer);\n unsubscribe();\n if (available.length === 0) {\n // We waited and looked again: this device has no voices at all.\n // Record it so `availability` becomes `no-voices` and the control\n // explains itself, instead of returning silently every press.\n setVoiceProbeSettled(true);\n return;\n }\n setVoices(available);\n speakWithRef.current(messageId, text, available, speechLocale);\n };\n\n const timer = setTimeout(() => finish(engine.listVoices()), VOICE_LIST_TIMEOUT_MS);\n unsubscribe = engine.subscribeVoices(() => finish(engine.listVoices()));\n\n pendingRef.current = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n unsubscribe();\n pendingRef.current = null;\n };\n },\n [cancelPending, engine]\n );\n\n /**\n * Speak text against a KNOWN voice list.\n *\n * Every playback path funnels through here — the per-message button, the\n * header toggle's auto-speak, the store subscription — so the language gate\n * cannot be bypassed by any of them. Reading a Tamil reply with an English\n * voice is confident nonsense; it has to be impossible, not merely unlikely.\n */\n const speakWith = useCallback(\n (messageId: string, text: string, available: readonly SpeechVoiceLike[], speechLocale: string) => {\n let known = available;\n\n // Chrome answers the FIRST getVoices() with [] and fills the list in\n // asynchronously. One more synchronous read usually settles it.\n if (known.length === 0) {\n const refreshed = engine.listVoices();\n if (refreshed.length > 0) {\n known = refreshed;\n setVoices(refreshed);\n }\n }\n\n const speechLang = tagFor(speechLocale);\n\n const gate = speechGate(voiceAvailability(true, known, speechLocale, voiceProbeSettled));\n if (gate === 'block') {\n // Recorded for THIS message, always. Availability is resolved per reply\n // now, so a global \"your language has no voice\" cannot stand in for it:\n // the language the user chose to converse in says nothing about the one\n // this particular reply came back in.\n const reason = tr(\n 'healthybowl.assistant.speech.noVoiceForReply',\n 'This reply is in {{language}}, and no {{language}} voice is installed on this device.',\n { language: languageDisplayName(speechLang, locale) }\n );\n setUnspeakable((current) => new Map(current).set(messageId, reason));\n return;\n }\n if (gate === 'wait-for-voices') {\n waitForVoices(messageId, text, speechLocale);\n return;\n }\n\n setUnspeakable((current) => {\n if (!current.has(messageId)) return current;\n const next = new Map(current);\n next.delete(messageId);\n return next;\n });\n\n const requestId = requestRef.current + 1;\n requestRef.current = requestId;\n dispatch({ type: 'start', messageId, requestId });\n\n engine.speak(\n chunkForSpeech(text),\n // The TAG, not the code — so exact regional matching gets its chance\n // before the same-language fallback. `rate` had never been passed at\n // all, so every reply was read at the engine default.\n {\n voice: selectVoiceForLocale(known, speechLang, preferredVoices[speechLocale]),\n lang: speechLang,\n rate: rateFor(speechLocale),\n },\n {\n onEnd: () => dispatch({ type: 'finished', requestId }),\n // Includes the 'cancelled' every queued utterance reports when we\n // pre-empt a batch; the request-id guard drops those as stale.\n onError: () => dispatch({ type: 'failed', requestId }),\n }\n );\n },\n [engine, locale, preferredVoices, rateFor, tagFor, tr, voiceProbeSettled, waitForVoices]\n );\n\n // `waitForVoices` resumes through this ref, so the two do not become a\n // circular hook dependency.\n useEffect(() => {\n speakWithRef.current = speakWith;\n }, [speakWith]);\n\n const speak = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (!isSupported) return;\n\n // Resolve the reply's language BEFORE building the spoken text, because\n // the stand-in words must be in that language. Detection deliberately runs\n // on a SILENT_LABELS pass — our own words must not vote on which language\n // the reply is in — so it does not depend on the labels chosen here.\n const replyLocale = resolveSpeechLocale(\n toSpeakableText(markdown, { labels: SILENT_LABELS }),\n turnLocale ?? spokenLocale\n );\n\n // ★ Labels in the REPLY's language, not the interface's. An English\n // interface reading a Tamil answer used to say \"Code block\" and \"image\" in\n // English, mid-Tamil-sentence — the same defect the email `at`/`dot` fix\n // addressed and did not generalise.\n const text = toSpeakableText(markdown, { labels: speechLabelsFor(replyLocale, labels) });\n if (!text) return;\n\n // Detect on the text that will actually be SPOKEN, with our own words\n // removed — neither the raw markdown nor the finished transformation.\n //\n // The transformation injects app-locale placeholders (\"Code block\"), which\n // let English chrome outvote short non-Latin prose. The raw markdown keeps\n // fenced code, whose Latin identifiers do the same thing — and that code is\n // never spoken at all. Running the same transformation with EMPTY labels\n // strips the unspoken constructs while contributing no words of its own,\n // which is exactly the denominator the decision needs.\n // The turn's OWN language first — the preference is only a stand-in for\n // replies that predate it. Resolved above, and reused rather than\n // recomputed.\n speakWith(messageId, text, voices, replyLocale);\n },\n [isSupported, labels, spokenLocale, speakWith, voices]\n );\n\n const toggle = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (isSpeakingMessage(playback, messageId)) {\n stop();\n return;\n }\n speak(messageId, markdown, turnLocale);\n },\n [playback, speak, stop]\n );\n\n // ── Never leave a voice talking to an empty room ─────────────────────────\n useEffect(() => {\n if (!visible) stop();\n }, [visible, stop]);\n\n useEffect(() => {\n // Switching (or creating) a conversation abandons the reply being read —\n // and the refusal explained a message that is no longer on screen.\n stop();\n setUnspeakable(new Map());\n }, [activeConversationId, stop]);\n\n useEffect(() => {\n // Every refusal was decided against the locale in force at the time, which\n // is what a Latin-script reply falls back to. Change the locale and those\n // verdicts may simply be wrong — an English reply refused on a\n // Spanish-only device would stay disabled forever after switching the UI to\n // Spanish, with the voice that could read it already installed.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n // And stop anything mid-sentence. The new language can make this message\n // unspeakable, which disables its button — leaving it reading \"Stop\" with no\n // way to actually stop, short of closing the panel.\n stop();\n }, [spokenLocale, stop]);\n\n useEffect(() => {\n return () => {\n pendingRef.current?.();\n pendingRef.current = null;\n engine.cancel();\n };\n }, [engine]);\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n // Chrome carries speech across a same-tab navigation and a bfcache restore\n // would otherwise come back mid-sentence.\n const handlePageHide = () => engine.cancel();\n window.addEventListener('pagehide', handlePageHide);\n return () => window.removeEventListener('pagehide', handlePageHide);\n }, [engine]);\n\n // ── One timeout is not a life sentence ───────────────────────────────────\n //\n // `no-voices` disables the control, and a disabled control can never reach\n // `speakWith` — the only path that re-reads `engine.listVoices()`. So without\n // this, a user who follows our own advice, leaves to install a voice and comes\n // back stays blocked until a reload: we would be telling them how to fix it\n // and then refusing to notice that they had.\n //\n // Returning to the tab is exactly when that happens, and it costs one\n // synchronous read of an already-populated list.\n useEffect(() => {\n if (typeof document === 'undefined' || !isSupported) return;\n const reprobe = () => {\n if (document.visibilityState !== 'visible') return;\n // Adopt the list UNCONDITIONALLY, including an empty one. Keeping the old\n // cache on an empty read means a user who uninstalled their last voice\n // stays `ready`, and playback then hands the engine a voice object that no\n // longer exists instead of explaining the problem.\n //\n // Safe to accept an empty read here precisely because the probe verdict is\n // cleared on the next line: empty + unsettled is `pending`, which leaves\n // the control ENABLED and defers the real decision to the next press.\n const available = engine.listVoices();\n // A Listen press may still be inside its two-second wait. Adopting voices\n // here flips the control to `ready`, so the user can press again and start\n // playback — and then the original timer fires, calls back into\n // `speakWith` for the same message, and the engine cancels and restarts it\n // mid-sentence. Retire the waiter as part of adopting the list.\n if (available.length > 0) cancelPending();\n setVoices(available);\n setVoiceProbeSettled(false);\n // Same reason the `voiceschanged` path clears them: every refusal meant\n // \"no voice for this language\", and this is the moment a user who went\n // away to install one comes back. `subscribeVoices` does not fire on an\n // eventless engine, which is precisely why this re-probe exists — so it\n // has to expire the refusals too.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n document.addEventListener('visibilitychange', reprobe);\n window.addEventListener('focus', reprobe);\n return () => {\n document.removeEventListener('visibilitychange', reprobe);\n window.removeEventListener('focus', reprobe);\n };\n }, [cancelPending, engine, isSupported]);\n\n // ── Opt-in auto-speak ────────────────────────────────────────────────────\n const speakRef = useRef(speak);\n useEffect(() => {\n speakRef.current = speak;\n }, [speak]);\n\n useEffect(() => {\n // `isBlocked` is the same gate the per-message button uses. Without it the\n // subscription fires on a device with no voice for the app language and the\n // engine reads a Tamil reply in English — the one thing this feature says\n // it will never do. `pending` is allowed through because `speakWith` waits\n // for the list before deciding.\n // NOT gated on `isSpeechBlocked(availability)` any more: that is the APP\n // language's availability, and it would suppress auto-speak for a reply in\n // a language this device CAN speak. `speakWith` resolves the reply's own\n // language and refuses safely there, which is the only place that can know.\n // Either the user's own preference, or a live voice session — which speaks\n // by definition and must not have to change that preference to do it.\n if ((!autoSpeakEnabled && !sessionSpeaking) || !visible || !isSupported) return;\n\n // Deliberately a store subscription keyed on the processing TRANSITION\n // rather than an effect over the message list: it fires only on the\n // in-flight → complete edge of the active conversation, so mounting the\n // panel, loading history or switching chats can never start talking.\n return useAssistantStore.subscribe((next, previous) => {\n const conversationId = next.activeConversationId;\n if (!conversationId || conversationId !== previous.activeConversationId) return;\n\n const current = next.processingByConversationId[conversationId];\n const before = previous.processingByConversationId[conversationId];\n if (current?.status !== 'complete' || !isTurnInFlight(before?.status)) return;\n\n const messageId = current.messageId ?? before?.messageId ?? null;\n if (!messageId) return;\n\n const message = next.conversations\n .find((conversation) => conversation.id === conversationId)\n ?.messages.find((candidate) => candidate.id === messageId);\n if (!message || message.role !== 'assistant') return;\n\n // ★ Speak a turn only if it belongs to the surface currently doing the\n // speaking. This subscription IS the live session's audio path —\n // `useVoiceSession` never calls `speak` itself, it flips `sessionSpeaking`\n // and lets this fire — and it had no channel check, so a TYPED reply\n // completing mid-session was read aloud as the answer to a spoken\n // question. Reachable with no typing at all: a host page queues work\n // through `pendingPrompt`, which is store-driven and fires past the voice\n // overlay.\n //\n // The mirror case matters too: after End, a reply still in flight must not\n // be spoken by ordinary auto-read — the user closed the conversation.\n if (isVoiceTurn(message) !== sessionSpeaking) return;\n\n // Same split the transcript uses: speak the prose, not the tool log.\n const { text } = parseToolActivity(message.content);\n if (!text.trim()) return;\n\n speakRef.current(messageId, text, (message.metadata as { lang?: string } | undefined)?.lang);\n });\n }, [autoSpeakEnabled, sessionSpeaking, isSupported, visible]);\n\n // The candidates for the language the user SPEAKS — the picker is a setting,\n // so it must not follow whatever language the last reply happened to be in.\n const voiceChoices = useMemo(() => voicesForLocale(voices, spokenLanguage.tag), [voices, spokenLanguage]);\n const activeVoice = useMemo(\n () => selectVoiceForLocale(voices, spokenLanguage.tag, preferredVoices[spokenLocale]),\n [voices, spokenLanguage, preferredVoices, spokenLocale]\n );\n\n const value = useMemo<AssistantSpeechContextValue>(\n () => ({\n isSupported,\n availability,\n // ONLY `no-voices` — a device with no voices at all can never speak\n // anything. `missing-voice` means the APP language has none, which says\n // nothing about the language a given reply came back in; that case is\n // resolved per message by `blockedFor`.\n isBlocked: availability === 'no-voices',\n // Both blocked states are the user's device, not our bug — so the copy\n // names the language and says where to fix it. \"Nothing happened\" was\n // the old behaviour and it read as a broken feature.\n disabledReason:\n availability === 'no-voices'\n ? tr(\n 'healthybowl.assistant.speech.noVoicesOnDevice',\n 'This device has no speech voices installed. Add one in your device speech or accessibility settings.'\n )\n : null,\n blockedFor,\n voiceChoices,\n activeVoiceName: activeVoice?.name ?? null,\n preferredVoiceName: preferredVoices[spokenLocale] ?? null,\n setVoice: (voiceName: string | null) => setPreferredVoice(spokenLocale, voiceName),\n speakingMessageId: playback.status === 'speaking' ? playback.messageId : null,\n isSpeaking: (messageId: string) => isSpeakingMessage(playback, messageId),\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n setSessionSpeaking,\n previewVoice,\n }),\n [\n isSupported,\n availability,\n blockedFor,\n voiceChoices,\n activeVoice,\n preferredVoices,\n setPreferredVoice,\n spokenLocale,\n playback,\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n previewVoice,\n tr,\n ]\n );\n\n return <AssistantSpeechContext.Provider value={value}>{children}</AssistantSpeechContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsDA,IAAM,KAAiC;CACrC,WAAW;CACX,OAAO;CACP,MAAM;CACN,YAAY;CACZ,WAAW;CACX,SAAS;CACT,UAAU;CACV,YAAY;AACd,GAoHM,IAAyB,GAA2C;CApBxE,aAAa;CACb,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assistant/voice/AssistantVoiceSession.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type FC } from 'react';\nimport { Maximize2, Minimize2, ScrollText, X } from 'lucide-react';\nimport { AssistantVoiceOrb } from './AssistantVoiceOrb';\nimport { VoiceStage } from './VoiceStage';\nimport { VoiceMiniController } from './VoiceMiniController';\nimport { VoiceTranscriptDrawer } from './VoiceTranscriptDrawer';\nimport { voiceStageState, micIsInterrupt } from '../../../utils/voiceStageState';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { spokenSoFar, type VoiceSessionSnapshot } from '../../../utils/voiceSession';\nimport type { VoiceSessionError } from '../../../utils/voiceSession';\nimport type { VoiceSessionNotice } from '../../../hooks/useVoiceSession';\n\n/** How much room the voice session takes: a strip, the panel, or the screen. */\nexport type VoiceView = 'mini' | 'panel' | 'full';\n\ninterface Props {\n session: VoiceSessionSnapshot;\n /** Recent exchanges, oldest first — the running conversation. */\n turns?: ReadonlyArray<{ id: string; role: 'user' | 'assistant'; text: string }>;\n /** Cut the assistant off mid-reply. */\n onInterrupt?: () => void;\n /** A recoverable problem to surface. Null when the microphone is healthy. */\n notice?: VoiceSessionNotice | null;\n /** The assistant's last reply, captioned while it is spoken. */\n spoken: string | null;\n onToggleMute: () => void;\n onEnd: () => void;\n /** Is the recogniser actually running? Distinguishes CONNECTING from LISTENING. */\n capturing?: boolean;\n /** The user has cut the assistant off and capture has not resumed yet. */\n interrupting?: boolean;\n /** Quiet has fallen and the two-second correction window is running. */\n awaitingEndpoint?: boolean;\n}\n\n/**\n * Full-screen voice conversation (BOFF-7120).\n *\n * ★ **Voice only, by explicit product decision.** The reference (Gemini Live)\n * also offers camera and screen sharing; those are deliberately absent here.\n * Attaching images is a separate, existing capability of the assistant and\n * stays in the composer, and screen sharing could not work on the primary\n * device anyway — `getDisplayMedia` is unsupported by every iOS browser, so\n * that control would be dead on an iPhone.\n *\n * The controls are therefore the two that a voice conversation actually needs:\n * mute, and end. Anything else would be a button the user has to think about\n * while talking.\n *\n * This component is presentational: every transition is owned by\n * `voiceSessionReducer`, which is pure and tested. That split exists because\n * this file cannot be tested at all in this repo — vitest runs in `node` with\n * no DOM and no audio.\n */\nexport const AssistantVoiceSession: FC<Props> = ({\n session,\n turns = [],\n notice = null,\n spoken,\n onInterrupt,\n onToggleMute,\n onEnd,\n capturing = true,\n interrupting = false,\n awaitingEndpoint = false,\n}) => {\n const tr = useTr();\n const { phase, muted, error } = session;\n const endRef = useRef<HTMLButtonElement>(null);\n const dialogRef = useRef<HTMLDivElement>(null);\n /**\n * Docked inside the assistant panel by default; full-screen only on request.\n *\n * A voice conversation is usually a glance-and-listen thing, so taking over\n * the whole screen for it is the wrong default — the user loses the page they\n * were asking about. Expanding is opt-in and per-session: reopening starts\n * docked again, which is the behaviour that matches \"default should be the\n * same size as the assistant\".\n */\n /**\n * ★ THREE sizes, not two.\n *\n * The compact controller was added so voice stops taking over the panel — but\n * making it the only docked size removed the in-panel stage that existed\n * before, which is a genuinely useful middle: big enough to read a reply,\n * without losing the page behind it.\n *\n * mini — a strip at the bottom; the assistant panel stays visible\n * panel — fills the assistant panel (what \"docked\" used to mean)\n * full — full screen\n *\n * One button steps mini → panel → full and wraps, with the label always\n * naming where it goes next, so a single control stays predictable.\n */\n const [view, setView] = useState<VoiceView>('mini');\n const expanded = view === 'full';\n const mini = view === 'mini';\n const nextView: VoiceView = view === 'mini' ? 'panel' : view === 'panel' ? 'full' : 'mini';\n /** History is secondary: the stage shows now, this shows the session. */\n const [transcriptOpen, setTranscriptOpen] = useState(false);\n\n // A full-screen `aria-modal` overlay that cannot be dismissed from the\n // keyboard is a trap. Escape ends the session, and focus starts on End so a\n // keyboard or screen-reader user lands somewhere useful rather than behind\n // the overlay.\n // Focus lands on End ONCE, on open. Keeping this in the keydown effect below\n // meant every expand/collapse re-ran it and silently stole focus from the\n // button just pressed — a Space or Enter a beat later would then end the\n // session instead of toggling the size again.\n useEffect(() => {\n endRef.current?.focus();\n }, []);\n\n useEffect(() => {\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n // ★ Escape closes the drawer first. Ending the whole conversation\n // because someone dismissed a panel would be a surprising amount of\n // destruction for one keypress.\n if (transcriptOpen) {\n setTranscriptOpen(false);\n return;\n }\n onEnd();\n return;\n }\n // Trapping focus is only correct when the overlay actually covers\n // everything. Docked, it sits inside the panel and the rest of the page\n // is legitimately reachable, so trapping there would be the bug rather\n // than the fix.\n if (event.key !== 'Tab' || !expanded) return;\n // `aria-modal` only TELLS assistive technology this is modal; it does not\n // make it so. Without this, Tab walks straight out of the overlay into the\n // page behind it, which is still fully interactive underneath — a\n // keyboard user ends up operating a screen they cannot see.\n // ★ Scope the trap to what is actually on screen. With the transcript\n // drawer open, a flat `button` query also collects the controls it covers,\n // so Tab walked into buttons the user could not see — the same class of\n // bug the trap exists to prevent.\n const scope = transcriptOpen\n ? dialogRef.current?.querySelector<HTMLElement>('[data-testid=\"assistant-voice-transcript\"]')\n : dialogRef.current;\n const focusable = scope?.querySelectorAll<HTMLElement>('button:not([disabled])');\n if (!focusable || focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (!first || !last) return;\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n window.addEventListener('keydown', onKeyDown);\n return () => window.removeEventListener('keydown', onKeyDown);\n }, [onEnd, expanded, transcriptOpen]);\n\n // While speaking, the caption shows the REPLY; otherwise what we have heard.\n // Showing the stale transcript under the assistant's own voice reads as a\n // mis-transcription of the assistant, which is worse than showing nothing.\n // A notice competes with the error for the same slot; the error owns the\n // stage, so they are never both shown.\n const showNotice = notice !== null && error === null;\n\n const heard = spokenSoFar(session);\n\n // ★ ONE state, derived. The reducer's phase cannot tell \"listening\" from\n // \"the microphone has not started yet\", and the old overlay rendered every\n // signal at once — status, warning, transcript, caption and orb together.\n // ★ Both signals were accepted by `voiceStageState` and passed by nobody, so\n // `endpoint-grace` and `interrupting` were unreachable branches.\n const stage = voiceStageState({ snapshot: session, capturing, interrupting, awaitingEndpoint });\n\n /**\n * The label for the STAGE, not for the phase.\n *\n * ★ This used to read `phase`, which is why three derived stages were\n * invisible even once they were reachable: `connecting`, `endpoint-grace` and\n * `interrupting` are all `phase === 'listening'` underneath, so every one of\n * them said \"Listening…\". The stage exists precisely because the phase cannot\n * make these distinctions — deriving the caption from the phase threw that\n * away again, and told the user we were listening before the recogniser had\n * started, the exact lie `voiceStageState` was written to stop.\n */\n const stageText = (() => {\n switch (stage) {\n case 'connecting':\n return tr('healthybowl.assistant.voiceSession.connecting', 'Starting the microphone…');\n case 'endpoint-grace':\n // Reads as an invitation, not a countdown: the window exists so the\n // user can still correct themselves, and hurrying them defeats it.\n return tr('healthybowl.assistant.voiceSession.endpointGrace', 'Still listening — take your time');\n case 'interrupting':\n return tr('healthybowl.assistant.voiceSession.interrupting', 'Stopped — go ahead');\n case 'thinking':\n return tr('healthybowl.assistant.voiceSession.thinking', 'Thinking…');\n case 'speaking':\n return tr('healthybowl.assistant.voiceSession.speaking', 'Speaking — tap to stop');\n case 'mic-error':\n case 'ended':\n // Owned by the error branch of the stage, which gets it to itself.\n return '';\n case 'listening':\n return muted\n ? tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')\n : tr('healthybowl.assistant.voiceSession.listening', 'Listening…');\n default: {\n // ★ Exhaustive on purpose, matching `errorMessage` and `noticeMessage`\n // below. A stage with no copy is the exact bug this change fixes, so a\n // new one without a label must fail the BUILD rather than silently\n // inherit \"Listening…\" the way three of them already did.\n const unhandled: never = stage;\n return unhandled;\n }\n }\n })();\n\n // Muted is reported ALONGSIDE the stage, not instead of it: the assistant may\n // still be speaking with the microphone off, and saying only \"Microphone off\"\n // would misreport that.\n //\n // ★ Gated on the STAGE, not the phase. `connecting`, `endpoint-grace` and\n // `interrupting` are all `phase === 'listening'` underneath, so a phase test\n // dropped the suffix on exactly the three stages this change introduced —\n // leaving \"Stopped — go ahead\" inviting someone to speak into a muted\n // microphone. The `!== ''` guard keeps ended/mic-error from rendering a bare\n // \" · Microphone off\".\n //\n // ★ No `error !== null` arm: `stageText` is already '' for `mic-error`, and\n // the message itself belongs to the stage's alert element. Testing the error\n // here printed the whole sentence TWICE on the one screen this change exists\n // to make visible — truncated in the status line, repeated below it, and\n // announced twice by a screen reader.\n const status =\n muted && stage !== 'listening' && stageText !== ''\n ? `${stageText} · ${tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')}`\n : stageText;\n\n return (\n <div\n ref={dialogRef}\n className={`flex flex-col items-center justify-between bg-bg-sunken ${\n view === 'full'\n ? // ★ Below the app header, not behind it. The header is `z-[100]` and\n // this overlay was `z-[60]` at `inset-0`, so the top 56px sat behind\n // it — and the End button did not merely LOOK hidden, it was\n // unclickable (`elementFromPoint` returned the header). Starting at\n // `top-14` means nothing is ever behind the header, and the header\n // stays usable for orientation.\n 'fixed inset-x-0 bottom-0 top-14 z-[60] px-6 py-8'\n : view === 'panel'\n ? // The in-panel stage: covers the assistant panel, keeps the page.\n 'absolute inset-0 z-20 px-4 py-6'\n : // A strip at the bottom, ~180px, so the panel behind stays visible.\n 'absolute inset-x-0 bottom-0 z-20 h-[11.25rem] border-t border-border-subtle px-3 py-3 shadow-lg'\n }`}\n role=\"dialog\"\n // Only modal when it really is: docked, the page behind stays usable.\n // `undefined` rather than `false` — the ARIA default is already false, and\n // some older assistive technology treats an explicit \"false\" on a dialog\n // as still modal.\n aria-modal={expanded || undefined}\n aria-label={tr('healthybowl.assistant.voiceSession.title', 'Voice conversation')}\n data-testid=\"assistant-voice-session\"\n >\n {/* End sits top-right and expand bottom-left, out of the centre column.\n Absolute rather than part of the flow so the pill stays optically\n centred at both sizes — the overlay is already a positioning context\n (`fixed` when expanded, `absolute` when docked). */}\n <button\n ref={endRef}\n type=\"button\"\n onClick={onEnd}\n // ★ Height + horizontal padding, never `size-*`. A fixed square cannot\n // grow to fit a word, so a label dropped into one spills outside its own\n // rounded border. The mini strip keeps the square: its transcript toggle\n // sits 4px away at `right-11`, and a wider button there would grow\n // leftward underneath it — which is precisely the defect the previous\n // commit on this file fixed (\"the close button was unclickable\").\n className={`absolute ${\n expanded\n ? 'right-6 top-6 h-14 gap-2 px-5 text-base'\n : mini\n ? 'right-2 top-2 size-8'\n : 'right-3 top-3 h-11 gap-2 px-4 text-sm'\n } flex items-center justify-center rounded-full border border-border-default bg-bg-elevated text-text-secondary hover:bg-bg-sunken transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n // ★ Only when the label is INVISIBLE. With visible text the accessible\n // name comes from that text, which keeps WCAG 2.5.3 (Label in Name)\n // true by construction in every locale — including before `endShort` is\n // seeded. An aria-label here would instead pin a translated sentence\n // against an untranslated visible word, and speech-input users say the\n // word they can see.\n aria-label={mini ? tr('healthybowl.assistant.voiceSession.end', 'End the voice conversation') : undefined}\n data-testid=\"assistant-voice-end\"\n >\n <X className={expanded ? 'size-6' : mini ? 'size-4' : 'size-5'} aria-hidden=\"true\" />\n {/* The glyph alone said \"close\" only to people who already knew.\n ★ Bounded: the width is a TRANSLATED string while the layout around\n it is fixed pixels — \"Beenden\" and \"Terminer\" are ~2.4x \"End\". The\n cap turns a future overflow into an ellipsis rather than a control\n that creeps over its neighbour. */}\n {!mini ? (\n <span className=\"max-w-[7rem] truncate whitespace-nowrap font-medium\">\n {tr('healthybowl.assistant.voiceSession.endShort', 'End')}\n </span>\n ) : null}\n </button>\n\n {/* ★ The notice is CHROME, not conversation. It used to sit above the\n transcript in the same column as the reply, which is why a microphone\n warning read as part of what the assistant said. The status line moved\n into the stage, where it labels the state it belongs to. */}\n {/* ★ Cleared VERTICALLY, not horizontally. This div is a flex item of a\n `flex flex-col items-center` column, so it is SHRINK-TO-FIT: side\n padding does not reserve space beside the End button, it eats the\n text's own measure — symmetrically, for a control on one side only.\n Widening `px-14` to match a labelled button collapsed the microphone\n warning to a 78px, nine-line column on a phone and in the docked\n panel, because 78px is the min-content width of the longest word in it.\n\n Dropping below the button instead makes the clearance independent of\n both the container width and the label's length — which matters\n because that label is TRANSLATED (\"Beenden\", \"Terminer\") while these\n offsets are fixed pixels. End occupies y=24..80 expanded (top-6 +\n h-14) and y=12..56 docked (top-3 + h-11); the column's own padding\n already starts content at 32 / 24, so these add the rest plus 8px.\n\n ★ NOT true of `mini`, where End, transcript and expand are ALL in the\n top band and this stays `px-3`. A notice there can still be painted\n over by those opaque buttons. Pre-existing and left alone: the strip is\n 180px tall and buying 32px of top padding would squeeze the stage. */}\n <div\n className={`flex flex-col items-center ${\n mini\n ? 'px-3'\n : // ★ The reserve is applied ONLY when there is something to clear.\n // `padding` is not subject to `min-h`, so an unconditional `pt-14`\n // would stand a permanent 56px column above an empty div and take\n // that height out of the `flex-1` stage on every session — paying\n // the cost of a warning that is not there.\n `min-h-[1.5rem] ${showNotice ? (expanded ? 'pt-14' : 'pt-10') : ''}`\n }`}\n >\n {showNotice ? (\n <p className=\"max-w-xs text-center text-xs text-status-warning\" data-testid=\"assistant-voice-notice\">\n {noticeMessage(notice, tr)}\n </p>\n ) : null}\n </div>\n\n {/* ★ Two genuinely different surfaces, not one scaled. Expanded is a\n reading stage; docked is a controller. */}\n {(() => {\n const orb = (\n <AssistantVoiceOrb\n session={session}\n compact={mini}\n connecting={stage === 'connecting'}\n onPress={micIsInterrupt(stage) ? onInterrupt : onToggleMute}\n label={\n micIsInterrupt(stage)\n ? tr('healthybowl.assistant.voiceSession.interrupt', 'Stop the assistant and speak')\n : muted\n ? tr('healthybowl.assistant.voiceSession.unmute', 'Turn the microphone on')\n : tr('healthybowl.assistant.voiceSession.mute', 'Turn the microphone off')\n }\n />\n );\n const caption = micIsInterrupt(stage) ? spoken : heard || null;\n const errorText = error !== null ? errorMessage(error, tr) : null;\n return !mini ? (\n <VoiceStage\n state={stage}\n userCaption={heard || null}\n assistantCaption={spoken}\n // ★ `expanded` — the JSX shorthand — means `expanded={true}`, not\n // `expanded={expanded}`. This branch serves BOTH the docked panel and\n // full screen, so the panel was being styled as full screen: the\n // full-screen caption measure and clamp applied in a column far\n // too narrow for them, and VoiceCaption's non-expanded branch became\n // unreachable code. The variable it shadowed is right there on line 90.\n expanded={expanded}\n statusText={status}\n errorText={errorText}\n control={orb}\n />\n ) : (\n <VoiceMiniController\n state={stage}\n caption={caption}\n statusText={status}\n errorText={errorText}\n control={orb}\n />\n );\n })()}\n\n {transcriptOpen ? <VoiceTranscriptDrawer turns={turns} onClose={() => setTranscriptOpen(false)} /> : null}\n\n {/* History is SECONDARY — behind a button, never on the stage. */}\n <button\n type=\"button\"\n onClick={() => setTranscriptOpen((open) => !open)}\n className={`absolute ${expanded ? 'bottom-6 right-6 size-14' : mini ? 'right-11 top-2 size-8' : 'bottom-3 right-3 size-11'} flex items-center justify-center rounded-full bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n aria-pressed={transcriptOpen}\n aria-label={tr('healthybowl.assistant.voiceSession.transcript', 'Voice transcript')}\n data-testid=\"assistant-voice-transcript-toggle\"\n >\n <ScrollText className={expanded ? 'size-6' : mini ? 'size-4' : 'size-5'} />\n </button>\n\n <button\n type=\"button\"\n onClick={() => setView(nextView)}\n className={`absolute ${expanded ? 'bottom-6 left-6 size-14' : mini ? 'left-2 top-2 size-8' : 'bottom-3 left-3 size-11'} flex items-center justify-center rounded-full bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n // Not a toggle any more, so `aria-pressed` would be a lie. The label\n // names where the button GOES, which is what a stepping control needs.\n aria-label={\n nextView === 'panel'\n ? tr('healthybowl.assistant.voiceSession.expandPanel', 'Show the conversation in the panel')\n : nextView === 'full'\n ? tr('healthybowl.assistant.voiceSession.expand', 'Expand the conversation to full screen')\n : tr('healthybowl.assistant.voiceSession.collapse', 'Shrink to the compact controller')\n }\n data-testid=\"assistant-voice-expand\"\n >\n {expanded ? <Minimize2 className=\"size-5\" /> : <Maximize2 className={mini ? 'size-4' : 'size-5'} />}\n </button>\n </div>\n );\n};\n\n/**\n * Recoverable problems, shown WITHOUT ending the session.\n *\n * The bug these exist for: the overlay said \"Listening…\" while the recogniser\n * was dead, and nothing anywhere said otherwise.\n */\nfunction noticeMessage(notice: VoiceSessionNotice, tr: ReturnType<typeof useTr>): string {\n switch (notice) {\n case 'network':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNetwork',\n 'Speech recognition lost its connection. Check your network — it will retry.'\n );\n case 'not-capturing':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNotCapturing',\n 'The microphone did not start. Check that this site is allowed to use it, then try again.'\n );\n case 'recognition-failed':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeRecognitionFailed',\n 'Speech recognition stopped unexpectedly. It will retry — if it keeps happening, reload the page.'\n );\n case 'nothing-heard':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNothingHeard',\n 'Nothing heard yet. Check your microphone is not muted or in use by another app.'\n );\n default: {\n const unhandled: never = notice;\n return unhandled;\n }\n }\n}\n\n/**\n * Every failure is explained rather than silently closing the session.\n *\n * A session that just vanishes is the dead-button bug in another shape — the\n * exact defect BOFF-7106 had to fix on the per-message speak control.\n */\nfunction errorMessage(error: VoiceSessionError, tr: ReturnType<typeof useTr>): string {\n switch (error) {\n case 'mic-denied':\n return tr(\n 'healthybowl.assistant.voiceSession.micDenied',\n 'Microphone access is blocked. Allow it in your browser settings to talk.'\n );\n case 'no-speech-support':\n return tr(\n 'healthybowl.assistant.voiceSession.noSpeechSupport',\n 'This browser cannot listen. Try a different browser, or type instead.'\n );\n case 'no-voice-support':\n return tr(\n 'healthybowl.assistant.voiceSession.noVoiceSupport',\n 'This device has no voice that can speak this language.'\n );\n default: {\n // Exhaustive: adding a variant without copy becomes a build error rather\n // than a silently empty status line.\n const unhandled: never = error;\n return unhandled;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAsDA,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Ac,GAA4B,GAAsC;CACvF,QAAQ,GAAR;EACE,KAAK,WACH,OAAO,EACL,oDACA,6EACF;EACF,KAAK,iBACH,OAAO,EACL,yDACA,0FACF;EACF,KAAK,sBACH,OAAO,EACL,8DACA,kGACF;EACF,KAAK,iBACH,OAAO,EACL,yDACA,iFACF;EACF,SAEE,OAAO;CAEX;AACF;AAQA,SAAS,EAAa,GAA0B,GAAsC;CACpF,QAAQ,GAAR;EACE,KAAK,cACH,OAAO,EACL,gDACA,0EACF;EACF,KAAK,qBACH,OAAO,EACL,sDACA,uEACF;EACF,KAAK,oBACH,OAAO,EACL,qDACA,wDACF;EACF,SAIE,OAAO;CAEX;AACF"}
1
+ {"version":3,"file":"AssistantVoiceSession.js","names":[],"sources":["../../../../src/components/assistant/voice/AssistantVoiceSession.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type FC } from 'react';\nimport { Maximize2, Minimize2, ScrollText, X } from 'lucide-react';\nimport { AssistantVoiceOrb } from './AssistantVoiceOrb';\nimport { VoiceStage } from './VoiceStage';\nimport { VoiceMiniController } from './VoiceMiniController';\nimport { VoiceTranscriptDrawer } from './VoiceTranscriptDrawer';\nimport { voiceStageState, micIsInterrupt } from '../../../utils/voiceStageState';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { spokenSoFar, type VoiceSessionSnapshot } from '../../../utils/voiceSession';\nimport type { VoiceSessionError } from '../../../utils/voiceSession';\nimport type { VoiceSessionNotice } from '../../../hooks/useVoiceSession';\nimport type { VoiceTranscriptTurn } from '../../../utils/voiceTurnVisibility';\n\n/** How much room the voice session takes: a strip, the panel, or the screen. */\nexport type VoiceView = 'mini' | 'panel' | 'full';\n\ninterface Props {\n session: VoiceSessionSnapshot;\n /** Recent exchanges, oldest first — the running conversation. */\n turns?: ReadonlyArray<VoiceTranscriptTurn>;\n /** Cut the assistant off mid-reply. */\n onInterrupt?: () => void;\n /** A recoverable problem to surface. Null when the microphone is healthy. */\n notice?: VoiceSessionNotice | null;\n /** The assistant's last reply, captioned while it is spoken. */\n spoken: string | null;\n onToggleMute: () => void;\n onEnd: () => void;\n /** Is the recogniser actually running? Distinguishes CONNECTING from LISTENING. */\n capturing?: boolean;\n /** The user has cut the assistant off and capture has not resumed yet. */\n interrupting?: boolean;\n /** Quiet has fallen and the two-second correction window is running. */\n awaitingEndpoint?: boolean;\n}\n\n/**\n * Full-screen voice conversation (BOFF-7120).\n *\n * ★ **Voice only, by explicit product decision.** The reference (Gemini Live)\n * also offers camera and screen sharing; those are deliberately absent here.\n * Attaching images is a separate, existing capability of the assistant and\n * stays in the composer, and screen sharing could not work on the primary\n * device anyway — `getDisplayMedia` is unsupported by every iOS browser, so\n * that control would be dead on an iPhone.\n *\n * The controls are therefore the two that a voice conversation actually needs:\n * mute, and end. Anything else would be a button the user has to think about\n * while talking.\n *\n * This component is presentational: every transition is owned by\n * `voiceSessionReducer`, which is pure and tested. That split exists because\n * this file cannot be tested at all in this repo — vitest runs in `node` with\n * no DOM and no audio.\n */\nexport const AssistantVoiceSession: FC<Props> = ({\n session,\n turns = [],\n notice = null,\n spoken,\n onInterrupt,\n onToggleMute,\n onEnd,\n capturing = true,\n interrupting = false,\n awaitingEndpoint = false,\n}) => {\n const tr = useTr();\n const { phase, muted, error } = session;\n const endRef = useRef<HTMLButtonElement>(null);\n const dialogRef = useRef<HTMLDivElement>(null);\n /**\n * Docked inside the assistant panel by default; full-screen only on request.\n *\n * A voice conversation is usually a glance-and-listen thing, so taking over\n * the whole screen for it is the wrong default — the user loses the page they\n * were asking about. Expanding is opt-in and per-session: reopening starts\n * docked again, which is the behaviour that matches \"default should be the\n * same size as the assistant\".\n */\n /**\n * ★ THREE sizes, not two.\n *\n * The compact controller was added so voice stops taking over the panel — but\n * making it the only docked size removed the in-panel stage that existed\n * before, which is a genuinely useful middle: big enough to read a reply,\n * without losing the page behind it.\n *\n * mini — a strip at the bottom; the assistant panel stays visible\n * panel — fills the assistant panel (what \"docked\" used to mean)\n * full — full screen\n *\n * One button steps mini → panel → full and wraps, with the label always\n * naming where it goes next, so a single control stays predictable.\n */\n const [view, setView] = useState<VoiceView>('mini');\n const expanded = view === 'full';\n const mini = view === 'mini';\n const nextView: VoiceView = view === 'mini' ? 'panel' : view === 'panel' ? 'full' : 'mini';\n /** History is secondary: the stage shows now, this shows the session. */\n const [transcriptOpen, setTranscriptOpen] = useState(false);\n\n // A full-screen `aria-modal` overlay that cannot be dismissed from the\n // keyboard is a trap. Escape ends the session, and focus starts on End so a\n // keyboard or screen-reader user lands somewhere useful rather than behind\n // the overlay.\n // Focus lands on End ONCE, on open. Keeping this in the keydown effect below\n // meant every expand/collapse re-ran it and silently stole focus from the\n // button just pressed — a Space or Enter a beat later would then end the\n // session instead of toggling the size again.\n useEffect(() => {\n endRef.current?.focus();\n }, []);\n\n useEffect(() => {\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n // ★ Escape closes the drawer first. Ending the whole conversation\n // because someone dismissed a panel would be a surprising amount of\n // destruction for one keypress.\n if (transcriptOpen) {\n setTranscriptOpen(false);\n return;\n }\n onEnd();\n return;\n }\n // Trapping focus is only correct when the overlay actually covers\n // everything. Docked, it sits inside the panel and the rest of the page\n // is legitimately reachable, so trapping there would be the bug rather\n // than the fix.\n if (event.key !== 'Tab' || !expanded) return;\n // `aria-modal` only TELLS assistive technology this is modal; it does not\n // make it so. Without this, Tab walks straight out of the overlay into the\n // page behind it, which is still fully interactive underneath — a\n // keyboard user ends up operating a screen they cannot see.\n // ★ Scope the trap to what is actually on screen. With the transcript\n // drawer open, a flat `button` query also collects the controls it covers,\n // so Tab walked into buttons the user could not see — the same class of\n // bug the trap exists to prevent.\n const scope = transcriptOpen\n ? dialogRef.current?.querySelector<HTMLElement>('[data-testid=\"assistant-voice-transcript\"]')\n : dialogRef.current;\n const focusable = scope?.querySelectorAll<HTMLElement>('button:not([disabled])');\n if (!focusable || focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (!first || !last) return;\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n window.addEventListener('keydown', onKeyDown);\n return () => window.removeEventListener('keydown', onKeyDown);\n }, [onEnd, expanded, transcriptOpen]);\n\n // While speaking, the caption shows the REPLY; otherwise what we have heard.\n // Showing the stale transcript under the assistant's own voice reads as a\n // mis-transcription of the assistant, which is worse than showing nothing.\n // A notice competes with the error for the same slot; the error owns the\n // stage, so they are never both shown.\n const showNotice = notice !== null && error === null;\n\n const heard = spokenSoFar(session);\n\n // ★ ONE state, derived. The reducer's phase cannot tell \"listening\" from\n // \"the microphone has not started yet\", and the old overlay rendered every\n // signal at once — status, warning, transcript, caption and orb together.\n // ★ Both signals were accepted by `voiceStageState` and passed by nobody, so\n // `endpoint-grace` and `interrupting` were unreachable branches.\n const stage = voiceStageState({ snapshot: session, capturing, interrupting, awaitingEndpoint });\n\n /**\n * The label for the STAGE, not for the phase.\n *\n * ★ This used to read `phase`, which is why three derived stages were\n * invisible even once they were reachable: `connecting`, `endpoint-grace` and\n * `interrupting` are all `phase === 'listening'` underneath, so every one of\n * them said \"Listening…\". The stage exists precisely because the phase cannot\n * make these distinctions — deriving the caption from the phase threw that\n * away again, and told the user we were listening before the recogniser had\n * started, the exact lie `voiceStageState` was written to stop.\n */\n const stageText = (() => {\n switch (stage) {\n case 'connecting':\n return tr('healthybowl.assistant.voiceSession.connecting', 'Starting the microphone…');\n case 'endpoint-grace':\n // Reads as an invitation, not a countdown: the window exists so the\n // user can still correct themselves, and hurrying them defeats it.\n return tr('healthybowl.assistant.voiceSession.endpointGrace', 'Still listening — take your time');\n case 'interrupting':\n return tr('healthybowl.assistant.voiceSession.interrupting', 'Stopped — go ahead');\n case 'thinking':\n return tr('healthybowl.assistant.voiceSession.thinking', 'Thinking…');\n case 'speaking':\n return tr('healthybowl.assistant.voiceSession.speaking', 'Speaking — tap to stop');\n case 'mic-error':\n case 'ended':\n // Owned by the error branch of the stage, which gets it to itself.\n return '';\n case 'listening':\n return muted\n ? tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')\n : tr('healthybowl.assistant.voiceSession.listening', 'Listening…');\n default: {\n // ★ Exhaustive on purpose, matching `errorMessage` and `noticeMessage`\n // below. A stage with no copy is the exact bug this change fixes, so a\n // new one without a label must fail the BUILD rather than silently\n // inherit \"Listening…\" the way three of them already did.\n const unhandled: never = stage;\n return unhandled;\n }\n }\n })();\n\n // Muted is reported ALONGSIDE the stage, not instead of it: the assistant may\n // still be speaking with the microphone off, and saying only \"Microphone off\"\n // would misreport that.\n //\n // ★ Gated on the STAGE, not the phase. `connecting`, `endpoint-grace` and\n // `interrupting` are all `phase === 'listening'` underneath, so a phase test\n // dropped the suffix on exactly the three stages this change introduced —\n // leaving \"Stopped — go ahead\" inviting someone to speak into a muted\n // microphone. The `!== ''` guard keeps ended/mic-error from rendering a bare\n // \" · Microphone off\".\n //\n // ★ No `error !== null` arm: `stageText` is already '' for `mic-error`, and\n // the message itself belongs to the stage's alert element. Testing the error\n // here printed the whole sentence TWICE on the one screen this change exists\n // to make visible — truncated in the status line, repeated below it, and\n // announced twice by a screen reader.\n const status =\n muted && stage !== 'listening' && stageText !== ''\n ? `${stageText} · ${tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')}`\n : stageText;\n\n return (\n <div\n ref={dialogRef}\n className={`flex flex-col items-center justify-between bg-bg-sunken ${\n view === 'full'\n ? // ★ Below the app header, not behind it. The header is `z-[100]` and\n // this overlay was `z-[60]` at `inset-0`, so the top 56px sat behind\n // it — and the End button did not merely LOOK hidden, it was\n // unclickable (`elementFromPoint` returned the header). Starting at\n // `top-14` means nothing is ever behind the header, and the header\n // stays usable for orientation.\n 'fixed inset-x-0 bottom-0 top-14 z-[60] px-6 py-8'\n : view === 'panel'\n ? // The in-panel stage: covers the assistant panel, keeps the page.\n 'absolute inset-0 z-20 px-4 py-6'\n : // A strip at the bottom, ~180px, so the panel behind stays visible.\n 'absolute inset-x-0 bottom-0 z-20 h-[11.25rem] border-t border-border-subtle px-3 py-3 shadow-lg'\n }`}\n role=\"dialog\"\n // Only modal when it really is: docked, the page behind stays usable.\n // `undefined` rather than `false` — the ARIA default is already false, and\n // some older assistive technology treats an explicit \"false\" on a dialog\n // as still modal.\n aria-modal={expanded || undefined}\n aria-label={tr('healthybowl.assistant.voiceSession.title', 'Voice conversation')}\n data-testid=\"assistant-voice-session\"\n >\n {/* End sits top-right and expand bottom-left, out of the centre column.\n Absolute rather than part of the flow so the pill stays optically\n centred at both sizes — the overlay is already a positioning context\n (`fixed` when expanded, `absolute` when docked). */}\n <button\n ref={endRef}\n type=\"button\"\n onClick={onEnd}\n // ★ Height + horizontal padding, never `size-*`. A fixed square cannot\n // grow to fit a word, so a label dropped into one spills outside its own\n // rounded border. The mini strip keeps the square: its transcript toggle\n // sits 4px away at `right-11`, and a wider button there would grow\n // leftward underneath it — which is precisely the defect the previous\n // commit on this file fixed (\"the close button was unclickable\").\n className={`absolute ${\n expanded\n ? 'right-6 top-6 h-14 gap-2 px-5 text-base'\n : mini\n ? 'right-2 top-2 size-8'\n : 'right-3 top-3 h-11 gap-2 px-4 text-sm'\n } flex items-center justify-center rounded-full border border-border-default bg-bg-elevated text-text-secondary hover:bg-bg-sunken transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n // ★ Only when the label is INVISIBLE. With visible text the accessible\n // name comes from that text, which keeps WCAG 2.5.3 (Label in Name)\n // true by construction in every locale — including before `endShort` is\n // seeded. An aria-label here would instead pin a translated sentence\n // against an untranslated visible word, and speech-input users say the\n // word they can see.\n aria-label={mini ? tr('healthybowl.assistant.voiceSession.end', 'End the voice conversation') : undefined}\n data-testid=\"assistant-voice-end\"\n >\n <X className={expanded ? 'size-6' : mini ? 'size-4' : 'size-5'} aria-hidden=\"true\" />\n {/* The glyph alone said \"close\" only to people who already knew.\n ★ Bounded: the width is a TRANSLATED string while the layout around\n it is fixed pixels — \"Beenden\" and \"Terminer\" are ~2.4x \"End\". The\n cap turns a future overflow into an ellipsis rather than a control\n that creeps over its neighbour. */}\n {!mini ? (\n <span className=\"max-w-[7rem] truncate whitespace-nowrap font-medium\">\n {tr('healthybowl.assistant.voiceSession.endShort', 'End')}\n </span>\n ) : null}\n </button>\n\n {/* ★ The notice is CHROME, not conversation. It used to sit above the\n transcript in the same column as the reply, which is why a microphone\n warning read as part of what the assistant said. The status line moved\n into the stage, where it labels the state it belongs to. */}\n {/* ★ Cleared VERTICALLY, not horizontally. This div is a flex item of a\n `flex flex-col items-center` column, so it is SHRINK-TO-FIT: side\n padding does not reserve space beside the End button, it eats the\n text's own measure — symmetrically, for a control on one side only.\n Widening `px-14` to match a labelled button collapsed the microphone\n warning to a 78px, nine-line column on a phone and in the docked\n panel, because 78px is the min-content width of the longest word in it.\n\n Dropping below the button instead makes the clearance independent of\n both the container width and the label's length — which matters\n because that label is TRANSLATED (\"Beenden\", \"Terminer\") while these\n offsets are fixed pixels. End occupies y=24..80 expanded (top-6 +\n h-14) and y=12..56 docked (top-3 + h-11); the column's own padding\n already starts content at 32 / 24, so these add the rest plus 8px.\n\n ★ NOT true of `mini`, where End, transcript and expand are ALL in the\n top band and this stays `px-3`. A notice there can still be painted\n over by those opaque buttons. Pre-existing and left alone: the strip is\n 180px tall and buying 32px of top padding would squeeze the stage. */}\n <div\n className={`flex flex-col items-center ${\n mini\n ? 'px-3'\n : // ★ The reserve is applied ONLY when there is something to clear.\n // `padding` is not subject to `min-h`, so an unconditional `pt-14`\n // would stand a permanent 56px column above an empty div and take\n // that height out of the `flex-1` stage on every session — paying\n // the cost of a warning that is not there.\n `min-h-[1.5rem] ${showNotice ? (expanded ? 'pt-14' : 'pt-10') : ''}`\n }`}\n >\n {showNotice ? (\n <p className=\"max-w-xs text-center text-xs text-status-warning\" data-testid=\"assistant-voice-notice\">\n {noticeMessage(notice, tr)}\n </p>\n ) : null}\n </div>\n\n {/* ★ Two genuinely different surfaces, not one scaled. Expanded is a\n reading stage; docked is a controller. */}\n {(() => {\n const orb = (\n <AssistantVoiceOrb\n session={session}\n compact={mini}\n connecting={stage === 'connecting'}\n onPress={micIsInterrupt(stage) ? onInterrupt : onToggleMute}\n label={\n micIsInterrupt(stage)\n ? tr('healthybowl.assistant.voiceSession.interrupt', 'Stop the assistant and speak')\n : muted\n ? tr('healthybowl.assistant.voiceSession.unmute', 'Turn the microphone on')\n : tr('healthybowl.assistant.voiceSession.mute', 'Turn the microphone off')\n }\n />\n );\n const caption = micIsInterrupt(stage) ? spoken : heard || null;\n const errorText = error !== null ? errorMessage(error, tr) : null;\n return !mini ? (\n <VoiceStage\n state={stage}\n userCaption={heard || null}\n assistantCaption={spoken}\n // ★ `expanded` — the JSX shorthand — means `expanded={true}`, not\n // `expanded={expanded}`. This branch serves BOTH the docked panel and\n // full screen, so the panel was being styled as full screen: the\n // full-screen caption measure and clamp applied in a column far\n // too narrow for them, and VoiceCaption's non-expanded branch became\n // unreachable code. The variable it shadowed is right there on line 90.\n expanded={expanded}\n statusText={status}\n errorText={errorText}\n control={orb}\n />\n ) : (\n <VoiceMiniController\n state={stage}\n caption={caption}\n statusText={status}\n errorText={errorText}\n control={orb}\n />\n );\n })()}\n\n {transcriptOpen ? <VoiceTranscriptDrawer turns={turns} onClose={() => setTranscriptOpen(false)} /> : null}\n\n {/* History is SECONDARY — behind a button, never on the stage. */}\n <button\n type=\"button\"\n onClick={() => setTranscriptOpen((open) => !open)}\n className={`absolute ${expanded ? 'bottom-6 right-6 size-14' : mini ? 'right-11 top-2 size-8' : 'bottom-3 right-3 size-11'} flex items-center justify-center rounded-full bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n aria-pressed={transcriptOpen}\n aria-label={tr('healthybowl.assistant.voiceSession.transcript', 'Voice transcript')}\n data-testid=\"assistant-voice-transcript-toggle\"\n >\n <ScrollText className={expanded ? 'size-6' : mini ? 'size-4' : 'size-5'} />\n </button>\n\n <button\n type=\"button\"\n onClick={() => setView(nextView)}\n className={`absolute ${expanded ? 'bottom-6 left-6 size-14' : mini ? 'left-2 top-2 size-8' : 'bottom-3 left-3 size-11'} flex items-center justify-center rounded-full bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n // Not a toggle any more, so `aria-pressed` would be a lie. The label\n // names where the button GOES, which is what a stepping control needs.\n aria-label={\n nextView === 'panel'\n ? tr('healthybowl.assistant.voiceSession.expandPanel', 'Show the conversation in the panel')\n : nextView === 'full'\n ? tr('healthybowl.assistant.voiceSession.expand', 'Expand the conversation to full screen')\n : tr('healthybowl.assistant.voiceSession.collapse', 'Shrink to the compact controller')\n }\n data-testid=\"assistant-voice-expand\"\n >\n {expanded ? <Minimize2 className=\"size-5\" /> : <Maximize2 className={mini ? 'size-4' : 'size-5'} />}\n </button>\n </div>\n );\n};\n\n/**\n * Recoverable problems, shown WITHOUT ending the session.\n *\n * The bug these exist for: the overlay said \"Listening…\" while the recogniser\n * was dead, and nothing anywhere said otherwise.\n */\nfunction noticeMessage(notice: VoiceSessionNotice, tr: ReturnType<typeof useTr>): string {\n switch (notice) {\n case 'network':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNetwork',\n 'Speech recognition lost its connection. Check your network — it will retry.'\n );\n case 'not-capturing':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNotCapturing',\n 'The microphone did not start. Check that this site is allowed to use it, then try again.'\n );\n case 'recognition-failed':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeRecognitionFailed',\n 'Speech recognition stopped unexpectedly. It will retry — if it keeps happening, reload the page.'\n );\n case 'nothing-heard':\n return tr(\n 'healthybowl.assistant.voiceSession.noticeNothingHeard',\n 'Nothing heard yet. Check your microphone is not muted or in use by another app.'\n );\n default: {\n const unhandled: never = notice;\n return unhandled;\n }\n }\n}\n\n/**\n * Every failure is explained rather than silently closing the session.\n *\n * A session that just vanishes is the dead-button bug in another shape — the\n * exact defect BOFF-7106 had to fix on the per-message speak control.\n */\nfunction errorMessage(error: VoiceSessionError, tr: ReturnType<typeof useTr>): string {\n switch (error) {\n case 'mic-denied':\n return tr(\n 'healthybowl.assistant.voiceSession.micDenied',\n 'Microphone access is blocked. Allow it in your browser settings to talk.'\n );\n case 'no-speech-support':\n return tr(\n 'healthybowl.assistant.voiceSession.noSpeechSupport',\n 'This browser cannot listen. Try a different browser, or type instead.'\n );\n case 'no-voice-support':\n return tr(\n 'healthybowl.assistant.voiceSession.noVoiceSupport',\n 'This device has no voice that can speak this language.'\n );\n default: {\n // Exhaustive: adding a variant without copy becomes a build error rather\n // than a silently empty status line.\n const unhandled: never = error;\n return unhandled;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAuDA,IAAa,KAAoC,EAC/C,YACA,WAAQ,CAAC,GACT,YAAS,MACT,WACA,gBACA,iBACA,UACA,eAAY,IACZ,kBAAe,IACf,sBAAmB,SACf;CACJ,IAAM,IAAK,EAAM,GACX,EAAE,UAAO,UAAO,aAAU,GAC1B,IAAS,EAA0B,IAAI,GACvC,IAAY,EAAuB,IAAI,GAyBvC,CAAC,GAAM,KAAW,EAAoB,MAAM,GAC5C,IAAW,MAAS,QACpB,IAAO,MAAS,QAChB,IAAsB,MAAS,SAAS,UAAU,MAAS,UAAU,SAAS,QAE9E,CAAC,GAAgB,KAAqB,EAAS,EAAK;CAc1D,AAJA,QAAgB;EACd,EAAO,SAAS,MAAM;CACxB,GAAG,CAAC,CAAC,GAEL,QAAgB;EACd,IAAM,KAAa,MAAyB;GAC1C,IAAI,EAAM,QAAQ,UAAU;IAI1B,IAAI,GAAgB;KAClB,EAAkB,EAAK;KACvB;IACF;IACA,EAAM;IACN;GACF;GAKA,IAAI,EAAM,QAAQ,SAAS,CAAC,GAAU;GAYtC,IAAM,KAHQ,IACV,EAAU,SAAS,cAA2B,8CAA4C,IAC1F,EAAU,UACW,iBAA8B,wBAAwB;GA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ACd,cAAY,EAAG,iDAAiD,kBAAkB;IAClF,eAAY;cAEZ,kBAAC,GAAD,EAAY,WAAW,IAAW,WAAW,IAAO,WAAW,SAAW,CAAA;GACpE,CAAA;GAER,kBAAC,UAAD;IACE,MAAK;IACL,eAAe,EAAQ,CAAQ;IAC/B,WAAW,YAAY,IAAW,4BAA4B,IAAO,wBAAwB,0BAA0B;IAGvH,cACE,MAAa,UACT,EAAG,kDAAkD,oCAAoC,IACzF,MAAa,SACX,EAAG,6CAA6C,wCAAwC,IACxF,EAAG,+CAA+C,kCAAkC;IAE5F,eAAY;cAEX,IAAW,kBAAC,GAAD,EAAW,WAAU,SAAU,CAAA,IAAI,kBAAC,GAAD,EAAW,WAAW,IAAO,WAAW,SAAW,CAAA;GAC5F,CAAA;EACL;;AAET;AAQA,SAAS,EAAc,GAA4B,GAAsC;CACvF,QAAQ,GAAR;EACE,KAAK,WACH,OAAO,EACL,oDACA,6EACF;EACF,KAAK,iBACH,OAAO,EACL,yDACA,0FACF;EACF,KAAK,sBACH,OAAO,EACL,8DACA,kGACF;EACF,KAAK,iBACH,OAAO,EACL,yDACA,iFACF;EACF,SAEE,OAAO;CAEX;AACF;AAQA,SAAS,EAAa,GAA0B,GAAsC;CACpF,QAAQ,GAAR;EACE,KAAK,cACH,OAAO,EACL,gDACA,0EACF;EACF,KAAK,qBACH,OAAO,EACL,sDACA,uEACF;EACF,KAAK,oBACH,OAAO,EACL,qDACA,wDACF;EACF,SAIE,OAAO;CAEX;AACF"}
@@ -1,31 +1,47 @@
1
1
  import { useTr as e } from "../../../shared/hooks/useTr.js";
2
- import { AssistantMarkdownRenderer as t } from "../AssistantMarkdownRenderer.js";
3
- import { jsx as n } from "react/jsx-runtime";
2
+ import { groupConsecutiveBySession as t } from "../../../utils/voiceTurnVisibility.js";
3
+ import { AssistantMarkdownRenderer as n } from "../AssistantMarkdownRenderer.js";
4
+ import { useMemo as r } from "react";
5
+ import { jsx as i, jsxs as a } from "react/jsx-runtime";
4
6
  //#region src/components/assistant/voice/VoiceConversationView.tsx
5
- var r = ({ turns: r }) => {
6
- let i = e();
7
- return r.length === 0 ? /* @__PURE__ */ n("div", {
7
+ var o = ({ turns: o }) => {
8
+ let s = e(), c = r(() => t(o, (e) => e.sessionId), [o]);
9
+ return o.length === 0 ? /* @__PURE__ */ i("div", {
8
10
  className: "flex flex-1 items-center justify-center px-6",
9
- children: /* @__PURE__ */ n("p", {
11
+ children: /* @__PURE__ */ i("p", {
10
12
  className: "text-center text-sm text-text-muted",
11
- children: i("healthybowl.assistant.voiceSession.transcriptEmpty", "Nothing spoken yet in this session.")
13
+ children: s("healthybowl.assistant.voiceSession.transcriptEmpty", "Nothing spoken yet in this session.")
12
14
  })
13
- }) : /* @__PURE__ */ n("div", {
14
- className: "flex-1 space-y-4 overflow-y-auto px-4 py-4",
15
+ }) : /* @__PURE__ */ i("div", {
16
+ className: "flex-1 overflow-y-auto px-4 py-4",
15
17
  "data-testid": "assistant-voice-conversation",
16
- children: r.map((e) => e.role === "user" ? /* @__PURE__ */ n("div", {
17
- className: "flex justify-end",
18
- children: /* @__PURE__ */ n("p", {
19
- className: "max-w-[85%] whitespace-pre-wrap break-words rounded-2xl bg-bg-elevated px-3 py-2 text-sm leading-relaxed text-text-primary",
20
- children: e.text
21
- })
22
- }, e.id) : /* @__PURE__ */ n("div", {
23
- className: "text-sm leading-relaxed text-text-secondary",
24
- children: /* @__PURE__ */ n(t, { content: e.text })
25
- }, e.id))
18
+ children: c.map((e, t) => /* @__PURE__ */ a("section", {
19
+ className: "space-y-4 pb-4",
20
+ children: [t > 0 ? /* @__PURE__ */ a("div", {
21
+ className: "flex items-center gap-2 pt-2",
22
+ role: "separator",
23
+ children: [
24
+ /* @__PURE__ */ i("span", { className: "h-px flex-1 bg-border-subtle" }),
25
+ /* @__PURE__ */ i("span", {
26
+ className: "text-[11px] uppercase tracking-wide text-text-muted",
27
+ children: s("healthybowl.assistant.voiceSession.newSession", "New voice session")
28
+ }),
29
+ /* @__PURE__ */ i("span", { className: "h-px flex-1 bg-border-subtle" })
30
+ ]
31
+ }) : null, e.turns.map((e) => e.role === "user" ? /* @__PURE__ */ i("div", {
32
+ className: "flex justify-end",
33
+ children: /* @__PURE__ */ i("p", {
34
+ className: "max-w-[85%] whitespace-pre-wrap break-words rounded-2xl bg-bg-elevated px-3 py-2 text-sm leading-relaxed text-text-primary",
35
+ children: e.text
36
+ })
37
+ }, e.id) : /* @__PURE__ */ i("div", {
38
+ className: "text-sm leading-relaxed text-text-secondary",
39
+ children: /* @__PURE__ */ i(n, { content: e.text })
40
+ }, e.id))]
41
+ }, `${e.sessionId ?? "earlier"}-${t}`))
26
42
  });
27
43
  };
28
44
  //#endregion
29
- export { r as VoiceConversationView };
45
+ export { o as VoiceConversationView };
30
46
 
31
47
  //# sourceMappingURL=VoiceConversationView.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"VoiceConversationView.js","names":[],"sources":["../../../../src/components/assistant/voice/VoiceConversationView.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { AssistantMarkdownRenderer } from '../AssistantMarkdownRenderer';\nimport { useTr } from '../../../shared/hooks/useTr';\n\n/**\n * The voice conversation, as a normal chat.\n *\n * ★ This exists because separating voice from chat took something away. The\n * chat panel now filters voice turns OUT, so a conversation held entirely by\n * voice renders the \"How can I help?\" empty state behind the session — the\n * exchange the user just had appears nowhere in a readable form. Splitting the\n * surfaces was right; leaving no way to READ the voice conversation was not.\n *\n * So voice has two perspectives rather than one:\n * - LIVE — the stage: one state, big captions, what is happening now\n * - CHAT — this: the whole exchange, scrollable, rendered properly\n *\n * ★ It uses `AssistantMarkdownRenderer`, the SAME renderer the typed chat uses.\n * That matters: the old voice overlay printed the model's text raw, which is\n * why `##` and `**` appeared as literal characters. Voice replies should be\n * plain prose now (the prompt asks for it), but if any markdown survives it\n * renders as formatting rather than as syntax.\n *\n * Still NOT the chat thread: these turns stay marked `voice`, so they never\n * appear in the typed conversation. This is a second view of the same voice\n * session, not a merge.\n */\n\ninterface Props {\n turns: ReadonlyArray<{ id: string; role: 'user' | 'assistant'; text: string }>;\n}\n\nexport const VoiceConversationView: FC<Props> = ({ turns }) => {\n const tr = useTr();\n\n if (turns.length === 0) {\n return (\n <div className=\"flex flex-1 items-center justify-center px-6\">\n <p className=\"text-center text-sm text-text-muted\">\n {tr('healthybowl.assistant.voiceSession.transcriptEmpty', 'Nothing spoken yet in this session.')}\n </p>\n </div>\n );\n }\n\n return (\n <div className=\"flex-1 space-y-4 overflow-y-auto px-4 py-4\" data-testid=\"assistant-voice-conversation\">\n {turns.map((turn) =>\n turn.role === 'user' ? (\n // Mirrors the chat bubble so the two surfaces feel like one product.\n <div key={turn.id} className=\"flex justify-end\">\n <p className=\"max-w-[85%] whitespace-pre-wrap break-words rounded-2xl bg-bg-elevated px-3 py-2 text-sm leading-relaxed text-text-primary\">\n {turn.text}\n </p>\n </div>\n ) : (\n <div key={turn.id} className=\"text-sm leading-relaxed text-text-secondary\">\n <AssistantMarkdownRenderer content={turn.text} />\n </div>\n )\n )}\n </div>\n );\n};\n"],"mappings":";;;;AAgCA,IAAa,KAAoC,EAAE,eAAY;CAC7D,IAAM,IAAK,EAAM;CAYjB,OAVI,EAAM,WAAW,IAEjB,kBAAC,OAAD;EAAK,WAAU;YACb,kBAAC,KAAD;GAAG,WAAU;aACV,EAAG,sDAAsD,qCAAqC;EAC9F,CAAA;CACA,CAAA,IAKP,kBAAC,OAAD;EAAK,WAAU;EAA6C,eAAY;YACrE,EAAM,KAAK,MACV,EAAK,SAAS,SAEZ,kBAAC,OAAD;GAAmB,WAAU;aAC3B,kBAAC,KAAD;IAAG,WAAU;cACV,EAAK;GACL,CAAA;EACA,GAJK,EAAK,EAIV,IAEL,kBAAC,OAAD;GAAmB,WAAU;aAC3B,kBAAC,GAAD,EAA2B,SAAS,EAAK,KAAO,CAAA;EAC7C,GAFK,EAAK,EAEV,CAET;CACG,CAAA;AAET"}
1
+ {"version":3,"file":"VoiceConversationView.js","names":[],"sources":["../../../../src/components/assistant/voice/VoiceConversationView.tsx"],"sourcesContent":["import { useMemo, type FC } from 'react';\nimport { AssistantMarkdownRenderer } from '../AssistantMarkdownRenderer';\nimport { groupConsecutiveBySession, type VoiceTranscriptTurn } from '../../../utils/voiceTurnVisibility';\nimport { useTr } from '../../../shared/hooks/useTr';\n\n/**\n * The voice conversation, as a normal chat.\n *\n * ★ This exists because separating voice from chat took something away. The\n * chat panel now filters voice turns OUT, so a conversation held entirely by\n * voice renders the \"How can I help?\" empty state behind the session — the\n * exchange the user just had appears nowhere in a readable form. Splitting the\n * surfaces was right; leaving no way to READ the voice conversation was not.\n *\n * So voice has two perspectives rather than one:\n * - LIVE — the stage: one state, big captions, what is happening now\n * - CHAT — this: the whole exchange, scrollable, rendered properly\n *\n * ★ It uses `AssistantMarkdownRenderer`, the SAME renderer the typed chat uses.\n * That matters: the old voice overlay printed the model's text raw, which is\n * why `##` and `**` appeared as literal characters. Voice replies should be\n * plain prose now (the prompt asks for it), but if any markdown survives it\n * renders as formatting rather than as syntax.\n *\n * Still NOT the chat thread: these turns stay marked `voice`, so they never\n * appear in the typed conversation. This is a second view of the same voice\n * session, not a merge.\n */\n\ninterface Props {\n /**\n * Every spoken turn in the conversation, oldest first.\n *\n * `sessionId` is absent on turns recorded before session ids existed. They are\n * shown, not dropped — the user really said them — and they collapse into one\n * leading group rather than being scattered one divider apart.\n */\n turns: ReadonlyArray<VoiceTranscriptTurn>;\n}\n\nexport const VoiceConversationView: FC<Props> = ({ turns }) => {\n const tr = useTr();\n const groups = useMemo(() => groupConsecutiveBySession(turns, (turn) => turn.sessionId), [turns]);\n\n if (turns.length === 0) {\n return (\n <div className=\"flex flex-1 items-center justify-center px-6\">\n <p className=\"text-center text-sm text-text-muted\">\n {tr('healthybowl.assistant.voiceSession.transcriptEmpty', 'Nothing spoken yet in this session.')}\n </p>\n </div>\n );\n }\n\n return (\n <div className=\"flex-1 overflow-y-auto px-4 py-4\" data-testid=\"assistant-voice-conversation\">\n {groups.map((group, index) => (\n <section\n // ★ Composite, because a session id is NOT unique across groups.\n // Grouping is by consecutive RUNS, so an id that reappears after\n // another session produces two groups carrying the same id — and two\n // siblings with the same key make React reconcile the wrong one.\n key={`${group.sessionId ?? 'earlier'}-${index}`}\n className=\"space-y-4 pb-4\"\n >\n {/* ★ A divider only BETWEEN sessions, never above the first. The\n transcript deliberately shows the conversation's whole spoken\n history — you can go back to what you asked last time — but run\n together it reads as one exchange, so a question from days ago\n looks like it was just asked. This is what makes showing\n everything honest. Skipped when there is only one session, where a\n heading would be noise. */}\n {index > 0 ? (\n <div className=\"flex items-center gap-2 pt-2\" role=\"separator\">\n <span className=\"h-px flex-1 bg-border-subtle\" />\n <span className=\"text-[11px] uppercase tracking-wide text-text-muted\">\n {tr('healthybowl.assistant.voiceSession.newSession', 'New voice session')}\n </span>\n <span className=\"h-px flex-1 bg-border-subtle\" />\n </div>\n ) : null}\n\n {group.turns.map((turn) =>\n turn.role === 'user' ? (\n // Mirrors the chat bubble so the two surfaces feel like one product.\n <div key={turn.id} className=\"flex justify-end\">\n <p className=\"max-w-[85%] whitespace-pre-wrap break-words rounded-2xl bg-bg-elevated px-3 py-2 text-sm leading-relaxed text-text-primary\">\n {turn.text}\n </p>\n </div>\n ) : (\n <div key={turn.id} className=\"text-sm leading-relaxed text-text-secondary\">\n <AssistantMarkdownRenderer content={turn.text} />\n </div>\n )\n )}\n </section>\n ))}\n </div>\n );\n};\n"],"mappings":";;;;;;AAwCA,IAAa,KAAoC,EAAE,eAAY;CAC7D,IAAM,IAAK,EAAM,GACX,IAAS,QAAc,EAA0B,IAAQ,MAAS,EAAK,SAAS,GAAG,CAAC,CAAK,CAAC;CAYhG,OAVI,EAAM,WAAW,IAEjB,kBAAC,OAAD;EAAK,WAAU;YACb,kBAAC,KAAD;GAAG,WAAU;aACV,EAAG,sDAAsD,qCAAqC;EAC9F,CAAA;CACA,CAAA,IAKP,kBAAC,OAAD;EAAK,WAAU;EAAmC,eAAY;YAC3D,EAAO,KAAK,GAAO,MAClB,kBAAC,WAAD;GAME,WAAU;aANZ,CAeG,IAAQ,IACP,kBAAC,OAAD;IAAK,WAAU;IAA+B,MAAK;cAAnD;KACE,kBAAC,QAAD,EAAM,WAAU,+BAAgC,CAAA;KAChD,kBAAC,QAAD;MAAM,WAAU;gBACb,EAAG,iDAAiD,mBAAmB;KACpE,CAAA;KACN,kBAAC,QAAD,EAAM,WAAU,+BAAgC,CAAA;IAC7C;QACH,MAEH,EAAM,MAAM,KAAK,MAChB,EAAK,SAAS,SAEZ,kBAAC,OAAD;IAAmB,WAAU;cAC3B,kBAAC,KAAD;KAAG,WAAU;eACV,EAAK;IACL,CAAA;GACA,GAJK,EAAK,EAIV,IAEL,kBAAC,OAAD;IAAmB,WAAU;cAC3B,kBAAC,GAAD,EAA2B,SAAS,EAAK,KAAO,CAAA;GAC7C,GAFK,EAAK,EAEV,CAET,CACO;KAlCF,GAAG,EAAM,aAAa,UAAU,GAAG,GAkCjC,CACV;CACE,CAAA;AAET"}
@@ -1 +1 @@
1
- {"version":3,"file":"VoiceTranscriptDrawer.js","names":[],"sources":["../../../../src/components/assistant/voice/VoiceTranscriptDrawer.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { X } from 'lucide-react';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { VoiceConversationView } from './VoiceConversationView';\n\n/**\n * This session's spoken turns, on demand.\n *\n * The stage shows only what is happening NOW, which is right for a live\n * conversation and would otherwise mean the history is simply gone. This is\n * where it goes: secondary, behind a button, and explicitly a VOICE transcript\n * rather than the chat thread.\n *\n * ★ `z-30` is not decoration: the session container is `z-20` docked and\n * `z-[60]` expanded, and a child at `z-10` painted BEHIND its own parent — the\n * drawer opened and was invisible. Stacking contexts are per-parent, so this\n * only has to beat its siblings, not the overlay itself.\n *\n * ★ Renders only the turns it is handed, which are already filtered to the\n * SPOKEN channel — so it can never resurrect the typed conversation the old\n * overlay used to paint. Note \"spoken\", not \"this session\": the marker is a\n * boolean, so this is the conversation's whole spoken history. The heading below\n * says so.\n */\n\ninterface Props {\n turns: ReadonlyArray<{ id: string; role: 'user' | 'assistant'; text: string }>;\n onClose: () => void;\n}\n\nexport const VoiceTranscriptDrawer: FC<Props> = ({ turns, onClose }) => {\n const tr = useTr();\n return (\n <div\n className=\"absolute inset-0 z-30 flex flex-col bg-bg-sunken/95 backdrop-blur-sm\"\n role=\"dialog\"\n // ★ Its OWN key. This shared `…voiceSession.transcript` with the heading\n // below while giving it a different English default, so once the key is\n // seeded one of the two silently changes to the other's wording.\n aria-label={tr('healthybowl.assistant.voiceSession.transcriptTitle', 'Voice transcript')}\n data-testid=\"assistant-voice-transcript\"\n >\n <div className=\"flex items-center justify-between border-b border-border-subtle px-4 py-3\">\n <div className=\"min-w-0\">\n <h2 className=\"text-sm font-semibold text-text-primary\">\n {tr('healthybowl.assistant.voiceSession.transcript', 'Voice conversation')}\n </h2>\n {/* Say plainly that this is NOT the typed thread, so nobody wonders\n why it is not in their chat history.\n\n ★ It used to say \"This session only\", which was not true:\n `voiceTurnsOnly` filters on a per-message marker, so it returns every\n spoken turn in the CONVERSATION, and a second voice session showed the\n first one's turns under a promise that it would not. Showing the whole\n conversation's spoken history is the more useful behaviour of the two,\n so the wording changed rather than the filter. */}\n <p className=\"truncate text-xs text-text-muted\">\n {tr(\n 'healthybowl.assistant.voiceSession.transcriptHint',\n 'Spoken turns in this conversation — kept out of your typed chat.'\n )}\n </p>\n </div>\n <button\n type=\"button\"\n onClick={onClose}\n className=\"flex size-8 items-center justify-center rounded-full text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong\"\n aria-label={tr('healthybowl.assistant.voiceSession.transcriptClose', 'Close the transcript')}\n data-testid=\"assistant-voice-transcript-close\"\n >\n <X className=\"size-4\" />\n </button>\n </div>\n\n <VoiceConversationView turns={turns} />\n </div>\n );\n};\n"],"mappings":";;;;;AA8BA,IAAa,KAAoC,EAAE,UAAO,iBAAc;CACtE,IAAM,IAAK,EAAM;CACjB,OACE,kBAAC,OAAD;EACE,WAAU;EACV,MAAK;EAIL,cAAY,EAAG,sDAAsD,kBAAkB;EACvF,eAAY;YAPd,CASE,kBAAC,OAAD;GAAK,WAAU;aAAf,CACE,kBAAC,OAAD;IAAK,WAAU;cAAf,CACE,kBAAC,MAAD;KAAI,WAAU;eACX,EAAG,iDAAiD,oBAAoB;IACvE,CAAA,GAUJ,kBAAC,KAAD;KAAG,WAAU;eACV,EACC,qDACA,kEACF;IACC,CAAA,CACA;OACL,kBAAC,UAAD;IACE,MAAK;IACL,SAAS;IACT,WAAU;IACV,cAAY,EAAG,sDAAsD,sBAAsB;IAC3F,eAAY;cAEZ,kBAAC,GAAD,EAAG,WAAU,SAAU,CAAA;GACjB,CAAA,CACL;MAEL,kBAAC,GAAD,EAA8B,SAAQ,CAAA,CACnC;;AAET"}
1
+ {"version":3,"file":"VoiceTranscriptDrawer.js","names":[],"sources":["../../../../src/components/assistant/voice/VoiceTranscriptDrawer.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { X } from 'lucide-react';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { VoiceConversationView } from './VoiceConversationView';\nimport type { VoiceTranscriptTurn } from '../../../utils/voiceTurnVisibility';\n\n/**\n * This session's spoken turns, on demand.\n *\n * The stage shows only what is happening NOW, which is right for a live\n * conversation and would otherwise mean the history is simply gone. This is\n * where it goes: secondary, behind a button, and explicitly a VOICE transcript\n * rather than the chat thread.\n *\n * ★ `z-30` is not decoration: the session container is `z-20` docked and\n * `z-[60]` expanded, and a child at `z-10` painted BEHIND its own parent — the\n * drawer opened and was invisible. Stacking contexts are per-parent, so this\n * only has to beat its siblings, not the overlay itself.\n *\n * ★ Renders only the turns it is handed, which are already filtered to the\n * SPOKEN channel — so it can never resurrect the typed conversation the old\n * overlay used to paint. Note \"spoken\", not \"this session\": the marker is a\n * boolean, so this is the conversation's whole spoken history. The heading below\n * says so.\n */\n\ninterface Props {\n turns: ReadonlyArray<VoiceTranscriptTurn>;\n onClose: () => void;\n}\n\nexport const VoiceTranscriptDrawer: FC<Props> = ({ turns, onClose }) => {\n const tr = useTr();\n return (\n <div\n className=\"absolute inset-0 z-30 flex flex-col bg-bg-sunken/95 backdrop-blur-sm\"\n role=\"dialog\"\n // ★ Its OWN key. This shared `…voiceSession.transcript` with the heading\n // below while giving it a different English default, so once the key is\n // seeded one of the two silently changes to the other's wording.\n aria-label={tr('healthybowl.assistant.voiceSession.transcriptTitle', 'Voice transcript')}\n data-testid=\"assistant-voice-transcript\"\n >\n <div className=\"flex items-center justify-between border-b border-border-subtle px-4 py-3\">\n <div className=\"min-w-0\">\n <h2 className=\"text-sm font-semibold text-text-primary\">\n {tr('healthybowl.assistant.voiceSession.transcript', 'Voice conversation')}\n </h2>\n {/* Say plainly that this is NOT the typed thread, so nobody wonders\n why it is not in their chat history.\n\n ★ It used to say \"This session only\", which was not true:\n `voiceTurnsOnly` filters on a per-message marker, so it returns every\n spoken turn in the CONVERSATION, and a second voice session showed the\n first one's turns under a promise that it would not. Showing the whole\n conversation's spoken history is the more useful behaviour of the two,\n so the wording changed rather than the filter. */}\n <p className=\"truncate text-xs text-text-muted\">\n {tr(\n 'healthybowl.assistant.voiceSession.transcriptHint',\n 'Spoken turns in this conversation — kept out of your typed chat.'\n )}\n </p>\n </div>\n <button\n type=\"button\"\n onClick={onClose}\n className=\"flex size-8 items-center justify-center rounded-full text-text-secondary transition-colors hover:bg-bg-raised hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong\"\n aria-label={tr('healthybowl.assistant.voiceSession.transcriptClose', 'Close the transcript')}\n data-testid=\"assistant-voice-transcript-close\"\n >\n <X className=\"size-4\" />\n </button>\n </div>\n\n <VoiceConversationView turns={turns} />\n </div>\n );\n};\n"],"mappings":";;;;;AA+BA,IAAa,KAAoC,EAAE,UAAO,iBAAc;CACtE,IAAM,IAAK,EAAM;CACjB,OACE,kBAAC,OAAD;EACE,WAAU;EACV,MAAK;EAIL,cAAY,EAAG,sDAAsD,kBAAkB;EACvF,eAAY;YAPd,CASE,kBAAC,OAAD;GAAK,WAAU;aAAf,CACE,kBAAC,OAAD;IAAK,WAAU;cAAf,CACE,kBAAC,MAAD;KAAI,WAAU;eACX,EAAG,iDAAiD,oBAAoB;IACvE,CAAA,GAUJ,kBAAC,KAAD;KAAG,WAAU;eACV,EACC,qDACA,kEACF;IACC,CAAA,CACA;OACL,kBAAC,UAAD;IACE,MAAK;IACL,SAAS;IACT,WAAU;IACV,cAAY,EAAG,sDAAsD,sBAAsB;IAC3F,eAAY;cAEZ,kBAAC,GAAD,EAAG,WAAU,SAAU,CAAA;GACjB,CAAA,CACL;MAEL,kBAAC,GAAD,EAA8B,SAAQ,CAAA,CACnC;;AAET"}
@@ -48,7 +48,7 @@ function x({ onSubmit: x, latestReply: S, language: C }) {
48
48
  T.phase === "listening" && (K.current = c(T)), d(() => {
49
49
  if (T.phase !== "thinking") return;
50
50
  let e = K.current.trim();
51
- e && x(e);
51
+ e && x(e, q.current ?? `vs-orphan-${Date.now().toString(36)}`);
52
52
  }, [T.phase]), d(() => {
53
53
  let e = s(S?.id, T.phase, M.current);
54
54
  e.claim && (M.current = S?.id ?? null, e.advance && S && E({
@@ -87,7 +87,7 @@ function x({ onSubmit: x, latestReply: S, language: C }) {
87
87
  }, [T, G.isListening]), d(() => {
88
88
  c(T) !== "" && F(null);
89
89
  }, [T]);
90
- let q = u(() => {
90
+ let q = m(null), J = u(() => {
91
91
  if (L(!1), z(!1), !G.isSupported) {
92
92
  E({
93
93
  type: "fail",
@@ -115,14 +115,14 @@ function x({ onSubmit: x, latestReply: S, language: C }) {
115
115
  e.volume = 0, e.play().catch(() => {});
116
116
  }
117
117
  } catch {}
118
- O(!0), F(null), M.current = V.current?.id ?? null, E({ type: "start" });
118
+ O(!0), F(null), M.current = V.current?.id ?? null, q.current = `vs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`, E({ type: "start" });
119
119
  }, [
120
120
  G.isSupported,
121
121
  D.isBlocked,
122
122
  O
123
- ]), J = u(() => {
124
- L(!1), z(!1), E({ type: "end" }), A(), O(!1);
125
- }, [A, O]), Y = u(() => {
123
+ ]), Y = u(() => {
124
+ L(!1), z(!1), q.current = null, E({ type: "end" }), A(), O(!1);
125
+ }, [A, O]), X = u(() => {
126
126
  E({
127
127
  type: "mute",
128
128
  muted: !B.current.muted
@@ -138,9 +138,9 @@ function x({ onSubmit: x, latestReply: S, language: C }) {
138
138
  interrupting: I,
139
139
  awaitingEndpoint: R,
140
140
  available: G.isSupported && !D.isBlocked,
141
- start: q,
142
- end: J,
143
- toggleMute: Y,
141
+ start: J,
142
+ end: Y,
143
+ toggleMute: X,
144
144
  interrupt: W
145
145
  }), [
146
146
  T,
@@ -150,9 +150,9 @@ function x({ onSubmit: x, latestReply: S, language: C }) {
150
150
  G.isListening,
151
151
  G.isSupported,
152
152
  D.isBlocked,
153
- q,
154
153
  J,
155
154
  Y,
155
+ X,
156
156
  W
157
157
  ]);
158
158
  }