@burdenoff/microfe-healthybowl 2026.902.21 → 2026.902.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/assistant/AssistantChatArea.js +244 -243
- package/dist/components/assistant/AssistantChatArea.js.map +1 -1
- package/dist/components/assistant/AssistantSpeechProvider.js +175 -174
- package/dist/components/assistant/AssistantSpeechProvider.js.map +1 -1
- package/dist/components/assistant/voice/AssistantVoiceSession.js.map +1 -1
- package/dist/components/assistant/voice/VoiceConversationView.js +36 -20
- package/dist/components/assistant/voice/VoiceConversationView.js.map +1 -1
- package/dist/components/assistant/voice/VoiceTranscriptDrawer.js.map +1 -1
- package/dist/hooks/useVoiceSession.js +10 -10
- package/dist/hooks/useVoiceSession.js.map +1 -1
- package/dist/types/assistant.js.map +1 -1
- package/dist/utils/voiceTurnVisibility.js +22 -4
- package/dist/utils/voiceTurnVisibility.js.map +1 -1
- package/package.json +1 -1
|
@@ -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 ENDPOINT_GRACE_MS,\n INTERRUPT_MAX_MS,\n INTERRUPT_MIN_MS,\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 { setSessionSpeaking, speakingMessageId, stop: stopSpeaking } = speech;\n\n const silenceTimer = useRef<ReturnType<typeof setTimeout> | 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 /**\n * The two signals `voiceStageState` accepts but nothing was producing.\n *\n * ★ Both stages existed, were typed, and were unit-tested — and neither could\n * ever render, because the only call site omitted the props. `interrupting`\n * left the tap on the orb looking like a start-up stall, and the two-second\n * correction window was indistinguishable from ordinary listening.\n *\n * They live here rather than in the reducer on purpose: neither is a\n * turn-taking transition, and `voiceSessionReducer` stays pure and total.\n */\n const [interrupting, setInterrupting] = useState(false);\n const [awaitingEndpoint, setAwaitingEndpoint] = useState(false);\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 interruptedAt = useRef(0);\n const interrupt = useCallback(() => {\n stopSpeaking();\n interruptedAt.current = Date.now();\n // Set before dispatching so the very next render already shows that the\n // user was obeyed — the reducer puts the phase back to `listening`, but the\n // microphone takes a moment to reopen, and without this the tap landed in\n // `connecting` — which since #367 is a real, observed state rather than a\n // single commit, so the acknowledgement matters more, not less.\n setInterrupting(true);\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 //\n // ★ The same window also drives `awaitingEndpoint`, on a SECOND, shorter\n // timer. It cannot be derived from the snapshot: the guard below is already\n // true the moment a submittable phrase exists, i.e. while the user is still\n // mid-sentence, so using it directly would flag \"endpoint\" during ordinary\n // speech. Waiting out ENDPOINT_GRACE_MS of genuine quiet first is what makes\n // the remaining window read as the pause it is.\n useEffect(() => {\n if (silenceTimer.current) clearTimeout(silenceTimer.current);\n // Any new fragment cancels the pause. Safe to call unconditionally: React\n // bails out when the value is unchanged, and `session` identity is what\n // this effect depends on, so no loop.\n setAwaitingEndpoint(false);\n if (session.phase !== 'listening' || session.muted || !isSubmittable(spokenSoFar(session))) return;\n const graceTimer = setTimeout(() => setAwaitingEndpoint(true), ENDPOINT_GRACE_MS);\n silenceTimer.current = setTimeout(() => dispatch({ type: 'silence' }), SILENCE_SUBMIT_MS);\n return () => {\n clearTimeout(graceTimer);\n if (silenceTimer.current) clearTimeout(silenceTimer.current);\n };\n }, [session]);\n\n /**\n * Interruption is momentary: it ends when the microphone is genuinely back.\n *\n * ★ The timeout is not cosmetic. If capture never resumes — which is exactly\n * what happens when the microphone is the thing that failed — the flag would\n * otherwise latch on forever and outrank the error stage, hiding the very\n * message that explains the failure.\n */\n useEffect(() => {\n if (!interrupting) return undefined;\n const elapsed = Date.now() - interruptedAt.current;\n // ★ A MINIMUM, not just a ceiling. `isListening` flips true as soon as\n // `recognition.start()` returns — synchronously, in the same flush, long\n // before the microphone is really open — so clearing on it alone left the\n // acknowledgement on screen for about one frame. Holding it briefly is what\n // makes \"Stopped — go ahead\" something the user can actually read.\n const wait = voice.isListening ? Math.max(0, INTERRUPT_MIN_MS - elapsed) : Math.max(0, INTERRUPT_MAX_MS - elapsed);\n const timer = setTimeout(() => setInterrupting(false), wait);\n return () => clearTimeout(timer);\n }, [interrupting, voice.isListening]);\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 // Same reason as `end`: a fresh session must not inherit either flag.\n setInterrupting(false);\n setAwaitingEndpoint(false);\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 // ★ Session-scoped, NOT the persisted preference. This used to save the\n // user's `autoSpeakEnabled`, force it true, and restore it on exit — but\n // that field is persisted and the restore only ran on a clean `end()`, so a\n // reload or a closed tab mid-session left auto-speak switched on in normal\n // typed chat forever. Nothing to save, nothing to restore, nothing to leak.\n setSessionSpeaking(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, setSessionSpeaking]);\n\n const end = useCallback(() => {\n // Reset here rather than relying on an effect to notice: both are UI-only\n // flags, and a stale one bleeds into the NEXT session — relaunching inside\n // INTERRUPT_MAX_MS opened it reading \"Stopped — go ahead\".\n setInterrupting(false);\n setAwaitingEndpoint(false);\n dispatch({ type: 'end' });\n stopSpeaking();\n setSessionSpeaking(false);\n }, [stopSpeaking, setSessionSpeaking]);\n\n const toggleMute = useCallback(() => {\n dispatch({ type: 'mute', muted: !sessionRef.current.muted });\n }, []);\n\n // Unmounting mid-session must not leave the session speaking. The preference\n // itself is never touched now, so this only clears the session flag.\n useEffect(\n () => () => {\n setSessionSpeaking(false);\n },\n [setSessionSpeaking]\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 /**\n * True once started and not yet ended — what decides whether to render.\n *\n * ★ A failure keeps it true. `fail` sets phase `ended`, so this used to go\n * false the instant the microphone was refused and the panel vanished\n * without ever saying why. `end` clears the error, which is how the user\n * dismisses it.\n */\n active: session.phase !== 'idle' && (session.phase !== 'ended' || session.error !== null),\n /** The user has cut the assistant off and capture has not resumed yet. */\n interrupting,\n /** Quiet has fallen and the correction window is running. */\n awaitingEndpoint,\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 [\n session,\n notice,\n interrupting,\n awaitingEndpoint,\n voice.isListening,\n voice.isSupported,\n speech.isBlocked,\n start,\n end,\n toggleMute,\n interrupt,\n ]\n );\n}\n"],"mappings":";;;;;AAwBA,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,uBAAoB,sBAAmB,MAAM,MAAiB,GAEhE,IAAe,EAA6C,IAAI,GAEhE,IAAkB,EAAsB,IAAI,GAC5C,IAAc,EAAO,EAAK,GAC1B,CAAC,GAAQ,KAAa,EAAoC,IAAI,GAa9D,CAAC,GAAc,KAAmB,EAAS,EAAK,GAChD,CAAC,GAAkB,KAAuB,EAAS,EAAK,GAExD,IAAa,EAAO,CAAO;CACjC,EAAW,UAAU;CAQrB,IAAM,IAAiB,EAAO,CAAW;CAMzC,AALA,EAAe,UAAU,GAKzB,QAAgB;EACd,IAAI,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ErD,AADA,EAAO,SAAS,GAChB,EAAU,MAAM,CAAM;GACxB;EACF,QAAQ,CAGR;EAEA,IAAI;GACF,IAAI,OAAO,SAAW,OAAe,OAAO,OAAO,SAAU,YAAY;IAGvE,IAAM,IAAS,IAAI,OAAO,MAAM,CAAU;IAE1C,AADA,EAAO,SAAS,GAChB,EAAY,KAAK,EAAE,YAAY,CAAC,CAAC;GACnC;EACF,QAAQ,CAER;EA4BA,AArBA,EAAmB,EAAI,GACvB,EAAU,IAAI,GAmBd,EAAgB,UAAU,EAAe,SAAS,MAAM,MACxD,EAAS,EAAE,MAAM,QAAQ,CAAC;CAC5B,GAAG;EAAC,EAAM;EAAa,EAAO;EAAW;CAAkB,CAAC,GAEtD,IAAM,QAAkB;EAQ5B,AAJA,EAAgB,EAAK,GACrB,EAAoB,EAAK,GACzB,EAAS,EAAE,MAAM,MAAM,CAAC,GACxB,EAAa,GACb,EAAmB,EAAK;CAC1B,GAAG,CAAC,GAAc,CAAkB,CAAC,GAE/B,IAAa,QAAkB;EACnC,EAAS;GAAE,MAAM;GAAQ,OAAO,CAAC,EAAW,QAAQ;EAAM,CAAC;CAC7D,GAAG,CAAC,CAAC;CAWL,OAPA,cACc;EACV,EAAmB,EAAK;CAC1B,GACA,CAAC,CAAkB,CACrB,GAEO,SACE;EACL;EAEA;EAEA,WAAW,EAAM;EASjB,QAAQ,EAAQ,UAAU,WAAW,EAAQ,UAAU,WAAW,EAAQ,UAAU;EAEpF;EAEA;EAEA,WAAW,EAAM,eAAe,CAAC,EAAO;EACxC;EACA;EACA;EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA,EAAM;EACN,EAAM;EACN,EAAO;EACP;EACA;EACA;EACA;CACF,CACF;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 ENDPOINT_GRACE_MS,\n INTERRUPT_MAX_MS,\n INTERRUPT_MIN_MS,\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 /**\n * Send a turn.\n *\n * ★ The session id is handed over HERE rather than exposed for the parent to\n * read, so the value that stamps the turn is the one live at the instant it\n * was spoken. A parent reading an exposed id would sample it a render later,\n * which is a race the very first turn of a session is most likely to lose.\n */\n onSubmit: (text: string, voiceSessionId: 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 { setSessionSpeaking, speakingMessageId, stop: stopSpeaking } = speech;\n\n const silenceTimer = useRef<ReturnType<typeof setTimeout> | 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 /**\n * The two signals `voiceStageState` accepts but nothing was producing.\n *\n * ★ Both stages existed, were typed, and were unit-tested — and neither could\n * ever render, because the only call site omitted the props. `interrupting`\n * left the tap on the orb looking like a start-up stall, and the two-second\n * correction window was indistinguishable from ordinary listening.\n *\n * They live here rather than in the reducer on purpose: neither is a\n * turn-taking transition, and `voiceSessionReducer` stays pure and total.\n */\n const [interrupting, setInterrupting] = useState(false);\n const [awaitingEndpoint, setAwaitingEndpoint] = useState(false);\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 interruptedAt = useRef(0);\n const interrupt = useCallback(() => {\n stopSpeaking();\n interruptedAt.current = Date.now();\n // Set before dispatching so the very next render already shows that the\n // user was obeyed — the reducer puts the phase back to `listening`, but the\n // microphone takes a moment to reopen, and without this the tap landed in\n // `connecting` — which since #367 is a real, observed state rather than a\n // single commit, so the acknowledgement matters more, not less.\n setInterrupting(true);\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 //\n // ★ The same window also drives `awaitingEndpoint`, on a SECOND, shorter\n // timer. It cannot be derived from the snapshot: the guard below is already\n // true the moment a submittable phrase exists, i.e. while the user is still\n // mid-sentence, so using it directly would flag \"endpoint\" during ordinary\n // speech. Waiting out ENDPOINT_GRACE_MS of genuine quiet first is what makes\n // the remaining window read as the pause it is.\n useEffect(() => {\n if (silenceTimer.current) clearTimeout(silenceTimer.current);\n // Any new fragment cancels the pause. Safe to call unconditionally: React\n // bails out when the value is unchanged, and `session` identity is what\n // this effect depends on, so no loop.\n setAwaitingEndpoint(false);\n if (session.phase !== 'listening' || session.muted || !isSubmittable(spokenSoFar(session))) return;\n const graceTimer = setTimeout(() => setAwaitingEndpoint(true), ENDPOINT_GRACE_MS);\n silenceTimer.current = setTimeout(() => dispatch({ type: 'silence' }), SILENCE_SUBMIT_MS);\n return () => {\n clearTimeout(graceTimer);\n if (silenceTimer.current) clearTimeout(silenceTimer.current);\n };\n }, [session]);\n\n /**\n * Interruption is momentary: it ends when the microphone is genuinely back.\n *\n * ★ The timeout is not cosmetic. If capture never resumes — which is exactly\n * what happens when the microphone is the thing that failed — the flag would\n * otherwise latch on forever and outrank the error stage, hiding the very\n * message that explains the failure.\n */\n useEffect(() => {\n if (!interrupting) return undefined;\n const elapsed = Date.now() - interruptedAt.current;\n // ★ A MINIMUM, not just a ceiling. `isListening` flips true as soon as\n // `recognition.start()` returns — synchronously, in the same flush, long\n // before the microphone is really open — so clearing on it alone left the\n // acknowledgement on screen for about one frame. Holding it briefly is what\n // makes \"Stopped — go ahead\" something the user can actually read.\n const wait = voice.isListening ? Math.max(0, INTERRUPT_MIN_MS - elapsed) : Math.max(0, INTERRUPT_MAX_MS - elapsed);\n const timer = setTimeout(() => setInterrupting(false), wait);\n return () => clearTimeout(timer);\n }, [interrupting, voice.isListening]);\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 // A turn with no session cannot exist: `submit` only runs from inside a\n // started session, and `start` mints the id before dispatching. Falling back\n // to a fresh id rather than sending an unstamped turn keeps that invariant\n // true even if a future path reaches here another way.\n if (text) onSubmit(text, sessionIdRef.current ?? `vs-orphan-${Date.now().toString(36)}`);\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 /**\n * Identifies THIS microphone-on-to-End, so every turn it produces can say\n * which exchange it belongs to.\n *\n * ★ A ref, not reducer state. It has to be readable synchronously by\n * `submitVoiceTurn` at the moment a turn is sent; routing it through a\n * dispatch would hand the send whatever value the last render happened to\n * close over, and the first turn of a session — the one most likely to race\n * the state update — is exactly the one that would come out unstamped.\n *\n * Minted on `start` rather than on the first turn, so a session that the user\n * abandons without speaking still consumes its own id and cannot lend it to\n * the next one.\n */\n const sessionIdRef = useRef<string | null>(null);\n\n const start = useCallback(() => {\n // Same reason as `end`: a fresh session must not inherit either flag.\n setInterrupting(false);\n setAwaitingEndpoint(false);\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 // ★ Session-scoped, NOT the persisted preference. This used to save the\n // user's `autoSpeakEnabled`, force it true, and restore it on exit — but\n // that field is persisted and the restore only ran on a clean `end()`, so a\n // reload or a closed tab mid-session left auto-speak switched on in normal\n // typed chat forever. Nothing to save, nothing to restore, nothing to leak.\n setSessionSpeaking(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 // AFTER the support guards: a session that never started must not mint an\n // id, or an abandoned failure would divide the transcript at a point where\n // nothing was ever said.\n sessionIdRef.current = `vs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;\n dispatch({ type: 'start' });\n }, [voice.isSupported, speech.isBlocked, setSessionSpeaking]);\n\n const end = useCallback(() => {\n // Reset here rather than relying on an effect to notice: both are UI-only\n // flags, and a stale one bleeds into the NEXT session — relaunching inside\n // INTERRUPT_MAX_MS opened it reading \"Stopped — go ahead\".\n setInterrupting(false);\n setAwaitingEndpoint(false);\n // Cleared so a turn can never be stamped with a session that has closed —\n // `pendingPrompt` and the composer both reach `handleSend` after End.\n sessionIdRef.current = null;\n dispatch({ type: 'end' });\n stopSpeaking();\n setSessionSpeaking(false);\n }, [stopSpeaking, setSessionSpeaking]);\n\n const toggleMute = useCallback(() => {\n dispatch({ type: 'mute', muted: !sessionRef.current.muted });\n }, []);\n\n // Unmounting mid-session must not leave the session speaking. The preference\n // itself is never touched now, so this only clears the session flag.\n useEffect(\n () => () => {\n setSessionSpeaking(false);\n },\n [setSessionSpeaking]\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 /**\n * True once started and not yet ended — what decides whether to render.\n *\n * ★ A failure keeps it true. `fail` sets phase `ended`, so this used to go\n * false the instant the microphone was refused and the panel vanished\n * without ever saying why. `end` clears the error, which is how the user\n * dismisses it.\n */\n active: session.phase !== 'idle' && (session.phase !== 'ended' || session.error !== null),\n /** The user has cut the assistant off and capture has not resumed yet. */\n interrupting,\n /** Quiet has fallen and the correction window is running. */\n awaitingEndpoint,\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 [\n session,\n notice,\n interrupting,\n awaitingEndpoint,\n voice.isListening,\n voice.isSupported,\n speech.isBlocked,\n start,\n end,\n toggleMute,\n interrupt,\n ]\n );\n}\n"],"mappings":";;;;;AAwBA,IAAM,IAAwB,KAUxB,IAAgB,MAShB,IAAyB,KASzB,IAAmB,MAcnB,IAAa;AAqCnB,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,uBAAoB,sBAAmB,MAAM,MAAiB,GAEhE,IAAe,EAA6C,IAAI,GAEhE,IAAkB,EAAsB,IAAI,GAC5C,IAAc,EAAO,EAAK,GAC1B,CAAC,GAAQ,KAAa,EAAoC,IAAI,GAa9D,CAAC,GAAc,KAAmB,EAAS,EAAK,GAChD,CAAC,GAAkB,KAAuB,EAAS,EAAK,GAExD,IAAa,EAAO,CAAO;CACjC,EAAW,UAAU;CAQrB,IAAM,IAAiB,EAAO,CAAW;CAMzC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EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA,EAAM;EACN,EAAM;EACN,EAAO;EACP;EACA;EACA;EACA;CACF,CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assistant.js","names":[],"sources":["../../src/types/assistant.ts"],"sourcesContent":["/**\n * AI Assistant types.\n *\n * Defines the data model for the right-pane AI assistant panel.\n * Interface shapes align with aiApi.ts (AISession, AISessionLog), which is\n * the real workspace gateway backed assistant contract.\n */\n\nimport { ASSISTANT_USECASE_CONFIG, type AssistantUsecaseId } from '@/config/assistantUsecases';\nimport type { AssistantMessageAttachment } from '@/utils/assistantAttachments';\n\nexport type AssistantMode = AssistantUsecaseId;\n\nexport type AssistantSandboxStatus = 'none' | 'provisioning' | 'running' | 'stopping' | 'error';\n\nexport type AssistantConversationStatus = 'idle' | 'provisioning' | 'connecting' | 'streaming' | 'complete' | 'error';\n\nexport interface AssistantArtifact {\n name: string;\n path: string;\n type: 'file' | 'directory';\n size: number;\n downloadPath?: string;\n}\n\nexport interface AssistantMessageMetadata {\n artifacts?: AssistantArtifact[];\n mode?: AssistantMode;\n sandboxId?: string;\n sessionId?: string;\n /**\n * Files the user attached to this turn. Deliberately the SLIM descriptor —\n * conversations are persisted to localStorage, so preview data URLs and\n * inlined text content must never land here (see AssistantMessageAttachment).\n */\n attachments?: AssistantMessageAttachment[];\n /**\n * The language this turn was generated under (BOFF-7108), as an assistant\n * language code.\n *\n * Fixed at send time, because it is a property of the TURN and not of the\n * current preference. `resolveSpeechLocale` cannot tell English from Spanish\n * or French — they share a script — so it falls back to whatever language is\n * selected NOW. Without this, a French reply starts being read by a Spanish\n * voice the moment the user switches, even with the right voice installed.\n */\n lang?: string;\n /**\n * This turn happened inside a live VOICE session, not in the chat panel.\n *\n * ★ The two surfaces share one conversation and one backend session — voice\n * was built as an overlay over the chat thread, so `submitVoiceTurn` calls\n * the same `handleSend` the composer does. Without a marker there is no way\n * to tell a spoken turn from a typed one once it is in the store, and every\n * voice exchange therefore appeared in the normal chat: the operator's own\n * report, \"I see the same chat in the normal conversation tab, both are\n * separate, don't confuse\".\n *\n * Stamped at send time and persisted, so the distinction survives a reload —\n * the chat transcript is never rehydrated from the backend, so the store is\n * the only source of truth for what the panel shows.\n */\n voice?: boolean;\n [key: string]: unknown;\n}\n\nexport interface Message {\n id: string;\n role: 'user' | 'assistant' | 'system';\n content: string;\n timestamp: string;\n tokens?: { input: number; output: number };\n metadata?: AssistantMessageMetadata;\n}\n\nexport interface Conversation {\n id: string;\n title: string;\n mode: AssistantMode;\n /**\n * EVERY turn, both surfaces — typed and spoken.\n *\n * ★ `readonly` on purpose, and it is load-bearing rather than hygiene. Voice\n * and chat share this one array; what separates them is `metadata.voice` plus\n * a filter at every reader, so the failure mode is a new reader that renders\n * the array as-is and silently spills spoken content into the typed thread.\n * Nothing about that is a type error, and it stays green in CI.\n *\n * Being readonly makes it one: components take `Message[]`, so handing them\n * this field directly no longer compiles. The way through is `chatTurns()` or\n * `voiceTurnsOnly()` (see `utils/voiceTurnVisibility`), both of which return a\n * fresh mutable array — which means picking a surface is now a step you cannot\n * skip by accident.\n *\n * Counting is still fine: `.length` answers \"is this conversation used at\n * all\", which is a question about the conversation and not about either\n * surface.\n */\n messages: readonly Message[];\n createdAt: string;\n updatedAt: string;\n /** Backend session ID for this conversation */\n backendSessionId?: string | null;\n}\n\nexport interface AssistantSandboxRuntime {\n sandboxId: string;\n status: AssistantSandboxStatus;\n}\n\nexport interface AssistantConversationProcessing {\n status: AssistantConversationStatus;\n messageId: string | null;\n error?: string | null;\n updatedAt: string;\n}\n\nexport interface AssistantModeConfig {\n id: AssistantMode;\n label: string;\n description: string;\n suggestions: readonly string[];\n /** Only offered to a global Owner/Admin (see useAssistantApiAccess). */\n requiresAdmin?: boolean;\n /** Executes mutations on live data → triggers the confirm-before-mutate guard. */\n writeCapable?: boolean;\n}\n\nexport const ASSISTANT_MODES: AssistantModeConfig[] = [...ASSISTANT_USECASE_CONFIG];\n"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"assistant.js","names":[],"sources":["../../src/types/assistant.ts"],"sourcesContent":["/**\n * AI Assistant types.\n *\n * Defines the data model for the right-pane AI assistant panel.\n * Interface shapes align with aiApi.ts (AISession, AISessionLog), which is\n * the real workspace gateway backed assistant contract.\n */\n\nimport { ASSISTANT_USECASE_CONFIG, type AssistantUsecaseId } from '@/config/assistantUsecases';\nimport type { AssistantMessageAttachment } from '@/utils/assistantAttachments';\n\nexport type AssistantMode = AssistantUsecaseId;\n\nexport type AssistantSandboxStatus = 'none' | 'provisioning' | 'running' | 'stopping' | 'error';\n\nexport type AssistantConversationStatus = 'idle' | 'provisioning' | 'connecting' | 'streaming' | 'complete' | 'error';\n\nexport interface AssistantArtifact {\n name: string;\n path: string;\n type: 'file' | 'directory';\n size: number;\n downloadPath?: string;\n}\n\nexport interface AssistantMessageMetadata {\n artifacts?: AssistantArtifact[];\n mode?: AssistantMode;\n sandboxId?: string;\n sessionId?: string;\n /**\n * Files the user attached to this turn. Deliberately the SLIM descriptor —\n * conversations are persisted to localStorage, so preview data URLs and\n * inlined text content must never land here (see AssistantMessageAttachment).\n */\n attachments?: AssistantMessageAttachment[];\n /**\n * The language this turn was generated under (BOFF-7108), as an assistant\n * language code.\n *\n * Fixed at send time, because it is a property of the TURN and not of the\n * current preference. `resolveSpeechLocale` cannot tell English from Spanish\n * or French — they share a script — so it falls back to whatever language is\n * selected NOW. Without this, a French reply starts being read by a Spanish\n * voice the moment the user switches, even with the right voice installed.\n */\n lang?: string;\n /**\n * This turn happened inside a live VOICE session, not in the chat panel.\n *\n * ★ The two surfaces share one conversation and one backend session — voice\n * was built as an overlay over the chat thread, so `submitVoiceTurn` calls\n * the same `handleSend` the composer does. Without a marker there is no way\n * to tell a spoken turn from a typed one once it is in the store, and every\n * voice exchange therefore appeared in the normal chat: the operator's own\n * report, \"I see the same chat in the normal conversation tab, both are\n * separate, don't confuse\".\n *\n * Stamped at send time and persisted, so the distinction survives a reload —\n * the chat transcript is never rehydrated from the backend, so the store is\n * the only source of truth for what the panel shows.\n */\n voice?: boolean;\n /**\n * WHICH live voice session produced this turn.\n *\n * ★ Not the same thing as `sessionId` above, which is the BACKEND session and\n * is shared with the typed thread. This one identifies a single\n * microphone-on-to-End, so the transcript can say where one spoken exchange\n * stopped and the next began.\n *\n * `voice: true` alone could never do that: it is a boolean, so a second voice\n * session was indistinguishable from the first and the transcript silently ran\n * them together. Two comments claimed the transcript was scoped to \"this\n * session\" while it was in fact showing the conversation's entire spoken\n * history.\n *\n * ★ OPTIONAL, and it has to stay optional. Every spoken turn recorded before\n * this field existed has `voice: true` and no id, and those conversations are\n * in users' localStorage right now. Anything that REQUIRED an id would erase\n * their history — so an absent id means \"some earlier session\", which is\n * exactly what it is, and never \"not a voice turn\".\n */\n voiceSessionId?: string;\n [key: string]: unknown;\n}\n\nexport interface Message {\n id: string;\n role: 'user' | 'assistant' | 'system';\n content: string;\n timestamp: string;\n tokens?: { input: number; output: number };\n metadata?: AssistantMessageMetadata;\n}\n\nexport interface Conversation {\n id: string;\n title: string;\n mode: AssistantMode;\n /**\n * EVERY turn, both surfaces — typed and spoken.\n *\n * ★ `readonly` on purpose, and it is load-bearing rather than hygiene. Voice\n * and chat share this one array; what separates them is `metadata.voice` plus\n * a filter at every reader, so the failure mode is a new reader that renders\n * the array as-is and silently spills spoken content into the typed thread.\n * Nothing about that is a type error, and it stays green in CI.\n *\n * Being readonly makes it one: components take `Message[]`, so handing them\n * this field directly no longer compiles. The way through is `chatTurns()` or\n * `voiceTurnsOnly()` (see `utils/voiceTurnVisibility`), both of which return a\n * fresh mutable array — which means picking a surface is now a step you cannot\n * skip by accident.\n *\n * Counting is still fine: `.length` answers \"is this conversation used at\n * all\", which is a question about the conversation and not about either\n * surface.\n */\n messages: readonly Message[];\n createdAt: string;\n updatedAt: string;\n /** Backend session ID for this conversation */\n backendSessionId?: string | null;\n}\n\nexport interface AssistantSandboxRuntime {\n sandboxId: string;\n status: AssistantSandboxStatus;\n}\n\nexport interface AssistantConversationProcessing {\n status: AssistantConversationStatus;\n messageId: string | null;\n error?: string | null;\n updatedAt: string;\n}\n\nexport interface AssistantModeConfig {\n id: AssistantMode;\n label: string;\n description: string;\n suggestions: readonly string[];\n /** Only offered to a global Owner/Admin (see useAssistantApiAccess). */\n requiresAdmin?: boolean;\n /** Executes mutations on live data → triggers the confirm-before-mutate guard. */\n writeCapable?: boolean;\n}\n\nexport const ASSISTANT_MODES: AssistantModeConfig[] = [...ASSISTANT_USECASE_CONFIG];\n"],"mappings":";;AAqJA,IAAa,IAAyC,CAAC,GAAG,CAAwB"}
|
|
@@ -3,15 +3,33 @@ function e(e) {
|
|
|
3
3
|
return e.metadata?.voice === !0;
|
|
4
4
|
}
|
|
5
5
|
function t(e) {
|
|
6
|
-
|
|
6
|
+
let t = e.metadata?.voiceSessionId;
|
|
7
|
+
return typeof t == "string" && t.length > 0 ? t : void 0;
|
|
7
8
|
}
|
|
8
|
-
function n(
|
|
9
|
-
return
|
|
9
|
+
function n(e) {
|
|
10
|
+
return e ? {
|
|
11
|
+
voice: !0,
|
|
12
|
+
voiceSessionId: e
|
|
13
|
+
} : {};
|
|
10
14
|
}
|
|
11
15
|
function r(t) {
|
|
16
|
+
return t.filter((t) => !e(t));
|
|
17
|
+
}
|
|
18
|
+
function i(t) {
|
|
12
19
|
return t.filter(e);
|
|
13
20
|
}
|
|
21
|
+
function a(e, t) {
|
|
22
|
+
let n = [];
|
|
23
|
+
for (let r of e) {
|
|
24
|
+
let e = t(r), i = n[n.length - 1];
|
|
25
|
+
i && i.sessionId === e ? i.turns.push(r) : n.push({
|
|
26
|
+
sessionId: e,
|
|
27
|
+
turns: [r]
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
return n;
|
|
31
|
+
}
|
|
14
32
|
//#endregion
|
|
15
|
-
export {
|
|
33
|
+
export { r as chatTurns, a as groupConsecutiveBySession, e as isVoiceTurn, n as voiceMarker, t as voiceSessionIdOf, i as voiceTurnsOnly };
|
|
16
34
|
|
|
17
35
|
//# sourceMappingURL=voiceTurnVisibility.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"voiceTurnVisibility.js","names":[],"sources":["../../src/utils/voiceTurnVisibility.ts"],"sourcesContent":["/**\n * Which surface does a turn belong to?\n *\n * Voice and chat share ONE conversation: the live session was built as an\n * overlay over the chat thread, so `submitVoiceTurn` calls the same `handleSend`\n * the composer does and both write into the same persisted `messages` array.\n * That is why every spoken exchange appeared in the typed thread, and why the\n * voice panel painted the last six messages of the whole conversation —\n * including typed replies full of `##` and `**`, which it renders as literal\n * text.\n *\n * One marker fixes both directions:\n * - the chat panel hides turns that happened in voice\n * - the voice panel shows ONLY turns that happened in voice\n *\n * ★ Deliberately a display split, not separate persistence. It survives a\n * reload because the chat transcript is never rehydrated from the backend — the\n * store is the only source of truth for what either panel shows. The backend\n * session is still shared, so the model keeps full context of the conversation\n * across both surfaces, which is what makes \"carry on where we left off\" work.\n * Genuinely separate backend sessions are a larger change and would cost that.\n */\n\ninterface TurnLike {\n metadata?: ({ voice?: boolean } & Record<string, unknown>) | undefined;\n}\n\n/** True when this turn happened inside a live voice session. */\nexport function isVoiceTurn(message: TurnLike): boolean {\n return message.metadata?.voice === true;\n}\n\n/**\n * The marker as a fragment to spread into a message's `metadata`.\n *\n * ★ `patchMessage` REPLACES `metadata` instead of merging it, so every write\n * that rebuilds the object has to re-assert this or the turn silently demotes\n * itself to a chat turn. That is exactly what shipped: the marker was stamped\n * at creation and destroyed the instant the reply completed, so a spoken answer\n * appeared in the typed thread AND disappeared from the voice transcript at the\n * same moment — the transcript could only ever show the user's questions.\n *\n * Spreading one helper at all four sites is what keeps them from drifting;\n * `voiceMarkerCallSitesAreComplete` in the test file fails the build if a new\n * metadata write forgets it.\n *\n * Takes the
|
|
1
|
+
{"version":3,"file":"voiceTurnVisibility.js","names":[],"sources":["../../src/utils/voiceTurnVisibility.ts"],"sourcesContent":["/**\n * Which surface does a turn belong to?\n *\n * Voice and chat share ONE conversation: the live session was built as an\n * overlay over the chat thread, so `submitVoiceTurn` calls the same `handleSend`\n * the composer does and both write into the same persisted `messages` array.\n * That is why every spoken exchange appeared in the typed thread, and why the\n * voice panel painted the last six messages of the whole conversation —\n * including typed replies full of `##` and `**`, which it renders as literal\n * text.\n *\n * One marker fixes both directions:\n * - the chat panel hides turns that happened in voice\n * - the voice panel shows ONLY turns that happened in voice\n *\n * ★ Deliberately a display split, not separate persistence. It survives a\n * reload because the chat transcript is never rehydrated from the backend — the\n * store is the only source of truth for what either panel shows. The backend\n * session is still shared, so the model keeps full context of the conversation\n * across both surfaces, which is what makes \"carry on where we left off\" work.\n * Genuinely separate backend sessions are a larger change and would cost that.\n */\n\ninterface TurnLike {\n metadata?: ({ voice?: boolean; voiceSessionId?: string } & Record<string, unknown>) | undefined;\n}\n\n/** True when this turn happened inside a live voice session. */\nexport function isVoiceTurn(message: TurnLike): boolean {\n return message.metadata?.voice === true;\n}\n\n/**\n * WHICH voice session produced this turn, if we know.\n *\n * ★ `undefined` is a real answer, not a failure: every spoken turn recorded\n * before session ids existed carries `voice: true` and nothing else, and those\n * conversations are in users' localStorage today. It means \"some earlier\n * session\" and must never be read as \"not spoken\" — `isVoiceTurn` remains the\n * only thing that decides which surface a turn belongs to.\n */\nexport function voiceSessionIdOf(message: TurnLike): string | undefined {\n const id = message.metadata?.voiceSessionId;\n return typeof id === 'string' && id.length > 0 ? id : undefined;\n}\n\n/**\n * The marker as a fragment to spread into a message's `metadata`.\n *\n * ★ `patchMessage` REPLACES `metadata` instead of merging it, so every write\n * that rebuilds the object has to re-assert this or the turn silently demotes\n * itself to a chat turn. That is exactly what shipped: the marker was stamped\n * at creation and destroyed the instant the reply completed, so a spoken answer\n * appeared in the typed thread AND disappeared from the voice transcript at the\n * same moment — the transcript could only ever show the user's questions.\n *\n * Spreading one helper at all four sites is what keeps them from drifting;\n * `voiceMarkerCallSitesAreComplete` in the test file fails the build if a new\n * metadata write forgets it.\n *\n * ★ Takes the SESSION ID rather than a boolean, and stamps both fields from it.\n * There used to be a separate `dictated` flag that call sites passed straight\n * through, which made it possible to mark a turn as spoken while recording no\n * session — a state with no meaning that only the transcript would ever notice.\n * One argument means the two can never disagree.\n *\n * An absent id yields an EMPTY object, so a typed turn gets no marker at all:\n * `chatTurns` is allow-by-default, and a stray `voice: false` would be a second\n * way of saying the same thing.\n */\nexport function voiceMarker(sessionId: string | undefined): { voice?: true; voiceSessionId?: string } {\n return sessionId ? { voice: true, voiceSessionId: sessionId } : {};\n}\n\n/**\n * The turns the CHAT panel should show: everything that was not spoken.\n *\n * Untagged turns are treated as chat, so every conversation recorded before the\n * marker existed keeps rendering exactly as it did.\n */\nexport function chatTurns<T extends TurnLike>(messages: readonly T[]): T[] {\n return messages.filter((message) => !isVoiceTurn(message));\n}\n\n/**\n * The turns the VOICE panel should show: only what was spoken.\n *\n * This is also what scopes the voice transcript to the session. Previously it\n * took the last six messages of the whole conversation, so opening voice on an\n * existing thread immediately painted typed replies — the wall of raw markdown\n * in the operator's screenshot.\n */\nexport function voiceTurnsOnly<T extends TurnLike>(messages: readonly T[]): T[] {\n return messages.filter(isVoiceTurn);\n}\n\n/** One microphone-on-to-End, and the turns it produced, oldest first. */\nexport interface VoiceSessionGroup<T> {\n /**\n * `undefined` for turns recorded before session ids existed. Rendered as one\n * leading group rather than dropped — it is real history the user spoke.\n */\n sessionId: string | undefined;\n turns: T[];\n}\n\n/**\n * Split spoken turns into the sessions that produced them.\n *\n * The transcript shows a conversation's whole spoken history, which is the more\n * useful of the two options — you can go back to what you asked last time — but\n * run together it reads as one long exchange, and a question from a session\n * three days ago looks like it was just asked. Grouping is what makes showing\n * everything honest.\n *\n * ★ Groups by RUNS, not by collecting every turn with the same id. Turns are\n * stored in the order they happened, so a run IS a session; gathering by id\n * instead would silently reorder history if two sessions ever interleaved, and\n * would hide it rather than show it if they did.\n *\n * ★ Consecutive un-stamped turns collapse into a single leading group. Treating\n * each as its own session would print a divider between every pre-existing turn\n * — one long exchange shattered into fragments, which is worse than the\n * undivided version this is meant to fix.\n */\nexport function groupBySession<T extends TurnLike>(turns: readonly T[]): VoiceSessionGroup<T>[] {\n return groupConsecutiveBySession(turns, voiceSessionIdOf);\n}\n\n/**\n * The same grouping for turns that have already been flattened for display.\n *\n * The transcript renders `{id, role, text}`, not `Message`, so it cannot reach\n * `metadata`. Passing the extractor keeps ONE implementation of the run logic\n * instead of a second copy that drifts — the subtle part is the `undefined`\n * merge, and having it in two places is how one of them stops doing it.\n */\nexport function groupConsecutiveBySession<T>(\n turns: readonly T[],\n sessionIdOf: (turn: T) => string | undefined\n): VoiceSessionGroup<T>[] {\n const groups: VoiceSessionGroup<T>[] = [];\n for (const turn of turns) {\n const sessionId = sessionIdOf(turn);\n const current = groups[groups.length - 1];\n // A run continues while the id is unchanged. `undefined === undefined` is\n // what merges the legacy turns, and is deliberate rather than incidental.\n if (current && current.sessionId === sessionId) current.turns.push(turn);\n else groups.push({ sessionId, turns: [turn] });\n }\n return groups;\n}\n\n/**\n * A spoken turn flattened for display.\n *\n * ★ Shared by every component between the chat area and the transcript, so the\n * session id is carried in the TYPE and not merely at runtime. The intermediate\n * props used to declare `{id, role, text}` while the objects flowing through\n * happened to have more: it compiled, and the dividers worked, purely because\n * JavaScript keeps the extra property. Any future refactor that rebuilt one of\n * those objects would have dropped the id and silently run every session back\n * together — the exact defect this field was added to fix, reintroduced with no\n * type error.\n */\nexport interface VoiceTranscriptTurn {\n id: string;\n role: 'user' | 'assistant';\n text: string;\n /**\n * `undefined` on turns recorded before session ids existed.\n *\n * ★ REQUIRED-but-nullable rather than optional, and the difference is the\n * whole point. With `sessionId?: string`, an object rebuilt without the key is\n * still structurally assignable — so a refactor that mapped turns through and\n * dropped it would compile, and every session would silently run back\n * together. Written this way, omitting the key is a type error and passing\n * `undefined` is a decision someone made on purpose.\n */\n sessionId: string | undefined;\n}\n"],"mappings":";AA4BA,SAAgB,EAAY,GAA4B;CACtD,OAAO,EAAQ,UAAU,UAAU;AACrC;AAWA,SAAgB,EAAiB,GAAuC;CACtE,IAAM,IAAK,EAAQ,UAAU;CAC7B,OAAO,OAAO,KAAO,YAAY,EAAG,SAAS,IAAI,IAAK,KAAA;AACxD;AA0BA,SAAgB,EAAY,GAA0E;CACpG,OAAO,IAAY;EAAE,OAAO;EAAM,gBAAgB;CAAU,IAAI,CAAC;AACnE;AAQA,SAAgB,EAA8B,GAA6B;CACzE,OAAO,EAAS,QAAQ,MAAY,CAAC,EAAY,CAAO,CAAC;AAC3D;AAUA,SAAgB,EAAmC,GAA6B;CAC9E,OAAO,EAAS,OAAO,CAAW;AACpC;AA2CA,SAAgB,EACd,GACA,GACwB;CACxB,IAAM,IAAiC,CAAC;CACxC,KAAK,IAAM,KAAQ,GAAO;EACxB,IAAM,IAAY,EAAY,CAAI,GAC5B,IAAU,EAAO,EAAO,SAAS;EAGvC,AAAI,KAAW,EAAQ,cAAc,IAAW,EAAQ,MAAM,KAAK,CAAI,IAClE,EAAO,KAAK;GAAE;GAAW,OAAO,CAAC,CAAI;EAAE,CAAC;CAC/C;CACA,OAAO;AACT"}
|
package/package.json
CHANGED