@burdenoff/microfe-healthybowl 2026.903.20 → 2026.903.22

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.
@@ -7,16 +7,16 @@ import { chunkForSpeech as a, toSpeakableText as o } from "../../utils/speakable
7
7
  import { speechLabelsFor as s } from "../../config/speechLabels.js";
8
8
  import { VOICE_LIST_TIMEOUT_MS as c, languageDisplayName as ee, selectVoiceForLocale as l, speechGate as te, speechLangForLocale as u, voiceAvailability as d, voicesForLocale as ne } from "../../utils/speechVoices.js";
9
9
  import { resolveSpeechLocale as re } from "../../utils/replyLanguage.js";
10
- import { findAssistantLanguage as ie } from "../../config/assistantLanguages.js";
11
- import { resolveLanguagePair as ae } from "../../config/assistantLanguagePair.js";
12
- import { IDLE_PLAYBACK as oe, isSpeakingMessage as f, speechPlaybackReducer as se } from "../../utils/speechPlayback.js";
13
- import { isTurnInFlight as ce } from "../../utils/assistantTurnState.js";
14
- import { parseToolActivity as le } from "./AssistantToolActivity.js";
15
- import { createContext as p, useCallback as m, useContext as h, useEffect as g, useMemo as _, useReducer as ue, useRef as v, useState as y } from "react";
16
- import { useI18n as de } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
17
- import { jsx as fe } from "react/jsx-runtime";
10
+ import { DEFAULT_SPEECH_RATE as ie, findAssistantLanguage as ae } from "../../config/assistantLanguages.js";
11
+ import { resolveLanguagePair as oe } from "../../config/assistantLanguagePair.js";
12
+ import { IDLE_PLAYBACK as se, isSpeakingMessage as f, speechPlaybackReducer as ce } from "../../utils/speechPlayback.js";
13
+ import { isTurnInFlight as le } from "../../utils/assistantTurnState.js";
14
+ import { parseToolActivity as ue } from "./AssistantToolActivity.js";
15
+ import { createContext as p, useCallback as m, useContext as h, useEffect as g, useMemo as _, useReducer as de, useRef as v, useState as y } from "react";
16
+ import { useI18n as fe } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
17
+ import { jsx as pe } from "react/jsx-runtime";
18
18
  //#region src/components/assistant/AssistantSpeechProvider.tsx
