@burdenoff/microfe-healthybowl 2026.831.6 → 2026.831.8
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/AssistantSpeechProvider.js +8 -8
- package/dist/healthybowl/context/HealthyBowlContext.js +28 -21
- package/dist/healthybowl/context/HealthyBowlContext.js.map +1 -1
- package/dist/services/speech/createSpeechEngine.js +13 -6
- package/dist/services/speech/createSpeechEngine.js.map +1 -1
- package/dist/services/speech/hostedTtsSpeechEngine.js +22 -18
- package/dist/services/speech/hostedTtsSpeechEngine.js.map +1 -1
- package/dist/services/speech/routingSpeechEngine.js +18 -1
- package/dist/services/speech/routingSpeechEngine.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { useTr as t } from "../../shared/hooks/useTr.js";
|
|
3
|
-
import { getSpeechEngine as n } from "../../services/speech/createSpeechEngine.js";
|
|
1
|
+
import { getSpeechEngine as e } from "../../services/speech/createSpeechEngine.js";
|
|
4
2
|
import "../../services/speech/index.js";
|
|
3
|
+
import { useAssistantStore as t } from "../../store/assistantStore.js";
|
|
4
|
+
import { useTr as n } from "../../shared/hooks/useTr.js";
|
|
5
5
|
import { chunkForSpeech as r, toSpeakableText as i } from "../../utils/speakableText.js";
|
|
6
6
|
import { speechLabelsFor as a } from "../../config/speechLabels.js";
|
|
7
7
|
import { VOICE_LIST_TIMEOUT_MS as o, languageDisplayName as s, selectVoiceForLocale as c, speechGate as ee, speechLangForLocale as l, voiceAvailability as u, voicesForLocale as d } from "../../utils/speechVoices.js";
|
|
@@ -43,10 +43,10 @@ var ue = {
|
|
|
43
43
|
function S() {
|
|
44
44
|
return g(x);
|
|
45
45
|
}
|
|
46
|
-
var C = ({ children: m, visible: g = !0, engine: S =
|
|
47
|
-
let C =
|
|
46
|
+
var C = ({ children: m, visible: g = !0, engine: S = e() }) => {
|
|
47
|
+
let C = n(), { locale: w } = ce(), [T, E] = se(ie, re), [D, O] = b(() => S.listVoices()), [k, A] = b(!1), [j, M] = b(() => /* @__PURE__ */ new Map()), N = y(0), P = y(null), F = y(() => {}), I = h(() => {
|
|
48
48
|
P.current?.(), P.current = null;
|
|
49
|
-
}, []), L =
|
|
49
|
+
}, []), L = t((e) => e.autoSpeakEnabled), R = t((e) => e.setAutoSpeak), de = t((e) => e.activeConversationId), z = v(() => S.isSupported(), [S]);
|
|
50
50
|
_(() => {
|
|
51
51
|
if (!z) return;
|
|
52
52
|
let e = () => {
|
|
@@ -54,7 +54,7 @@ var C = ({ children: m, visible: g = !0, engine: S = n() }) => {
|
|
|
54
54
|
};
|
|
55
55
|
return e(), S.subscribeVoices(e);
|
|
56
56
|
}, [S, z]);
|
|
57
|
-
let B =
|
|
57
|
+
let B = t((e) => e.assistantLanguage), V = t((e) => e.preferredVoices), H = t((e) => e.setPreferredVoice), U = v(() => ne(B, w), [B, w]), W = U.code, G = h((e) => f(e)?.tag ?? l(e), []), K = h((e) => f(e)?.rate ?? .9, []), q = v(() => u(z, D, U.tag, k), [
|
|
58
58
|
z,
|
|
59
59
|
D,
|
|
60
60
|
U,
|
|
@@ -189,7 +189,7 @@ var C = ({ children: m, visible: g = !0, engine: S = n() }) => {
|
|
|
189
189
|
_(() => {
|
|
190
190
|
me.current = Q;
|
|
191
191
|
}, [Q]), _(() => {
|
|
192
|
-
if (!(!L || !g || !z)) return
|
|
192
|
+
if (!(!L || !g || !z)) return t.subscribe((e, t) => {
|
|
193
193
|
let n = e.activeConversationId;
|
|
194
194
|
if (!n || n !== t.activeConversationId) return;
|
|
195
195
|
let r = e.processingByConversationId[n], i = t.processingByConversationId[n];
|
|
@@ -1,31 +1,38 @@
|
|
|
1
1
|
import { configureGeocoder as e } from "../utils/geocode.js";
|
|
2
|
-
import {
|
|
3
|
-
import
|
|
4
|
-
import {
|
|
2
|
+
import { configureSpeechEngine as t } from "../../services/speech/createSpeechEngine.js";
|
|
3
|
+
import "../../services/speech/index.js";
|
|
4
|
+
import { createContext as n, useCallback as r, useContext as i, useRef as a } from "react";
|
|
5
|
+
import { MemoryRouter as o } from "react-router";
|
|
6
|
+
import { jsx as s } from "react/jsx-runtime";
|
|
5
7
|
//#region src/healthybowl/context/HealthyBowlContext.tsx
|
|
6
|
-
var
|
|
7
|
-
function
|
|
8
|
-
let e =
|
|
8
|
+
var c = n(null);
|
|
9
|
+
function l() {
|
|
10
|
+
let e = i(c);
|
|
9
11
|
if (!e) throw Error("useHealthyBowl must be used within a HealthyBowlProvider");
|
|
10
12
|
return e;
|
|
11
13
|
}
|
|
12
|
-
var
|
|
13
|
-
e({ googleMapsApiKey:
|
|
14
|
-
let
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
workspaceId: c,
|
|
19
|
-
apiGatewayUrl: l,
|
|
20
|
-
globalGatewayUrl: u,
|
|
21
|
-
authToken: d
|
|
22
|
-
}, m = /* @__PURE__ */ i(a.Provider, {
|
|
23
|
-
value: p,
|
|
24
|
-
children: t
|
|
14
|
+
var u = ({ children: n, basePath: i = "/", navigate: l = () => {}, currentUser: u, workspaceId: d = "", apiGatewayUrl: f = "", globalGatewayUrl: p = "", authToken: m = "", googleMapsApiKey: h, ttsEndpoint: g }) => {
|
|
15
|
+
e({ googleMapsApiKey: h });
|
|
16
|
+
let _ = a(m);
|
|
17
|
+
_.current = m, t({
|
|
18
|
+
ttsEndpoint: g,
|
|
19
|
+
getHeaders: r(() => _.current ? { authorization: `Bearer ${_.current}` } : {}, [])
|
|
25
20
|
});
|
|
26
|
-
|
|
21
|
+
let v = {
|
|
22
|
+
basePath: i,
|
|
23
|
+
navigate: l,
|
|
24
|
+
currentUser: u,
|
|
25
|
+
workspaceId: d,
|
|
26
|
+
apiGatewayUrl: f,
|
|
27
|
+
globalGatewayUrl: p,
|
|
28
|
+
authToken: m
|
|
29
|
+
}, y = /* @__PURE__ */ s(c.Provider, {
|
|
30
|
+
value: v,
|
|
31
|
+
children: n
|
|
32
|
+
});
|
|
33
|
+
return i && i !== "/" ? y : /* @__PURE__ */ s(o, { children: y });
|
|
27
34
|
};
|
|
28
35
|
//#endregion
|
|
29
|
-
export {
|
|
36
|
+
export { u as HealthyBowlProvider, l as useHealthyBowl };
|
|
30
37
|
|
|
31
38
|
//# sourceMappingURL=HealthyBowlContext.js.map
|
|
@@ -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, useContext, type FC, type PropsWithChildren } from 'react';\nimport { MemoryRouter } from 'react-router';\nimport type { HealthyBowlRootProps } from '../types';\nimport { configureGeocoder } from '../utils/geocode';\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}) => {\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 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"}
|
|
@@ -4,7 +4,11 @@ import { createHostedTtsEngine as t } from "./hostedTtsSpeechEngine.js";
|
|
|
4
4
|
import { createRoutingSpeechEngine as n } from "./routingSpeechEngine.js";
|
|
5
5
|
//#region src/services/speech/createSpeechEngine.ts
|
|
6
6
|
var r, i;
|
|
7
|
-
function a() {
|
|
7
|
+
function a(e) {
|
|
8
|
+
let t = e.ttsEndpoint?.trim() || void 0;
|
|
9
|
+
t === r && e.getHeaders === i || (r = t, i = e.getHeaders, u());
|
|
10
|
+
}
|
|
11
|
+
function o() {
|
|
8
12
|
if (r) return {
|
|
9
13
|
endpoint: r,
|
|
10
14
|
getHeaders: i
|
|
@@ -18,7 +22,7 @@ function a() {
|
|
|
18
22
|
}
|
|
19
23
|
return { endpoint: null };
|
|
20
24
|
}
|
|
21
|
-
function
|
|
25
|
+
function s(n = o()) {
|
|
22
26
|
return {
|
|
23
27
|
device: e,
|
|
24
28
|
hosted: n.endpoint ? t({
|
|
@@ -28,11 +32,14 @@ function o(n = a()) {
|
|
|
28
32
|
}) : null
|
|
29
33
|
};
|
|
30
34
|
}
|
|
31
|
-
var
|
|
32
|
-
function
|
|
33
|
-
return
|
|
35
|
+
var c = null;
|
|
36
|
+
function l() {
|
|
37
|
+
return c ||= n(s()), c;
|
|
38
|
+
}
|
|
39
|
+
function u() {
|
|
40
|
+
c = null;
|
|
34
41
|
}
|
|
35
42
|
//#endregion
|
|
36
|
-
export {
|
|
43
|
+
export { a as configureSpeechEngine, s as createSpeechEngines, l as getSpeechEngine, o as readSpeechEngineConfig, u as resetSpeechEngine };
|
|
37
44
|
|
|
38
45
|
//# sourceMappingURL=createSpeechEngine.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createSpeechEngine.js","names":[],"sources":["../../../src/services/speech/createSpeechEngine.ts"],"sourcesContent":["/**\n * Which engine speaks — the single switch for the hosted-TTS rollout\n * (BOFF-7111).\n *\n * **Default is unchanged behaviour.** With no endpoint configured this returns\n * the device engine that ships today, so merging this changes nothing for\n * anyone.\n *\n * ★The endpoint MUST be resolved at RUNTIME, not from `import.meta.env`. This\n * microfe is published as a prebuilt package by its own CI, which has no such\n * variable, so a build-time constant is inlined to `undefined` and the whole\n * hosted path is eliminated before the host app ever consumes it — the flag\n * could then never be turned on at all. Verified against the published\n * `2026.829.4` bundle: `geocode.js` ships with its `import.meta.env` fallback\n * gone entirely, leaving only the runtime lookups. `configureGeocoder` exists\n * for exactly this reason and this mirrors it.\n *\n * The fallback is per-language, not global: a hosted vendor that cannot speak\n * the reply's language is worse than the device voice, not better, so\n * `resolveEngine` is asked per playback rather than once at startup.\n */\n\nimport { browserSpeechEngine } from './browserSpeechEngine';\nimport { createHostedTtsEngine } from './hostedTtsSpeechEngine';\nimport { hostedSupportsLanguage } from './hostedVoiceCatalogue';\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
|
|
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 * `resolveEngine` is asked per playback rather than once at startup.\n */\n\nimport { browserSpeechEngine } from './browserSpeechEngine';\nimport { createHostedTtsEngine } from './hostedTtsSpeechEngine';\nimport { hostedSupportsLanguage } from './hostedVoiceCatalogue';\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 * Pick the engine for a specific language.\n *\n * Hosted wins when it is configured, usable on this platform, and actually\n * covers the language. Otherwise the device engine — which may itself have no\n * voice for the language, and the existing `voiceAvailability` / `speechGate`\n * logic explains that to the user exactly as it does today.\n */\nexport function resolveEngine(\n engines: { device: SpeechEngine; hosted: SpeechEngine | null },\n languageTag: string\n): SpeechEngine {\n const { device, hosted } = engines;\n if (!hosted) return device;\n if (!hosted.isSupported()) return device;\n // A hosted voice in the wrong language would be read with the wrong phoneme\n // model — the same \"confident nonsense\" the device path already refuses.\n if (!hostedSupportsLanguage(languageTag)) return device;\n return 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":";;;;;AAoCA,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;AAkCA,IAAI,IAA8B;AAElC,SAAgB,IAAgC;CAE9C,OADA,AAAa,MAAS,EAA0B,EAAoB,CAAC,GAC9D;AACT;AAGA,SAAgB,IAA0B;CACxC,IAAS;AACX"}
|
|
@@ -35,31 +35,33 @@ function s(s) {
|
|
|
35
35
|
}
|
|
36
36
|
return p;
|
|
37
37
|
}
|
|
38
|
-
function _(e, t) {
|
|
39
|
-
return new Promise((
|
|
38
|
+
function _(e, t, n) {
|
|
39
|
+
return new Promise((r, i) => {
|
|
40
40
|
if (t !== d) {
|
|
41
|
-
|
|
41
|
+
r();
|
|
42
42
|
return;
|
|
43
43
|
}
|
|
44
|
-
let
|
|
45
|
-
m(), u = URL.createObjectURL(
|
|
46
|
-
let
|
|
47
|
-
l =
|
|
48
|
-
t === d &&
|
|
49
|
-
},
|
|
44
|
+
let a = new Blob([e.slice().buffer], { type: "audio/mpeg" });
|
|
45
|
+
m(), u = URL.createObjectURL(a);
|
|
46
|
+
let o = new Audio(u);
|
|
47
|
+
l = o, o.onended = () => {
|
|
48
|
+
t === d && r();
|
|
49
|
+
}, o.onerror = () => {
|
|
50
50
|
if (t !== d) {
|
|
51
|
-
|
|
51
|
+
r();
|
|
52
52
|
return;
|
|
53
53
|
}
|
|
54
54
|
let e = /* @__PURE__ */ Error("audio playback failed");
|
|
55
|
-
e.reason = "unknown",
|
|
56
|
-
},
|
|
55
|
+
e.reason = "unknown", i(e);
|
|
56
|
+
}, o.play().then(() => {
|
|
57
|
+
t === d && n?.();
|
|
58
|
+
}, (e) => {
|
|
57
59
|
if (t !== d) {
|
|
58
|
-
|
|
60
|
+
r();
|
|
59
61
|
return;
|
|
60
62
|
}
|
|
61
|
-
let
|
|
62
|
-
|
|
63
|
+
let n = /* @__PURE__ */ Error("audio play rejected");
|
|
64
|
+
n.reason = e?.name === "NotAllowedError" ? "not-allowed" : "unknown", i(n);
|
|
63
65
|
});
|
|
64
66
|
});
|
|
65
67
|
}
|
|
@@ -85,19 +87,21 @@ function s(s) {
|
|
|
85
87
|
h();
|
|
86
88
|
let a = new AbortController();
|
|
87
89
|
f = a;
|
|
88
|
-
let s = (
|
|
90
|
+
let s = !1, c = () => {
|
|
91
|
+
s || (s = !0, n.onStart?.());
|
|
92
|
+
}, l = (e) => {
|
|
89
93
|
let n = g(e, t, a.signal);
|
|
90
94
|
return n.catch(() => {}), n;
|
|
91
95
|
};
|
|
92
96
|
(async () => {
|
|
93
97
|
try {
|
|
94
|
-
let e =
|
|
98
|
+
let e = l(r[0]);
|
|
95
99
|
for (let t = 0; t < r.length; t += 1) {
|
|
96
100
|
if (i !== d) return;
|
|
97
101
|
let n = await e;
|
|
98
102
|
if (i !== d) return;
|
|
99
103
|
let a = r[t + 1];
|
|
100
|
-
a !== void 0 && (e =
|
|
104
|
+
a !== void 0 && (e = l(a)), await _(n, i, c);
|
|
101
105
|
}
|
|
102
106
|
i === d && n.onEnd?.();
|
|
103
107
|
} catch (e) {
|
|
@@ -1 +1 @@
|
|
|
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 { buildRequest, classifyHttpFailure, decodeAudioResponse, splitForVendor } 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 function play(bytes: Uint8Array, batch: number): 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().catch((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 };\n err.reason = (cause as DOMException)?.name === 'NotAllowedError' ? 'not-allowed' : 'unknown';\n reject(err);\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 /**\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 await play(current, batch);\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 if (reason === 'not-allowed' || reason === 'unsupported') 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":";;;AAsCA,SAAgB,EAAsB,GAAyC;CAC7E,IAAM,IAAU,EAAQ,eAAe,GAAG,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I,IAAI,GAAG,IAAI,EAAU,QAAQ,KAAK,GAAG;MAC5C,IAAI,MAAU,GAAY;MAC1B,IAAM,IAAU,MAAM;MACtB,IAAI,MAAU,GAAY;MAC1B,IAAM,IAAO,EAAU,IAAI;MAI3B,AADI,MAAS,KAAA,MAAW,IAAU,EAAM,CAAI,IAC5C,MAAM,EAAK,GAAS,CAAK;KAC3B;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;KAM/C,CADI,MAAW,iBAAiB,MAAW,mBAAe,IAAW,KACrE,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
|
+
{"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 { buildRequest, classifyHttpFailure, decodeAudioResponse, splitForVendor } 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 };\n err.reason = (cause as DOMException)?.name === 'NotAllowedError' ? 'not-allowed' : 'unknown';\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 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 if (reason === 'not-allowed' || reason === 'unsupported') 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":";;;AAsCA,SAAgB,EAAsB,GAAyC;CAC7E,IAAM,IAAU,EAAQ,eAAe,GAAG,MAAmC,MAAM,GAAG,CAAI,IACtF,IAAiC,MACjC,IAA2B,MAS3B,IAAa,GAEb,IAAiC,MAOjC,IAAW,IAET,UAAmB;EACvB,AAEE,OADA,IAAI,gBAAgB,CAAS,GACjB;CAEhB,GAEM,UAAkB;EACtB,IAAI,GAAO;GAET,AADA,EAAM,UAAU,MAChB,EAAM,UAAU;GAChB,IAAI;IACF,EAAM,MAAM;GACd,QAAQ,CAER;GACA,IAAQ;EACV;EACA,EAAW;CACb;CAGA,eAAe,EAAW,GAAc,GAA0B,GAA0C;EAK1G,IAAM,IAAO,EA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AAI,MAAU,KAAY,EAAS,QAAQ;IAC7C,SAAS,GAAO;KAEd,IADA,EAAW,MAAM,GACb,MAAU,GAAY;KAE1B,AADA,KAAc,GACd,EAAU;KACV,IAAM,IAAU,GAA+B;KAM/C,CADI,MAAW,iBAAiB,MAAW,mBAAe,IAAW,KACrE,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"}
|
|
@@ -15,7 +15,24 @@ function t({ device: t, hosted: n }) {
|
|
|
15
15
|
return t.subscribeVoices(e);
|
|
16
16
|
},
|
|
17
17
|
speak(e, r, a) {
|
|
18
|
-
t.cancel(), n.cancel(), i(r)
|
|
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
|
+
onError: (n) => {
|
|
29
|
+
if (n === "cancelled" || o) {
|
|
30
|
+
a?.onError?.(n);
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
t.speak(e, r, a);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
19
36
|
},
|
|
20
37
|
cancel() {
|
|
21
38
|
t.cancel(), n.cancel();
|
|
@@ -1 +1 @@
|
|
|
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 pick(options).speak(chunks, options, handlers);\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;
|
|
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 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;IAC/B,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"}
|
package/package.json
CHANGED