@burdenoff/microfe-healthybowl 2026.903.17 → 2026.903.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,102 +1,102 @@
1
1
  import { useAssistantSpeech as e } from "../components/assistant/AssistantSpeechProvider.js";
2
2
  import { useVoiceInput as t } from "./useVoiceInput.js";
3
- import { INITIAL_SESSION as n, INTERRUPT_MAX_MS as r, SILENCE_SUBMIT_MS as i, isCapturing as a, isSubmittable as o, planReplyConsumption as s, spokenSoFar as c, voiceSessionReducer as l } from "../utils/voiceSession.js";
4
- import { useCallback as u, useEffect as d, useMemo as f, useReducer as p, useRef as m, useState as h } from "react";
3
+ import { ENDPOINT_GRACE_MS as n, INITIAL_SESSION as r, INTERRUPT_MAX_MS as i, INTERRUPT_MIN_MS as a, SILENCE_SUBMIT_MS as o, isCapturing as s, isSubmittable as c, planReplyConsumption as l, spokenSoFar as u, voiceSessionReducer as d } from "../utils/voiceSession.js";
4
+ import { useCallback as f, useEffect as p, useMemo as m, useReducer as h, useRef as g, useState as _ } from "react";
5
5
  //#region src/hooks/useVoiceSession.ts