19
- var pe = {
19
+ var me = {
20
20
  codeBlock: "",
21
21
  image: "",
22
22
  link: "",
@@ -25,7 +25,7 @@ var pe = {
25
25
  emailAt: "at",
26
26
  emailDot: "dot",
27
27
  nestedItem: ""
28
- }, b = p({
28
+ }, he = p({
29
29
  isSupported: !1,
30
30
  availability: "unsupported",
31
31
  isBlocked: !0,
@@ -46,250 +46,250 @@ var pe = {
46
46
  setSessionSpeaking: () => {},
47
47
  previewVoice: () => {}
48
48
  });
49
- function x() {
50
- return h(b);
49
+ function b() {
50
+ return h(he);
51
51
  }
52
- var S = ({ children: p, visible: h = !0, engine: x = e() }) => {
53
- let S = n(), { locale: C } = de(), [w, T] = ue(se, oe), [E, D] = y(() => x.listVoices()), [O, k] = y(!1), [A, j] = y(() => /* @__PURE__ */ new Map()), M = v(0), [N, P] = y(null), F = v(null), I = v(() => {}), L = m(() => {
54
- F.current?.(), F.current = null;
55
- }, []), R = t((e) => e.autoSpeakEnabled), z = t((e) => e.setAutoSpeak), [B, me] = y(!1), he = t((e) => e.activeConversationId), V = _(() => x.isSupported(), [x]);
52
+ var x = ({ children: p, visible: h = !0, engine: b = e() }) => {
53
+ let x = n(), { locale: S } = fe(), [C, w] = de(ce, se), [T, E] = y(() => b.listVoices()), [D, O] = y(!1), [k, A] = y(() => /* @__PURE__ */ new Map()), j = v(0), [M, N] = y(null), P = v(null), F = v(() => {}), I = m(() => {
54
+ P.current?.(), P.current = null;
55
+ }, []), L = t((e) => e.autoSpeakEnabled), R = t((e) => e.setAutoSpeak), [z, ge] = y(!1), _e = t((e) => e.activeConversationId), B = _(() => b.isSupported(), [b]);
56
56
  g(() => {
57
- if (!V) return;
57
+ if (!B) return;
58
58
  let e = () => {
59
- D(x.listVoices()), j((e) => e.size === 0 ? e : /* @__PURE__ */ new Map());
59
+ E(b.listVoices()), A((e) => e.size === 0 ? e : /* @__PURE__ */ new Map());
60
60
  };
61
- return e(), x.subscribeVoices(e);
62
- }, [x, V]);
63
- let H = t((e) => e.assistantLanguage), U = t((e) => e.replyLanguage), W = t((e) => e.preferredVoices), G = t((e) => e.setPreferredVoice), K = _(() => ae(H, U, C).reply, [
64
- H,
65
- U,
66
- C
67
- ]), q = K.code, J = m((e) => ie(e)?.tag ?? u(e), []), ge = m((e) => ie(e)?.rate ?? .9, []), Y = _(() => d(V, E, K.tag, O), [
61
+ return e(), b.subscribeVoices(e);
62
+ }, [b, B]);
63
+ let V = t((e) => e.assistantLanguage), ve = t((e) => e.replyLanguage), H = t((e) => e.preferredVoices), U = t((e) => e.setPreferredVoice), W = _(() => oe(V, ve, S).reply, [
68
64
  V,
69
- E,
70
- K,
71
- O
72
- ]), _e = _(() => ({
73
- codeBlock: S("healthybowl.assistant.speech.codeBlock", "Code block"),
74
- image: S("healthybowl.assistant.speech.image", "image"),
75
- link: S("healthybowl.assistant.speech.link", "link"),
76
- largeTable: S("healthybowl.assistant.speech.largeTable", "Table with {{rows}} rows and {{columns}} columns"),
77
- truncated: S("healthybowl.assistant.speech.truncated", "The rest of this message is not read aloud"),
78
- nestedItem: S("healthybowl.assistant.speech.nestedItem", "Sub-item {{ordinal}}"),
79
- emailAt: S("healthybowl.assistant.speech.emailAt", "at"),
80
- emailDot: S("healthybowl.assistant.speech.emailDot", "dot")
81
- }), [S]), X = m(() => {
82
- L(), x.cancel(), T({ type: "stop" });
83
- }, [L, x]), ve = m((e) => {
84
- let t = x.listVoices().find((t) => t.name === e) ?? null;
85
- t && (X(), x.speak([i(q)], {
65
+ ve,
66
+ S
67
+ ]), G = W.code, K = m((e) => ae(e)?.tag ?? u(e), []), q = m((e) => ae(e)?.rate ?? ie, []), J = _(() => d(B, T, W.tag, D), [
68
+ B,
69
+ T,
70
+ W,
71
+ D
72
+ ]), ye = _(() => ({
73
+ codeBlock: x("healthybowl.assistant.speech.codeBlock", "Code block"),
74
+ image: x("healthybowl.assistant.speech.image", "image"),
75
+ link: x("healthybowl.assistant.speech.link", "link"),
76
+ largeTable: x("healthybowl.assistant.speech.largeTable", "Table with {{rows}} rows and {{columns}} columns"),
77
+ truncated: x("healthybowl.assistant.speech.truncated", "The rest of this message is not read aloud"),
78
+ nestedItem: x("healthybowl.assistant.speech.nestedItem", "Sub-item {{ordinal}}"),
79
+ emailAt: x("healthybowl.assistant.speech.emailAt", "at"),
80
+ emailDot: x("healthybowl.assistant.speech.emailDot", "dot")
81
+ }), [x]), Y = m(() => {
82
+ I(), b.cancel(), w({ type: "stop" });
83
+ }, [I, b]), be = m((e) => {
84
+ let t = b.listVoices().find((t) => t.name === e) ?? null;
85
+ t && (Y(), b.speak([i(G)], {
86
86
  voice: t,
87
- lang: J(q)
87
+ lang: K(G)
88
88
  }));
89
89
  }, [
90
- x,
91
- q,
92
- X,
93
- J
94
- ]), ye = m((e) => A.get(e) ?? null, [A]), Z = m((e, t, n) => {
95
- L();
90
+ b,
91
+ G,
92
+ Y,
93
+ K
94
+ ]), xe = m((e) => k.get(e) ?? null, [k]), Se = m((e, t, n) => {
95
+ I();
96
96
  let r = !1, i = () => {}, a = (a) => {
97
97
  if (!r) {
98
- if (r = !0, F.current = null, clearTimeout(o), i(), a.length === 0) {
99
- k(!0);
98
+ if (r = !0, P.current = null, clearTimeout(o), i(), a.length === 0) {
99
+ O(!0);
100
100
  return;
101
101
  }
102
- D(a), I.current(e, t, a, n);
102
+ E(a), F.current(e, t, a, n);
103
103
  }
104
- }, o = setTimeout(() => a(x.listVoices()), c);
105
- i = x.subscribeVoices(() => a(x.listVoices())), F.current = () => {
106
- r || (r = !0, clearTimeout(o), i(), F.current = null);
104
+ }, o = setTimeout(() => a(b.listVoices()), c);
105
+ i = b.subscribeVoices(() => a(b.listVoices())), P.current = () => {
106
+ r || (r = !0, clearTimeout(o), i(), P.current = null);
107
107
  };
108
- }, [L, x]), Q = m((e, t, n, r) => {
108
+ }, [I, b]), X = m((e, t, n, r) => {
109
109
  let i = n;
110
110
  if (i.length === 0) {
111
- let e = x.listVoices();
112
- e.length > 0 && (i = e, D(e));
111
+ let e = b.listVoices();
112
+ e.length > 0 && (i = e, E(e));
113
113
  }
114
- let o = J(r), s = te(d(!0, i, r, O));
114
+ let o = K(r), s = te(d(!0, i, r, D));
115
115
  if (s === "block") {
116
- let t = S("healthybowl.assistant.speech.noVoiceForReply", "This reply is in {{language}}, and no {{language}} voice is installed on this device.", { language: ee(o, C) });
117
- j((n) => new Map(n).set(e, t));
116
+ let t = x("healthybowl.assistant.speech.noVoiceForReply", "This reply is in {{language}}, and no {{language}} voice is installed on this device.", { language: ee(o, S) });
117
+ A((n) => new Map(n).set(e, t));
118
118
  return;
119
119
  }
120
120
  if (s === "wait-for-voices") {
121
- Z(e, t, r);
121
+ Se(e, t, r);
122
122
  return;
123
123
  }
124
- j((t) => {
124
+ A((t) => {
125
125
  if (!t.has(e)) return t;
126
126
  let n = new Map(t);
127
127
  return n.delete(e), n;
128
128
  });
129
- let c = M.current + 1;
130
- M.current = c, T({
129
+ let c = j.current + 1;
130
+ j.current = c, w({
131
131
  type: "start",
132
132
  messageId: e,
133
133
  requestId: c
134
134
  });
135
135
  let u = a(t);
136
- P({
136
+ N({
137
137
  requestId: c,
138
138
  chunks: u,
139
139
  index: -1
140
- }), x.speak(u, {
141
- voice: l(i, o, W[r]),
140
+ }), b.speak(u, {
141
+ voice: l(i, o, H[r]),
142
142
  lang: o,
143
- rate: ge(r)
143
+ rate: q(r)
144
144
  }, {
145
- onChunkStart: (e) => P((t) => t?.requestId === c ? {
145
+ onChunkStart: (e) => N((t) => t?.requestId === c ? {
146
146
  ...t,
147
147
  index: e
148
148
  } : t),
149
- onEnd: () => T({
149
+ onEnd: () => w({
150
150
  type: "finished",
151
151
  requestId: c
152
152
  }),
153
- onError: () => T({
153
+ onError: () => w({
154
154
  type: "failed",
155
155
  requestId: c
156
156
  })
157
157
  });
158
158
  }, [
159
- x,
160
- C,
161
- W,
162
- ge,
163
- J,
159
+ b,
164
160
  S,
165
- O,
166
- Z
161
+ H,
162
+ q,
163
+ K,
164
+ x,
165
+ D,
166
+ Se
167
167
  ]);
168
168
  g(() => {
169
- I.current = Q;
170
- }, [Q]);
171
- let $ = m((e, t, n) => {
172
- if (!V) return;
173
- let r = re(o(t, { labels: pe }), n ?? q), i = o(t, { labels: s(r, _e) });
174
- i && Q(e, i, E, r);
169
+ F.current = X;
170
+ }, [X]);
171
+ let Z = m((e, t, n) => {
172
+ if (!B) return;
173
+ let r = re(o(t, { labels: me }), n ?? G), i = o(t, { labels: s(r, ye) });
174
+ i && X(e, i, T, r);
175
175
  }, [
176
- V,
177
- _e,
178
- q,
179
- Q,
180
- E
181
- ]), be = m((e, t, n) => {
182
- if (f(w, e)) {
183
- X();
176
+ B,
177
+ ye,
178
+ G,
179
+ X,
180
+ T
181
+ ]), Ce = m((e, t, n) => {
182
+ if (f(C, e)) {
183
+ Y();
184
184
  return;
185
185
  }
186
- $(e, t, n);
186
+ Z(e, t, n);
187
187
  }, [
188
- w,
189
- $,
190
- X
188
+ C,
189
+ Z,
190
+ Y
191
191
  ]);
192
192
  g(() => {
193
- h || X();
194
- }, [h, X]), g(() => {
195
- X(), j(/* @__PURE__ */ new Map());
196
- }, [he, X]), g(() => {
197
- j((e) => e.size === 0 ? e : /* @__PURE__ */ new Map()), X();
198
- }, [q, X]), g(() => () => {
199
- F.current?.(), F.current = null, x.cancel();
200
- }, [x]), g(() => {
193
+ h || Y();
194
+ }, [h, Y]), g(() => {
195
+ Y(), A(/* @__PURE__ */ new Map());
196
+ }, [_e, Y]), g(() => {
197
+ A((e) => e.size === 0 ? e : /* @__PURE__ */ new Map()), Y();
198
+ }, [G, Y]), g(() => () => {
199
+ P.current?.(), P.current = null, b.cancel();
200
+ }, [b]), g(() => {
201
201
  if (typeof window > "u") return;
202
- let e = () => x.cancel();
202
+ let e = () => b.cancel();
203
203
  return window.addEventListener("pagehide", e), () => window.removeEventListener("pagehide", e);
204
- }, [x]), g(() => {
205
- if (typeof document > "u" || !V) return;
204
+ }, [b]), g(() => {
205
+ if (typeof document > "u" || !B) return;
206
206
  let e = () => {
207
207
  if (document.visibilityState !== "visible") return;
208
- let e = x.listVoices();
209
- e.length > 0 && L(), D(e), k(!1), j((e) => e.size === 0 ? e : /* @__PURE__ */ new Map());
208
+ let e = b.listVoices();
209
+ e.length > 0 && I(), E(e), O(!1), A((e) => e.size === 0 ? e : /* @__PURE__ */ new Map());
210
210
  };
211
211
  return document.addEventListener("visibilitychange", e), window.addEventListener("focus", e), () => {
212
212
  document.removeEventListener("visibilitychange", e), window.removeEventListener("focus", e);
213
213
  };
214
214
  }, [
215
- L,
216
- x,
217
- V
215
+ I,
216
+ b,
217
+ B
218
218
  ]);
219
- let xe = v($);
219
+ let we = v(Z);
220
220
  g(() => {
221
- xe.current = $;
222
- }, [$]), g(() => {
223
- if (!(!R && !B || !h || !V)) return t.subscribe((e, t) => {
221
+ we.current = Z;
222
+ }, [Z]), g(() => {
223
+ if (!(!L && !z || !h || !B)) return t.subscribe((e, t) => {
224
224
  let n = e.activeConversationId;
225
225
  if (!n || n !== t.activeConversationId) return;
226
226
  let i = e.processingByConversationId[n], a = t.processingByConversationId[n];
227
- if (i?.status !== "complete" || !ce(a?.status)) return;
227
+ if (i?.status !== "complete" || !le(a?.status)) return;
228
228
  let o = i.messageId ?? a?.messageId ?? null;
229
229
  if (!o) return;
230
230
  let s = e.conversations.find((e) => e.id === n)?.messages.find((e) => e.id === o);
231
- if (!s || s.role !== "assistant" || r(s) !== B) return;
232
- let { text: c } = le(s.content);
233
- c.trim() && xe.current(o, c, s.metadata?.lang);
231
+ if (!s || s.role !== "assistant" || r(s) !== z) return;
232
+ let { text: c } = ue(s.content);
233
+ c.trim() && we.current(o, c, s.metadata?.lang);
234
234
  });
235
235
  }, [
236
- R,
236
+ L,
237
+ z,
237
238
  B,
238
- V,
239
239
  h
240
240
  ]);
241
- let Se = _(() => ne(E, K.tag), [E, K]), Ce = _(() => l(E, K.tag, W[q]), [
242
- E,
243
- K,
241
+ let Q = _(() => ne(T, W.tag), [T, W]), $ = _(() => l(T, W.tag, H[G]), [
242
+ T,
244
243
  W,
245
- q
246
- ]), we = _(() => ({
247
- isSupported: V,
248
- availability: Y,
249
- isBlocked: Y === "no-voices",
250
- disabledReason: Y === "no-voices" ? S("healthybowl.assistant.speech.noVoicesOnDevice", "This device has no speech voices installed. Add one in your device speech or accessibility settings.") : null,
251
- blockedFor: ye,
252
- voiceChoices: Se,
253
- spokenChunks: N ? {
254
- chunks: N.chunks,
255
- index: N.index
244
+ H,
245
+ G
246
+ ]), Te = _(() => ({
247
+ isSupported: B,
248
+ availability: J,
249
+ isBlocked: J === "no-voices",
250
+ disabledReason: J === "no-voices" ? x("healthybowl.assistant.speech.noVoicesOnDevice", "This device has no speech voices installed. Add one in your device speech or accessibility settings.") : null,
251
+ blockedFor: xe,
252
+ voiceChoices: Q,
253
+ spokenChunks: M ? {
254
+ chunks: M.chunks,
255
+ index: M.index
256
256
  } : null,
257
- activeVoiceName: Ce?.name ?? null,
258
- preferredVoiceName: W[q] ?? null,
259
- setVoice: (e) => G(q, e),
260
- speakingMessageId: w.status === "speaking" ? w.messageId : null,
261
- isSpeaking: (e) => f(w, e),
262
- toggle: be,
263
- stop: X,
264
- autoSpeakEnabled: R,
265
- setAutoSpeak: z,
266
- sessionSpeaking: B,
267
- setSessionSpeaking: me,
268
- previewVoice: ve
257
+ activeVoiceName: $?.name ?? null,
258
+ preferredVoiceName: H[G] ?? null,
259
+ setVoice: (e) => U(G, e),
260
+ speakingMessageId: C.status === "speaking" ? C.messageId : null,
261
+ isSpeaking: (e) => f(C, e),
262
+ toggle: Ce,
263
+ stop: Y,
264
+ autoSpeakEnabled: L,
265
+ setAutoSpeak: R,
266
+ sessionSpeaking: z,
267
+ setSessionSpeaking: ge,
268
+ previewVoice: be
269
269
  }), [
270
- V,
271
- Y,
272
- ye,
273
- Se,
274
- Ce,
275
- W,
270
+ B,
271
+ J,
272
+ xe,
273
+ Q,
274
+ $,
275
+ H,
276
+ U,
276
277
  G,
277
- q,
278
- w,
279
- be,
280
- X,
278
+ C,
279
+ Ce,
280
+ Y,
281
+ L,
281
282
  R,
282
283
  z,
283
- B,
284
- ve,
285
- S
284
+ be,
285
+ x
286
286
  ]);
287
- return /* @__PURE__ */ fe(b.Provider, {
288
- value: we,
287
+ return /* @__PURE__ */ pe(he.Provider, {
288
+ value: Te,
289
289
  children: p
290
290
  });
291
291
  };
292
292
  //#endregion
293
- export { S as AssistantSpeechProvider, x as useAssistantSpeech };
293
+ export { x as AssistantSpeechProvider, b as useAssistantSpeech };
294
294
 
295
295
  //# sourceMappingURL=AssistantSpeechProvider.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantSpeechProvider.js","names":[],"sources":["../../../src/components/assistant/AssistantSpeechProvider.tsx"],"sourcesContent":["/**\n * Speech-output context for the assistant panel (BOFF-6290).\n *\n * The assistant could already hear (`useVoiceInput`); this is the other half —\n * it can now answer out loud. That matters for a farming product where the user\n * is outdoors with dirty hands, a phone in a pocket and sun on the screen, and\n * it is a plain accessibility win everywhere else.\n *\n * Everything stateful about playback lives here, once, so that:\n *\n * - **playback is never orphaned.** A voice that keeps talking after the UI is\n * gone is a bug, so speech is cancelled when the panel hides, when the\n * conversation changes, on unmount, and on `pagehide` (Chrome keeps speaking\n * across a navigation otherwise);\n * - **only one message speaks at a time.** Starting a new playback cancels the\n * previous one — enforced by the engine and by the request-id guard in\n * `speechPlaybackReducer`;\n * - **nothing ever autoplays.** Playback starts from a button press. The\n * persisted auto-speak preference defaults OFF and is opt-in from the header.\n *\n * Components consume this through `useAssistantSpeech()`, which falls back to an\n * inert value when there is no provider (Storybook, a header rendered on its\n * own) rather than throwing.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type FC,\n type ReactNode,\n} from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { voicePreviewText } from '@/utils/voicePreview';\nimport { getSpeechEngine } from '../../services/speech';\nimport type { SpeechEngine, SpeechVoiceLike } from '../../services/speech';\nimport { chunkForSpeech, toSpeakableText, type SpeakableLabels } from '../../utils/speakableText';\nimport { speechLabelsFor } from '../../config/speechLabels';\n\n/**\n * The speakable transformation with nothing of ours added — used ONLY to decide\n * the reply's language.\n *\n * Detection needs the prose that will be spoken: code blocks and URLs stripped\n * (they are never read aloud, and their Latin identifiers would outvote short\n * non-Latin prose), but no substitute wording introduced either (that would let\n * our own app-locale words vote instead).\n */\nconst SILENT_LABELS: SpeakableLabels = {\n codeBlock: '',\n image: '',\n link: '',\n largeTable: '',\n truncated: '',\n emailAt: 'at',\n emailDot: 'dot',\n nestedItem: '',\n};\nimport {\n VOICE_LIST_TIMEOUT_MS,\n languageDisplayName,\n selectVoiceForLocale,\n voicesForLocale,\n speechGate,\n speechLangForLocale,\n voiceAvailability,\n type VoiceAvailability,\n} from '../../utils/speechVoices';\nimport { resolveSpeechLocale } from '../../utils/replyLanguage';\nimport { DEFAULT_SPEECH_RATE, findAssistantLanguage } from '../../config/assistantLanguages';\nimport { resolveLanguagePair } from '../../config/assistantLanguagePair';\nimport { IDLE_PLAYBACK, isSpeakingMessage, speechPlaybackReducer } from '../../utils/speechPlayback';\nimport { isVoiceTurn } from '../../utils/voiceTurnVisibility';\nimport { isTurnInFlight } from '../../utils/assistantTurnState';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport interface AssistantSpeechContextValue {\n /** False when the platform has no speech output — hide the control entirely. */\n isSupported: boolean;\n availability: VoiceAvailability;\n /**\n * True when nothing can be spoken in the app language, so every control that\n * starts playback — the per-message button AND the header toggle — must be\n * inert. `pending` is not blocked: see `speechGate`.\n */\n isBlocked: boolean;\n /** Explains a disabled control (no installed voice for the app language). */\n disabledReason: string | null;\n /**\n * Why THIS message cannot be spoken, when the app language is fine but the\n * reply is not in it — a Tamil answer in an English UI on a device with no\n * Tamil voice. `isBlocked` cannot see that: it is computed before any reply\n * exists. Without this the control looks enabled and silently refuses, which\n * is the dead-button bug all over again (BOFF-7106).\n */\n blockedFor: (messageId: string) => string | null;\n /**\n * Every installed voice that can read the language the user speaks, best\n * first. Empty when there is no choice to offer — the picker hides itself\n * rather than showing a one-item dropdown.\n */\n voiceChoices: readonly SpeechVoiceLike[];\n /** The voice that will actually be used, resolved from the pick + ranking. */\n /**\n * The reply as it is being SPOKEN: every chunk, plus the one sounding now.\n *\n * `null` when nothing is playing. `index: -1` means chunked but not yet\n * audible. Consumers reveal `chunks[0..index]` — anything beyond that is the\n * caption running ahead of the voice.\n */\n spokenChunks: { chunks: string[]; index: number } | null;\n activeVoiceName: string | null;\n /**\n * The RAW stored pick: `null` means \"use the ranked default\".\n *\n * The picker must be driven by this rather than by `activeVoiceName`, or the\n * two states collapse — with nothing stored, the ranked winner is already the\n * shown option, so choosing it fires no change event and the pick can never\n * be made. The user's voice would then silently move the next time the device\n * installs a higher-ranked one. Same trap as the language selector.\n */\n preferredVoiceName: string | null;\n /** `null` restores the ranked default for the current language. */\n setVoice: (voiceName: string | null) => void;\n /** The message currently being spoken, if any. */\n speakingMessageId: string | null;\n isSpeaking: (messageId: string) => boolean;\n /**\n * Speak this message, or stop if it is already the one speaking.\n *\n * `turnLocale` is the language the reply was GENERATED under, from the\n * message's own metadata. It matters because script detection cannot separate\n * Latin-script languages, so without it an old French reply would be read\n * with whatever voice the CURRENT preference selects.\n */\n toggle: (messageId: string, markdown: string, turnLocale?: string) => void;\n stop: () => void;\n autoSpeakEnabled: boolean;\n setAutoSpeak: (enabled: boolean) => void;\n /**\n * Speak replies for the duration of a live voice session, WITHOUT touching the\n * user's saved preference.\n *\n * ★ Live Voice used to force `autoSpeakEnabled` true and restore it on exit.\n * That field is PERSISTED (assistantStore partialize), and the restore only\n * ran on a clean `end()` — so a reload, a closed tab or a backgrounded webview\n * during a session left auto-speak switched ON for the user permanently, in\n * normal typed chat, with the toggle showing a state they never chose. The\n * default was never wrong; the session was overwriting it.\n *\n * Session-scoped React state instead: it cannot outlive the page, so there is\n * nothing to restore and nothing to leak.\n */\n sessionSpeaking: boolean;\n setSessionSpeaking: (enabled: boolean) => void;\n /** Play a short sample in a named voice. No model call, no message, no tokens. */\n previewVoice: (voiceName: string) => void;\n}\n\nconst INERT_SPEECH: AssistantSpeechContextValue = {\n isSupported: false,\n availability: 'unsupported',\n isBlocked: true,\n disabledReason: null,\n blockedFor: () => null,\n voiceChoices: [],\n spokenChunks: null,\n activeVoiceName: null,\n preferredVoiceName: null,\n setVoice: () => {},\n speakingMessageId: null,\n isSpeaking: () => false,\n toggle: () => {},\n stop: () => {},\n autoSpeakEnabled: false,\n setAutoSpeak: () => {},\n sessionSpeaking: false,\n setSessionSpeaking: () => {},\n previewVoice: () => {},\n};\n\nconst AssistantSpeechContext = createContext<AssistantSpeechContextValue>(INERT_SPEECH);\n\nexport function useAssistantSpeech(): AssistantSpeechContextValue {\n return useContext(AssistantSpeechContext);\n}\n\ninterface Props {\n children: ReactNode;\n /** Panel visibility. Hiding the panel stops the voice. */\n visible?: boolean;\n /**\n * Injectable for tests and local experiments. The default routes between the\n * device engine and the hosted one; with hosted TTS unconfigured it IS the\n * device engine, unchanged.\n */\n engine?: SpeechEngine;\n}\n\nexport const AssistantSpeechProvider: FC<Props> = ({ children, visible = true, engine = getSpeechEngine() }) => {\n const tr = useTr();\n const { locale } = useI18n();\n const [playback, dispatch] = useReducer(speechPlaybackReducer, IDLE_PLAYBACK);\n const [voices, setVoices] = useState<SpeechVoiceLike[]>(() => engine.listVoices());\n /**\n * True once we have waited out the voice list and it was still empty.\n *\n * Turns an indefinite `pending` into a terminal `no-voices`, which is what\n * lets the control be disabled with a reason instead of silently doing\n * nothing on every press.\n */\n const [voiceProbeSettled, setVoiceProbeSettled] = useState(false);\n /**\n * Every message we have refused, and why — keyed by id (see `blockedFor`).\n *\n * A single record could only describe one refusal: refusing a second reply\n * silently re-enabled the first, whose voice was still just as missing, so\n * pressing the buttons walked the disabled state around the transcript.\n */\n const [unspeakable, setUnspeakable] = useState<ReadonlyMap<string, string>>(() => new Map());\n const requestRef = useRef(0);\n\n /**\n * Which chunk of the current reply is sounding right now.\n *\n * ★ `index: -1` means \"chunked, nothing playing yet\" — distinct from no\n * progress at all, so the caption can stay empty until audio genuinely starts\n * instead of flashing the first sentence while the engine is still fetching.\n */\n const [spokenProgress, setSpokenProgress] = useState<{\n requestId: number;\n chunks: string[];\n index: number;\n } | null>(null);\n /** Cancels a playback that is waiting for the engine's voice list, if any. */\n const pendingRef = useRef<(() => void) | null>(null);\n const speakWithRef = useRef<\n (messageId: string, text: string, voices: readonly SpeechVoiceLike[], speechLocale: string) => void\n >(() => {});\n\n const cancelPending = useCallback(() => {\n pendingRef.current?.();\n pendingRef.current = null;\n }, []);\n\n const autoSpeakEnabled = useAssistantStore((state) => state.autoSpeakEnabled);\n const setAutoSpeak = useAssistantStore((state) => state.setAutoSpeak);\n // Not in the store on purpose — see `sessionSpeaking` on the context type.\n const [sessionSpeaking, setSessionSpeaking] = useState(false);\n const activeConversationId = useAssistantStore((state) => state.activeConversationId);\n\n const isSupported = useMemo(() => engine.isSupported(), [engine]);\n\n // getVoices() is empty on the first call in Chrome and only fills in when\n // 'voiceschanged' fires; Safari populates it synchronously and may never fire\n // the event. Read eagerly AND subscribe, so both engines end up correct.\n useEffect(() => {\n if (!isSupported) return;\n const sync = () => {\n setVoices(engine.listVoices());\n // Every recorded refusal was \"no voice for this language\". A new voice\n // list may well have supplied one — most likely because the user just\n // followed our instructions and installed it. Keeping the refusals would\n // leave those buttons disabled with no way back except a reload.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n sync();\n return engine.subscribeVoices(sync);\n }, [engine, isSupported]);\n\n // The language being SPOKEN ALOUD — which is the language of the reply, not\n // of the input and not of the interface. The two were one field until the\n // reply language was split out (BOFF-7108).\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const replyLanguage = useAssistantStore((state) => state.replyLanguage);\n const preferredVoices = useAssistantStore((state) => state.preferredVoices);\n const setPreferredVoice = useAssistantStore((state) => state.setPreferredVoice);\n const spokenLanguage = useMemo(\n // ★ The REPLY language, not the input. This is the language of the text\n // being spoken, so wiring it to the input would give a Tamil voice reading\n // an English answer the moment the two are set differently — the single\n // worst outcome available here, and the reason they were split at all.\n () => resolveLanguagePair(assistantLanguage, replyLanguage, locale).reply,\n [assistantLanguage, replyLanguage, locale]\n );\n const spokenLocale = spokenLanguage.code;\n\n /**\n * BCP-47 tag to ask the engine for, given a resolved language CODE.\n *\n * Resolved through the catalogue for ANY known code, not merely the currently\n * selected one — a historical Bengali reply must still get `bn-IN` after the\n * user switches to Tamil, or with both `bn-IN` and `bn-BD` installed the\n * engine's own order decides, and picks the wrong country.\n *\n * Falls back to the generic table for codes the catalogue does not carry.\n */\n const tagFor = useCallback((code: string) => findAssistantLanguage(code)?.tag ?? speechLangForLocale(code), []);\n\n /** Speaking rate for a resolved language code — see `AssistantLanguage.rate`. */\n const rateFor = useCallback((code: string) => findAssistantLanguage(code)?.rate ?? DEFAULT_SPEECH_RATE, []);\n\n const availability = useMemo(\n () => voiceAvailability(isSupported, voices, spokenLanguage.tag, voiceProbeSettled),\n [isSupported, voices, spokenLanguage, voiceProbeSettled]\n );\n\n // Spoken placeholders follow the app locale like the rest of the copy; the\n // transformation itself stays a pure function by taking them as arguments.\n const labels = useMemo<SpeakableLabels>(\n () => ({\n codeBlock: tr('healthybowl.assistant.speech.codeBlock', 'Code block'),\n image: tr('healthybowl.assistant.speech.image', 'image'),\n link: tr('healthybowl.assistant.speech.link', 'link'),\n largeTable: tr('healthybowl.assistant.speech.largeTable', 'Table with {{rows}} rows and {{columns}} columns'),\n truncated: tr('healthybowl.assistant.speech.truncated', 'The rest of this message is not read aloud'),\n nestedItem: tr('healthybowl.assistant.speech.nestedItem', 'Sub-item {{ordinal}}'),\n emailAt: tr('healthybowl.assistant.speech.emailAt', 'at'),\n emailDot: tr('healthybowl.assistant.speech.emailDot', 'dot'),\n }),\n [tr]\n );\n\n const stop = useCallback(() => {\n cancelPending();\n engine.cancel();\n dispatch({ type: 'stop' });\n }, [cancelPending, engine]);\n\n /**\n * Audition a voice — no model call, no message, no tokens.\n *\n * ★ Speaks through the engine DIRECTLY rather than through `speakWith`. That\n * path is built around a message: it resolves the reply's language, records\n * per-message \"cannot speak this\" state, and drives `speakingMessageId` so a\n * Listen button can light up. A preview has no message, so borrowing it would\n * mean inventing a fake id and then teaching every consumer to ignore it.\n *\n * Consequently it deliberately does NOT touch playback state: auditioning a\n * voice must not make a Listen button in the thread appear to be playing.\n *\n * Speaks the sample in the language being spoken, not the interface language —\n * the listener is judging how this voice reads THAT language.\n */\n const previewVoice = useCallback(\n (voiceName: string) => {\n const voice = engine.listVoices().find((candidate) => candidate.name === voiceName) ?? null;\n // An unknown name means the list changed under us (a download finished, a\n // profile switched). Silence is the right answer — better than falling\n // back to some other voice and auditioning the wrong one.\n if (!voice) return;\n // Whatever is speaking now is not what the user asked to hear.\n stop();\n engine.speak([voicePreviewText(spokenLocale)], { voice, lang: tagFor(spokenLocale) });\n },\n [engine, spokenLocale, stop, tagFor]\n );\n\n const blockedFor = useCallback((messageId: string) => unspeakable.get(messageId) ?? null, [unspeakable]);\n\n /**\n * Hold one playback until the engine publishes its voice list.\n *\n * Bounded: on timeout we take one last look and decide with whatever is\n * there, so an engine that never fires `voiceschanged` costs a two-second\n * wait rather than a control that is disabled forever. Nothing is spoken from\n * here unless a list actually arrives — an empty list means the engine would\n * pick its own default voice, which is the cross-language read this feature\n * promises never to do.\n */\n const waitForVoices = useCallback(\n (messageId: string, text: string, speechLocale: string) => {\n cancelPending();\n\n let settled = false;\n let unsubscribe = () => {};\n const finish = (available: SpeechVoiceLike[]) => {\n if (settled) return;\n settled = true;\n pendingRef.current = null;\n clearTimeout(timer);\n unsubscribe();\n if (available.length === 0) {\n // We waited and looked again: this device has no voices at all.\n // Record it so `availability` becomes `no-voices` and the control\n // explains itself, instead of returning silently every press.\n setVoiceProbeSettled(true);\n return;\n }\n setVoices(available);\n speakWithRef.current(messageId, text, available, speechLocale);\n };\n\n const timer = setTimeout(() => finish(engine.listVoices()), VOICE_LIST_TIMEOUT_MS);\n unsubscribe = engine.subscribeVoices(() => finish(engine.listVoices()));\n\n pendingRef.current = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n unsubscribe();\n pendingRef.current = null;\n };\n },\n [cancelPending, engine]\n );\n\n /**\n * Speak text against a KNOWN voice list.\n *\n * Every playback path funnels through here — the per-message button, the\n * header toggle's auto-speak, the store subscription — so the language gate\n * cannot be bypassed by any of them. Reading a Tamil reply with an English\n * voice is confident nonsense; it has to be impossible, not merely unlikely.\n */\n const speakWith = useCallback(\n (messageId: string, text: string, available: readonly SpeechVoiceLike[], speechLocale: string) => {\n let known = available;\n\n // Chrome answers the FIRST getVoices() with [] and fills the list in\n // asynchronously. One more synchronous read usually settles it.\n if (known.length === 0) {\n const refreshed = engine.listVoices();\n if (refreshed.length > 0) {\n known = refreshed;\n setVoices(refreshed);\n }\n }\n\n const speechLang = tagFor(speechLocale);\n\n const gate = speechGate(voiceAvailability(true, known, speechLocale, voiceProbeSettled));\n if (gate === 'block') {\n // Recorded for THIS message, always. Availability is resolved per reply\n // now, so a global \"your language has no voice\" cannot stand in for it:\n // the language the user chose to converse in says nothing about the one\n // this particular reply came back in.\n const reason = tr(\n 'healthybowl.assistant.speech.noVoiceForReply',\n 'This reply is in {{language}}, and no {{language}} voice is installed on this device.',\n { language: languageDisplayName(speechLang, locale) }\n );\n setUnspeakable((current) => new Map(current).set(messageId, reason));\n return;\n }\n if (gate === 'wait-for-voices') {\n waitForVoices(messageId, text, speechLocale);\n return;\n }\n\n setUnspeakable((current) => {\n if (!current.has(messageId)) return current;\n const next = new Map(current);\n next.delete(messageId);\n return next;\n });\n\n const requestId = requestRef.current + 1;\n requestRef.current = requestId;\n dispatch({ type: 'start', messageId, requestId });\n\n // ★ Chunked ONCE and kept, so the caption can show exactly what is being\n // spoken rather than a parallel rendering of the same markdown. A live\n // caption whose words differ from the audio is not a caption.\n const chunks = chunkForSpeech(text);\n setSpokenProgress({ requestId, chunks, index: -1 });\n\n engine.speak(\n chunks,\n // The TAG, not the code — so exact regional matching gets its chance\n // before the same-language fallback. `rate` had never been passed at\n // all, so every reply was read at the engine default.\n {\n voice: selectVoiceForLocale(known, speechLang, preferredVoices[speechLocale]),\n lang: speechLang,\n rate: rateFor(speechLocale),\n },\n {\n // Guarded on the request id like every other handler here: a stale\n // batch that has not noticed its cancellation must not drive the\n // caption of the reply that replaced it.\n onChunkStart: (index) =>\n setSpokenProgress((current) => (current?.requestId === requestId ? { ...current, index } : current)),\n onEnd: () => dispatch({ type: 'finished', requestId }),\n // Includes the 'cancelled' every queued utterance reports when we\n // pre-empt a batch; the request-id guard drops those as stale.\n onError: () => dispatch({ type: 'failed', requestId }),\n }\n );\n },\n [engine, locale, preferredVoices, rateFor, tagFor, tr, voiceProbeSettled, waitForVoices]\n );\n\n // `waitForVoices` resumes through this ref, so the two do not become a\n // circular hook dependency.\n useEffect(() => {\n speakWithRef.current = speakWith;\n }, [speakWith]);\n\n const speak = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (!isSupported) return;\n\n // Resolve the reply's language BEFORE building the spoken text, because\n // the stand-in words must be in that language. Detection deliberately runs\n // on a SILENT_LABELS pass — our own words must not vote on which language\n // the reply is in — so it does not depend on the labels chosen here.\n const replyLocale = resolveSpeechLocale(\n toSpeakableText(markdown, { labels: SILENT_LABELS }),\n turnLocale ?? spokenLocale\n );\n\n // ★ Labels in the REPLY's language, not the interface's. An English\n // interface reading a Tamil answer used to say \"Code block\" and \"image\" in\n // English, mid-Tamil-sentence — the same defect the email `at`/`dot` fix\n // addressed and did not generalise.\n const text = toSpeakableText(markdown, { labels: speechLabelsFor(replyLocale, labels) });\n if (!text) return;\n\n // Detect on the text that will actually be SPOKEN, with our own words\n // removed — neither the raw markdown nor the finished transformation.\n //\n // The transformation injects app-locale placeholders (\"Code block\"), which\n // let English chrome outvote short non-Latin prose. The raw markdown keeps\n // fenced code, whose Latin identifiers do the same thing — and that code is\n // never spoken at all. Running the same transformation with EMPTY labels\n // strips the unspoken constructs while contributing no words of its own,\n // which is exactly the denominator the decision needs.\n // The turn's OWN language first — the preference is only a stand-in for\n // replies that predate it. Resolved above, and reused rather than\n // recomputed.\n speakWith(messageId, text, voices, replyLocale);\n },\n [isSupported, labels, spokenLocale, speakWith, voices]\n );\n\n const toggle = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (isSpeakingMessage(playback, messageId)) {\n stop();\n return;\n }\n speak(messageId, markdown, turnLocale);\n },\n [playback, speak, stop]\n );\n\n // ── Never leave a voice talking to an empty room ─────────────────────────\n useEffect(() => {\n if (!visible) stop();\n }, [visible, stop]);\n\n useEffect(() => {\n // Switching (or creating) a conversation abandons the reply being read —\n // and the refusal explained a message that is no longer on screen.\n stop();\n setUnspeakable(new Map());\n }, [activeConversationId, stop]);\n\n useEffect(() => {\n // Every refusal was decided against the locale in force at the time, which\n // is what a Latin-script reply falls back to. Change the locale and those\n // verdicts may simply be wrong — an English reply refused on a\n // Spanish-only device would stay disabled forever after switching the UI to\n // Spanish, with the voice that could read it already installed.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n // And stop anything mid-sentence. The new language can make this message\n // unspeakable, which disables its button — leaving it reading \"Stop\" with no\n // way to actually stop, short of closing the panel.\n stop();\n }, [spokenLocale, stop]);\n\n useEffect(() => {\n return () => {\n pendingRef.current?.();\n pendingRef.current = null;\n engine.cancel();\n };\n }, [engine]);\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n // Chrome carries speech across a same-tab navigation and a bfcache restore\n // would otherwise come back mid-sentence.\n const handlePageHide = () => engine.cancel();\n window.addEventListener('pagehide', handlePageHide);\n return () => window.removeEventListener('pagehide', handlePageHide);\n }, [engine]);\n\n // ── One timeout is not a life sentence ───────────────────────────────────\n //\n // `no-voices` disables the control, and a disabled control can never reach\n // `speakWith` — the only path that re-reads `engine.listVoices()`. So without\n // this, a user who follows our own advice, leaves to install a voice and comes\n // back stays blocked until a reload: we would be telling them how to fix it\n // and then refusing to notice that they had.\n //\n // Returning to the tab is exactly when that happens, and it costs one\n // synchronous read of an already-populated list.\n useEffect(() => {\n if (typeof document === 'undefined' || !isSupported) return;\n const reprobe = () => {\n if (document.visibilityState !== 'visible') return;\n // Adopt the list UNCONDITIONALLY, including an empty one. Keeping the old\n // cache on an empty read means a user who uninstalled their last voice\n // stays `ready`, and playback then hands the engine a voice object that no\n // longer exists instead of explaining the problem.\n //\n // Safe to accept an empty read here precisely because the probe verdict is\n // cleared on the next line: empty + unsettled is `pending`, which leaves\n // the control ENABLED and defers the real decision to the next press.\n const available = engine.listVoices();\n // A Listen press may still be inside its two-second wait. Adopting voices\n // here flips the control to `ready`, so the user can press again and start\n // playback — and then the original timer fires, calls back into\n // `speakWith` for the same message, and the engine cancels and restarts it\n // mid-sentence. Retire the waiter as part of adopting the list.\n if (available.length > 0) cancelPending();\n setVoices(available);\n setVoiceProbeSettled(false);\n // Same reason the `voiceschanged` path clears them: every refusal meant\n // \"no voice for this language\", and this is the moment a user who went\n // away to install one comes back. `subscribeVoices` does not fire on an\n // eventless engine, which is precisely why this re-probe exists — so it\n // has to expire the refusals too.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n document.addEventListener('visibilitychange', reprobe);\n window.addEventListener('focus', reprobe);\n return () => {\n document.removeEventListener('visibilitychange', reprobe);\n window.removeEventListener('focus', reprobe);\n };\n }, [cancelPending, engine, isSupported]);\n\n // ── Opt-in auto-speak ────────────────────────────────────────────────────\n const speakRef = useRef(speak);\n useEffect(() => {\n speakRef.current = speak;\n }, [speak]);\n\n useEffect(() => {\n // `isBlocked` is the same gate the per-message button uses. Without it the\n // subscription fires on a device with no voice for the app language and the\n // engine reads a Tamil reply in English — the one thing this feature says\n // it will never do. `pending` is allowed through because `speakWith` waits\n // for the list before deciding.\n // NOT gated on `isSpeechBlocked(availability)` any more: that is the APP\n // language's availability, and it would suppress auto-speak for a reply in\n // a language this device CAN speak. `speakWith` resolves the reply's own\n // language and refuses safely there, which is the only place that can know.\n // Either the user's own preference, or a live voice session — which speaks\n // by definition and must not have to change that preference to do it.\n if ((!autoSpeakEnabled && !sessionSpeaking) || !visible || !isSupported) return;\n\n // Deliberately a store subscription keyed on the processing TRANSITION\n // rather than an effect over the message list: it fires only on the\n // in-flight → complete edge of the active conversation, so mounting the\n // panel, loading history or switching chats can never start talking.\n return useAssistantStore.subscribe((next, previous) => {\n const conversationId = next.activeConversationId;\n if (!conversationId || conversationId !== previous.activeConversationId) return;\n\n const current = next.processingByConversationId[conversationId];\n const before = previous.processingByConversationId[conversationId];\n if (current?.status !== 'complete' || !isTurnInFlight(before?.status)) return;\n\n const messageId = current.messageId ?? before?.messageId ?? null;\n if (!messageId) return;\n\n const message = next.conversations\n .find((conversation) => conversation.id === conversationId)\n ?.messages.find((candidate) => candidate.id === messageId);\n if (!message || message.role !== 'assistant') return;\n\n // ★ Speak a turn only if it belongs to the surface currently doing the\n // speaking. This subscription IS the live session's audio path —\n // `useVoiceSession` never calls `speak` itself, it flips `sessionSpeaking`\n // and lets this fire — and it had no channel check, so a TYPED reply\n // completing mid-session was read aloud as the answer to a spoken\n // question. Reachable with no typing at all: a host page queues work\n // through `pendingPrompt`, which is store-driven and fires past the voice\n // overlay.\n //\n // The mirror case matters too: after End, a reply still in flight must not\n // be spoken by ordinary auto-read — the user closed the conversation.\n if (isVoiceTurn(message) !== sessionSpeaking) return;\n\n // Same split the transcript uses: speak the prose, not the tool log.\n const { text } = parseToolActivity(message.content);\n if (!text.trim()) return;\n\n speakRef.current(messageId, text, (message.metadata as { lang?: string } | undefined)?.lang);\n });\n }, [autoSpeakEnabled, sessionSpeaking, isSupported, visible]);\n\n // The candidates for the language the user SPEAKS — the picker is a setting,\n // so it must not follow whatever language the last reply happened to be in.\n const voiceChoices = useMemo(() => voicesForLocale(voices, spokenLanguage.tag), [voices, spokenLanguage]);\n const activeVoice = useMemo(\n () => selectVoiceForLocale(voices, spokenLanguage.tag, preferredVoices[spokenLocale]),\n [voices, spokenLanguage, preferredVoices, spokenLocale]\n );\n\n const value = useMemo<AssistantSpeechContextValue>(\n () => ({\n isSupported,\n availability,\n // ONLY `no-voices` — a device with no voices at all can never speak\n // anything. `missing-voice` means the APP language has none, which says\n // nothing about the language a given reply came back in; that case is\n // resolved per message by `blockedFor`.\n isBlocked: availability === 'no-voices',\n // Both blocked states are the user's device, not our bug — so the copy\n // names the language and says where to fix it. \"Nothing happened\" was\n // the old behaviour and it read as a broken feature.\n disabledReason:\n availability === 'no-voices'\n ? tr(\n 'healthybowl.assistant.speech.noVoicesOnDevice',\n 'This device has no speech voices installed. Add one in your device speech or accessibility settings.'\n )\n : null,\n blockedFor,\n voiceChoices,\n spokenChunks: spokenProgress ? { chunks: spokenProgress.chunks, index: spokenProgress.index } : null,\n activeVoiceName: activeVoice?.name ?? null,\n preferredVoiceName: preferredVoices[spokenLocale] ?? null,\n setVoice: (voiceName: string | null) => setPreferredVoice(spokenLocale, voiceName),\n speakingMessageId: playback.status === 'speaking' ? playback.messageId : null,\n isSpeaking: (messageId: string) => isSpeakingMessage(playback, messageId),\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n setSessionSpeaking,\n previewVoice,\n }),\n [\n isSupported,\n availability,\n blockedFor,\n voiceChoices,\n activeVoice,\n preferredVoices,\n setPreferredVoice,\n spokenLocale,\n playback,\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n previewVoice,\n tr,\n ]\n );\n\n return <AssistantSpeechContext.Provider value={value}>{children}</AssistantSpeechContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsDA,IAAM,KAAiC;CACrC,WAAW;CACX,OAAO;CACP,MAAM;CACN,YAAY;CACZ,WAAW;CACX,SAAS;CACT,UAAU;CACV,YAAY;AACd,GA6HM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S,YAAY;EACzE,aAAa,MAAsB,EAAkB,GAAU,CAAS;EACxE;EACA;EACA;EACA;EACA;EACA;EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,OAAO,mBAAC,EAAuB,UAAxB;EAAwC;EAAQ;CAA0C,CAAA;AACnG"}
1
+ {"version":3,"file":"AssistantSpeechProvider.js","names":[],"sources":["../../../src/components/assistant/AssistantSpeechProvider.tsx"],"sourcesContent":["/**\n * Speech-output context for the assistant panel (BOFF-6290).\n *\n * The assistant could already hear (`useVoiceInput`); this is the other half —\n * it can now answer out loud. That matters for a farming product where the user\n * is outdoors with dirty hands, a phone in a pocket and sun on the screen, and\n * it is a plain accessibility win everywhere else.\n *\n * Everything stateful about playback lives here, once, so that:\n *\n * - **playback is never orphaned.** A voice that keeps talking after the UI is\n * gone is a bug, so speech is cancelled when the panel hides, when the\n * conversation changes, on unmount, and on `pagehide` (Chrome keeps speaking\n * across a navigation otherwise);\n * - **only one message speaks at a time.** Starting a new playback cancels the\n * previous one — enforced by the engine and by the request-id guard in\n * `speechPlaybackReducer`;\n * - **nothing ever autoplays.** Playback starts from a button press. The\n * persisted auto-speak preference defaults OFF and is opt-in from the header.\n *\n * Components consume this through `useAssistantSpeech()`, which falls back to an\n * inert value when there is no provider (Storybook, a header rendered on its\n * own) rather than throwing.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type FC,\n type ReactNode,\n} from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { voicePreviewText } from '@/utils/voicePreview';\nimport { getSpeechEngine } from '../../services/speech';\nimport type { SpeechEngine, SpeechVoiceLike } from '../../services/speech';\nimport { chunkForSpeech, toSpeakableText, type SpeakableLabels } from '../../utils/speakableText';\nimport { speechLabelsFor } from '../../config/speechLabels';\n\n/**\n * The speakable transformation with nothing of ours added — used ONLY to decide\n * the reply's language.\n *\n * Detection needs the prose that will be spoken: code blocks and URLs stripped\n * (they are never read aloud, and their Latin identifiers would outvote short\n * non-Latin prose), but no substitute wording introduced either (that would let\n * our own app-locale words vote instead).\n */\nconst SILENT_LABELS: SpeakableLabels = {\n codeBlock: '',\n image: '',\n link: '',\n largeTable: '',\n truncated: '',\n emailAt: 'at',\n emailDot: 'dot',\n nestedItem: '',\n};\nimport {\n VOICE_LIST_TIMEOUT_MS,\n languageDisplayName,\n selectVoiceForLocale,\n voicesForLocale,\n speechGate,\n speechLangForLocale,\n voiceAvailability,\n type VoiceAvailability,\n} from '../../utils/speechVoices';\nimport { resolveSpeechLocale } from '../../utils/replyLanguage';\nimport { DEFAULT_SPEECH_RATE, findAssistantLanguage } from '../../config/assistantLanguages';\nimport { resolveLanguagePair } from '../../config/assistantLanguagePair';\nimport { IDLE_PLAYBACK, isSpeakingMessage, speechPlaybackReducer } from '../../utils/speechPlayback';\nimport { isVoiceTurn } from '../../utils/voiceTurnVisibility';\nimport { isTurnInFlight } from '../../utils/assistantTurnState';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport interface AssistantSpeechContextValue {\n /** False when the platform has no speech output — hide the control entirely. */\n isSupported: boolean;\n availability: VoiceAvailability;\n /**\n * True when nothing can be spoken in the app language, so every control that\n * starts playback — the per-message button AND the header toggle — must be\n * inert. `pending` is not blocked: see `speechGate`.\n */\n isBlocked: boolean;\n /** Explains a disabled control (no installed voice for the app language). */\n disabledReason: string | null;\n /**\n * Why THIS message cannot be spoken, when the app language is fine but the\n * reply is not in it — a Tamil answer in an English UI on a device with no\n * Tamil voice. `isBlocked` cannot see that: it is computed before any reply\n * exists. Without this the control looks enabled and silently refuses, which\n * is the dead-button bug all over again (BOFF-7106).\n */\n blockedFor: (messageId: string) => string | null;\n /**\n * Every installed voice that can read the language the user speaks, best\n * first. Empty when there is no choice to offer — the picker hides itself\n * rather than showing a one-item dropdown.\n */\n voiceChoices: readonly SpeechVoiceLike[];\n /** The voice that will actually be used, resolved from the pick + ranking. */\n /**\n * The reply as it is being SPOKEN: every chunk, plus the one sounding now.\n *\n * `null` when nothing is playing. `index: -1` means chunked but not yet\n * audible. Consumers reveal `chunks[0..index]` — anything beyond that is the\n * caption running ahead of the voice.\n */\n spokenChunks: { chunks: string[]; index: number } | null;\n activeVoiceName: string | null;\n /**\n * The RAW stored pick: `null` means \"use the ranked default\".\n *\n * The picker must be driven by this rather than by `activeVoiceName`, or the\n * two states collapse — with nothing stored, the ranked winner is already the\n * shown option, so choosing it fires no change event and the pick can never\n * be made. The user's voice would then silently move the next time the device\n * installs a higher-ranked one. Same trap as the language selector.\n */\n preferredVoiceName: string | null;\n /** `null` restores the ranked default for the current language. */\n setVoice: (voiceName: string | null) => void;\n /** The message currently being spoken, if any. */\n speakingMessageId: string | null;\n isSpeaking: (messageId: string) => boolean;\n /**\n * Speak this message, or stop if it is already the one speaking.\n *\n * `turnLocale` is the language the reply was GENERATED under, from the\n * message's own metadata. It matters because script detection cannot separate\n * Latin-script languages, so without it an old French reply would be read\n * with whatever voice the CURRENT preference selects.\n */\n toggle: (messageId: string, markdown: string, turnLocale?: string) => void;\n stop: () => void;\n autoSpeakEnabled: boolean;\n setAutoSpeak: (enabled: boolean) => void;\n /**\n * Speak replies for the duration of a live voice session, WITHOUT touching the\n * user's saved preference.\n *\n * ★ Live Voice used to force `autoSpeakEnabled` true and restore it on exit.\n * That field is PERSISTED (assistantStore partialize), and the restore only\n * ran on a clean `end()` — so a reload, a closed tab or a backgrounded webview\n * during a session left auto-speak switched ON for the user permanently, in\n * normal typed chat, with the toggle showing a state they never chose. The\n * default was never wrong; the session was overwriting it.\n *\n * Session-scoped React state instead: it cannot outlive the page, so there is\n * nothing to restore and nothing to leak.\n */\n sessionSpeaking: boolean;\n setSessionSpeaking: (enabled: boolean) => void;\n /** Play a short sample in a named voice. No model call, no message, no tokens. */\n previewVoice: (voiceName: string) => void;\n}\n\nconst INERT_SPEECH: AssistantSpeechContextValue = {\n isSupported: false,\n availability: 'unsupported',\n isBlocked: true,\n disabledReason: null,\n blockedFor: () => null,\n voiceChoices: [],\n spokenChunks: null,\n activeVoiceName: null,\n preferredVoiceName: null,\n setVoice: () => {},\n speakingMessageId: null,\n isSpeaking: () => false,\n toggle: () => {},\n stop: () => {},\n autoSpeakEnabled: false,\n setAutoSpeak: () => {},\n sessionSpeaking: false,\n setSessionSpeaking: () => {},\n previewVoice: () => {},\n};\n\nconst AssistantSpeechContext = createContext<AssistantSpeechContextValue>(INERT_SPEECH);\n\nexport function useAssistantSpeech(): AssistantSpeechContextValue {\n return useContext(AssistantSpeechContext);\n}\n\ninterface Props {\n children: ReactNode;\n /** Panel visibility. Hiding the panel stops the voice. */\n visible?: boolean;\n /**\n * Injectable for tests and local experiments. The default routes between the\n * device engine and the hosted one; with hosted TTS unconfigured it IS the\n * device engine, unchanged.\n */\n engine?: SpeechEngine;\n}\n\nexport const AssistantSpeechProvider: FC<Props> = ({ children, visible = true, engine = getSpeechEngine() }) => {\n const tr = useTr();\n const { locale } = useI18n();\n const [playback, dispatch] = useReducer(speechPlaybackReducer, IDLE_PLAYBACK);\n const [voices, setVoices] = useState<SpeechVoiceLike[]>(() => engine.listVoices());\n /**\n * True once we have waited out the voice list and it was still empty.\n *\n * Turns an indefinite `pending` into a terminal `no-voices`, which is what\n * lets the control be disabled with a reason instead of silently doing\n * nothing on every press.\n */\n const [voiceProbeSettled, setVoiceProbeSettled] = useState(false);\n /**\n * Every message we have refused, and why — keyed by id (see `blockedFor`).\n *\n * A single record could only describe one refusal: refusing a second reply\n * silently re-enabled the first, whose voice was still just as missing, so\n * pressing the buttons walked the disabled state around the transcript.\n */\n const [unspeakable, setUnspeakable] = useState<ReadonlyMap<string, string>>(() => new Map());\n const requestRef = useRef(0);\n\n /**\n * Which chunk of the current reply is sounding right now.\n *\n * ★ `index: -1` means \"chunked, nothing playing yet\" — distinct from no\n * progress at all, so the caption can stay empty until audio genuinely starts\n * instead of flashing the first sentence while the engine is still fetching.\n */\n const [spokenProgress, setSpokenProgress] = useState<{\n requestId: number;\n chunks: string[];\n index: number;\n } | null>(null);\n /** Cancels a playback that is waiting for the engine's voice list, if any. */\n const pendingRef = useRef<(() => void) | null>(null);\n const speakWithRef = useRef<\n (messageId: string, text: string, voices: readonly SpeechVoiceLike[], speechLocale: string) => void\n >(() => {});\n\n const cancelPending = useCallback(() => {\n pendingRef.current?.();\n pendingRef.current = null;\n }, []);\n\n const autoSpeakEnabled = useAssistantStore((state) => state.autoSpeakEnabled);\n const setAutoSpeak = useAssistantStore((state) => state.setAutoSpeak);\n // Not in the store on purpose — see `sessionSpeaking` on the context type.\n const [sessionSpeaking, setSessionSpeaking] = useState(false);\n const activeConversationId = useAssistantStore((state) => state.activeConversationId);\n\n const isSupported = useMemo(() => engine.isSupported(), [engine]);\n\n // getVoices() is empty on the first call in Chrome and only fills in when\n // 'voiceschanged' fires; Safari populates it synchronously and may never fire\n // the event. Read eagerly AND subscribe, so both engines end up correct.\n useEffect(() => {\n if (!isSupported) return;\n const sync = () => {\n setVoices(engine.listVoices());\n // Every recorded refusal was \"no voice for this language\". A new voice\n // list may well have supplied one — most likely because the user just\n // followed our instructions and installed it. Keeping the refusals would\n // leave those buttons disabled with no way back except a reload.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n sync();\n return engine.subscribeVoices(sync);\n }, [engine, isSupported]);\n\n // The language being SPOKEN ALOUD — which is the language of the reply, not\n // of the input and not of the interface. The two were one field until the\n // reply language was split out (BOFF-7108).\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const replyLanguage = useAssistantStore((state) => state.replyLanguage);\n const preferredVoices = useAssistantStore((state) => state.preferredVoices);\n const setPreferredVoice = useAssistantStore((state) => state.setPreferredVoice);\n const spokenLanguage = useMemo(\n // ★ The REPLY language, not the input. This is the language of the text\n // being spoken, so wiring it to the input would give a Tamil voice reading\n // an English answer the moment the two are set differently — the single\n // worst outcome available here, and the reason they were split at all.\n () => resolveLanguagePair(assistantLanguage, replyLanguage, locale).reply,\n [assistantLanguage, replyLanguage, locale]\n );\n const spokenLocale = spokenLanguage.code;\n\n /**\n * BCP-47 tag to ask the engine for, given a resolved language CODE.\n *\n * Resolved through the catalogue for ANY known code, not merely the currently\n * selected one — a historical Bengali reply must still get `bn-IN` after the\n * user switches to Tamil, or with both `bn-IN` and `bn-BD` installed the\n * engine's own order decides, and picks the wrong country.\n *\n * Falls back to the generic table for codes the catalogue does not carry.\n */\n const tagFor = useCallback((code: string) => findAssistantLanguage(code)?.tag ?? speechLangForLocale(code), []);\n\n /** Speaking rate for a resolved language code — see `AssistantLanguage.rate`. */\n const rateFor = useCallback((code: string) => findAssistantLanguage(code)?.rate ?? DEFAULT_SPEECH_RATE, []);\n\n const availability = useMemo(\n () => voiceAvailability(isSupported, voices, spokenLanguage.tag, voiceProbeSettled),\n [isSupported, voices, spokenLanguage, voiceProbeSettled]\n );\n\n // Spoken placeholders follow the app locale like the rest of the copy; the\n // transformation itself stays a pure function by taking them as arguments.\n const labels = useMemo<SpeakableLabels>(\n () => ({\n codeBlock: tr('healthybowl.assistant.speech.codeBlock', 'Code block'),\n image: tr('healthybowl.assistant.speech.image', 'image'),\n link: tr('healthybowl.assistant.speech.link', 'link'),\n largeTable: tr('healthybowl.assistant.speech.largeTable', 'Table with {{rows}} rows and {{columns}} columns'),\n truncated: tr('healthybowl.assistant.speech.truncated', 'The rest of this message is not read aloud'),\n nestedItem: tr('healthybowl.assistant.speech.nestedItem', 'Sub-item {{ordinal}}'),\n emailAt: tr('healthybowl.assistant.speech.emailAt', 'at'),\n emailDot: tr('healthybowl.assistant.speech.emailDot', 'dot'),\n }),\n [tr]\n );\n\n const stop = useCallback(() => {\n cancelPending();\n engine.cancel();\n dispatch({ type: 'stop' });\n }, [cancelPending, engine]);\n\n /**\n * Audition a voice — no model call, no message, no tokens.\n *\n * ★ Speaks through the engine DIRECTLY rather than through `speakWith`. That\n * path is built around a message: it resolves the reply's language, records\n * per-message \"cannot speak this\" state, and drives `speakingMessageId` so a\n * Listen button can light up. A preview has no message, so borrowing it would\n * mean inventing a fake id and then teaching every consumer to ignore it.\n *\n * Consequently it deliberately does NOT touch playback state: auditioning a\n * voice must not make a Listen button in the thread appear to be playing.\n *\n * Speaks the sample in the language being spoken, not the interface language —\n * the listener is judging how this voice reads THAT language.\n */\n const previewVoice = useCallback(\n (voiceName: string) => {\n const voice = engine.listVoices().find((candidate) => candidate.name === voiceName) ?? null;\n // An unknown name means the list changed under us (a download finished, a\n // profile switched). Silence is the right answer — better than falling\n // back to some other voice and auditioning the wrong one.\n if (!voice) return;\n // Whatever is speaking now is not what the user asked to hear.\n stop();\n engine.speak([voicePreviewText(spokenLocale)], { voice, lang: tagFor(spokenLocale) });\n },\n [engine, spokenLocale, stop, tagFor]\n );\n\n const blockedFor = useCallback((messageId: string) => unspeakable.get(messageId) ?? null, [unspeakable]);\n\n /**\n * Hold one playback until the engine publishes its voice list.\n *\n * Bounded: on timeout we take one last look and decide with whatever is\n * there, so an engine that never fires `voiceschanged` costs a two-second\n * wait rather than a control that is disabled forever. Nothing is spoken from\n * here unless a list actually arrives — an empty list means the engine would\n * pick its own default voice, which is the cross-language read this feature\n * promises never to do.\n */\n const waitForVoices = useCallback(\n (messageId: string, text: string, speechLocale: string) => {\n cancelPending();\n\n let settled = false;\n let unsubscribe = () => {};\n const finish = (available: SpeechVoiceLike[]) => {\n if (settled) return;\n settled = true;\n pendingRef.current = null;\n clearTimeout(timer);\n unsubscribe();\n if (available.length === 0) {\n // We waited and looked again: this device has no voices at all.\n // Record it so `availability` becomes `no-voices` and the control\n // explains itself, instead of returning silently every press.\n setVoiceProbeSettled(true);\n return;\n }\n setVoices(available);\n speakWithRef.current(messageId, text, available, speechLocale);\n };\n\n const timer = setTimeout(() => finish(engine.listVoices()), VOICE_LIST_TIMEOUT_MS);\n unsubscribe = engine.subscribeVoices(() => finish(engine.listVoices()));\n\n pendingRef.current = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n unsubscribe();\n pendingRef.current = null;\n };\n },\n [cancelPending, engine]\n );\n\n /**\n * Speak text against a KNOWN voice list.\n *\n * Every playback path funnels through here — the per-message button, the\n * header toggle's auto-speak, the store subscription — so the language gate\n * cannot be bypassed by any of them. Reading a Tamil reply with an English\n * voice is confident nonsense; it has to be impossible, not merely unlikely.\n */\n const speakWith = useCallback(\n (messageId: string, text: string, available: readonly SpeechVoiceLike[], speechLocale: string) => {\n let known = available;\n\n // Chrome answers the FIRST getVoices() with [] and fills the list in\n // asynchronously. One more synchronous read usually settles it.\n if (known.length === 0) {\n const refreshed = engine.listVoices();\n if (refreshed.length > 0) {\n known = refreshed;\n setVoices(refreshed);\n }\n }\n\n const speechLang = tagFor(speechLocale);\n\n const gate = speechGate(voiceAvailability(true, known, speechLocale, voiceProbeSettled));\n if (gate === 'block') {\n // Recorded for THIS message, always. Availability is resolved per reply\n // now, so a global \"your language has no voice\" cannot stand in for it:\n // the language the user chose to converse in says nothing about the one\n // this particular reply came back in.\n const reason = tr(\n 'healthybowl.assistant.speech.noVoiceForReply',\n 'This reply is in {{language}}, and no {{language}} voice is installed on this device.',\n { language: languageDisplayName(speechLang, locale) }\n );\n setUnspeakable((current) => new Map(current).set(messageId, reason));\n return;\n }\n if (gate === 'wait-for-voices') {\n waitForVoices(messageId, text, speechLocale);\n return;\n }\n\n setUnspeakable((current) => {\n if (!current.has(messageId)) return current;\n const next = new Map(current);\n next.delete(messageId);\n return next;\n });\n\n const requestId = requestRef.current + 1;\n requestRef.current = requestId;\n dispatch({ type: 'start', messageId, requestId });\n\n // ★ Chunked ONCE and kept, so the caption can show exactly what is being\n // spoken rather than a parallel rendering of the same markdown. A live\n // caption whose words differ from the audio is not a caption.\n const chunks = chunkForSpeech(text);\n setSpokenProgress({ requestId, chunks, index: -1 });\n\n engine.speak(\n chunks,\n // The TAG, not the code — so exact regional matching gets its chance\n // before the same-language fallback. `rate` had never been passed at\n // all, so every reply was read at the engine default.\n {\n voice: selectVoiceForLocale(known, speechLang, preferredVoices[speechLocale]),\n lang: speechLang,\n rate: rateFor(speechLocale),\n },\n {\n // Guarded on the request id like every other handler here: a stale\n // batch that has not noticed its cancellation must not drive the\n // caption of the reply that replaced it.\n onChunkStart: (index) =>\n setSpokenProgress((current) => (current?.requestId === requestId ? { ...current, index } : current)),\n onEnd: () => dispatch({ type: 'finished', requestId }),\n // Includes the 'cancelled' every queued utterance reports when we\n // pre-empt a batch; the request-id guard drops those as stale.\n onError: () => dispatch({ type: 'failed', requestId }),\n }\n );\n },\n [engine, locale, preferredVoices, rateFor, tagFor, tr, voiceProbeSettled, waitForVoices]\n );\n\n // `waitForVoices` resumes through this ref, so the two do not become a\n // circular hook dependency.\n useEffect(() => {\n speakWithRef.current = speakWith;\n }, [speakWith]);\n\n const speak = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (!isSupported) return;\n\n // Resolve the reply's language BEFORE building the spoken text, because\n // the stand-in words must be in that language. Detection deliberately runs\n // on a SILENT_LABELS pass — our own words must not vote on which language\n // the reply is in — so it does not depend on the labels chosen here.\n const replyLocale = resolveSpeechLocale(\n toSpeakableText(markdown, { labels: SILENT_LABELS }),\n turnLocale ?? spokenLocale\n );\n\n // ★ Labels in the REPLY's language, not the interface's. An English\n // interface reading a Tamil answer used to say \"Code block\" and \"image\" in\n // English, mid-Tamil-sentence — the same defect the email `at`/`dot` fix\n // addressed and did not generalise.\n const text = toSpeakableText(markdown, { labels: speechLabelsFor(replyLocale, labels) });\n if (!text) return;\n\n // Detect on the text that will actually be SPOKEN, with our own words\n // removed — neither the raw markdown nor the finished transformation.\n //\n // The transformation injects app-locale placeholders (\"Code block\"), which\n // let English chrome outvote short non-Latin prose. The raw markdown keeps\n // fenced code, whose Latin identifiers do the same thing — and that code is\n // never spoken at all. Running the same transformation with EMPTY labels\n // strips the unspoken constructs while contributing no words of its own,\n // which is exactly the denominator the decision needs.\n // The turn's OWN language first — the preference is only a stand-in for\n // replies that predate it. Resolved above, and reused rather than\n // recomputed.\n speakWith(messageId, text, voices, replyLocale);\n },\n [isSupported, labels, spokenLocale, speakWith, voices]\n );\n\n const toggle = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (isSpeakingMessage(playback, messageId)) {\n stop();\n return;\n }\n speak(messageId, markdown, turnLocale);\n },\n [playback, speak, stop]\n );\n\n // ── Never leave a voice talking to an empty room ─────────────────────────\n useEffect(() => {\n if (!visible) stop();\n }, [visible, stop]);\n\n useEffect(() => {\n // Switching (or creating) a conversation abandons the reply being read —\n // and the refusal explained a message that is no longer on screen.\n stop();\n setUnspeakable(new Map());\n }, [activeConversationId, stop]);\n\n useEffect(() => {\n // Every refusal was decided against the locale in force at the time, which\n // is what a Latin-script reply falls back to. Change the locale and those\n // verdicts may simply be wrong — an English reply refused on a\n // Spanish-only device would stay disabled forever after switching the UI to\n // Spanish, with the voice that could read it already installed.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n // And stop anything mid-sentence. The new language can make this message\n // unspeakable, which disables its button — leaving it reading \"Stop\" with no\n // way to actually stop, short of closing the panel.\n stop();\n }, [spokenLocale, stop]);\n\n useEffect(() => {\n return () => {\n pendingRef.current?.();\n pendingRef.current = null;\n engine.cancel();\n };\n }, [engine]);\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n // Chrome carries speech across a same-tab navigation and a bfcache restore\n // would otherwise come back mid-sentence.\n const handlePageHide = () => engine.cancel();\n window.addEventListener('pagehide', handlePageHide);\n return () => window.removeEventListener('pagehide', handlePageHide);\n }, [engine]);\n\n // ── One timeout is not a life sentence ───────────────────────────────────\n //\n // `no-voices` disables the control, and a disabled control can never reach\n // `speakWith` — the only path that re-reads `engine.listVoices()`. So without\n // this, a user who follows our own advice, leaves to install a voice and comes\n // back stays blocked until a reload: we would be telling them how to fix it\n // and then refusing to notice that they had.\n //\n // Returning to the tab is exactly when that happens, and it costs one\n // synchronous read of an already-populated list.\n useEffect(() => {\n if (typeof document === 'undefined' || !isSupported) return;\n const reprobe = () => {\n if (document.visibilityState !== 'visible') return;\n // Adopt the list UNCONDITIONALLY, including an empty one. Keeping the old\n // cache on an empty read means a user who uninstalled their last voice\n // stays `ready`, and playback then hands the engine a voice object that no\n // longer exists instead of explaining the problem.\n //\n // Safe to accept an empty read here precisely because the probe verdict is\n // cleared on the next line: empty + unsettled is `pending`, which leaves\n // the control ENABLED and defers the real decision to the next press.\n const available = engine.listVoices();\n // A Listen press may still be inside its two-second wait. Adopting voices\n // here flips the control to `ready`, so the user can press again and start\n // playback — and then the original timer fires, calls back into\n // `speakWith` for the same message, and the engine cancels and restarts it\n // mid-sentence. Retire the waiter as part of adopting the list.\n if (available.length > 0) cancelPending();\n setVoices(available);\n setVoiceProbeSettled(false);\n // Same reason the `voiceschanged` path clears them: every refusal meant\n // \"no voice for this language\", and this is the moment a user who went\n // away to install one comes back. `subscribeVoices` does not fire on an\n // eventless engine, which is precisely why this re-probe exists — so it\n // has to expire the refusals too.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n document.addEventListener('visibilitychange', reprobe);\n window.addEventListener('focus', reprobe);\n return () => {\n document.removeEventListener('visibilitychange', reprobe);\n window.removeEventListener('focus', reprobe);\n };\n }, [cancelPending, engine, isSupported]);\n\n // ── Opt-in auto-speak ────────────────────────────────────────────────────\n const speakRef = useRef(speak);\n useEffect(() => {\n speakRef.current = speak;\n }, [speak]);\n\n useEffect(() => {\n // `isBlocked` is the same gate the per-message button uses. Without it the\n // subscription fires on a device with no voice for the app language and the\n // engine reads a Tamil reply in English — the one thing this feature says\n // it will never do. `pending` is allowed through because `speakWith` waits\n // for the list before deciding.\n // NOT gated on `isSpeechBlocked(availability)` any more: that is the APP\n // language's availability, and it would suppress auto-speak for a reply in\n // a language this device CAN speak. `speakWith` resolves the reply's own\n // language and refuses safely there, which is the only place that can know.\n // Either the user's own preference, or a live voice session — which speaks\n // by definition and must not have to change that preference to do it.\n if ((!autoSpeakEnabled && !sessionSpeaking) || !visible || !isSupported) return;\n\n // Deliberately a store subscription keyed on the processing TRANSITION\n // rather than an effect over the message list: it fires only on the\n // in-flight → complete edge of the active conversation, so mounting the\n // panel, loading history or switching chats can never start talking.\n return useAssistantStore.subscribe((next, previous) => {\n const conversationId = next.activeConversationId;\n if (!conversationId || conversationId !== previous.activeConversationId) return;\n\n const current = next.processingByConversationId[conversationId];\n const before = previous.processingByConversationId[conversationId];\n if (current?.status !== 'complete' || !isTurnInFlight(before?.status)) return;\n\n const messageId = current.messageId ?? before?.messageId ?? null;\n if (!messageId) return;\n\n const message = next.conversations\n .find((conversation) => conversation.id === conversationId)\n ?.messages.find((candidate) => candidate.id === messageId);\n if (!message || message.role !== 'assistant') return;\n\n // ★ Speak a turn only if it belongs to the surface currently doing the\n // speaking. This subscription IS the live session's audio path —\n // `useVoiceSession` never calls `speak` itself, it flips `sessionSpeaking`\n // and lets this fire — and it had no channel check, so a TYPED reply\n // completing mid-session was read aloud as the answer to a spoken\n // question. Reachable with no typing at all: a host page queues work\n // through `pendingPrompt`, which is store-driven and fires past the voice\n // overlay.\n //\n // The mirror case matters too: after End, a reply still in flight must not\n // be spoken by ordinary auto-read — the user closed the conversation.\n if (isVoiceTurn(message) !== sessionSpeaking) return;\n\n // Same split the transcript uses: speak the prose, not the tool log.\n const { text } = parseToolActivity(message.content);\n if (!text.trim()) return;\n\n speakRef.current(messageId, text, (message.metadata as { lang?: string } | undefined)?.lang);\n });\n }, [autoSpeakEnabled, sessionSpeaking, isSupported, visible]);\n\n // The candidates for the language the user SPEAKS — the picker is a setting,\n // so it must not follow whatever language the last reply happened to be in.\n const voiceChoices = useMemo(() => voicesForLocale(voices, spokenLanguage.tag), [voices, spokenLanguage]);\n const activeVoice = useMemo(\n () => selectVoiceForLocale(voices, spokenLanguage.tag, preferredVoices[spokenLocale]),\n [voices, spokenLanguage, preferredVoices, spokenLocale]\n );\n\n const value = useMemo<AssistantSpeechContextValue>(\n () => ({\n isSupported,\n availability,\n // ONLY `no-voices` — a device with no voices at all can never speak\n // anything. `missing-voice` means the APP language has none, which says\n // nothing about the language a given reply came back in; that case is\n // resolved per message by `blockedFor`.\n isBlocked: availability === 'no-voices',\n // Both blocked states are the user's device, not our bug — so the copy\n // names the language and says where to fix it. \"Nothing happened\" was\n // the old behaviour and it read as a broken feature.\n disabledReason:\n availability === 'no-voices'\n ? tr(\n 'healthybowl.assistant.speech.noVoicesOnDevice',\n 'This device has no speech voices installed. Add one in your device speech or accessibility settings.'\n )\n : null,\n blockedFor,\n voiceChoices,\n spokenChunks: spokenProgress ? { chunks: spokenProgress.chunks, index: spokenProgress.index } : null,\n activeVoiceName: activeVoice?.name ?? null,\n preferredVoiceName: preferredVoices[spokenLocale] ?? null,\n setVoice: (voiceName: string | null) => setPreferredVoice(spokenLocale, voiceName),\n speakingMessageId: playback.status === 'speaking' ? playback.messageId : null,\n isSpeaking: (messageId: string) => isSpeakingMessage(playback, messageId),\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n setSessionSpeaking,\n previewVoice,\n }),\n [\n isSupported,\n availability,\n blockedFor,\n voiceChoices,\n activeVoice,\n preferredVoices,\n setPreferredVoice,\n spokenLocale,\n playback,\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n previewVoice,\n tr,\n ]\n );\n\n return <AssistantSpeechContext.Provider value={value}>{children}</AssistantSpeechContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsDA,IAAM,KAAiC;CACrC,WAAW;CACX,OAAO;CACP,MAAM;CACN,YAAY;CACZ,WAAW;CACX,SAAS;CACT,UAAU;CACV,YAAY;AACd,GA6HM,KAAyB,EAA2C;CArBxE,aAAa;CACb,cAAc;CACd,WAAW;CACX,gBAAgB;CAChB,kBAAkB;CAClB,cAAc,CAAC;CACf,cAAc;CACd,iBAAiB;CACjB,oBAAoB;CACpB,gB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A;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,OAAO,mBAAC,GAAuB,UAAxB;EAAwC;EAAQ;CAA0C,CAAA;AACnG"}
@@ -1,14 +1,2 @@
1
- import { findAssistantLanguage as e, resolveAssistantLanguage as t } from "./assistantLanguages.js";
2
- //#region src/config/assistantLanguagePair.ts
3
- function n(n, r, i) {
4
- let a = t(n, i), o = e(r);
5
- return {
6
- input: a,
7
- reply: o ?? a,
8
- replyIsExplicit: o !== null || e(n) !== null
9
- };
10
- }
11
- //#endregion
12
- export { n as resolveLanguagePair };
13
-
14
- //# sourceMappingURL=assistantLanguagePair.js.map
1
+ import { resolveLanguagePair as e } from "@burdenoff/fe-libs/shared/assistant";
2
+ export { e as resolveLanguagePair };
@@ -1,126 +1,2 @@
1
- //#region src/config/assistantLanguages.ts
2
- var e = .9, t = .85, n = [
3
- {
4
- code: "en",
5
- tag: "en-IN",
6
- label: "English",
7
- english: "English"
8
- },
9
- {
10
- code: "hi",
11
- tag: "hi-IN",
12
- label: "हिन्दी",
13
- english: "Hindi",
14
- rate: t
15
- },
16
- {
17
- code: "bn",
18
- tag: "bn-IN",
19
- label: "বাংলা",
20
- english: "Bengali",
21
- rate: t
22
- },
23
- {
24
- code: "te",
25
- tag: "te-IN",
26
- label: "తెలుగు",
27
- english: "Telugu",
28
- rate: t
29
- },
30
- {
31
- code: "mr",
32
- tag: "mr-IN",
33
- label: "मराठी",
34
- english: "Marathi",
35
- rate: t
36
- },
37
- {
38
- code: "ta",
39
- tag: "ta-IN",
40
- label: "தமிழ்",
41
- english: "Tamil",
42
- rate: t
43
- },
44
- {
45
- code: "gu",
46
- tag: "gu-IN",
47
- label: "ગુજરાતી",
48
- english: "Gujarati",
49
- rate: t
50
- },
51
- {
52
- code: "kn",
53
- tag: "kn-IN",
54
- label: "ಕನ್ನಡ",
55
- english: "Kannada",
56
- rate: t
57
- },
58
- {
59
- code: "ml",
60
- tag: "ml-IN",
61
- label: "മലയാളം",
62
- english: "Malayalam",
63
- rate: t
64
- },
65
- {
66
- code: "pa",
67
- tag: "pa-IN",
68
- label: "ਪੰਜਾਬੀ",
69
- english: "Punjabi",
70
- rate: t
71
- },
72
- {
73
- code: "ur",
74
- tag: "ur-IN",
75
- label: "اردو",
76
- english: "Urdu",
77
- rate: t
78
- },
79
- {
80
- code: "ar",
81
- tag: "ar-SA",
82
- label: "العربية",
83
- english: "Arabic",
84
- rate: t
85
- },
86
- {
87
- code: "es",
88
- tag: "es-ES",
89
- label: "Español",
90
- english: "Spanish"
91
- },
92
- {
93
- code: "fr",
94
- tag: "fr-FR",
95
- label: "Français",
96
- english: "French"
97
- },
98
- {
99
- code: "de",
100
- tag: "de-DE",
101
- label: "Deutsch",
102
- english: "German"
103
- },
104
- {
105
- code: "zh",
106
- tag: "zh-CN",
107
- label: "中文",
108
- english: "Chinese"
109
- },
110
- {
111
- code: "ja",
112
- tag: "ja-JP",
113
- label: "日本語",
114
- english: "Japanese"
115
- }
116
- ], r = new Map(n.map((e) => [e.code, e])), i = r.get("en");
117
- function a(e) {
118
- return e ? r.get(e.trim().toLowerCase().split("-")[0]) ?? null : null;
119
- }
120
- function o(e, t) {
121
- return a(e) ?? a(t) ?? i;
122
- }
123
- //#endregion
124
- export { n as ASSISTANT_LANGUAGES, e as DEFAULT_SPEECH_RATE, a as findAssistantLanguage, o as resolveAssistantLanguage };
125
-
126
- //# sourceMappingURL=assistantLanguages.js.map
1
+ import { ASSISTANT_LANGUAGES as e, DEFAULT_SPEECH_RATE as t, findAssistantLanguage as n, resolveAssistantLanguage as r } from "@burdenoff/fe-libs/shared/assistant";
2
+ export { e as ASSISTANT_LANGUAGES, t as DEFAULT_SPEECH_RATE, n as findAssistantLanguage, r as resolveAssistantLanguage };
@@ -1,102 +1,2 @@
1
- import { useCallback as e, useEffect as t, useRef as n, useState as r } from "react";
2
- import { useI18n as i } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
3
- //#region src/hooks/useVoiceInput.ts
4
- var a = {
5
- en: "en-US",
6
- es: "es-ES",
7
- fr: "fr-FR",
8
- de: "de-DE",
9
- ja: "ja-JP",
10
- zh: "zh-CN",
11
- ta: "ta-IN",
12
- hi: "hi-IN",
13
- ar: "ar-SA"
14
- };
15
- function o() {
16
- if (typeof window > "u") return null;
17
- let e = window;
18
- return e.SpeechRecognition ?? e.webkitSpeechRecognition ?? null;
19
- }
20
- function s(e) {
21
- switch (e) {
22
- case "not-allowed":
23
- case "service-not-allowed": return "not-allowed";
24
- case "no-speech": return "no-speech";
25
- case "audio-capture": return "audio-capture";
26
- case "network": return "network";
27
- case "language-not-supported": return "language-not-supported";
28
- default: return "unknown";
29
- }
30
- }
31
- function c({ onFinalize: c, language: l }) {
32
- let { locale: u } = i(), [d, f] = r(!1), [p, m] = r(!1), [h, g] = r(""), [_, v] = r(null), y = n(null), b = n(0), x = n(c);
33
- t(() => {
34
- x.current = c;
35
- }, [c]);
36
- let S = o() !== null, C = l ?? a[u] ?? "en-US";
37
- t(() => () => {
38
- y.current?.abort(), y.current = null;
39
- }, []);
40
- let w = e(() => {
41
- let e = o();
42
- if (!e || y.current) return;
43
- let t = new e();
44
- t.continuous = !0, t.interimResults = !0, t.lang = C;
45
- let n = b.current;
46
- t.onresult = (e) => {
47
- if (n !== b.current) return;
48
- let t = "", r = "";
49
- for (let n = e.resultIndex; n < e.results.length; n += 1) {
50
- let i = e.results[n], a = i[0]?.transcript ?? "";
51
- i.isFinal ? t += a : r += a;
52
- }
53
- t.trim() && x.current(t.trim()), g(r.trim());
54
- }, t.onerror = (e) => {
55
- if (n !== b.current) return;
56
- let t = s(e.error);
57
- t !== "no-speech" && v(t);
58
- }, t.onend = () => {
59
- n === b.current && (y.current = null, m(!1), f(!1), g(""));
60
- }, t.onstart = () => {
61
- n === b.current && (m(!1), f(!0));
62
- }, m(!0);
63
- try {
64
- t.start();
65
- } catch {
66
- y.current = null, m(!1), f(!1);
67
- return;
68
- }
69
- y.current = t, v(null), g("");
70
- }, [C]), T = e(() => {
71
- let e = y.current;
72
- y.current = null, b.current += 1, e?.stop(), m(!1), f(!1), g("");
73
- }, []), E = n(C);
74
- t(() => {
75
- E.current !== C && (E.current = C, T(), v(null));
76
- }, [C, T]);
77
- let D = e(() => {
78
- d || p ? T() : w();
79
- }, [
80
- d,
81
- p,
82
- w,
83
- T
84
- ]), O = e(() => v(null), []);
85
- return {
86
- isSupported: S,
87
- isListening: d,
88
- isStarting: p,
89
- isActive: d || p,
90
- interim: h,
91
- error: _,
92
- language: C,
93
- start: w,
94
- stop: T,
95
- toggle: D,
96
- clearError: O
97
- };
98
- }
99
- //#endregion
100
- export { c as useVoiceInput };
101
-
102
- //# sourceMappingURL=useVoiceInput.js.map
1
+ import { useVoiceInput as e } from "@burdenoff/fe-libs/shared/assistant";
2
+ export { e as useVoiceInput };
@@ -1,87 +1,2 @@
1
- //#region src/utils/pendingWrite.ts
2
- var e = "CONFIRMATION_REQUIRED", t = /CONFIRMATION_REQUIRED: the write "([^"]+)" was NOT sent/, n = "Values you were about to send:";
3
- function r(e) {
4
- if (typeof e == "string") return e;
5
- if (e && typeof e == "object" && "output" in e) {
6
- let t = e.output;
7
- if (typeof t == "string") return t;
8
- }
9
- return null;
10
- }
11
- function i(e) {
12
- if (!e || typeof e != "object" || Array.isArray(e)) return null;
13
- let t = Object.entries(e);
14
- return t.length === 0 ? null : t.map(([e, t]) => ({
15
- key: e,
16
- value: typeof t == "string" ? t : t == null ? "—" : JSON.stringify(t)
17
- }));
18
- }
19
- function a(r) {
20
- if (!r.includes(e)) return null;
21
- let a = t.exec(r)?.[1]?.trim();
22
- if (!a) return null;
23
- let o = r.indexOf(n);
24
- if (o === -1) return {
25
- operation: a,
26
- values: null
27
- };
28
- let s = r.slice(o + 30).trim();
29
- if (!s || s.startsWith("(no variables)")) return {
30
- operation: a,
31
- values: null
32
- };
33
- let c = s.indexOf("{");
34
- if (c === -1) return {
35
- operation: a,
36
- values: null
37
- };
38
- let l = 0, u = -1, d = !1, f = !1;
39
- for (let e = c; e < s.length; e += 1) {
40
- let t = s[e];
41
- if (f) {
42
- f = !1;
43
- continue;
44
- }
45
- if (t === "\\" && d) {
46
- f = !0;
47
- continue;
48
- }
49
- if (t === "\"") d = !d;
50
- else if (!d && t === "{") l += 1;
51
- else if (!d && t === "}" && (--l, l === 0)) {
52
- u = e + 1;
53
- break;
54
- }
55
- }
56
- if (u === -1) return {
57
- operation: a,
58
- values: null
59
- };
60
- try {
61
- return {
62
- operation: a,
63
- values: i(JSON.parse(s.slice(c, u)))
64
- };
65
- } catch {
66
- return {
67
- operation: a,
68
- values: null
69
- };
70
- }
71
- }
72
- function o(e) {
73
- if (!e) return null;
74
- let t = null;
75
- for (let n of e) {
76
- if (n?.type !== "tool") continue;
77
- let e = r(n.state?.output);
78
- if (!e) continue;
79
- let i = a(e);
80
- i && (t = i);
81
- }
82
- return t;
83
- }
84
- //#endregion
85
- export { o as findPendingWrite };
86
-
87
- //# sourceMappingURL=pendingWrite.js.map
1
+ import { findPendingWrite as e } from "@burdenoff/fe-libs/shared/assistant";
2
+ export { e as findPendingWrite };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/microfe-healthybowl",
3
- "version": "2026.903.20",
3
+ "version": "2026.903.22",
4
4
  "description": "Burdenoff HealthyBowl Microfrontend - Comprehensive organic farming and agro-foods management platform",
5
5
  "type": "module",
6
6
  "files": [
@@ -48,7 +48,7 @@
48
48
  },
49
49
  "dependencies": {
50
50
  "@apollo/client": "^4.0.11",
51
- "@burdenoff/fe-libs": "2026.903.8",
51
+ "@burdenoff/fe-libs": "2026.903.9",
52
52
  "@burdenoff/planmagnet-fe-sdk": "2026.831.1",
53
53
  "@tanstack/react-query": "^5.90.16",
54
54
  "clsx": "^2.1.1",
@@ -1 +0,0 @@
1
- {"version":3,"file":"assistantLanguagePair.js","names":[],"sources":["../../src/config/assistantLanguagePair.ts"],"sourcesContent":["/**\n * Two languages, not one.\n *\n * A single preference used to drive the recogniser, the reply and the voice\n * together — which quietly asserts that everyone answers in the language they\n * speak. That is wrong for exactly the users this product is for: a farmer may\n * dictate in Tamil and want the answer in English to forward to a buyer, or type\n * in English and want it read back in Tamil.\n *\n * ★ INPUT is what the user produces — the recogniser's language.\n * ★ REPLY is what the assistant produces — the prompt directive AND the voice\n * that reads it. Those two must never diverge: a Tamil voice reading an\n * English sentence is the single worst outcome available here, and it is what\n * you get by wiring the voice to the input language.\n *\n * `null` is meaningful in both, and differently:\n * input null → follow the interface language, which is what shipped before.\n * reply null → MATCH THE INPUT. Not \"follow the interface\" — someone who\n * switched their dictation to Tamil and left the reply alone\n * means \"answer me in Tamil\", not \"answer me in the menu\n * language\".\n */\n\nimport { findAssistantLanguage, resolveAssistantLanguage, type AssistantLanguage } from './assistantLanguages';\n\nexport interface AssistantLanguagePair {\n /** What the user speaks or types. Drives the recogniser. */\n input: AssistantLanguage;\n /** What the assistant answers in. Drives the prompt directive and the voice. */\n reply: AssistantLanguage;\n /**\n * A human chose this reply language, rather than it being guessed.\n *\n * `buildLanguagePreamble` uses this to decide whether the language the user\n * WROTE IN overrides their setting. For a guess it should — what they typed is\n * better evidence than the interface language. For a choice it must not, or\n * the preference is inert for everyone who types rather than dictates.\n *\n * ★ True when EITHER field was pinned, not only the reply field. Someone who\n * picked Tamil before this setting existed has `replyLanguage` null and means\n * \"answer me in Tamil\"; reading only the reply field would decide they never\n * chose anything and hand their setting back to the mirror clause — silently\n * re-breaking, for every existing user, the exact bug that clause was written\n * to fix.\n *\n * False only when NOTHING was pinned and the language came from the interface.\n *\n * Resolved rather than merely non-null, so a stale persisted code from a build\n * that offered more languages is not mistaken for a decision.\n */\n replyIsExplicit: boolean;\n}\n\nexport function resolveLanguagePair(\n inputCode: string | null | undefined,\n replyCode: string | null | undefined,\n appLocale: string\n): AssistantLanguagePair {\n const input = resolveAssistantLanguage(inputCode, appLocale);\n const explicitReply = findAssistantLanguage(replyCode);\n return {\n input,\n // Falling back to `input`, never to the app locale: see the header.\n reply: explicitReply ?? input,\n // Inheriting from a DELIBERATE input choice is still deliberate — see the\n // field's own note. Only an interface-derived guess is not a choice.\n replyIsExplicit: explicitReply !== null || findAssistantLanguage(inputCode) !== null,\n };\n}\n\n/**\n * Does the reply language follow the input, or has it been pinned?\n *\n * The selector shows \"Match my language\" for the former, and it is the default.\n */\nexport function replyFollowsInput(replyCode: string | null | undefined): boolean {\n return findAssistantLanguage(replyCode) === null;\n}\n"],"mappings":";;AAqDA,SAAgB,EACd,GACA,GACA,GACuB;CACvB,IAAM,IAAQ,EAAyB,GAAW,CAAS,GACrD,IAAgB,EAAsB,CAAS;CACrD,OAAO;EACL;EAEA,OAAO,KAAiB;EAGxB,iBAAiB,MAAkB,QAAQ,EAAsB,CAAS,MAAM;CAClF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"assistantLanguages.js","names":[],"sources":["../../src/config/assistantLanguages.ts"],"sourcesContent":["/**\n * The language the user is TALKING TO the assistant in (BOFF-7108).\n *\n * Separate from the app locale on purpose. A farmer whose phone and UI are in\n * English may well speak Tamil, and until now the only way to dictate Tamil was\n * to translate the entire interface — the recogniser language was derived from\n * `useI18n().locale`, so the two could not be chosen independently.\n *\n * One selection drives three things, which is the point:\n * 1. `recognition.lang` — what the recogniser is listening for;\n * 2. the reply-language directive — what the model answers in;\n * 3. the voice for reading that reply aloud.\n *\n * Deliberately NOT keyed on the app `Locale` union. That union is the set of\n * languages the INTERFACE is translated into (9, from fe-libs); this is the set\n * of languages a user might SPEAK, which is larger and grows for different\n * reasons. Tying them together is what created the problem.\n */\n\nexport interface AssistantLanguage {\n /** Primary subtag. What we persist, and what the speech-locale helpers take. */\n code: string;\n /** BCP-47 tag handed to the Web Speech APIs — region matters to acoustic models. */\n tag: string;\n /**\n * The ENDONYM — what a speaker calls their own language. Someone who reads\n * only Tamil cannot find \"Tamil\" in a list; they can find \"தமிழ்\".\n */\n label: string;\n /**\n * English name, for the model-facing directive.\n *\n * Hardcoded rather than derived from `Intl.DisplayNames` because this string\n * goes into a prompt: it must be stable and correct regardless of the reader's\n * browser, and a missing `Intl` implementation must not silently degrade an\n * instruction into a bare subtag the model may answer *about* instead of *in*.\n */\n english: string;\n /**\n * Speaking rate for this language, 1 = the engine's default.\n *\n * Nothing set a rate at all until now, so every user heard the spec default of\n * 1.0 — reported as \"it reads fast\", which it is: a synthesised voice at 1.0 is\n * harder to follow than a person at the same nominal speed, and harder again\n * when the listener is outdoors or hearing a second language.\n *\n * Indic and Arabic get a further reduction. Their scripts pack more syllables\n * per character than Latin, so the same nominal rate delivers noticeably more\n * speech per second.\n */\n rate?: number;\n}\n\n/** Applied when a language does not override it. */\nexport const DEFAULT_SPEECH_RATE = 0.9;\nconst INDIC_RATE = 0.85;\n\n/**\n * India first and by speaker count, then the other app locales.\n *\n * Regions follow where HealthyBowl operates: `-IN` for the Indic languages,\n * because a recogniser tuned for `ur-PK` or a voice for `bn-BD` is the wrong\n * pronunciation model for this product's users.\n */\nexport const ASSISTANT_LANGUAGES: readonly AssistantLanguage[] = [\n { code: 'en', tag: 'en-IN', label: 'English', english: 'English' },\n { code: 'hi', tag: 'hi-IN', label: 'हिन्दी', english: 'Hindi', rate: INDIC_RATE },\n { code: 'bn', tag: 'bn-IN', label: 'বাংলা', english: 'Bengali', rate: INDIC_RATE },\n { code: 'te', tag: 'te-IN', label: 'తెలుగు', english: 'Telugu', rate: INDIC_RATE },\n { code: 'mr', tag: 'mr-IN', label: 'मराठी', english: 'Marathi', rate: INDIC_RATE },\n { code: 'ta', tag: 'ta-IN', label: 'தமிழ்', english: 'Tamil', rate: INDIC_RATE },\n { code: 'gu', tag: 'gu-IN', label: 'ગુજરાતી', english: 'Gujarati', rate: INDIC_RATE },\n { code: 'kn', tag: 'kn-IN', label: 'ಕನ್ನಡ', english: 'Kannada', rate: INDIC_RATE },\n { code: 'ml', tag: 'ml-IN', label: 'മലയാളം', english: 'Malayalam', rate: INDIC_RATE },\n { code: 'pa', tag: 'pa-IN', label: 'ਪੰਜਾਬੀ', english: 'Punjabi', rate: INDIC_RATE },\n { code: 'ur', tag: 'ur-IN', label: 'اردو', english: 'Urdu', rate: INDIC_RATE },\n { code: 'ar', tag: 'ar-SA', label: 'العربية', english: 'Arabic', rate: INDIC_RATE },\n { code: 'es', tag: 'es-ES', label: 'Español', english: 'Spanish' },\n { code: 'fr', tag: 'fr-FR', label: 'Français', english: 'French' },\n { code: 'de', tag: 'de-DE', label: 'Deutsch', english: 'German' },\n { code: 'zh', tag: 'zh-CN', label: '中文', english: 'Chinese' },\n { code: 'ja', tag: 'ja-JP', label: '日本語', english: 'Japanese' },\n];\n\nconst BY_CODE = new Map(ASSISTANT_LANGUAGES.map((language) => [language.code, language]));\n\n/** English is the last resort, and it is in the list, so this cannot be undefined. */\nconst FALLBACK = BY_CODE.get('en') as AssistantLanguage;\n\nexport function findAssistantLanguage(code: string | null | undefined): AssistantLanguage | null {\n if (!code) return null;\n return BY_CODE.get(code.trim().toLowerCase().split('-')[0]) ?? null;\n}\n\n/**\n * Which language to use: the user's explicit choice, else the app locale, else\n * English.\n *\n * The app-locale step is what keeps this backwards-compatible — a user who never\n * touches the new control behaves exactly as before, because the value derived\n * is the one the old code derived. An app locale outside this list (or a stale\n * persisted code from a build that offered more) degrades to English rather than\n * handing the recogniser a tag it will reject.\n */\nexport function resolveAssistantLanguage(\n selectedCode: string | null | undefined,\n appLocale: string\n): AssistantLanguage {\n return findAssistantLanguage(selectedCode) ?? findAssistantLanguage(appLocale) ?? FALLBACK;\n}\n"],"mappings":";AAsDA,IAAa,IAAsB,IAC7B,IAAa,KASN,IAAoD;CAC/D;EAAE,MAAM;EAAM,KAAK;EAAS,OAAO;EAAW,SAAS;CAAU;CACjE;EAAE,MAAM;EAAM,KAAK;EAAS,OAAO;EAAU,SAAS;EAAS,MAAM;CAAW;CAChF;EAAE,MAAM;EAAM,KAAK;EAAS,OAAO;EAAS,SAAS;EAAW,MAAM;CAAW;CACjF;EAAE,MAAM;EAAM,KAAK;EAAS,OAAO;EAAU,SAAS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AK;AACpF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"useVoiceInput.js","names":[],"sources":["../../src/hooks/useVoiceInput.ts"],"sourcesContent":["/**\n * Speech-to-text for the assistant composer (Workstream 2 of the AI Assistant\n * V2 multimodal effort).\n *\n * Input-only, browser-native (Web Speech API). It degrades gracefully:\n * `isSupported` is false on engines without SpeechRecognition (notably Firefox),\n * and the composer hides the mic entirely in that case rather than showing a\n * dead control.\n *\n * ⚠️ This does NOT mean the audio stays on the device. Chrome's\n * `webkitSpeechRecognition` is a NETWORK service — the audio is streamed to the\n * browser vendor for recognition, and the supported language list is theirs, not\n * ours. We neither receive nor store it, which is all an earlier version of this\n * comment (\"no audio ever leaves the device through us\") actually claimed; read\n * literally it implied something stronger and untrue. Whether recording farmers'\n * speech this way needs disclosure or consent is a product/legal call, not a\n * code one.\n *\n * Output (reading replies aloud) is a separate concern and lives in\n * `AssistantSpeechProvider`; an earlier version of this note said the assistant\n * does not speak, which stopped being true when BOFF-6290 shipped.\n *\n * Differences from the fe-libs `assistantWidget/useVoiceInput` this is modelled\n * on, all of which the composer needs:\n * - **interim results are exposed**, so the user sees words appear while\n * speaking instead of staring at a silent button until a phrase finalises;\n * - **errors are surfaced** (`error`) so a denied mic permission can be\n * explained rather than looking like a no-op;\n * - **the recogniser language follows the app locale** (a Tamil or Hindi\n * farmer dictating into an `en-US` recogniser gets garbage);\n * - **`stop()` resolves the final transcript** through `onFinalize`, so the\n * composer can commit exactly once when the user stops.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport type { Locale } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\n\ninterface SpeechRecognitionEventLike extends Event {\n results: SpeechRecognitionResultList;\n resultIndex: number;\n}\n\ninterface SpeechRecognitionErrorEventLike extends Event {\n error: string;\n message: string;\n}\n\ninterface SpeechRecognitionInstance extends EventTarget {\n continuous: boolean;\n interimResults: boolean;\n lang: string;\n start(): void;\n stop(): void;\n abort(): void;\n onresult: ((event: SpeechRecognitionEventLike) => void) | null;\n onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;\n onend: (() => void) | null;\n /**\n * Fires when the service has actually begun listening — the only honest\n * \"capture has started\" signal. Absent from this declaration until now, which\n * is part of why capture was inferred from `start()` returning instead.\n */\n onstart: (() => void) | null;\n}\n\ntype SpeechRecognitionConstructor = new () => SpeechRecognitionInstance;\n\n/**\n * BCP-47 tag for the recogniser, per app locale. Regional choices follow where\n * HealthyBowl actually operates (India for ta/hi) rather than a generic tag,\n * because the recogniser's acoustic model is region-specific.\n */\nconst RECOGNITION_LANG: Record<Locale, string> = {\n en: 'en-US',\n es: 'es-ES',\n fr: 'fr-FR',\n de: 'de-DE',\n ja: 'ja-JP',\n zh: 'zh-CN',\n ta: 'ta-IN',\n hi: 'hi-IN',\n ar: 'ar-SA',\n};\n\nfunction getSpeechRecognitionConstructor(): SpeechRecognitionConstructor | null {\n if (typeof window === 'undefined') return null;\n const win = window as unknown as Record<string, unknown>;\n return (\n (win.SpeechRecognition as SpeechRecognitionConstructor | undefined) ??\n (win.webkitSpeechRecognition as SpeechRecognitionConstructor | undefined) ??\n null\n );\n}\n\nexport type VoiceInputError =\n 'not-allowed' | 'no-speech' | 'audio-capture' | 'network' | 'language-not-supported' | 'unknown';\n\n/**\n * Map the spec's `SpeechRecognitionErrorEvent.error` codes onto the cases the UI\n * actually distinguishes. Anything else is 'unknown' (generic copy).\n *\n * `language-not-supported` is called out separately because it is the single\n * most likely failure for the users this feature exists for: the recogniser's\n * language list belongs to the browser vendor, not to us, so a Tamil or Hindi\n * speaker can hit it on a browser that simply does not offer their language.\n * Folding it into 'unknown' produced \"Dictation stopped unexpectedly\", which\n * tells them nothing and reads like a bug in HealthyBowl.\n */\nfunction toVoiceInputError(code: string): VoiceInputError {\n switch (code) {\n case 'not-allowed':\n case 'service-not-allowed':\n return 'not-allowed';\n case 'no-speech':\n return 'no-speech';\n case 'audio-capture':\n return 'audio-capture';\n case 'network':\n return 'network';\n case 'language-not-supported':\n return 'language-not-supported';\n default:\n return 'unknown';\n }\n}\n\nexport interface UseVoiceInputOptions {\n /**\n * Called with each newly finalised phrase. The composer appends it to the\n * draft; keeping the committed text in the caller (rather than accumulating\n * here) means the user can freely edit while dictation continues.\n */\n onFinalize: (text: string) => void;\n /**\n * BCP-47 tag to listen for. Omit to follow the app locale, which is what this\n * hook did unconditionally before (BOFF-7108).\n *\n * The two are genuinely independent: a farmer whose interface is English may\n * well speak Tamil, and deriving the recogniser language from the UI meant the\n * only way to dictate Tamil was to translate the entire app.\n */\n language?: string;\n}\n\nexport interface UseVoiceInputResult {\n isSupported: boolean;\n isListening: boolean;\n /** Requested, not yet capturing. Distinguishes starting up from listening. */\n isStarting: boolean;\n /**\n * Starting OR listening — \"the microphone is busy\".\n *\n * ★ Most callers mean THIS and were testing `isListening`, which was the same\n * thing only while capture was assumed the instant start() returned. Exposing\n * it once stops four call sites disagreeing about what counts as active.\n */\n isActive: boolean;\n /** Words recognised but not yet finalised — render as a live hint. */\n interim: string;\n error: VoiceInputError | null;\n /**\n * BCP-47 tag the recogniser was asked for. Exposed so error copy can name the\n * language that failed (\"Tamil dictation is not supported…\") rather than\n * leaving the user to guess which language the browser rejected.\n */\n language: string;\n start: () => void;\n stop: () => void;\n /** Start if idle, stop if listening — what the mic button binds to. */\n toggle: () => void;\n clearError: () => void;\n}\n\nexport function useVoiceInput({ onFinalize, language: requested }: UseVoiceInputOptions): UseVoiceInputResult {\n const { locale } = useI18n();\n const [isListening, setIsListening] = useState(false);\n /**\n * Requested but not yet capturing — the permission prompt / start-up window.\n *\n * ★ Needed BECAUSE `isListening` now waits for `recognition.onstart`. That is\n * the honest signal, but it lengthened the window in which a caller has been\n * asked to listen and can say nothing about it — the composer showed its\n * idle hint after the user had already tapped the microphone.\n */\n const [isStarting, setIsStarting] = useState(false);\n const [interim, setInterim] = useState('');\n const [error, setError] = useState<VoiceInputError | null>(null);\n const recognitionRef = useRef<SpeechRecognitionInstance | null>(null);\n // Incremented on every stop. Handlers capture the session they were created\n // under and ignore events that arrive after it ends.\n const sessionRef = useRef(0);\n\n // Keep the newest callback reachable from the recogniser's long-lived event\n // handlers without re-creating the recogniser on every parent render.\n const onFinalizeRef = useRef(onFinalize);\n useEffect(() => {\n onFinalizeRef.current = onFinalize;\n }, [onFinalize]);\n\n const isSupported = getSpeechRecognitionConstructor() !== null;\n const language = requested ?? RECOGNITION_LANG[locale] ?? 'en-US';\n\n // Abort (not stop) on unmount: the panel is closing, so a trailing final\n // result would be committed into a draft nobody can see.\n useEffect(() => {\n return () => {\n recognitionRef.current?.abort();\n recognitionRef.current = null;\n };\n }, []);\n\n const start = useCallback(() => {\n const Ctor = getSpeechRecognitionConstructor();\n if (!Ctor || recognitionRef.current) return;\n\n const recognition = new Ctor();\n recognition.continuous = true;\n recognition.interimResults = true;\n recognition.lang = language;\n\n const session = sessionRef.current;\n\n recognition.onresult = (event) => {\n if (session !== sessionRef.current) return;\n let finalText = '';\n let interimText = '';\n for (let index = event.resultIndex; index < event.results.length; index += 1) {\n const result = event.results[index];\n const alternative = result[0]?.transcript ?? '';\n if (result.isFinal) {\n finalText += alternative;\n } else {\n interimText += alternative;\n }\n }\n if (finalText.trim()) onFinalizeRef.current(finalText.trim());\n setInterim(interimText.trim());\n };\n\n recognition.onerror = (event) => {\n if (session !== sessionRef.current) return;\n const mapped = toVoiceInputError(event.error);\n // 'no-speech' fires routinely during a natural pause and the recogniser\n // keeps running — surfacing it would flash a scary message mid-sentence.\n if (mapped !== 'no-speech') setError(mapped);\n };\n\n recognition.onend = () => {\n if (session !== sessionRef.current) return;\n recognitionRef.current = null;\n setIsStarting(false);\n setIsListening(false);\n setInterim('');\n };\n\n /**\n * ★ The TRUE capture signal.\n *\n * This was set optimistically on the line after `start()` returned — which\n * is synchronous, and says only that the request was accepted, not that the\n * microphone is open. Everything downstream then believed capture had begun\n * while the permission prompt was still up: the stage showed \"Listening…\"\n * over a microphone that could not yet hear, so a user who started talking\n * immediately lost the first word or two; the `connecting` stage lasted a\n * single commit; and the 5s \"we aren't hearing your microphone\" notice\n * could never fire, because `capturing` was already true.\n */\n recognition.onstart = () => {\n if (session !== sessionRef.current) return;\n setIsStarting(false);\n setIsListening(true);\n };\n\n setIsStarting(true);\n try {\n recognition.start();\n } catch {\n // start() throws if a recogniser is somehow already running — treat the\n // session as not started rather than leaving the button stuck \"live\".\n recognitionRef.current = null;\n setIsStarting(false);\n setIsListening(false);\n return;\n }\n\n recognitionRef.current = recognition;\n setError(null);\n setInterim('');\n }, [language]);\n\n const stop = useCallback(() => {\n // Detach BEFORE stopping. `onend` is what used to clear this ref, but it\n // arrives asynchronously — so a user who tapped stop and immediately tapped\n // the mic again hit `start()`'s `if (recognitionRef.current) return` guard\n // and got a silent no-op. Bumping the session also makes any trailing final\n // phrase the engine flushes on stop land on a dead session, instead of\n // reappearing in a draft the composer has already sent and cleared.\n const recognition = recognitionRef.current;\n recognitionRef.current = null;\n sessionRef.current += 1;\n recognition?.stop();\n setIsStarting(false);\n setIsListening(false);\n setInterim('');\n }, []);\n\n // Changing language must END the session it no longer describes.\n //\n // A running recogniser keeps the `lang` it was constructed with, so after a\n // switch the in-flight session is still listening in the OLD language while\n // this hook already reports the new one. A late `language-not-supported` from\n // that session would then be rendered as though the browser had rejected the\n // language the user just picked. Clearing the error is not enough — the\n // session producing it has to go too.\n const languageRef = useRef(language);\n useEffect(() => {\n if (languageRef.current === language) return;\n languageRef.current = language;\n stop();\n setError(null);\n }, [language, stop]);\n\n const toggle = useCallback(() => {\n // ★ `isStarting` too, or the button is DEAD for the whole permission window.\n // `start()` bails on `if (recognitionRef.current) return`, and that ref is\n // assigned synchronously the moment start() is called — so once isListening\n // stopped being set optimistically, a press here took the `else start()`\n // branch and returned immediately. The user tapped the microphone, saw the\n // idle icon, tapped again to cancel, and nothing happened either time.\n if (isListening || isStarting) stop();\n else start();\n }, [isListening, isStarting, start, stop]);\n\n const clearError = useCallback(() => setError(null), []);\n\n return {\n isSupported,\n isListening,\n isStarting,\n isActive: isListening || isStarting,\n interim,\n error,\n language,\n start,\n stop,\n toggle,\n clearError,\n };\n}\n"],"mappings":";;;AAyEA,IAAM,IAA2C;CAC/C,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;AACN;AAEA,SAAS,IAAuE;CAC9E,IAAI,OAAO,SAAW,KAAa,OAAO;CAC1C,IAAM,IAAM;CACZ,OACG,EAAI,qBACJ,EAAI,2BACL;AAEJ;AAgBA,SAAS,EAAkB,GAA+B;CACxD,QAAQ,GAAR;EACE,KAAK;EACL,KAAK,uBACH,OAAO;EACT,KAAK,aACH,OAAO;EACT,KAAK,iBACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,0BACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAiDA,SAAgB,EAAc,EAAE,eAAY,UAAU,KAAwD;CAC5G,IAAM,EAAE,cAAW,EAAQ,GACrB,CAAC,GAAa,KAAkB,EAAS,EAAK,GAS9C,CAAC,GAAY,KAAiB,EAAS,EAAK,GAC5C,CAAC,GAAS,KAAc,EAAS,EAAE,GACnC,CAAC,GAAO,KAAY,EAAiC,IAAI,GACzD,IAAiB,EAAyC,IAAI,GAG9D,IAAa,EAAO,CAAC,GAIrB,IAAgB,EAAO,CAAU;CACvC,QAAgB;EACd,EAAc,UAAU;CAC1B,GAAG,CAAC,CAAU,CAAC;CAEf,IAAM,IAAc,EAAgC,MAAM,MACpD,IAAW,KAAa,EAAiB,MAAW;CAI1D,cACe;EAEX,AADA,EAAe,SAAS,MAAM,GAC9B,EAAe,UAAU;CAC3B,GACC,CAAC,CAAC;CAEL,IAAM,IAAQ,QAAkB;EAC9B,IAAM,IAAO,EAAgC;EAC7C,IAAI,CAAC,KAAQ,EAAe,SAAS;EAErC,IAAM,IAAc,IAAI,EAAK;EAG7B,AAFA,EAA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,EAAY,YAAY,MAC5B,EAAY,UAAU,GACtB,EAAK,GACL,EAAS,IAAI;CACf,GAAG,CAAC,GAAU,CAAI,CAAC;CAEnB,IAAM,IAAS,QAAkB;EAO/B,AAAI,KAAe,IAAY,EAAK,IAC/B,EAAM;CACb,GAAG;EAAC;EAAa;EAAY;EAAO;CAAI,CAAC,GAEnC,IAAa,QAAkB,EAAS,IAAI,GAAG,CAAC,CAAC;CAEvD,OAAO;EACL;EACA;EACA;EACA,UAAU,KAAe;EACzB;EACA;EACA;EACA;EACA;EACA;EACA;CACF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"pendingWrite.js","names":[],"sources":["../../src/utils/pendingWrite.ts"],"sourcesContent":["/**\n * The write the assistant is asking permission for — read from the request\n * itself, not from the model's description of it.\n *\n * ★ WHY THIS EXISTS. In \"Take action\" mode the in-sandbox helper refuses every\n * mutation on its first attempt and returns a `CONFIRMATION_REQUIRED` tool\n * result naming the operation and the exact values it was about to send. The\n * model is then instructed to describe that change in prose and ask the user.\n *\n * So today the user approves a PARAGRAPH. The paragraph is generated by the same\n * model that wants the write to go through, and nothing checks it against the\n * payload — a field can be omitted, rounded, or described as something milder\n * than it is, and the approval still counts.\n *\n * The refusal itself is already in the message parts the panel receives, and the\n * panel throws it away (`getToolProgress` reduces a tool part to\n * \"Completed: <tool>\"). Reading it back means the confirmation card can show the\n * operation and values that will actually be sent.\n *\n * ★ WHAT THIS IS NOT. It does not make the UI the authorization boundary. The\n * approval still travels back through the model, which holds the single-use\n * token and could in principle retry without asking — see the module docstring\n * in `ai-assistant/src/write-confirmation.ts`, which names the remaining gap and\n * the fix (\"the UI holding the approval\"). This narrows what the user can be\n * misled about; it does not close that.\n */\n\nexport interface PendingWriteValue {\n key: string;\n /** Already stringified for display; objects and arrays are JSON. */\n value: string;\n}\n\nexport interface PendingWrite {\n /** GraphQL operation name, e.g. `createCrop`. */\n operation: string;\n /**\n * The variables, flattened for display. `null` when the refusal reported no\n * variables or the block could not be parsed — the card then falls back to\n * naming the operation alone rather than implying there is nothing to send.\n */\n values: PendingWriteValue[] | null;\n}\n\n/** The marker the in-sandbox helper emits when it refuses a write. */\nconst MARKER = 'CONFIRMATION_REQUIRED';\nconst OPERATION_RE = /CONFIRMATION_REQUIRED: the write \"([^\"]+)\" was NOT sent/;\nconst VALUES_HEADING = 'Values you were about to send:';\n\n/**\n * A tool part as the transport delivers it. Deliberately loose: `state.output`\n * is typed `unknown` upstream and different agent versions have wrapped the text\n * differently, so this accepts anything and proves the shape at runtime.\n */\ninterface ToolPartLike {\n type?: string;\n state?: { output?: unknown; [key: string]: unknown } | undefined;\n}\n\n/**\n * Pull the human-readable text out of a tool result.\n *\n * Handles the two shapes seen in practice — a bare string, and `{ output }` —\n * and refuses anything else rather than stringifying an object into `[object\n * Object]`, which would then never match the marker and fail silently.\n */\nfunction outputText(output: unknown): string | null {\n if (typeof output === 'string') return output;\n if (output && typeof output === 'object' && 'output' in output) {\n const inner = (output as { output?: unknown }).output;\n if (typeof inner === 'string') return inner;\n }\n return null;\n}\n\nfunction flatten(parsed: unknown): PendingWriteValue[] | null {\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;\n const entries = Object.entries(parsed as Record<string, unknown>);\n if (entries.length === 0) return null;\n return entries.map(([key, value]) => ({\n key,\n // Nested objects are shown as JSON rather than flattened further: a nested\n // key rendered at top level reads as a field of the record being changed,\n // which it is not.\n value: typeof value === 'string' ? value : value === null || value === undefined ? '—' : JSON.stringify(value),\n }));\n}\n\n/**\n * Parse one refusal.\n *\n * ★ The single-use token is deliberately NOT extracted. It is a capability: the\n * write goes through if it is echoed back, so putting it on screen would invite\n * a user — or anything reading the page — to replay it, and would turn a\n * confirmation card into a bypass. The card needs the operation and the values;\n * it never needs the token.\n */\nexport function parseConfirmationRefusal(text: string): PendingWrite | null {\n if (!text.includes(MARKER)) return null;\n\n const operation = OPERATION_RE.exec(text)?.[1]?.trim();\n if (!operation) return null;\n\n const headingAt = text.indexOf(VALUES_HEADING);\n if (headingAt === -1) return { operation, values: null };\n\n const block = text.slice(headingAt + VALUES_HEADING.length).trim();\n // The helper writes this literal when there is nothing to send.\n if (!block || block.startsWith('(no variables)')) return { operation, values: null };\n\n // The JSON block runs to the end of the refusal, but be defensive: take from\n // the first brace to its matching close rather than assuming.\n const start = block.indexOf('{');\n if (start === -1) return { operation, values: null };\n let depth = 0;\n let end = -1;\n let inString = false;\n let escaped = false;\n for (let i = start; i < block.length; i += 1) {\n const ch = block[i]!;\n if (escaped) {\n escaped = false;\n continue;\n }\n if (ch === '\\\\' && inString) {\n escaped = true;\n continue;\n }\n if (ch === '\"') inString = !inString;\n // Braces inside a string value are text, not structure — a crop named\n // `{North}` would otherwise close the object early and lose every field\n // after it.\n else if (!inString && ch === '{') depth += 1;\n else if (!inString && ch === '}') {\n depth -= 1;\n if (depth === 0) {\n end = i + 1;\n break;\n }\n }\n }\n if (end === -1) return { operation, values: null };\n\n try {\n return { operation, values: flatten(JSON.parse(block.slice(start, end))) };\n } catch {\n // Malformed JSON must still name the operation. Showing \"the assistant wants\n // to run createCrop\" with no values beats showing nothing at all, because\n // the alternative is the user seeing only the model's prose again.\n return { operation, values: null };\n }\n}\n\n/**\n * The pending write in a set of message parts, if the agent refused one.\n *\n * Takes the LAST match: within a turn the model may be told to stop after the\n * first refusal, but a turn that somehow produced two is asking about the most\n * recent one.\n */\nexport function findPendingWrite(parts: readonly ToolPartLike[] | undefined): PendingWrite | null {\n if (!parts) return null;\n let found: PendingWrite | null = null;\n for (const part of parts) {\n if (part?.type !== 'tool') continue;\n const text = outputText(part.state?.output);\n if (!text) continue;\n const parsed = parseConfirmationRefusal(text);\n if (parsed) found = parsed;\n }\n return found;\n}\n"],"mappings":";AA6CA,IAAM,IAAS,yBACT,IAAe,2DACf,IAAiB;AAmBvB,SAAS,EAAW,GAAgC;CAClD,IAAI,OAAO,KAAW,UAAU,OAAO;CACvC,IAAI,KAAU,OAAO,KAAW,YAAY,YAAY,GAAQ;EAC9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