@burdenoff/microfe-healthybowl 2026.831.2 → 2026.831.3
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 +53 -52
- package/dist/components/assistant/AssistantSpeechProvider.js.map +1 -1
- package/dist/config/speechLabels.js +66 -0
- package/dist/config/speechLabels.js.map +1 -0
- package/dist/utils/speakableText.js +7 -2
- package/dist/utils/speakableText.js.map +1 -1
- package/package.json +1 -1
|
@@ -3,17 +3,18 @@ import { useTr as t } from "../../shared/hooks/useTr.js";
|
|
|
3
3
|
import { getSpeechEngine as n } from "../../services/speech/createSpeechEngine.js";
|
|
4
4
|
import "../../services/speech/index.js";
|
|
5
5
|
import { chunkForSpeech as r, toSpeakableText as i } from "../../utils/speakableText.js";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
6
|
+
import { speechLabelsFor as a } from "../../config/speechLabels.js";
|
|
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";
|
|
8
|
+
import { resolveSpeechLocale as te } from "../../utils/replyLanguage.js";
|
|
9
|
+
import { findAssistantLanguage as f, resolveAssistantLanguage as ne } from "../../config/assistantLanguages.js";
|
|
10
|
+
import { IDLE_PLAYBACK as re, isSpeakingMessage as p, speechPlaybackReducer as ie } from "../../utils/speechPlayback.js";
|
|
11
|
+
import { isTurnInFlight as ae } from "../../utils/assistantTurnState.js";
|
|
12
|
+
import { parseToolActivity as oe } from "./AssistantToolActivity.js";
|
|
13
|
+
import { createContext as m, useCallback as h, useContext as g, useEffect as _, useMemo as v, useReducer as se, useRef as y, useState as b } from "react";
|
|
14
|
+
import { useI18n as ce } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
|
|
15
|
+
import { jsx as le } from "react/jsx-runtime";
|
|
15
16
|
//#region src/components/assistant/AssistantSpeechProvider.tsx
|
|
16
|
-
var
|
|
17
|
+
var ue = {
|
|
17
18
|
codeBlock: "",
|
|
18
19
|
image: "",
|
|
19
20
|
link: "",
|
|
@@ -43,9 +44,9 @@ function S() {
|
|
|
43
44
|
return g(x);
|
|
44
45
|
}
|
|
45
46
|
var C = ({ children: m, visible: g = !0, engine: S = n() }) => {
|
|
46
|
-
let C = t(), { locale: w } =
|
|
47
|
+
let C = t(), { 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(() => {
|
|
47
48
|
P.current?.(), P.current = null;
|
|
48
|
-
}, []), L = e((e) => e.autoSpeakEnabled), R = e((e) => e.setAutoSpeak),
|
|
49
|
+
}, []), L = e((e) => e.autoSpeakEnabled), R = e((e) => e.setAutoSpeak), de = e((e) => e.activeConversationId), z = v(() => S.isSupported(), [S]);
|
|
49
50
|
_(() => {
|
|
50
51
|
if (!z) return;
|
|
51
52
|
let e = () => {
|
|
@@ -53,7 +54,7 @@ var C = ({ children: m, visible: g = !0, engine: S = n() }) => {
|
|
|
53
54
|
};
|
|
54
55
|
return e(), S.subscribeVoices(e);
|
|
55
56
|
}, [S, z]);
|
|
56
|
-
let B = e((e) => e.assistantLanguage), V = e((e) => e.preferredVoices), H = e((e) => e.setPreferredVoice), U = v(() =>
|
|
57
|
+
let B = e((e) => e.assistantLanguage), V = e((e) => e.preferredVoices), H = e((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), [
|
|
57
58
|
z,
|
|
58
59
|
D,
|
|
59
60
|
U,
|
|
@@ -69,9 +70,9 @@ var C = ({ children: m, visible: g = !0, engine: S = n() }) => {
|
|
|
69
70
|
emailDot: C("healthybowl.assistant.speech.emailDot", "dot")
|
|
70
71
|
}), [C]), Y = h(() => {
|
|
71
72
|
I(), S.cancel(), E({ type: "stop" });
|
|
72
|
-
}, [I, S]), X = h((e) => j.get(e) ?? null, [j]),
|
|
73
|
+
}, [I, S]), X = h((e) => j.get(e) ?? null, [j]), fe = h((e, t, n) => {
|
|
73
74
|
I();
|
|
74
|
-
let r = !1, i = () => {},
|
|
75
|
+
let r = !1, i = () => {}, a = (a) => {
|
|
75
76
|
if (!r) {
|
|
76
77
|
if (r = !0, P.current = null, clearTimeout(s), i(), a.length === 0) {
|
|
77
78
|
A(!0);
|
|
@@ -79,24 +80,24 @@ var C = ({ children: m, visible: g = !0, engine: S = n() }) => {
|
|
|
79
80
|
}
|
|
80
81
|
O(a), F.current(e, t, a, n);
|
|
81
82
|
}
|
|
82
|
-
}, s = setTimeout(() =>
|
|
83
|
-
i = S.subscribeVoices(() =>
|
|
83
|
+
}, s = setTimeout(() => a(S.listVoices()), o);
|
|
84
|
+
i = S.subscribeVoices(() => a(S.listVoices())), P.current = () => {
|
|
84
85
|
r || (r = !0, clearTimeout(s), i(), P.current = null);
|
|
85
86
|
};
|
|
86
|
-
}, [I, S]),
|
|
87
|
+
}, [I, S]), Z = h((e, t, n, i) => {
|
|
87
88
|
let a = n;
|
|
88
89
|
if (a.length === 0) {
|
|
89
90
|
let e = S.listVoices();
|
|
90
91
|
e.length > 0 && (a = e, O(e));
|
|
91
92
|
}
|
|
92
|
-
let
|
|
93
|
-
if (
|
|
94
|
-
let t = C("healthybowl.assistant.speech.noVoiceForReply", "This reply is in {{language}}, and no {{language}} voice is installed on this device.", { language: o
|
|
93
|
+
let o = G(i), l = ee(u(!0, a, i, k));
|
|
94
|
+
if (l === "block") {
|
|
95
|
+
let t = C("healthybowl.assistant.speech.noVoiceForReply", "This reply is in {{language}}, and no {{language}} voice is installed on this device.", { language: s(o, w) });
|
|
95
96
|
M((n) => new Map(n).set(e, t));
|
|
96
97
|
return;
|
|
97
98
|
}
|
|
98
|
-
if (
|
|
99
|
-
|
|
99
|
+
if (l === "wait-for-voices") {
|
|
100
|
+
fe(e, t, i);
|
|
100
101
|
return;
|
|
101
102
|
}
|
|
102
103
|
M((t) => {
|
|
@@ -110,8 +111,8 @@ var C = ({ children: m, visible: g = !0, engine: S = n() }) => {
|
|
|
110
111
|
messageId: e,
|
|
111
112
|
requestId: d
|
|
112
113
|
}), S.speak(r(t), {
|
|
113
|
-
voice:
|
|
114
|
-
lang:
|
|
114
|
+
voice: c(a, o, V[i]),
|
|
115
|
+
lang: o,
|
|
115
116
|
rate: K(i)
|
|
116
117
|
}, {
|
|
117
118
|
onEnd: () => E({
|
|
@@ -131,37 +132,37 @@ var C = ({ children: m, visible: g = !0, engine: S = n() }) => {
|
|
|
131
132
|
G,
|
|
132
133
|
C,
|
|
133
134
|
k,
|
|
134
|
-
|
|
135
|
+
fe
|
|
135
136
|
]);
|
|
136
137
|
_(() => {
|
|
137
|
-
F.current =
|
|
138
|
-
}, [
|
|
139
|
-
let
|
|
138
|
+
F.current = Z;
|
|
139
|
+
}, [Z]);
|
|
140
|
+
let Q = h((e, t, n) => {
|
|
140
141
|
if (!z) return;
|
|
141
|
-
let r = i(t, { labels: J });
|
|
142
|
-
|
|
142
|
+
let r = te(i(t, { labels: ue }), n ?? W), o = i(t, { labels: a(r, J) });
|
|
143
|
+
o && Z(e, o, D, r);
|
|
143
144
|
}, [
|
|
144
145
|
z,
|
|
145
146
|
J,
|
|
146
147
|
W,
|
|
147
|
-
|
|
148
|
+
Z,
|
|
148
149
|
D
|
|
149
|
-
]),
|
|
150
|
+
]), pe = h((e, t, n) => {
|
|
150
151
|
if (p(T, e)) {
|
|
151
152
|
Y();
|
|
152
153
|
return;
|
|
153
154
|
}
|
|
154
|
-
|
|
155
|
+
Q(e, t, n);
|
|
155
156
|
}, [
|
|
156
157
|
T,
|
|
157
|
-
|
|
158
|
+
Q,
|
|
158
159
|
Y
|
|
159
160
|
]);
|
|
160
161
|
_(() => {
|
|
161
162
|
g || Y();
|
|
162
163
|
}, [g, Y]), _(() => {
|
|
163
164
|
Y(), M(/* @__PURE__ */ new Map());
|
|
164
|
-
}, [
|
|
165
|
+
}, [de, Y]), _(() => {
|
|
165
166
|
M((e) => e.size === 0 ? e : /* @__PURE__ */ new Map()), Y();
|
|
166
167
|
}, [W, Y]), _(() => () => {
|
|
167
168
|
P.current?.(), P.current = null, S.cancel();
|
|
@@ -184,45 +185,45 @@ var C = ({ children: m, visible: g = !0, engine: S = n() }) => {
|
|
|
184
185
|
S,
|
|
185
186
|
z
|
|
186
187
|
]);
|
|
187
|
-
let
|
|
188
|
+
let me = y(Q);
|
|
188
189
|
_(() => {
|
|
189
|
-
|
|
190
|
-
}, [
|
|
190
|
+
me.current = Q;
|
|
191
|
+
}, [Q]), _(() => {
|
|
191
192
|
if (!(!L || !g || !z)) return e.subscribe((e, t) => {
|
|
192
193
|
let n = e.activeConversationId;
|
|
193
194
|
if (!n || n !== t.activeConversationId) return;
|
|
194
195
|
let r = e.processingByConversationId[n], i = t.processingByConversationId[n];
|
|
195
|
-
if (r?.status !== "complete" || !
|
|
196
|
+
if (r?.status !== "complete" || !ae(i?.status)) return;
|
|
196
197
|
let a = r.messageId ?? i?.messageId ?? null;
|
|
197
198
|
if (!a) return;
|
|
198
199
|
let o = e.conversations.find((e) => e.id === n)?.messages.find((e) => e.id === a);
|
|
199
200
|
if (!o || o.role !== "assistant") return;
|
|
200
|
-
let { text: s } =
|
|
201
|
-
s.trim() &&
|
|
201
|
+
let { text: s } = oe(o.content);
|
|
202
|
+
s.trim() && me.current(a, s, o.metadata?.lang);
|
|
202
203
|
});
|
|
203
204
|
}, [
|
|
204
205
|
L,
|
|
205
206
|
z,
|
|
206
207
|
g
|
|
207
208
|
]);
|
|
208
|
-
let
|
|
209
|
+
let he = v(() => d(D, U.tag), [D, U]), $ = v(() => c(D, U.tag, V[W]), [
|
|
209
210
|
D,
|
|
210
211
|
U,
|
|
211
212
|
V,
|
|
212
213
|
W
|
|
213
|
-
]),
|
|
214
|
+
]), ge = v(() => ({
|
|
214
215
|
isSupported: z,
|
|
215
216
|
availability: q,
|
|
216
217
|
isBlocked: q === "no-voices",
|
|
217
218
|
disabledReason: q === "no-voices" ? C("healthybowl.assistant.speech.noVoicesOnDevice", "This device has no speech voices installed. Add one in your device speech or accessibility settings.") : null,
|
|
218
219
|
blockedFor: X,
|
|
219
|
-
voiceChoices:
|
|
220
|
-
activeVoiceName:
|
|
220
|
+
voiceChoices: he,
|
|
221
|
+
activeVoiceName: $?.name ?? null,
|
|
221
222
|
preferredVoiceName: V[W] ?? null,
|
|
222
223
|
setVoice: (e) => H(W, e),
|
|
223
224
|
speakingMessageId: T.status === "speaking" ? T.messageId : null,
|
|
224
225
|
isSpeaking: (e) => p(T, e),
|
|
225
|
-
toggle:
|
|
226
|
+
toggle: pe,
|
|
226
227
|
stop: Y,
|
|
227
228
|
autoSpeakEnabled: L,
|
|
228
229
|
setAutoSpeak: R
|
|
@@ -230,20 +231,20 @@ var C = ({ children: m, visible: g = !0, engine: S = n() }) => {
|
|
|
230
231
|
z,
|
|
231
232
|
q,
|
|
232
233
|
X,
|
|
233
|
-
|
|
234
|
-
|
|
234
|
+
he,
|
|
235
|
+
$,
|
|
235
236
|
V,
|
|
236
237
|
H,
|
|
237
238
|
W,
|
|
238
239
|
T,
|
|
239
|
-
|
|
240
|
+
pe,
|
|
240
241
|
Y,
|
|
241
242
|
L,
|
|
242
243
|
R,
|
|
243
244
|
C
|
|
244
245
|
]);
|
|
245
|
-
return /* @__PURE__ */
|
|
246
|
-
value:
|
|
246
|
+
return /* @__PURE__ */ le(x.Provider, {
|
|
247
|
+
value: ge,
|
|
247
248
|
children: m
|
|
248
249
|
});
|
|
249
250
|
};
|
|
@@ -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 { getSpeechEngine } from '../../services/speech';\nimport type { SpeechEngine, SpeechVoiceLike } from '../../services/speech';\nimport { chunkForSpeech, toSpeakableText, type SpeakableLabels } from '../../utils/speakableText';\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, resolveAssistantLanguage } from '../../config/assistantLanguages';\nimport { IDLE_PLAYBACK, isSpeakingMessage, speechPlaybackReducer } from '../../utils/speechPlayback';\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 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\nconst INERT_SPEECH: AssistantSpeechContextValue = {\n isSupported: false,\n availability: 'unsupported',\n isBlocked: true,\n disabledReason: null,\n blockedFor: () => null,\n voiceChoices: [],\n activeVoiceName: null,\n preferredVoiceName: null,\n setVoice: () => {},\n speakingMessageId: null,\n isSpeaking: () => false,\n toggle: () => {},\n stop: () => {},\n autoSpeakEnabled: false,\n setAutoSpeak: () => {},\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 /** 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 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 the user chose to converse in — not the interface language.\n // Completes the \"one selection drives three things\" promise: recogniser,\n // reply, and the voice that reads it (BOFF-7108).\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const preferredVoices = useAssistantStore((state) => state.preferredVoices);\n const setPreferredVoice = useAssistantStore((state) => state.setPreferredVoice);\n const spokenLanguage = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale),\n [assistantLanguage, 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 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 engine.speak(\n chunkForSpeech(text),\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 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 const text = toSpeakableText(markdown, { 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 speakWith(\n messageId,\n text,\n voices,\n // The turn's OWN language first — the preference is only a stand-in for\n // replies that predate it.\n resolveSpeechLocale(toSpeakableText(markdown, { labels: SILENT_LABELS }), turnLocale ?? spokenLocale)\n );\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 if (!autoSpeakEnabled || !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 // 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, 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 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 }),\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 tr,\n ]\n );\n\n return <AssistantSpeechContext.Provider value={value}>{children}</AssistantSpeechContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;;;;AAoDA,IAAM,KAAiC;CACrC,WAAW;CACX,OAAO;CACP,MAAM;CACN,YAAY;CACZ,WAAW;CACX,SAAS;CACT,UAAU;CACV,YAAY;AACd,GA6FM,IAAyB,EAA2C;CAjBxE,aAAa;CACb,cAAc;CACd,WAAW;CACX,gBAAgB;CAChB,kBAAkB;CAClB,cAAc,CAAC;CACf,iBAAiB;CACjB,oBAAoB;CACpB,gBAAgB,CAAC;CACjB,mBAAmB;CACnB,kBAAkB;CAClB,cAAc,CAAC;CACf,YAAY,CAAC;CACb,kBAAkB;CAClB,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,IAAa,EAAO,CAAC,GAErB,IAAa,EAA4B,IAAI,GAC7C,IAAe,QAEb,CAAC,CAAC,GAEJ,IAAgB,QAAkB;EAEtC,AADA,EAAW,UAAU,GACrB,EAAW,UAAU;CACvB,GAAG,CAAC,CAAC,GAEC,IAAmB,GAAmB,MAAU,EAAM,gBAAgB,GACtE,IAAe,GAAmB,MAAU,EAAM,YAAY,GAC9D,KAAuB,GAAmB,MAAU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IAAY,EAAQ,aAAa,GAAQ,aAAa;GAC5D,IAAI,CAAC,GAAW;GAEhB,IAAM,IAAU,EAAK,cAClB,MAAM,MAAiB,EAAa,OAAO,CAAc,GACxD,SAAS,MAAM,MAAc,EAAU,OAAO,CAAS;GAC3D,IAAI,CAAC,KAAW,EAAQ,SAAS,aAAa;GAG9C,IAAM,EAAE,YAAS,GAAkB,EAAQ,OAAO;GAC7C,EAAK,KAAK,KAEf,GAAS,QAAQ,GAAW,GAAO,EAAQ,UAA4C,IAAI;EAC7F,CAAC;CACH,GAAG;EAAC;EAAkB;EAAa;CAAO,CAAC;CAI3C,IAAM,KAAe,QAAc,EAAgB,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,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;CACF,IACA;EACE;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 { 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, resolveAssistantLanguage } from '../../config/assistantLanguages';\nimport { IDLE_PLAYBACK, isSpeakingMessage, speechPlaybackReducer } from '../../utils/speechPlayback';\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 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\nconst INERT_SPEECH: AssistantSpeechContextValue = {\n isSupported: false,\n availability: 'unsupported',\n isBlocked: true,\n disabledReason: null,\n blockedFor: () => null,\n voiceChoices: [],\n activeVoiceName: null,\n preferredVoiceName: null,\n setVoice: () => {},\n speakingMessageId: null,\n isSpeaking: () => false,\n toggle: () => {},\n stop: () => {},\n autoSpeakEnabled: false,\n setAutoSpeak: () => {},\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 /** 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 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 the user chose to converse in — not the interface language.\n // Completes the \"one selection drives three things\" promise: recogniser,\n // reply, and the voice that reads it (BOFF-7108).\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const preferredVoices = useAssistantStore((state) => state.preferredVoices);\n const setPreferredVoice = useAssistantStore((state) => state.setPreferredVoice);\n const spokenLanguage = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale),\n [assistantLanguage, 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 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 engine.speak(\n chunkForSpeech(text),\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 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 if (!autoSpeakEnabled || !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 // 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, 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 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 }),\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 tr,\n ]\n );\n\n return <AssistantSpeechContext.Provider value={value}>{children}</AssistantSpeechContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAqDA,IAAM,KAAiC;CACrC,WAAW;CACX,OAAO;CACP,MAAM;CACN,YAAY;CACZ,WAAW;CACX,SAAS;CACT,UAAU;CACV,YAAY;AACd,GA6FM,IAAyB,EAA2C;CAjBxE,aAAa;CACb,cAAc;CACd,WAAW;CACX,gBAAgB;CAChB,kBAAkB;CAClB,cAAc,CAAC;CACf,iBAAiB;CACjB,oBAAoB;CACpB,gBAAgB,CAAC;CACjB,mBAAmB;CACnB,kBAAkB;CAClB,cAAc,CAAC;CACf,YAAY,CAAC;CACb,kBAAkB;CAClB,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,IAAa,EAAO,CAAC,GAErB,IAAa,EAA4B,IAAI,GAC7C,IAAe,QAEb,CAAC,CAAC,GAEJ,IAAgB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AAA;AACnG"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
//#region src/config/speechLabels.ts
|
|
2
|
+
var e = {
|
|
3
|
+
ta: {
|
|
4
|
+
codeBlock: "நிரல் தொகுதி",
|
|
5
|
+
image: "படம்",
|
|
6
|
+
link: "இணைப்பு",
|
|
7
|
+
largeTable: "{{rows}} வரிசைகள் மற்றும் {{columns}} நெடுவரிசைகள் கொண்ட அட்டவணை",
|
|
8
|
+
truncated: "இந்தச் செய்தியின் மீதமுள்ள பகுதி வாசிக்கப்படவில்லை",
|
|
9
|
+
nestedItem: "துணை உருப்படி {{ordinal}}",
|
|
10
|
+
emailAt: "அட்",
|
|
11
|
+
emailDot: "புள்ளி"
|
|
12
|
+
},
|
|
13
|
+
hi: {
|
|
14
|
+
codeBlock: "कोड ब्लॉक",
|
|
15
|
+
image: "छवि",
|
|
16
|
+
link: "लिंक",
|
|
17
|
+
largeTable: "{{rows}} पंक्तियों और {{columns}} स्तंभों वाली तालिका",
|
|
18
|
+
truncated: "इस संदेश का शेष भाग नहीं पढ़ा जाता",
|
|
19
|
+
nestedItem: "उप-आइटम {{ordinal}}",
|
|
20
|
+
emailAt: "ऐट",
|
|
21
|
+
emailDot: "डॉट"
|
|
22
|
+
},
|
|
23
|
+
ar: {
|
|
24
|
+
codeBlock: "كتلة برمجية",
|
|
25
|
+
image: "صورة",
|
|
26
|
+
link: "رابط",
|
|
27
|
+
largeTable: "جدول من {{rows}} صفوف و {{columns}} أعمدة",
|
|
28
|
+
truncated: "لا تتم قراءة بقية هذه الرسالة بصوت عالٍ",
|
|
29
|
+
nestedItem: "عنصر فرعي {{ordinal}}",
|
|
30
|
+
emailAt: "أت",
|
|
31
|
+
emailDot: "نقطة"
|
|
32
|
+
},
|
|
33
|
+
es: {
|
|
34
|
+
codeBlock: "Bloque de código",
|
|
35
|
+
image: "imagen",
|
|
36
|
+
link: "enlace",
|
|
37
|
+
largeTable: "Tabla con {{rows}} filas y {{columns}} columnas",
|
|
38
|
+
truncated: "El resto de este mensaje no se lee en voz alta",
|
|
39
|
+
nestedItem: "Subelemento {{ordinal}}",
|
|
40
|
+
emailAt: "arroba",
|
|
41
|
+
emailDot: "punto"
|
|
42
|
+
},
|
|
43
|
+
zh: {
|
|
44
|
+
codeBlock: "代码块",
|
|
45
|
+
image: "图片",
|
|
46
|
+
link: "链接",
|
|
47
|
+
largeTable: "包含 {{rows}} 行 {{columns}} 列的表格",
|
|
48
|
+
truncated: "此消息的其余部分不会朗读",
|
|
49
|
+
nestedItem: "子项 {{ordinal}}",
|
|
50
|
+
emailAt: "at",
|
|
51
|
+
emailDot: "点"
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
function t(t, n) {
|
|
55
|
+
let r = t.trim().toLowerCase().split(/[-_]/)[0];
|
|
56
|
+
if (!r) return n;
|
|
57
|
+
let i = e[r];
|
|
58
|
+
return i ? {
|
|
59
|
+
...n,
|
|
60
|
+
...i
|
|
61
|
+
} : n;
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
export { t as speechLabelsFor };
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=speechLabels.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"speechLabels.js","names":[],"sources":["../../src/config/speechLabels.ts"],"sourcesContent":["import type { SpeakableLabels } from '../utils/speakableText';\n\n/**\n * The spoken stand-ins, in the language of the REPLY (BOFF-7120).\n *\n * When a reply contains something that cannot be read aloud — an image, a link,\n * a fenced code block, a wide table — the reader substitutes a word. Those words\n * used to come from `tr()`, which resolves against the INTERFACE language. So an\n * English interface reading a Tamil answer said \"Code block\" and \"image\" in\n * English, dropped into the middle of a Tamil sentence. Exactly the complaint\n * that produced the translatable `at`/`dot` for email addresses; that fix was\n * applied there and nowhere else.\n *\n * ★ Why a static table rather than `tr()` with a locale argument: the i18n\n * provider only ever FETCHES the active locale. `I18nContextValue.translations`\n * holds that one dictionary, so there is nothing to ask for Tamil while the\n * interface is English — the strings simply are not in the client. These eight\n * are short, stable, and needed synchronously mid-utterance, so they are carried\n * here instead.\n *\n * Anything not listed falls back to the interface-language label, which is what\n * happens today — so this can only improve on the current behaviour, never\n * regress it.\n */\ntype PartialLabels = Partial<SpeakableLabels>;\n\n/** Keyed by primary language subtag, since the reply locale may carry a region. */\nconst LABELS_BY_LANGUAGE: Record<string, PartialLabels> = {\n ta: {\n codeBlock: 'நிரல் தொகுதி',\n image: 'படம்',\n link: 'இணைப்பு',\n largeTable: '{{rows}} வரிசைகள் மற்றும் {{columns}} நெடுவரிசைகள் கொண்ட அட்டவணை',\n truncated: 'இந்தச் செய்தியின் மீதமுள்ள பகுதி வாசிக்கப்படவில்லை',\n nestedItem: 'துணை உருப்படி {{ordinal}}',\n emailAt: 'அட்',\n emailDot: 'புள்ளி',\n },\n hi: {\n codeBlock: 'कोड ब्लॉक',\n image: 'छवि',\n link: 'लिंक',\n largeTable: '{{rows}} पंक्तियों और {{columns}} स्तंभों वाली तालिका',\n truncated: 'इस संदेश का शेष भाग नहीं पढ़ा जाता',\n nestedItem: 'उप-आइटम {{ordinal}}',\n emailAt: 'ऐट',\n emailDot: 'डॉट',\n },\n ar: {\n codeBlock: 'كتلة برمجية',\n image: 'صورة',\n link: 'رابط',\n largeTable: 'جدول من {{rows}} صفوف و {{columns}} أعمدة',\n truncated: 'لا تتم قراءة بقية هذه الرسالة بصوت عالٍ',\n nestedItem: 'عنصر فرعي {{ordinal}}',\n emailAt: 'أت',\n emailDot: 'نقطة',\n },\n es: {\n codeBlock: 'Bloque de código',\n image: 'imagen',\n link: 'enlace',\n largeTable: 'Tabla con {{rows}} filas y {{columns}} columnas',\n truncated: 'El resto de este mensaje no se lee en voz alta',\n nestedItem: 'Subelemento {{ordinal}}',\n emailAt: 'arroba',\n emailDot: 'punto',\n },\n zh: {\n codeBlock: '代码块',\n image: '图片',\n link: '链接',\n largeTable: '包含 {{rows}} 行 {{columns}} 列的表格',\n truncated: '此消息的其余部分不会朗读',\n nestedItem: '子项 {{ordinal}}',\n emailAt: 'at',\n emailDot: '点',\n },\n};\n\n/**\n * Labels to read a reply in `locale` with.\n *\n * `uiLabels` is the interface-language set, used both as the base and as the\n * fallback for any language not carried here — so English replies, and any\n * language we have no table for, behave exactly as before.\n */\nexport function speechLabelsFor(locale: string, uiLabels: SpeakableLabels): SpeakableLabels {\n const primary = locale.trim().toLowerCase().split(/[-_]/)[0];\n if (!primary) return uiLabels;\n const overrides = LABELS_BY_LANGUAGE[primary];\n return overrides ? { ...uiLabels, ...overrides } : uiLabels;\n}\n\n/** Exposed for tests: which languages have their own spoken labels. */\nexport const SPOKEN_LABEL_LANGUAGES = Object.keys(LABELS_BY_LANGUAGE);\n"],"mappings":";AA2BA,IAAM,IAAoD;CACxD,IAAI;EACF,WAAW;EACX,OAAO;EACP,MAAM;EACN,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS;EACT,UAAU;CACZ;CACA,IAAI;EACF,WAAW;EACX,OAAO;EACP,MAAM;EACN,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS;EACT,UAAU;CACZ;CACA,IAAI;EACF,WAAW;EACX,OAAO;EACP,MAAM;EACN,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS;EACT,UAAU;CACZ;CACA,IAAI;EACF,WAAW;EACX,OAAO;EACP,MAAM;EACN,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS;EACT,UAAU;CACZ;CACA,IAAI;EACF,WAAW;EACX,OAAO;EACP,MAAM;EACN,YAAY;EACZ,WAAW;EACX,YAAY;EACZ,SAAS;EACT,UAAU;CACZ;AACF;AASA,SAAgB,EAAgB,GAAgB,GAA4C;CAC1F,IAAM,IAAU,EAAO,KAAK,EAAE,YAAY,EAAE,MAAM,MAAM,EAAE;CAC1D,IAAI,CAAC,GAAS,OAAO;CACrB,IAAM,IAAY,EAAmB;CACrC,OAAO,IAAY;EAAE,GAAG;EAAU,GAAG;CAAU,IAAI;AACrD"}
|
|
@@ -8,7 +8,7 @@ var e = {
|
|
|
8
8
|
nestedItem: "Sub-item {{ordinal}}",
|
|
9
9
|
emailAt: "at",
|
|
10
10
|
emailDot: "dot"
|
|
11
|
-
}, t = /^\s{0,3}(?:`{3,}|~{3,})/, n = /^\s{0,3}#{1,6}\s+(.*)$/, r = /^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/, i = /^\s{0,3}(?:>\s?)+/, a = /^(\s*)(?:[-*+]|(\d{1,9})[.)])\s+/, o = /^\[[ xX]\]\s*/, s = /[
|
|
11
|
+
}, t = /^\s{0,3}(?:`{3,}|~{3,})/, n = /^\s{0,3}#{1,6}\s+(.*)$/, r = /^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/, i = /^\s{0,3}(?:>\s?)+/, a = /^(\s*)(?:[-*+]|(\d{1,9})[.)])\s+/, o = /^\[[ xX]\]\s*/, s = /[.!?…⋯:;。!?;.।॥۔؟؛]$/, c = /^\s{0,3}=+\s*$/, l = /^(?: {4}|\t)/;
|
|
12
12
|
function u(e, t) {
|
|
13
13
|
return Object.entries(t).reduce((e, [t, n]) => e.replace(RegExp(`\\{\\{${t}\\}\\}`, "g"), String(n)), e);
|
|
14
14
|
}
|
|
@@ -176,7 +176,12 @@ var T = new Set([
|
|
|
176
176
|
".",
|
|
177
177
|
"。",
|
|
178
178
|
"…",
|
|
179
|
-
"⋯"
|
|
179
|
+
"⋯",
|
|
180
|
+
"।",
|
|
181
|
+
"॥",
|
|
182
|
+
"۔",
|
|
183
|
+
"؟",
|
|
184
|
+
"؛"
|
|
180
185
|
]), D = new Set([
|
|
181
186
|
"\"",
|
|
182
187
|
"'",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"speakableText.js","names":[],"sources":["../../src/utils/speakableText.ts"],"sourcesContent":["/**\n * Markdown → speakable plain text (BOFF-6290, assistant voice reply).\n *\n * An assistant reply is Markdown: headings, tables, fenced code, links, list\n * markers, the odd emoji. Handing that string straight to a speech engine reads\n * out \"asterisk asterisk yield asterisk asterisk\", spells URLs character by\n * character, and grinds through a forty-row table one pipe at a time. This\n * module flattens a reply into something a person would actually say.\n *\n * Design notes:\n *\n * - **Pure, and deliberately so.** This repo's vitest runs in the `node`\n * environment (no jsdom), so audio and DOM behaviour are not testable here.\n * The transformation is where the real logic lives, so it is isolated as a\n * pure function with no imports and covered directly by `speakableText.test.ts`.\n * - **Copy comes in through `labels`**, not `useTr`, so the function stays pure\n * and the spoken placeholders still follow the app locale (the hook passes\n * translated strings in). `{{rows}}` / `{{columns}}` interpolate the same way\n * `useTr` params do.\n * - **No lookbehind assertions.** Safari < 16.4 throws at *parse* time on a\n * lookbehind, which would take down the whole module — the same trap the\n * old hand-rolled markdown renderer fell into (see AssistantMarkdownRenderer).\n * Every rule below uses a captured prefix or a lookahead instead.\n */\n\nexport interface SpeakableLabels {\n /** Spoken in place of a fenced code block, which is unlistenable read out. */\n codeBlock: string;\n /** Spoken for an image with no alt text. */\n image: string;\n /** Spoken in place of a URL — nobody wants \"h t t p s colon slash slash\". */\n link: string;\n /** Spoken in place of a table too large to read. Params: rows, columns. */\n largeTable: string;\n /** Appended when a very long reply is cut short. */\n truncated: string;\n /** Spoken for `@` in an address. English \"at\" inside a Tamil reply is jarring. */\n emailAt: string;\n /** Spoken for `.` in an address. */\n emailDot: string;\n /**\n * Prefix for a numbered item nested under an UNnumbered one. Param: ordinal.\n *\n * Nested ordered items normally read as a dotted path (\"2.1.\") which already\n * says where the sub-steps are; that is impossible when the parent is a\n * bullet and has no number of its own, so the level is named instead.\n */\n nestedItem: string;\n}\n\n/**\n * Sentence punctuation is deliberately absent: block-level labels get a full\n * stop from `asSentence`, and the inline ones (\"link\", \"image\") have to read\n * naturally mid-sentence — \"see link for details\", not \"see Link. for details\".\n */\nexport const DEFAULT_SPEAKABLE_LABELS: SpeakableLabels = {\n codeBlock: 'Code block',\n image: 'image',\n link: 'link',\n largeTable: 'Table with {{rows}} rows and {{columns}} columns',\n truncated: 'The rest of this message is not read aloud',\n nestedItem: 'Sub-item {{ordinal}}',\n emailAt: 'at',\n emailDot: 'dot',\n};\n\n/**\n * Tables at or below this many body rows are flattened into \"header: value\"\n * sentences, because a 2×3 table is usually THE answer. Anything larger is\n * summarised — the point of the limit is that a long table is unlistenable, not\n * that tables are unimportant.\n */\nexport const MAX_SPOKEN_TABLE_ROWS = 3;\n\n/** Roughly ten minutes of speech. Past this the reply is summarised as cut off. */\nexport const MAX_SPEAKABLE_CHARS = 8_000;\n\n/**\n * Utterances are split at about this length before being queued.\n *\n * Chrome (and Edge) silently stop a single `SpeechSynthesisUtterance` after\n * roughly fifteen seconds — a long-standing engine bug, not something we can\n * feature-detect. Queueing sentence-sized utterances keeps every one of them\n * well under that ceiling, so a long reply finishes instead of dying mid-word.\n */\nexport const SPEECH_CHUNK_CHARS = 180;\n\n/**\n * Chunk ceiling for Chinese and Japanese, in CHARACTERS.\n *\n * The limit above is sized for Latin text, where ~180 characters is ~30 words\n * and lands around ten seconds. A CJK character is a whole syllable — a zh voice\n * reads roughly 4–6 of them a second — so 180 of them is a minute of speech,\n * four times past the very cut-off the chunking exists to dodge. 40 characters\n * is ~7–10 seconds, the same target the Latin limit is aiming at.\n */\nexport const SPEECH_CHUNK_CJK_CHARS = 40;\n\nexport interface SpeakableOptions {\n labels?: Partial<SpeakableLabels>;\n maxChars?: number;\n maxSpokenTableRows?: number;\n}\n\nconst FENCE_RE = /^\\s{0,3}(?:`{3,}|~{3,})/;\nconst HEADING_RE = /^\\s{0,3}#{1,6}\\s+(.*)$/;\nconst HORIZONTAL_RULE_RE = /^\\s{0,3}([-*_])(?:\\s*\\1){2,}\\s*$/;\nconst BLOCKQUOTE_RE = /^\\s{0,3}(?:>\\s?)+/;\n/** Group 1 = indentation (nesting depth), group 2 = the ordinal, if numbered. */\nconst LIST_MARKER_RE = /^(\\s*)(?:[-*+]|(\\d{1,9})[.)])\\s+/;\nconst TASK_MARKER_RE = /^\\[[ xX]\\]\\s*/;\nconst SENTENCE_END_RE = /[.!?…⋯:;。!?;.]$/;\n/** A `=====` line under a paragraph: a setext heading, never prose. */\nconst SETEXT_UNDERLINE_RE = /^\\s{0,3}=+\\s*$/;\n/** Four spaces or a tab: an indented code block, which is not worth reading. */\nconst INDENTED_CODE_RE = /^(?: {4}|\\t)/;\n\nfunction interpolate(template: string, params: Record<string, string | number>): string {\n return Object.entries(params).reduce(\n (out, [key, value]) => out.replace(new RegExp(`\\\\{\\\\{${key}\\\\}\\\\}`, 'g'), String(value)),\n template\n );\n}\n\n/** A `|`-only rule row (`|---|:--:|`) — what makes the line above it a header. */\nfunction isTableDelimiter(line: string): boolean {\n const trimmed = line.trim();\n return trimmed.includes('|') && trimmed.includes('-') && /^[\\s:|-]+$/.test(trimmed);\n}\n\n/**\n * Split a GFM table row into cells, honouring `\\|` escapes.\n *\n * Written as a scan rather than `split(/(?<!\\\\)\\|/)` on purpose — see the\n * no-lookbehind note at the top of the file.\n */\nexport function splitTableRow(line: string): string[] {\n const trimmed = line.trim().replace(/^\\|/, '').replace(/\\|$/, '');\n const cells: string[] = [];\n let current = '';\n\n for (let index = 0; index < trimmed.length; index += 1) {\n const char = trimmed[index];\n if (char === '\\\\' && trimmed[index + 1] === '|') {\n current += '|';\n index += 1;\n continue;\n }\n if (char === '|') {\n cells.push(current);\n current = '';\n continue;\n }\n current += char;\n }\n cells.push(current);\n\n return cells.map((cell) => cell.trim());\n}\n\nconst ENTITIES: Record<string, string> = {\n '&': ' and ',\n '<': ' less than ',\n '>': ' greater than ',\n '"': '\"',\n ''': \"'\",\n ''': \"'\",\n ' ': ' ',\n};\n\nconst EMAIL_BODY = '[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\\\\.[A-Za-z0-9-]+)+';\n/** `<support@x.com>`, the autolink form — and what the HTML strip used to eat. */\nconst AUTOLINK_EMAIL_RE = new RegExp(`<(?:mailto:)?(${EMAIL_BODY})>`, 'g');\nconst MAILTO_RE = new RegExp(`\\\\bmailto:(${EMAIL_BODY})`, 'g');\nconst BARE_EMAIL_RE = new RegExp(EMAIL_BODY, 'g');\n\n/**\n * Say an address the way a person reads one out.\n *\n * \"support at healthybowl dot com\" — an engine handed the raw string either\n * spells it or swallows the punctuation, and expanding the dots here also keeps\n * the sentence splitter from mistaking `.com` for the end of a sentence.\n */\nexport function speakableEmail(address: string, at = 'at', dot = 'dot'): string {\n return address.replace(/@/g, ` ${at} `).replace(/\\./g, ` ${dot} `).replace(/\\s+/g, ' ').trim();\n}\n\n/**\n * Flatten the inline span syntax of one line: emphasis, code, links, images,\n * raw HTML, entities and pictographs.\n */\nfunction flattenInline(input: string, labels: SpeakableLabels): string {\n let text = input;\n\n // Images first: `` also matches the link pattern below.\n text = text.replace(/!\\[([^\\]]*)\\]\\([^)]*\\)/g, (_match, alt: string) => alt.trim() || ` ${labels.image} `);\n\n // Inline links: keep the human-readable text, drop the URL entirely.\n text = text.replace(/\\[([^\\]]*)\\]\\([^)]*\\)/g, (_match, label: string) => label.trim() || ` ${labels.link} `);\n // Reference links (`[text][ref]`, `[text][]`).\n text = text.replace(/\\[([^\\]]*)\\]\\[[^\\]]*\\]/g, (_match, label: string) => label.trim() || ` ${labels.link} `);\n\n // Autolinks and bare URLs.\n text = text.replace(/<https?:\\/\\/[^>\\s]+>/g, ` ${labels.link} `);\n text = text.replace(/\\bhttps?:\\/\\/\\S+/g, ` ${labels.link} `);\n\n // Email addresses, BEFORE the HTML strip below: `<support@x.com>` looks like a\n // tag to that rule, and deleting it turns \"Contact <support@x.com>.\" into\n // \"Contact.\" — the one piece of information in the sentence, silently gone.\n // Addresses run after URLs so that `https://user@host/x` is already a \"link\".\n text = text.replace(\n AUTOLINK_EMAIL_RE,\n (_match, address: string) => ` ${speakableEmail(address, labels.emailAt, labels.emailDot)} `\n );\n text = text.replace(\n MAILTO_RE,\n (_match, address: string) => ` ${speakableEmail(address, labels.emailAt, labels.emailDot)} `\n );\n text = text.replace(BARE_EMAIL_RE, (match: string) => ` ${speakableEmail(match, labels.emailAt, labels.emailDot)} `);\n\n // Inline code — the backticks go, the identifier inside is usually the point.\n text = text.replace(/`+([^`]*)`+/g, (_match, code: string) => code);\n\n // Raw HTML. The renderer escapes rather than renders it, so the user SEES the\n // tag; either way \"less than b greater than\" is not worth saying.\n text = text.replace(/<\\/?[a-zA-Z][^>]*>/g, ' ');\n\n for (const [entity, replacement] of Object.entries(ENTITIES)) {\n text = text.split(entity).join(replacement);\n }\n\n // Emphasis. `***x***` / `**x**` before `*x*` so the longer fence wins.\n text = text.replace(/(\\*\\*\\*|___)(\\S(?:[\\s\\S]*?\\S)?)\\1/g, '$2');\n text = text.replace(/(\\*\\*|__)(\\S(?:[\\s\\S]*?\\S)?)\\1/g, '$2');\n text = text.replace(/~~(\\S(?:[\\s\\S]*?\\S)?)~~/g, '$1');\n // Single-character emphasis is boundary-anchored: without it `crop_yield_total`\n // becomes \"cropyieldtotal\" and `2 * 3 * 4` loses its operators.\n text = text.replace(/(^|[\\s([{\"'])\\*(\\S(?:[\\s\\S]*?\\S)?)\\*(?=$|[\\s)\\]}\"'.,!?;:])/g, '$1$2');\n text = text.replace(/(^|[\\s([{\"'])_(\\S(?:[\\s\\S]*?\\S)?)_(?=$|[\\s)\\]}\"'.,!?;:])/g, '$1$2');\n\n // Pictographs: some voices announce every emoji by name (\"seedling\", \"sun\n // with face\"), which is noise in the middle of an agronomy answer. The two\n // escapes are the variation selector and the zero-width joiner that glue\n // multi-codepoint emoji together.\n text = text.replace(/[\\p{Extended_Pictographic}\\uFE0F\\u200D]/gu, ' ');\n\n // …and the decorative symbols that are NOT Extended_Pictographic, which is\n // why they survived and were read aloud. A reply mixing ✅ and ✓ had one\n // stripped and the other announced. Deliberately an explicit list rather than\n // a Unicode category: `\\p{Po}` would take `.` `,` `?` with it, and `\\p{So}`\n // would take `°`, which engines pronounce correctly and users want.\n text = text.replace(/[•·▪▫◦‣⁃∙●○■□▶▸►➤➜→←↑↓⇒⇔★☆⭐✦✧✓✔✗✘✕✖]/gu, ' ');\n\n // Em/en dashes are read as the word \"dash\" by some engines. As punctuation\n // they mean a pause, so give the engine one it understands.\n //\n // NOT between two numbers: there the dash is a RANGE, and a comma splits one\n // value into two. \"Apply 3–5 kg per hectare\" read as \"apply three, five\n // kilograms per hectare\" is a dosage a farmer could act on wrongly, so a\n // digit on both sides is left exactly as it was.\n //\n // Written with capture groups rather than a lookbehind: lookbehind only\n // reached Safari in 16.4, and iOS WebKit is the primary device here.\n text = text.replace(/(\\d)?\\s*[—–―]\\s*(\\d)?/g, (match, before, after) =>\n before !== undefined && after !== undefined ? match : `${before ?? ''}, ${after ?? ''}`\n );\n\n // Residual emphasis markers. The fences above require non-whitespace inside\n // them, so unbalanced or word-internal markup leaks: `**N**-**P**-**K**`\n // survives as `N**-P-**K` and is spoken \"N star star P\". Only runs of two or\n // more are removed — a lone `*` is left alone so `2 * 3` keeps its operator.\n text = text.replace(/\\*{2,}/g, '');\n\n return (\n text\n .replace(/\\s+/g, ' ')\n // Removing a span leaves a gap in front of the punctuation that followed\n // it (\"Docs at link .\"). Harmless to read, but it also breaks the\n // sentence-boundary detection that `chunkForSpeech` relies on.\n .replace(/\\s+([.,!?;:)\\]}])/g, '$1')\n .replace(/([([{])\\s+/g, '$1')\n .trim()\n );\n}\n\n/** Give the engine somewhere to breathe between headings, list items and rows. */\nfunction asSentence(text: string): string {\n const trimmed = text.trim();\n if (!trimmed) return '';\n return SENTENCE_END_RE.test(trimmed) ? trimmed : `${trimmed}.`;\n}\n\nfunction truncateSpeakable(text: string, maxChars: number, notice: string): string {\n if (text.length <= maxChars) return text;\n\n const head = text.slice(0, maxChars);\n const sentenceEnd = Math.max(head.lastIndexOf('. '), head.lastIndexOf('\\n'));\n const wordEnd = head.lastIndexOf(' ');\n const cut = sentenceEnd > maxChars * 0.5 ? sentenceEnd + 1 : wordEnd > 0 ? wordEnd : maxChars;\n\n return `${head.slice(0, cut).trim()}\\n${notice}`;\n}\n\n/** Leading whitespace as a column count, so a tab nests like four spaces do. */\nfunction indentWidth(indent: string): number {\n let width = 0;\n for (const char of indent) width += char === '\\t' ? 4 : 1;\n return width;\n}\n\n/** One entry per open list level; `ordinal` is null for a bullet. */\ninterface ListLevel {\n indent: number;\n ordinal: string | null;\n}\n\n/**\n * What to say in front of a list item so the listener can hear the nesting.\n *\n * A depth-2 \"1.\" read as \"one\" is indistinguishable from the depth-1 \"1.\" that\n * preceded it, which is exactly how a listener loses track of where the\n * sub-steps started. Nested numbers therefore read as their full path — \"2.1.\"\n * — and a number nested under a BULLET, which has no path, is named instead.\n */\nfunction spokenOrdinal(stack: readonly ListLevel[], labels: SpeakableLabels): string {\n const self = stack[stack.length - 1];\n if (!self?.ordinal) return '';\n if (stack.length === 1) return `${self.ordinal}. `;\n\n const path = stack.map((level) => level.ordinal);\n if (path.every((ordinal): ordinal is string => Boolean(ordinal))) return `${path.join('.')}. `;\n return `${interpolate(labels.nestedItem, { ordinal: self.ordinal })}. `;\n}\n\n/**\n * Convert an assistant reply (Markdown) into plain text worth speaking.\n *\n * Returns `''` when there is nothing speakable — the caller should treat that\n * as \"no speak control\", not as an error.\n */\nexport function toSpeakableText(markdown: string, options: SpeakableOptions = {}): string {\n const labels = { ...DEFAULT_SPEAKABLE_LABELS, ...options.labels };\n const maxChars = options.maxChars ?? MAX_SPEAKABLE_CHARS;\n const maxTableRows = options.maxSpokenTableRows ?? MAX_SPOKEN_TABLE_ROWS;\n\n if (!markdown) return '';\n\n const lines = markdown.replace(/\\r\\n?/g, '\\n').split('\\n');\n const spoken: string[] = [];\n const listStack: ListLevel[] = [];\n let index = 0;\n\n while (index < lines.length) {\n const raw = lines[index];\n const line = raw.replace(BLOCKQUOTE_RE, '');\n // Positional, so it stays correct across every branch below: an indented\n // code block can only start after a blank line (it cannot interrupt a\n // paragraph), and the start of the reply counts as one.\n const previousBlank = index === 0 || !lines[index - 1].replace(BLOCKQUOTE_RE, '').trim();\n\n // ── Fenced code: announce it, skip to the closing fence ──────────────\n if (FENCE_RE.test(line)) {\n index += 1;\n while (index < lines.length && !FENCE_RE.test(lines[index].replace(BLOCKQUOTE_RE, ''))) index += 1;\n index += 1; // consume the closing fence (or fall off the end, unclosed)\n spoken.push(asSentence(labels.codeBlock));\n continue;\n }\n\n // ── Indented code: the OTHER way Markdown writes a code block ────────\n // Announced exactly like a fenced one; read verbatim it is \"SELECT star\n // FROM crops WHERE p h less than…\". Not applied inside a list, where four\n // spaces mean a continuation line rather than code.\n if (previousBlank && listStack.length === 0 && line.trim() && INDENTED_CODE_RE.test(line)) {\n index += 1;\n while (index < lines.length) {\n const candidate = lines[index].replace(BLOCKQUOTE_RE, '');\n if (candidate.trim() && INDENTED_CODE_RE.test(candidate)) {\n index += 1;\n continue;\n }\n if (candidate.trim()) break;\n // A blank line only ends the block if no indented line follows it.\n let peek = index;\n while (peek < lines.length && !lines[peek].replace(BLOCKQUOTE_RE, '').trim()) peek += 1;\n const resumed = peek < lines.length ? lines[peek].replace(BLOCKQUOTE_RE, '') : '';\n if (!resumed.trim() || !INDENTED_CODE_RE.test(resumed)) break;\n index = peek;\n }\n spoken.push(asSentence(labels.codeBlock));\n continue;\n }\n\n if (HORIZONTAL_RULE_RE.test(line)) {\n index += 1;\n continue;\n }\n\n // A stray `=====` carries no meaning of its own; without this it is read\n // out as prose (the setext case below consumes the ones that have a title).\n if (SETEXT_UNDERLINE_RE.test(line)) {\n index += 1;\n continue;\n }\n\n // ── GFM table: header row followed by a `|---|` rule ─────────────────\n const next = index + 1 < lines.length ? lines[index + 1].replace(BLOCKQUOTE_RE, '') : '';\n if (line.includes('|') && isTableDelimiter(next)) {\n listStack.length = 0;\n const headers = splitTableRow(line).map((cell) => flattenInline(cell, labels));\n index += 2;\n\n const rows: string[][] = [];\n while (index < lines.length) {\n const rowLine = lines[index].replace(BLOCKQUOTE_RE, '');\n if (!rowLine.includes('|') || !rowLine.trim()) break;\n rows.push(splitTableRow(rowLine).map((cell) => flattenInline(cell, labels)));\n index += 1;\n }\n\n if (rows.length > maxTableRows) {\n spoken.push(asSentence(interpolate(labels.largeTable, { rows: rows.length, columns: headers.length })));\n } else {\n for (const row of rows) {\n const pairs = row\n .map((cell, column) => {\n if (!cell) return '';\n const header = headers[column];\n return header ? `${header}: ${cell}` : cell;\n })\n .filter(Boolean);\n if (pairs.length) spoken.push(asSentence(pairs.join(', ')));\n }\n }\n continue;\n }\n\n index += 1;\n\n // A blank line does NOT close a list: loose lists have one between items.\n if (!line.trim()) continue;\n\n const heading = HEADING_RE.exec(line);\n if (heading) {\n listStack.length = 0;\n // `## Title ##` — ATX closing hashes are decoration, not content.\n const text = flattenInline(heading[1].replace(/\\s+#+\\s*$/, ''), labels);\n if (text) spoken.push(asSentence(text));\n continue;\n }\n\n // ── List item: drop bullets, keep ordinals (they carry step order) ───\n const marker = LIST_MARKER_RE.exec(line);\n let body = line;\n let ordinal = '';\n if (marker) {\n body = line.slice(marker[0].length).replace(TASK_MARKER_RE, '');\n\n const depth = indentWidth(marker[1]);\n while (listStack.length > 0 && listStack[listStack.length - 1].indent >= depth) listStack.pop();\n listStack.push({ indent: depth, ordinal: marker[2] ?? null });\n ordinal = spokenOrdinal(listStack, labels);\n } else if (!/^\\s/.test(line)) {\n // Un-indented prose ends the list; an indented line continues an item.\n listStack.length = 0;\n }\n\n // ── Setext heading: `Title` over `=====` ─────────────────────────────\n if (!marker && SETEXT_UNDERLINE_RE.test(next)) {\n listStack.length = 0;\n index += 1; // the underline is decoration\n const text = flattenInline(line, labels);\n if (text) spoken.push(asSentence(text));\n continue;\n }\n\n const text = flattenInline(body, labels);\n if (text) spoken.push(asSentence(`${ordinal}${text}`));\n }\n\n const result = spoken\n .join('\\n')\n .replace(/\\n{2,}/g, '\\n')\n .trim();\n return truncateSpeakable(result, maxChars, asSentence(labels.truncated));\n}\n\n/* ── Sentence boundaries ───────────────────────────────────────────────────\n *\n * The naive rule (\"a run of . ! ? ends a sentence\") is wrong for exactly the\n * content this product exists to talk about. `12.5 kg/ha`, `pH 6.5`, `N-P-K\n * 10.10.10`, `$18.75`, `2026.07.01` and `i.e.` all contain a period that ends\n * nothing, and splitting there does not merely add a pause: each chunk is a\n * SEPARATE utterance, so \"8.4 kg\" comes out as \"eight.\" … \"four kilograms\".\n *\n * So a period is a boundary only when it is followed by whitespace (or the end\n * of the line) AND the token in front of it is not an abbreviation, an initial\n * or a list ordinal. `!` and `?` take the whitespace rule but skip the rest.\n *\n * CJK terminators are unconditional: those scripts do not put a space after\n * `。`, so the whitespace rule would never fire and a whole Chinese or Japanese\n * reply would arrive here as one \"sentence\".\n */\n\nconst ASCII_TERMINATORS = new Set(['.', '!', '?']);\n/** `。!?;.。` and the ellipses — a boundary wherever they appear. */\nconst CJK_TERMINATORS = new Set(['。', '!', '?', ';', '.', '。', '…', '⋯']);\n/** Punctuation that may trail a terminator and still belong to the sentence. */\nconst SENTENCE_CLOSERS = new Set(['\"', \"'\", ')', ']', '}', '»', '”', '’', '〉', '》', '」', '』', '】', ')']);\n\n/**\n * Tokens that take a period without ending a sentence. Stored WITHOUT the final\n * dot, lower-cased. Single letters (\"J. Smith\", the `i` of `i.e.`) are covered\n * by a rule rather than listed.\n */\nconst ABBREVIATIONS = new Set([\n 'i.e',\n 'e.g',\n 'etc',\n 'approx',\n 'vs',\n 'cf',\n 'viz',\n 'al',\n 'est',\n 'dept',\n 'fig',\n 'figs',\n 'ref',\n 'min',\n 'max',\n 'avg',\n 'qty',\n 'temp',\n 'mr',\n 'mrs',\n 'ms',\n 'dr',\n 'prof',\n 'sr',\n 'jr',\n 'st',\n 'inc',\n 'ltd',\n 'co',\n 'corp',\n 'univ',\n 'ca',\n // Units. An agronomy reply is full of them, and \"12 kg. of lime\" is one\n // sentence however the model punctuated it.\n 'kg',\n 'mg',\n 'gm',\n 'ha',\n 'cm',\n 'mm',\n 'km',\n 'ml',\n 'lb',\n 'oz',\n 'sq',\n 'hrs',\n 'wk',\n 'yr',\n 'mo',\n 'vol',\n 'pp',\n]);\n\n/** Abbreviations that only hold when a number follows: \"No. 4\", not \"the answer is no.\" */\nconst NUMBER_ABBREVIATIONS = new Set(['no', 'nos', 'p', 'ch', 'sec', 'art']);\n\nconst DIGITS_ONLY_RE = /^\\d+(?:\\.\\d+)*$/;\nconst SINGLE_LETTER_RE = /^[A-Za-z]$/;\n\nfunction isSentenceBoundary(line: string, termStart: number, end: number): boolean {\n // Any CJK terminator in the run settles it — those scripts have no space rule.\n for (let cursor = termStart; cursor < end; cursor += 1) {\n if (CJK_TERMINATORS.has(line[cursor])) return true;\n }\n\n // `12.5`, `10.10.10`, `report.pdf`, `hb.example`: a period glued to what\n // follows it is part of a token, never the end of a sentence.\n if (end < line.length && !/\\s/.test(line[end])) return false;\n if (line[termStart] !== '.') return true;\n\n const before = line.slice(0, termStart);\n const token = /(\\S+)$/.exec(before)?.[1] ?? '';\n if (!token) return true;\n\n // A list ordinal at the head of the line (\"1.\" / \"2.1.\") is a marker, not a\n // sentence: splitting there queues the number as its own utterance.\n if (DIGITS_ONLY_RE.test(token) && !before.slice(0, before.length - token.length).trim()) return false;\n\n const lower = token.toLowerCase();\n if (SINGLE_LETTER_RE.test(token)) return false;\n if (ABBREVIATIONS.has(lower)) return false;\n if (NUMBER_ABBREVIATIONS.has(lower)) return !/^\\s*\\d/.test(line.slice(end));\n\n return true;\n}\n\n/** Break one line into sentence-ish units. */\nfunction splitSentences(text: string): string[] {\n const out: string[] = [];\n\n for (const line of text.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n let start = 0;\n let cursor = 0;\n\n while (cursor < trimmed.length) {\n const char = trimmed[cursor];\n if (!ASCII_TERMINATORS.has(char) && !CJK_TERMINATORS.has(char)) {\n cursor += 1;\n continue;\n }\n\n let end = cursor;\n while (end < trimmed.length && (ASCII_TERMINATORS.has(trimmed[end]) || CJK_TERMINATORS.has(trimmed[end]))) {\n end += 1;\n }\n while (end < trimmed.length && SENTENCE_CLOSERS.has(trimmed[end])) end += 1;\n\n if (isSentenceBoundary(trimmed, cursor, end)) {\n const piece = trimmed.slice(start, end).trim();\n if (piece) out.push(piece);\n start = end;\n }\n cursor = end;\n }\n\n const tail = trimmed.slice(start).trim();\n if (tail) out.push(tail);\n }\n\n return out;\n}\n\n/* ── CJK ──────────────────────────────────────────────────────────────────\n *\n * Chinese and Japanese are two of the six shipped locales and neither uses\n * spaces, so whitespace-based packing degenerates to a blind character slice\n * that lands mid-number and mid-clause. They also carry far more speech per\n * character than Latin text does — see SPEECH_CHUNK_CJK_CHARS.\n */\n\n/** Kana, CJK ideographs (incl. extension A and compatibility) and halfwidth kana. */\nconst CJK_CHAR_RE = /[\\u3040-\\u30ff\\u3400-\\u4dbf\\u4e00-\\u9fff\\uf900-\\ufaff\\uff66-\\uff9f]/;\n/** The above plus CJK and fullwidth punctuation: characters that need no space beside them. */\nconst CJK_ADJACENT_RE = /[\\u3000-\\u303f\\u3040-\\u30ff\\u3400-\\u4dbf\\u4e00-\\u9fff\\uf900-\\ufaff\\uff01-\\uff9f]/;\n/** Mid-sentence pause marks: the natural place to end a chunk. */\nconst CJK_PAUSE_RE = /[、,,;;::。!?!?]/;\n/**\n * One indivisible unit: a Latin/numeric token (so `12.5`, `10.10.10` and `kg/ha`\n * are never cut in half) or a single character.\n */\nconst CJK_ATOM_RE = /[A-Za-z0-9][A-Za-z0-9._,:%/+-]*[A-Za-z0-9%]|[\\s\\S]/gu;\n\n/** Does this text need CJK treatment? True for mixed \"土壤 pH 6.5\" text too. */\nexport function containsCjk(text: string): boolean {\n return CJK_CHAR_RE.test(text);\n}\n\n/** CJK runs together without a space; Latin needs one. */\nfunction joinSpoken(left: string, right: string): string {\n const seam = `${left.slice(-1)}${right.slice(0, 1)}`;\n return CJK_ADJACENT_RE.test(seam) ? `${left}${right}` : `${left} ${right}`;\n}\n\nfunction pushTrimmed(chunks: string[], text: string): void {\n const trimmed = text.trim();\n if (trimmed) chunks.push(trimmed);\n}\n\n/** Pack a space-less run into chunks, breaking at pause marks and never inside a number. */\nfunction splitCjkRun(sentence: string, maxChars: number): string[] {\n const chunks: string[] = [];\n let current = '';\n let lastPause = -1;\n\n for (const atom of sentence.match(CJK_ATOM_RE) ?? []) {\n if (current.length + atom.length > maxChars && current.trim()) {\n // Prefer the last 、 or ,— a listener expects a pause there anyway.\n if (lastPause > 0 && lastPause < current.length && lastPause >= maxChars * 0.4) {\n pushTrimmed(chunks, current.slice(0, lastPause));\n const rest = current.slice(lastPause);\n if (rest.trim().length + atom.length > maxChars) {\n pushTrimmed(chunks, rest);\n current = '';\n } else current = rest;\n } else {\n pushTrimmed(chunks, current);\n current = '';\n }\n lastPause = -1;\n }\n\n if (atom.length > maxChars) {\n pushTrimmed(chunks, current);\n current = '';\n lastPause = -1;\n for (let start = 0; start < atom.length; start += maxChars) chunks.push(atom.slice(start, start + maxChars));\n continue;\n }\n\n current += atom;\n if (CJK_PAUSE_RE.test(atom)) lastPause = current.length;\n }\n\n pushTrimmed(chunks, current);\n return chunks;\n}\n\nfunction splitLongRun(sentence: string, maxChars: number): string[] {\n if (containsCjk(sentence)) return splitCjkRun(sentence, maxChars);\n\n const chunks: string[] = [];\n let current = '';\n\n for (const word of sentence.split(/\\s+/)) {\n if (word.length > maxChars) {\n if (current) {\n chunks.push(current);\n current = '';\n }\n for (let start = 0; start < word.length; start += maxChars) {\n chunks.push(word.slice(start, start + maxChars));\n }\n continue;\n }\n if (!current) current = word;\n else if (current.length + 1 + word.length <= maxChars) current = `${current} ${word}`;\n else {\n chunks.push(current);\n current = word;\n }\n }\n\n if (current) chunks.push(current);\n return chunks;\n}\n\n/**\n * Split speakable text into utterance-sized chunks.\n *\n * See SPEECH_CHUNK_CHARS: this exists to dodge Chrome's ~15 second single\n * utterance cut-off, so the split points are sentence boundaries (a pause the\n * listener expects) rather than an arbitrary character offset. A CJK sentence\n * gets the tighter CJK ceiling, because a character there is a whole syllable.\n */\nexport function chunkForSpeech(\n text: string,\n maxChars: number = SPEECH_CHUNK_CHARS,\n cjkMaxChars: number = SPEECH_CHUNK_CJK_CHARS\n): string[] {\n const limit = Math.max(1, maxChars);\n const cjkLimit = Math.max(1, Math.min(cjkMaxChars, limit));\n const chunks: string[] = [];\n let current = '';\n let currentLimit = limit;\n\n for (const sentence of splitSentences(text)) {\n const sentenceLimit = containsCjk(sentence) ? cjkLimit : limit;\n\n if (sentence.length > sentenceLimit) {\n if (current) {\n chunks.push(current);\n current = '';\n }\n chunks.push(...splitLongRun(sentence, sentenceLimit));\n currentLimit = limit;\n continue;\n }\n\n if (!current) {\n current = sentence;\n currentLimit = sentenceLimit;\n continue;\n }\n\n const merged = joinSpoken(current, sentence);\n const mergedLimit = Math.min(currentLimit, sentenceLimit);\n if (merged.length <= mergedLimit) {\n current = merged;\n currentLimit = mergedLimit;\n } else {\n chunks.push(current);\n current = sentence;\n currentLimit = sentenceLimit;\n }\n }\n\n if (current) chunks.push(current);\n return chunks;\n}\n"],"mappings":";AAuDA,IAAa,IAA4C;CACvD,WAAW;CACX,OAAO;CACP,MAAM;CACN,YAAY;CACZ,WAAW;CACX,YAAY;CACZ,SAAS;CACT,UAAU;AACZ,GAwCM,IAAW,2BACX,IAAa,0BACb,IAAqB,oCACrB,IAAgB,qBAEhB,IAAiB,oCACjB,IAAiB,iBACjB,IAAkB,mBAElB,IAAsB,kBAEtB,IAAmB;AAEzB,SAAS,EAAY,GAAkB,GAAiD;CACtF,OAAO,OAAO,QAAQ,CAAM,EAAE,QAC3B,GAAK,CAAC,GAAK,OAAW,EAAI,QAAY,OAAO,SAAS,EAAI,SAAS,GAAG,GAAG,OAAO,CAAK,CAAC,GACvF,CACF;AACF;AAGA,SAAS,EAAiB,GAAuB;CAC/C,IAAM,IAAU,EAAK,KAAK;CAC1B,OAAO,EAAQ,SAAS,GAAG,KAAK,EAAQ,SAAS,GAAG,KAAK,aAAa,KAAK,CAAO;AACpF;AAQA,SAAgB,EAAc,GAAwB;CACpD,IAAM,IAAU,EAAK,KAAK,EAAE,QAAQ,OAAO,EAAE,EAAE,QAAQ,OAAO,EAAE,GAC1D,IAAkB,CAAC,GACrB,IAAU;CAEd,KAAK,IAAI,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|
+
{"version":3,"file":"speakableText.js","names":[],"sources":["../../src/utils/speakableText.ts"],"sourcesContent":["/**\n * Markdown → speakable plain text (BOFF-6290, assistant voice reply).\n *\n * An assistant reply is Markdown: headings, tables, fenced code, links, list\n * markers, the odd emoji. Handing that string straight to a speech engine reads\n * out \"asterisk asterisk yield asterisk asterisk\", spells URLs character by\n * character, and grinds through a forty-row table one pipe at a time. This\n * module flattens a reply into something a person would actually say.\n *\n * Design notes:\n *\n * - **Pure, and deliberately so.** This repo's vitest runs in the `node`\n * environment (no jsdom), so audio and DOM behaviour are not testable here.\n * The transformation is where the real logic lives, so it is isolated as a\n * pure function with no imports and covered directly by `speakableText.test.ts`.\n * - **Copy comes in through `labels`**, not `useTr`, so the function stays pure\n * and the spoken placeholders still follow the app locale (the hook passes\n * translated strings in). `{{rows}}` / `{{columns}}` interpolate the same way\n * `useTr` params do.\n * - **No lookbehind assertions.** Safari < 16.4 throws at *parse* time on a\n * lookbehind, which would take down the whole module — the same trap the\n * old hand-rolled markdown renderer fell into (see AssistantMarkdownRenderer).\n * Every rule below uses a captured prefix or a lookahead instead.\n */\n\nexport interface SpeakableLabels {\n /** Spoken in place of a fenced code block, which is unlistenable read out. */\n codeBlock: string;\n /** Spoken for an image with no alt text. */\n image: string;\n /** Spoken in place of a URL — nobody wants \"h t t p s colon slash slash\". */\n link: string;\n /** Spoken in place of a table too large to read. Params: rows, columns. */\n largeTable: string;\n /** Appended when a very long reply is cut short. */\n truncated: string;\n /** Spoken for `@` in an address. English \"at\" inside a Tamil reply is jarring. */\n emailAt: string;\n /** Spoken for `.` in an address. */\n emailDot: string;\n /**\n * Prefix for a numbered item nested under an UNnumbered one. Param: ordinal.\n *\n * Nested ordered items normally read as a dotted path (\"2.1.\") which already\n * says where the sub-steps are; that is impossible when the parent is a\n * bullet and has no number of its own, so the level is named instead.\n */\n nestedItem: string;\n}\n\n/**\n * Sentence punctuation is deliberately absent: block-level labels get a full\n * stop from `asSentence`, and the inline ones (\"link\", \"image\") have to read\n * naturally mid-sentence — \"see link for details\", not \"see Link. for details\".\n */\nexport const DEFAULT_SPEAKABLE_LABELS: SpeakableLabels = {\n codeBlock: 'Code block',\n image: 'image',\n link: 'link',\n largeTable: 'Table with {{rows}} rows and {{columns}} columns',\n truncated: 'The rest of this message is not read aloud',\n nestedItem: 'Sub-item {{ordinal}}',\n emailAt: 'at',\n emailDot: 'dot',\n};\n\n/**\n * Tables at or below this many body rows are flattened into \"header: value\"\n * sentences, because a 2×3 table is usually THE answer. Anything larger is\n * summarised — the point of the limit is that a long table is unlistenable, not\n * that tables are unimportant.\n */\nexport const MAX_SPOKEN_TABLE_ROWS = 3;\n\n/** Roughly ten minutes of speech. Past this the reply is summarised as cut off. */\nexport const MAX_SPEAKABLE_CHARS = 8_000;\n\n/**\n * Utterances are split at about this length before being queued.\n *\n * Chrome (and Edge) silently stop a single `SpeechSynthesisUtterance` after\n * roughly fifteen seconds — a long-standing engine bug, not something we can\n * feature-detect. Queueing sentence-sized utterances keeps every one of them\n * well under that ceiling, so a long reply finishes instead of dying mid-word.\n */\nexport const SPEECH_CHUNK_CHARS = 180;\n\n/**\n * Chunk ceiling for Chinese and Japanese, in CHARACTERS.\n *\n * The limit above is sized for Latin text, where ~180 characters is ~30 words\n * and lands around ten seconds. A CJK character is a whole syllable — a zh voice\n * reads roughly 4–6 of them a second — so 180 of them is a minute of speech,\n * four times past the very cut-off the chunking exists to dodge. 40 characters\n * is ~7–10 seconds, the same target the Latin limit is aiming at.\n */\nexport const SPEECH_CHUNK_CJK_CHARS = 40;\n\nexport interface SpeakableOptions {\n labels?: Partial<SpeakableLabels>;\n maxChars?: number;\n maxSpokenTableRows?: number;\n}\n\nconst FENCE_RE = /^\\s{0,3}(?:`{3,}|~{3,})/;\nconst HEADING_RE = /^\\s{0,3}#{1,6}\\s+(.*)$/;\nconst HORIZONTAL_RULE_RE = /^\\s{0,3}([-*_])(?:\\s*\\1){2,}\\s*$/;\nconst BLOCKQUOTE_RE = /^\\s{0,3}(?:>\\s?)+/;\n/** Group 1 = indentation (nesting depth), group 2 = the ordinal, if numbered. */\nconst LIST_MARKER_RE = /^(\\s*)(?:[-*+]|(\\d{1,9})[.)])\\s+/;\nconst TASK_MARKER_RE = /^\\[[ xX]\\]\\s*/;\n/**\n * What counts as the end of a spoken sentence.\n *\n * Latin and CJK were covered; the Indic and Arabic terminators were not, so a\n * Hindi or Urdu reply had NO recognised sentence end at all and fell through to\n * being cut by length — pauses landing mid-sentence. It also made `asSentence`\n * append a full stop after a danda, producing \"…।.\"\n *\n * । danda, ॥ double danda — Hindi, Marathi, Nepali, Sanskrit\n * ۔ Urdu full stop\n * ؟ Arabic question mark, ؛ Arabic semicolon\n *\n * The Arabic comma `،` is deliberately absent, matching the Latin `,`: a comma\n * is a pause inside a sentence, not the end of one.\n *\n * Tamil is unaffected either way — modern Tamil uses the ordinary full stop.\n */\nconst SENTENCE_END_RE = /[.!?…⋯:;。!?;.।॥۔؟؛]$/;\n/** A `=====` line under a paragraph: a setext heading, never prose. */\nconst SETEXT_UNDERLINE_RE = /^\\s{0,3}=+\\s*$/;\n/** Four spaces or a tab: an indented code block, which is not worth reading. */\nconst INDENTED_CODE_RE = /^(?: {4}|\\t)/;\n\nfunction interpolate(template: string, params: Record<string, string | number>): string {\n return Object.entries(params).reduce(\n (out, [key, value]) => out.replace(new RegExp(`\\\\{\\\\{${key}\\\\}\\\\}`, 'g'), String(value)),\n template\n );\n}\n\n/** A `|`-only rule row (`|---|:--:|`) — what makes the line above it a header. */\nfunction isTableDelimiter(line: string): boolean {\n const trimmed = line.trim();\n return trimmed.includes('|') && trimmed.includes('-') && /^[\\s:|-]+$/.test(trimmed);\n}\n\n/**\n * Split a GFM table row into cells, honouring `\\|` escapes.\n *\n * Written as a scan rather than `split(/(?<!\\\\)\\|/)` on purpose — see the\n * no-lookbehind note at the top of the file.\n */\nexport function splitTableRow(line: string): string[] {\n const trimmed = line.trim().replace(/^\\|/, '').replace(/\\|$/, '');\n const cells: string[] = [];\n let current = '';\n\n for (let index = 0; index < trimmed.length; index += 1) {\n const char = trimmed[index];\n if (char === '\\\\' && trimmed[index + 1] === '|') {\n current += '|';\n index += 1;\n continue;\n }\n if (char === '|') {\n cells.push(current);\n current = '';\n continue;\n }\n current += char;\n }\n cells.push(current);\n\n return cells.map((cell) => cell.trim());\n}\n\nconst ENTITIES: Record<string, string> = {\n '&': ' and ',\n '<': ' less than ',\n '>': ' greater than ',\n '"': '\"',\n ''': \"'\",\n ''': \"'\",\n ' ': ' ',\n};\n\nconst EMAIL_BODY = '[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\\\\.[A-Za-z0-9-]+)+';\n/** `<support@x.com>`, the autolink form — and what the HTML strip used to eat. */\nconst AUTOLINK_EMAIL_RE = new RegExp(`<(?:mailto:)?(${EMAIL_BODY})>`, 'g');\nconst MAILTO_RE = new RegExp(`\\\\bmailto:(${EMAIL_BODY})`, 'g');\nconst BARE_EMAIL_RE = new RegExp(EMAIL_BODY, 'g');\n\n/**\n * Say an address the way a person reads one out.\n *\n * \"support at healthybowl dot com\" — an engine handed the raw string either\n * spells it or swallows the punctuation, and expanding the dots here also keeps\n * the sentence splitter from mistaking `.com` for the end of a sentence.\n */\nexport function speakableEmail(address: string, at = 'at', dot = 'dot'): string {\n return address.replace(/@/g, ` ${at} `).replace(/\\./g, ` ${dot} `).replace(/\\s+/g, ' ').trim();\n}\n\n/**\n * Flatten the inline span syntax of one line: emphasis, code, links, images,\n * raw HTML, entities and pictographs.\n */\nfunction flattenInline(input: string, labels: SpeakableLabels): string {\n let text = input;\n\n // Images first: `` also matches the link pattern below.\n text = text.replace(/!\\[([^\\]]*)\\]\\([^)]*\\)/g, (_match, alt: string) => alt.trim() || ` ${labels.image} `);\n\n // Inline links: keep the human-readable text, drop the URL entirely.\n text = text.replace(/\\[([^\\]]*)\\]\\([^)]*\\)/g, (_match, label: string) => label.trim() || ` ${labels.link} `);\n // Reference links (`[text][ref]`, `[text][]`).\n text = text.replace(/\\[([^\\]]*)\\]\\[[^\\]]*\\]/g, (_match, label: string) => label.trim() || ` ${labels.link} `);\n\n // Autolinks and bare URLs.\n text = text.replace(/<https?:\\/\\/[^>\\s]+>/g, ` ${labels.link} `);\n text = text.replace(/\\bhttps?:\\/\\/\\S+/g, ` ${labels.link} `);\n\n // Email addresses, BEFORE the HTML strip below: `<support@x.com>` looks like a\n // tag to that rule, and deleting it turns \"Contact <support@x.com>.\" into\n // \"Contact.\" — the one piece of information in the sentence, silently gone.\n // Addresses run after URLs so that `https://user@host/x` is already a \"link\".\n text = text.replace(\n AUTOLINK_EMAIL_RE,\n (_match, address: string) => ` ${speakableEmail(address, labels.emailAt, labels.emailDot)} `\n );\n text = text.replace(\n MAILTO_RE,\n (_match, address: string) => ` ${speakableEmail(address, labels.emailAt, labels.emailDot)} `\n );\n text = text.replace(BARE_EMAIL_RE, (match: string) => ` ${speakableEmail(match, labels.emailAt, labels.emailDot)} `);\n\n // Inline code — the backticks go, the identifier inside is usually the point.\n text = text.replace(/`+([^`]*)`+/g, (_match, code: string) => code);\n\n // Raw HTML. The renderer escapes rather than renders it, so the user SEES the\n // tag; either way \"less than b greater than\" is not worth saying.\n text = text.replace(/<\\/?[a-zA-Z][^>]*>/g, ' ');\n\n for (const [entity, replacement] of Object.entries(ENTITIES)) {\n text = text.split(entity).join(replacement);\n }\n\n // Emphasis. `***x***` / `**x**` before `*x*` so the longer fence wins.\n text = text.replace(/(\\*\\*\\*|___)(\\S(?:[\\s\\S]*?\\S)?)\\1/g, '$2');\n text = text.replace(/(\\*\\*|__)(\\S(?:[\\s\\S]*?\\S)?)\\1/g, '$2');\n text = text.replace(/~~(\\S(?:[\\s\\S]*?\\S)?)~~/g, '$1');\n // Single-character emphasis is boundary-anchored: without it `crop_yield_total`\n // becomes \"cropyieldtotal\" and `2 * 3 * 4` loses its operators.\n text = text.replace(/(^|[\\s([{\"'])\\*(\\S(?:[\\s\\S]*?\\S)?)\\*(?=$|[\\s)\\]}\"'.,!?;:])/g, '$1$2');\n text = text.replace(/(^|[\\s([{\"'])_(\\S(?:[\\s\\S]*?\\S)?)_(?=$|[\\s)\\]}\"'.,!?;:])/g, '$1$2');\n\n // Pictographs: some voices announce every emoji by name (\"seedling\", \"sun\n // with face\"), which is noise in the middle of an agronomy answer. The two\n // escapes are the variation selector and the zero-width joiner that glue\n // multi-codepoint emoji together.\n text = text.replace(/[\\p{Extended_Pictographic}\\uFE0F\\u200D]/gu, ' ');\n\n // …and the decorative symbols that are NOT Extended_Pictographic, which is\n // why they survived and were read aloud. A reply mixing ✅ and ✓ had one\n // stripped and the other announced. Deliberately an explicit list rather than\n // a Unicode category: `\\p{Po}` would take `.` `,` `?` with it, and `\\p{So}`\n // would take `°`, which engines pronounce correctly and users want.\n text = text.replace(/[•·▪▫◦‣⁃∙●○■□▶▸►➤➜→←↑↓⇒⇔★☆⭐✦✧✓✔✗✘✕✖]/gu, ' ');\n\n // Em/en dashes are read as the word \"dash\" by some engines. As punctuation\n // they mean a pause, so give the engine one it understands.\n //\n // NOT between two numbers: there the dash is a RANGE, and a comma splits one\n // value into two. \"Apply 3–5 kg per hectare\" read as \"apply three, five\n // kilograms per hectare\" is a dosage a farmer could act on wrongly, so a\n // digit on both sides is left exactly as it was.\n //\n // Written with capture groups rather than a lookbehind: lookbehind only\n // reached Safari in 16.4, and iOS WebKit is the primary device here.\n text = text.replace(/(\\d)?\\s*[—–―]\\s*(\\d)?/g, (match, before, after) =>\n before !== undefined && after !== undefined ? match : `${before ?? ''}, ${after ?? ''}`\n );\n\n // Residual emphasis markers. The fences above require non-whitespace inside\n // them, so unbalanced or word-internal markup leaks: `**N**-**P**-**K**`\n // survives as `N**-P-**K` and is spoken \"N star star P\". Only runs of two or\n // more are removed — a lone `*` is left alone so `2 * 3` keeps its operator.\n text = text.replace(/\\*{2,}/g, '');\n\n return (\n text\n .replace(/\\s+/g, ' ')\n // Removing a span leaves a gap in front of the punctuation that followed\n // it (\"Docs at link .\"). Harmless to read, but it also breaks the\n // sentence-boundary detection that `chunkForSpeech` relies on.\n .replace(/\\s+([.,!?;:)\\]}])/g, '$1')\n .replace(/([([{])\\s+/g, '$1')\n .trim()\n );\n}\n\n/** Give the engine somewhere to breathe between headings, list items and rows. */\nfunction asSentence(text: string): string {\n const trimmed = text.trim();\n if (!trimmed) return '';\n return SENTENCE_END_RE.test(trimmed) ? trimmed : `${trimmed}.`;\n}\n\nfunction truncateSpeakable(text: string, maxChars: number, notice: string): string {\n if (text.length <= maxChars) return text;\n\n const head = text.slice(0, maxChars);\n const sentenceEnd = Math.max(head.lastIndexOf('. '), head.lastIndexOf('\\n'));\n const wordEnd = head.lastIndexOf(' ');\n const cut = sentenceEnd > maxChars * 0.5 ? sentenceEnd + 1 : wordEnd > 0 ? wordEnd : maxChars;\n\n return `${head.slice(0, cut).trim()}\\n${notice}`;\n}\n\n/** Leading whitespace as a column count, so a tab nests like four spaces do. */\nfunction indentWidth(indent: string): number {\n let width = 0;\n for (const char of indent) width += char === '\\t' ? 4 : 1;\n return width;\n}\n\n/** One entry per open list level; `ordinal` is null for a bullet. */\ninterface ListLevel {\n indent: number;\n ordinal: string | null;\n}\n\n/**\n * What to say in front of a list item so the listener can hear the nesting.\n *\n * A depth-2 \"1.\" read as \"one\" is indistinguishable from the depth-1 \"1.\" that\n * preceded it, which is exactly how a listener loses track of where the\n * sub-steps started. Nested numbers therefore read as their full path — \"2.1.\"\n * — and a number nested under a BULLET, which has no path, is named instead.\n */\nfunction spokenOrdinal(stack: readonly ListLevel[], labels: SpeakableLabels): string {\n const self = stack[stack.length - 1];\n if (!self?.ordinal) return '';\n if (stack.length === 1) return `${self.ordinal}. `;\n\n const path = stack.map((level) => level.ordinal);\n if (path.every((ordinal): ordinal is string => Boolean(ordinal))) return `${path.join('.')}. `;\n return `${interpolate(labels.nestedItem, { ordinal: self.ordinal })}. `;\n}\n\n/**\n * Convert an assistant reply (Markdown) into plain text worth speaking.\n *\n * Returns `''` when there is nothing speakable — the caller should treat that\n * as \"no speak control\", not as an error.\n */\nexport function toSpeakableText(markdown: string, options: SpeakableOptions = {}): string {\n const labels = { ...DEFAULT_SPEAKABLE_LABELS, ...options.labels };\n const maxChars = options.maxChars ?? MAX_SPEAKABLE_CHARS;\n const maxTableRows = options.maxSpokenTableRows ?? MAX_SPOKEN_TABLE_ROWS;\n\n if (!markdown) return '';\n\n const lines = markdown.replace(/\\r\\n?/g, '\\n').split('\\n');\n const spoken: string[] = [];\n const listStack: ListLevel[] = [];\n let index = 0;\n\n while (index < lines.length) {\n const raw = lines[index];\n const line = raw.replace(BLOCKQUOTE_RE, '');\n // Positional, so it stays correct across every branch below: an indented\n // code block can only start after a blank line (it cannot interrupt a\n // paragraph), and the start of the reply counts as one.\n const previousBlank = index === 0 || !lines[index - 1].replace(BLOCKQUOTE_RE, '').trim();\n\n // ── Fenced code: announce it, skip to the closing fence ──────────────\n if (FENCE_RE.test(line)) {\n index += 1;\n while (index < lines.length && !FENCE_RE.test(lines[index].replace(BLOCKQUOTE_RE, ''))) index += 1;\n index += 1; // consume the closing fence (or fall off the end, unclosed)\n spoken.push(asSentence(labels.codeBlock));\n continue;\n }\n\n // ── Indented code: the OTHER way Markdown writes a code block ────────\n // Announced exactly like a fenced one; read verbatim it is \"SELECT star\n // FROM crops WHERE p h less than…\". Not applied inside a list, where four\n // spaces mean a continuation line rather than code.\n if (previousBlank && listStack.length === 0 && line.trim() && INDENTED_CODE_RE.test(line)) {\n index += 1;\n while (index < lines.length) {\n const candidate = lines[index].replace(BLOCKQUOTE_RE, '');\n if (candidate.trim() && INDENTED_CODE_RE.test(candidate)) {\n index += 1;\n continue;\n }\n if (candidate.trim()) break;\n // A blank line only ends the block if no indented line follows it.\n let peek = index;\n while (peek < lines.length && !lines[peek].replace(BLOCKQUOTE_RE, '').trim()) peek += 1;\n const resumed = peek < lines.length ? lines[peek].replace(BLOCKQUOTE_RE, '') : '';\n if (!resumed.trim() || !INDENTED_CODE_RE.test(resumed)) break;\n index = peek;\n }\n spoken.push(asSentence(labels.codeBlock));\n continue;\n }\n\n if (HORIZONTAL_RULE_RE.test(line)) {\n index += 1;\n continue;\n }\n\n // A stray `=====` carries no meaning of its own; without this it is read\n // out as prose (the setext case below consumes the ones that have a title).\n if (SETEXT_UNDERLINE_RE.test(line)) {\n index += 1;\n continue;\n }\n\n // ── GFM table: header row followed by a `|---|` rule ─────────────────\n const next = index + 1 < lines.length ? lines[index + 1].replace(BLOCKQUOTE_RE, '') : '';\n if (line.includes('|') && isTableDelimiter(next)) {\n listStack.length = 0;\n const headers = splitTableRow(line).map((cell) => flattenInline(cell, labels));\n index += 2;\n\n const rows: string[][] = [];\n while (index < lines.length) {\n const rowLine = lines[index].replace(BLOCKQUOTE_RE, '');\n if (!rowLine.includes('|') || !rowLine.trim()) break;\n rows.push(splitTableRow(rowLine).map((cell) => flattenInline(cell, labels)));\n index += 1;\n }\n\n if (rows.length > maxTableRows) {\n spoken.push(asSentence(interpolate(labels.largeTable, { rows: rows.length, columns: headers.length })));\n } else {\n for (const row of rows) {\n const pairs = row\n .map((cell, column) => {\n if (!cell) return '';\n const header = headers[column];\n return header ? `${header}: ${cell}` : cell;\n })\n .filter(Boolean);\n if (pairs.length) spoken.push(asSentence(pairs.join(', ')));\n }\n }\n continue;\n }\n\n index += 1;\n\n // A blank line does NOT close a list: loose lists have one between items.\n if (!line.trim()) continue;\n\n const heading = HEADING_RE.exec(line);\n if (heading) {\n listStack.length = 0;\n // `## Title ##` — ATX closing hashes are decoration, not content.\n const text = flattenInline(heading[1].replace(/\\s+#+\\s*$/, ''), labels);\n if (text) spoken.push(asSentence(text));\n continue;\n }\n\n // ── List item: drop bullets, keep ordinals (they carry step order) ───\n const marker = LIST_MARKER_RE.exec(line);\n let body = line;\n let ordinal = '';\n if (marker) {\n body = line.slice(marker[0].length).replace(TASK_MARKER_RE, '');\n\n const depth = indentWidth(marker[1]);\n while (listStack.length > 0 && listStack[listStack.length - 1].indent >= depth) listStack.pop();\n listStack.push({ indent: depth, ordinal: marker[2] ?? null });\n ordinal = spokenOrdinal(listStack, labels);\n } else if (!/^\\s/.test(line)) {\n // Un-indented prose ends the list; an indented line continues an item.\n listStack.length = 0;\n }\n\n // ── Setext heading: `Title` over `=====` ─────────────────────────────\n if (!marker && SETEXT_UNDERLINE_RE.test(next)) {\n listStack.length = 0;\n index += 1; // the underline is decoration\n const text = flattenInline(line, labels);\n if (text) spoken.push(asSentence(text));\n continue;\n }\n\n const text = flattenInline(body, labels);\n if (text) spoken.push(asSentence(`${ordinal}${text}`));\n }\n\n const result = spoken\n .join('\\n')\n .replace(/\\n{2,}/g, '\\n')\n .trim();\n return truncateSpeakable(result, maxChars, asSentence(labels.truncated));\n}\n\n/* ── Sentence boundaries ───────────────────────────────────────────────────\n *\n * The naive rule (\"a run of . ! ? ends a sentence\") is wrong for exactly the\n * content this product exists to talk about. `12.5 kg/ha`, `pH 6.5`, `N-P-K\n * 10.10.10`, `$18.75`, `2026.07.01` and `i.e.` all contain a period that ends\n * nothing, and splitting there does not merely add a pause: each chunk is a\n * SEPARATE utterance, so \"8.4 kg\" comes out as \"eight.\" … \"four kilograms\".\n *\n * So a period is a boundary only when it is followed by whitespace (or the end\n * of the line) AND the token in front of it is not an abbreviation, an initial\n * or a list ordinal. `!` and `?` take the whitespace rule but skip the rest.\n *\n * CJK terminators are unconditional: those scripts do not put a space after\n * `。`, so the whitespace rule would never fire and a whole Chinese or Japanese\n * reply would arrive here as one \"sentence\".\n */\n\nconst ASCII_TERMINATORS = new Set(['.', '!', '?']);\n/**\n * Terminators that end a sentence WHEREVER they appear, with no space rule.\n *\n * The Latin `.` needs care — `12.5`, `report.pdf`, `Dr.` — so it lives in\n * ASCII_TERMINATORS and goes through `isSentenceBoundary`. These do not: none\n * of them appears mid-token, so seeing one IS the boundary.\n *\n * ★ The Indic and Arabic marks were missing, which is the half of BOFF-7120\n * that actually mattered. `SENTENCE_END_RE` (used only by `asSentence`) governs\n * whether a full stop is appended; THIS set is what `splitSentences` chunks on.\n * Fixing only the former removed the stray \"।.\" and left Hindi, Urdu and Arabic\n * still being cut by LENGTH, pauses landing mid-sentence — the original\n * complaint, untouched.\n *\n * ।॥ danda and double danda · ۔ Urdu full stop · ؟ Arabic question mark\n * ؛ Arabic semicolon\n */\nconst UNSPACED_TERMINATORS = new Set(['。', '!', '?', ';', '.', '。', '…', '⋯', '।', '॥', '۔', '؟', '؛']);\n/** Punctuation that may trail a terminator and still belong to the sentence. */\nconst SENTENCE_CLOSERS = new Set(['\"', \"'\", ')', ']', '}', '»', '”', '’', '〉', '》', '」', '』', '】', ')']);\n\n/**\n * Tokens that take a period without ending a sentence. Stored WITHOUT the final\n * dot, lower-cased. Single letters (\"J. Smith\", the `i` of `i.e.`) are covered\n * by a rule rather than listed.\n */\nconst ABBREVIATIONS = new Set([\n 'i.e',\n 'e.g',\n 'etc',\n 'approx',\n 'vs',\n 'cf',\n 'viz',\n 'al',\n 'est',\n 'dept',\n 'fig',\n 'figs',\n 'ref',\n 'min',\n 'max',\n 'avg',\n 'qty',\n 'temp',\n 'mr',\n 'mrs',\n 'ms',\n 'dr',\n 'prof',\n 'sr',\n 'jr',\n 'st',\n 'inc',\n 'ltd',\n 'co',\n 'corp',\n 'univ',\n 'ca',\n // Units. An agronomy reply is full of them, and \"12 kg. of lime\" is one\n // sentence however the model punctuated it.\n 'kg',\n 'mg',\n 'gm',\n 'ha',\n 'cm',\n 'mm',\n 'km',\n 'ml',\n 'lb',\n 'oz',\n 'sq',\n 'hrs',\n 'wk',\n 'yr',\n 'mo',\n 'vol',\n 'pp',\n]);\n\n/** Abbreviations that only hold when a number follows: \"No. 4\", not \"the answer is no.\" */\nconst NUMBER_ABBREVIATIONS = new Set(['no', 'nos', 'p', 'ch', 'sec', 'art']);\n\nconst DIGITS_ONLY_RE = /^\\d+(?:\\.\\d+)*$/;\nconst SINGLE_LETTER_RE = /^[A-Za-z]$/;\n\nfunction isSentenceBoundary(line: string, termStart: number, end: number): boolean {\n // Any unspaced terminator in the run settles it — those scripts have no\n // space rule, so the mark itself is the boundary.\n for (let cursor = termStart; cursor < end; cursor += 1) {\n if (UNSPACED_TERMINATORS.has(line[cursor])) return true;\n }\n\n // `12.5`, `10.10.10`, `report.pdf`, `hb.example`: a period glued to what\n // follows it is part of a token, never the end of a sentence.\n if (end < line.length && !/\\s/.test(line[end])) return false;\n if (line[termStart] !== '.') return true;\n\n const before = line.slice(0, termStart);\n const token = /(\\S+)$/.exec(before)?.[1] ?? '';\n if (!token) return true;\n\n // A list ordinal at the head of the line (\"1.\" / \"2.1.\") is a marker, not a\n // sentence: splitting there queues the number as its own utterance.\n if (DIGITS_ONLY_RE.test(token) && !before.slice(0, before.length - token.length).trim()) return false;\n\n const lower = token.toLowerCase();\n if (SINGLE_LETTER_RE.test(token)) return false;\n if (ABBREVIATIONS.has(lower)) return false;\n if (NUMBER_ABBREVIATIONS.has(lower)) return !/^\\s*\\d/.test(line.slice(end));\n\n return true;\n}\n\n/** Break one line into sentence-ish units. */\nfunction splitSentences(text: string): string[] {\n const out: string[] = [];\n\n for (const line of text.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) continue;\n\n let start = 0;\n let cursor = 0;\n\n while (cursor < trimmed.length) {\n const char = trimmed[cursor];\n if (!ASCII_TERMINATORS.has(char) && !UNSPACED_TERMINATORS.has(char)) {\n cursor += 1;\n continue;\n }\n\n let end = cursor;\n while (end < trimmed.length && (ASCII_TERMINATORS.has(trimmed[end]) || UNSPACED_TERMINATORS.has(trimmed[end]))) {\n end += 1;\n }\n while (end < trimmed.length && SENTENCE_CLOSERS.has(trimmed[end])) end += 1;\n\n if (isSentenceBoundary(trimmed, cursor, end)) {\n const piece = trimmed.slice(start, end).trim();\n if (piece) out.push(piece);\n start = end;\n }\n cursor = end;\n }\n\n const tail = trimmed.slice(start).trim();\n if (tail) out.push(tail);\n }\n\n return out;\n}\n\n/* ── CJK ──────────────────────────────────────────────────────────────────\n *\n * Chinese and Japanese are two of the six shipped locales and neither uses\n * spaces, so whitespace-based packing degenerates to a blind character slice\n * that lands mid-number and mid-clause. They also carry far more speech per\n * character than Latin text does — see SPEECH_CHUNK_CJK_CHARS.\n */\n\n/** Kana, CJK ideographs (incl. extension A and compatibility) and halfwidth kana. */\nconst CJK_CHAR_RE = /[\\u3040-\\u30ff\\u3400-\\u4dbf\\u4e00-\\u9fff\\uf900-\\ufaff\\uff66-\\uff9f]/;\n/** The above plus CJK and fullwidth punctuation: characters that need no space beside them. */\nconst CJK_ADJACENT_RE = /[\\u3000-\\u303f\\u3040-\\u30ff\\u3400-\\u4dbf\\u4e00-\\u9fff\\uf900-\\ufaff\\uff01-\\uff9f]/;\n/** Mid-sentence pause marks: the natural place to end a chunk. */\nconst CJK_PAUSE_RE = /[、,,;;::。!?!?]/;\n/**\n * One indivisible unit: a Latin/numeric token (so `12.5`, `10.10.10` and `kg/ha`\n * are never cut in half) or a single character.\n */\nconst CJK_ATOM_RE = /[A-Za-z0-9][A-Za-z0-9._,:%/+-]*[A-Za-z0-9%]|[\\s\\S]/gu;\n\n/** Does this text need CJK treatment? True for mixed \"土壤 pH 6.5\" text too. */\nexport function containsCjk(text: string): boolean {\n return CJK_CHAR_RE.test(text);\n}\n\n/** CJK runs together without a space; Latin needs one. */\nfunction joinSpoken(left: string, right: string): string {\n const seam = `${left.slice(-1)}${right.slice(0, 1)}`;\n return CJK_ADJACENT_RE.test(seam) ? `${left}${right}` : `${left} ${right}`;\n}\n\nfunction pushTrimmed(chunks: string[], text: string): void {\n const trimmed = text.trim();\n if (trimmed) chunks.push(trimmed);\n}\n\n/** Pack a space-less run into chunks, breaking at pause marks and never inside a number. */\nfunction splitCjkRun(sentence: string, maxChars: number): string[] {\n const chunks: string[] = [];\n let current = '';\n let lastPause = -1;\n\n for (const atom of sentence.match(CJK_ATOM_RE) ?? []) {\n if (current.length + atom.length > maxChars && current.trim()) {\n // Prefer the last 、 or ,— a listener expects a pause there anyway.\n if (lastPause > 0 && lastPause < current.length && lastPause >= maxChars * 0.4) {\n pushTrimmed(chunks, current.slice(0, lastPause));\n const rest = current.slice(lastPause);\n if (rest.trim().length + atom.length > maxChars) {\n pushTrimmed(chunks, rest);\n current = '';\n } else current = rest;\n } else {\n pushTrimmed(chunks, current);\n current = '';\n }\n lastPause = -1;\n }\n\n if (atom.length > maxChars) {\n pushTrimmed(chunks, current);\n current = '';\n lastPause = -1;\n for (let start = 0; start < atom.length; start += maxChars) chunks.push(atom.slice(start, start + maxChars));\n continue;\n }\n\n current += atom;\n if (CJK_PAUSE_RE.test(atom)) lastPause = current.length;\n }\n\n pushTrimmed(chunks, current);\n return chunks;\n}\n\nfunction splitLongRun(sentence: string, maxChars: number): string[] {\n if (containsCjk(sentence)) return splitCjkRun(sentence, maxChars);\n\n const chunks: string[] = [];\n let current = '';\n\n for (const word of sentence.split(/\\s+/)) {\n if (word.length > maxChars) {\n if (current) {\n chunks.push(current);\n current = '';\n }\n for (let start = 0; start < word.length; start += maxChars) {\n chunks.push(word.slice(start, start + maxChars));\n }\n continue;\n }\n if (!current) current = word;\n else if (current.length + 1 + word.length <= maxChars) current = `${current} ${word}`;\n else {\n chunks.push(current);\n current = word;\n }\n }\n\n if (current) chunks.push(current);\n return chunks;\n}\n\n/**\n * Split speakable text into utterance-sized chunks.\n *\n * See SPEECH_CHUNK_CHARS: this exists to dodge Chrome's ~15 second single\n * utterance cut-off, so the split points are sentence boundaries (a pause the\n * listener expects) rather than an arbitrary character offset. A CJK sentence\n * gets the tighter CJK ceiling, because a character there is a whole syllable.\n */\nexport function chunkForSpeech(\n text: string,\n maxChars: number = SPEECH_CHUNK_CHARS,\n cjkMaxChars: number = SPEECH_CHUNK_CJK_CHARS\n): string[] {\n const limit = Math.max(1, maxChars);\n const cjkLimit = Math.max(1, Math.min(cjkMaxChars, limit));\n const chunks: string[] = [];\n let current = '';\n let currentLimit = limit;\n\n for (const sentence of splitSentences(text)) {\n const sentenceLimit = containsCjk(sentence) ? cjkLimit : limit;\n\n if (sentence.length > sentenceLimit) {\n if (current) {\n chunks.push(current);\n current = '';\n }\n chunks.push(...splitLongRun(sentence, sentenceLimit));\n currentLimit = limit;\n continue;\n }\n\n if (!current) {\n current = sentence;\n currentLimit = sentenceLimit;\n continue;\n }\n\n const merged = joinSpoken(current, sentence);\n const mergedLimit = Math.min(currentLimit, sentenceLimit);\n if (merged.length <= mergedLimit) {\n current = merged;\n currentLimit = mergedLimit;\n } else {\n chunks.push(current);\n current = sentence;\n currentLimit = sentenceLimit;\n }\n }\n\n if (current) chunks.push(current);\n return chunks;\n}\n"],"mappings":";AAuDA,IAAa,IAA4C;CACvD,WAAW;CACX,OAAO;CACP,MAAM;CACN,YAAY;CACZ,WAAW;CACX,YAAY;CACZ,SAAS;CACT,UAAU;AACZ,GAwCM,IAAW,2BACX,IAAa,0BACb,IAAqB,oCACrB,IAAgB,qBAEhB,IAAiB,oCACjB,IAAiB,iBAkBjB,IAAkB,wBAElB,IAAsB,kBAEtB,IAAmB;AAEzB,SAAS,EAAY,GAAkB,GAAiD;CACtF,OAAO,OAAO,QAAQ,CAAM,EAAE,QAC3B,GAAK,CAAC,GAAK,OAAW,EAAI,QAAY,OAAO,SAAS,EAAI,SAAS,GAAG,GAAG,OAAO,CAAK,CAAC,GACvF,CACF;AACF;AAGA,SAAS,EAAiB,GAAuB;CAC/C,IAAM,IAAU,EAAK,KAAK;CAC1B,OAAO,EAAQ,SAAS,GAAG,KAAK,EAAQ,SAAS,GAAG,KAAK,aAAa,KAAK,CAAO;AACpF;AAQA,SAAgB,EAAc,GAAwB;CACpD,IAAM,IAAU,EAAK,KAAK,EAAE,QAAQ,OAAO,EAAE,EAAE,QAAQ,OAAO,EAAE,GAC1D,IAAkB,CAAC,GACrB,IAAU;CAEd,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAQ,QAAQ,KAAS,GAAG;EACtD,IAAM,IAAO,EAAQ;EACrB,IAAI,MAAS,QAAQ,EAAQ,IAAQ,OAAO,KAAK;GAE/C,AADA,KAAW,KACX,KAAS;GACT;EACF;EACA,IAAI,M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