6
- var g = 4e3, _ = 2500, v = 5e3, y = 12e3, b = "data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA=";
7
- function x({ onSubmit: x, latestReply: S, language: C }) {
8
- let w = m(null), [T, E] = p(u((e, t) => l(e, t, w.current), []), n), D = e(), { setSessionSpeaking: O, speakingMessageId: k, stop: A } = D, j = m(null), M = m(null), N = m(!1), [P, F] = h(null), [I, L] = h(!1), [R, z] = h(!1), B = m(T);
9
- B.current = T;
10
- let V = m(S);
11
- V.current = S, d(() => {
12
- if (T.phase === "speaking") {
13
- w.current = S?.text ?? null;
6
+ var v = 4e3, y = 2500, b = 5e3, x = 12e3, S = "data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YQAAAAA=";
7
+ function C({ onSubmit: C, latestReply: w, language: T }) {
8
+ let E = g(null), [D, O] = h(f((e, t) => d(e, t, E.current), []), r), k = e(), { setSessionSpeaking: A, speakingMessageId: j, stop: M } = k, N = g(null), P = g(null), F = g(!1), [I, L] = _(null), [R, z] = _(!1), [B, V] = _(!1), H = g(D);
9
+ H.current = D;
10
+ let U = g(w);
11
+ U.current = w, p(() => {
12
+ if (D.phase === "speaking") {
13
+ E.current = w?.text ?? null;
14
14
  return;
15
15
  }
16
- if (w.current === null) return;
16
+ if (E.current === null) return;
17
17
  let e = setTimeout(() => {
18
- w.current = null;
19
- }, _);
18
+ E.current = null;
19
+ }, y);
20
20
  return () => clearTimeout(e);
21
- }, [T.phase, S]);
22
- let H = u((e, t) => {
23
- E({
21
+ }, [D.phase, w]);
22
+ let W = f((e, t) => {
23
+ O({
24
24
  type: "speech",
25
25
  transcript: e,
26
26
  final: t
27
27
  });
28
- }, []), U = m(0), W = u(() => {
29
- A(), U.current = Date.now(), L(!0), E({ type: "interrupt" });
30
- }, [A]), G = t({
31
- onFinalize: u((e) => H(e, !0), [H]),
32
- language: C
28
+ }, []), G = g(0), K = f(() => {
29
+ M(), G.current = Date.now(), z(!0), O({ type: "interrupt" });
30
+ }, [M]), q = t({
31
+ onFinalize: f((e) => W(e, !0), [W]),
32
+ language: T
33
33
  });
34
- d(() => {
35
- G.interim && H(G.interim, !1);
36
- }, [G.interim, H]), d(() => {
37
- if (j.current && clearTimeout(j.current), z(!1), T.phase !== "listening" || T.muted || !o(c(T))) return;
38
- let e = setTimeout(() => z(!0), 800);
39
- return j.current = setTimeout(() => E({ type: "silence" }), i), () => {
40
- clearTimeout(e), j.current && clearTimeout(j.current);
34
+ p(() => {
35
+ q.interim && W(q.interim, !1);
36
+ }, [q.interim, W]), p(() => {
37
+ if (N.current && clearTimeout(N.current), V(!1), D.phase !== "listening" || D.muted || !c(u(D))) return;
38
+ let e = setTimeout(() => V(!0), n);
39
+ return N.current = setTimeout(() => O({ type: "silence" }), o), () => {
40
+ clearTimeout(e), N.current && clearTimeout(N.current);
41
41
  };
42
- }, [T]), d(() => {
43
- if (!I) return;
44
- let e = Date.now() - U.current, t = G.isListening ? Math.max(0, 500 - e) : Math.max(0, r - e), n = setTimeout(() => L(!1), t);
42
+ }, [D]), p(() => {
43
+ if (!R) return;
44
+ let e = Date.now() - G.current, t = q.isListening ? Math.max(0, a - e) : Math.max(0, i - e), n = setTimeout(() => z(!1), t);
45
45
  return () => clearTimeout(n);
46
- }, [I, G.isListening]);
47
- let K = m("");
48
- T.phase === "listening" && (K.current = c(T)), d(() => {
49
- if (T.phase !== "thinking") return;
50
- let e = K.current.trim();
51
- e && x(e, q.current ?? `vs-orphan-${Date.now().toString(36)}`);
52
- }, [T.phase]), d(() => {
53
- let e = s(S?.id, T.phase, M.current);
54
- e.claim && (M.current = S?.id ?? null, e.advance && S && E({
46
+ }, [R, q.isListening]);
47
+ let J = g("");
48
+ D.phase === "listening" && (J.current = u(D)), p(() => {
49
+ if (D.phase !== "thinking") return;
50
+ let e = J.current.trim();
51
+ e && C(e, Y.current ?? `vs-orphan-${Date.now().toString(36)}`);
52
+ }, [D.phase]), p(() => {
53
+ let e = l(w?.id, D.phase, P.current);
54
+ e.claim && (P.current = w?.id ?? null, e.advance && w && O({
55
55
  type: "reply",
56
- text: S.text
56
+ text: w.text
57
57
  }));
58
- }, [S, T.phase]), d(() => {
59
- let e = k !== null;
60
- N.current && !e && E({ type: "speech-ended" }), N.current = e;
61
- }, [k]), d(() => {
62
- T.phase !== "listening" && F((e) => e === "nothing-heard" ? null : e);
63
- }, [T.phase]), d(() => {
64
- if (T.phase !== "speaking" || k !== null) return;
58
+ }, [w, D.phase]), p(() => {
59
+ let e = j !== null;
60
+ F.current && !e && O({ type: "speech-ended" }), F.current = e;
61
+ }, [j]), p(() => {
62
+ D.phase !== "listening" && L((e) => e === "nothing-heard" ? null : e);
63
+ }, [D.phase]), p(() => {
64
+ if (D.phase !== "speaking" || j !== null) return;
65
65
  let e = setTimeout(() => {
66
- N.current || E({ type: "speech-ended" });
67
- }, g);
66
+ F.current || O({ type: "speech-ended" });
67
+ }, v);
68
68
  return () => clearTimeout(e);
69
- }, [T.phase, k]), d(() => {
70
- a(T) ? G.isListening || G.start() : G.isListening && G.stop();
71
- }, [T, G]), d(() => {
72
- G.error === "not-allowed" || G.error === "audio-capture" ? E({
69
+ }, [D.phase, j]), p(() => {
70
+ s(D) ? q.isListening || q.start() : q.isListening && q.stop();
71
+ }, [D, q]), p(() => {
72
+ q.error === "not-allowed" || q.error === "audio-capture" ? O({
73
73
  type: "fail",
74
74
  error: "mic-denied"
75
- }) : G.error === "language-not-supported" ? E({
75
+ }) : q.error === "language-not-supported" ? O({
76
76
  type: "fail",
77
77
  error: "no-speech-support"
78
- }) : G.error === "network" ? F("network") : G.error === "unknown" && F("recognition-failed");
79
- }, [G.error]), d(() => {
80
- if (!a(T) || G.isListening) return;
81
- let e = setTimeout(() => F("not-capturing"), v);
78
+ }) : q.error === "network" ? L("network") : q.error === "unknown" && L("recognition-failed");
79
+ }, [q.error]), p(() => {
80
+ if (!s(D) || q.isListening) return;
81
+ let e = setTimeout(() => L("not-capturing"), b);
82
82
  return () => clearTimeout(e);
83
- }, [T, G.isListening]), d(() => {
84
- if (T.phase !== "listening" || T.muted || !G.isListening || c(T) !== "") return;
85
- let e = setTimeout(() => F("nothing-heard"), y);
83
+ }, [D, q.isListening]), p(() => {
84
+ if (D.phase !== "listening" || D.muted || !q.isListening || u(D) !== "") return;
85
+ let e = setTimeout(() => L("nothing-heard"), x);
86
86
  return () => clearTimeout(e);
87
- }, [T, G.isListening]), d(() => {
88
- c(T) !== "" && F(null);
89
- }, [T]);
90
- let q = m(null), J = u(() => {
91
- if (L(!1), z(!1), !G.isSupported) {
92
- E({
87
+ }, [D, q.isListening]), p(() => {
88
+ u(D) !== "" && L(null);
89
+ }, [D]);
90
+ let Y = g(null), X = f(() => {
91
+ if (z(!1), V(!1), !q.isSupported) {
92
+ O({
93
93
  type: "fail",
94
94
  error: "no-speech-support"
95
95
  });
96
96
  return;
97
97
  }
98
- if (D.isBlocked) {
99
- E({
98
+ if (k.isBlocked) {
99
+ O({
100
100
  type: "fail",
101
101
  error: "no-voice-support"
102
102
  });
@@ -111,54 +111,54 @@ function x({ onSubmit: x, latestReply: S, language: C }) {
111
111
  } catch {}
112
112
  try {
113
113
  if (typeof window < "u" && typeof window.Audio == "function") {
114
- let e = new window.Audio(b);
114
+ let e = new window.Audio(S);
115
115
  e.volume = 0, e.play().catch(() => {});
116
116
  }
117
117
  } catch {}
118
- O(!0), F(null), M.current = V.current?.id ?? null, q.current = `vs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`, E({ type: "start" });
118
+ A(!0), L(null), P.current = U.current?.id ?? null, Y.current = `vs-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`, O({ type: "start" });
119
119
  }, [
120
- G.isSupported,
121
- D.isBlocked,
122
- O
123
- ]), Y = u(() => {
124
- L(!1), z(!1), q.current = null, E({ type: "end" }), A(), O(!1);
125
- }, [A, O]), X = u(() => {
126
- E({
120
+ q.isSupported,
121
+ k.isBlocked,
122
+ A
123
+ ]), Z = f(() => {
124
+ z(!1), V(!1), Y.current = null, O({ type: "end" }), M(), A(!1);
125
+ }, [M, A]), Q = f(() => {
126
+ O({
127
127
  type: "mute",
128
- muted: !B.current.muted
128
+ muted: !H.current.muted
129
129
  });
130
130
  }, []);
131
- return d(() => () => {
132
- O(!1);
133
- }, [O]), f(() => ({
134
- session: T,
135
- notice: P,
136
- spokenChunks: D.spokenChunks,
137
- capturing: G.isListening,
138
- active: T.phase !== "idle" && (T.phase !== "ended" || T.error !== null),
139
- interrupting: I,
140
- awaitingEndpoint: R,
141
- available: G.isSupported && !D.isBlocked,
142
- start: J,
143
- end: Y,
144
- toggleMute: X,
145
- interrupt: W
131
+ return p(() => () => {
132
+ A(!1);
133
+ }, [A]), m(() => ({
134
+ session: D,
135
+ notice: I,
136
+ spokenChunks: k.spokenChunks,
137
+ capturing: q.isListening,
138
+ active: D.phase !== "idle" && (D.phase !== "ended" || D.error !== null),
139
+ interrupting: R,
140
+ awaitingEndpoint: B,
141
+ available: q.isSupported && !k.isBlocked,
142
+ start: X,
143
+ end: Z,
144
+ toggleMute: Q,
145
+ interrupt: K
146
146
  }), [
147
- T,
148
- P,
147
+ D,
149
148
  I,
150
149
  R,
151
- G.isListening,
152
- G.isSupported,
153
- D.isBlocked,
154
- D.spokenChunks,
155
- J,
156
- Y,
150
+ B,
151
+ q.isListening,
152
+ q.isSupported,
153
+ k.isBlocked,
154
+ k.spokenChunks,
157
155
  X,
158
- W
156
+ Z,
157
+ Q,
158
+ K
159
159
  ]);
160
160
  }
161
161
  //#endregion
162
- export { x as useVoiceSession };
162
+ export { C as useVoiceSession };
163
163
 
164
164
  //# sourceMappingURL=useVoiceSession.js.map
@@ -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 /**\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 /**\n * The reply as it is being spoken, chunk by chunk — for the live caption.\n *\n * Relayed from the speech provider rather than read there directly by the\n * UI, because the voice session is already this hook's contract with the\n * component and a second speech consumer would be a second way for the two\n * to disagree about what is playing.\n */\n spokenChunks: speech.spokenChunks,\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 // ★ Load-bearing. Without it this memo never recomputes as playback moves\n // from chunk to chunk, so the caption would freeze on the first sentence\n // and every later one would arrive only when some unrelated state\n // happened to change. The feature would look implemented and be silently\n // stuck — eslint's exhaustive-deps does not see through the destructured\n // `speech` object.\n speech.spokenChunks,\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,AALA,EAAe,UAAU,GAKzB,QAAgB;EACd,IAAI,EAAQ,UAAU,YAAY;GAChC,EAAc,UAAU,GAAa,QAAQ;GAC7C;EACF;EACA,IAAI,EAAc,YAAY,MAAM;EACpC,IAAM,IAAQ,iBAAiB;GAC7B,EAAc,UAAU;EAC1B,GA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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 /**\n * The reply as it is being spoken, chunk by chunk — for the live caption.\n *\n * Relayed from the speech provider rather than read there directly by the\n * UI, because the voice session is already this hook's contract with the\n * component and a second speech consumer would be a second way for the two\n * to disagree about what is playing.\n */\n spokenChunks: speech.spokenChunks,\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 // ★ Load-bearing. Without it this memo never recomputes as playback moves\n // from chunk to chunk, so the caption would freeze on the first sentence\n // and every later one would arrive only when some unrelated state\n // happened to change. The feature would look implemented and be silently\n // stuck — eslint's exhaustive-deps does not see through the destructured\n // `speech` object.\n speech.spokenChunks,\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,E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AM,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;EASA,cAAc,EAAO;EAErB,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;EAOP,EAAO;EACP;EACA;EACA;EACA;CACF,CACF;AACF"}
@@ -1,8 +1,2 @@
1
- var e = 1e3, t = 1500;
2
- function n(n) {
3
- return n < 6e3 ? 600 : n < 2e4 ? e : t;
4
- }
5
- //#endregion
6
- export { n as pollDelayMs };
7
-
8
- //# sourceMappingURL=assistantPollSchedule.js.map
1
+ import { pollDelayMs as e } from "@burdenoff/fe-libs/shared/assistant";
2
+ export { e as pollDelayMs };
@@ -1,51 +1,2 @@
1
- //#region src/utils/captionText.ts
2
- var e = "", t = "\\uE000", n = /^[\s:|-]*$/, r = /^\s*([-*_])\s*(?:\1\s*){2,}$/, i = /^\s*=+\s*$/;
3
- function a(e) {
4
- return e.includes("|") && e.includes("-") && n.test(e);
5
- }
6
- function o(e) {
7
- let t = /* @__PURE__ */ new Set();
8
- return e.forEach((n, r) => {
9
- if (!a(n)) return;
10
- let i = e[r - 1];
11
- r > 0 && i !== void 0 && i.includes("|") && t.add(r - 1);
12
- for (let n = r + 1; n < e.length; n += 1) {
13
- let r = e[n];
14
- if (r === void 0 || r.trim() === "" || !r.includes("|")) break;
15
- t.add(n);
16
- }
17
- }), t;
18
- }
19
- function s(n, r) {
20
- let i = (t) => (r.push(t), `${e}${r.length - 1}${e}`);
21
- return n.replace(/^ {0,3}```[^\n]*\n([\s\S]*?)^ {0,3}```[^\n]*$/gm, (e, t) => i(t.replace(/\n$/, ""))).replace(/^ {0,3}```[^\n]*\n?([\s\S]*)$/m, (e, t) => i(t)).replace(/`([^`\n]+)`/g, (e, t) => i(t)).replace(RegExp(`<((?:https?://|mailto:)[^>\\s${t}]+)>`, "gi"), (e, t) => i(t)).replace(RegExp(`<([^@<>\\s${t}]+@[^@<>\\s${t}]+\\.[^@<>\\s${t}]+)>`, "g"), (e, t) => i(t)).replace(RegExp(`\\b(?:https?://|www\\.)[^\\s<>()\\[\\]${t}]+`, "gi"), (e) => i(e)).replace(/\b[\w.+-]{1,64}@[\w-]{1,63}\.[\w.-]{1,63}\b/g, (e) => i(e));
22
- }
23
- function c(t, n) {
24
- let r = RegExp(`${e}(\\d+)${e}`, "g"), i = t;
25
- for (let e = 0; e <= n.length; e += 1) {
26
- let e = i.replace(r, (e, t) => n[Number(t)] ?? "");
27
- if (e === i) break;
28
- i = e;
29
- }
30
- return i;
31
- }
32
- function l(e) {
33
- return e.replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\[([^\]]*)\]\([^)]*\)/g, "$1").replace(/\[([^\]]*)\]\[[^\]]*\]/g, "$1").replace(/(^|[^\w~])~~(\S(?:[^\n]*?\S)?)~~(?=[^\w~]|$)/g, "$1$2").replace(/(^|[^\w*])\*\*(\S(?:[^\n]*?\S)?)\*\*(?=[^\w*]|$)/g, "$1$2").replace(/(^|[^\p{L}\p{N}_])__(\S(?:[^\n]*?\S)?)__(?=[^\p{L}\p{N}_]|$)/gu, "$1$2").replace(/(^|[^\w*])\*(\S(?:[^*\n]*\S)?)\*(?=[^\w*]|$)/g, "$1$2").replace(/(^|[^\p{L}\p{N}_])_(\S(?:[^_\n]*\S)?)_(?=[^\p{L}\p{N}_]|$)/gu, "$1$2");
34
- }
35
- function u(e) {
36
- return e.trim().replace(/^\|/, "").replace(/\|$/, "").split("|").map((e) => e.trim()).join(" · ");
37
- }
38
- function d(t) {
39
- if (!t) return "";
40
- let n = [], d = s(t.replace(/\r\n/g, "\n").replace(new RegExp(e, "g"), ""), n).split("\n"), f = o(d), p = [];
41
- return d.forEach((e, t) => {
42
- if (a(e) || r.test(e) || i.test(e) && (p[p.length - 1] ?? "").trim() !== "") return;
43
- let n = e;
44
- for (; /^\s*>\s?/.test(n);) n = n.replace(/^\s*>\s?/, "");
45
- n = n.replace(/^\s*#{1,6}\s+/, ""), n = n.replace(/^(\s*)[-*+]\s+/, "$1"), n = n.replace(/^(\s*)\d{1,2}[.)]\s+/, "$1"), f.has(t) && (n = u(n)), p.push(l(n).replace(/\s+$/, ""));
46
- }), c(p.join("\n").replace(/\n{3,}/g, "\n\n").trim(), n);
47
- }
48
- //#endregion
49
- export { d as toCaptionText };
50
-
51
- //# sourceMappingURL=captionText.js.map
1
+ import { toCaptionText as e } from "@burdenoff/fe-libs/shared/assistant";
2
+ export { e as toCaptionText };