@burdenoff/microfe-healthybowl 2026.901.5 → 2026.901.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/assistant/voice/AssistantVoiceSession.js +1 -0
- package/dist/components/assistant/voice/AssistantVoiceSession.js.map +1 -1
- package/dist/hooks/useVoiceSession.js +1 -1
- package/dist/hooks/useVoiceSession.js.map +1 -1
- package/dist/services/speech/createSpeechEngine.js +0 -1
- package/dist/services/speech/createSpeechEngine.js.map +1 -1
- package/dist/utils/voiceSession.js.map +1 -1
- package/package.json +1 -1
|
@@ -95,6 +95,7 @@ function f(e, t) {
|
|
|
95
95
|
switch (e) {
|
|
96
96
|
case "network": return t("healthybowl.assistant.voiceSession.noticeNetwork", "Speech recognition lost its connection. Check your network — it will retry.");
|
|
97
97
|
case "not-capturing": return t("healthybowl.assistant.voiceSession.noticeNotCapturing", "The microphone did not start. Check that this site is allowed to use it, then try again.");
|
|
98
|
+
case "recognition-failed": return t("healthybowl.assistant.voiceSession.noticeRecognitionFailed", "Speech recognition stopped unexpectedly. It will retry — if it keeps happening, reload the page.");
|
|
98
99
|
case "nothing-heard": return t("healthybowl.assistant.voiceSession.noticeNothingHeard", "Nothing heard yet. Check your microphone is not muted or in use by another app.");
|
|
99
100
|
default: return e;
|
|
100
101
|
}
|
|
@@ -1 +1 @@
|
|
|
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, X } from 'lucide-react';\nimport { AssistantVoiceOrb } from './AssistantVoiceOrb';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { spokenSoFar, type VoiceSessionSnapshot } from '../../../utils/voiceSession';\nimport type { VoiceSessionError } from '../../../utils/voiceSession';\nimport type { VoiceSessionNotice } from '../../../hooks/useVoiceSession';\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}\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}) => {\n const tr = useTr();\n const { phase, muted, error } = session;\n const endRef = useRef<HTMLButtonElement>(null);\n const dialogRef = useRef<HTMLDivElement>(null);\n /**\n * Docked inside the assistant panel by default; full-screen only on request.\n *\n * A voice conversation is usually a glance-and-listen thing, so taking over\n * the whole screen for it is the wrong default — the user loses the page they\n * were asking about. Expanding is opt-in and per-session: reopening starts\n * docked again, which is the behaviour that matches \"default should be the\n * same size as the assistant\".\n */\n const [expanded, setExpanded] = useState(false);\n\n // A full-screen `aria-modal` overlay that cannot be dismissed from the\n // keyboard is a trap. Escape ends the session, and focus starts on End so a\n // keyboard or screen-reader user lands somewhere useful rather than behind\n // the overlay.\n // Focus lands on End ONCE, on open. Keeping this in the keydown effect below\n // meant every expand/collapse re-ran it and silently stole focus from the\n // button just pressed — a Space or Enter a beat later would then end the\n // session instead of toggling the size again.\n useEffect(() => {\n endRef.current?.focus();\n }, []);\n\n useEffect(() => {\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n onEnd();\n return;\n }\n // Trapping focus is only correct when the overlay actually covers\n // everything. Docked, it sits inside the panel and the rest of the page\n // is legitimately reachable, so trapping there would be the bug rather\n // than the fix.\n if (event.key !== 'Tab' || !expanded) return;\n // `aria-modal` only TELLS assistive technology this is modal; it does not\n // make it so. Without this, Tab walks straight out of the overlay into the\n // page behind it, which is still fully interactive underneath — a\n // keyboard user ends up operating a screen they cannot see.\n const focusable = dialogRef.current?.querySelectorAll<HTMLElement>('button:not([disabled])');\n if (!focusable || focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (!first || !last) return;\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n window.addEventListener('keydown', onKeyDown);\n return () => window.removeEventListener('keydown', onKeyDown);\n }, [onEnd, expanded]);\n\n // Muted is reported ALONGSIDE the phase, not instead of it: the assistant may\n // still be speaking with the microphone off, and saying only \"Microphone off\"\n // would misreport that.\n const phaseText =\n phase === 'thinking'\n ? tr('healthybowl.assistant.voiceSession.thinking', 'Thinking…')\n : phase === 'speaking'\n ? tr('healthybowl.assistant.voiceSession.speaking', 'Speaking — tap to stop')\n : muted\n ? tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')\n : tr('healthybowl.assistant.voiceSession.listening', 'Listening…');\n\n const status =\n error !== null\n ? errorMessage(error, tr)\n : muted && phase !== 'listening'\n ? `${phaseText} · ${tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')}`\n : phaseText;\n\n // While speaking, the caption shows the REPLY; otherwise what we have heard.\n // Showing the stale transcript under the assistant's own voice reads as a\n // mis-transcription of the assistant, which is worse than showing nothing.\n const caption = phase === 'speaking' ? spoken : spokenSoFar(session);\n\n return (\n <div\n ref={dialogRef}\n className={`flex flex-col items-center justify-between bg-bg-sunken ${\n expanded ? 'fixed inset-0 z-[60] px-6 py-10' : 'absolute inset-0 z-20 px-4 py-6'\n }`}\n role=\"dialog\"\n // Only modal when it really is: docked, the page behind stays usable.\n // `undefined` rather than `false` — the ARIA default is already false, and\n // some older assistive technology treats an explicit \"false\" on a dialog\n // as still modal.\n aria-modal={expanded || undefined}\n aria-label={tr('healthybowl.assistant.voiceSession.title', 'Voice conversation')}\n data-testid=\"assistant-voice-session\"\n >\n {/* 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 className={`absolute ${expanded ? 'right-6 top-6 size-14' : 'right-3 top-3 size-11'} 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 aria-label={tr('healthybowl.assistant.voiceSession.end', 'End the voice conversation')}\n data-testid=\"assistant-voice-end\"\n >\n <X className={expanded ? 'size-6' : 'size-5'} />\n </button>\n\n {/* The session's single live region. It has real words, unlike the orb. */}\n <div className=\"flex flex-col items-center gap-1 px-14\">\n <p className=\"text-sm text-text-muted\" role=\"status\" aria-live=\"polite\" data-testid=\"assistant-voice-status\">\n {status}\n </p>\n {/* A dead microphone used to look exactly like a live one. Whatever else\n happens, the session must never claim to be listening in silence. */}\n {notice && error === null ? (\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 {/* Padded so the pill and caption never collide with the corner controls\n in a docked panel only a few hundred pixels wide. */}\n <div className=\"flex min-h-0 w-full flex-1 flex-col items-center justify-center gap-4 px-14\">\n {/* The running conversation, as Gemini shows it — so a second question\n in the same session has the first still visible. Oldest first, with\n the newest pinned at the bottom next to the orb. */}\n {turns.length > 0 ? (\n <div\n className={`flex w-full flex-1 flex-col justify-end gap-2 overflow-y-auto text-sm ${expanded ? 'max-w-3xl' : 'max-w-md'}`}\n data-testid=\"assistant-voice-turns\"\n >\n {turns.map((turn) => (\n <p\n key={turn.id}\n className={\n turn.role === 'user'\n ? 'self-end rounded-2xl bg-bg-elevated px-3 py-1.5 text-text-primary'\n : 'self-start text-text-secondary'\n }\n >\n {turn.text}\n </p>\n ))}\n </div>\n ) : null}\n\n <AssistantVoiceOrb\n session={session}\n compact={!expanded}\n onPress={phase === 'speaking' ? onInterrupt : onToggleMute}\n label={\n phase === 'speaking'\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 {/* The LIVE caption: what is being said right now, before it is\n finalised into the conversation. `turns` only holds messages that\n already reached history, so without this the in-progress utterance\n appears nowhere and the session looks deaf while it is working. */}\n {caption ? (\n <p\n className={`text-center leading-relaxed text-text-secondary ${expanded ? 'max-w-3xl text-2xl font-semibold' : 'line-clamp-3 max-w-md text-base'}`}\n data-testid=\"assistant-voice-caption\"\n >\n {caption}\n </p>\n ) : null}\n </div>\n\n <button\n type=\"button\"\n onClick={() => setExpanded((current) => !current)}\n className={`absolute ${expanded ? 'bottom-6 left-6 size-14' : '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 aria-pressed={expanded}\n aria-label={\n expanded\n ? tr('healthybowl.assistant.voiceSession.collapse', 'Fit the conversation back into the panel')\n : tr('healthybowl.assistant.voiceSession.expand', 'Expand the conversation to full screen')\n }\n data-testid=\"assistant-voice-expand\"\n >\n {expanded ? <Minimize2 className=\"size-5\" /> : <Maximize2 className=\"size-5\" />}\n </button>\n </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 '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":";;;;;;;AAyCA,IAAa,KAAoC,EAC/C,YACA,WAAQ,CAAC,GACT,YAAS,MACT,WACA,gBACA,iBACA,eACI;CACJ,IAAM,IAAK,EAAM,GACX,EAAE,UAAO,UAAO,aAAU,GAC1B,IAAS,EAA0B,IAAI,G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AQ,GAAR;EACE,KAAK,WACH,OAAO,EACL,oDACA,6EACF;EACF,KAAK,iBACH,OAAO,EACL,yDACA,0FACF;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, X } from 'lucide-react';\nimport { AssistantVoiceOrb } from './AssistantVoiceOrb';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { spokenSoFar, type VoiceSessionSnapshot } from '../../../utils/voiceSession';\nimport type { VoiceSessionError } from '../../../utils/voiceSession';\nimport type { VoiceSessionNotice } from '../../../hooks/useVoiceSession';\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}\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}) => {\n const tr = useTr();\n const { phase, muted, error } = session;\n const endRef = useRef<HTMLButtonElement>(null);\n const dialogRef = useRef<HTMLDivElement>(null);\n /**\n * Docked inside the assistant panel by default; full-screen only on request.\n *\n * A voice conversation is usually a glance-and-listen thing, so taking over\n * the whole screen for it is the wrong default — the user loses the page they\n * were asking about. Expanding is opt-in and per-session: reopening starts\n * docked again, which is the behaviour that matches \"default should be the\n * same size as the assistant\".\n */\n const [expanded, setExpanded] = useState(false);\n\n // A full-screen `aria-modal` overlay that cannot be dismissed from the\n // keyboard is a trap. Escape ends the session, and focus starts on End so a\n // keyboard or screen-reader user lands somewhere useful rather than behind\n // the overlay.\n // Focus lands on End ONCE, on open. Keeping this in the keydown effect below\n // meant every expand/collapse re-ran it and silently stole focus from the\n // button just pressed — a Space or Enter a beat later would then end the\n // session instead of toggling the size again.\n useEffect(() => {\n endRef.current?.focus();\n }, []);\n\n useEffect(() => {\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n onEnd();\n return;\n }\n // Trapping focus is only correct when the overlay actually covers\n // everything. Docked, it sits inside the panel and the rest of the page\n // is legitimately reachable, so trapping there would be the bug rather\n // than the fix.\n if (event.key !== 'Tab' || !expanded) return;\n // `aria-modal` only TELLS assistive technology this is modal; it does not\n // make it so. Without this, Tab walks straight out of the overlay into the\n // page behind it, which is still fully interactive underneath — a\n // keyboard user ends up operating a screen they cannot see.\n const focusable = dialogRef.current?.querySelectorAll<HTMLElement>('button:not([disabled])');\n if (!focusable || focusable.length === 0) return;\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n if (!first || !last) return;\n if (event.shiftKey && document.activeElement === first) {\n event.preventDefault();\n last.focus();\n } else if (!event.shiftKey && document.activeElement === last) {\n event.preventDefault();\n first.focus();\n }\n };\n window.addEventListener('keydown', onKeyDown);\n return () => window.removeEventListener('keydown', onKeyDown);\n }, [onEnd, expanded]);\n\n // Muted is reported ALONGSIDE the phase, not instead of it: the assistant may\n // still be speaking with the microphone off, and saying only \"Microphone off\"\n // would misreport that.\n const phaseText =\n phase === 'thinking'\n ? tr('healthybowl.assistant.voiceSession.thinking', 'Thinking…')\n : phase === 'speaking'\n ? tr('healthybowl.assistant.voiceSession.speaking', 'Speaking — tap to stop')\n : muted\n ? tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')\n : tr('healthybowl.assistant.voiceSession.listening', 'Listening…');\n\n const status =\n error !== null\n ? errorMessage(error, tr)\n : muted && phase !== 'listening'\n ? `${phaseText} · ${tr('healthybowl.assistant.voiceSession.muted', 'Microphone off')}`\n : phaseText;\n\n // While speaking, the caption shows the REPLY; otherwise what we have heard.\n // Showing the stale transcript under the assistant's own voice reads as a\n // mis-transcription of the assistant, which is worse than showing nothing.\n const caption = phase === 'speaking' ? spoken : spokenSoFar(session);\n\n return (\n <div\n ref={dialogRef}\n className={`flex flex-col items-center justify-between bg-bg-sunken ${\n expanded ? 'fixed inset-0 z-[60] px-6 py-10' : 'absolute inset-0 z-20 px-4 py-6'\n }`}\n role=\"dialog\"\n // Only modal when it really is: docked, the page behind stays usable.\n // `undefined` rather than `false` — the ARIA default is already false, and\n // some older assistive technology treats an explicit \"false\" on a dialog\n // as still modal.\n aria-modal={expanded || undefined}\n aria-label={tr('healthybowl.assistant.voiceSession.title', 'Voice conversation')}\n data-testid=\"assistant-voice-session\"\n >\n {/* 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 className={`absolute ${expanded ? 'right-6 top-6 size-14' : 'right-3 top-3 size-11'} 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 aria-label={tr('healthybowl.assistant.voiceSession.end', 'End the voice conversation')}\n data-testid=\"assistant-voice-end\"\n >\n <X className={expanded ? 'size-6' : 'size-5'} />\n </button>\n\n {/* The session's single live region. It has real words, unlike the orb. */}\n <div className=\"flex flex-col items-center gap-1 px-14\">\n <p className=\"text-sm text-text-muted\" role=\"status\" aria-live=\"polite\" data-testid=\"assistant-voice-status\">\n {status}\n </p>\n {/* A dead microphone used to look exactly like a live one. Whatever else\n happens, the session must never claim to be listening in silence. */}\n {notice && error === null ? (\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 {/* Padded so the pill and caption never collide with the corner controls\n in a docked panel only a few hundred pixels wide. */}\n <div className=\"flex min-h-0 w-full flex-1 flex-col items-center justify-center gap-4 px-14\">\n {/* The running conversation, as Gemini shows it — so a second question\n in the same session has the first still visible. Oldest first, with\n the newest pinned at the bottom next to the orb. */}\n {turns.length > 0 ? (\n <div\n className={`flex w-full flex-1 flex-col justify-end gap-2 overflow-y-auto text-sm ${expanded ? 'max-w-3xl' : 'max-w-md'}`}\n data-testid=\"assistant-voice-turns\"\n >\n {turns.map((turn) => (\n <p\n key={turn.id}\n className={\n turn.role === 'user'\n ? 'self-end rounded-2xl bg-bg-elevated px-3 py-1.5 text-text-primary'\n : 'self-start text-text-secondary'\n }\n >\n {turn.text}\n </p>\n ))}\n </div>\n ) : null}\n\n <AssistantVoiceOrb\n session={session}\n compact={!expanded}\n onPress={phase === 'speaking' ? onInterrupt : onToggleMute}\n label={\n phase === 'speaking'\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 {/* The LIVE caption: what is being said right now, before it is\n finalised into the conversation. `turns` only holds messages that\n already reached history, so without this the in-progress utterance\n appears nowhere and the session looks deaf while it is working. */}\n {caption ? (\n <p\n className={`text-center leading-relaxed text-text-secondary ${expanded ? 'max-w-3xl text-2xl font-semibold' : 'line-clamp-3 max-w-md text-base'}`}\n data-testid=\"assistant-voice-caption\"\n >\n {caption}\n </p>\n ) : null}\n </div>\n\n <button\n type=\"button\"\n onClick={() => setExpanded((current) => !current)}\n className={`absolute ${expanded ? 'bottom-6 left-6 size-14' : '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 aria-pressed={expanded}\n aria-label={\n expanded\n ? tr('healthybowl.assistant.voiceSession.collapse', 'Fit the conversation back into the panel')\n : tr('healthybowl.assistant.voiceSession.expand', 'Expand the conversation to full screen')\n }\n data-testid=\"assistant-voice-expand\"\n >\n {expanded ? <Minimize2 className=\"size-5\" /> : <Maximize2 className=\"size-5\" />}\n </button>\n </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":";;;;;;;AAyCA,IAAa,KAAoC,EAC/C,YACA,WAAQ,CAAC,GACT,YAAS,MACT,WACA,gBACA,iBACA,eACI;CACJ,IAAM,IAAK,EAAM,GACX,EAAE,UAAO,UAAO,aAAU,GAC1B,IAAS,EAA0B,IAAI,GACvC,IAAY,EAAuB,IAAI,GAUvC,CAAC,GAAU,KAAe,EAAS,EAAK;CAc9C,AAJA,QAAgB;EACd,EAAO,SAAS,MAAM;CACxB,GAAG,CAAC,CAAC,GAEL,QAAgB;EACd,IAAM,KAAa,MAAyB;GAC1C,IAAI,EAAM,QAAQ,UAAU;IAC1B,EAAM;IACN;GACF;GAKA,IAAI,EAAM,QAAQ,SAAS,CAAC,GAAU;GAKtC,IAAM,IAAY,EAAU,SAAS,iBAA8B,wBAAwB;GAC3F,IAAI,CAAC,KAAa,EAAU,WAAW,GAAG;GAC1C,IAAM,IAAQ,EAAU,IAClB,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AACF"}
|
|
@@ -69,7 +69,7 @@ function b({ onSubmit: b, latestReply: x, language: S }) {
|
|
|
69
69
|
}) : V.error === "language-not-supported" ? T({
|
|
70
70
|
type: "fail",
|
|
71
71
|
error: "no-speech-support"
|
|
72
|
-
}) : V.error === "network"
|
|
72
|
+
}) : V.error === "network" ? I("network") : V.error === "unknown" && I("recognition-failed");
|
|
73
73
|
}, [V.error]), u(() => {
|
|
74
74
|
if (!i(w) || V.isListening) return;
|
|
75
75
|
let e = setTimeout(() => I("not-capturing"), _);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useVoiceSession.js","names":[],"sources":["../../src/hooks/useVoiceSession.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react';\nimport { useVoiceInput } from './useVoiceInput';\nimport { useAssistantSpeech } from '../components/assistant/AssistantSpeechProvider';\nimport {\n INITIAL_SESSION,\n SILENCE_SUBMIT_MS,\n isCapturing,\n isSubmittable,\n planReplyConsumption,\n spokenSoFar,\n type VoiceSessionEvent,\n type VoiceSessionSnapshot,\n voiceSessionReducer,\n} from '../utils/voiceSession';\n\n/**\n * How long to wait for playback to actually start before assuming it never will.\n *\n * Generous enough to cover a hosted round trip (the voice is fetched, not local)\n * and short enough that a silent failure does not strand the session.\n */\nconst SPEECH_START_GRACE_MS = 4000;\n\n/**\n * How long the assistant's last reply stays usable as an echo reference after\n * playback ends.\n *\n * The recogniser emits a trailing FINAL result for speaker leakage a beat after\n * the audio stops. Without this window that result is treated as a fresh user\n * utterance and submitted, and the assistant answers itself — indefinitely.\n */\nconst ECHO_GRACE_MS = 2500;\n\n/**\n * How long the session may claim to be listening while the recogniser is not\n * actually running before saying so.\n *\n * Covers the permission prompt and the recogniser's own start-up, and is short\n * enough that a dead microphone is reported rather than mimed.\n */\nconst CAPTURE_START_GRACE_MS = 5000;\n\n/**\n * How long to listen with NOTHING heard at all before hinting that we may not\n * be hearing the user.\n *\n * Deliberately generous: a person thinking before they speak is normal, and a\n * hint that fires during a pause would be worse than no hint.\n */\nconst NOTHING_HEARD_MS = 12000;\n\n/**\n * A problem worth TELLING the user about that does not warrant killing the\n * session.\n *\n * These exist because the previous behaviour was the failure mode this whole\n * feature keeps hitting: the overlay said \"Listening…\" while the recogniser was\n * dead, and nothing anywhere said otherwise. `useVoiceInput` reports `network`\n * and `unknown` and the session ignored both.\n */\nexport type VoiceSessionNotice = 'network' | 'not-capturing' | 'nothing-heard';\n\n/** 44 bytes of silence — just enough to satisfy an autoplay unlock. */\nconst SILENT_WAV = 'data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA=';\n\ninterface Options {\n /** Send a turn. The reply is observed via `latestReply`, not returned here. */\n onSubmit: (text: string) => void;\n /**\n * Id + text of the newest assistant reply. A CHANGE of id is what advances\n * the session out of `thinking` — the text alone is not enough, because two\n * consecutive replies can be identical.\n */\n latestReply: { id: string; text: string } | null;\n /** Language the user is speaking, so the recogniser is pointed correctly. */\n language: string;\n}\n\n/**\n * Drives a live voice conversation (BOFF-7120).\n *\n * Deliberately thin: the loop itself is `voiceSessionReducer`, which is pure and\n * tested, and playback is the assistant's EXISTING auto-speak path rather than a\n * second speaking mechanism. Reusing auto-speak is what keeps the \"never speak a\n * reply in a language this device has no voice for\" guarantee from BOFF-7106/7107\n * true inside the session too — a bespoke playback path here would have quietly\n * bypassed all of it.\n *\n * What this hook owns is only the parts a reducer cannot: the silence timer, the\n * microphone's lifetime, and turning \"auto-speak is currently on\" back off again\n * when the session ends.\n */\nexport function useVoiceSession({ onSubmit, latestReply, language }: Options) {\n /**\n * What the assistant is saying right now, so the reducer can tell an\n * interruption from its own voice echoing back through the speaker. Held in a\n * ref so the reducer identity stays stable across renders.\n */\n const spokenTextRef = useRef<string | null>(null);\n const reduce = useCallback(\n (snapshot: VoiceSessionSnapshot, event: VoiceSessionEvent) =>\n voiceSessionReducer(snapshot, event, spokenTextRef.current),\n []\n );\n const [session, dispatch] = useReducer(reduce, INITIAL_SESSION);\n const speech = useAssistantSpeech();\n const { autoSpeakEnabled, setAutoSpeak, speakingMessageId, stop: stopSpeaking } = speech;\n\n const silenceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n /** Auto-speak as the user had it, so ending the session restores their choice. */\n const priorAutoSpeak = useRef<boolean | null>(null);\n /** The reply id already consumed, so one reply cannot advance two turns. */\n const consumedReplyId = useRef<string | null>(null);\n const wasSpeaking = useRef(false);\n const [notice, setNotice] = useState<VoiceSessionNotice | null>(null);\n\n const sessionRef = useRef(session);\n sessionRef.current = session;\n\n /**\n * The latest reply, readable from `start` without making it a dependency.\n *\n * `start` is a `useCallback` the UI holds across renders; adding `latestReply`\n * to its deps would rebuild the handler every time a message arrives.\n */\n const latestReplyRef = useRef(latestReply);\n latestReplyRef.current = latestReply;\n\n // The echo reference: the reply being spoken, held for a grace period after\n // playback stops. Cleared only once that window expires, so the recogniser's\n // trailing final result is still recognisable as echo.\n useEffect(() => {\n if (session.phase === 'speaking') {\n spokenTextRef.current = latestReply?.text ?? null;\n return;\n }\n if (spokenTextRef.current === null) return;\n const timer = setTimeout(() => {\n spokenTextRef.current = null;\n }, ECHO_GRACE_MS);\n return () => clearTimeout(timer);\n }, [session.phase, latestReply]);\n\n const handleSpeech = useCallback((transcript: string, final: boolean) => {\n dispatch({ type: 'speech', transcript, final });\n }, []);\n\n /**\n * Cut the assistant off. An explicit tap, never inferred from audio — the\n * microphone is closed while it speaks, precisely so its own voice cannot be\n * mistaken for the user's.\n */\n const interrupt = useCallback(() => {\n stopSpeaking();\n dispatch({ type: 'interrupt' });\n }, [stopSpeaking]);\n\n // `onFinalize` delivers each NEWLY finalised phrase on its own, so these are\n // committed and accumulated by the reducer rather than replacing what came\n // before — see the composer's `appendTranscript` for the same contract.\n const handleFinal = useCallback((phrase: string) => handleSpeech(phrase, true), [handleSpeech]);\n const voice = useVoiceInput({ onFinalize: handleFinal, language });\n\n // Interim results are what make barge-in feel immediate; waiting for the\n // recogniser to finalise would leave the assistant talking over the user.\n useEffect(() => {\n if (voice.interim) handleSpeech(voice.interim, false);\n }, [voice.interim, handleSpeech]);\n\n // Silence submits the turn. Restarted on every new fragment, so the timer\n // measures silence rather than elapsed time since the turn began.\n useEffect(() => {\n if (silenceTimer.current) clearTimeout(silenceTimer.current);\n if (session.phase !== 'listening' || session.muted || !isSubmittable(spokenSoFar(session))) return;\n silenceTimer.current = setTimeout(() => dispatch({ type: 'silence' }), SILENCE_SUBMIT_MS);\n return () => {\n if (silenceTimer.current) clearTimeout(silenceTimer.current);\n };\n }, [session]);\n\n // Submitting is a side effect OF entering `thinking`, not part of the\n // reduction — the reducer stays pure.\n const pendingAtSubmit = useRef('');\n if (session.phase === 'listening') pendingAtSubmit.current = spokenSoFar(session);\n useEffect(() => {\n if (session.phase !== 'thinking') return;\n const text = pendingAtSubmit.current.trim();\n if (text) onSubmit(text);\n // `onSubmit` deliberately not a dependency: a parent that recreates it each\n // render would otherwise resubmit the same turn repeatedly.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [session.phase]);\n\n /**\n * A NEW reply id advances the session. Guarded so a re-render, or two\n * identical answers in a row, cannot double-advance it.\n *\n * ★ A reply that lands while we are NOT thinking is CLAIMED, not ignored.\n *\n * Interrupting only stops playback — nothing cancels the model, so the\n * abandoned answer still arrives seconds later, while the phase is\n * `listening`. The old guard returned early WITHOUT recording its id, which\n * left it sitting there unconsumed; the next question then entered\n * `thinking`, found that stale reply, and spoke the answer to the question\n * the user had already cut off. Ending and restarting a session had the same\n * shape.\n *\n * So the rule is: a reply arriving outside a thinking phase belongs to a turn\n * that is over. Record it so it can never advance a LATER turn, and do not\n * act on it. This is the general form of the seeding fix — that one stopped\n * the FIRST turn consuming a persisted reply, this one stops every abandoned\n * turn doing the same thing.\n */\n useEffect(() => {\n const plan = planReplyConsumption(latestReply?.id, session.phase, consumedReplyId.current);\n if (!plan.claim) return;\n consumedReplyId.current = latestReply?.id ?? null;\n if (plan.advance && latestReply) dispatch({ type: 'reply', text: latestReply.text });\n }, [latestReply, session.phase]);\n\n // Playback finishing returns us to listening, detected on the FALLING edge of\n // `speakingMessageId`.\n useEffect(() => {\n const speakingNow = speakingMessageId !== null;\n if (wasSpeaking.current && !speakingNow) dispatch({ type: 'speech-ended' });\n wasSpeaking.current = speakingNow;\n }, [speakingMessageId]);\n\n /**\n * ★ A falling edge needs a RISING edge first.\n *\n * When a reply is never spoken at all — no installed voice for that language,\n * or the browser's autoplay policy refuses because auto-speak is not a user\n * gesture — `speakingMessageId` never becomes non-null, so the effect above\n * can never fire and the session hangs in `speaking` forever with the\n * microphone open and no way back except ending it.\n *\n * So entering `speaking` starts a watchdog: if nothing has actually begun\n * speaking shortly after, the turn is handed back and the conversation\n * continues silently rather than dying.\n */\n /**\n * ★ Clear the \"we can't hear you\" hint the moment listening ends.\n *\n * It fired after 12s of silence and then had no path back: nothing cleared it\n * on LEAVING `listening`, so it stayed on screen through \"Thinking…\", through\n * the assistant speaking, and into every later turn. On a screenshot taken\n * mid-reply it claimed the microphone was dead while the assistant was\n * talking — a warning that is not merely stale but false.\n */\n useEffect(() => {\n if (session.phase === 'listening') return;\n setNotice((current) => (current === 'nothing-heard' ? null : current));\n }, [session.phase]);\n\n useEffect(() => {\n if (session.phase !== 'speaking' || speakingMessageId !== null) return;\n const timer = setTimeout(() => {\n if (!wasSpeaking.current) dispatch({ type: 'speech-ended' });\n }, SPEECH_START_GRACE_MS);\n return () => clearTimeout(timer);\n }, [session.phase, speakingMessageId]);\n\n // The microphone follows the state machine, including while the assistant\n // speaks — barge-in is impossible with a closed microphone.\n useEffect(() => {\n if (isCapturing(session)) {\n if (!voice.isListening) voice.start();\n } else if (voice.isListening) {\n voice.stop();\n }\n }, [session, voice]);\n\n // Only the FATAL recognition errors end the session. `no-speech`, `network`\n // and `unknown` are transient — the recogniser recovers from them, and tearing\n // the session down on a moment's silence or a network blip would be worse than\n // the problem.\n useEffect(() => {\n if (voice.error === 'not-allowed' || voice.error === 'audio-capture') {\n dispatch({ type: 'fail', error: 'mic-denied' });\n } else if (voice.error === 'language-not-supported') {\n dispatch({ type: 'fail', error: 'no-speech-support' });\n } else if (voice.error === 'network') {\n // Chrome's recogniser is a NETWORK service. Losing it leaves the session\n // deaf while still looking alive, so it is reported rather than ignored —\n // but not fatal, because it recovers on its own.\n setNotice('network');\n }\n }, [voice.error]);\n\n // Say so when we claim to be listening but the recogniser never actually\n // started. `useVoiceInput.start()` swallows a throw and simply leaves\n // `isListening` false, which previously produced a silent, permanent\n // \"Listening…\".\n useEffect(() => {\n if (!isCapturing(session) || voice.isListening) return;\n const timer = setTimeout(() => setNotice('not-capturing'), CAPTURE_START_GRACE_MS);\n return () => clearTimeout(timer);\n }, [session, voice.isListening]);\n\n // And say so when the microphone IS running but has heard nothing at all.\n useEffect(() => {\n if (session.phase !== 'listening' || session.muted || !voice.isListening) return;\n if (spokenSoFar(session) !== '') return;\n const timer = setTimeout(() => setNotice('nothing-heard'), NOTHING_HEARD_MS);\n return () => clearTimeout(timer);\n }, [session, voice.isListening]);\n\n // Any successful capture clears the complaint — the recogniser recovered.\n useEffect(() => {\n if (spokenSoFar(session) !== '') setNotice(null);\n }, [session]);\n\n const start = useCallback(() => {\n if (!voice.isSupported) {\n dispatch({ type: 'fail', error: 'no-speech-support' });\n return;\n }\n if (speech.isBlocked) {\n dispatch({ type: 'fail', error: 'no-voice-support' });\n return;\n }\n // Replies must be spoken for a voice conversation to be a conversation, so\n // auto-speak is forced on for the session and the user's own setting is\n // restored on exit.\n // ★ Unlock audio while we still hold a user gesture.\n //\n // iOS refuses `speechSynthesis.speak()` unless it originates from a user\n // interaction. In a session the reply arrives asynchronously and auto-speak\n // fires on its own, which is NOT a gesture — so on iPhone the assistant\n // answered on screen and stayed silent. Speaking an empty utterance inside\n // this click unlocks synthesis for the rest of the session.\n // BOTH media paths, because they are gated independently. `speechSynthesis`\n // is what the device engine uses; the hosted engine plays an\n // `HTMLAudioElement` (`new Audio(...).play()` in hostedTtsSpeechEngine), and\n // unlocking one does NOT unlock the other. Priming only synthesis would work\n // today and go silent again the moment hosted TTS is switched on — the same\n // iOS silence, reintroduced by a fix for it.\n try {\n const synthesis = typeof window !== 'undefined' ? window.speechSynthesis : null;\n if (synthesis && typeof window.SpeechSynthesisUtterance === 'function') {\n const primer = new window.SpeechSynthesisUtterance('');\n primer.volume = 0;\n synthesis.speak(primer);\n }\n } catch {\n // Best effort: a platform that throws here is one where playback was\n // never going to work, and the watchdog reports that.\n }\n\n try {\n if (typeof window !== 'undefined' && typeof window.Audio === 'function') {\n // A minimal silent WAV. Playing it inside the gesture is what grants the\n // media element permission for the rest of the session.\n const silent = new window.Audio(SILENT_WAV);\n silent.volume = 0;\n void silent.play().catch(() => {});\n }\n } catch {\n /* same rationale as above */\n }\n\n priorAutoSpeak.current = autoSpeakEnabled;\n if (!autoSpeakEnabled) setAutoSpeak(true);\n setNotice(null);\n\n /**\n * ★ Claim whatever reply already exists, so the first turn cannot consume it.\n *\n * `consumedReplyId` starts null, and conversations are persisted — so on the\n * first turn of a reopened session `latestReply` is the PREVIOUS answer. The\n * reply effect fired the moment the phase became `thinking`, consumed that\n * stale answer and advanced to `speaking`. Nothing was actually playing, so\n * the watchdog handed the turn back to `listening` while the real reply was\n * still in flight — with the echo reference already cleared. The microphone\n * was then open when the real answer came out of the speaker, transcribed\n * it, and submitted the assistant's own words as the next question.\n *\n * It never re-synced either: the real reply then arrived while the phase was\n * `listening`, so the effect returned early without updating the id, and\n * every following turn repeated the same stale advance. That is the \"it\n * gives result different things\" report, and it is not mis-hearing anyone.\n */\n consumedReplyId.current = latestReplyRef.current?.id ?? null;\n dispatch({ type: 'start' });\n }, [voice.isSupported, speech.isBlocked, autoSpeakEnabled, setAutoSpeak]);\n\n const end = useCallback(() => {\n dispatch({ type: 'end' });\n stopSpeaking();\n if (priorAutoSpeak.current !== null) setAutoSpeak(priorAutoSpeak.current);\n priorAutoSpeak.current = null;\n }, [stopSpeaking, setAutoSpeak]);\n\n const toggleMute = useCallback(() => {\n dispatch({ type: 'mute', muted: !sessionRef.current.muted });\n }, []);\n\n // Leaving the panel mid-session must not leave the microphone open or the\n // user's auto-speak preference flipped.\n useEffect(\n () => () => {\n if (priorAutoSpeak.current !== null) setAutoSpeak(priorAutoSpeak.current);\n },\n [setAutoSpeak]\n );\n\n return useMemo(\n () => ({\n session,\n /** A recoverable problem worth showing, or null when all is well. */\n notice,\n /** Whether the microphone is genuinely capturing right now. */\n capturing: voice.isListening,\n /** True once started and not yet ended — what decides whether to render. */\n active: session.phase !== 'idle' && session.phase !== 'ended',\n /** Can a session be offered at all on this device? */\n available: voice.isSupported && !speech.isBlocked,\n start,\n end,\n toggleMute,\n interrupt,\n }),\n [session, notice, voice.isListening, voice.isSupported, speech.isBlocked, start, end, toggleMute, interrupt]\n );\n}\n"],"mappings":";;;;;AAqBA,IAAM,IAAwB,KAUxB,IAAgB,MAShB,IAAyB,KASzB,IAAmB,MAcnB,IAAa;AA6BnB,SAAgB,EAAgB,EAAE,aAAU,gBAAa,eAAqB;CAM5E,IAAM,IAAgB,EAAsB,IAAI,GAM1C,CAAC,GAAS,KAAY,EALb,GACZ,GAAgC,MAC/B,EAAoB,GAAU,GAAO,EAAc,OAAO,GAC5D,CAAC,CAEoC,GAAQ,CAAe,GACxD,IAAS,EAAmB,GAC5B,EAAE,qBAAkB,iBAAc,sBAAmB,MAAM,MAAiB,GAE5E,IAAe,EAA6C,IAAI,GAEhE,IAAiB,EAAuB,IAAI,GAE5C,IAAkB,EAAsB,IAAI,GAC5C,IAAc,EAAO,EAAK,GAC1B,CAAC,GAAQ,KAAa,EAAoC,IAAI,GAE9D,IAAa,EAAO,CAAO;CACjC,EAAW,UAAU;CAQrB,IAAM,IAAiB,EAAO,CAAW;CAMzC,AALA,EAAe,UAAU,GAKzB,QAAgB;EACd,IAAI,EAAQ,UAAU,YAAY;GAChC,EAAc,UAAU,GAAa,QAAQ;GAC7C;EACF;EACA,IAAI,EAAc,YAAY,M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GAAc,CAAY,CAAC,GAEzB,IAAa,QAAkB;EACnC,EAAS;GAAE,MAAM;GAAQ,OAAO,CAAC,EAAW,QAAQ;EAAM,CAAC;CAC7D,GAAG,CAAC,CAAC;CAWL,OAPA,cACc;EACV,AAAI,EAAe,YAAY,QAAM,EAAa,EAAe,OAAO;CAC1E,GACA,CAAC,CAAY,CACf,GAEO,SACE;EACL;EAEA;EAEA,WAAW,EAAM;EAEjB,QAAQ,EAAQ,UAAU,UAAU,EAAQ,UAAU;EAEtD,WAAW,EAAM,eAAe,CAAC,EAAO;EACxC;EACA;EACA;EACA;CACF,IACA;EAAC;EAAS;EAAQ,EAAM;EAAa,EAAM;EAAa,EAAO;EAAW;EAAO;EAAK;EAAY;CAAS,CAC7G;AACF"}
|
|
1
|
+
{"version":3,"file":"useVoiceSession.js","names":[],"sources":["../../src/hooks/useVoiceSession.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from 'react';\nimport { useVoiceInput } from './useVoiceInput';\nimport { useAssistantSpeech } from '../components/assistant/AssistantSpeechProvider';\nimport {\n INITIAL_SESSION,\n SILENCE_SUBMIT_MS,\n isCapturing,\n isSubmittable,\n planReplyConsumption,\n spokenSoFar,\n type VoiceSessionEvent,\n type VoiceSessionSnapshot,\n voiceSessionReducer,\n} from '../utils/voiceSession';\n\n/**\n * How long to wait for playback to actually start before assuming it never will.\n *\n * Generous enough to cover a hosted round trip (the voice is fetched, not local)\n * and short enough that a silent failure does not strand the session.\n */\nconst SPEECH_START_GRACE_MS = 4000;\n\n/**\n * How long the assistant's last reply stays usable as an echo reference after\n * playback ends.\n *\n * The recogniser emits a trailing FINAL result for speaker leakage a beat after\n * the audio stops. Without this window that result is treated as a fresh user\n * utterance and submitted, and the assistant answers itself — indefinitely.\n */\nconst ECHO_GRACE_MS = 2500;\n\n/**\n * How long the session may claim to be listening while the recogniser is not\n * actually running before saying so.\n *\n * Covers the permission prompt and the recogniser's own start-up, and is short\n * enough that a dead microphone is reported rather than mimed.\n */\nconst CAPTURE_START_GRACE_MS = 5000;\n\n/**\n * How long to listen with NOTHING heard at all before hinting that we may not\n * be hearing the user.\n *\n * Deliberately generous: a person thinking before they speak is normal, and a\n * hint that fires during a pause would be worse than no hint.\n */\nconst NOTHING_HEARD_MS = 12000;\n\n/**\n * A problem worth TELLING the user about that does not warrant killing the\n * session.\n *\n * These exist because the previous behaviour was the failure mode this whole\n * feature keeps hitting: the overlay said \"Listening…\" while the recogniser was\n * dead, and nothing anywhere said otherwise. `useVoiceInput` reports `network`\n * and `unknown` and the session ignored both.\n */\nexport type VoiceSessionNotice = 'network' | 'not-capturing' | 'nothing-heard' | 'recognition-failed';\n\n/** 44 bytes of silence — just enough to satisfy an autoplay unlock. */\nconst SILENT_WAV = 'data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA=';\n\ninterface Options {\n /** Send a turn. The reply is observed via `latestReply`, not returned here. */\n onSubmit: (text: string) => void;\n /**\n * Id + text of the newest assistant reply. A CHANGE of id is what advances\n * the session out of `thinking` — the text alone is not enough, because two\n * consecutive replies can be identical.\n */\n latestReply: { id: string; text: string } | null;\n /** Language the user is speaking, so the recogniser is pointed correctly. */\n language: string;\n}\n\n/**\n * Drives a live voice conversation (BOFF-7120).\n *\n * Deliberately thin: the loop itself is `voiceSessionReducer`, which is pure and\n * tested, and playback is the assistant's EXISTING auto-speak path rather than a\n * second speaking mechanism. Reusing auto-speak is what keeps the \"never speak a\n * reply in a language this device has no voice for\" guarantee from BOFF-7106/7107\n * true inside the session too — a bespoke playback path here would have quietly\n * bypassed all of it.\n *\n * What this hook owns is only the parts a reducer cannot: the silence timer, the\n * microphone's lifetime, and turning \"auto-speak is currently on\" back off again\n * when the session ends.\n */\nexport function useVoiceSession({ onSubmit, latestReply, language }: Options) {\n /**\n * What the assistant is saying right now, so the reducer can tell an\n * interruption from its own voice echoing back through the speaker. Held in a\n * ref so the reducer identity stays stable across renders.\n */\n const spokenTextRef = useRef<string | null>(null);\n const reduce = useCallback(\n (snapshot: VoiceSessionSnapshot, event: VoiceSessionEvent) =>\n voiceSessionReducer(snapshot, event, spokenTextRef.current),\n []\n );\n const [session, dispatch] = useReducer(reduce, INITIAL_SESSION);\n const speech = useAssistantSpeech();\n const { autoSpeakEnabled, setAutoSpeak, speakingMessageId, stop: stopSpeaking } = speech;\n\n const silenceTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n /** Auto-speak as the user had it, so ending the session restores their choice. */\n const priorAutoSpeak = useRef<boolean | null>(null);\n /** The reply id already consumed, so one reply cannot advance two turns. */\n const consumedReplyId = useRef<string | null>(null);\n const wasSpeaking = useRef(false);\n const [notice, setNotice] = useState<VoiceSessionNotice | null>(null);\n\n const sessionRef = useRef(session);\n sessionRef.current = session;\n\n /**\n * The latest reply, readable from `start` without making it a dependency.\n *\n * `start` is a `useCallback` the UI holds across renders; adding `latestReply`\n * to its deps would rebuild the handler every time a message arrives.\n */\n const latestReplyRef = useRef(latestReply);\n latestReplyRef.current = latestReply;\n\n // The echo reference: the reply being spoken, held for a grace period after\n // playback stops. Cleared only once that window expires, so the recogniser's\n // trailing final result is still recognisable as echo.\n useEffect(() => {\n if (session.phase === 'speaking') {\n spokenTextRef.current = latestReply?.text ?? null;\n return;\n }\n if (spokenTextRef.current === null) return;\n const timer = setTimeout(() => {\n spokenTextRef.current = null;\n }, ECHO_GRACE_MS);\n return () => clearTimeout(timer);\n }, [session.phase, latestReply]);\n\n const handleSpeech = useCallback((transcript: string, final: boolean) => {\n dispatch({ type: 'speech', transcript, final });\n }, []);\n\n /**\n * Cut the assistant off. An explicit tap, never inferred from audio — the\n * microphone is closed while it speaks, precisely so its own voice cannot be\n * mistaken for the user's.\n */\n const interrupt = useCallback(() => {\n stopSpeaking();\n dispatch({ type: 'interrupt' });\n }, [stopSpeaking]);\n\n // `onFinalize` delivers each NEWLY finalised phrase on its own, so these are\n // committed and accumulated by the reducer rather than replacing what came\n // before — see the composer's `appendTranscript` for the same contract.\n const handleFinal = useCallback((phrase: string) => handleSpeech(phrase, true), [handleSpeech]);\n const voice = useVoiceInput({ onFinalize: handleFinal, language });\n\n // Interim results are what make the live caption feel immediate — the user\n // sees their words as they say them rather than only after a pause.\n // (They are NOT barge-in: the microphone is closed while the assistant\n // speaks, so nothing can be heard to interrupt it. Interruption is the\n // explicit tap on the orb.)\n useEffect(() => {\n if (voice.interim) handleSpeech(voice.interim, false);\n }, [voice.interim, handleSpeech]);\n\n // Silence submits the turn. Restarted on every new fragment, so the timer\n // measures silence rather than elapsed time since the turn began.\n useEffect(() => {\n if (silenceTimer.current) clearTimeout(silenceTimer.current);\n if (session.phase !== 'listening' || session.muted || !isSubmittable(spokenSoFar(session))) return;\n silenceTimer.current = setTimeout(() => dispatch({ type: 'silence' }), SILENCE_SUBMIT_MS);\n return () => {\n if (silenceTimer.current) clearTimeout(silenceTimer.current);\n };\n }, [session]);\n\n // Submitting is a side effect OF entering `thinking`, not part of the\n // reduction — the reducer stays pure.\n const pendingAtSubmit = useRef('');\n if (session.phase === 'listening') pendingAtSubmit.current = spokenSoFar(session);\n useEffect(() => {\n if (session.phase !== 'thinking') return;\n const text = pendingAtSubmit.current.trim();\n if (text) onSubmit(text);\n // `onSubmit` deliberately not a dependency: a parent that recreates it each\n // render would otherwise resubmit the same turn repeatedly.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [session.phase]);\n\n /**\n * A NEW reply id advances the session. Guarded so a re-render, or two\n * identical answers in a row, cannot double-advance it.\n *\n * ★ A reply that lands while we are NOT thinking is CLAIMED, not ignored.\n *\n * Interrupting only stops playback — nothing cancels the model, so the\n * abandoned answer still arrives seconds later, while the phase is\n * `listening`. The old guard returned early WITHOUT recording its id, which\n * left it sitting there unconsumed; the next question then entered\n * `thinking`, found that stale reply, and spoke the answer to the question\n * the user had already cut off. Ending and restarting a session had the same\n * shape.\n *\n * So the rule is: a reply arriving outside a thinking phase belongs to a turn\n * that is over. Record it so it can never advance a LATER turn, and do not\n * act on it. This is the general form of the seeding fix — that one stopped\n * the FIRST turn consuming a persisted reply, this one stops every abandoned\n * turn doing the same thing.\n */\n useEffect(() => {\n const plan = planReplyConsumption(latestReply?.id, session.phase, consumedReplyId.current);\n if (!plan.claim) return;\n consumedReplyId.current = latestReply?.id ?? null;\n if (plan.advance && latestReply) dispatch({ type: 'reply', text: latestReply.text });\n }, [latestReply, session.phase]);\n\n // Playback finishing returns us to listening, detected on the FALLING edge of\n // `speakingMessageId`.\n useEffect(() => {\n const speakingNow = speakingMessageId !== null;\n if (wasSpeaking.current && !speakingNow) dispatch({ type: 'speech-ended' });\n wasSpeaking.current = speakingNow;\n }, [speakingMessageId]);\n\n /**\n * ★ A falling edge needs a RISING edge first.\n *\n * When a reply is never spoken at all — no installed voice for that language,\n * or the browser's autoplay policy refuses because auto-speak is not a user\n * gesture — `speakingMessageId` never becomes non-null, so the effect above\n * can never fire and the session hangs in `speaking` forever with the\n * microphone open and no way back except ending it.\n *\n * So entering `speaking` starts a watchdog: if nothing has actually begun\n * speaking shortly after, the turn is handed back and the conversation\n * continues silently rather than dying.\n */\n /**\n * ★ Clear the \"we can't hear you\" hint the moment listening ends.\n *\n * It fired after 12s of silence and then had no path back: nothing cleared it\n * on LEAVING `listening`, so it stayed on screen through \"Thinking…\", through\n * the assistant speaking, and into every later turn. On a screenshot taken\n * mid-reply it claimed the microphone was dead while the assistant was\n * talking — a warning that is not merely stale but false.\n */\n useEffect(() => {\n if (session.phase === 'listening') return;\n setNotice((current) => (current === 'nothing-heard' ? null : current));\n }, [session.phase]);\n\n useEffect(() => {\n if (session.phase !== 'speaking' || speakingMessageId !== null) return;\n const timer = setTimeout(() => {\n if (!wasSpeaking.current) dispatch({ type: 'speech-ended' });\n }, SPEECH_START_GRACE_MS);\n return () => clearTimeout(timer);\n }, [session.phase, speakingMessageId]);\n\n // The microphone follows the state machine: OPEN only while `listening`, and\n // closed for the whole `speaking` phase. That is what makes audio barge-in\n // impossible today — there is nothing listening to interrupt with. Cutting\n // the assistant off is the explicit tap on the orb.\n useEffect(() => {\n if (isCapturing(session)) {\n if (!voice.isListening) voice.start();\n } else if (voice.isListening) {\n voice.stop();\n }\n }, [session, voice]);\n\n // Only the FATAL recognition errors end the session. `no-speech`, `network`\n // and `unknown` are transient — the recogniser recovers from them, and tearing\n // the session down on a moment's silence or a network blip would be worse than\n // the problem.\n useEffect(() => {\n if (voice.error === 'not-allowed' || voice.error === 'audio-capture') {\n dispatch({ type: 'fail', error: 'mic-denied' });\n } else if (voice.error === 'language-not-supported') {\n dispatch({ type: 'fail', error: 'no-speech-support' });\n } else if (voice.error === 'network') {\n // Chrome's recogniser is a NETWORK service. Losing it leaves the session\n // deaf while still looking alive, so it is reported rather than ignored —\n // but not fatal, because it recovers on its own.\n setNotice('network');\n } else if (voice.error === 'unknown') {\n // ★ Previously fell through with NO branch, so an unrecognised recogniser\n // failure left the session looking healthy while hearing nothing — the\n // exact \"it says Listening but nothing happens\" failure this notice\n // mechanism exists to prevent. Not fatal: like `network`, the recogniser\n // often recovers, so it is reported rather than ending the session.\n setNotice('recognition-failed');\n }\n }, [voice.error]);\n\n // Say so when we claim to be listening but the recogniser never actually\n // started. `useVoiceInput.start()` swallows a throw and simply leaves\n // `isListening` false, which previously produced a silent, permanent\n // \"Listening…\".\n useEffect(() => {\n if (!isCapturing(session) || voice.isListening) return;\n const timer = setTimeout(() => setNotice('not-capturing'), CAPTURE_START_GRACE_MS);\n return () => clearTimeout(timer);\n }, [session, voice.isListening]);\n\n // And say so when the microphone IS running but has heard nothing at all.\n useEffect(() => {\n if (session.phase !== 'listening' || session.muted || !voice.isListening) return;\n if (spokenSoFar(session) !== '') return;\n const timer = setTimeout(() => setNotice('nothing-heard'), NOTHING_HEARD_MS);\n return () => clearTimeout(timer);\n }, [session, voice.isListening]);\n\n // Any successful capture clears the complaint — the recogniser recovered.\n useEffect(() => {\n if (spokenSoFar(session) !== '') setNotice(null);\n }, [session]);\n\n const start = useCallback(() => {\n if (!voice.isSupported) {\n dispatch({ type: 'fail', error: 'no-speech-support' });\n return;\n }\n if (speech.isBlocked) {\n dispatch({ type: 'fail', error: 'no-voice-support' });\n return;\n }\n // Replies must be spoken for a voice conversation to be a conversation, so\n // auto-speak is forced on for the session and the user's own setting is\n // restored on exit.\n // ★ Unlock audio while we still hold a user gesture.\n //\n // iOS refuses `speechSynthesis.speak()` unless it originates from a user\n // interaction. In a session the reply arrives asynchronously and auto-speak\n // fires on its own, which is NOT a gesture — so on iPhone the assistant\n // answered on screen and stayed silent. Speaking an empty utterance inside\n // this click unlocks synthesis for the rest of the session.\n // BOTH media paths, because they are gated independently. `speechSynthesis`\n // is what the device engine uses; the hosted engine plays an\n // `HTMLAudioElement` (`new Audio(...).play()` in hostedTtsSpeechEngine), and\n // unlocking one does NOT unlock the other. Priming only synthesis would work\n // today and go silent again the moment hosted TTS is switched on — the same\n // iOS silence, reintroduced by a fix for it.\n try {\n const synthesis = typeof window !== 'undefined' ? window.speechSynthesis : null;\n if (synthesis && typeof window.SpeechSynthesisUtterance === 'function') {\n const primer = new window.SpeechSynthesisUtterance('');\n primer.volume = 0;\n synthesis.speak(primer);\n }\n } catch {\n // Best effort: a platform that throws here is one where playback was\n // never going to work, and the watchdog reports that.\n }\n\n try {\n if (typeof window !== 'undefined' && typeof window.Audio === 'function') {\n // A minimal silent WAV. Playing it inside the gesture is what grants the\n // media element permission for the rest of the session.\n const silent = new window.Audio(SILENT_WAV);\n silent.volume = 0;\n void silent.play().catch(() => {});\n }\n } catch {\n /* same rationale as above */\n }\n\n priorAutoSpeak.current = autoSpeakEnabled;\n if (!autoSpeakEnabled) setAutoSpeak(true);\n setNotice(null);\n\n /**\n * ★ Claim whatever reply already exists, so the first turn cannot consume it.\n *\n * `consumedReplyId` starts null, and conversations are persisted — so on the\n * first turn of a reopened session `latestReply` is the PREVIOUS answer. The\n * reply effect fired the moment the phase became `thinking`, consumed that\n * stale answer and advanced to `speaking`. Nothing was actually playing, so\n * the watchdog handed the turn back to `listening` while the real reply was\n * still in flight — with the echo reference already cleared. The microphone\n * was then open when the real answer came out of the speaker, transcribed\n * it, and submitted the assistant's own words as the next question.\n *\n * It never re-synced either: the real reply then arrived while the phase was\n * `listening`, so the effect returned early without updating the id, and\n * every following turn repeated the same stale advance. That is the \"it\n * gives result different things\" report, and it is not mis-hearing anyone.\n */\n consumedReplyId.current = latestReplyRef.current?.id ?? null;\n dispatch({ type: 'start' });\n }, [voice.isSupported, speech.isBlocked, autoSpeakEnabled, setAutoSpeak]);\n\n const end = useCallback(() => {\n dispatch({ type: 'end' });\n stopSpeaking();\n if (priorAutoSpeak.current !== null) setAutoSpeak(priorAutoSpeak.current);\n priorAutoSpeak.current = null;\n }, [stopSpeaking, setAutoSpeak]);\n\n const toggleMute = useCallback(() => {\n dispatch({ type: 'mute', muted: !sessionRef.current.muted });\n }, []);\n\n // Leaving the panel mid-session must not leave the microphone open or the\n // user's auto-speak preference flipped.\n useEffect(\n () => () => {\n if (priorAutoSpeak.current !== null) setAutoSpeak(priorAutoSpeak.current);\n },\n [setAutoSpeak]\n );\n\n return useMemo(\n () => ({\n session,\n /** A recoverable problem worth showing, or null when all is well. */\n notice,\n /** Whether the microphone is genuinely capturing right now. */\n capturing: voice.isListening,\n /** True once started and not yet ended — what decides whether to render. */\n active: session.phase !== 'idle' && session.phase !== 'ended',\n /** Can a session be offered at all on this device? */\n available: voice.isSupported && !speech.isBlocked,\n start,\n end,\n toggleMute,\n interrupt,\n }),\n [session, notice, voice.isListening, voice.isSupported, speech.isBlocked, start, end, toggleMute, interrupt]\n );\n}\n"],"mappings":";;;;;AAqBA,IAAM,IAAwB,KAUxB,IAAgB,MAShB,IAAyB,KASzB,IAAmB,MAcnB,IAAa;AA6BnB,SAAgB,EAAgB,EAAE,aAAU,gBAAa,eAAqB;CAM5E,IAAM,IAAgB,EAAsB,IAAI,GAM1C,CAAC,GAAS,KAAY,EALb,GACZ,GAAgC,MAC/B,EAAoB,GAAU,GAAO,EAAc,O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U,YAAY;IAGvE,IAAM,IAAS,IAAI,OAAO,MAAM,CAAU;IAE1C,AADA,EAAO,SAAS,GAChB,EAAY,KAAK,EAAE,YAAY,CAAC,CAAC;GACnC;EACF,QAAQ,CAER;EAwBA,AAtBA,EAAe,UAAU,GACpB,KAAkB,EAAa,EAAI,GACxC,EAAU,IAAI,GAmBd,EAAgB,UAAU,EAAe,SAAS,MAAM,MACxD,EAAS,EAAE,MAAM,QAAQ,CAAC;CAC5B,GAAG;EAAC,EAAM;EAAa,EAAO;EAAW;EAAkB;CAAY,CAAC,GAElE,IAAM,QAAkB;EAI5B,AAHA,EAAS,EAAE,MAAM,MAAM,CAAC,GACxB,EAAa,GACT,EAAe,YAAY,QAAM,EAAa,EAAe,OAAO,GACxE,EAAe,UAAU;CAC3B,GAAG,CAAC,GAAc,CAAY,CAAC,GAEzB,IAAa,QAAkB;EACnC,EAAS;GAAE,MAAM;GAAQ,OAAO,CAAC,EAAW,QAAQ;EAAM,CAAC;CAC7D,GAAG,CAAC,CAAC;CAWL,OAPA,cACc;EACV,AAAI,EAAe,YAAY,QAAM,EAAa,EAAe,OAAO;CAC1E,GACA,CAAC,CAAY,CACf,GAEO,SACE;EACL;EAEA;EAEA,WAAW,EAAM;EAEjB,QAAQ,EAAQ,UAAU,UAAU,EAAQ,UAAU;EAEtD,WAAW,EAAM,eAAe,CAAC,EAAO;EACxC;EACA;EACA;EACA;CACF,IACA;EAAC;EAAS;EAAQ,EAAM;EAAa,EAAM;EAAa,EAAO;EAAW;EAAO;EAAK;EAAY;CAAS,CAC7G;AACF"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { browserSpeechEngine as e } from "./browserSpeechEngine.js";
|
|
2
|
-
import "./hostedVoiceCatalogue.js";
|
|
3
2
|
import { createHostedTtsEngine as t } from "./hostedTtsSpeechEngine.js";
|
|
4
3
|
import { createRoutingSpeechEngine as n } from "./routingSpeechEngine.js";
|
|
5
4
|
//#region src/services/speech/createSpeechEngine.ts
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createSpeechEngine.js","names":[],"sources":["../../../src/services/speech/createSpeechEngine.ts"],"sourcesContent":["/**\n * Which engine speaks — the single switch for the hosted-TTS rollout\n * (BOFF-7111).\n *\n * **Default is unchanged behaviour.** With no endpoint configured this returns\n * the device engine that ships today, so merging this changes nothing for\n * anyone.\n *\n * ★The endpoint MUST be resolved at RUNTIME, not from `import.meta.env`. This\n * microfe is published as a prebuilt package by its own CI, which has no such\n * variable, so a build-time constant is inlined to `undefined` and the whole\n * hosted path is eliminated before the host app ever consumes it — the flag\n * could then never be turned on at all. Verified against the published\n * `2026.829.4` bundle: `geocode.js` ships with its `import.meta.env` fallback\n * gone entirely, leaving only the runtime lookups. `configureGeocoder` exists\n * for exactly this reason and this mirrors it.\n *\n * The fallback is per-language, not global: a hosted vendor that cannot speak\n * the reply's language is worse than the device voice, not better, so\n *
|
|
1
|
+
{"version":3,"file":"createSpeechEngine.js","names":[],"sources":["../../../src/services/speech/createSpeechEngine.ts"],"sourcesContent":["/**\n * Which engine speaks — the single switch for the hosted-TTS rollout\n * (BOFF-7111).\n *\n * **Default is unchanged behaviour.** With no endpoint configured this returns\n * the device engine that ships today, so merging this changes nothing for\n * anyone.\n *\n * ★The endpoint MUST be resolved at RUNTIME, not from `import.meta.env`. This\n * microfe is published as a prebuilt package by its own CI, which has no such\n * variable, so a build-time constant is inlined to `undefined` and the whole\n * hosted path is eliminated before the host app ever consumes it — the flag\n * could then never be turned on at all. Verified against the published\n * `2026.829.4` bundle: `geocode.js` ships with its `import.meta.env` fallback\n * gone entirely, leaving only the runtime lookups. `configureGeocoder` exists\n * for exactly this reason and this mirrors it.\n *\n * The fallback is per-language, not global: a hosted vendor that cannot speak\n * the reply's language is worse than the device voice, not better, so\n * the routing engine decides per playback rather than once at startup.\n */\n\nimport { browserSpeechEngine } from './browserSpeechEngine';\nimport { createHostedTtsEngine } from './hostedTtsSpeechEngine';\nimport { createRoutingSpeechEngine } from './routingSpeechEngine';\nimport type { SpeechEngine } from './types';\n\nexport interface SpeechEngineConfig {\n /** Our proxy's URL. Empty/undefined keeps the device engine. */\n endpoint?: string | null;\n getHeaders?: () => Record<string, string>;\n fetchImpl?: typeof fetch;\n}\n\n/** Injected by the host app, which is the only build that knows the URL. */\nlet runtimeEndpoint: string | undefined;\nlet runtimeGetHeaders: (() => Record<string, string>) | undefined;\n\n/**\n * Point the assistant at a hosted TTS proxy.\n *\n * Called by the host shell's provider, exactly as `configureGeocoder` is. This\n * is the supported way to turn hosted speech on; the environment variable below\n * only ever works when this package is run directly (dev / standalone).\n *\n * ★ `getHeaders` is not optional in practice, only in the type. The proxy turns\n * text into audio the org is BILLED for, so an endpoint that accepts anonymous\n * POSTs is a metered API open to anyone who reads the bundle. The engine has\n * always supported per-request headers; until now nothing could reach that hook\n * from the host, which meant the only configuration this function could express\n * was an unauthenticated one. It is a function rather than a value because\n * access tokens expire and the engine outlives any one of them — reading a\n * token once at configure time would work until it rotated and then fail\n * exactly where it is hardest to notice, mid-reply.\n */\nexport function configureSpeechEngine(options: {\n ttsEndpoint?: string | null;\n getHeaders?: () => Record<string, string>;\n}): void {\n const endpoint = options.ttsEndpoint?.trim() || undefined;\n\n // ★ Idempotent because it is called from RENDER, exactly as `configureGeocoder`\n // is. That sibling gets away with an unconditional assignment; this one cannot.\n // `resetSpeechEngine()` drops the memoised engine, and the engine's identity is\n // a dependency of `AssistantSpeechProvider`'s effects (it takes\n // `engine = getSpeechEngine()` as a default prop) — so resetting on every\n // render would hand back a new object every render, re-running the voice\n // subscription continuously and cancelling playback mid-reply. Bailing out\n // when nothing changed keeps the singleton stable without asking every caller\n // to remember why.\n if (endpoint === runtimeEndpoint && options.getHeaders === runtimeGetHeaders) return;\n\n runtimeEndpoint = endpoint;\n runtimeGetHeaders = options.getHeaders;\n // The engine is memoised, so a real change must invalidate it or the setting\n // would silently not take effect.\n resetSpeechEngine();\n}\n\n/**\n * Read the rollout config.\n *\n * Order matters: explicit runtime configuration, then a global the host can set\n * before the bundle loads, and only then the build-time variable — which is\n * eliminated in the published package and therefore useful for local dev only.\n */\nexport function readSpeechEngineConfig(): SpeechEngineConfig {\n // `getHeaders` rides along with every source, not just the first: the window\n // global carries a URL only, and a host that sets it still needs its auth\n // headers to reach the engine.\n if (runtimeEndpoint) return { endpoint: runtimeEndpoint, getHeaders: runtimeGetHeaders };\n if (typeof window !== 'undefined') {\n const fromWindow = (window as unknown as { __HB_TTS_ENDPOINT__?: string }).__HB_TTS_ENDPOINT__;\n if (fromWindow) return { endpoint: fromWindow, getHeaders: runtimeGetHeaders };\n }\n const fromEnv =\n typeof import.meta !== 'undefined' ? (import.meta.env?.VITE_HB_TTS_ENDPOINT as string | undefined) : undefined;\n return { endpoint: fromEnv?.trim() || null };\n}\n\n/**\n * The engine to use, or the device engine when hosted TTS is not configured.\n *\n * Returns `null` for `hosted` when off, so callers can tell \"hosted is not\n * configured\" from \"hosted is configured but cannot speak this language\".\n */\nexport function createSpeechEngines(config: SpeechEngineConfig = readSpeechEngineConfig()): {\n device: SpeechEngine;\n hosted: SpeechEngine | null;\n} {\n const hosted = config.endpoint\n ? createHostedTtsEngine({\n endpoint: config.endpoint,\n getHeaders: config.getHeaders,\n fetchImpl: config.fetchImpl,\n })\n : null;\n return { device: browserSpeechEngine, hosted };\n}\n\n/**\n * The engine the assistant actually uses.\n *\n * A module-level singleton on purpose: the engine's identity appears in\n * `AssistantSpeechProvider`'s dependency arrays, so producing a new object per\n * render would re-run the voice subscription on every render.\n *\n * With no endpoint configured this IS `browserSpeechEngine` — `createRoutingSpeechEngine`\n * returns the device engine unchanged rather than wrapping it — so the default\n * path keeps today's behaviour and today's object identity.\n */\nlet cached: SpeechEngine | null = null;\n\nexport function getSpeechEngine(): SpeechEngine {\n if (!cached) cached = createRoutingSpeechEngine(createSpeechEngines());\n return cached;\n}\n\n/** Test seam: drop the singleton so the next call re-reads the config. */\nexport function resetSpeechEngine(): void {\n cached = null;\n}\n"],"mappings":";;;;AAmCA,IAAI,GACA;AAmBJ,SAAgB,EAAsB,GAG7B;CACP,IAAM,IAAW,EAAQ,aAAa,KAAK,KAAK,KAAA;CAW5C,MAAa,KAAmB,EAAQ,eAAe,MAE3D,IAAkB,GAClB,IAAoB,EAAQ,YAG5B,EAAkB;AACpB;AASA,SAAgB,IAA6C;CAI3D,IAAI,GAAiB,OAAO;EAAE,UAAU;EAAiB,YAAY;CAAkB;CACvF,IAAI,OAAO,SAAW,KAAa;EACjC,IAAM,IAAc,OAAuD;EAC3E,IAAI,GAAY,OAAO;GAAE,UAAU;GAAY,YAAY;EAAkB;CAC/E;CAGA,OAAO,EAAE,UAA6B,KAAK;AAC7C;AAQA,SAAgB,EAAoB,IAA6B,EAAuB,GAGtF;CAQA,OAAO;EAAE,QAAQ;EAAqB,QAPvB,EAAO,WAClB,EAAsB;GACpB,UAAU,EAAO;GACjB,YAAY,EAAO;GACnB,WAAW,EAAO;EACpB,CAAC,IACD;CACyC;AAC/C;AAaA,IAAI,IAA8B;AAElC,SAAgB,IAAgC;CAE9C,OADA,AAAa,MAAS,EAA0B,EAAoB,CAAC,GAC9D;AACT;AAGA,SAAgB,IAA0B;CACxC,IAAS;AACX"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"voiceSession.js","names":[],"sources":["../../src/utils/voiceSession.ts"],"sourcesContent":["/**\n * The voice-conversation state machine (BOFF-7120).\n *\n * A live voice session is a loop — listen, submit, wait, speak, listen again —\n * and every interesting decision in it is about TIMING and INTERRUPTION rather\n * than about rendering. Those decisions live here, with no DOM, no audio and no\n * React, for the same reason `browserSpeechEngine` pushed its logic into\n * `speakableText`/`speechVoices`: this repo's vitest runs in the `node`\n * environment, so anything touching `window` cannot be tested at all.\n *\n * ★ **The microphone is CLOSED while the assistant speaks.** It was open, so\n * that talking over the assistant could interrupt it, guarded by matching the\n * transcript against the text being spoken. That guard was too weak to survive\n * contact with reality: speech recognition of synthesised speech mis-hears it\n * (\"sow ragi\" -> \"so ragi\"), so exact containment fails, the mis-heard echo is\n * accepted as a new question, submitted, answered, spoken — and round it goes.\n * The operator hit this loop on a real device.\n *\n * Browsers do not give the Web Speech API the acoustic echo cancellation that a\n * native duplex app has, so there is no text-level fix for this. Interruption is\n * now an explicit tap instead, which is reliable, and the echo check survives\n * only as a guard on the moments just after playback stops.\n *\n * ★ **Mute is NOT a phase.** It is a property of the microphone, orthogonal to\n * where the conversation is. Modelling it as a state meant muting while the\n * assistant was thinking discarded the `thinking` phase, so the reply — already\n * in flight — was then ignored, and unmuting landed in `listening` with nothing\n * pending and nothing coming. The session dead-ended and the user's question was\n * silently lost.\n *\n * What this deliberately does NOT model: the assistant is turn-based\n * (speech -> text -> LLM -> text -> speech), so `thinking` is a real, visible\n * phase lasting seconds. A native speech-to-speech API would collapse\n * listening/thinking/speaking into one duplex stream; we are not that, and\n * pretending otherwise would hide latency the UI must show.\n */\n\n/** Where the CONVERSATION is. Independent of whether the mic is capturing. */\nexport type VoiceSessionPhase = 'idle' | 'listening' | 'thinking' | 'speaking' | 'ended';\n\nexport interface VoiceSessionSnapshot {\n phase: VoiceSessionPhase;\n /** Microphone off. Orthogonal to `phase` — see the header. */\n muted: boolean;\n /** FINALISED speech for the turn not yet submitted, accumulated. */\n pending: string;\n /** The recogniser's current guess, replaced wholesale until it finalises. */\n interim: string;\n /** Why the session stopped, when it stopped abnormally. */\n error: VoiceSessionError | null;\n}\n\n/**\n * Deliberately does NOT include a \"playback blocked\" variant. Nothing can\n * detect it — the speech provider does not surface a per-message playback\n * refusal — and the watchdog in `useVoiceSession` already recovers by handing\n * the turn back silently, which continues the conversation rather than killing\n * it. An error the code cannot raise is dead UI copy.\n */\nexport type VoiceSessionError = 'no-speech-support' | 'no-voice-support' | 'mic-denied';\n\nexport type VoiceSessionEvent =\n /** `final` distinguishes a committed phrase from a revisable guess. */\n | { type: 'start' }\n | { type: 'speech'; transcript: string; final: boolean }\n /** Nothing heard for `SILENCE_SUBMIT_MS`. */\n | { type: 'silence' }\n | { type: 'reply'; text: string }\n | { type: 'speech-ended' }\n | { type: 'mute'; muted: boolean }\n /** The user tapped to cut the assistant off. Explicit, not inferred. */\n | { type: 'interrupt' }\n | { type: 'fail'; error: VoiceSessionError }\n | { type: 'end' };\n\n/**\n * How long the user must stop talking before the turn is submitted.\n *\n * Long enough to survive a mid-sentence breath — a farmer describing a problem\n * pauses — and short enough that the session does not feel unresponsive. A\n * premature send truncates the question, which costs a whole 2-5s round trip to\n * recover from.\n *\n * ★ Raised from 1200ms because 1.2s does not survive an ordinary pause: the\n * operator reported being cut off mid-sentence, and the cost is worse than a\n * truncated prompt — once the turn is submitted the reducer discards every\n * `speech` event outside `listening`, so the rest of the sentence is not\n * queued, it is thrown away, and the assistant answers half a question.\n *\n * The asymmetry is what settles the number: waiting 800ms longer costs a moment\n * of silence, while cutting someone off costs the whole round trip AND makes\n * them repeat themselves.\n */\nexport const SILENCE_SUBMIT_MS = 2000;\n\n/** A turn is submitted only when there is something worth sending. */\nexport function isSubmittable(text: string): boolean {\n return text.trim().length > 0;\n}\n\n/** Everything heard this turn: committed phrases plus the current guess. */\nexport function spokenSoFar(snapshot: VoiceSessionSnapshot): string {\n return `${snapshot.pending} ${snapshot.interim}`.replace(/\\s+/g, ' ').trim();\n}\n\n/** Comparable form for echo detection: letters and digits only. */\nfunction normalise(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}]+/gu, ' ')\n .trim();\n}\n\n/**\n * Is this transcript the assistant's OWN voice coming back through the mic?\n *\n * The microphone stays open while the assistant speaks so interruption is\n * possible at all, which means on any device using a speaker the recogniser will\n * happily transcribe the reply. Every such transcript is long enough to pass a\n * length threshold, so without this the assistant interrupts ITSELF on the first\n * phrase it utters — the feature would be unusable on a phone held normally.\n *\n * Containment is the signal length cannot provide: whatever we are currently\n * speaking is known, so anything already inside it is echo, not a person.\n */\n/**\n * Below this many words, a transcript is treated as a person interrupting\n * rather than as the assistant's own voice.\n *\n * Containment alone cannot tell \"no\" (a correction) from \"no\" (a word inside a\n * long reply), and the assistant's own voice arrives as long phrases, not as\n * one or two words. Anything shorter is far more likely to be the user cutting\n * in — which is precisely the case that must not be swallowed.\n */\nconst ECHO_MIN_WORDS = 3;\n\nexport function isEcho(transcript: string, spokenText: string | null): boolean {\n if (!spokenText) return false;\n const heard = normalise(transcript);\n if (heard.length === 0) return true;\n\n // A short utterance during playback is a correction, not an echo.\n if (heard.split(' ').length < ECHO_MIN_WORDS) return false;\n\n // ★ Word-boundary containment, not raw substring. `includes('no')` matched\n // inside \"know\", \"not\" and \"another\", so single-word corrections were\n // silently discarded — the user spoke and nothing happened at all.\n return ` ${normalise(spokenText)} `.includes(` ${heard} `);\n}\n\n/**\n * What to do with a reply the app has just observed.\n *\n * Pure, because the rule is subtle and the hook that used to hold it has no\n * test file at all — which is how the original defect shipped.\n *\n * Three outcomes:\n * - already claimed -> do nothing (a re-render, or two identical answers)\n * - arrived while thinking -> claim it AND advance the turn\n * - arrived any other time -> ★ CLAIM IT, but do not advance\n *\n * That last case is the one that matters. Interrupting stops playback but\n * nothing cancels the model, so the abandoned answer still lands seconds later\n * while the phase is `listening`. Leaving it unclaimed meant the NEXT question\n * found it waiting and spoke the answer to the question the user had cut off.\n */\nexport function planReplyConsumption(\n replyId: string | null | undefined,\n phase: VoiceSessionPhase,\n consumedReplyId: string | null\n): { claim: boolean; advance: boolean } {\n if (!replyId) return { claim: false, advance: false };\n if (replyId === consumedReplyId) return { claim: false, advance: false };\n return { claim: true, advance: phase === 'thinking' };\n}\n\nexport const INITIAL_SESSION: Readonly<VoiceSessionSnapshot> = Object.freeze({\n phase: 'idle' as const,\n muted: false,\n pending: '',\n interim: '',\n error: null,\n});\n\n/**\n * The whole session loop, as one pure reduction.\n *\n * `spokenText` is what the assistant is currently saying, supplied so echo can\n * be told from interruption. It is an argument rather than snapshot state\n * because it belongs to the speech engine, not to the session.\n */\nexport function voiceSessionReducer(\n snapshot: VoiceSessionSnapshot,\n event: VoiceSessionEvent,\n spokenText: string | null = null\n): VoiceSessionSnapshot {\n // ★ An explicit `start` is handled BEFORE the terminal guard, because it is\n // the one event that legitimately follows `ended`: the user tapping the\n // launcher again. Without this the reducer is never reset, `start` is ignored\n // from `ended`, and the voice session is one-time-use per page load — the\n // launcher does nothing after the first conversation.\n if (event.type === 'start') return { ...INITIAL_SESSION, phase: 'listening' };\n\n // Terminal otherwise. A late recognition result, a trailing playback error or\n // a reply still in flight must never reanimate a session the user dismissed,\n // nor rewrite a clean exit into a failure during teardown.\n if (snapshot.phase === 'ended') return snapshot;\n if (event.type === 'end') return { ...snapshot, phase: 'ended', pending: '', interim: '' };\n if (event.type === 'fail') {\n return { ...snapshot, phase: 'ended', pending: '', interim: '', error: event.error };\n }\n\n switch (event.type) {\n case 'mute':\n // Only the microphone changes. An in-flight turn keeps its phase, so the\n // reply that is already coming still lands and is still spoken.\n return {\n ...snapshot,\n muted: event.muted,\n // A half-heard fragment is dropped on mute rather than being submitted\n // later as a truncated question.\n ...(event.muted ? { pending: '', interim: '' } : {}),\n };\n\n case 'interrupt':\n // Cutting the assistant off starts a fresh turn. Explicit, because\n // inferring it from audio is what caused the feedback loop.\n return snapshot.phase === 'speaking' ? { ...snapshot, phase: 'listening', pending: '', interim: '' } : snapshot;\n\n case 'speech': {\n if (snapshot.muted) return snapshot;\n // Nothing heard outside `listening` is ever the user: while the assistant\n // speaks the microphone is closed, and anything arriving during\n // `thinking` is a trailing result from the turn just submitted.\n if (snapshot.phase !== 'listening') return snapshot;\n // ★ Still echo, even though playback has finished. The recogniser emits a\n // trailing FINAL result for speaker leakage after `speech-ended` has\n // returned us to listening; accepted, it is submitted 1.2s later and the\n // assistant answers its own reply — a self-sustaining loop that costs a\n // turn every round. The caller keeps `spokenText` set for a grace window\n // past the end of playback precisely so this check still has a reference.\n if (isEcho(event.transcript, spokenText)) return snapshot;\n // ★ Finalised phrases ACCUMULATE. `useVoiceInput` emits each newly\n // finalised phrase on its own — which is why the composer's handler is\n // called `appendTranscript` — so replacing here would reduce \"when should\n // I\" + \"sow ragi\" to just \"sow ragi\" and submit a truncated question.\n return event.final\n ? { ...snapshot, pending: `${snapshot.pending} ${event.transcript}`.replace(/\\s+/g, ' ').trim(), interim: '' }\n : { ...snapshot, interim: event.transcript };\n }\n\n case 'silence':\n // Submits only while listening, unmuted, and with something actually said\n // — otherwise an idle session would fire empty turns forever.\n if (snapshot.phase !== 'listening' || snapshot.muted) return snapshot;\n if (!isSubmittable(spokenSoFar(snapshot))) return snapshot;\n return { ...snapshot, phase: 'thinking' };\n\n case 'reply':\n // A reply arriving after the user already started talking again must not\n // yank the session back into `speaking`.\n if (snapshot.phase !== 'thinking') return snapshot;\n return { ...snapshot, phase: 'speaking', pending: '', interim: '' };\n\n case 'speech-ended':\n return snapshot.phase === 'speaking' ? { ...snapshot, phase: 'listening', pending: '', interim: '' } : snapshot;\n\n default:\n return snapshot;\n }\n}\n\n/**\n * Is the microphone capturing right now?\n *\n * False while the assistant speaks, which is the whole point: an open\n * microphone during playback is what created the feedback loop. False whenever\n * muted, whatever the phase.\n */\nexport function isCapturing(snapshot: VoiceSessionSnapshot): boolean {\n if (snapshot.muted) return false;\n // ONLY while listening. Capturing during `speaking` fed the assistant's own\n // voice back in as a question — see the header. Interruption is a tap.\n return snapshot.phase === 'listening';\n}\n\n/** The orb's visual mode. Kept here so the UI has no state logic of its own. */\nexport function orbMode(snapshot: VoiceSessionSnapshot): 'idle' | 'listening' | 'thinking' | 'speaking' {\n switch (snapshot.phase) {\n case 'thinking':\n return 'thinking';\n case 'speaking':\n // Still speaking even if the mic is muted — muting does not stop the\n // assistant, and showing idle here would misreport what is happening.\n return 'speaking';\n case 'listening':\n return snapshot.muted ? 'idle' : 'listening';\n default:\n return 'idle';\n }\n}\n"],"mappings":";AA6FA,IAAa,IAAoB;AAGjC,SAAgB,EAAc,GAAuB;CACnD,OAAO,EAAK,KAAK,EAAE,SAAS;AAC9B;AAGA,SAAgB,EAAY,GAAwC;CAClE,OAAO,GAAG,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O;GAAa,SAAS;GAAI,SAAS;EAAG,IAAI;EAEzG,KAAK,UAiBH,OAhBI,EAAS,SAIT,EAAS,UAAU,eAOnB,EAAO,EAAM,YAAY,CAAU,IAAU,IAK1C,EAAM,QACT;GAAE,GAAG;GAAU,SAAS,GAAG,EAAS,QAAQ,GAAG,EAAM,aAAa,QAAQ,QAAQ,GAAG,EAAE,KAAK;GAAG,SAAS;EAAG,IAC3G;GAAE,GAAG;GAAU,SAAS,EAAM;EAAW;EAG/C,KAAK,WAKH,OAFI,EAAS,UAAU,eAAe,EAAS,SAC3C,CAAC,EAAc,EAAY,CAAQ,CAAC,IAAU,IAC3C;GAAE,GAAG;GAAU,OAAO;EAAW;EAE1C,KAAK,SAIH,OADI,EAAS,UAAU,aAChB;GAAE,GAAG;GAAU,OAAO;GAAY,SAAS;GAAI,SAAS;EAAG,IADxB;EAG5C,KAAK,gBACH,OAAO,EAAS,UAAU,aAAa;GAAE,GAAG;GAAU,OAAO;GAAa,SAAS;GAAI,SAAS;EAAG,IAAI;EAEzG,SACE,OAAO;CACX;AACF;AASA,SAAgB,EAAY,GAAyC;CAInE,OAHI,EAAS,QAAc,KAGpB,EAAS,UAAU;AAC5B;AAGA,SAAgB,EAAQ,GAAgF;CACtG,QAAQ,EAAS,OAAjB;EACE,KAAK,YACH,OAAO;EACT,KAAK,YAGH,OAAO;EACT,KAAK,aACH,OAAO,EAAS,QAAQ,SAAS;EACnC,SACE,OAAO;CACX;AACF"}
|
|
1
|
+
{"version":3,"file":"voiceSession.js","names":[],"sources":["../../src/utils/voiceSession.ts"],"sourcesContent":["/**\n * The voice-conversation state machine (BOFF-7120).\n *\n * A live voice session is a loop — listen, submit, wait, speak, listen again —\n * and every interesting decision in it is about TIMING and INTERRUPTION rather\n * than about rendering. Those decisions live here, with no DOM, no audio and no\n * React, for the same reason `browserSpeechEngine` pushed its logic into\n * `speakableText`/`speechVoices`: this repo's vitest runs in the `node`\n * environment, so anything touching `window` cannot be tested at all.\n *\n * ★ **The microphone is CLOSED while the assistant speaks.** It was open, so\n * that talking over the assistant could interrupt it, guarded by matching the\n * transcript against the text being spoken. That guard was too weak to survive\n * contact with reality: speech recognition of synthesised speech mis-hears it\n * (\"sow ragi\" -> \"so ragi\"), so exact containment fails, the mis-heard echo is\n * accepted as a new question, submitted, answered, spoken — and round it goes.\n * The operator hit this loop on a real device.\n *\n * Browsers do not give the Web Speech API the acoustic echo cancellation that a\n * native duplex app has, so there is no text-level fix for this. Interruption is\n * now an explicit tap instead, which is reliable, and the echo check survives\n * only as a guard on the moments just after playback stops.\n *\n * ★ **Mute is NOT a phase.** It is a property of the microphone, orthogonal to\n * where the conversation is. Modelling it as a state meant muting while the\n * assistant was thinking discarded the `thinking` phase, so the reply — already\n * in flight — was then ignored, and unmuting landed in `listening` with nothing\n * pending and nothing coming. The session dead-ended and the user's question was\n * silently lost.\n *\n * What this deliberately does NOT model: the assistant is turn-based\n * (speech -> text -> LLM -> text -> speech), so `thinking` is a real, visible\n * phase lasting seconds. A native speech-to-speech API would collapse\n * listening/thinking/speaking into one duplex stream; we are not that, and\n * pretending otherwise would hide latency the UI must show.\n */\n\n/** Where the CONVERSATION is. Independent of whether the mic is capturing. */\nexport type VoiceSessionPhase = 'idle' | 'listening' | 'thinking' | 'speaking' | 'ended';\n\nexport interface VoiceSessionSnapshot {\n phase: VoiceSessionPhase;\n /** Microphone off. Orthogonal to `phase` — see the header. */\n muted: boolean;\n /** FINALISED speech for the turn not yet submitted, accumulated. */\n pending: string;\n /** The recogniser's current guess, replaced wholesale until it finalises. */\n interim: string;\n /** Why the session stopped, when it stopped abnormally. */\n error: VoiceSessionError | null;\n}\n\n/**\n * Deliberately does NOT include a \"playback blocked\" variant. Nothing can\n * detect it — the speech provider does not surface a per-message playback\n * refusal — and the watchdog in `useVoiceSession` already recovers by handing\n * the turn back silently, which continues the conversation rather than killing\n * it. An error the code cannot raise is dead UI copy.\n */\nexport type VoiceSessionError = 'no-speech-support' | 'no-voice-support' | 'mic-denied';\n\nexport type VoiceSessionEvent =\n /** `final` distinguishes a committed phrase from a revisable guess. */\n | { type: 'start' }\n | { type: 'speech'; transcript: string; final: boolean }\n /** Nothing heard for `SILENCE_SUBMIT_MS`. */\n | { type: 'silence' }\n | { type: 'reply'; text: string }\n | { type: 'speech-ended' }\n | { type: 'mute'; muted: boolean }\n /** The user tapped to cut the assistant off. Explicit, not inferred. */\n | { type: 'interrupt' }\n | { type: 'fail'; error: VoiceSessionError }\n | { type: 'end' };\n\n/**\n * How long the user must stop talking before the turn is submitted.\n *\n * Long enough to survive a mid-sentence breath — a farmer describing a problem\n * pauses — and short enough that the session does not feel unresponsive. A\n * premature send truncates the question, which costs a whole 2-5s round trip to\n * recover from.\n *\n * ★ Raised from 1200ms because 1.2s does not survive an ordinary pause: the\n * operator reported being cut off mid-sentence, and the cost is worse than a\n * truncated prompt — once the turn is submitted the reducer discards every\n * `speech` event outside `listening`, so the rest of the sentence is not\n * queued, it is thrown away, and the assistant answers half a question.\n *\n * The asymmetry is what settles the number: waiting 800ms longer costs a moment\n * of silence, while cutting someone off costs the whole round trip AND makes\n * them repeat themselves.\n */\nexport const SILENCE_SUBMIT_MS = 2000;\n\n/** A turn is submitted only when there is something worth sending. */\nexport function isSubmittable(text: string): boolean {\n return text.trim().length > 0;\n}\n\n/** Everything heard this turn: committed phrases plus the current guess. */\nexport function spokenSoFar(snapshot: VoiceSessionSnapshot): string {\n return `${snapshot.pending} ${snapshot.interim}`.replace(/\\s+/g, ' ').trim();\n}\n\n/** Comparable form for echo detection: letters and digits only. */\nfunction normalise(text: string): string {\n return text\n .toLowerCase()\n .replace(/[^\\p{L}\\p{N}]+/gu, ' ')\n .trim();\n}\n\n/**\n * Is this transcript the assistant's OWN voice coming back through the mic?\n *\n * ★ The microphone is CLOSED for the whole `speaking` phase — see `isCapturing`\n * below. This comment used to claim the opposite, which is worth correcting\n * because it is exactly what the next person attempting barge-in would read.\n *\n * The guard still earns its place: the recogniser emits a trailing FINAL result\n * for speaker leakage a beat AFTER playback stops and the microphone reopens,\n * and `useVoiceSession` deliberately keeps the reply as an echo reference for a\n * grace period to catch it. Without that, the assistant answers itself. It is\n * also what a future open-microphone design would rely on.\n *\n * Containment is the signal length cannot provide: whatever we are currently\n * speaking is known, so anything already inside it is echo, not a person.\n */\n/**\n * Below this many words, a transcript is treated as a person interrupting\n * rather than as the assistant's own voice.\n *\n * Containment alone cannot tell \"no\" (a correction) from \"no\" (a word inside a\n * long reply), and the assistant's own voice arrives as long phrases, not as\n * one or two words. Anything shorter is far more likely to be the user cutting\n * in — which is precisely the case that must not be swallowed.\n */\nconst ECHO_MIN_WORDS = 3;\n\nexport function isEcho(transcript: string, spokenText: string | null): boolean {\n if (!spokenText) return false;\n const heard = normalise(transcript);\n if (heard.length === 0) return true;\n\n // A short utterance during playback is a correction, not an echo.\n if (heard.split(' ').length < ECHO_MIN_WORDS) return false;\n\n // ★ Word-boundary containment, not raw substring. `includes('no')` matched\n // inside \"know\", \"not\" and \"another\", so single-word corrections were\n // silently discarded — the user spoke and nothing happened at all.\n return ` ${normalise(spokenText)} `.includes(` ${heard} `);\n}\n\n/**\n * What to do with a reply the app has just observed.\n *\n * Pure, because the rule is subtle and the hook that used to hold it has no\n * test file at all — which is how the original defect shipped.\n *\n * Three outcomes:\n * - already claimed -> do nothing (a re-render, or two identical answers)\n * - arrived while thinking -> claim it AND advance the turn\n * - arrived any other time -> ★ CLAIM IT, but do not advance\n *\n * That last case is the one that matters. Interrupting stops playback but\n * nothing cancels the model, so the abandoned answer still lands seconds later\n * while the phase is `listening`. Leaving it unclaimed meant the NEXT question\n * found it waiting and spoke the answer to the question the user had cut off.\n */\nexport function planReplyConsumption(\n replyId: string | null | undefined,\n phase: VoiceSessionPhase,\n consumedReplyId: string | null\n): { claim: boolean; advance: boolean } {\n if (!replyId) return { claim: false, advance: false };\n if (replyId === consumedReplyId) return { claim: false, advance: false };\n return { claim: true, advance: phase === 'thinking' };\n}\n\nexport const INITIAL_SESSION: Readonly<VoiceSessionSnapshot> = Object.freeze({\n phase: 'idle' as const,\n muted: false,\n pending: '',\n interim: '',\n error: null,\n});\n\n/**\n * The whole session loop, as one pure reduction.\n *\n * `spokenText` is what the assistant is currently saying, supplied so echo can\n * be told from interruption. It is an argument rather than snapshot state\n * because it belongs to the speech engine, not to the session.\n */\nexport function voiceSessionReducer(\n snapshot: VoiceSessionSnapshot,\n event: VoiceSessionEvent,\n spokenText: string | null = null\n): VoiceSessionSnapshot {\n // ★ An explicit `start` is handled BEFORE the terminal guard, because it is\n // the one event that legitimately follows `ended`: the user tapping the\n // launcher again. Without this the reducer is never reset, `start` is ignored\n // from `ended`, and the voice session is one-time-use per page load — the\n // launcher does nothing after the first conversation.\n if (event.type === 'start') return { ...INITIAL_SESSION, phase: 'listening' };\n\n // Terminal otherwise. A late recognition result, a trailing playback error or\n // a reply still in flight must never reanimate a session the user dismissed,\n // nor rewrite a clean exit into a failure during teardown.\n if (snapshot.phase === 'ended') return snapshot;\n if (event.type === 'end') return { ...snapshot, phase: 'ended', pending: '', interim: '' };\n if (event.type === 'fail') {\n return { ...snapshot, phase: 'ended', pending: '', interim: '', error: event.error };\n }\n\n switch (event.type) {\n case 'mute':\n // Only the microphone changes. An in-flight turn keeps its phase, so the\n // reply that is already coming still lands and is still spoken.\n return {\n ...snapshot,\n muted: event.muted,\n // A half-heard fragment is dropped on mute rather than being submitted\n // later as a truncated question.\n ...(event.muted ? { pending: '', interim: '' } : {}),\n };\n\n case 'interrupt':\n // Cutting the assistant off starts a fresh turn. Explicit, because\n // inferring it from audio is what caused the feedback loop.\n return snapshot.phase === 'speaking' ? { ...snapshot, phase: 'listening', pending: '', interim: '' } : snapshot;\n\n case 'speech': {\n if (snapshot.muted) return snapshot;\n // Nothing heard outside `listening` is ever the user: while the assistant\n // speaks the microphone is closed, and anything arriving during\n // `thinking` is a trailing result from the turn just submitted.\n if (snapshot.phase !== 'listening') return snapshot;\n // ★ Still echo, even though playback has finished. The recogniser emits a\n // trailing FINAL result for speaker leakage after `speech-ended` has\n // returned us to listening; accepted, it is submitted 1.2s later and the\n // assistant answers its own reply — a self-sustaining loop that costs a\n // turn every round. The caller keeps `spokenText` set for a grace window\n // past the end of playback precisely so this check still has a reference.\n if (isEcho(event.transcript, spokenText)) return snapshot;\n // ★ Finalised phrases ACCUMULATE. `useVoiceInput` emits each newly\n // finalised phrase on its own — which is why the composer's handler is\n // called `appendTranscript` — so replacing here would reduce \"when should\n // I\" + \"sow ragi\" to just \"sow ragi\" and submit a truncated question.\n return event.final\n ? { ...snapshot, pending: `${snapshot.pending} ${event.transcript}`.replace(/\\s+/g, ' ').trim(), interim: '' }\n : { ...snapshot, interim: event.transcript };\n }\n\n case 'silence':\n // Submits only while listening, unmuted, and with something actually said\n // — otherwise an idle session would fire empty turns forever.\n if (snapshot.phase !== 'listening' || snapshot.muted) return snapshot;\n if (!isSubmittable(spokenSoFar(snapshot))) return snapshot;\n return { ...snapshot, phase: 'thinking' };\n\n case 'reply':\n // A reply arriving after the user already started talking again must not\n // yank the session back into `speaking`.\n if (snapshot.phase !== 'thinking') return snapshot;\n return { ...snapshot, phase: 'speaking', pending: '', interim: '' };\n\n case 'speech-ended':\n return snapshot.phase === 'speaking' ? { ...snapshot, phase: 'listening', pending: '', interim: '' } : snapshot;\n\n default:\n return snapshot;\n }\n}\n\n/**\n * Is the microphone capturing right now?\n *\n * False while the assistant speaks, which is the whole point: an open\n * microphone during playback is what created the feedback loop. False whenever\n * muted, whatever the phase.\n */\nexport function isCapturing(snapshot: VoiceSessionSnapshot): boolean {\n if (snapshot.muted) return false;\n // ONLY while listening. Capturing during `speaking` fed the assistant's own\n // voice back in as a question — see the header. Interruption is a tap.\n return snapshot.phase === 'listening';\n}\n\n/** The orb's visual mode. Kept here so the UI has no state logic of its own. */\nexport function orbMode(snapshot: VoiceSessionSnapshot): 'idle' | 'listening' | 'thinking' | 'speaking' {\n switch (snapshot.phase) {\n case 'thinking':\n return 'thinking';\n case 'speaking':\n // Still speaking even if the mic is muted — muting does not stop the\n // assistant, and showing idle here would misreport what is happening.\n return 'speaking';\n case 'listening':\n return snapshot.muted ? 'idle' : 'listening';\n default:\n return 'idle';\n }\n}\n"],"mappings":";AA6FA,IAAa,IAAoB;AAGjC,SAAgB,EAAc,GAAuB;CACnD,OAAO,EAAK,KAAK,EAAE,SAAS;AAC9B;AAGA,SAAgB,EAAY,GAAwC;CAClE,OAAO,GAAG,EAAS,QAAQ,GAAG,EAAS,UAAU,QAAQ,QAAQ,GAAG,EAAE,KAAK;AAC7E;AAGA,SAAS,EAAU,GAAsB;CACvC,OAAO,EACJ,YAAY,EACZ,QAAQ,oBAAoB,GAAG,EAC/B,KAAK;AACV;AA2BA,IAAM,IAAiB;AAEvB,SAAgB,EAAO,GAAoB,GAAoC;CAC7E,IAAI,CAAC,GAAY,OAAO;CACxB,IAAM,IAAQ,EAAU,CAAU;CASlC,OARI,EAAM,WAAW,IAAU,KAG3B,EAAM,MAAM,GAAG,EAAE,SAAS,IAAuB,KAK9C,IAAI,EAAU,CAAU,EAAE,GAAG,SAAS,IAAI,EAAM,EAAE;AAC3D;AAkBA,SAAgB,EACd,GACA,GACA,GACsC;CAGtC,OAFI,CAAC,KACD,MAAY,IAAwB;EAAE,OAAO;EAAO,SAAS;CAAM,IAChE;EAAE,OAAO;EAAM,SAAS,MAAU;CAAW;AACtD;AAEA,IAAa,IAAkD,OAAO,OAAO;CAC3E,OAAO;CACP,OAAO;CACP,SAAS;CACT,SAAS;CACT,OAAO;AACT,CAAC;AASD,SAAgB,EACd,GACA,GACA,IAA4B,MACN;CAMtB,IAAI,EAAM,SAAS,SAAS,OAAO;EAAE,GAAG;EAAiB,OAAO;CAAY;CAK5E,IAAI,EAAS,UAAU,SAAS,OAAO;CACvC,IAAI,EAAM,SAAS,OAAO,OAAO;EAAE,GAAG;EAAU,OAAO;EAAS,SAAS;EAAI,SAAS;CAAG;CACzF,IAAI,EAAM,SAAS,QACjB,OAAO;EAAE,GAAG;EAAU,OAAO;EAAS,S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