@burdenoff/microfe-healthybowl 2026.903.16 → 2026.903.18
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 +26 -26
- package/dist/components/assistant/AssistantSpeechProvider.js +1 -2
- package/dist/components/assistant/AssistantSpeechProvider.js.map +1 -1
- package/dist/healthybowl/context/HealthyBowlContext.js +1 -2
- package/dist/healthybowl/context/HealthyBowlContext.js.map +1 -1
- package/dist/services/speech/index.js +2 -5
- package/package.json +2 -2
- package/dist/services/speech/browserSpeechEngine.js +0 -91
- package/dist/services/speech/browserSpeechEngine.js.map +0 -1
- package/dist/services/speech/createSpeechEngine.js +0 -44
- package/dist/services/speech/createSpeechEngine.js.map +0 -1
- package/dist/services/speech/hostedTtsProtocol.js +0 -44
- package/dist/services/speech/hostedTtsProtocol.js.map +0 -1
- package/dist/services/speech/hostedTtsSpeechEngine.js +0 -123
- package/dist/services/speech/hostedTtsSpeechEngine.js.map +0 -1
- package/dist/services/speech/hostedVoiceCatalogue.js +0 -58
- package/dist/services/speech/hostedVoiceCatalogue.js.map +0 -1
- package/dist/services/speech/routingSpeechEngine.js +0 -46
- package/dist/services/speech/routingSpeechEngine.js.map +0 -1
|
@@ -34,10 +34,10 @@ import { buildContinuedFromVoiceNote as Oe, buildVoiceTranscriptMarkdown as ke,
|
|
|
34
34
|
import { createReadinessTracker as je } from "../../utils/sandboxReadiness.js";
|
|
35
35
|
import { useCallback as E, useEffect as D, useMemo as O, useRef as k, useState as Me } from "react";
|
|
36
36
|
import { useI18n as Ne } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
|
|
37
|
-
import {
|
|
37
|
+
import { getAssistantMedia as A } from "@burdenoff/fe-libs/shared/assistant";
|
|
38
|
+
import { jsx as j, jsxs as Pe } from "react/jsx-runtime";
|
|
38
39
|
import { useGatewayClient as Fe } from "@burdenoff/fe-libs/shared/graphql";
|
|
39
40
|
import { useAuthToken as Ie } from "@burdenoff/fe-libs/shared/providers/shell";
|
|
40
|
-
import { getAssistantMedia as j } from "@burdenoff/fe-libs/shared/assistant";
|
|
41
41
|
//#region src/components/assistant/AssistantChatArea.tsx
|
|
42
42
|
var Le = {
|
|
43
43
|
general: 18e4,
|
|
@@ -69,7 +69,7 @@ function He(e, t) {
|
|
|
69
69
|
content: "Thinking...",
|
|
70
70
|
done: !1
|
|
71
71
|
};
|
|
72
|
-
let r = n[n.length - 1], i = N(r.parts), a =
|
|
72
|
+
let r = n[n.length - 1], i = N(r.parts), a = A(r.parts), o = P(r.parts), s = Ee(r.parts);
|
|
73
73
|
return {
|
|
74
74
|
content: [
|
|
75
75
|
i,
|
|
@@ -90,7 +90,7 @@ function Ue(e) {
|
|
|
90
90
|
}
|
|
91
91
|
}
|
|
92
92
|
var We = ({ visible: Ee = !0 }) => {
|
|
93
|
-
let
|
|
93
|
+
let A = t(), N = Fe("workspace"), { getAccessToken: P, getWorkspaceToken: We, userId: Ge } = Ie(), { locale: Ke } = Ne(), qe = e((e) => e.assistantLanguage), Je = e((e) => e.replyLanguage), Ye = O(() => ee(qe, Je, Ke), [
|
|
94
94
|
qe,
|
|
95
95
|
Je,
|
|
96
96
|
Ke
|
|
@@ -216,7 +216,7 @@ var We = ({ visible: Ee = !0 }) => {
|
|
|
216
216
|
content: `${C.content}\n\n_Still building in the background — any artifacts below will finish shortly. Re-open this conversation to pick up the completed plugin._`
|
|
217
217
|
}), i && (C = {
|
|
218
218
|
...C,
|
|
219
|
-
content: `${C.content}\n\n${
|
|
219
|
+
content: `${C.content}\n\n${A("healthybowl.assistant.attachments.imagesNotSent", "_Your photo was too large to include with this message, so the answer above is from the text and the file link only. Try a smaller or more tightly cropped photo._")}`
|
|
220
220
|
}), S(C.content, T, n, e), C.tokens) {
|
|
221
221
|
V(h, x, { tokens: C.tokens });
|
|
222
222
|
try {
|
|
@@ -264,7 +264,7 @@ var We = ({ visible: Ee = !0 }) => {
|
|
|
264
264
|
at,
|
|
265
265
|
R,
|
|
266
266
|
H,
|
|
267
|
-
|
|
267
|
+
A,
|
|
268
268
|
K,
|
|
269
269
|
Ge
|
|
270
270
|
]), Et = E((e) => {
|
|
@@ -302,14 +302,14 @@ var We = ({ visible: Ee = !0 }) => {
|
|
|
302
302
|
if (Y.length === 0) return;
|
|
303
303
|
let e = /* @__PURE__ */ new Date();
|
|
304
304
|
v(ke(Y, {
|
|
305
|
-
title:
|
|
306
|
-
savedAt:
|
|
307
|
-
session:
|
|
308
|
-
earlier:
|
|
309
|
-
you:
|
|
310
|
-
assistant:
|
|
305
|
+
title: A("healthybowl.assistant.voiceSession.transcript", "Voice conversation"),
|
|
306
|
+
savedAt: A("healthybowl.assistant.voiceSession.savedAt", "Saved"),
|
|
307
|
+
session: A("healthybowl.assistant.voiceSession.sessionLabel", "Session"),
|
|
308
|
+
earlier: A("healthybowl.assistant.voiceSession.earlierLabel", "Earlier"),
|
|
309
|
+
you: A("healthybowl.assistant.voiceSession.speakerYou", "You"),
|
|
310
|
+
assistant: A("healthybowl.assistant.voiceSession.speakerAssistant", "Assistant")
|
|
311
311
|
}, e), Ae(e), "text/markdown");
|
|
312
|
-
}, [Y,
|
|
312
|
+
}, [Y, A]), X = fe(), Z = k(X);
|
|
313
313
|
Z.current = X;
|
|
314
314
|
let Q = he({
|
|
315
315
|
onSubmit: E((e, t) => {
|
|
@@ -333,16 +333,16 @@ var We = ({ visible: Ee = !0 }) => {
|
|
|
333
333
|
id: Be(),
|
|
334
334
|
role: "system",
|
|
335
335
|
content: Oe(Y, {
|
|
336
|
-
intro:
|
|
337
|
-
nothing:
|
|
338
|
-
more: (e) =>
|
|
336
|
+
intro: A("healthybowl.assistant.voiceSession.continuedIntro", "Continued from a voice conversation. You asked about:"),
|
|
337
|
+
nothing: A("healthybowl.assistant.voiceSession.continuedNothing", "Continued from a voice conversation."),
|
|
338
|
+
more: (e) => A("healthybowl.assistant.voiceSession.continuedMore", "…and {{count}} more", { count: e })
|
|
339
339
|
}),
|
|
340
340
|
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
341
341
|
}), bt(!1), Q.end());
|
|
342
342
|
}, [
|
|
343
343
|
Y,
|
|
344
344
|
B,
|
|
345
|
-
|
|
345
|
+
A
|
|
346
346
|
]);
|
|
347
347
|
D(() => {
|
|
348
348
|
!Ee && Q.active && Q.end();
|
|
@@ -395,27 +395,27 @@ var We = ({ visible: Ee = !0 }) => {
|
|
|
395
395
|
className: "contents",
|
|
396
396
|
inert: Q.active || void 0,
|
|
397
397
|
children: [
|
|
398
|
-
Y.length > 0 && !Q.active ? /* @__PURE__ */
|
|
398
|
+
Y.length > 0 && !Q.active ? /* @__PURE__ */ j(ue, {
|
|
399
399
|
count: Y.length,
|
|
400
400
|
onOpenTranscript: () => bt(!0)
|
|
401
401
|
}) : null,
|
|
402
|
-
At.length === 0 ? /* @__PURE__ */
|
|
402
|
+
At.length === 0 ? /* @__PURE__ */ j(le, {
|
|
403
403
|
mode: I,
|
|
404
404
|
onSuggestionClick: Et
|
|
405
|
-
}) : /* @__PURE__ */
|
|
405
|
+
}) : /* @__PURE__ */ j("div", {
|
|
406
406
|
className: "flex min-h-0 flex-1 flex-col",
|
|
407
|
-
children: /* @__PURE__ */
|
|
407
|
+
children: /* @__PURE__ */ j(T, {
|
|
408
408
|
messages: At,
|
|
409
409
|
streamingMessageId: dt,
|
|
410
410
|
failedMessageId: ft,
|
|
411
411
|
onRetry: Dt
|
|
412
412
|
})
|
|
413
413
|
}),
|
|
414
|
-
/* @__PURE__ */
|
|
414
|
+
/* @__PURE__ */ j(pe, {
|
|
415
415
|
onStartVoiceSession: Q.available && I !== "api-calls" ? Q.start : void 0,
|
|
416
416
|
onSend: (e, t) => void q(e, t),
|
|
417
417
|
disabled: ut,
|
|
418
|
-
placeholder: I === "api-calls" ?
|
|
418
|
+
placeholder: I === "api-calls" ? A("healthybowl.assistant.chatArea.placeholderActions", "What would you like me to do?") : A("healthybowl.assistant.chatArea.placeholderGeneral", "Ask HealthyBowl anything…"),
|
|
419
419
|
mode: I,
|
|
420
420
|
writeAccessDenied: ht === "denied" && !!wt?.writeCapable,
|
|
421
421
|
availableModes: gt,
|
|
@@ -423,12 +423,12 @@ var We = ({ visible: Ee = !0 }) => {
|
|
|
423
423
|
})
|
|
424
424
|
]
|
|
425
425
|
}),
|
|
426
|
-
yt && !Q.active ? /* @__PURE__ */
|
|
426
|
+
yt && !Q.active ? /* @__PURE__ */ j(de, {
|
|
427
427
|
turns: Y,
|
|
428
428
|
onClose: () => bt(!1),
|
|
429
429
|
onSave: jt
|
|
430
430
|
}) : null,
|
|
431
|
-
Q.active && /* @__PURE__ */
|
|
431
|
+
Q.active && /* @__PURE__ */ j(me, {
|
|
432
432
|
session: Q.session,
|
|
433
433
|
notice: Q.notice,
|
|
434
434
|
capturing: Q.capturing,
|
|
@@ -449,7 +449,7 @@ var We = ({ visible: Ee = !0 }) => {
|
|
|
449
449
|
onToggleMute: Q.toggleMute,
|
|
450
450
|
onEnd: Q.end
|
|
451
451
|
}),
|
|
452
|
-
/* @__PURE__ */
|
|
452
|
+
/* @__PURE__ */ j(se, {
|
|
453
453
|
open: _t !== null,
|
|
454
454
|
onConfirm: Pt,
|
|
455
455
|
onCancel: Ft
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { getSpeechEngine as e } from "../../services/speech/
|
|
2
|
-
import "../../services/speech/index.js";
|
|
1
|
+
import { getSpeechEngine as e } from "../../services/speech/index.js";
|
|
3
2
|
import { useAssistantStore as t } from "../../store/assistantStore.js";
|
|
4
3
|
import { useTr as n } from "../../shared/hooks/useTr.js";
|
|
5
4
|
import { isVoiceTurn as r } from "../../utils/voiceTurnVisibility.js";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantSpeechProvider.js","names":[],"sources":["../../../src/components/assistant/AssistantSpeechProvider.tsx"],"sourcesContent":["/**\n * Speech-output context for the assistant panel (BOFF-6290).\n *\n * The assistant could already hear (`useVoiceInput`); this is the other half —\n * it can now answer out loud. That matters for a farming product where the user\n * is outdoors with dirty hands, a phone in a pocket and sun on the screen, and\n * it is a plain accessibility win everywhere else.\n *\n * Everything stateful about playback lives here, once, so that:\n *\n * - **playback is never orphaned.** A voice that keeps talking after the UI is\n * gone is a bug, so speech is cancelled when the panel hides, when the\n * conversation changes, on unmount, and on `pagehide` (Chrome keeps speaking\n * across a navigation otherwise);\n * - **only one message speaks at a time.** Starting a new playback cancels the\n * previous one — enforced by the engine and by the request-id guard in\n * `speechPlaybackReducer`;\n * - **nothing ever autoplays.** Playback starts from a button press. The\n * persisted auto-speak preference defaults OFF and is opt-in from the header.\n *\n * Components consume this through `useAssistantSpeech()`, which falls back to an\n * inert value when there is no provider (Storybook, a header rendered on its\n * own) rather than throwing.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type FC,\n type ReactNode,\n} from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { voicePreviewText } from '@/utils/voicePreview';\nimport { getSpeechEngine } from '../../services/speech';\nimport type { SpeechEngine, SpeechVoiceLike } from '../../services/speech';\nimport { chunkForSpeech, toSpeakableText, type SpeakableLabels } from '../../utils/speakableText';\nimport { speechLabelsFor } from '../../config/speechLabels';\n\n/**\n * The speakable transformation with nothing of ours added — used ONLY to decide\n * the reply's language.\n *\n * Detection needs the prose that will be spoken: code blocks and URLs stripped\n * (they are never read aloud, and their Latin identifiers would outvote short\n * non-Latin prose), but no substitute wording introduced either (that would let\n * our own app-locale words vote instead).\n */\nconst SILENT_LABELS: SpeakableLabels = {\n codeBlock: '',\n image: '',\n link: '',\n largeTable: '',\n truncated: '',\n emailAt: 'at',\n emailDot: 'dot',\n nestedItem: '',\n};\nimport {\n VOICE_LIST_TIMEOUT_MS,\n languageDisplayName,\n selectVoiceForLocale,\n voicesForLocale,\n speechGate,\n speechLangForLocale,\n voiceAvailability,\n type VoiceAvailability,\n} from '../../utils/speechVoices';\nimport { resolveSpeechLocale } from '../../utils/replyLanguage';\nimport { DEFAULT_SPEECH_RATE, findAssistantLanguage } from '../../config/assistantLanguages';\nimport { resolveLanguagePair } from '../../config/assistantLanguagePair';\nimport { IDLE_PLAYBACK, isSpeakingMessage, speechPlaybackReducer } from '../../utils/speechPlayback';\nimport { isVoiceTurn } from '../../utils/voiceTurnVisibility';\nimport { isTurnInFlight } from '../../utils/assistantTurnState';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport interface AssistantSpeechContextValue {\n /** False when the platform has no speech output — hide the control entirely. */\n isSupported: boolean;\n availability: VoiceAvailability;\n /**\n * True when nothing can be spoken in the app language, so every control that\n * starts playback — the per-message button AND the header toggle — must be\n * inert. `pending` is not blocked: see `speechGate`.\n */\n isBlocked: boolean;\n /** Explains a disabled control (no installed voice for the app language). */\n disabledReason: string | null;\n /**\n * Why THIS message cannot be spoken, when the app language is fine but the\n * reply is not in it — a Tamil answer in an English UI on a device with no\n * Tamil voice. `isBlocked` cannot see that: it is computed before any reply\n * exists. Without this the control looks enabled and silently refuses, which\n * is the dead-button bug all over again (BOFF-7106).\n */\n blockedFor: (messageId: string) => string | null;\n /**\n * Every installed voice that can read the language the user speaks, best\n * first. Empty when there is no choice to offer — the picker hides itself\n * rather than showing a one-item dropdown.\n */\n voiceChoices: readonly SpeechVoiceLike[];\n /** The voice that will actually be used, resolved from the pick + ranking. */\n /**\n * The reply as it is being SPOKEN: every chunk, plus the one sounding now.\n *\n * `null` when nothing is playing. `index: -1` means chunked but not yet\n * audible. Consumers reveal `chunks[0..index]` — anything beyond that is the\n * caption running ahead of the voice.\n */\n spokenChunks: { chunks: string[]; index: number } | null;\n activeVoiceName: string | null;\n /**\n * The RAW stored pick: `null` means \"use the ranked default\".\n *\n * The picker must be driven by this rather than by `activeVoiceName`, or the\n * two states collapse — with nothing stored, the ranked winner is already the\n * shown option, so choosing it fires no change event and the pick can never\n * be made. The user's voice would then silently move the next time the device\n * installs a higher-ranked one. Same trap as the language selector.\n */\n preferredVoiceName: string | null;\n /** `null` restores the ranked default for the current language. */\n setVoice: (voiceName: string | null) => void;\n /** The message currently being spoken, if any. */\n speakingMessageId: string | null;\n isSpeaking: (messageId: string) => boolean;\n /**\n * Speak this message, or stop if it is already the one speaking.\n *\n * `turnLocale` is the language the reply was GENERATED under, from the\n * message's own metadata. It matters because script detection cannot separate\n * Latin-script languages, so without it an old French reply would be read\n * with whatever voice the CURRENT preference selects.\n */\n toggle: (messageId: string, markdown: string, turnLocale?: string) => void;\n stop: () => void;\n autoSpeakEnabled: boolean;\n setAutoSpeak: (enabled: boolean) => void;\n /**\n * Speak replies for the duration of a live voice session, WITHOUT touching the\n * user's saved preference.\n *\n * ★ Live Voice used to force `autoSpeakEnabled` true and restore it on exit.\n * That field is PERSISTED (assistantStore partialize), and the restore only\n * ran on a clean `end()` — so a reload, a closed tab or a backgrounded webview\n * during a session left auto-speak switched ON for the user permanently, in\n * normal typed chat, with the toggle showing a state they never chose. The\n * default was never wrong; the session was overwriting it.\n *\n * Session-scoped React state instead: it cannot outlive the page, so there is\n * nothing to restore and nothing to leak.\n */\n sessionSpeaking: boolean;\n setSessionSpeaking: (enabled: boolean) => void;\n /** Play a short sample in a named voice. No model call, no message, no tokens. */\n previewVoice: (voiceName: string) => void;\n}\n\nconst INERT_SPEECH: AssistantSpeechContextValue = {\n isSupported: false,\n availability: 'unsupported',\n isBlocked: true,\n disabledReason: null,\n blockedFor: () => null,\n voiceChoices: [],\n spokenChunks: null,\n activeVoiceName: null,\n preferredVoiceName: null,\n setVoice: () => {},\n speakingMessageId: null,\n isSpeaking: () => false,\n toggle: () => {},\n stop: () => {},\n autoSpeakEnabled: false,\n setAutoSpeak: () => {},\n sessionSpeaking: false,\n setSessionSpeaking: () => {},\n previewVoice: () => {},\n};\n\nconst AssistantSpeechContext = createContext<AssistantSpeechContextValue>(INERT_SPEECH);\n\nexport function useAssistantSpeech(): AssistantSpeechContextValue {\n return useContext(AssistantSpeechContext);\n}\n\ninterface Props {\n children: ReactNode;\n /** Panel visibility. Hiding the panel stops the voice. */\n visible?: boolean;\n /**\n * Injectable for tests and local experiments. The default routes between the\n * device engine and the hosted one; with hosted TTS unconfigured it IS the\n * device engine, unchanged.\n */\n engine?: SpeechEngine;\n}\n\nexport const AssistantSpeechProvider: FC<Props> = ({ children, visible = true, engine = getSpeechEngine() }) => {\n const tr = useTr();\n const { locale } = useI18n();\n const [playback, dispatch] = useReducer(speechPlaybackReducer, IDLE_PLAYBACK);\n const [voices, setVoices] = useState<SpeechVoiceLike[]>(() => engine.listVoices());\n /**\n * True once we have waited out the voice list and it was still empty.\n *\n * Turns an indefinite `pending` into a terminal `no-voices`, which is what\n * lets the control be disabled with a reason instead of silently doing\n * nothing on every press.\n */\n const [voiceProbeSettled, setVoiceProbeSettled] = useState(false);\n /**\n * Every message we have refused, and why — keyed by id (see `blockedFor`).\n *\n * A single record could only describe one refusal: refusing a second reply\n * silently re-enabled the first, whose voice was still just as missing, so\n * pressing the buttons walked the disabled state around the transcript.\n */\n const [unspeakable, setUnspeakable] = useState<ReadonlyMap<string, string>>(() => new Map());\n const requestRef = useRef(0);\n\n /**\n * Which chunk of the current reply is sounding right now.\n *\n * ★ `index: -1` means \"chunked, nothing playing yet\" — distinct from no\n * progress at all, so the caption can stay empty until audio genuinely starts\n * instead of flashing the first sentence while the engine is still fetching.\n */\n const [spokenProgress, setSpokenProgress] = useState<{\n requestId: number;\n chunks: string[];\n index: number;\n } | null>(null);\n /** Cancels a playback that is waiting for the engine's voice list, if any. */\n const pendingRef = useRef<(() => void) | null>(null);\n const speakWithRef = useRef<\n (messageId: string, text: string, voices: readonly SpeechVoiceLike[], speechLocale: string) => void\n >(() => {});\n\n const cancelPending = useCallback(() => {\n pendingRef.current?.();\n pendingRef.current = null;\n }, []);\n\n const autoSpeakEnabled = useAssistantStore((state) => state.autoSpeakEnabled);\n const setAutoSpeak = useAssistantStore((state) => state.setAutoSpeak);\n // Not in the store on purpose — see `sessionSpeaking` on the context type.\n const [sessionSpeaking, setSessionSpeaking] = useState(false);\n const activeConversationId = useAssistantStore((state) => state.activeConversationId);\n\n const isSupported = useMemo(() => engine.isSupported(), [engine]);\n\n // getVoices() is empty on the first call in Chrome and only fills in when\n // 'voiceschanged' fires; Safari populates it synchronously and may never fire\n // the event. Read eagerly AND subscribe, so both engines end up correct.\n useEffect(() => {\n if (!isSupported) return;\n const sync = () => {\n setVoices(engine.listVoices());\n // Every recorded refusal was \"no voice for this language\". A new voice\n // list may well have supplied one — most likely because the user just\n // followed our instructions and installed it. Keeping the refusals would\n // leave those buttons disabled with no way back except a reload.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n sync();\n return engine.subscribeVoices(sync);\n }, [engine, isSupported]);\n\n // The language being SPOKEN ALOUD — which is the language of the reply, not\n // of the input and not of the interface. The two were one field until the\n // reply language was split out (BOFF-7108).\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const replyLanguage = useAssistantStore((state) => state.replyLanguage);\n const preferredVoices = useAssistantStore((state) => state.preferredVoices);\n const setPreferredVoice = useAssistantStore((state) => state.setPreferredVoice);\n const spokenLanguage = useMemo(\n // ★ The REPLY language, not the input. This is the language of the text\n // being spoken, so wiring it to the input would give a Tamil voice reading\n // an English answer the moment the two are set differently — the single\n // worst outcome available here, and the reason they were split at all.\n () => resolveLanguagePair(assistantLanguage, replyLanguage, locale).reply,\n [assistantLanguage, replyLanguage, locale]\n );\n const spokenLocale = spokenLanguage.code;\n\n /**\n * BCP-47 tag to ask the engine for, given a resolved language CODE.\n *\n * Resolved through the catalogue for ANY known code, not merely the currently\n * selected one — a historical Bengali reply must still get `bn-IN` after the\n * user switches to Tamil, or with both `bn-IN` and `bn-BD` installed the\n * engine's own order decides, and picks the wrong country.\n *\n * Falls back to the generic table for codes the catalogue does not carry.\n */\n const tagFor = useCallback((code: string) => findAssistantLanguage(code)?.tag ?? speechLangForLocale(code), []);\n\n /** Speaking rate for a resolved language code — see `AssistantLanguage.rate`. */\n const rateFor = useCallback((code: string) => findAssistantLanguage(code)?.rate ?? DEFAULT_SPEECH_RATE, []);\n\n const availability = useMemo(\n () => voiceAvailability(isSupported, voices, spokenLanguage.tag, voiceProbeSettled),\n [isSupported, voices, spokenLanguage, voiceProbeSettled]\n );\n\n // Spoken placeholders follow the app locale like the rest of the copy; the\n // transformation itself stays a pure function by taking them as arguments.\n const labels = useMemo<SpeakableLabels>(\n () => ({\n codeBlock: tr('healthybowl.assistant.speech.codeBlock', 'Code block'),\n image: tr('healthybowl.assistant.speech.image', 'image'),\n link: tr('healthybowl.assistant.speech.link', 'link'),\n largeTable: tr('healthybowl.assistant.speech.largeTable', 'Table with {{rows}} rows and {{columns}} columns'),\n truncated: tr('healthybowl.assistant.speech.truncated', 'The rest of this message is not read aloud'),\n nestedItem: tr('healthybowl.assistant.speech.nestedItem', 'Sub-item {{ordinal}}'),\n emailAt: tr('healthybowl.assistant.speech.emailAt', 'at'),\n emailDot: tr('healthybowl.assistant.speech.emailDot', 'dot'),\n }),\n [tr]\n );\n\n const stop = useCallback(() => {\n cancelPending();\n engine.cancel();\n dispatch({ type: 'stop' });\n }, [cancelPending, engine]);\n\n /**\n * Audition a voice — no model call, no message, no tokens.\n *\n * ★ Speaks through the engine DIRECTLY rather than through `speakWith`. That\n * path is built around a message: it resolves the reply's language, records\n * per-message \"cannot speak this\" state, and drives `speakingMessageId` so a\n * Listen button can light up. A preview has no message, so borrowing it would\n * mean inventing a fake id and then teaching every consumer to ignore it.\n *\n * Consequently it deliberately does NOT touch playback state: auditioning a\n * voice must not make a Listen button in the thread appear to be playing.\n *\n * Speaks the sample in the language being spoken, not the interface language —\n * the listener is judging how this voice reads THAT language.\n */\n const previewVoice = useCallback(\n (voiceName: string) => {\n const voice = engine.listVoices().find((candidate) => candidate.name === voiceName) ?? null;\n // An unknown name means the list changed under us (a download finished, a\n // profile switched). Silence is the right answer — better than falling\n // back to some other voice and auditioning the wrong one.\n if (!voice) return;\n // Whatever is speaking now is not what the user asked to hear.\n stop();\n engine.speak([voicePreviewText(spokenLocale)], { voice, lang: tagFor(spokenLocale) });\n },\n [engine, spokenLocale, stop, tagFor]\n );\n\n const blockedFor = useCallback((messageId: string) => unspeakable.get(messageId) ?? null, [unspeakable]);\n\n /**\n * Hold one playback until the engine publishes its voice list.\n *\n * Bounded: on timeout we take one last look and decide with whatever is\n * there, so an engine that never fires `voiceschanged` costs a two-second\n * wait rather than a control that is disabled forever. Nothing is spoken from\n * here unless a list actually arrives — an empty list means the engine would\n * pick its own default voice, which is the cross-language read this feature\n * promises never to do.\n */\n const waitForVoices = useCallback(\n (messageId: string, text: string, speechLocale: string) => {\n cancelPending();\n\n let settled = false;\n let unsubscribe = () => {};\n const finish = (available: SpeechVoiceLike[]) => {\n if (settled) return;\n settled = true;\n pendingRef.current = null;\n clearTimeout(timer);\n unsubscribe();\n if (available.length === 0) {\n // We waited and looked again: this device has no voices at all.\n // Record it so `availability` becomes `no-voices` and the control\n // explains itself, instead of returning silently every press.\n setVoiceProbeSettled(true);\n return;\n }\n setVoices(available);\n speakWithRef.current(messageId, text, available, speechLocale);\n };\n\n const timer = setTimeout(() => finish(engine.listVoices()), VOICE_LIST_TIMEOUT_MS);\n unsubscribe = engine.subscribeVoices(() => finish(engine.listVoices()));\n\n pendingRef.current = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n unsubscribe();\n pendingRef.current = null;\n };\n },\n [cancelPending, engine]\n );\n\n /**\n * Speak text against a KNOWN voice list.\n *\n * Every playback path funnels through here — the per-message button, the\n * header toggle's auto-speak, the store subscription — so the language gate\n * cannot be bypassed by any of them. Reading a Tamil reply with an English\n * voice is confident nonsense; it has to be impossible, not merely unlikely.\n */\n const speakWith = useCallback(\n (messageId: string, text: string, available: readonly SpeechVoiceLike[], speechLocale: string) => {\n let known = available;\n\n // Chrome answers the FIRST getVoices() with [] and fills the list in\n // asynchronously. One more synchronous read usually settles it.\n if (known.length === 0) {\n const refreshed = engine.listVoices();\n if (refreshed.length > 0) {\n known = refreshed;\n setVoices(refreshed);\n }\n }\n\n const speechLang = tagFor(speechLocale);\n\n const gate = speechGate(voiceAvailability(true, known, speechLocale, voiceProbeSettled));\n if (gate === 'block') {\n // Recorded for THIS message, always. Availability is resolved per reply\n // now, so a global \"your language has no voice\" cannot stand in for it:\n // the language the user chose to converse in says nothing about the one\n // this particular reply came back in.\n const reason = tr(\n 'healthybowl.assistant.speech.noVoiceForReply',\n 'This reply is in {{language}}, and no {{language}} voice is installed on this device.',\n { language: languageDisplayName(speechLang, locale) }\n );\n setUnspeakable((current) => new Map(current).set(messageId, reason));\n return;\n }\n if (gate === 'wait-for-voices') {\n waitForVoices(messageId, text, speechLocale);\n return;\n }\n\n setUnspeakable((current) => {\n if (!current.has(messageId)) return current;\n const next = new Map(current);\n next.delete(messageId);\n return next;\n });\n\n const requestId = requestRef.current + 1;\n requestRef.current = requestId;\n dispatch({ type: 'start', messageId, requestId });\n\n // ★ Chunked ONCE and kept, so the caption can show exactly what is being\n // spoken rather than a parallel rendering of the same markdown. A live\n // caption whose words differ from the audio is not a caption.\n const chunks = chunkForSpeech(text);\n setSpokenProgress({ requestId, chunks, index: -1 });\n\n engine.speak(\n chunks,\n // The TAG, not the code — so exact regional matching gets its chance\n // before the same-language fallback. `rate` had never been passed at\n // all, so every reply was read at the engine default.\n {\n voice: selectVoiceForLocale(known, speechLang, preferredVoices[speechLocale]),\n lang: speechLang,\n rate: rateFor(speechLocale),\n },\n {\n // Guarded on the request id like every other handler here: a stale\n // batch that has not noticed its cancellation must not drive the\n // caption of the reply that replaced it.\n onChunkStart: (index) =>\n setSpokenProgress((current) => (current?.requestId === requestId ? { ...current, index } : current)),\n onEnd: () => dispatch({ type: 'finished', requestId }),\n // Includes the 'cancelled' every queued utterance reports when we\n // pre-empt a batch; the request-id guard drops those as stale.\n onError: () => dispatch({ type: 'failed', requestId }),\n }\n );\n },\n [engine, locale, preferredVoices, rateFor, tagFor, tr, voiceProbeSettled, waitForVoices]\n );\n\n // `waitForVoices` resumes through this ref, so the two do not become a\n // circular hook dependency.\n useEffect(() => {\n speakWithRef.current = speakWith;\n }, [speakWith]);\n\n const speak = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (!isSupported) return;\n\n // Resolve the reply's language BEFORE building the spoken text, because\n // the stand-in words must be in that language. Detection deliberately runs\n // on a SILENT_LABELS pass — our own words must not vote on which language\n // the reply is in — so it does not depend on the labels chosen here.\n const replyLocale = resolveSpeechLocale(\n toSpeakableText(markdown, { labels: SILENT_LABELS }),\n turnLocale ?? spokenLocale\n );\n\n // ★ Labels in the REPLY's language, not the interface's. An English\n // interface reading a Tamil answer used to say \"Code block\" and \"image\" in\n // English, mid-Tamil-sentence — the same defect the email `at`/`dot` fix\n // addressed and did not generalise.\n const text = toSpeakableText(markdown, { labels: speechLabelsFor(replyLocale, labels) });\n if (!text) return;\n\n // Detect on the text that will actually be SPOKEN, with our own words\n // removed — neither the raw markdown nor the finished transformation.\n //\n // The transformation injects app-locale placeholders (\"Code block\"), which\n // let English chrome outvote short non-Latin prose. The raw markdown keeps\n // fenced code, whose Latin identifiers do the same thing — and that code is\n // never spoken at all. Running the same transformation with EMPTY labels\n // strips the unspoken constructs while contributing no words of its own,\n // which is exactly the denominator the decision needs.\n // The turn's OWN language first — the preference is only a stand-in for\n // replies that predate it. Resolved above, and reused rather than\n // recomputed.\n speakWith(messageId, text, voices, replyLocale);\n },\n [isSupported, labels, spokenLocale, speakWith, voices]\n );\n\n const toggle = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (isSpeakingMessage(playback, messageId)) {\n stop();\n return;\n }\n speak(messageId, markdown, turnLocale);\n },\n [playback, speak, stop]\n );\n\n // ── Never leave a voice talking to an empty room ─────────────────────────\n useEffect(() => {\n if (!visible) stop();\n }, [visible, stop]);\n\n useEffect(() => {\n // Switching (or creating) a conversation abandons the reply being read —\n // and the refusal explained a message that is no longer on screen.\n stop();\n setUnspeakable(new Map());\n }, [activeConversationId, stop]);\n\n useEffect(() => {\n // Every refusal was decided against the locale in force at the time, which\n // is what a Latin-script reply falls back to. Change the locale and those\n // verdicts may simply be wrong — an English reply refused on a\n // Spanish-only device would stay disabled forever after switching the UI to\n // Spanish, with the voice that could read it already installed.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n // And stop anything mid-sentence. The new language can make this message\n // unspeakable, which disables its button — leaving it reading \"Stop\" with no\n // way to actually stop, short of closing the panel.\n stop();\n }, [spokenLocale, stop]);\n\n useEffect(() => {\n return () => {\n pendingRef.current?.();\n pendingRef.current = null;\n engine.cancel();\n };\n }, [engine]);\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n // Chrome carries speech across a same-tab navigation and a bfcache restore\n // would otherwise come back mid-sentence.\n const handlePageHide = () => engine.cancel();\n window.addEventListener('pagehide', handlePageHide);\n return () => window.removeEventListener('pagehide', handlePageHide);\n }, [engine]);\n\n // ── One timeout is not a life sentence ───────────────────────────────────\n //\n // `no-voices` disables the control, and a disabled control can never reach\n // `speakWith` — the only path that re-reads `engine.listVoices()`. So without\n // this, a user who follows our own advice, leaves to install a voice and comes\n // back stays blocked until a reload: we would be telling them how to fix it\n // and then refusing to notice that they had.\n //\n // Returning to the tab is exactly when that happens, and it costs one\n // synchronous read of an already-populated list.\n useEffect(() => {\n if (typeof document === 'undefined' || !isSupported) return;\n const reprobe = () => {\n if (document.visibilityState !== 'visible') return;\n // Adopt the list UNCONDITIONALLY, including an empty one. Keeping the old\n // cache on an empty read means a user who uninstalled their last voice\n // stays `ready`, and playback then hands the engine a voice object that no\n // longer exists instead of explaining the problem.\n //\n // Safe to accept an empty read here precisely because the probe verdict is\n // cleared on the next line: empty + unsettled is `pending`, which leaves\n // the control ENABLED and defers the real decision to the next press.\n const available = engine.listVoices();\n // A Listen press may still be inside its two-second wait. Adopting voices\n // here flips the control to `ready`, so the user can press again and start\n // playback — and then the original timer fires, calls back into\n // `speakWith` for the same message, and the engine cancels and restarts it\n // mid-sentence. Retire the waiter as part of adopting the list.\n if (available.length > 0) cancelPending();\n setVoices(available);\n setVoiceProbeSettled(false);\n // Same reason the `voiceschanged` path clears them: every refusal meant\n // \"no voice for this language\", and this is the moment a user who went\n // away to install one comes back. `subscribeVoices` does not fire on an\n // eventless engine, which is precisely why this re-probe exists — so it\n // has to expire the refusals too.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n document.addEventListener('visibilitychange', reprobe);\n window.addEventListener('focus', reprobe);\n return () => {\n document.removeEventListener('visibilitychange', reprobe);\n window.removeEventListener('focus', reprobe);\n };\n }, [cancelPending, engine, isSupported]);\n\n // ── Opt-in auto-speak ────────────────────────────────────────────────────\n const speakRef = useRef(speak);\n useEffect(() => {\n speakRef.current = speak;\n }, [speak]);\n\n useEffect(() => {\n // `isBlocked` is the same gate the per-message button uses. Without it the\n // subscription fires on a device with no voice for the app language and the\n // engine reads a Tamil reply in English — the one thing this feature says\n // it will never do. `pending` is allowed through because `speakWith` waits\n // for the list before deciding.\n // NOT gated on `isSpeechBlocked(availability)` any more: that is the APP\n // language's availability, and it would suppress auto-speak for a reply in\n // a language this device CAN speak. `speakWith` resolves the reply's own\n // language and refuses safely there, which is the only place that can know.\n // Either the user's own preference, or a live voice session — which speaks\n // by definition and must not have to change that preference to do it.\n if ((!autoSpeakEnabled && !sessionSpeaking) || !visible || !isSupported) return;\n\n // Deliberately a store subscription keyed on the processing TRANSITION\n // rather than an effect over the message list: it fires only on the\n // in-flight → complete edge of the active conversation, so mounting the\n // panel, loading history or switching chats can never start talking.\n return useAssistantStore.subscribe((next, previous) => {\n const conversationId = next.activeConversationId;\n if (!conversationId || conversationId !== previous.activeConversationId) return;\n\n const current = next.processingByConversationId[conversationId];\n const before = previous.processingByConversationId[conversationId];\n if (current?.status !== 'complete' || !isTurnInFlight(before?.status)) return;\n\n const messageId = current.messageId ?? before?.messageId ?? null;\n if (!messageId) return;\n\n const message = next.conversations\n .find((conversation) => conversation.id === conversationId)\n ?.messages.find((candidate) => candidate.id === messageId);\n if (!message || message.role !== 'assistant') return;\n\n // ★ Speak a turn only if it belongs to the surface currently doing the\n // speaking. This subscription IS the live session's audio path —\n // `useVoiceSession` never calls `speak` itself, it flips `sessionSpeaking`\n // and lets this fire — and it had no channel check, so a TYPED reply\n // completing mid-session was read aloud as the answer to a spoken\n // question. Reachable with no typing at all: a host page queues work\n // through `pendingPrompt`, which is store-driven and fires past the voice\n // overlay.\n //\n // The mirror case matters too: after End, a reply still in flight must not\n // be spoken by ordinary auto-read — the user closed the conversation.\n if (isVoiceTurn(message) !== sessionSpeaking) return;\n\n // Same split the transcript uses: speak the prose, not the tool log.\n const { text } = parseToolActivity(message.content);\n if (!text.trim()) return;\n\n speakRef.current(messageId, text, (message.metadata as { lang?: string } | undefined)?.lang);\n });\n }, [autoSpeakEnabled, sessionSpeaking, isSupported, visible]);\n\n // The candidates for the language the user SPEAKS — the picker is a setting,\n // so it must not follow whatever language the last reply happened to be in.\n const voiceChoices = useMemo(() => voicesForLocale(voices, spokenLanguage.tag), [voices, spokenLanguage]);\n const activeVoice = useMemo(\n () => selectVoiceForLocale(voices, spokenLanguage.tag, preferredVoices[spokenLocale]),\n [voices, spokenLanguage, preferredVoices, spokenLocale]\n );\n\n const value = useMemo<AssistantSpeechContextValue>(\n () => ({\n isSupported,\n availability,\n // ONLY `no-voices` — a device with no voices at all can never speak\n // anything. `missing-voice` means the APP language has none, which says\n // nothing about the language a given reply came back in; that case is\n // resolved per message by `blockedFor`.\n isBlocked: availability === 'no-voices',\n // Both blocked states are the user's device, not our bug — so the copy\n // names the language and says where to fix it. \"Nothing happened\" was\n // the old behaviour and it read as a broken feature.\n disabledReason:\n availability === 'no-voices'\n ? tr(\n 'healthybowl.assistant.speech.noVoicesOnDevice',\n 'This device has no speech voices installed. Add one in your device speech or accessibility settings.'\n )\n : null,\n blockedFor,\n voiceChoices,\n spokenChunks: spokenProgress ? { chunks: spokenProgress.chunks, index: spokenProgress.index } : null,\n activeVoiceName: activeVoice?.name ?? null,\n preferredVoiceName: preferredVoices[spokenLocale] ?? null,\n setVoice: (voiceName: string | null) => setPreferredVoice(spokenLocale, voiceName),\n speakingMessageId: playback.status === 'speaking' ? playback.messageId : null,\n isSpeaking: (messageId: string) => isSpeakingMessage(playback, messageId),\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n setSessionSpeaking,\n previewVoice,\n }),\n [\n isSupported,\n availability,\n blockedFor,\n voiceChoices,\n activeVoice,\n preferredVoices,\n setPreferredVoice,\n spokenLocale,\n playback,\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n previewVoice,\n tr,\n ]\n );\n\n return <AssistantSpeechContext.Provider value={value}>{children}</AssistantSpeechContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsDA,IAAM,KAAiC;CACrC,WAAW;CACX,OAAO;CACP,MAAM;CACN,YAAY;CACZ,WAAW;CACX,SAAS;CACT,UAAU;CACV,YAAY;AACd,GA6HM,IAAyB,EAA2C;CArBxE,aAAa;CACb,cAAc;CACd,WAAW;CACX,gBAAgB;CAChB,kBAAkB;CAClB,cAAc,CAAC;CACf,cAAc;CACd,iBAAiB;CACjB,oBAAoB;CACpB,gBAAgB,CAAC;CACjB,mBAAmB;CACnB,kBAAkB;CAClB,cAAc,CAAC;CACf,YAAY,CAAC;CACb,kBAAkB;CAClB,oBAAoB,CAAC;CACrB,iBAAiB;CACjB,0BAA0B,CAAC;CAC3B,oBAAoB,CAAC;AAGmD,CAAY;AAEtF,SAAgB,IAAkD;CAChE,OAAO,EAAW,CAAsB;AAC1C;AAcA,IAAa,KAAsC,EAAE,aAAU,aAAU,IAAM,YAAS,EAAgB,QAAQ;CAC9G,IAAM,IAAK,EAAM,GACX,EAAE,cAAW,GAAQ,GACrB,CAAC,GAAU,KAAY,GAAW,IAAuB,EAAa,GACtE,CAAC,GAA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,MAAM,GAAiB;GAG9C,IAAM,EAAE,YAAS,GAAkB,EAAQ,OAAO;GAC7C,EAAK,KAAK,KAEf,GAAS,QAAQ,GAAW,GAAO,EAAQ,UAA4C,IAAI;EAC7F,CAAC;CACH,GAAG;EAAC;EAAkB;EAAiB;EAAa;CAAO,CAAC;CAI5D,IAAM,KAAe,QAAc,GAAgB,GAAQ,EAAe,GAAG,GAAG,CAAC,GAAQ,CAAc,CAAC,GAClG,KAAc,QACZ,EAAqB,GAAQ,EAAe,KAAK,EAAgB,EAAa,GACpF;EAAC;EAAQ;EAAgB;EAAiB;CAAY,CACxD,GAEM,KAAQ,SACL;EACL;EACA;EAKA,WAAW,MAAiB;EAI5B,gBACE,MAAiB,cACb,EACE,iDACA,sGACF,IACA;EACN;EACA;EACA,cAAc,IAAiB;GAAE,QAAQ,EAAe;GAAQ,OAAO,EAAe;EAAM,IAAI;EAChG,iBAAiB,IAAa,QAAQ;EACtC,oBAAoB,EAAgB,MAAiB;EACrD,WAAW,MAA6B,EAAkB,GAAc,CAAS;EACjF,mBAAmB,EAAS,WAAW,aAAa,EAAS,YAAY;EACzE,aAAa,MAAsB,EAAkB,GAAU,CAAS;EACxE;EACA;EACA;EACA;EACA;EACA;EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,OAAO,mBAAC,EAAuB,UAAxB;EAAwC;EAAQ;CAA0C,CAAA;AACnG"}
|
|
1
|
+
{"version":3,"file":"AssistantSpeechProvider.js","names":[],"sources":["../../../src/components/assistant/AssistantSpeechProvider.tsx"],"sourcesContent":["/**\n * Speech-output context for the assistant panel (BOFF-6290).\n *\n * The assistant could already hear (`useVoiceInput`); this is the other half —\n * it can now answer out loud. That matters for a farming product where the user\n * is outdoors with dirty hands, a phone in a pocket and sun on the screen, and\n * it is a plain accessibility win everywhere else.\n *\n * Everything stateful about playback lives here, once, so that:\n *\n * - **playback is never orphaned.** A voice that keeps talking after the UI is\n * gone is a bug, so speech is cancelled when the panel hides, when the\n * conversation changes, on unmount, and on `pagehide` (Chrome keeps speaking\n * across a navigation otherwise);\n * - **only one message speaks at a time.** Starting a new playback cancels the\n * previous one — enforced by the engine and by the request-id guard in\n * `speechPlaybackReducer`;\n * - **nothing ever autoplays.** Playback starts from a button press. The\n * persisted auto-speak preference defaults OFF and is opt-in from the header.\n *\n * Components consume this through `useAssistantSpeech()`, which falls back to an\n * inert value when there is no provider (Storybook, a header rendered on its\n * own) rather than throwing.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type FC,\n type ReactNode,\n} from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { voicePreviewText } from '@/utils/voicePreview';\nimport { getSpeechEngine } from '../../services/speech';\nimport type { SpeechEngine, SpeechVoiceLike } from '../../services/speech';\nimport { chunkForSpeech, toSpeakableText, type SpeakableLabels } from '../../utils/speakableText';\nimport { speechLabelsFor } from '../../config/speechLabels';\n\n/**\n * The speakable transformation with nothing of ours added — used ONLY to decide\n * the reply's language.\n *\n * Detection needs the prose that will be spoken: code blocks and URLs stripped\n * (they are never read aloud, and their Latin identifiers would outvote short\n * non-Latin prose), but no substitute wording introduced either (that would let\n * our own app-locale words vote instead).\n */\nconst SILENT_LABELS: SpeakableLabels = {\n codeBlock: '',\n image: '',\n link: '',\n largeTable: '',\n truncated: '',\n emailAt: 'at',\n emailDot: 'dot',\n nestedItem: '',\n};\nimport {\n VOICE_LIST_TIMEOUT_MS,\n languageDisplayName,\n selectVoiceForLocale,\n voicesForLocale,\n speechGate,\n speechLangForLocale,\n voiceAvailability,\n type VoiceAvailability,\n} from '../../utils/speechVoices';\nimport { resolveSpeechLocale } from '../../utils/replyLanguage';\nimport { DEFAULT_SPEECH_RATE, findAssistantLanguage } from '../../config/assistantLanguages';\nimport { resolveLanguagePair } from '../../config/assistantLanguagePair';\nimport { IDLE_PLAYBACK, isSpeakingMessage, speechPlaybackReducer } from '../../utils/speechPlayback';\nimport { isVoiceTurn } from '../../utils/voiceTurnVisibility';\nimport { isTurnInFlight } from '../../utils/assistantTurnState';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport interface AssistantSpeechContextValue {\n /** False when the platform has no speech output — hide the control entirely. */\n isSupported: boolean;\n availability: VoiceAvailability;\n /**\n * True when nothing can be spoken in the app language, so every control that\n * starts playback — the per-message button AND the header toggle — must be\n * inert. `pending` is not blocked: see `speechGate`.\n */\n isBlocked: boolean;\n /** Explains a disabled control (no installed voice for the app language). */\n disabledReason: string | null;\n /**\n * Why THIS message cannot be spoken, when the app language is fine but the\n * reply is not in it — a Tamil answer in an English UI on a device with no\n * Tamil voice. `isBlocked` cannot see that: it is computed before any reply\n * exists. Without this the control looks enabled and silently refuses, which\n * is the dead-button bug all over again (BOFF-7106).\n */\n blockedFor: (messageId: string) => string | null;\n /**\n * Every installed voice that can read the language the user speaks, best\n * first. Empty when there is no choice to offer — the picker hides itself\n * rather than showing a one-item dropdown.\n */\n voiceChoices: readonly SpeechVoiceLike[];\n /** The voice that will actually be used, resolved from the pick + ranking. */\n /**\n * The reply as it is being SPOKEN: every chunk, plus the one sounding now.\n *\n * `null` when nothing is playing. `index: -1` means chunked but not yet\n * audible. Consumers reveal `chunks[0..index]` — anything beyond that is the\n * caption running ahead of the voice.\n */\n spokenChunks: { chunks: string[]; index: number } | null;\n activeVoiceName: string | null;\n /**\n * The RAW stored pick: `null` means \"use the ranked default\".\n *\n * The picker must be driven by this rather than by `activeVoiceName`, or the\n * two states collapse — with nothing stored, the ranked winner is already the\n * shown option, so choosing it fires no change event and the pick can never\n * be made. The user's voice would then silently move the next time the device\n * installs a higher-ranked one. Same trap as the language selector.\n */\n preferredVoiceName: string | null;\n /** `null` restores the ranked default for the current language. */\n setVoice: (voiceName: string | null) => void;\n /** The message currently being spoken, if any. */\n speakingMessageId: string | null;\n isSpeaking: (messageId: string) => boolean;\n /**\n * Speak this message, or stop if it is already the one speaking.\n *\n * `turnLocale` is the language the reply was GENERATED under, from the\n * message's own metadata. It matters because script detection cannot separate\n * Latin-script languages, so without it an old French reply would be read\n * with whatever voice the CURRENT preference selects.\n */\n toggle: (messageId: string, markdown: string, turnLocale?: string) => void;\n stop: () => void;\n autoSpeakEnabled: boolean;\n setAutoSpeak: (enabled: boolean) => void;\n /**\n * Speak replies for the duration of a live voice session, WITHOUT touching the\n * user's saved preference.\n *\n * ★ Live Voice used to force `autoSpeakEnabled` true and restore it on exit.\n * That field is PERSISTED (assistantStore partialize), and the restore only\n * ran on a clean `end()` — so a reload, a closed tab or a backgrounded webview\n * during a session left auto-speak switched ON for the user permanently, in\n * normal typed chat, with the toggle showing a state they never chose. The\n * default was never wrong; the session was overwriting it.\n *\n * Session-scoped React state instead: it cannot outlive the page, so there is\n * nothing to restore and nothing to leak.\n */\n sessionSpeaking: boolean;\n setSessionSpeaking: (enabled: boolean) => void;\n /** Play a short sample in a named voice. No model call, no message, no tokens. */\n previewVoice: (voiceName: string) => void;\n}\n\nconst INERT_SPEECH: AssistantSpeechContextValue = {\n isSupported: false,\n availability: 'unsupported',\n isBlocked: true,\n disabledReason: null,\n blockedFor: () => null,\n voiceChoices: [],\n spokenChunks: null,\n activeVoiceName: null,\n preferredVoiceName: null,\n setVoice: () => {},\n speakingMessageId: null,\n isSpeaking: () => false,\n toggle: () => {},\n stop: () => {},\n autoSpeakEnabled: false,\n setAutoSpeak: () => {},\n sessionSpeaking: false,\n setSessionSpeaking: () => {},\n previewVoice: () => {},\n};\n\nconst AssistantSpeechContext = createContext<AssistantSpeechContextValue>(INERT_SPEECH);\n\nexport function useAssistantSpeech(): AssistantSpeechContextValue {\n return useContext(AssistantSpeechContext);\n}\n\ninterface Props {\n children: ReactNode;\n /** Panel visibility. Hiding the panel stops the voice. */\n visible?: boolean;\n /**\n * Injectable for tests and local experiments. The default routes between the\n * device engine and the hosted one; with hosted TTS unconfigured it IS the\n * device engine, unchanged.\n */\n engine?: SpeechEngine;\n}\n\nexport const AssistantSpeechProvider: FC<Props> = ({ children, visible = true, engine = getSpeechEngine() }) => {\n const tr = useTr();\n const { locale } = useI18n();\n const [playback, dispatch] = useReducer(speechPlaybackReducer, IDLE_PLAYBACK);\n const [voices, setVoices] = useState<SpeechVoiceLike[]>(() => engine.listVoices());\n /**\n * True once we have waited out the voice list and it was still empty.\n *\n * Turns an indefinite `pending` into a terminal `no-voices`, which is what\n * lets the control be disabled with a reason instead of silently doing\n * nothing on every press.\n */\n const [voiceProbeSettled, setVoiceProbeSettled] = useState(false);\n /**\n * Every message we have refused, and why — keyed by id (see `blockedFor`).\n *\n * A single record could only describe one refusal: refusing a second reply\n * silently re-enabled the first, whose voice was still just as missing, so\n * pressing the buttons walked the disabled state around the transcript.\n */\n const [unspeakable, setUnspeakable] = useState<ReadonlyMap<string, string>>(() => new Map());\n const requestRef = useRef(0);\n\n /**\n * Which chunk of the current reply is sounding right now.\n *\n * ★ `index: -1` means \"chunked, nothing playing yet\" — distinct from no\n * progress at all, so the caption can stay empty until audio genuinely starts\n * instead of flashing the first sentence while the engine is still fetching.\n */\n const [spokenProgress, setSpokenProgress] = useState<{\n requestId: number;\n chunks: string[];\n index: number;\n } | null>(null);\n /** Cancels a playback that is waiting for the engine's voice list, if any. */\n const pendingRef = useRef<(() => void) | null>(null);\n const speakWithRef = useRef<\n (messageId: string, text: string, voices: readonly SpeechVoiceLike[], speechLocale: string) => void\n >(() => {});\n\n const cancelPending = useCallback(() => {\n pendingRef.current?.();\n pendingRef.current = null;\n }, []);\n\n const autoSpeakEnabled = useAssistantStore((state) => state.autoSpeakEnabled);\n const setAutoSpeak = useAssistantStore((state) => state.setAutoSpeak);\n // Not in the store on purpose — see `sessionSpeaking` on the context type.\n const [sessionSpeaking, setSessionSpeaking] = useState(false);\n const activeConversationId = useAssistantStore((state) => state.activeConversationId);\n\n const isSupported = useMemo(() => engine.isSupported(), [engine]);\n\n // getVoices() is empty on the first call in Chrome and only fills in when\n // 'voiceschanged' fires; Safari populates it synchronously and may never fire\n // the event. Read eagerly AND subscribe, so both engines end up correct.\n useEffect(() => {\n if (!isSupported) return;\n const sync = () => {\n setVoices(engine.listVoices());\n // Every recorded refusal was \"no voice for this language\". A new voice\n // list may well have supplied one — most likely because the user just\n // followed our instructions and installed it. Keeping the refusals would\n // leave those buttons disabled with no way back except a reload.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n sync();\n return engine.subscribeVoices(sync);\n }, [engine, isSupported]);\n\n // The language being SPOKEN ALOUD — which is the language of the reply, not\n // of the input and not of the interface. The two were one field until the\n // reply language was split out (BOFF-7108).\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const replyLanguage = useAssistantStore((state) => state.replyLanguage);\n const preferredVoices = useAssistantStore((state) => state.preferredVoices);\n const setPreferredVoice = useAssistantStore((state) => state.setPreferredVoice);\n const spokenLanguage = useMemo(\n // ★ The REPLY language, not the input. This is the language of the text\n // being spoken, so wiring it to the input would give a Tamil voice reading\n // an English answer the moment the two are set differently — the single\n // worst outcome available here, and the reason they were split at all.\n () => resolveLanguagePair(assistantLanguage, replyLanguage, locale).reply,\n [assistantLanguage, replyLanguage, locale]\n );\n const spokenLocale = spokenLanguage.code;\n\n /**\n * BCP-47 tag to ask the engine for, given a resolved language CODE.\n *\n * Resolved through the catalogue for ANY known code, not merely the currently\n * selected one — a historical Bengali reply must still get `bn-IN` after the\n * user switches to Tamil, or with both `bn-IN` and `bn-BD` installed the\n * engine's own order decides, and picks the wrong country.\n *\n * Falls back to the generic table for codes the catalogue does not carry.\n */\n const tagFor = useCallback((code: string) => findAssistantLanguage(code)?.tag ?? speechLangForLocale(code), []);\n\n /** Speaking rate for a resolved language code — see `AssistantLanguage.rate`. */\n const rateFor = useCallback((code: string) => findAssistantLanguage(code)?.rate ?? DEFAULT_SPEECH_RATE, []);\n\n const availability = useMemo(\n () => voiceAvailability(isSupported, voices, spokenLanguage.tag, voiceProbeSettled),\n [isSupported, voices, spokenLanguage, voiceProbeSettled]\n );\n\n // Spoken placeholders follow the app locale like the rest of the copy; the\n // transformation itself stays a pure function by taking them as arguments.\n const labels = useMemo<SpeakableLabels>(\n () => ({\n codeBlock: tr('healthybowl.assistant.speech.codeBlock', 'Code block'),\n image: tr('healthybowl.assistant.speech.image', 'image'),\n link: tr('healthybowl.assistant.speech.link', 'link'),\n largeTable: tr('healthybowl.assistant.speech.largeTable', 'Table with {{rows}} rows and {{columns}} columns'),\n truncated: tr('healthybowl.assistant.speech.truncated', 'The rest of this message is not read aloud'),\n nestedItem: tr('healthybowl.assistant.speech.nestedItem', 'Sub-item {{ordinal}}'),\n emailAt: tr('healthybowl.assistant.speech.emailAt', 'at'),\n emailDot: tr('healthybowl.assistant.speech.emailDot', 'dot'),\n }),\n [tr]\n );\n\n const stop = useCallback(() => {\n cancelPending();\n engine.cancel();\n dispatch({ type: 'stop' });\n }, [cancelPending, engine]);\n\n /**\n * Audition a voice — no model call, no message, no tokens.\n *\n * ★ Speaks through the engine DIRECTLY rather than through `speakWith`. That\n * path is built around a message: it resolves the reply's language, records\n * per-message \"cannot speak this\" state, and drives `speakingMessageId` so a\n * Listen button can light up. A preview has no message, so borrowing it would\n * mean inventing a fake id and then teaching every consumer to ignore it.\n *\n * Consequently it deliberately does NOT touch playback state: auditioning a\n * voice must not make a Listen button in the thread appear to be playing.\n *\n * Speaks the sample in the language being spoken, not the interface language —\n * the listener is judging how this voice reads THAT language.\n */\n const previewVoice = useCallback(\n (voiceName: string) => {\n const voice = engine.listVoices().find((candidate) => candidate.name === voiceName) ?? null;\n // An unknown name means the list changed under us (a download finished, a\n // profile switched). Silence is the right answer — better than falling\n // back to some other voice and auditioning the wrong one.\n if (!voice) return;\n // Whatever is speaking now is not what the user asked to hear.\n stop();\n engine.speak([voicePreviewText(spokenLocale)], { voice, lang: tagFor(spokenLocale) });\n },\n [engine, spokenLocale, stop, tagFor]\n );\n\n const blockedFor = useCallback((messageId: string) => unspeakable.get(messageId) ?? null, [unspeakable]);\n\n /**\n * Hold one playback until the engine publishes its voice list.\n *\n * Bounded: on timeout we take one last look and decide with whatever is\n * there, so an engine that never fires `voiceschanged` costs a two-second\n * wait rather than a control that is disabled forever. Nothing is spoken from\n * here unless a list actually arrives — an empty list means the engine would\n * pick its own default voice, which is the cross-language read this feature\n * promises never to do.\n */\n const waitForVoices = useCallback(\n (messageId: string, text: string, speechLocale: string) => {\n cancelPending();\n\n let settled = false;\n let unsubscribe = () => {};\n const finish = (available: SpeechVoiceLike[]) => {\n if (settled) return;\n settled = true;\n pendingRef.current = null;\n clearTimeout(timer);\n unsubscribe();\n if (available.length === 0) {\n // We waited and looked again: this device has no voices at all.\n // Record it so `availability` becomes `no-voices` and the control\n // explains itself, instead of returning silently every press.\n setVoiceProbeSettled(true);\n return;\n }\n setVoices(available);\n speakWithRef.current(messageId, text, available, speechLocale);\n };\n\n const timer = setTimeout(() => finish(engine.listVoices()), VOICE_LIST_TIMEOUT_MS);\n unsubscribe = engine.subscribeVoices(() => finish(engine.listVoices()));\n\n pendingRef.current = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n unsubscribe();\n pendingRef.current = null;\n };\n },\n [cancelPending, engine]\n );\n\n /**\n * Speak text against a KNOWN voice list.\n *\n * Every playback path funnels through here — the per-message button, the\n * header toggle's auto-speak, the store subscription — so the language gate\n * cannot be bypassed by any of them. Reading a Tamil reply with an English\n * voice is confident nonsense; it has to be impossible, not merely unlikely.\n */\n const speakWith = useCallback(\n (messageId: string, text: string, available: readonly SpeechVoiceLike[], speechLocale: string) => {\n let known = available;\n\n // Chrome answers the FIRST getVoices() with [] and fills the list in\n // asynchronously. One more synchronous read usually settles it.\n if (known.length === 0) {\n const refreshed = engine.listVoices();\n if (refreshed.length > 0) {\n known = refreshed;\n setVoices(refreshed);\n }\n }\n\n const speechLang = tagFor(speechLocale);\n\n const gate = speechGate(voiceAvailability(true, known, speechLocale, voiceProbeSettled));\n if (gate === 'block') {\n // Recorded for THIS message, always. Availability is resolved per reply\n // now, so a global \"your language has no voice\" cannot stand in for it:\n // the language the user chose to converse in says nothing about the one\n // this particular reply came back in.\n const reason = tr(\n 'healthybowl.assistant.speech.noVoiceForReply',\n 'This reply is in {{language}}, and no {{language}} voice is installed on this device.',\n { language: languageDisplayName(speechLang, locale) }\n );\n setUnspeakable((current) => new Map(current).set(messageId, reason));\n return;\n }\n if (gate === 'wait-for-voices') {\n waitForVoices(messageId, text, speechLocale);\n return;\n }\n\n setUnspeakable((current) => {\n if (!current.has(messageId)) return current;\n const next = new Map(current);\n next.delete(messageId);\n return next;\n });\n\n const requestId = requestRef.current + 1;\n requestRef.current = requestId;\n dispatch({ type: 'start', messageId, requestId });\n\n // ★ Chunked ONCE and kept, so the caption can show exactly what is being\n // spoken rather than a parallel rendering of the same markdown. A live\n // caption whose words differ from the audio is not a caption.\n const chunks = chunkForSpeech(text);\n setSpokenProgress({ requestId, chunks, index: -1 });\n\n engine.speak(\n chunks,\n // The TAG, not the code — so exact regional matching gets its chance\n // before the same-language fallback. `rate` had never been passed at\n // all, so every reply was read at the engine default.\n {\n voice: selectVoiceForLocale(known, speechLang, preferredVoices[speechLocale]),\n lang: speechLang,\n rate: rateFor(speechLocale),\n },\n {\n // Guarded on the request id like every other handler here: a stale\n // batch that has not noticed its cancellation must not drive the\n // caption of the reply that replaced it.\n onChunkStart: (index) =>\n setSpokenProgress((current) => (current?.requestId === requestId ? { ...current, index } : current)),\n onEnd: () => dispatch({ type: 'finished', requestId }),\n // Includes the 'cancelled' every queued utterance reports when we\n // pre-empt a batch; the request-id guard drops those as stale.\n onError: () => dispatch({ type: 'failed', requestId }),\n }\n );\n },\n [engine, locale, preferredVoices, rateFor, tagFor, tr, voiceProbeSettled, waitForVoices]\n );\n\n // `waitForVoices` resumes through this ref, so the two do not become a\n // circular hook dependency.\n useEffect(() => {\n speakWithRef.current = speakWith;\n }, [speakWith]);\n\n const speak = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (!isSupported) return;\n\n // Resolve the reply's language BEFORE building the spoken text, because\n // the stand-in words must be in that language. Detection deliberately runs\n // on a SILENT_LABELS pass — our own words must not vote on which language\n // the reply is in — so it does not depend on the labels chosen here.\n const replyLocale = resolveSpeechLocale(\n toSpeakableText(markdown, { labels: SILENT_LABELS }),\n turnLocale ?? spokenLocale\n );\n\n // ★ Labels in the REPLY's language, not the interface's. An English\n // interface reading a Tamil answer used to say \"Code block\" and \"image\" in\n // English, mid-Tamil-sentence — the same defect the email `at`/`dot` fix\n // addressed and did not generalise.\n const text = toSpeakableText(markdown, { labels: speechLabelsFor(replyLocale, labels) });\n if (!text) return;\n\n // Detect on the text that will actually be SPOKEN, with our own words\n // removed — neither the raw markdown nor the finished transformation.\n //\n // The transformation injects app-locale placeholders (\"Code block\"), which\n // let English chrome outvote short non-Latin prose. The raw markdown keeps\n // fenced code, whose Latin identifiers do the same thing — and that code is\n // never spoken at all. Running the same transformation with EMPTY labels\n // strips the unspoken constructs while contributing no words of its own,\n // which is exactly the denominator the decision needs.\n // The turn's OWN language first — the preference is only a stand-in for\n // replies that predate it. Resolved above, and reused rather than\n // recomputed.\n speakWith(messageId, text, voices, replyLocale);\n },\n [isSupported, labels, spokenLocale, speakWith, voices]\n );\n\n const toggle = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (isSpeakingMessage(playback, messageId)) {\n stop();\n return;\n }\n speak(messageId, markdown, turnLocale);\n },\n [playback, speak, stop]\n );\n\n // ── Never leave a voice talking to an empty room ─────────────────────────\n useEffect(() => {\n if (!visible) stop();\n }, [visible, stop]);\n\n useEffect(() => {\n // Switching (or creating) a conversation abandons the reply being read —\n // and the refusal explained a message that is no longer on screen.\n stop();\n setUnspeakable(new Map());\n }, [activeConversationId, stop]);\n\n useEffect(() => {\n // Every refusal was decided against the locale in force at the time, which\n // is what a Latin-script reply falls back to. Change the locale and those\n // verdicts may simply be wrong — an English reply refused on a\n // Spanish-only device would stay disabled forever after switching the UI to\n // Spanish, with the voice that could read it already installed.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n // And stop anything mid-sentence. The new language can make this message\n // unspeakable, which disables its button — leaving it reading \"Stop\" with no\n // way to actually stop, short of closing the panel.\n stop();\n }, [spokenLocale, stop]);\n\n useEffect(() => {\n return () => {\n pendingRef.current?.();\n pendingRef.current = null;\n engine.cancel();\n };\n }, [engine]);\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n // Chrome carries speech across a same-tab navigation and a bfcache restore\n // would otherwise come back mid-sentence.\n const handlePageHide = () => engine.cancel();\n window.addEventListener('pagehide', handlePageHide);\n return () => window.removeEventListener('pagehide', handlePageHide);\n }, [engine]);\n\n // ── One timeout is not a life sentence ───────────────────────────────────\n //\n // `no-voices` disables the control, and a disabled control can never reach\n // `speakWith` — the only path that re-reads `engine.listVoices()`. So without\n // this, a user who follows our own advice, leaves to install a voice and comes\n // back stays blocked until a reload: we would be telling them how to fix it\n // and then refusing to notice that they had.\n //\n // Returning to the tab is exactly when that happens, and it costs one\n // synchronous read of an already-populated list.\n useEffect(() => {\n if (typeof document === 'undefined' || !isSupported) return;\n const reprobe = () => {\n if (document.visibilityState !== 'visible') return;\n // Adopt the list UNCONDITIONALLY, including an empty one. Keeping the old\n // cache on an empty read means a user who uninstalled their last voice\n // stays `ready`, and playback then hands the engine a voice object that no\n // longer exists instead of explaining the problem.\n //\n // Safe to accept an empty read here precisely because the probe verdict is\n // cleared on the next line: empty + unsettled is `pending`, which leaves\n // the control ENABLED and defers the real decision to the next press.\n const available = engine.listVoices();\n // A Listen press may still be inside its two-second wait. Adopting voices\n // here flips the control to `ready`, so the user can press again and start\n // playback — and then the original timer fires, calls back into\n // `speakWith` for the same message, and the engine cancels and restarts it\n // mid-sentence. Retire the waiter as part of adopting the list.\n if (available.length > 0) cancelPending();\n setVoices(available);\n setVoiceProbeSettled(false);\n // Same reason the `voiceschanged` path clears them: every refusal meant\n // \"no voice for this language\", and this is the moment a user who went\n // away to install one comes back. `subscribeVoices` does not fire on an\n // eventless engine, which is precisely why this re-probe exists — so it\n // has to expire the refusals too.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n document.addEventListener('visibilitychange', reprobe);\n window.addEventListener('focus', reprobe);\n return () => {\n document.removeEventListener('visibilitychange', reprobe);\n window.removeEventListener('focus', reprobe);\n };\n }, [cancelPending, engine, isSupported]);\n\n // ── Opt-in auto-speak ────────────────────────────────────────────────────\n const speakRef = useRef(speak);\n useEffect(() => {\n speakRef.current = speak;\n }, [speak]);\n\n useEffect(() => {\n // `isBlocked` is the same gate the per-message button uses. Without it the\n // subscription fires on a device with no voice for the app language and the\n // engine reads a Tamil reply in English — the one thing this feature says\n // it will never do. `pending` is allowed through because `speakWith` waits\n // for the list before deciding.\n // NOT gated on `isSpeechBlocked(availability)` any more: that is the APP\n // language's availability, and it would suppress auto-speak for a reply in\n // a language this device CAN speak. `speakWith` resolves the reply's own\n // language and refuses safely there, which is the only place that can know.\n // Either the user's own preference, or a live voice session — which speaks\n // by definition and must not have to change that preference to do it.\n if ((!autoSpeakEnabled && !sessionSpeaking) || !visible || !isSupported) return;\n\n // Deliberately a store subscription keyed on the processing TRANSITION\n // rather than an effect over the message list: it fires only on the\n // in-flight → complete edge of the active conversation, so mounting the\n // panel, loading history or switching chats can never start talking.\n return useAssistantStore.subscribe((next, previous) => {\n const conversationId = next.activeConversationId;\n if (!conversationId || conversationId !== previous.activeConversationId) return;\n\n const current = next.processingByConversationId[conversationId];\n const before = previous.processingByConversationId[conversationId];\n if (current?.status !== 'complete' || !isTurnInFlight(before?.status)) return;\n\n const messageId = current.messageId ?? before?.messageId ?? null;\n if (!messageId) return;\n\n const message = next.conversations\n .find((conversation) => conversation.id === conversationId)\n ?.messages.find((candidate) => candidate.id === messageId);\n if (!message || message.role !== 'assistant') return;\n\n // ★ Speak a turn only if it belongs to the surface currently doing the\n // speaking. This subscription IS the live session's audio path —\n // `useVoiceSession` never calls `speak` itself, it flips `sessionSpeaking`\n // and lets this fire — and it had no channel check, so a TYPED reply\n // completing mid-session was read aloud as the answer to a spoken\n // question. Reachable with no typing at all: a host page queues work\n // through `pendingPrompt`, which is store-driven and fires past the voice\n // overlay.\n //\n // The mirror case matters too: after End, a reply still in flight must not\n // be spoken by ordinary auto-read — the user closed the conversation.\n if (isVoiceTurn(message) !== sessionSpeaking) return;\n\n // Same split the transcript uses: speak the prose, not the tool log.\n const { text } = parseToolActivity(message.content);\n if (!text.trim()) return;\n\n speakRef.current(messageId, text, (message.metadata as { lang?: string } | undefined)?.lang);\n });\n }, [autoSpeakEnabled, sessionSpeaking, isSupported, visible]);\n\n // The candidates for the language the user SPEAKS — the picker is a setting,\n // so it must not follow whatever language the last reply happened to be in.\n const voiceChoices = useMemo(() => voicesForLocale(voices, spokenLanguage.tag), [voices, spokenLanguage]);\n const activeVoice = useMemo(\n () => selectVoiceForLocale(voices, spokenLanguage.tag, preferredVoices[spokenLocale]),\n [voices, spokenLanguage, preferredVoices, spokenLocale]\n );\n\n const value = useMemo<AssistantSpeechContextValue>(\n () => ({\n isSupported,\n availability,\n // ONLY `no-voices` — a device with no voices at all can never speak\n // anything. `missing-voice` means the APP language has none, which says\n // nothing about the language a given reply came back in; that case is\n // resolved per message by `blockedFor`.\n isBlocked: availability === 'no-voices',\n // Both blocked states are the user's device, not our bug — so the copy\n // names the language and says where to fix it. \"Nothing happened\" was\n // the old behaviour and it read as a broken feature.\n disabledReason:\n availability === 'no-voices'\n ? tr(\n 'healthybowl.assistant.speech.noVoicesOnDevice',\n 'This device has no speech voices installed. Add one in your device speech or accessibility settings.'\n )\n : null,\n blockedFor,\n voiceChoices,\n spokenChunks: spokenProgress ? { chunks: spokenProgress.chunks, index: spokenProgress.index } : null,\n activeVoiceName: activeVoice?.name ?? null,\n preferredVoiceName: preferredVoices[spokenLocale] ?? null,\n setVoice: (voiceName: string | null) => setPreferredVoice(spokenLocale, voiceName),\n speakingMessageId: playback.status === 'speaking' ? playback.messageId : null,\n isSpeaking: (messageId: string) => isSpeakingMessage(playback, messageId),\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n setSessionSpeaking,\n previewVoice,\n }),\n [\n isSupported,\n availability,\n blockedFor,\n voiceChoices,\n activeVoice,\n preferredVoices,\n setPreferredVoice,\n spokenLocale,\n playback,\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n previewVoice,\n tr,\n ]\n );\n\n return <AssistantSpeechContext.Provider value={value}>{children}</AssistantSpeechContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsDA,IAAM,KAAiC;CACrC,WAAW;CACX,OAAO;CACP,MAAM;CACN,YAAY;CACZ,WAAW;CACX,SAAS;CACT,UAAU;CACV,YAAY;AACd,GA6HM,IAAyB,EAA2C;CArBxE,aAAa;CACb,cAAc;CACd,WAAW;CACX,gBAAgB;CAChB,kBAAkB;CAClB,cAAc,CAAC;CACf,cAAc;CACd,iBAAiB;CACjB,oBAAoB;CACpB,gBAAgB,CAAC;CACjB,mBAAmB;CACnB,kBAAkB;CAClB,cAAc,CAAC;CACf,YAAY,CAAC;CACb,kBAAkB;CAClB,oBAAoB,CAAC;CACrB,iBAAiB;CACjB,0BAA0B,CAAC;CAC3B,oBAAoB,CAAC;AAGmD,CAAY;AAEtF,SAAgB,IAAkD;CAChE,OAAO,EAAW,CAAsB;AAC1C;AAcA,IAAa,KAAsC,EAAE,aAAU,aAAU,IAAM,YAAS,EAAgB,QAAQ;CAC9G,IAAM,IAAK,EAAM,GACX,EAAE,cAAW,GAAQ,GACrB,CAAC,GAAU,KAAY,GAAW,IAAuB,EAAa,GACtE,CAAC,GAAQ,KAAa,QAAkC,EAAO,WAAW,CAAC,GAQ3E,CAAC,GAAmB,KAAwB,EAAS,EAAK,GAQ1D,CAAC,GAAa,KAAkB,wBAA4C,IAAI,IAAI,CAAC,GACrF,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F,CAAC;CACH,GAAG;EAAC;EAAkB;EAAiB;EAAa;CAAO,CAAC;CAI5D,IAAM,KAAe,QAAc,GAAgB,GAAQ,EAAe,GAAG,GAAG,CAAC,GAAQ,CAAc,CAAC,GAClG,KAAc,QACZ,EAAqB,GAAQ,EAAe,KAAK,EAAgB,EAAa,GACpF;EAAC;EAAQ;EAAgB;EAAiB;CAAY,CACxD,GAEM,KAAQ,SACL;EACL;EACA;EAKA,WAAW,MAAiB;EAI5B,gBACE,MAAiB,cACb,EACE,iDACA,sGACF,IACA;EACN;EACA;EACA,cAAc,IAAiB;GAAE,QAAQ,EAAe;GAAQ,OAAO,EAAe;EAAM,IAAI;EAChG,iBAAiB,IAAa,QAAQ;EACtC,oBAAoB,EAAgB,MAAiB;EACrD,WAAW,MAA6B,EAAkB,GAAc,CAAS;EACjF,mBAAmB,EAAS,WAAW,aAAa,EAAS,YAAY;EACzE,aAAa,MAAsB,EAAkB,GAAU,CAAS;EACxE;EACA;EACA;EACA;EACA;EACA;EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,OAAO,mBAAC,EAAuB,UAAxB;EAAwC;EAAQ;CAA0C,CAAA;AACnG"}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { configureGeocoder as e } from "../utils/geocode.js";
|
|
2
|
-
import { configureSpeechEngine as t } from "../../services/speech/
|
|
3
|
-
import "../../services/speech/index.js";
|
|
2
|
+
import { configureSpeechEngine as t } from "../../services/speech/index.js";
|
|
4
3
|
import { createContext as n, useCallback as r, useContext as i, useRef as a } from "react";
|
|
5
4
|
import { MemoryRouter as o } from "react-router";
|
|
6
5
|
import { jsx as s } from "react/jsx-runtime";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HealthyBowlContext.js","names":[],"sources":["../../../src/healthybowl/context/HealthyBowlContext.tsx"],"sourcesContent":["/**\n * HealthyBowl Context Provider\n * @module healthybowl\n */\n\nimport { createContext, useCallback, useContext, useRef, type FC, type PropsWithChildren } from 'react';\nimport { MemoryRouter } from 'react-router';\nimport type { HealthyBowlRootProps } from '../types';\nimport { configureGeocoder } from '../utils/geocode';\nimport { configureSpeechEngine } from '../../services/speech';\n\ninterface HealthyBowlContextValue {\n basePath: string;\n navigate: (path: string) => void;\n currentUser: HealthyBowlRootProps['currentUser'];\n workspaceId: string;\n apiGatewayUrl: string;\n globalGatewayUrl: string;\n authToken: string;\n}\n\nconst HealthyBowlContext = createContext<HealthyBowlContextValue | null>(null);\n\nexport function useHealthyBowl(): HealthyBowlContextValue {\n const context = useContext(HealthyBowlContext);\n if (!context) {\n throw new Error('useHealthyBowl must be used within a HealthyBowlProvider');\n }\n return context;\n}\n\nexport const HealthyBowlProvider: FC<PropsWithChildren<HealthyBowlRootProps>> = ({\n children,\n basePath = '/',\n navigate = () => {},\n currentUser,\n workspaceId = '',\n apiGatewayUrl = '',\n globalGatewayUrl = '',\n authToken = '',\n googleMapsApiKey,\n ttsEndpoint,\n}) => {\n // Inject the host app's Google Maps key into the (non-React) geocoder. Done\n // synchronously in render (not useEffect) so it's set before child map effects\n // run — child effects fire before parent effects. Idempotent module assignment.\n configureGeocoder({ googleMapsApiKey });\n\n /**\n * Point the assistant's speech stack at the hosted TTS proxy.\n *\n * Wiring it HERE, rather than exporting `configureSpeechEngine` for the host\n * to call, is what makes the feature exist at all: nothing outside this graph\n * imported it, so the published bundle had the function tree-shaken away and\n * the module-level endpoint/header slots could never be assigned. The only\n * reachable switch was `window.__HB_TTS_ENDPOINT__`, which carries no headers\n * — i.e. hosted TTS could previously only have been enabled ANONYMOUSLY,\n * against a proxy that bills per character.\n *\n * The token is read through a ref rather than captured. `configureSpeechEngine`\n * is deliberately idempotent (resetting the memoised engine every render would\n * cancel playback mid-reply), so it keeps the FIRST `getHeaders` it is given —\n * and a captured token would work right up until it refreshed, then fail in\n * the hardest place to notice. A stable identity also means this call is a\n * no-op on every render after the first.\n */\n const authTokenRef = useRef(authToken);\n authTokenRef.current = authToken;\n const getHeaders = useCallback(\n (): Record<string, string> => (authTokenRef.current ? { authorization: `Bearer ${authTokenRef.current}` } : {}),\n []\n );\n configureSpeechEngine({ ttsEndpoint, getHeaders });\n\n const contextValue: HealthyBowlContextValue = {\n basePath,\n navigate,\n currentUser,\n workspaceId,\n apiGatewayUrl,\n globalGatewayUrl,\n authToken,\n };\n\n const content = <HealthyBowlContext.Provider value={contextValue}>{children}</HealthyBowlContext.Provider>;\n\n // If basePath is provided, we're running inside the host shell (which has BrowserRouter)\n if (basePath && basePath !== '/') return content;\n\n // Standalone mode: wrap in MemoryRouter\n return <MemoryRouter>{content}</MemoryRouter>;\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"HealthyBowlContext.js","names":[],"sources":["../../../src/healthybowl/context/HealthyBowlContext.tsx"],"sourcesContent":["/**\n * HealthyBowl Context Provider\n * @module healthybowl\n */\n\nimport { createContext, useCallback, useContext, useRef, type FC, type PropsWithChildren } from 'react';\nimport { MemoryRouter } from 'react-router';\nimport type { HealthyBowlRootProps } from '../types';\nimport { configureGeocoder } from '../utils/geocode';\nimport { configureSpeechEngine } from '../../services/speech';\n\ninterface HealthyBowlContextValue {\n basePath: string;\n navigate: (path: string) => void;\n currentUser: HealthyBowlRootProps['currentUser'];\n workspaceId: string;\n apiGatewayUrl: string;\n globalGatewayUrl: string;\n authToken: string;\n}\n\nconst HealthyBowlContext = createContext<HealthyBowlContextValue | null>(null);\n\nexport function useHealthyBowl(): HealthyBowlContextValue {\n const context = useContext(HealthyBowlContext);\n if (!context) {\n throw new Error('useHealthyBowl must be used within a HealthyBowlProvider');\n }\n return context;\n}\n\nexport const HealthyBowlProvider: FC<PropsWithChildren<HealthyBowlRootProps>> = ({\n children,\n basePath = '/',\n navigate = () => {},\n currentUser,\n workspaceId = '',\n apiGatewayUrl = '',\n globalGatewayUrl = '',\n authToken = '',\n googleMapsApiKey,\n ttsEndpoint,\n}) => {\n // Inject the host app's Google Maps key into the (non-React) geocoder. Done\n // synchronously in render (not useEffect) so it's set before child map effects\n // run — child effects fire before parent effects. Idempotent module assignment.\n configureGeocoder({ googleMapsApiKey });\n\n /**\n * Point the assistant's speech stack at the hosted TTS proxy.\n *\n * Wiring it HERE, rather than exporting `configureSpeechEngine` for the host\n * to call, is what makes the feature exist at all: nothing outside this graph\n * imported it, so the published bundle had the function tree-shaken away and\n * the module-level endpoint/header slots could never be assigned. The only\n * reachable switch was `window.__HB_TTS_ENDPOINT__`, which carries no headers\n * — i.e. hosted TTS could previously only have been enabled ANONYMOUSLY,\n * against a proxy that bills per character.\n *\n * The token is read through a ref rather than captured. `configureSpeechEngine`\n * is deliberately idempotent (resetting the memoised engine every render would\n * cancel playback mid-reply), so it keeps the FIRST `getHeaders` it is given —\n * and a captured token would work right up until it refreshed, then fail in\n * the hardest place to notice. A stable identity also means this call is a\n * no-op on every render after the first.\n */\n const authTokenRef = useRef(authToken);\n authTokenRef.current = authToken;\n const getHeaders = useCallback(\n (): Record<string, string> => (authTokenRef.current ? { authorization: `Bearer ${authTokenRef.current}` } : {}),\n []\n );\n configureSpeechEngine({ ttsEndpoint, getHeaders });\n\n const contextValue: HealthyBowlContextValue = {\n basePath,\n navigate,\n currentUser,\n workspaceId,\n apiGatewayUrl,\n globalGatewayUrl,\n authToken,\n };\n\n const content = <HealthyBowlContext.Provider value={contextValue}>{children}</HealthyBowlContext.Provider>;\n\n // If basePath is provided, we're running inside the host shell (which has BrowserRouter)\n if (basePath && basePath !== '/') return content;\n\n // Standalone mode: wrap in MemoryRouter\n return <MemoryRouter>{content}</MemoryRouter>;\n};\n"],"mappings":";;;;;;AAqBA,IAAM,IAAqB,EAA8C,IAAI;AAE7E,SAAgB,IAA0C;CACxD,IAAM,IAAU,EAAW,CAAkB;CAC7C,IAAI,CAAC,GACH,MAAU,MAAM,0DAA0D;CAE5E,OAAO;AACT;AAEA,IAAa,KAAoE,EAC/E,aACA,cAAW,KACX,oBAAiB,CAAC,GAClB,gBACA,iBAAc,IACd,mBAAgB,IAChB,sBAAmB,IACnB,eAAY,IACZ,qBACA,qBACI;CAIJ,EAAkB,EAAE,oBAAiB,CAAC;CAoBtC,IAAM,IAAe,EAAO,CAAS;CAMrC,AALA,EAAa,UAAU,GAKvB,EAAsB;EAAE;EAAa,YAJlB,QACc,EAAa,UAAU,EAAE,eAAe,UAAU,EAAa,UAAU,IAAI,CAAC,GAC7G,CAAC,CAEkC;CAAW,CAAC;CAEjD,IAAM,IAAwC;EAC5C;EACA;EACA;EACA;EACA;EACA;EACA;CACF,GAEM,IAAU,kBAAC,EAAmB,UAApB;EAA6B,OAAO;EAAe;CAAsC,CAAA;CAMzG,OAHI,KAAY,MAAa,MAAY,IAGlC,kBAAC,GAAD,EAAA,UAAe,EAAsB,CAAA;AAC9C"}
|
|
@@ -1,5 +1,2 @@
|
|
|
1
|
-
import "
|
|
2
|
-
|
|
3
|
-
import "./hostedTtsSpeechEngine.js";
|
|
4
|
-
import "./routingSpeechEngine.js";
|
|
5
|
-
import "./createSpeechEngine.js";
|
|
1
|
+
import { configureSpeechEngine as e, getSpeechEngine as t } from "@burdenoff/fe-libs/shared/assistant";
|
|
2
|
+
export { e as configureSpeechEngine, t as getSpeechEngine };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@burdenoff/microfe-healthybowl",
|
|
3
|
-
"version": "2026.903.
|
|
3
|
+
"version": "2026.903.18",
|
|
4
4
|
"description": "Burdenoff HealthyBowl Microfrontend - Comprehensive organic farming and agro-foods management platform",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
50
|
"@apollo/client": "^4.0.11",
|
|
51
|
-
"@burdenoff/fe-libs": "2026.903.
|
|
51
|
+
"@burdenoff/fe-libs": "2026.903.7",
|
|
52
52
|
"@burdenoff/planmagnet-fe-sdk": "2026.831.1",
|
|
53
53
|
"@tanstack/react-query": "^5.90.16",
|
|
54
54
|
"clsx": "^2.1.1",
|
|
@@ -1,91 +0,0 @@
|
|
|
1
|
-
//#region src/services/speech/browserSpeechEngine.ts
|
|
2
|
-
function e() {
|
|
3
|
-
if (typeof window > "u") return null;
|
|
4
|
-
try {
|
|
5
|
-
return window.speechSynthesis ?? null;
|
|
6
|
-
} catch {
|
|
7
|
-
return null;
|
|
8
|
-
}
|
|
9
|
-
}
|
|
10
|
-
function t() {
|
|
11
|
-
return typeof window < "u" && typeof window.SpeechSynthesisUtterance == "function";
|
|
12
|
-
}
|
|
13
|
-
function n(e) {
|
|
14
|
-
switch (e) {
|
|
15
|
-
case "canceled":
|
|
16
|
-
case "cancelled":
|
|
17
|
-
case "interrupted": return "cancelled";
|
|
18
|
-
case "not-allowed": return "not-allowed";
|
|
19
|
-
case "synthesis-unavailable":
|
|
20
|
-
case "language-unavailable":
|
|
21
|
-
case "voice-unavailable": return "unsupported";
|
|
22
|
-
default: return "unknown";
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
var r = 0, i = {
|
|
26
|
-
id: "browser-speech-synthesis",
|
|
27
|
-
isSupported() {
|
|
28
|
-
return e() !== null && t();
|
|
29
|
-
},
|
|
30
|
-
listVoices() {
|
|
31
|
-
try {
|
|
32
|
-
return e()?.getVoices() ?? [];
|
|
33
|
-
} catch {
|
|
34
|
-
return [];
|
|
35
|
-
}
|
|
36
|
-
},
|
|
37
|
-
subscribeVoices(t) {
|
|
38
|
-
let n = e();
|
|
39
|
-
if (!n?.addEventListener) return () => {};
|
|
40
|
-
let r = () => t();
|
|
41
|
-
return n.addEventListener("voiceschanged", r), () => n.removeEventListener("voiceschanged", r);
|
|
42
|
-
},
|
|
43
|
-
speak(i, a, o = {}) {
|
|
44
|
-
let s = e();
|
|
45
|
-
if (!s || !t()) {
|
|
46
|
-
o.onError?.("unsupported");
|
|
47
|
-
return;
|
|
48
|
-
}
|
|
49
|
-
let c = i.filter((e) => e.trim().length > 0);
|
|
50
|
-
if (c.length === 0) {
|
|
51
|
-
o.onEnd?.();
|
|
52
|
-
return;
|
|
53
|
-
}
|
|
54
|
-
r += 1;
|
|
55
|
-
let l = r;
|
|
56
|
-
try {
|
|
57
|
-
s.cancel();
|
|
58
|
-
} catch {}
|
|
59
|
-
c.forEach((e, t) => {
|
|
60
|
-
let i = new window.SpeechSynthesisUtterance(e);
|
|
61
|
-
i.lang = a.lang, a.voice && (i.voice = a.voice), a.rate !== void 0 && (i.rate = a.rate), i.onstart = () => {
|
|
62
|
-
l === r && o.onChunkStart?.(t);
|
|
63
|
-
}, i.onerror = (e) => {
|
|
64
|
-
if (l === r) {
|
|
65
|
-
r += 1;
|
|
66
|
-
try {
|
|
67
|
-
s.cancel();
|
|
68
|
-
} catch {}
|
|
69
|
-
o.onError?.(n(e.error));
|
|
70
|
-
}
|
|
71
|
-
}, t === c.length - 1 && (i.onend = () => {
|
|
72
|
-
l === r && o.onEnd?.();
|
|
73
|
-
});
|
|
74
|
-
try {
|
|
75
|
-
s.speak(i);
|
|
76
|
-
} catch {
|
|
77
|
-
l === r && o.onError?.("unknown");
|
|
78
|
-
}
|
|
79
|
-
});
|
|
80
|
-
},
|
|
81
|
-
cancel() {
|
|
82
|
-
r += 1;
|
|
83
|
-
try {
|
|
84
|
-
e()?.cancel();
|
|
85
|
-
} catch {}
|
|
86
|
-
}
|
|
87
|
-
};
|
|
88
|
-
//#endregion
|
|
89
|
-
export { i as browserSpeechEngine };
|
|
90
|
-
|
|
91
|
-
//# sourceMappingURL=browserSpeechEngine.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"browserSpeechEngine.js","names":[],"sources":["../../../src/services/speech/browserSpeechEngine.ts"],"sourcesContent":["/**\n * `window.speechSynthesis` implementation of the `SpeechEngine` seam (BOFF-6290).\n *\n * Everything platform-specific about speaking lives here, so the hook and the\n * components stay engine-agnostic:\n *\n * - **Feature detection that survives a hostile embed.** Accessing\n * `window.speechSynthesis` can throw in a sandboxed iframe, so every entry\n * point is guarded and returns a benign value instead of crashing the panel.\n * - **Queued utterances, not one long one.** Chrome silently stops an utterance\n * after ~15 seconds; `chunkForSpeech` splits the text and this speaks the\n * pieces in order, reporting `onEnd` only after the last one.\n * - **A generation counter.** `cancel()` makes every queued utterance fire\n * `onerror` with `canceled`/`interrupted`. Those belong to a batch nobody is\n * listening to any more, so they are dropped here rather than being allowed\n * to clear the state of a playback that has already started.\n *\n * Not unit-tested: this repo's vitest runs in the `node` environment with no\n * DOM and no audio. The logic that IS testable was deliberately kept out of this\n * file — see speakableText.ts, speechVoices.ts and speechPlayback.ts.\n */\n\nimport type {\n SpeechEngine,\n SpeechErrorReason,\n SpeechSpeakHandlers,\n SpeechSpeakOptions,\n SpeechVoiceLike,\n} from './types';\n\nfunction getSynthesis(): SpeechSynthesis | null {\n if (typeof window === 'undefined') return null;\n try {\n return window.speechSynthesis ?? null;\n } catch {\n // Sandboxed iframe / policy-blocked: treat as unsupported, never throw.\n return null;\n }\n}\n\nfunction canConstructUtterance(): boolean {\n return typeof window !== 'undefined' && typeof window.SpeechSynthesisUtterance === 'function';\n}\n\nfunction toErrorReason(code: string | undefined): SpeechErrorReason {\n switch (code) {\n // Both spellings appear in the wild (\"canceled\" per spec, \"interrupted\"\n // when a later utterance pre-empts an earlier one).\n case 'canceled':\n case 'cancelled':\n case 'interrupted':\n return 'cancelled';\n case 'not-allowed':\n return 'not-allowed';\n case 'synthesis-unavailable':\n case 'language-unavailable':\n case 'voice-unavailable':\n return 'unsupported';\n default:\n return 'unknown';\n }\n}\n\n/** Bumped on every `speak`/`cancel`; handlers from older batches are ignored. */\nlet generation = 0;\n\nexport const browserSpeechEngine: SpeechEngine = {\n id: 'browser-speech-synthesis',\n\n isSupported(): boolean {\n return getSynthesis() !== null && canConstructUtterance();\n },\n\n listVoices(): SpeechVoiceLike[] {\n try {\n return getSynthesis()?.getVoices() ?? [];\n } catch {\n return [];\n }\n },\n\n subscribeVoices(listener: () => void): () => void {\n const synthesis = getSynthesis();\n if (!synthesis?.addEventListener) return () => {};\n\n // Chrome returns [] from the first getVoices() and fills the list in\n // asynchronously, announcing it with this event. Safari populates\n // synchronously and may never fire it — hence the 'pending' availability\n // state, which keeps the control usable either way.\n const handler = () => listener();\n synthesis.addEventListener('voiceschanged', handler);\n return () => synthesis.removeEventListener('voiceschanged', handler);\n },\n\n speak(chunks: readonly string[], options: SpeechSpeakOptions, handlers: SpeechSpeakHandlers = {}): void {\n const synthesis = getSynthesis();\n if (!synthesis || !canConstructUtterance()) {\n handlers.onError?.('unsupported');\n return;\n }\n\n const speakable = chunks.filter((chunk) => chunk.trim().length > 0);\n if (speakable.length === 0) {\n handlers.onEnd?.();\n return;\n }\n\n // Starting a new playback always ends the old one.\n generation += 1;\n const batch = generation;\n try {\n synthesis.cancel();\n } catch {\n /* cancel on an idle engine can throw in older WebKit — harmless */\n }\n\n speakable.forEach((chunk, index) => {\n const utterance = new window.SpeechSynthesisUtterance(chunk);\n utterance.lang = options.lang;\n if (options.voice) {\n // The seam hands back the caller's own array element, which for this\n // engine is the real SpeechSynthesisVoice that `listVoices` returned.\n utterance.voice = options.voice as SpeechSynthesisVoice;\n }\n if (options.rate !== undefined) utterance.rate = options.rate;\n\n // ★ Per-chunk sync for the live caption. `onstart` is the moment THIS\n // chunk's audio begins, which is exactly when its text should appear —\n // anything earlier is the caption running ahead of the voice.\n utterance.onstart = () => {\n if (batch !== generation) return;\n handlers.onChunkStart?.(index);\n };\n\n utterance.onerror = (event: SpeechSynthesisErrorEvent) => {\n if (batch !== generation) return;\n generation += 1; // abandon the rest of this batch\n try {\n synthesis.cancel();\n } catch {\n /* best effort */\n }\n handlers.onError?.(toErrorReason(event.error));\n };\n\n if (index === speakable.length - 1) {\n utterance.onend = () => {\n if (batch !== generation) return;\n handlers.onEnd?.();\n };\n }\n\n try {\n synthesis.speak(utterance);\n } catch {\n if (batch === generation) handlers.onError?.('unknown');\n }\n });\n },\n\n cancel(): void {\n generation += 1;\n try {\n getSynthesis()?.cancel();\n } catch {\n /* nothing to stop */\n }\n },\n};\n"],"mappings":";AA8BA,SAAS,IAAuC;CAC9C,IAAI,OAAO,SAAW,KAAa,OAAO;CAC1C,IAAI;EACF,OAAO,OAAO,mBAAmB;CACnC,QAAQ;EAEN,OAAO;CACT;AACF;AAEA,SAAS,IAAiC;CACxC,OAAO,OAAO,SAAW,OAAe,OAAO,OAAO,4BAA6B;AACrF;AAEA,SAAS,EAAc,GAA6C;CAClE,QAAQ,GAAR;EAGE,KAAK;EACL,KAAK;EACL,KAAK,eACH,OAAO;EACT,KAAK,eACH,OAAO;EACT,KAAK;EACL,KAAK;EACL,KAAK,qBACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAGA,IAAI,IAAa,GAEJ,IAAoC;CAC/C,IAAI;CAEJ,cAAuB;EACrB,OAAO,EAAa,MAAM,QAAQ,EAAsB;CAC1D;CAEA,aAAgC;EAC9B,IAAI;GACF,OAAO,EAAa,GAAG,UAAU,KAAK,CAAC;EACzC,QAAQ;GACN,OAAO,CAAC;EACV;CACF;CAEA,gBAAgB,GAAkC;EAChD,IAAM,IAAY,EAAa;EAC/B,IAAI,CAAC,GAAW,kBAAkB,aAAa,CAAC;EAMhD,IAAM,UAAgB,EAAS;EAE/B,OADA,EAAU,iBAAiB,iBAAiB,CAAO,SACtC,EAAU,oBAAoB,iBAAiB,CAAO;CACrE;CAEA,MAAM,GAA2B,GAA6B,IAAgC,CAAC,GAAS;EACtG,IAAM,IAAY,EAAa;EAC/B,IAAI,CAAC,KAAa,CAAC,EAAsB,GAAG;GAC1C,EAAS,UAAU,aAAa;GAChC;EACF;EAEA,IAAM,IAAY,EAAO,QAAQ,MAAU,EAAM,KAAK,EAAE,SAAS,CAAC;EAClE,IAAI,EAAU,WAAW,GAAG;GAC1B,EAAS,QAAQ;GACjB;EACF;EAGA,KAAc;EACd,IAAM,IAAQ;EACd,IAAI;GACF,EAAU,OAAO;EACnB,QAAQ,CAER;EAEA,EAAU,SAAS,GAAO,MAAU;GAClC,IAAM,IAAY,IAAI,OAAO,yBAAyB,CAAK;GA4B3D,AA3BA,EAAU,OAAO,EAAQ,MACrB,EAAQ,UAGV,EAAU,QAAQ,EAAQ,QAExB,EAAQ,SAAS,KAAA,MAAW,EAAU,OAAO,EAAQ,OAKzD,EAAU,gBAAgB;IACpB,MAAU,KACd,EAAS,eAAe,CAAK;GAC/B,GAEA,EAAU,WAAW,MAAqC;IACpD,UAAU,GACd;UAAc;KACd,IAAI;MACF,EAAU,OAAO;KACnB,QAAQ,CAER;KACA,EAAS,UAAU,EAAc,EAAM,KAAK,CAAC;IAN/B;GAOhB,GAEI,MAAU,EAAU,SAAS,MAC/B,EAAU,cAAc;IAClB,MAAU,KACd,EAAS,QAAQ;GACnB;GAGF,IAAI;IACF,EAAU,MAAM,CAAS;GAC3B,QAAQ;IACN,AAAI,MAAU,KAAY,EAAS,UAAU,SAAS;GACxD;EACF,CAAC;CACH;CAEA,SAAe;EACb,KAAc;EACd,IAAI;GACF,EAAa,GAAG,OAAO;EACzB,QAAQ,CAER;CACF;AACF"}
|
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
import { browserSpeechEngine as e } from "./browserSpeechEngine.js";
|
|
2
|
-
import { createHostedTtsEngine as t } from "./hostedTtsSpeechEngine.js";
|
|
3
|
-
import { createRoutingSpeechEngine as n } from "./routingSpeechEngine.js";
|
|
4
|
-
//#region src/services/speech/createSpeechEngine.ts
|
|
5
|
-
var r, i;
|
|
6
|
-
function a(e) {
|
|
7
|
-
let t = e.ttsEndpoint?.trim() || void 0;
|
|
8
|
-
t === r && e.getHeaders === i || (r = t, i = e.getHeaders, u());
|
|
9
|
-
}
|
|
10
|
-
function o() {
|
|
11
|
-
if (r) return {
|
|
12
|
-
endpoint: r,
|
|
13
|
-
getHeaders: i
|
|
14
|
-
};
|
|
15
|
-
if (typeof window < "u") {
|
|
16
|
-
let e = window.__HB_TTS_ENDPOINT__;
|
|
17
|
-
if (e) return {
|
|
18
|
-
endpoint: e,
|
|
19
|
-
getHeaders: i
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
return { endpoint: null };
|
|
23
|
-
}
|
|
24
|
-
function s(n = o()) {
|
|
25
|
-
return {
|
|
26
|
-
device: e,
|
|
27
|
-
hosted: n.endpoint ? t({
|
|
28
|
-
endpoint: n.endpoint,
|
|
29
|
-
getHeaders: n.getHeaders,
|
|
30
|
-
fetchImpl: n.fetchImpl
|
|
31
|
-
}) : null
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
|
-
var c = null;
|
|
35
|
-
function l() {
|
|
36
|
-
return c ||= n(s()), c;
|
|
37
|
-
}
|
|
38
|
-
function u() {
|
|
39
|
-
c = null;
|
|
40
|
-
}
|
|
41
|
-
//#endregion
|
|
42
|
-
export { a as configureSpeechEngine, s as createSpeechEngines, l as getSpeechEngine, o as readSpeechEngineConfig, u as resetSpeechEngine };
|
|
43
|
-
|
|
44
|
-
//# sourceMappingURL=createSpeechEngine.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"createSpeechEngine.js","names":[],"sources":["../../../src/services/speech/createSpeechEngine.ts"],"sourcesContent":["/**\n * Which engine speaks — the single switch for the hosted-TTS rollout\n * (BOFF-7111).\n *\n * **Default is unchanged behaviour.** With no endpoint configured this returns\n * the device engine that ships today, so merging this changes nothing for\n * anyone.\n *\n * ★The endpoint MUST be resolved at RUNTIME, not from `import.meta.env`. This\n * microfe is published as a prebuilt package by its own CI, which has no such\n * variable, so a build-time constant is inlined to `undefined` and the whole\n * hosted path is eliminated before the host app ever consumes it — the flag\n * could then never be turned on at all. Verified against the published\n * `2026.829.4` bundle: `geocode.js` ships with its `import.meta.env` fallback\n * gone entirely, leaving only the runtime lookups. `configureGeocoder` exists\n * for exactly this reason and this mirrors it.\n *\n * The fallback is per-language, not global: a hosted vendor that cannot speak\n * the reply's language is worse than the device voice, not better, so\n * the routing engine decides per playback rather than once at startup.\n */\n\nimport { browserSpeechEngine } from './browserSpeechEngine';\nimport { createHostedTtsEngine } from './hostedTtsSpeechEngine';\nimport { createRoutingSpeechEngine } from './routingSpeechEngine';\nimport type { SpeechEngine } from './types';\n\nexport interface SpeechEngineConfig {\n /** Our proxy's URL. Empty/undefined keeps the device engine. */\n endpoint?: string | null;\n getHeaders?: () => Record<string, string>;\n fetchImpl?: typeof fetch;\n}\n\n/** Injected by the host app, which is the only build that knows the URL. */\nlet runtimeEndpoint: string | undefined;\nlet runtimeGetHeaders: (() => Record<string, string>) | undefined;\n\n/**\n * Point the assistant at a hosted TTS proxy.\n *\n * Called by the host shell's provider, exactly as `configureGeocoder` is. This\n * is the supported way to turn hosted speech on; the environment variable below\n * only ever works when this package is run directly (dev / standalone).\n *\n * ★ `getHeaders` is not optional in practice, only in the type. The proxy turns\n * text into audio the org is BILLED for, so an endpoint that accepts anonymous\n * POSTs is a metered API open to anyone who reads the bundle. The engine has\n * always supported per-request headers; until now nothing could reach that hook\n * from the host, which meant the only configuration this function could express\n * was an unauthenticated one. It is a function rather than a value because\n * access tokens expire and the engine outlives any one of them — reading a\n * token once at configure time would work until it rotated and then fail\n * exactly where it is hardest to notice, mid-reply.\n */\nexport function configureSpeechEngine(options: {\n ttsEndpoint?: string | null;\n getHeaders?: () => Record<string, string>;\n}): void {\n const endpoint = options.ttsEndpoint?.trim() || undefined;\n\n // ★ Idempotent because it is called from RENDER, exactly as `configureGeocoder`\n // is. That sibling gets away with an unconditional assignment; this one cannot.\n // `resetSpeechEngine()` drops the memoised engine, and the engine's identity is\n // a dependency of `AssistantSpeechProvider`'s effects (it takes\n // `engine = getSpeechEngine()` as a default prop) — so resetting on every\n // render would hand back a new object every render, re-running the voice\n // subscription continuously and cancelling playback mid-reply. Bailing out\n // when nothing changed keeps the singleton stable without asking every caller\n // to remember why.\n if (endpoint === runtimeEndpoint && options.getHeaders === runtimeGetHeaders) return;\n\n runtimeEndpoint = endpoint;\n runtimeGetHeaders = options.getHeaders;\n // The engine is memoised, so a real change must invalidate it or the setting\n // would silently not take effect.\n resetSpeechEngine();\n}\n\n/**\n * Read the rollout config.\n *\n * Order matters: explicit runtime configuration, then a global the host can set\n * before the bundle loads, and only then the build-time variable — which is\n * eliminated in the published package and therefore useful for local dev only.\n */\nexport function readSpeechEngineConfig(): SpeechEngineConfig {\n // `getHeaders` rides along with every source, not just the first: the window\n // global carries a URL only, and a host that sets it still needs its auth\n // headers to reach the engine.\n if (runtimeEndpoint) return { endpoint: runtimeEndpoint, getHeaders: runtimeGetHeaders };\n if (typeof window !== 'undefined') {\n const fromWindow = (window as unknown as { __HB_TTS_ENDPOINT__?: string }).__HB_TTS_ENDPOINT__;\n if (fromWindow) return { endpoint: fromWindow, getHeaders: runtimeGetHeaders };\n }\n const fromEnv =\n typeof import.meta !== 'undefined' ? (import.meta.env?.VITE_HB_TTS_ENDPOINT as string | undefined) : undefined;\n return { endpoint: fromEnv?.trim() || null };\n}\n\n/**\n * The engine to use, or the device engine when hosted TTS is not configured.\n *\n * Returns `null` for `hosted` when off, so callers can tell \"hosted is not\n * configured\" from \"hosted is configured but cannot speak this language\".\n */\nexport function createSpeechEngines(config: SpeechEngineConfig = readSpeechEngineConfig()): {\n device: SpeechEngine;\n hosted: SpeechEngine | null;\n} {\n const hosted = config.endpoint\n ? createHostedTtsEngine({\n endpoint: config.endpoint,\n getHeaders: config.getHeaders,\n fetchImpl: config.fetchImpl,\n })\n : null;\n return { device: browserSpeechEngine, hosted };\n}\n\n/**\n * The engine the assistant actually uses.\n *\n * A module-level singleton on purpose: the engine's identity appears in\n * `AssistantSpeechProvider`'s dependency arrays, so producing a new object per\n * render would re-run the voice subscription on every render.\n *\n * With no endpoint configured this IS `browserSpeechEngine` — `createRoutingSpeechEngine`\n * returns the device engine unchanged rather than wrapping it — so the default\n * path keeps today's behaviour and today's object identity.\n */\nlet cached: SpeechEngine | null = null;\n\nexport function getSpeechEngine(): SpeechEngine {\n if (!cached) cached = createRoutingSpeechEngine(createSpeechEngines());\n return cached;\n}\n\n/** Test seam: drop the singleton so the next call re-reads the config. */\nexport function resetSpeechEngine(): void {\n cached = null;\n}\n"],"mappings":";;;;AAmCA,IAAI,GACA;AAmBJ,SAAgB,EAAsB,GAG7B;CACP,IAAM,IAAW,EAAQ,aAAa,KAAK,KAAK,KAAA;CAW5C,MAAa,KAAmB,EAAQ,eAAe,MAE3D,IAAkB,GAClB,IAAoB,EAAQ,YAG5B,EAAkB;AACpB;AASA,SAAgB,IAA6C;CAI3D,IAAI,GAAiB,OAAO;EAAE,UAAU;EAAiB,YAAY;CAAkB;CACvF,IAAI,OAAO,SAAW,KAAa;EACjC,IAAM,IAAc,OAAuD;EAC3E,IAAI,GAAY,OAAO;GAAE,UAAU;GAAY,YAAY;EAAkB;CAC/E;CAGA,OAAO,EAAE,UAA6B,KAAK;AAC7C;AAQA,SAAgB,EAAoB,IAA6B,EAAuB,GAGtF;CAQA,OAAO;EAAE,QAAQ;EAAqB,QAPvB,EAAO,WAClB,EAAsB;GACpB,UAAU,EAAO;GACjB,YAAY,EAAO;GACnB,WAAW,EAAO;EACpB,CAAC,IACD;CACyC;AAC/C;AAaA,IAAI,IAA8B;AAElC,SAAgB,IAAgC;CAE9C,OADA,AAAa,MAAS,EAA0B,EAAoB,CAAC,GAC9D;AACT;AAGA,SAAgB,IAA0B;CACxC,IAAS;AACX"}
|
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
//#region src/services/speech/hostedTtsProtocol.ts
|
|
2
|
-
function e(e, t) {
|
|
3
|
-
return t ? !1 : e === "not-allowed" || e === "unsupported";
|
|
4
|
-
}
|
|
5
|
-
var t = 2e3;
|
|
6
|
-
function n(e, t, n, r, i) {
|
|
7
|
-
let a = {
|
|
8
|
-
text: e,
|
|
9
|
-
languageCode: t,
|
|
10
|
-
tier: n
|
|
11
|
-
};
|
|
12
|
-
return r && r.toLowerCase().startsWith(t.toLowerCase()) && (a.voiceName = r), i !== void 0 && (a.speakingRate = i), a;
|
|
13
|
-
}
|
|
14
|
-
function r(e) {
|
|
15
|
-
return e === 401 || e === 403 ? "not-allowed" : e === 404 || e === 501 ? "unsupported" : "unknown";
|
|
16
|
-
}
|
|
17
|
-
function i(e) {
|
|
18
|
-
let t = globalThis.Buffer, n = typeof atob == "function" ? atob(e) : t?.from(e, "base64").toString("binary") ?? "", r = new Uint8Array(n.length);
|
|
19
|
-
for (let e = 0; e < n.length; e += 1) r[e] = n.charCodeAt(e);
|
|
20
|
-
return r;
|
|
21
|
-
}
|
|
22
|
-
function a(e, t) {
|
|
23
|
-
if (t instanceof ArrayBuffer) return t.byteLength > 0 ? new Uint8Array(t) : null;
|
|
24
|
-
if (e?.includes("json") || typeof t == "object") {
|
|
25
|
-
let e = t.audioContent;
|
|
26
|
-
if (!e) return null;
|
|
27
|
-
let n = i(e);
|
|
28
|
-
return n.length > 0 ? n : null;
|
|
29
|
-
}
|
|
30
|
-
return null;
|
|
31
|
-
}
|
|
32
|
-
function o(e, n = t) {
|
|
33
|
-
if (e.length <= n) return [e];
|
|
34
|
-
let r = [], i = e;
|
|
35
|
-
for (; i.length > n;) {
|
|
36
|
-
let e = i.slice(0, n).lastIndexOf(" "), t = e > n * .5 ? e : n;
|
|
37
|
-
r.push(i.slice(0, t).trim()), i = i.slice(t).trim();
|
|
38
|
-
}
|
|
39
|
-
return i && r.push(i), r.filter((e) => e.length > 0);
|
|
40
|
-
}
|
|
41
|
-
//#endregion
|
|
42
|
-
export { n as buildRequest, r as classifyHttpFailure, a as decodeAudioResponse, e as shouldDisableEngine, o as splitForVendor };
|
|
43
|
-
|
|
44
|
-
//# sourceMappingURL=hostedTtsProtocol.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"hostedTtsProtocol.js","names":[],"sources":["../../../src/services/speech/hostedTtsProtocol.ts"],"sourcesContent":["/**\n * The wire contract for the hosted TTS proxy, kept pure so it can be tested\n * (BOFF-7111).\n *\n * `browserSpeechEngine` carries a note explaining that it is untestable in this\n * repo — vitest runs in the `node` environment with no DOM and no audio — and\n * that the testable logic was deliberately kept out of it. Same discipline\n * here: request building, response decoding and error classification live in\n * this file with no `window`, `Audio` or `fetch` reference, and the engine file\n * holds only the parts that genuinely need a browser.\n *\n * The browser never talks to the vendor directly. A Google Cloud service-account\n * key cannot be shipped to a client, so every request goes to our own proxy,\n * which holds the credential and does the vendor call.\n */\n\nimport type { SpeechErrorReason } from './types';\n\n/** What the client sends per chunk. */\nexport interface HostedTtsRequest {\n text: string;\n /** BCP-47, e.g. `ta-IN`. The vendor needs the region, not a bare subtag. */\n languageCode: string;\n /** Vendor voice id, e.g. `ta-IN-Chirp3-HD-Kore`. Omitted = server default. */\n voiceName?: string;\n /** Vendor voice tier, so the backend need not infer it from the name. */\n tier: string;\n /**\n * The same knob the device engine calls `rate`.\n *\n * ★ The accepted range depends on which vendor ENDPOINT the proxy calls, not\n * on the voice tier — see `SPEAKING_RATE_MAX_SYNC` below. Values in use are\n * 0.9, and 0.85 for Indic scripts and Arabic, comfortably inside every\n * variant, so this has never affected playback.\n */\n speakingRate?: number;\n}\n\n/**\n * Google's synthesize response is `{ audioContent: <base64 mp3> }`. We accept\n * that shape directly so the proxy can be a thin pass-through, but the proxy is\n * also free to return raw audio bytes — see `decodeAudioResponse`.\n */\nexport interface HostedTtsJsonResponse {\n audioContent?: string;\n error?: { message?: string };\n}\n\n/**\n * The accepted speaking-rate bounds, for any caller that clamps.\n *\n * ★ The ceiling is a property of the ENDPOINT, not of the voice tier, and the\n * vendor's own rejection message says both numbers out loud:\n *\n * \"Unable to adjust speaking rate. Please ensure that speaking_rate is in the\n * range [0.25, 4.0] for sync synthesis and in the range [0.25, 2.0] for\n * streaming synthesis.\"\n *\n * Measured against the live API on 2026-08-31 with `en-IN-Chirp3-HD-Puck` and a\n * fixed sentence, reading the returned LINEAR16 duration rather than trusting\n * the HTTP status — 4.0 synthesises and is genuinely ~4x faster (21.93s at 0.25\n * down to 1.37s at 4.0); 4.1, 5.0 and 0.2 are all rejected with the message\n * above.\n *\n * This corrects a previous edit of this file which narrowed the ceiling to 2.0\n * and attributed 4.0 to \"the older Standard/WaveNet tiers\". That reading was\n * wrong: 2.0 is the STREAMING limit, and the tier has nothing to do with it.\n *\n * `SPEAKING_RATE_MAX` is the sync ceiling because the proxy calls\n * `v1/text:synthesize`. Moving it to `v1/text:streamingSynthesize` — tempting,\n * since that is how you cut time-to-first-audio — halves the ceiling, and rates\n * the client had treated as valid would start returning 400. That switch has to\n * change this alias in the same commit, which is why both bounds are named\n * rather than one being a magic number.\n */\nexport const SPEAKING_RATE_MIN = 0.25;\nexport const SPEAKING_RATE_MAX_SYNC = 4.0;\nexport const SPEAKING_RATE_MAX_STREAMING = 2.0;\nexport const SPEAKING_RATE_MAX = SPEAKING_RATE_MAX_SYNC;\n\n/**\n * Should a failure stop the engine claiming support for the rest of the page?\n *\n * ★ `not-allowed` has TWO producers and only one of them is terminal:\n *\n * - `classifyHttpFailure` maps HTTP 401/403 to it — the proxy refuses us, and\n * every later request will be refused identically. Latching is right: it\n * makes `routingSpeechEngine` fall back to device voices instead of\n * repeating a request that cannot succeed.\n * - the engine maps the browser's `NotAllowedError` to it — the autoplay\n * policy declining to play audio that was not started by a user gesture.\n * That is PER-GESTURE and entirely transient; the very next tap works.\n *\n * Latching on the second silently deleted the hosted voice for the whole page\n * after a single refusal — and auto-speak is precisely the path that triggers\n * it, because an arriving reply is not a gesture. The user would hear Chirp 3\n * once, be refused once, and get device voices for the rest of the session with\n * nothing explaining why.\n *\n * Pure and exported because the engine itself cannot be unit-tested here (no\n * DOM, no Audio), so the decision is kept where it CAN be.\n */\nexport function shouldDisableEngine(reason: string | undefined, transient: boolean): boolean {\n if (transient) return false;\n return reason === 'not-allowed' || reason === 'unsupported';\n}\n\n/** Vendor limit is 5000 bytes per request; stay well inside it. */\nexport const HOSTED_TTS_MAX_CHARS = 2000;\n\nexport function buildRequest(\n text: string,\n languageCode: string,\n tier: string,\n voiceName?: string | null,\n speakingRate?: number\n): HostedTtsRequest {\n const request: HostedTtsRequest = { text, languageCode, tier };\n // A voice name from ANOTHER language must never be forwarded: the vendor\n // would either error or, worse, read the text with the wrong phoneme model.\n // The caller resolves the voice, but this is the last line of defence.\n if (voiceName && voiceName.toLowerCase().startsWith(languageCode.toLowerCase())) {\n request.voiceName = voiceName;\n }\n if (speakingRate !== undefined) request.speakingRate = speakingRate;\n return request;\n}\n\n/**\n * Map a transport failure onto the reasons the UI already knows how to explain.\n *\n * `cancelled` is deliberately NOT produced here — an aborted request is the\n * caller's own doing and the engine reports it, exactly as the browser engine\n * swallows its own `canceled` utterance errors.\n */\nexport function classifyHttpFailure(status: number): SpeechErrorReason {\n // 401/403 mean the proxy rejected us; there is nothing the user can do and\n // \"unsupported\" is what disables the control rather than showing a retry\n // that will fail identically.\n if (status === 401 || status === 403) return 'not-allowed';\n if (status === 404 || status === 501) return 'unsupported';\n return 'unknown';\n}\n\n/** Base64 → bytes, without assuming a DOM (`atob` is not in node). */\nexport function base64ToBytes(base64: string): Uint8Array {\n // `Buffer` only exists under node (the test environment); typed rather than\n // cast through `any`, which this repo's conventions forbid.\n const nodeBuffer = (\n globalThis as unknown as {\n Buffer?: { from(input: string, encoding: string): { toString(encoding: string): string } };\n }\n ).Buffer;\n const binary =\n typeof atob === 'function' ? atob(base64) : (nodeBuffer?.from(base64, 'base64').toString('binary') ?? '');\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\n/**\n * Accept either shape the proxy may return: a JSON body carrying base64\n * (the vendor's own shape, so the proxy can pass it straight through) or raw\n * audio bytes.\n *\n * Returns null when the payload carries no audio at all — which must be treated\n * as a failure, not as silence. A zero-byte \"success\" that plays nothing is the\n * dead-button bug this feature already fixed once.\n */\nexport function decodeAudioResponse(\n contentType: string | null,\n body: ArrayBuffer | HostedTtsJsonResponse\n): Uint8Array | null {\n if (body instanceof ArrayBuffer) {\n return body.byteLength > 0 ? new Uint8Array(body) : null;\n }\n if (contentType?.includes('json') || typeof body === 'object') {\n const encoded = body.audioContent;\n if (!encoded) return null;\n const bytes = base64ToBytes(encoded);\n return bytes.length > 0 ? bytes : null;\n }\n return null;\n}\n\n/**\n * Split text the hosted vendor would reject for length.\n *\n * `chunkForSpeech` already splits for the browser engine's ~15s utterance\n * ceiling, and those chunks are normally far under the vendor limit — this is a\n * backstop for a single pathological sentence, and it splits on whitespace so a\n * word is never cut in half.\n */\nexport function splitForVendor(text: string, limit = HOSTED_TTS_MAX_CHARS): string[] {\n if (text.length <= limit) return [text];\n const out: string[] = [];\n let rest = text;\n while (rest.length > limit) {\n const window = rest.slice(0, limit);\n const cut = window.lastIndexOf(' ');\n // No space at all (CJK, or one enormous token): hard-cut at the limit\n // rather than sending something the vendor will reject outright.\n const at = cut > limit * 0.5 ? cut : limit;\n out.push(rest.slice(0, at).trim());\n rest = rest.slice(at).trim();\n }\n if (rest) out.push(rest);\n return out.filter((part) => part.length > 0);\n}\n"],"mappings":";AAsGA,SAAgB,EAAoB,GAA4B,GAA6B;CAE3F,OADI,IAAkB,KACf,MAAW,iBAAiB,MAAW;AAChD;AAGA,IAAa,IAAuB;AAEpC,SAAgB,EACd,GACA,GACA,GACA,GACA,GACkB;CAClB,IAAM,IAA4B;EAAE;EAAM;EAAc;CAAK;CAQ7D,OAJI,KAAa,EAAU,YAAY,EAAE,WAAW,EAAa,YAAY,CAAC,MAC5E,EAAQ,YAAY,IAElB,MAAiB,KAAA,MAAW,EAAQ,eAAe,IAChD;AACT;AASA,SAAgB,EAAoB,GAAmC;CAMrE,OAFI,MAAW,OAAO,MAAW,MAAY,gBACzC,MAAW,OAAO,MAAW,MAAY,gBACtC;AACT;AAGA,SAAgB,EAAc,GAA4B;CAGxD,IAAM,IACJ,WAGA,QACI,IACJ,OAAO,QAAS,aAAa,KAAK,CAAM,IAAK,GAAY,KAAK,GAAQ,QAAQ,EAAE,SAAS,QAAQ,KAAK,IAClG,IAAQ,IAAI,WAAW,EAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,EAAO,QAAQ,KAAK,GAAG,EAAM,KAAK,EAAO,WAAW,CAAC;CACzE,OAAO;AACT;AAWA,SAAgB,EACd,GACA,GACmB;CACnB,IAAI,aAAgB,aAClB,OAAO,EAAK,aAAa,IAAI,IAAI,WAAW,CAAI,IAAI;CAEtD,IAAI,GAAa,SAAS,MAAM,KAAK,OAAO,KAAS,UAAU;EAC7D,IAAM,IAAU,EAAK;EACrB,IAAI,CAAC,GAAS,OAAO;EACrB,IAAM,IAAQ,EAAc,CAAO;EACnC,OAAO,EAAM,SAAS,IAAI,IAAQ;CACpC;CACA,OAAO;AACT;AAUA,SAAgB,EAAe,GAAc,IAAQ,GAAgC;CACnF,IAAI,EAAK,UAAU,GAAO,OAAO,CAAC,CAAI;CACtC,IAAM,IAAgB,CAAC,GACnB,IAAO;CACX,OAAO,EAAK,SAAS,IAAO;EAE1B,IAAM,IADS,EAAK,MAAM,GAAG,CACjB,EAAO,YAAY,GAAG,GAG5B,IAAK,IAAM,IAAQ,KAAM,IAAM;EAErC,AADA,EAAI,KAAK,EAAK,MAAM,GAAG,CAAE,EAAE,KAAK,CAAC,GACjC,IAAO,EAAK,MAAM,CAAE,EAAE,KAAK;CAC7B;CAEA,OADI,KAAM,EAAI,KAAK,CAAI,GAChB,EAAI,QAAQ,MAAS,EAAK,SAAS,CAAC;AAC7C"}
|
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
import { HOSTED_TTS_TIER as e, HOSTED_VOICES as t, hostedLocaleFor as n } from "./hostedVoiceCatalogue.js";
|
|
2
|
-
import { buildRequest as r, classifyHttpFailure as i, decodeAudioResponse as a, shouldDisableEngine as o, splitForVendor as s } from "./hostedTtsProtocol.js";
|
|
3
|
-
//#region src/services/speech/hostedTtsSpeechEngine.ts
|
|
4
|
-
function c(c) {
|
|
5
|
-
let l = c.fetchImpl ?? ((...e) => fetch(...e)), u = null, d = null, f = 0, p = null, m = !1, h = () => {
|
|
6
|
-
d &&= (URL.revokeObjectURL(d), null);
|
|
7
|
-
}, g = () => {
|
|
8
|
-
if (u) {
|
|
9
|
-
u.onended = null, u.onerror = null;
|
|
10
|
-
try {
|
|
11
|
-
u.pause();
|
|
12
|
-
} catch {}
|
|
13
|
-
u = null;
|
|
14
|
-
}
|
|
15
|
-
h();
|
|
16
|
-
};
|
|
17
|
-
async function _(t, o, s) {
|
|
18
|
-
let u = r(t, n(o.lang) ?? o.lang, e, o.voice?.name ?? null, o.rate), d = await l(c.endpoint, {
|
|
19
|
-
method: "POST",
|
|
20
|
-
signal: s,
|
|
21
|
-
headers: {
|
|
22
|
-
"content-type": "application/json",
|
|
23
|
-
...c.getHeaders?.() ?? {}
|
|
24
|
-
},
|
|
25
|
-
body: JSON.stringify(u)
|
|
26
|
-
});
|
|
27
|
-
if (!d.ok) {
|
|
28
|
-
let e = /* @__PURE__ */ Error(`hosted tts ${d.status}`);
|
|
29
|
-
throw e.reason = i(d.status), e;
|
|
30
|
-
}
|
|
31
|
-
let f = d.headers.get("content-type"), p = a(f, f?.includes("json") ? await d.json() : await d.arrayBuffer());
|
|
32
|
-
if (!p) {
|
|
33
|
-
let e = /* @__PURE__ */ Error("hosted tts returned no audio");
|
|
34
|
-
throw e.reason = "unknown", e;
|
|
35
|
-
}
|
|
36
|
-
return p;
|
|
37
|
-
}
|
|
38
|
-
function v(e, t, n) {
|
|
39
|
-
return new Promise((r, i) => {
|
|
40
|
-
if (t !== f) {
|
|
41
|
-
r();
|
|
42
|
-
return;
|
|
43
|
-
}
|
|
44
|
-
let a = new Blob([e.slice().buffer], { type: "audio/mpeg" });
|
|
45
|
-
h(), d = URL.createObjectURL(a);
|
|
46
|
-
let o = new Audio(d);
|
|
47
|
-
u = o, o.onended = () => {
|
|
48
|
-
t === f && r();
|
|
49
|
-
}, o.onerror = () => {
|
|
50
|
-
if (t !== f) {
|
|
51
|
-
r();
|
|
52
|
-
return;
|
|
53
|
-
}
|
|
54
|
-
let e = /* @__PURE__ */ Error("audio playback failed");
|
|
55
|
-
e.reason = "unknown", i(e);
|
|
56
|
-
}, o.play().then(() => {
|
|
57
|
-
t === f && n?.();
|
|
58
|
-
}, (e) => {
|
|
59
|
-
if (t !== f) {
|
|
60
|
-
r();
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
let n = /* @__PURE__ */ Error("audio play rejected"), a = e?.name === "NotAllowedError";
|
|
64
|
-
n.reason = a ? "not-allowed" : "unknown", n.transient = a, i(n);
|
|
65
|
-
});
|
|
66
|
-
});
|
|
67
|
-
}
|
|
68
|
-
return {
|
|
69
|
-
id: "hosted-tts",
|
|
70
|
-
isSupported() {
|
|
71
|
-
return m ? !1 : typeof window < "u" && typeof window.Audio == "function" && typeof fetch == "function";
|
|
72
|
-
},
|
|
73
|
-
listVoices() {
|
|
74
|
-
return [...t];
|
|
75
|
-
},
|
|
76
|
-
subscribeVoices() {
|
|
77
|
-
return () => {};
|
|
78
|
-
},
|
|
79
|
-
speak(e, t, n = {}) {
|
|
80
|
-
let r = e.filter((e) => e.trim().length > 0).flatMap((e) => s(e));
|
|
81
|
-
if (r.length === 0) {
|
|
82
|
-
n.onEnd?.();
|
|
83
|
-
return;
|
|
84
|
-
}
|
|
85
|
-
f += 1;
|
|
86
|
-
let i = f;
|
|
87
|
-
g();
|
|
88
|
-
let a = new AbortController();
|
|
89
|
-
p = a;
|
|
90
|
-
let c = !1, l = () => {
|
|
91
|
-
c || (c = !0, n.onStart?.());
|
|
92
|
-
}, u = (e) => {
|
|
93
|
-
let n = _(e, t, a.signal);
|
|
94
|
-
return n.catch(() => {}), n;
|
|
95
|
-
};
|
|
96
|
-
(async () => {
|
|
97
|
-
try {
|
|
98
|
-
let e = u(r[0]);
|
|
99
|
-
for (let t = 0; t < r.length; t += 1) {
|
|
100
|
-
if (i !== f) return;
|
|
101
|
-
let a = await e;
|
|
102
|
-
if (i !== f) return;
|
|
103
|
-
let o = r[t + 1];
|
|
104
|
-
o !== void 0 && (e = u(o)), n.onChunkStart?.(t), await v(a, i, l);
|
|
105
|
-
}
|
|
106
|
-
i === f && n.onEnd?.();
|
|
107
|
-
} catch (e) {
|
|
108
|
-
if (a.abort(), i !== f) return;
|
|
109
|
-
f += 1, g();
|
|
110
|
-
let t = e?.reason;
|
|
111
|
-
o(t, e?.transient === !0) && (m = !0), n.onError?.(t === "not-allowed" || t === "unsupported" || t === "cancelled" ? t : "unknown");
|
|
112
|
-
}
|
|
113
|
-
})();
|
|
114
|
-
},
|
|
115
|
-
cancel() {
|
|
116
|
-
f += 1, p?.abort(), p = null, g();
|
|
117
|
-
}
|
|
118
|
-
};
|
|
119
|
-
}
|
|
120
|
-
//#endregion
|
|
121
|
-
export { c as createHostedTtsEngine };
|
|
122
|
-
|
|
123
|
-
//# sourceMappingURL=hostedTtsSpeechEngine.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"hostedTtsSpeechEngine.js","names":[],"sources":["../../../src/services/speech/hostedTtsSpeechEngine.ts"],"sourcesContent":["/**\n * Hosted (server-side) implementation of the `SpeechEngine` seam (BOFF-7111).\n *\n * The device-voice engine is as good as it is ever going to get: the Web Speech\n * API can only play voices the OS has installed, and on the devices that matter\n * here those are compact voices that do not sound human. Every knob was already\n * turned — rate, voice ranking, punctuation — and the result is still not close\n * to Assistant quality. The remaining gap IS the synthesiser, so this engine\n * replaces it.\n *\n * Structure mirrors `browserSpeechEngine` deliberately:\n * - **A generation counter.** `cancel()` bumps it; any fetch or `ended` event\n * from an older batch is dropped rather than clearing the state of a\n * playback that has already started.\n * - **Chunks played in order**, with the NEXT chunk fetched while the current\n * one plays. Without that prefetch every chunk boundary costs a full network\n * round trip and the reply sounds stuttered — worse than the device voice it\n * replaces.\n * - **Everything testable lives elsewhere** (`hostedTtsProtocol.ts`,\n * `hostedVoiceCatalogue.ts`) because this repo's vitest has no DOM and no\n * audio, so this file cannot be unit-tested.\n *\n * Failure is never silent: any error surfaces through `onError`, and the caller\n * (`createSpeechEngine`) is what decides to fall back to the device engine.\n */\n\nimport { HOSTED_TTS_TIER, HOSTED_VOICES, hostedLocaleFor } from './hostedVoiceCatalogue';\nimport {\n buildRequest,\n classifyHttpFailure,\n decodeAudioResponse,\n shouldDisableEngine,\n splitForVendor,\n} from './hostedTtsProtocol';\nimport type { SpeechEngine, SpeechSpeakHandlers, SpeechSpeakOptions, SpeechVoiceLike } from './types';\n\nexport interface HostedTtsOptions {\n /** Absolute or same-origin path of OUR proxy. Never the vendor directly. */\n endpoint: string;\n /** Extra headers per request (auth). Called fresh each time so a rotated token is picked up. */\n getHeaders?: () => Record<string, string>;\n fetchImpl?: typeof fetch;\n}\n\nexport function createHostedTtsEngine(options: HostedTtsOptions): SpeechEngine {\n const doFetch = options.fetchImpl ?? ((...args: Parameters<typeof fetch>) => fetch(...args));\n let audio: HTMLAudioElement | null = null;\n let objectUrl: string | null = null;\n /**\n * Bumped on every `speak`/`cancel`; anything from an older batch is ignored.\n *\n * Per INSTANCE, not per module. `browserSpeechEngine` can keep this at module\n * scope because it is a singleton object; this is a factory, so a shared\n * counter would let one engine's `cancel()` silently invalidate another\n * engine's in-flight playback.\n */\n let generation = 0;\n /** The in-flight batch's controller, so `cancel()` can actually abort it. */\n let active: AbortController | null = null;\n /**\n * Set after a terminal proxy failure (401/403/404/501). Retrying cannot\n * succeed, and leaving the engine \"supported\" means every later press repeats\n * the same failing request. Reporting unsupported makes the routing engine\n * fall back to device voices, which still work.\n */\n let disabled = false;\n\n const releaseUrl = () => {\n if (objectUrl) {\n URL.revokeObjectURL(objectUrl);\n objectUrl = null;\n }\n };\n\n const stopAudio = () => {\n if (audio) {\n audio.onended = null;\n audio.onerror = null;\n try {\n audio.pause();\n } catch {\n /* pausing an already-dead element is harmless */\n }\n audio = null;\n }\n releaseUrl();\n };\n\n /** One chunk of text -> audio bytes. Throws with a `reason` the engine maps. */\n async function synthesise(text: string, opts: SpeechSpeakOptions, signal: AbortSignal): Promise<Uint8Array> {\n // The vendor's locale, not the app's: the app says `ar-SA`, Google only has\n // `ar-XA`. Sending the app tag would be an unsupported locale AND would\n // make `buildRequest` drop the chosen `ar-XA` voice as a mismatch.\n const languageCode = hostedLocaleFor(opts.lang) ?? opts.lang;\n const body = buildRequest(text, languageCode, HOSTED_TTS_TIER, opts.voice?.name ?? null, opts.rate);\n const response = await doFetch(options.endpoint, {\n method: 'POST',\n signal,\n headers: { 'content-type': 'application/json', ...(options.getHeaders?.() ?? {}) },\n body: JSON.stringify(body),\n });\n if (!response.ok) {\n const err = new Error(`hosted tts ${response.status}`) as Error & { reason?: string };\n err.reason = classifyHttpFailure(response.status);\n throw err;\n }\n const contentType = response.headers.get('content-type');\n const payload = contentType?.includes('json') ? await response.json() : await response.arrayBuffer();\n const bytes = decodeAudioResponse(contentType, payload);\n if (!bytes) {\n // A 200 carrying no audio is a failure, not silence. Treating it as\n // success is exactly the dead-button bug this feature already fixed once.\n const err = new Error('hosted tts returned no audio') as Error & { reason?: string };\n err.reason = 'unknown';\n throw err;\n }\n return bytes;\n }\n\n /**\n * `onBegin` fires when audio genuinely starts, not when it is requested, and\n * not when the chunk ends. The distinction matters to the routing engine: a\n * failure before any sound reached the user can be retried on the device\n * engine, and a failure after it cannot without repeating words.\n */\n function play(bytes: Uint8Array, batch: number, onBegin?: () => void): Promise<void> {\n return new Promise((resolve, reject) => {\n if (batch !== generation) {\n resolve();\n return;\n }\n // Copy into a fresh ArrayBuffer: the Uint8Array may be a view over a\n // larger buffer, and Blob would then include the neighbouring bytes.\n const blob = new Blob([bytes.slice().buffer as ArrayBuffer], { type: 'audio/mpeg' });\n releaseUrl();\n objectUrl = URL.createObjectURL(blob);\n const element = new Audio(objectUrl);\n audio = element;\n element.onended = () => {\n if (batch !== generation) return;\n resolve();\n };\n element.onerror = () => {\n if (batch !== generation) {\n resolve();\n return;\n }\n const err = new Error('audio playback failed') as Error & { reason?: string };\n err.reason = 'unknown';\n reject(err);\n };\n element.play().then(\n () => {\n if (batch === generation) onBegin?.();\n },\n (cause: unknown) => {\n if (batch !== generation) {\n resolve();\n return;\n }\n // Autoplay policy: playback needs a user gesture. Every path that\n // starts speech here is a button press, but an auto-speak triggered\n // by an arriving reply is not, and that is the case this reports.\n const err = new Error('audio play rejected') as Error & { reason?: string; transient?: boolean };\n const autoplayBlocked = (cause as DOMException)?.name === 'NotAllowedError';\n err.reason = autoplayBlocked ? 'not-allowed' : 'unknown';\n // ★ Marked transient so it cannot latch the engine off. An autoplay\n // refusal is per-gesture; the next tap plays. See shouldDisableEngine.\n err.transient = autoplayBlocked;\n reject(err);\n }\n );\n });\n }\n\n return {\n id: 'hosted-tts',\n\n isSupported(): boolean {\n if (disabled) return false;\n return typeof window !== 'undefined' && typeof window.Audio === 'function' && typeof fetch === 'function';\n },\n\n listVoices(): SpeechVoiceLike[] {\n // A hosted catalogue is known up front, so unlike the browser engine\n // there is never an empty-then-populated race: `voiceAvailability` sees a\n // full list on the first read and never reports `pending`.\n return [...HOSTED_VOICES];\n },\n\n subscribeVoices(): () => void {\n // The catalogue is static — nothing to subscribe to. Returning a no-op\n // unsubscribe keeps the caller identical for both engines.\n return () => {};\n },\n\n speak(chunks: readonly string[], opts: SpeechSpeakOptions, handlers: SpeechSpeakHandlers = {}): void {\n const speakable = chunks.filter((chunk) => chunk.trim().length > 0).flatMap((chunk) => splitForVendor(chunk));\n if (speakable.length === 0) {\n handlers.onEnd?.();\n return;\n }\n\n generation += 1;\n const batch = generation;\n stopAudio();\n const controller = new AbortController();\n active = controller;\n\n // Announced at most once per batch: the caller only needs to know that\n // sound reached the user, not how many chunks did.\n let announcedStart = false;\n const notifyStarted = (): void => {\n if (announcedStart) return;\n announcedStart = true;\n handlers.onStart?.();\n };\n\n /**\n * Start a request and neutralise it as an unhandled rejection.\n *\n * A prefetched chunk is abandoned whenever the batch is cancelled\n * mid-loop. Attaching a swallow handler here does NOT consume the\n * rejection for the real `await` — `.catch` returns a NEW promise and the\n * original still rejects — so the error is still reported if we get that\n * far, and is silent if we never do.\n */\n const start = (text: string): Promise<Uint8Array> => {\n const request = synthesise(text, opts, controller.signal);\n request.catch(() => {});\n return request;\n };\n\n void (async () => {\n try {\n // Fetch the first chunk, then keep exactly one chunk in flight ahead\n // of playback so a boundary never costs a whole round trip.\n let pending: Promise<Uint8Array> = start(speakable[0] as string);\n for (let i = 0; i < speakable.length; i += 1) {\n if (batch !== generation) return;\n const current = await pending;\n if (batch !== generation) return;\n const next = speakable[i + 1];\n // On the last chunk nothing new is queued; `pending` keeps its\n // already-settled value and the loop simply ends.\n if (next !== undefined) pending = start(next);\n // ★ Immediately before this chunk's audio plays — the sync signal\n // for the live caption. Here rather than inside `play` because this\n // loop is the only place that knows the INDEX, and a caption that\n // cannot say which chunk is sounding cannot emphasise it.\n handlers.onChunkStart?.(i);\n await play(current, batch, notifyStarted);\n }\n if (batch === generation) handlers.onEnd?.();\n } catch (cause) {\n controller.abort();\n if (batch !== generation) return; // cancelled — the caller already knows\n generation += 1; // abandon the rest of this batch\n stopAudio();\n const reason = (cause as { reason?: string })?.reason;\n // Terminal: the proxy is missing or refuses us, and retrying cannot\n // succeed. Stop claiming support so the routing engine falls back to\n // device voices from now on, instead of every later press repeating\n // the same failing request.\n //\n // ★ A browser autoplay refusal reports the SAME reason and must not\n // latch — it is per-gesture, and auto-speak is exactly the path that\n // triggers it.\n if (shouldDisableEngine(reason, (cause as { transient?: boolean })?.transient === true)) disabled = true;\n handlers.onError?.(\n reason === 'not-allowed' || reason === 'unsupported' || reason === 'cancelled' ? reason : 'unknown'\n );\n }\n })();\n },\n\n cancel(): void {\n generation += 1;\n // Abort the in-flight synthesis too. Without this a cancelled reply keeps\n // downloading — and keeps costing billable vendor characters — until it\n // completes into a batch nobody is listening to.\n active?.abort();\n active = null;\n stopAudio();\n },\n };\n}\n"],"mappings":";;;AA4CA,SAAgB,EAAsB,GAAyC;CAC7E,IAAM,IAAU,EAAQ,eAAe,GAAG,MAAmC,MAAM,GAAG,CAAI,IACtF,IAAiC,MACjC,IAA2B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,GACf;GACT;GAEA,CAAM,YAAY;IAChB,IAAI;KAGF,IAAI,IAA+B,EAAM,EAAU,EAAY;KAC/D,KAAK,IAAI,IAAI,GAAG,IAAI,EAAU,QAAQ,KAAK,GAAG;MAC5C,IAAI,MAAU,GAAY;MAC1B,IAAM,IAAU,MAAM;MACtB,IAAI,MAAU,GAAY;MAC1B,IAAM,IAAO,EAAU,IAAI;MAS3B,AANI,MAAS,KAAA,MAAW,IAAU,EAAM,CAAI,IAK5C,EAAS,eAAe,CAAC,GACzB,MAAM,EAAK,GAAS,GAAO,CAAa;KAC1C;KACA,AAAI,MAAU,KAAY,EAAS,QAAQ;IAC7C,SAAS,GAAO;KAEd,IADA,EAAW,MAAM,GACb,MAAU,GAAY;KAE1B,AADA,KAAc,GACd,EAAU;KACV,IAAM,IAAU,GAA+B;KAU/C,AADI,EAAoB,GAAS,GAAmC,cAAc,EAAI,MAAG,IAAW,KACpG,EAAS,UACP,MAAW,iBAAiB,MAAW,iBAAiB,MAAW,cAAc,IAAS,SAC5F;IACF;GACF,GAAG;EACL;EAEA,SAAe;GAOb,AANA,KAAc,GAId,GAAQ,MAAM,GACd,IAAS,MACT,EAAU;EACZ;CACF;AACF"}
|
|
@@ -1,58 +0,0 @@
|
|
|
1
|
-
//#region src/services/speech/hostedVoiceCatalogue.ts
|
|
2
|
-
var e = "chirp3-hd", t = [
|
|
3
|
-
"Achernar",
|
|
4
|
-
"Algenib",
|
|
5
|
-
"Charon",
|
|
6
|
-
"Kore",
|
|
7
|
-
"Puck",
|
|
8
|
-
"Zephyr"
|
|
9
|
-
], n = [
|
|
10
|
-
"en-US",
|
|
11
|
-
"en-GB",
|
|
12
|
-
"en-IN",
|
|
13
|
-
"ta-IN",
|
|
14
|
-
"hi-IN",
|
|
15
|
-
"bn-IN",
|
|
16
|
-
"te-IN",
|
|
17
|
-
"mr-IN",
|
|
18
|
-
"gu-IN",
|
|
19
|
-
"kn-IN",
|
|
20
|
-
"ml-IN",
|
|
21
|
-
"pa-IN",
|
|
22
|
-
"ur-IN",
|
|
23
|
-
"ar-XA",
|
|
24
|
-
"es-ES",
|
|
25
|
-
"cmn-CN",
|
|
26
|
-
"ja-JP",
|
|
27
|
-
"fr-FR",
|
|
28
|
-
"de-DE"
|
|
29
|
-
], r = { "cmn-CN": "zh-CN" };
|
|
30
|
-
function i(e) {
|
|
31
|
-
return r[e] ?? e;
|
|
32
|
-
}
|
|
33
|
-
var a = n.flatMap((e) => t.map((t) => ({
|
|
34
|
-
name: `${e}-Chirp3-HD-${t}`,
|
|
35
|
-
lang: i(e),
|
|
36
|
-
localService: !1
|
|
37
|
-
}))), o = /* @__PURE__ */ new Map();
|
|
38
|
-
for (let e of n) for (let t of new Set([i(e), e])) {
|
|
39
|
-
let n = t.toLowerCase().split("-")[0];
|
|
40
|
-
o.has(n) || o.set(n, e);
|
|
41
|
-
}
|
|
42
|
-
var s = /* @__PURE__ */ new Map();
|
|
43
|
-
for (let e of n) s.set(e.toLowerCase(), e), s.set(i(e).toLowerCase(), e);
|
|
44
|
-
function c(e) {
|
|
45
|
-
let t = e.trim().replace("_", "-");
|
|
46
|
-
if (!t) return null;
|
|
47
|
-
let n = s.get(t.toLowerCase());
|
|
48
|
-
if (n) return n;
|
|
49
|
-
let r = t.toLowerCase().split("-")[0];
|
|
50
|
-
return o.get(r) ?? null;
|
|
51
|
-
}
|
|
52
|
-
function l(e) {
|
|
53
|
-
return c(e) !== null;
|
|
54
|
-
}
|
|
55
|
-
//#endregion
|
|
56
|
-
export { e as HOSTED_TTS_TIER, a as HOSTED_VOICES, c as hostedLocaleFor, l as hostedSupportsLanguage };
|
|
57
|
-
|
|
58
|
-
//# sourceMappingURL=hostedVoiceCatalogue.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"hostedVoiceCatalogue.js","names":[],"sources":["../../../src/services/speech/hostedVoiceCatalogue.ts"],"sourcesContent":["/**\n * The voices a hosted engine can offer, per locale (BOFF-7111).\n *\n * A hosted engine has no `getVoices()` to ask — the catalogue is a property of\n * the vendor, not of the device — so it is declared here and returned from\n * `listVoices()`. That keeps the whole existing selection stack working\n * unchanged: `voicesForLocale` ranks these, `selectVoiceForLocale` honours the\n * user's saved pick, and the picker renders them exactly as it renders device\n * voices.\n *\n * Named for Google's Chirp 3: HD tier, which is the reason for doing this at\n * all — it is the only tier that covers every language the assistant speaks\n * INCLUDING Tamil. (Amazon Polly has no Tamil at all, which is why it was\n * rejected.) The names are the vendor's own voice ids so the backend can pass\n * them straight through without a mapping table that could drift.\n *\n * `localService: false` on every entry is not decoration: `voiceQualityRank`\n * scores non-local voices above local ones, so when a device voice and a hosted\n * voice are both somehow present the hosted one wins by default — which is the\n * whole point of turning the hosted engine on.\n *\n * Every entry below was verified against the vendor's live `voices.list` on\n * 2026-08-31 (BOFF-7117), once the API was actually enabled. That check is the\n * reason this file distinguishes an app tag from a vendor locale at all — see\n * `VENDOR_LOCALES`.\n */\n\nimport type { SpeechVoiceLike } from '../../utils/speechVoices';\n\n/** Vendor tier this catalogue describes; sent to the backend with each request. */\nexport const HOSTED_TTS_TIER = 'chirp3-hd';\n\n/**\n * Speaker names are shared across locales in this tier — the same speaker id is\n * offered in every supported locale, so the catalogue is a cross product rather\n * than a hand-written list per language.\n */\nconst SPEAKERS = ['Achernar', 'Algenib', 'Charon', 'Kore', 'Puck', 'Zephyr'] as const;\n\n/**\n * The locales the assistant can speak, **as the vendor spells them**.\n *\n * Deliberately NOT every locale the vendor supports: offering a language the\n * assistant cannot actually reply in would be a dead option in the picker.\n *\n * These are the vendor's tags, not the app's, and the two are not always the\n * same string. Getting that wrong is not a cosmetic bug: a voice id the vendor\n * does not publish is rejected with HTTP 400, `classifyHttpFailure` maps 400 to\n * `unknown`, and the reply then fails to play at all — strictly worse than the\n * device voice it was meant to replace, because the device path would at least\n * have spoken. `APP_TAG_BY_VENDOR_LOCALE` is what keeps the two vocabularies\n * from being confused.\n */\nconst VENDOR_LOCALES = [\n 'en-US',\n 'en-GB',\n 'en-IN',\n 'ta-IN',\n 'hi-IN',\n 'bn-IN',\n 'te-IN',\n 'mr-IN',\n 'gu-IN',\n 'kn-IN',\n 'ml-IN',\n 'pa-IN',\n 'ur-IN',\n 'ar-XA',\n 'es-ES',\n // Mandarin. The app calls this `zh-CN` (SPEECH_LANG.zh) but the vendor\n // publishes it ONLY as `cmn-CN` — `zh-CN-Chirp3-HD-Kore` does not exist and\n // returns \"Voice ... does not exist. Is it misspelled?\". Verified live.\n 'cmn-CN',\n 'ja-JP',\n 'fr-FR',\n 'de-DE',\n] as const;\n\n/**\n * Vendor locale -> the tag the APP uses for the same language, for the tags\n * where the two genuinely disagree.\n *\n * This is the `lang` each catalogue entry advertises, and it has to be the\n * app's tag rather than the vendor's, because `voicesForLocale` matches a voice\n * to a locale by PRIMARY SUBTAG. `zh` and `cmn` are different primary subtags,\n * so a catalogue entry advertising `lang: 'cmn-CN'` would be invisible to a\n * Chinese reply — the hosted Chinese voices would simply never appear in the\n * picker, which is the quiet half of the same bug.\n *\n * Arabic needs no entry here: the app says `ar-SA` and the vendor says `ar-XA`,\n * but both reduce to the primary subtag `ar`, so the existing \"same language,\n * any region\" rung of the ladder already matches them. Mandarin is the only\n * language in this catalogue where the primary subtags themselves differ.\n */\nconst APP_TAG_BY_VENDOR_LOCALE: Readonly<Record<string, string>> = {\n 'cmn-CN': 'zh-CN',\n};\n\n/** The app-facing tag to advertise for a vendor locale. */\nfunction appTagFor(vendorLocale: string): string {\n return APP_TAG_BY_VENDOR_LOCALE[vendorLocale] ?? vendorLocale;\n}\n\n/**\n * Every hosted voice, as `SpeechVoiceLike` so it is interchangeable with a\n * device voice everywhere downstream.\n *\n * The vendor id form is `<vendor-locale>-Chirp3-HD-<Speaker>`, e.g.\n * `ta-IN-Chirp3-HD-Kore`. It is used as BOTH the display name and the id the\n * backend receives, because the persisted preference is keyed by name — a\n * separate display label would break a saved pick the first time it changed.\n *\n * `name` is therefore always the VENDOR's spelling (it is sent on the wire and\n * must exist), while `lang` is always the APP's (it is matched against\n * `SPEECH_LANG`). For every locale but Mandarin these are the same string.\n */\nexport const HOSTED_VOICES: readonly SpeechVoiceLike[] = VENDOR_LOCALES.flatMap((vendorLocale) =>\n SPEAKERS.map((speaker) => ({\n name: `${vendorLocale}-Chirp3-HD-${speaker}`,\n lang: appTagFor(vendorLocale),\n // Never on-device. See the file header: this is what makes a hosted voice\n // outrank a compact device voice in `voiceQualityRank`.\n localService: false,\n }))\n);\n\n/**\n * App locale tag -> the vendor's own locale, by primary subtag.\n *\n * These are NOT always the same string, and assuming they were is a real bug:\n * the app speaks Arabic as `ar-SA` while Google's catalogue only has `ar-XA`,\n * and Mandarin as `zh-CN` while Google's catalogue only has `cmn-CN`. Sending\n * the app's tag would be an unsupported vendor locale AND would cause the\n * chosen voice to be dropped as a cross-language mismatch, so the language\n * would fail on both counts.\n *\n * Built once from the catalogue rather than hand-written, so a locale can never\n * be listed here that has no voices. Keyed on the primary subtag of the\n * APP-facing tag, because an app tag is what callers pass. First match wins,\n * which is why the regional English variants are ordered deliberately in\n * `VENDOR_LOCALES`.\n */\nconst VENDOR_LOCALE_BY_PRIMARY = new Map<string, string>();\nfor (const vendorLocale of VENDOR_LOCALES) {\n for (const tag of new Set([appTagFor(vendorLocale), vendorLocale])) {\n const primary = tag.toLowerCase().split('-')[0] as string;\n if (!VENDOR_LOCALE_BY_PRIMARY.has(primary)) VENDOR_LOCALE_BY_PRIMARY.set(primary, vendorLocale);\n }\n}\n\n/** Exact app-facing tag -> vendor locale, checked before the primary-subtag fallback. */\nconst VENDOR_LOCALE_BY_APP_TAG = new Map<string, string>();\nfor (const vendorLocale of VENDOR_LOCALES) {\n VENDOR_LOCALE_BY_APP_TAG.set(vendorLocale.toLowerCase(), vendorLocale);\n VENDOR_LOCALE_BY_APP_TAG.set(appTagFor(vendorLocale).toLowerCase(), vendorLocale);\n}\n\n/**\n * The exact vendor locale to request for an app tag, or null when the vendor\n * cannot speak the language at all.\n *\n * Prefers an exact match (`en-GB` stays `en-GB`, `zh-CN` becomes `cmn-CN`) and\n * otherwise falls back to the primary subtag's canonical vendor locale\n * (`ar-SA` -> `ar-XA`, `zh` -> `cmn-CN`).\n */\nexport function hostedLocaleFor(tag: string): string | null {\n const normalised = tag.trim().replace('_', '-');\n if (!normalised) return null;\n const exact = VENDOR_LOCALE_BY_APP_TAG.get(normalised.toLowerCase());\n if (exact) return exact;\n const primary = normalised.toLowerCase().split('-')[0] as string;\n return VENDOR_LOCALE_BY_PRIMARY.get(primary) ?? null;\n}\n\n/**\n * True when the hosted engine can actually speak this language.\n *\n * The caller needs this to decide whether to fall back to the device engine\n * for a reply in a language the vendor does not cover, rather than sending a\n * request that can only fail.\n */\nexport function hostedSupportsLanguage(tag: string): boolean {\n return hostedLocaleFor(tag) !== null;\n}\n"],"mappings":";AA8BA,IAAa,IAAkB,aAOzB,IAAW;CAAC;CAAY;CAAW;CAAU;CAAQ;CAAQ;AAAQ,GAgBrE,IAAiB;CACrB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAIA;CACA;CACA;CACA;AACF,GAkBM,IAA6D,EACjE,UAAU,QACZ;AAGA,SAAS,EAAU,GAA8B;CAC/C,OAAO,EAAyB,MAAiB;AACnD;AAeA,IAAa,IAA4C,EAAe,SAAS,MAC/E,EAAS,KAAK,OAAa;CACzB,MAAM,GAAG,EAAa,aAAa;CACnC,MAAM,EAAU,CAAY;CAG5B,cAAc;AAChB,EAAE,CACJ,GAkBM,oBAA2B,IAAI,IAAoB;AACzD,KAAK,IAAM,KAAgB,GACzB,KAAK,IAAM,KAAO,IAAI,IAAI,CAAC,EAAU,CAAY,GAAG,CAAY,CAAC,GAAG;CAClE,IAAM,IAAU,EAAI,YAAY,EAAE,MAAM,GAAG,EAAE;CAC7C,AAAK,EAAyB,IAAI,CAAO,KAAG,EAAyB,IAAI,GAAS,CAAY;AAChG;AAIF,IAAM,oBAA2B,IAAI,IAAoB;AACzD,KAAK,IAAM,KAAgB,GAEzB,AADA,EAAyB,IAAI,EAAa,YAAY,GAAG,CAAY,GACrE,EAAyB,IAAI,EAAU,CAAY,EAAE,YAAY,GAAG,CAAY;AAWlF,SAAgB,EAAgB,GAA4B;CAC1D,IAAM,IAAa,EAAI,KAAK,EAAE,QAAQ,KAAK,GAAG;CAC9C,IAAI,CAAC,GAAY,OAAO;CACxB,IAAM,IAAQ,EAAyB,IAAI,EAAW,YAAY,CAAC;CACnE,IAAI,GAAO,OAAO;CAClB,IAAM,IAAU,EAAW,YAAY,EAAE,MAAM,GAAG,EAAE;CACpD,OAAO,EAAyB,IAAI,CAAO,KAAK;AAClD;AASA,SAAgB,EAAuB,GAAsB;CAC3D,OAAO,EAAgB,CAAG,MAAM;AAClC"}
|
|
@@ -1,46 +0,0 @@
|
|
|
1
|
-
import { hostedSupportsLanguage as e } from "./hostedVoiceCatalogue.js";
|
|
2
|
-
//#region src/services/speech/routingSpeechEngine.ts
|
|
3
|
-
function t({ device: t, hosted: n }) {
|
|
4
|
-
if (!n) return t;
|
|
5
|
-
let r = new Set(n.listVoices().map((e) => e.name)), i = (i) => n.isSupported() ? i.voice ? r.has(i.voice.name) ? n : t : e(i.lang) ? n : t : t;
|
|
6
|
-
return {
|
|
7
|
-
id: `routing(${n.id}+${t.id})`,
|
|
8
|
-
isSupported() {
|
|
9
|
-
return n.isSupported() || t.isSupported();
|
|
10
|
-
},
|
|
11
|
-
listVoices() {
|
|
12
|
-
return [...n.listVoices(), ...t.listVoices()];
|
|
13
|
-
},
|
|
14
|
-
subscribeVoices(e) {
|
|
15
|
-
return t.subscribeVoices(e);
|
|
16
|
-
},
|
|
17
|
-
speak(e, r, a) {
|
|
18
|
-
if (t.cancel(), n.cancel(), i(r) !== n) {
|
|
19
|
-
t.speak(e, r, a);
|
|
20
|
-
return;
|
|
21
|
-
}
|
|
22
|
-
let o = !1;
|
|
23
|
-
n.speak(e, r, {
|
|
24
|
-
onStart: () => {
|
|
25
|
-
o = !0, a?.onStart?.();
|
|
26
|
-
},
|
|
27
|
-
onEnd: () => a?.onEnd?.(),
|
|
28
|
-
onChunkStart: (e) => a?.onChunkStart?.(e),
|
|
29
|
-
onError: (n) => {
|
|
30
|
-
if (n === "cancelled" || o) {
|
|
31
|
-
a?.onError?.(n);
|
|
32
|
-
return;
|
|
33
|
-
}
|
|
34
|
-
t.speak(e, r, a);
|
|
35
|
-
}
|
|
36
|
-
});
|
|
37
|
-
},
|
|
38
|
-
cancel() {
|
|
39
|
-
t.cancel(), n.cancel();
|
|
40
|
-
}
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
//#endregion
|
|
44
|
-
export { t as createRoutingSpeechEngine };
|
|
45
|
-
|
|
46
|
-
//# sourceMappingURL=routingSpeechEngine.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"routingSpeechEngine.js","names":[],"sources":["../../../src/services/speech/routingSpeechEngine.ts"],"sourcesContent":["/**\n * One `SpeechEngine` that routes each playback to the device or the hosted\n * engine (BOFF-7111).\n *\n * Why a routing engine rather than teaching `AssistantSpeechProvider` about two\n * engines: the provider, the availability logic, the gate and the voice picker\n * are all written against a SINGLE `SpeechEngine`, and they work. Splitting that\n * assumption would touch every one of them. Composing instead means the\n * hosted-TTS rollout changes **no component and no existing test** — which is\n * also what the seam's original author promised in `types.ts`.\n *\n * Routing is decided by the VOICE, not the language, because the voice is what\n * the user actually chose. `listVoices()` returns the hosted catalogue and the\n * device list together, `voiceQualityRank` already scores hosted voices above\n * compact local ones (they are `localService: false`), and the existing picker\n * therefore offers both with the hosted one selected by default. Picking a\n * device voice deliberately still works and routes to the device engine.\n */\n\nimport { hostedSupportsLanguage } from './hostedVoiceCatalogue';\nimport type { SpeechEngine, SpeechSpeakHandlers, SpeechSpeakOptions, SpeechVoiceLike } from './types';\n\nexport interface RoutingEngines {\n device: SpeechEngine;\n /** Null when hosted TTS is not configured — then this is a pass-through. */\n hosted: SpeechEngine | null;\n}\n\nexport function createRoutingSpeechEngine({ device, hosted }: RoutingEngines): SpeechEngine {\n if (!hosted) return device;\n\n /** Hosted voice names are the vendor ids the hosted catalogue declares. */\n const hostedNames = new Set(hosted.listVoices().map((voice) => voice.name));\n\n const pick = (options: SpeechSpeakOptions): SpeechEngine => {\n if (!hosted.isSupported()) return device;\n // An explicit pick wins: it is the user's own decision.\n if (options.voice) return hostedNames.has(options.voice.name) ? hosted : device;\n // No voice resolved (the caller found none for this language). Hosted can\n // still speak it if the vendor covers the language; otherwise the device\n // engine's own \"no voice\" handling explains the problem, as it does today.\n return hostedSupportsLanguage(options.lang) ? hosted : device;\n };\n\n return {\n id: `routing(${hosted.id}+${device.id})`,\n\n isSupported(): boolean {\n return hosted.isSupported() || device.isSupported();\n },\n\n listVoices(): SpeechVoiceLike[] {\n // Hosted first so that where ranks tie, list order favours the hosted\n // voice. Device voices are still offered: they work offline and some\n // users will prefer a familiar system voice.\n return [...hosted.listVoices(), ...device.listVoices()];\n },\n\n subscribeVoices(listener: () => void): () => void {\n // Only the device list changes over time; the hosted catalogue is static.\n return device.subscribeVoices(listener);\n },\n\n speak(chunks: readonly string[], options: SpeechSpeakOptions, handlers?: SpeechSpeakHandlers): void {\n // Stop BOTH before starting: the previous playback may have been on the\n // other engine, and leaving it running would produce two overlapping\n // voices — the one failure mode a routing layer can uniquely cause.\n device.cancel();\n hosted.cancel();\n\n const chosen = pick(options);\n if (chosen !== hosted) {\n device.speak(chunks, options, handlers);\n return;\n }\n\n /**\n * ★ Fall back to the device voice when the hosted engine fails before the\n * user has heard anything.\n *\n * Without this, turning hosted TTS on makes the product WORSE in exactly\n * the case it is meant to survive. The hosted engine already latches\n * itself off for `not-allowed` and `unsupported`, but everything else —\n * a proxy 500, a vendor outage, a timeout, a dropped connection — maps to\n * `unknown`, which latches nothing. So an outage produced silence on\n * every reply, indefinitely, where the device voice would have spoken.\n *\n * Two conditions, both necessary:\n *\n * - `cancelled` never retries. It is not a failure; it is the user (or a\n * new reply, or a closing panel) deliberately stopping playback, and\n * speaking again would be the worst possible response.\n * - Nothing may have been heard yet. If audio already started, the\n * remaining chunks are not worth repeating the earlier ones for, so the\n * error is reported as-is.\n *\n * Deliberately NOT a latch: it is decided per utterance, so a transient\n * outage costs one failed request per reply and recovers by itself the\n * moment the proxy is healthy again. A latch would strand every user on\n * the device voice until the page was reloaded.\n */\n let heardSomething = false;\n hosted.speak(chunks, options, {\n onStart: () => {\n heardSomething = true;\n handlers?.onStart?.();\n },\n onEnd: () => handlers?.onEnd?.(),\n // ★ Forwarded by hand. This object REPLACES the caller's handlers rather\n // than extending them, so a new handler that is not relayed here is\n // dropped on the hosted path ONLY — the caption would sync on some\n // devices and not others, with nothing failing anywhere.\n onChunkStart: (index) => handlers?.onChunkStart?.(index),\n onError: (reason) => {\n if (reason === 'cancelled' || heardSomething) {\n handlers?.onError?.(reason);\n return;\n }\n device.speak(chunks, options, handlers);\n },\n });\n },\n\n cancel(): void {\n device.cancel();\n hosted.cancel();\n },\n };\n}\n"],"mappings":";;AA4BA,SAAgB,EAA0B,EAAE,WAAQ,aAAwC;CAC1F,IAAI,CAAC,GAAQ,OAAO;CAGpB,IAAM,IAAc,IAAI,IAAI,EAAO,WAAW,EAAE,KAAK,MAAU,EAAM,IAAI,CAAC,GAEpE,KAAQ,MACP,EAAO,YAAY,IAEpB,EAAQ,QAAc,EAAY,IAAI,EAAQ,MAAM,IAAI,IAAI,IAAS,IAIlE,EAAuB,EAAQ,IAAI,IAAI,IAAS,IANrB;CASpC,OAAO;EACL,IAAI,WAAW,EAAO,GAAG,GAAG,EAAO,GAAG;EAEtC,cAAuB;GACrB,OAAO,EAAO,YAAY,KAAK,EAAO,YAAY;EACpD;EAEA,aAAgC;GAI9B,OAAO,CAAC,GAAG,EAAO,WAAW,GAAG,GAAG,EAAO,WAAW,CAAC;EACxD;EAEA,gBAAgB,GAAkC;GAEhD,OAAO,EAAO,gBAAgB,CAAQ;EACxC;EAEA,MAAM,GAA2B,GAA6B,GAAsC;GAQlG,IAJA,EAAO,OAAO,GACd,EAAO,OAAO,GAEC,EAAK,CAChB,MAAW,GAAQ;IACrB,EAAO,MAAM,GAAQ,GAAS,CAAQ;IACtC;GACF;GA2BA,IAAI,IAAiB;GACrB,EAAO,MAAM,GAAQ,GAAS;IAC5B,eAAe;KAEb,AADA,IAAiB,IACjB,GAAU,UAAU;IACtB;IACA,aAAa,GAAU,QAAQ;IAK/B,eAAe,MAAU,GAAU,eAAe,CAAK;IACvD,UAAU,MAAW;KACnB,IAAI,MAAW,eAAe,GAAgB;MAC5C,GAAU,UAAU,CAAM;MAC1B;KACF;KACA,EAAO,MAAM,GAAQ,GAAS,CAAQ;IACxC;GACF,CAAC;EACH;EAEA,SAAe;GAEb,AADA,EAAO,OAAO,GACd,EAAO,OAAO;EAChB;CACF;AACF"}
|