@burdenoff/microfe-healthybowl 2026.902.15 → 2026.902.16

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.
@@ -4,101 +4,111 @@ import { downloadFile as n, exportConversation as r } from "../../services/assis
4
4
  import { useAssistantSpeech as i } from "./AssistantSpeechProvider.js";
5
5
  import { AssistantVoiceSelector as a } from "./composer/AssistantVoiceSelector.js";
6
6
  import { useEffect as o, useRef as s, useState as c } from "react";
7
- import { Check as l, FileJson as u, FileText as d, MoreHorizontal as f, Volume2 as p } from "lucide-react";
8
- import { Fragment as m, jsx as h, jsxs as g } from "react/jsx-runtime";
7
+ import { Check as l, FileJson as u, FileText as d, MoreHorizontal as f, Play as p, Volume2 as m } from "lucide-react";
8
+ import { Fragment as h, jsx as g, jsxs as _ } from "react/jsx-runtime";
9
9
  //#region src/components/assistant/AssistantMoreMenu.tsx
10
- var _ = () => {
11
- let _ = t(), [v, y] = c(!1), b = s(null), x = s(null), { conversations: S, activeConversationId: C } = e(), w = S.find((e) => e.id === C), T = !!(w && w.messages.length > 0), { isSupported: E, isBlocked: D, disabledReason: O, autoSpeakEnabled: k, setAutoSpeak: A, stop: j } = i(), M = D && !k;
10
+ var v = () => {
11
+ let v = t(), [y, b] = c(!1), x = s(null), S = s(null), { conversations: C, activeConversationId: w } = e(), T = C.find((e) => e.id === w), E = !!(T && T.messages.length > 0), { isSupported: D, isBlocked: O, disabledReason: k, autoSpeakEnabled: A, setAutoSpeak: j, stop: M, previewVoice: N, activeVoiceName: P } = i(), F = O && !A;
12
12
  o(() => {
13
- if (!v) return;
13
+ if (!y) return;
14
14
  let e = (e) => {
15
- e.key === "Escape" && (y(!1), x.current?.focus());
15
+ e.key === "Escape" && (b(!1), S.current?.focus());
16
16
  }, t = (e) => {
17
17
  let t = e.target;
18
- b.current?.contains(t) || x.current?.contains(t) || y(!1);
18
+ x.current?.contains(t) || S.current?.contains(t) || b(!1);
19
19
  };
20
20
  return window.addEventListener("keydown", e), document.addEventListener("mousedown", t), () => {
21
21
  window.removeEventListener("keydown", e), document.removeEventListener("mousedown", t);
22
22
  };
23
- }, [v]);
24
- let N = (e) => {
25
- if (!w) return;
26
- let { content: t, filename: i, mimeType: a } = r(w, e);
27
- n(t, i, a), y(!1);
28
- }, P = () => {
29
- k && j(), A(!k);
30
- }, F = _("healthybowl.assistant.header.more", "More options");
31
- return /* @__PURE__ */ g("div", {
23
+ }, [y]);
24
+ let I = (e) => {
25
+ if (!T) return;
26
+ let { content: t, filename: i, mimeType: a } = r(T, e);
27
+ n(t, i, a), b(!1);
28
+ }, L = () => {
29
+ A && M(), j(!A);
30
+ }, R = v("healthybowl.assistant.header.more", "More options");
31
+ return /* @__PURE__ */ _("div", {
32
32
  className: "relative",
33
- children: [/* @__PURE__ */ h("button", {
34
- ref: x,
33
+ children: [/* @__PURE__ */ g("button", {
34
+ ref: S,
35
35
  type: "button",
36
- onClick: () => y((e) => !e),
36
+ onClick: () => b((e) => !e),
37
37
  className: "rounded p-1 transition-colors hover:bg-bg-elevated",
38
- "aria-label": F,
38
+ "aria-label": R,
39
39
  "aria-haspopup": "menu",
40
- "aria-expanded": v,
40
+ "aria-expanded": y,
41
41
  "data-testid": "assistant-more",
42
- children: /* @__PURE__ */ h(f, { className: "size-4 text-text-secondary" })
43
- }), v ? /* @__PURE__ */ g("div", {
44
- ref: b,
42
+ children: /* @__PURE__ */ g(f, { className: "size-4 text-text-secondary" })
43
+ }), y ? /* @__PURE__ */ _("div", {
44
+ ref: x,
45
45
  role: "menu",
46
- "aria-label": F,
46
+ "aria-label": R,
47
47
  className: "absolute right-0 top-full z-50 mt-1 min-w-56 overflow-hidden rounded-xl border border-border-default bg-bg-surface py-1 shadow-lg",
48
48
  "data-testid": "assistant-more-menu",
49
49
  children: [
50
- E ? /* @__PURE__ */ g("button", {
50
+ D ? /* @__PURE__ */ _("button", {
51
51
  type: "button",
52
52
  role: "menuitemcheckbox",
53
- "aria-checked": k,
54
- onClick: P,
55
- disabled: M,
56
- title: M ? O ?? void 0 : void 0,
53
+ "aria-checked": A,
54
+ onClick: L,
55
+ disabled: F,
56
+ title: F ? k ?? void 0 : void 0,
57
57
  className: "flex w-full items-center gap-2.5 px-3 py-2 text-left text-xs text-text-primary transition-colors hover:bg-bg-elevated disabled:cursor-not-allowed disabled:text-text-muted disabled:hover:bg-transparent",
58
58
  "data-testid": "assistant-auto-speak",
59
59
  children: [
60
- /* @__PURE__ */ h(p, {
60
+ /* @__PURE__ */ g(m, {
61
61
  className: "size-3.5 flex-shrink-0 text-text-secondary",
62
62
  "aria-hidden": "true"
63
63
  }),
64
- /* @__PURE__ */ h("span", {
64
+ /* @__PURE__ */ g("span", {
65
65
  className: "flex-1",
66
- children: _("healthybowl.assistant.header.autoRead", "Auto-read replies")
66
+ children: v("healthybowl.assistant.header.autoRead", "Auto-read replies")
67
67
  }),
68
- k ? /* @__PURE__ */ h(l, { className: "size-3.5 flex-shrink-0 text-action-primary-bg" }) : null
68
+ A ? /* @__PURE__ */ g(l, { className: "size-3.5 flex-shrink-0 text-action-primary-bg" }) : null
69
69
  ]
70
70
  }) : null,
71
- /* @__PURE__ */ h("div", {
72
- className: "px-3 py-1.5",
71
+ /* @__PURE__ */ _("div", {
72
+ className: "flex items-center gap-1 px-3 py-1.5",
73
73
  "data-testid": "assistant-more-voice",
74
- children: /* @__PURE__ */ h(a, {})
74
+ children: [/* @__PURE__ */ g(a, {}), P ? /* @__PURE__ */ _("button", {
75
+ type: "button",
76
+ onClick: () => N(P),
77
+ className: "flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] text-text-muted transition-colors hover:bg-bg-elevated hover:text-text-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong",
78
+ "aria-label": v("healthybowl.assistant.voice.preview", "Hear this voice"),
79
+ "data-testid": "assistant-voice-preview",
80
+ children: [/* @__PURE__ */ g(p, {
81
+ className: "size-3",
82
+ "aria-hidden": "true"
83
+ }), v("healthybowl.assistant.voice.previewShort", "Preview")]
84
+ }) : null]
75
85
  }),
76
- T ? /* @__PURE__ */ g(m, { children: [
77
- /* @__PURE__ */ h("div", {
86
+ E ? /* @__PURE__ */ _(h, { children: [
87
+ /* @__PURE__ */ g("div", {
78
88
  className: "my-1 border-t border-border-subtle",
79
89
  role: "separator"
80
90
  }),
81
- /* @__PURE__ */ g("button", {
91
+ /* @__PURE__ */ _("button", {
82
92
  type: "button",
83
93
  role: "menuitem",
84
- onClick: () => N("json"),
94
+ onClick: () => I("json"),
85
95
  className: "flex w-full items-center gap-2.5 px-3 py-2 text-left text-xs text-text-primary transition-colors hover:bg-bg-elevated",
86
96
  "data-testid": "export-json",
87
- children: [/* @__PURE__ */ h(u, {
97
+ children: [/* @__PURE__ */ g(u, {
88
98
  className: "size-3.5 flex-shrink-0 text-text-secondary",
89
99
  "aria-hidden": "true"
90
- }), _("healthybowl.assistant.export.json", "Export as JSON")]
100
+ }), v("healthybowl.assistant.export.json", "Export as JSON")]
91
101
  }),
92
- /* @__PURE__ */ g("button", {
102
+ /* @__PURE__ */ _("button", {
93
103
  type: "button",
94
104
  role: "menuitem",
95
- onClick: () => N("markdown"),
105
+ onClick: () => I("markdown"),
96
106
  className: "flex w-full items-center gap-2.5 px-3 py-2 text-left text-xs text-text-primary transition-colors hover:bg-bg-elevated",
97
107
  "data-testid": "export-markdown",
98
- children: [/* @__PURE__ */ h(d, {
108
+ children: [/* @__PURE__ */ g(d, {
99
109
  className: "size-3.5 flex-shrink-0 text-text-secondary",
100
110
  "aria-hidden": "true"
101
- }), _("healthybowl.assistant.export.markdown", "Export as Markdown")]
111
+ }), v("healthybowl.assistant.export.markdown", "Export as Markdown")]
102
112
  })
103
113
  ] }) : null
104
114
  ]
@@ -106,6 +116,6 @@ var _ = () => {
106
116
  });
107
117
  };
108
118
  //#endregion
109
- export { _ as AssistantMoreMenu };
119
+ export { v as AssistantMoreMenu };
110
120
 
111
121
  //# sourceMappingURL=AssistantMoreMenu.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantMoreMenu.js","names":[],"sources":["../../../src/components/assistant/AssistantMoreMenu.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type FC } from 'react';\nimport { Check, FileJson, FileText, MoreHorizontal, Volume2 } from 'lucide-react';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { exportConversation, downloadFile } from '@/services/assistantExportService';\nimport { useAssistantSpeech } from './AssistantSpeechProvider';\nimport { AssistantVoiceSelector } from './composer/AssistantVoiceSelector';\nimport { useTr } from '../../shared/hooks/useTr';\n\n/**\n * The header's secondary surface — everything that CONFIGURES the assistant.\n *\n * ★ `+` supplies content, `⋯` configures. Keeping those two meanings apart is\n * the point: the header carried seven controls, and three of them\n * (auto-read, the voice picker, export) render null under conditions the user\n * cannot see — no speech support, fewer than two voices, an empty conversation —\n * so the row silently changed width between devices and between the first and\n * second message of the same session.\n *\n * Now four primary controls, always present, and one menu that absorbs the\n * conditional ones. A menu ROW may still hide itself; a menu that keeps its\n * position while its contents vary is a much smaller surprise than a toolbar\n * that reflows.\n *\n * ★ Export is FLATTENED into this menu rather than nested inside it. It was\n * itself a dropdown, and a dropdown inside a dropdown is two Escape presses and\n * two outside-click regions for two menu items.\n *\n * ★ The voice picker keeps its native `<select>`. It is deliberate — see that\n * component — and a custom listbox would look tidier in a screenshot while being\n * worse on the phones this product is used on. Because the select lives inside\n * the menu's own subtree, the outside-click handler ignores clicks on it.\n *\n * Not included, deliberately: Live captions and Assistant settings have nothing\n * behind them yet, and a Transcript entry needs a product decision first (the\n * voice transcript is session-scoped, while the chat thread is always visible —\n * one menu label cannot honestly mean both).\n */\nexport const AssistantMoreMenu: FC = () => {\n const tr = useTr();\n const [open, setOpen] = useState(false);\n const menuRef = useRef<HTMLDivElement>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n\n const { conversations, activeConversationId } = useAssistantStore();\n const activeConversation = conversations.find((conversation) => conversation.id === activeConversationId);\n const canExport = Boolean(activeConversation && activeConversation.messages.length > 0);\n\n const { isSupported, isBlocked, disabledReason, autoSpeakEnabled, setAutoSpeak, stop } = useAssistantSpeech();\n // Blocked and already off means turning it on would do nothing audible.\n const autoReadDisabled = isBlocked && !autoSpeakEnabled;\n\n useEffect(() => {\n if (!open) return;\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n setOpen(false);\n buttonRef.current?.focus();\n }\n };\n const onPointerDown = (event: MouseEvent) => {\n const target = event.target as Node;\n if (menuRef.current?.contains(target) || buttonRef.current?.contains(target)) return;\n setOpen(false);\n };\n window.addEventListener('keydown', onKeyDown);\n document.addEventListener('mousedown', onPointerDown);\n return () => {\n window.removeEventListener('keydown', onKeyDown);\n document.removeEventListener('mousedown', onPointerDown);\n };\n }, [open]);\n\n const handleExport = (format: 'json' | 'markdown') => {\n if (!activeConversation) return;\n const { content, filename, mimeType } = exportConversation(activeConversation, format);\n downloadFile(content, filename, mimeType);\n setOpen(false);\n };\n\n const toggleAutoRead = () => {\n // Turning it OFF stops whatever is speaking now: leaving audio running\n // after the user switched the feature off reads as the control not working.\n if (autoSpeakEnabled) stop();\n setAutoSpeak(!autoSpeakEnabled);\n };\n\n const label = tr('healthybowl.assistant.header.more', 'More options');\n\n return (\n <div className=\"relative\">\n <button\n ref={buttonRef}\n type=\"button\"\n onClick={() => setOpen((wasOpen) => !wasOpen)}\n className=\"rounded p-1 transition-colors hover:bg-bg-elevated\"\n aria-label={label}\n aria-haspopup=\"menu\"\n aria-expanded={open}\n data-testid=\"assistant-more\"\n >\n <MoreHorizontal className=\"size-4 text-text-secondary\" />\n </button>\n\n {open ? (\n <div\n ref={menuRef}\n role=\"menu\"\n aria-label={label}\n className=\"absolute right-0 top-full z-50 mt-1 min-w-56 overflow-hidden rounded-xl border border-border-default bg-bg-surface py-1 shadow-lg\"\n data-testid=\"assistant-more-menu\"\n >\n {isSupported ? (\n <button\n type=\"button\"\n role=\"menuitemcheckbox\"\n aria-checked={autoSpeakEnabled}\n onClick={toggleAutoRead}\n disabled={autoReadDisabled}\n title={autoReadDisabled ? (disabledReason ?? undefined) : undefined}\n className=\"flex w-full items-center gap-2.5 px-3 py-2 text-left text-xs text-text-primary transition-colors hover:bg-bg-elevated disabled:cursor-not-allowed disabled:text-text-muted disabled:hover:bg-transparent\"\n data-testid=\"assistant-auto-speak\"\n >\n <Volume2 className=\"size-3.5 flex-shrink-0 text-text-secondary\" aria-hidden=\"true\" />\n <span className=\"flex-1\">{tr('healthybowl.assistant.header.autoRead', 'Auto-read replies')}</span>\n {/* State as a tick rather than the word \"On\": the row is already a\n checkbox to assistive technology via aria-checked. */}\n {autoSpeakEnabled ? <Check className=\"size-3.5 flex-shrink-0 text-action-primary-bg\" /> : null}\n </button>\n ) : null}\n\n {/* Renders nothing when the device offers fewer than two voices, which\n is most of them until a hosted TTS endpoint is configured. */}\n <div className=\"px-3 py-1.5\" data-testid=\"assistant-more-voice\">\n <AssistantVoiceSelector />\n </div>\n\n {canExport ? (\n <>\n <div className=\"my-1 border-t border-border-subtle\" role=\"separator\" />\n <button\n type=\"button\"\n role=\"menuitem\"\n onClick={() => handleExport('json')}\n className=\"flex w-full items-center gap-2.5 px-3 py-2 text-left text-xs text-text-primary transition-colors hover:bg-bg-elevated\"\n data-testid=\"export-json\"\n >\n <FileJson className=\"size-3.5 flex-shrink-0 text-text-secondary\" aria-hidden=\"true\" />\n {tr('healthybowl.assistant.export.json', 'Export as JSON')}\n </button>\n <button\n type=\"button\"\n role=\"menuitem\"\n onClick={() => handleExport('markdown')}\n className=\"flex w-full items-center gap-2.5 px-3 py-2 text-left text-xs text-text-primary transition-colors hover:bg-bg-elevated\"\n data-testid=\"export-markdown\"\n >\n <FileText className=\"size-3.5 flex-shrink-0 text-text-secondary\" aria-hidden=\"true\" />\n {tr('healthybowl.assistant.export.markdown', 'Export as Markdown')}\n </button>\n </>\n ) : null}\n </div>\n ) : null}\n </div>\n );\n};\n"],"mappings":";;;;;;;;;AAqCA,IAAa,UAA8B;CACzC,IAAM,IAAK,EAAM,GAC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EAAgB,WAAU,6BAA8B,CAAA;EAClD,CAAA,GAEP,IACC,kBAAC,OAAD;GACE,KAAK;GACL,MAAK;GACL,cAAY;GACZ,WAAU;GACV,eAAY;aALd;IAOG,IACC,kBAAC,UAAD;KACE,MAAK;KACL,MAAK;KACL,gBAAc;KACd,SAAS;KACT,UAAU;KACV,OAAO,IAAoB,KAAkB,KAAA,IAAa,KAAA;KAC1D,WAAU;KACV,eAAY;eARd;MAUE,kBAAC,GAAD;OAAS,WAAU;OAA6C,eAAY;MAAQ,CAAA;MACpF,kBAAC,QAAD;OAAM,WAAU;iBAAU,EAAG,yCAAyC,mBAAmB;MAAQ,CAAA;MAGhG,IAAmB,kBAAC,GAAD,EAAO,WAAU,gDAAiD,CAAA,IAAI;KACpF;SACN;IAIJ,kBAAC,OAAD;KAAK,WAAU;KAAc,eAAY;eACvC,kBAAC,GAAD,CAAyB,CAAA;IACtB,CAAA;IAEJ,IACC,kBAAA,GAAA,EAAA,UAAA;KACE,kBAAC,OAAD;MAAK,WAAU;MAAqC,MAAK;KAAa,CAAA;KACtE,kBAAC,UAAD;MACE,MAAK;MACL,MAAK;MACL,eAAe,EAAa,MAAM;MAClC,WAAU;MACV,eAAY;gBALd,CAOE,kBAAC,GAAD;OAAU,WAAU;OAA6C,eAAY;MAAQ,CAAA,GACpF,EAAG,qCAAqC,gBAAgB,CACnD;;KACR,kBAAC,UAAD;MACE,MAAK;MACL,MAAK;MACL,eAAe,EAAa,UAAU;MACtC,WAAU;MACV,eAAY;gBALd,CAOE,kBAAC,GAAD;OAAU,WAAU;OAA6C,eAAY;MAAQ,CAAA,GACpF,EAAG,yCAAyC,oBAAoB,CAC3D;;IACR,EAAA,CAAA,IACA;GACD;OACH,IACD;;AAET"}
1
+ {"version":3,"file":"AssistantMoreMenu.js","names":[],"sources":["../../../src/components/assistant/AssistantMoreMenu.tsx"],"sourcesContent":["import { useEffect, useRef, useState, type FC } from 'react';\nimport { Check, FileJson, FileText, MoreHorizontal, Play, Volume2 } from 'lucide-react';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { exportConversation, downloadFile } from '@/services/assistantExportService';\nimport { useAssistantSpeech } from './AssistantSpeechProvider';\nimport { AssistantVoiceSelector } from './composer/AssistantVoiceSelector';\nimport { useTr } from '../../shared/hooks/useTr';\n\n/**\n * The header's secondary surface — everything that CONFIGURES the assistant.\n *\n * ★ `+` supplies content, `⋯` configures. Keeping those two meanings apart is\n * the point: the header carried seven controls, and three of them\n * (auto-read, the voice picker, export) render null under conditions the user\n * cannot see — no speech support, fewer than two voices, an empty conversation —\n * so the row silently changed width between devices and between the first and\n * second message of the same session.\n *\n * Now four primary controls, always present, and one menu that absorbs the\n * conditional ones. A menu ROW may still hide itself; a menu that keeps its\n * position while its contents vary is a much smaller surprise than a toolbar\n * that reflows.\n *\n * ★ Export is FLATTENED into this menu rather than nested inside it. It was\n * itself a dropdown, and a dropdown inside a dropdown is two Escape presses and\n * two outside-click regions for two menu items.\n *\n * ★ The voice picker keeps its native `<select>`. It is deliberate — see that\n * component — and a custom listbox would look tidier in a screenshot while being\n * worse on the phones this product is used on. Because the select lives inside\n * the menu's own subtree, the outside-click handler ignores clicks on it.\n *\n * Not included, deliberately: Live captions and Assistant settings have nothing\n * behind them yet, and a Transcript entry needs a product decision first (the\n * voice transcript is session-scoped, while the chat thread is always visible —\n * one menu label cannot honestly mean both).\n */\nexport const AssistantMoreMenu: FC = () => {\n const tr = useTr();\n const [open, setOpen] = useState(false);\n const menuRef = useRef<HTMLDivElement>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n\n const { conversations, activeConversationId } = useAssistantStore();\n const activeConversation = conversations.find((conversation) => conversation.id === activeConversationId);\n const canExport = Boolean(activeConversation && activeConversation.messages.length > 0);\n\n const {\n isSupported,\n isBlocked,\n disabledReason,\n autoSpeakEnabled,\n setAutoSpeak,\n stop,\n previewVoice,\n activeVoiceName,\n } = useAssistantSpeech();\n // Blocked and already off means turning it on would do nothing audible.\n const autoReadDisabled = isBlocked && !autoSpeakEnabled;\n\n useEffect(() => {\n if (!open) return;\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n setOpen(false);\n buttonRef.current?.focus();\n }\n };\n const onPointerDown = (event: MouseEvent) => {\n const target = event.target as Node;\n if (menuRef.current?.contains(target) || buttonRef.current?.contains(target)) return;\n setOpen(false);\n };\n window.addEventListener('keydown', onKeyDown);\n document.addEventListener('mousedown', onPointerDown);\n return () => {\n window.removeEventListener('keydown', onKeyDown);\n document.removeEventListener('mousedown', onPointerDown);\n };\n }, [open]);\n\n const handleExport = (format: 'json' | 'markdown') => {\n if (!activeConversation) return;\n const { content, filename, mimeType } = exportConversation(activeConversation, format);\n downloadFile(content, filename, mimeType);\n setOpen(false);\n };\n\n const toggleAutoRead = () => {\n // Turning it OFF stops whatever is speaking now: leaving audio running\n // after the user switched the feature off reads as the control not working.\n if (autoSpeakEnabled) stop();\n setAutoSpeak(!autoSpeakEnabled);\n };\n\n const label = tr('healthybowl.assistant.header.more', 'More options');\n\n return (\n <div className=\"relative\">\n <button\n ref={buttonRef}\n type=\"button\"\n onClick={() => setOpen((wasOpen) => !wasOpen)}\n className=\"rounded p-1 transition-colors hover:bg-bg-elevated\"\n aria-label={label}\n aria-haspopup=\"menu\"\n aria-expanded={open}\n data-testid=\"assistant-more\"\n >\n <MoreHorizontal className=\"size-4 text-text-secondary\" />\n </button>\n\n {open ? (\n <div\n ref={menuRef}\n role=\"menu\"\n aria-label={label}\n className=\"absolute right-0 top-full z-50 mt-1 min-w-56 overflow-hidden rounded-xl border border-border-default bg-bg-surface py-1 shadow-lg\"\n data-testid=\"assistant-more-menu\"\n >\n {isSupported ? (\n <button\n type=\"button\"\n role=\"menuitemcheckbox\"\n aria-checked={autoSpeakEnabled}\n onClick={toggleAutoRead}\n disabled={autoReadDisabled}\n title={autoReadDisabled ? (disabledReason ?? undefined) : undefined}\n className=\"flex w-full items-center gap-2.5 px-3 py-2 text-left text-xs text-text-primary transition-colors hover:bg-bg-elevated disabled:cursor-not-allowed disabled:text-text-muted disabled:hover:bg-transparent\"\n data-testid=\"assistant-auto-speak\"\n >\n <Volume2 className=\"size-3.5 flex-shrink-0 text-text-secondary\" aria-hidden=\"true\" />\n <span className=\"flex-1\">{tr('healthybowl.assistant.header.autoRead', 'Auto-read replies')}</span>\n {/* State as a tick rather than the word \"On\": the row is already a\n checkbox to assistive technology via aria-checked. */}\n {autoSpeakEnabled ? <Check className=\"size-3.5 flex-shrink-0 text-action-primary-bg\" /> : null}\n </button>\n ) : null}\n\n {/* Renders nothing when the device offers fewer than two voices, which\n is most of them until a hosted TTS endpoint is configured. */}\n <div className=\"flex items-center gap-1 px-3 py-1.5\" data-testid=\"assistant-more-voice\">\n <AssistantVoiceSelector />\n {/* ★ Auditioning a voice used to cost a round trip: you picked one,\n nothing happened, and you first heard it after asking a real\n question. This speaks a short sample straight through the engine —\n no model call, no message in the thread, no tokens. Shown only\n once a voice has resolved, so it can never be a dead control. */}\n {activeVoiceName ? (\n <button\n type=\"button\"\n onClick={() => previewVoice(activeVoiceName)}\n className=\"flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] text-text-muted transition-colors hover:bg-bg-elevated hover:text-text-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong\"\n aria-label={tr('healthybowl.assistant.voice.preview', 'Hear this voice')}\n data-testid=\"assistant-voice-preview\"\n >\n <Play className=\"size-3\" aria-hidden=\"true\" />\n {tr('healthybowl.assistant.voice.previewShort', 'Preview')}\n </button>\n ) : null}\n </div>\n\n {canExport ? (\n <>\n <div className=\"my-1 border-t border-border-subtle\" role=\"separator\" />\n <button\n type=\"button\"\n role=\"menuitem\"\n onClick={() => handleExport('json')}\n className=\"flex w-full items-center gap-2.5 px-3 py-2 text-left text-xs text-text-primary transition-colors hover:bg-bg-elevated\"\n data-testid=\"export-json\"\n >\n <FileJson className=\"size-3.5 flex-shrink-0 text-text-secondary\" aria-hidden=\"true\" />\n {tr('healthybowl.assistant.export.json', 'Export as JSON')}\n </button>\n <button\n type=\"button\"\n role=\"menuitem\"\n onClick={() => handleExport('markdown')}\n className=\"flex w-full items-center gap-2.5 px-3 py-2 text-left text-xs text-text-primary transition-colors hover:bg-bg-elevated\"\n data-testid=\"export-markdown\"\n >\n <FileText className=\"size-3.5 flex-shrink-0 text-text-secondary\" aria-hidden=\"true\" />\n {tr('healthybowl.assistant.export.markdown', 'Export as Markdown')}\n </button>\n </>\n ) : null}\n </div>\n ) : null}\n </div>\n );\n};\n"],"mappings":";;;;;;;;;AAqCA,IAAa,UAA8B;CACzC,IAAM,IAAK,EAAM,GACX,CAAC,GAAM,KAAW,EAAS,EAAK,GAChC,IAAU,EAAuB,IAAI,GACrC,IAAY,EAA0B,IAAI,GAE1C,EAAE,kBAAe,4BAAyB,EAAkB,GAC5D,IAAqB,EAAc,MAAM,MAAiB,EAAa,OAAO,CAAoB,GAClG,IAAY,GAAQ,KAAsB,EAAmB,SAAS,SAAS,IAE/E,EACJ,gBACA,cACA,mBACA,qBACA,iBACA,SACA,iBACA,uBACE,EAAmB,GAEjB,IAAmB,KAAa,CAAC;CAEvC,QAAgB;EACd,IAAI,CAAC,GAAM;EACX,IAAM,KAAa,MAAyB;GAC1C,AAAI,EAAM,QAAQ,aAChB,EAAQ,EAAK,GACb,EAAU,SAAS,MAAM;EAE7B,GACM,KAAiB,MAAsB;GAC3C,IAAM,IAAS,EAAM;GACjB,EAAQ,SAAS,SAAS,CAAM,KAAK,EAAU,SAAS,SAAS,CAAM,KAC3E,EAAQ,EAAK;EACf;EAGA,OAFA,OAAO,iBAAiB,WAAW,CAAS,GAC5C,SAAS,iBAAiB,aAAa,CAAa,SACvC;GAEX,AADA,OAAO,oBAAoB,WAAW,CAAS,GAC/C,SAAS,oBAAoB,aAAa,CAAa;EACzD;CACF,GAAG,CAAC,CAAI,CAAC;CAET,IAAM,KAAgB,MAAgC;EACpD,IAAI,CAAC,GAAoB;EACzB,IAAM,EAAE,YAAS,aAAU,gBAAa,EAAm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U;MAAqC,MAAK;KAAa,CAAA;KACtE,kBAAC,UAAD;MACE,MAAK;MACL,MAAK;MACL,eAAe,EAAa,MAAM;MAClC,WAAU;MACV,eAAY;gBALd,CAOE,kBAAC,GAAD;OAAU,WAAU;OAA6C,eAAY;MAAQ,CAAA,GACpF,EAAG,qCAAqC,gBAAgB,CACnD;;KACR,kBAAC,UAAD;MACE,MAAK;MACL,MAAK;MACL,eAAe,EAAa,UAAU;MACtC,WAAU;MACV,eAAY;gBALd,CAOE,kBAAC,GAAD;OAAU,WAAU;OAA6C,eAAY;MAAQ,CAAA,GACpF,EAAG,yCAAyC,oBAAoB,CAC3D;;IACR,EAAA,CAAA,IACA;GACD;OACH,IACD;;AAET"}
@@ -2,19 +2,20 @@ import { getSpeechEngine as e } from "../../services/speech/createSpeechEngine.j
2
2
  import "../../services/speech/index.js";
3
3
  import { useAssistantStore as t } from "../../store/assistantStore.js";
4
4
  import { useTr as n } from "../../shared/hooks/useTr.js";
5
- import { chunkForSpeech as r, toSpeakableText as i } from "../../utils/speakableText.js";
6
- import { speechLabelsFor as a } from "../../config/speechLabels.js";
7
- import { VOICE_LIST_TIMEOUT_MS as o, languageDisplayName as s, selectVoiceForLocale as c, speechGate as ee, speechLangForLocale as l, voiceAvailability as u, voicesForLocale as d } from "../../utils/speechVoices.js";
8
- import { resolveSpeechLocale as te } from "../../utils/replyLanguage.js";
9
- import { findAssistantLanguage as f, resolveAssistantLanguage as ne } from "../../config/assistantLanguages.js";
10
- import { IDLE_PLAYBACK as re, isSpeakingMessage as p, speechPlaybackReducer as ie } from "../../utils/speechPlayback.js";
11
- import { isTurnInFlight as ae } from "../../utils/assistantTurnState.js";
12
- import { parseToolActivity as oe } from "./AssistantToolActivity.js";
13
- import { createContext as m, useCallback as h, useContext as g, useEffect as _, useMemo as v, useReducer as se, useRef as y, useState as b } from "react";
14
- import { useI18n as ce } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
15
- import { jsx as le } from "react/jsx-runtime";
5
+ import { voicePreviewText as r } from "../../utils/voicePreview.js";
6
+ import { chunkForSpeech as i, toSpeakableText as a } from "../../utils/speakableText.js";
7
+ import { speechLabelsFor as o } from "../../config/speechLabels.js";
8
+ import { VOICE_LIST_TIMEOUT_MS as s, languageDisplayName as ee, selectVoiceForLocale as c, speechGate as te, speechLangForLocale as l, voiceAvailability as u, voicesForLocale as ne } from "../../utils/speechVoices.js";
9
+ import { resolveSpeechLocale as re } from "../../utils/replyLanguage.js";
10
+ import { findAssistantLanguage as d, resolveAssistantLanguage as ie } from "../../config/assistantLanguages.js";
11
+ import { IDLE_PLAYBACK as ae, isSpeakingMessage as f, speechPlaybackReducer as oe } from "../../utils/speechPlayback.js";
12
+ import { isTurnInFlight as se } from "../../utils/assistantTurnState.js";
13
+ import { parseToolActivity as ce } from "./AssistantToolActivity.js";
14
+ import { createContext as p, useCallback as m, useContext as h, useEffect as g, useMemo as _, useReducer as le, useRef as v, useState as y } from "react";
15
+ import { useI18n as ue } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
16
+ import { jsx as de } from "react/jsx-runtime";
16
17
  //#region src/components/assistant/AssistantSpeechProvider.tsx
17
- var ue = {
18
+ var fe = {
18
19
  codeBlock: "",
19
20
  image: "",
20
21
  link: "",
@@ -23,7 +24,7 @@ var ue = {
23
24
  emailAt: "at",
24
25
  emailDot: "dot",
25
26
  nestedItem: ""
26
- }, x = m({
27
+ }, b = p({
27
28
  isSupported: !1,
28
29
  availability: "unsupported",
29
30
  isBlocked: !0,
@@ -40,221 +41,235 @@ var ue = {
40
41
  autoSpeakEnabled: !1,
41
42
  setAutoSpeak: () => {},
42
43
  sessionSpeaking: !1,
43
- setSessionSpeaking: () => {}
44
+ setSessionSpeaking: () => {},
45
+ previewVoice: () => {}
44
46
  });
45
- function S() {
46
- return g(x);
47
+ function x() {
48
+ return h(b);
47
49
  }
48
- var C = ({ children: m, visible: g = !0, engine: S = e() }) => {
49
- let C = n(), { locale: w } = ce(), [T, E] = se(ie, re), [D, O] = b(() => S.listVoices()), [k, A] = b(!1), [j, M] = b(() => /* @__PURE__ */ new Map()), N = y(0), P = y(null), F = y(() => {}), I = h(() => {
50
- P.current?.(), P.current = null;
51
- }, []), L = t((e) => e.autoSpeakEnabled), R = t((e) => e.setAutoSpeak), [z, de] = b(!1), fe = t((e) => e.activeConversationId), B = v(() => S.isSupported(), [S]);
52
- _(() => {
53
- if (!B) return;
50
+ var S = ({ children: p, visible: h = !0, engine: x = e() }) => {
51
+ let S = n(), { locale: C } = ue(), [w, T] = le(oe, ae), [E, D] = y(() => x.listVoices()), [O, k] = y(!1), [A, j] = y(() => /* @__PURE__ */ new Map()), M = v(0), N = v(null), P = v(() => {}), F = m(() => {
52
+ N.current?.(), N.current = null;
53
+ }, []), I = t((e) => e.autoSpeakEnabled), L = t((e) => e.setAutoSpeak), [R, pe] = y(!1), me = t((e) => e.activeConversationId), z = _(() => x.isSupported(), [x]);
54
+ g(() => {
55
+ if (!z) return;
54
56
  let e = () => {
55
- O(S.listVoices()), M((e) => e.size === 0 ? e : /* @__PURE__ */ new Map());
57
+ D(x.listVoices()), j((e) => e.size === 0 ? e : /* @__PURE__ */ new Map());
56
58
  };
57
- return e(), S.subscribeVoices(e);
58
- }, [S, B]);
59
- let V = t((e) => e.assistantLanguage), H = t((e) => e.preferredVoices), U = t((e) => e.setPreferredVoice), W = v(() => ne(V, w), [V, w]), G = W.code, K = h((e) => f(e)?.tag ?? l(e), []), q = h((e) => f(e)?.rate ?? .9, []), J = v(() => u(B, D, W.tag, k), [
60
- B,
61
- D,
59
+ return e(), x.subscribeVoices(e);
60
+ }, [x, z]);
61
+ let B = t((e) => e.assistantLanguage), V = t((e) => e.preferredVoices), H = t((e) => e.setPreferredVoice), U = _(() => ie(B, C), [B, C]), W = U.code, G = m((e) => d(e)?.tag ?? l(e), []), K = m((e) => d(e)?.rate ?? .9, []), q = _(() => u(z, E, U.tag, O), [
62
+ z,
63
+ E,
64
+ U,
65
+ O
66
+ ]), J = _(() => ({
67
+ codeBlock: S("healthybowl.assistant.speech.codeBlock", "Code block"),
68
+ image: S("healthybowl.assistant.speech.image", "image"),
69
+ link: S("healthybowl.assistant.speech.link", "link"),
70
+ largeTable: S("healthybowl.assistant.speech.largeTable", "Table with {{rows}} rows and {{columns}} columns"),
71
+ truncated: S("healthybowl.assistant.speech.truncated", "The rest of this message is not read aloud"),
72
+ nestedItem: S("healthybowl.assistant.speech.nestedItem", "Sub-item {{ordinal}}"),
73
+ emailAt: S("healthybowl.assistant.speech.emailAt", "at"),
74
+ emailDot: S("healthybowl.assistant.speech.emailDot", "dot")
75
+ }), [S]), Y = m(() => {
76
+ F(), x.cancel(), T({ type: "stop" });
77
+ }, [F, x]), X = m((e) => {
78
+ let t = x.listVoices().find((t) => t.name === e) ?? null;
79
+ t && (Y(), x.speak([r(W)], {
80
+ voice: t,
81
+ lang: G(W)
82
+ }));
83
+ }, [
84
+ x,
62
85
  W,
63
- k
64
- ]), Y = v(() => ({
65
- codeBlock: C("healthybowl.assistant.speech.codeBlock", "Code block"),
66
- image: C("healthybowl.assistant.speech.image", "image"),
67
- link: C("healthybowl.assistant.speech.link", "link"),
68
- largeTable: C("healthybowl.assistant.speech.largeTable", "Table with {{rows}} rows and {{columns}} columns"),
69
- truncated: C("healthybowl.assistant.speech.truncated", "The rest of this message is not read aloud"),
70
- nestedItem: C("healthybowl.assistant.speech.nestedItem", "Sub-item {{ordinal}}"),
71
- emailAt: C("healthybowl.assistant.speech.emailAt", "at"),
72
- emailDot: C("healthybowl.assistant.speech.emailDot", "dot")
73
- }), [C]), X = h(() => {
74
- I(), S.cancel(), E({ type: "stop" });
75
- }, [I, S]), Z = h((e) => j.get(e) ?? null, [j]), pe = h((e, t, n) => {
76
- I();
86
+ Y,
87
+ G
88
+ ]), he = m((e) => A.get(e) ?? null, [A]), ge = m((e, t, n) => {
89
+ F();
77
90
  let r = !1, i = () => {}, a = (a) => {
78
91
  if (!r) {
79
- if (r = !0, P.current = null, clearTimeout(s), i(), a.length === 0) {
80
- A(!0);
92
+ if (r = !0, N.current = null, clearTimeout(o), i(), a.length === 0) {
93
+ k(!0);
81
94
  return;
82
95
  }
83
- O(a), F.current(e, t, a, n);
96
+ D(a), P.current(e, t, a, n);
84
97
  }
85
- }, s = setTimeout(() => a(S.listVoices()), o);
86
- i = S.subscribeVoices(() => a(S.listVoices())), P.current = () => {
87
- r || (r = !0, clearTimeout(s), i(), P.current = null);
98
+ }, o = setTimeout(() => a(x.listVoices()), s);
99
+ i = x.subscribeVoices(() => a(x.listVoices())), N.current = () => {
100
+ r || (r = !0, clearTimeout(o), i(), N.current = null);
88
101
  };
89
- }, [I, S]), Q = h((e, t, n, i) => {
102
+ }, [F, x]), Z = m((e, t, n, r) => {
90
103
  let a = n;
91
104
  if (a.length === 0) {
92
- let e = S.listVoices();
93
- e.length > 0 && (a = e, O(e));
105
+ let e = x.listVoices();
106
+ e.length > 0 && (a = e, D(e));
94
107
  }
95
- let o = K(i), l = ee(u(!0, a, i, k));
96
- if (l === "block") {
97
- let t = C("healthybowl.assistant.speech.noVoiceForReply", "This reply is in {{language}}, and no {{language}} voice is installed on this device.", { language: s(o, w) });
98
- M((n) => new Map(n).set(e, t));
108
+ let o = G(r), s = te(u(!0, a, r, O));
109
+ if (s === "block") {
110
+ 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) });
111
+ j((n) => new Map(n).set(e, t));
99
112
  return;
100
113
  }
101
- if (l === "wait-for-voices") {
102
- pe(e, t, i);
114
+ if (s === "wait-for-voices") {
115
+ ge(e, t, r);
103
116
  return;
104
117
  }
105
- M((t) => {
118
+ j((t) => {
106
119
  if (!t.has(e)) return t;
107
120
  let n = new Map(t);
108
121
  return n.delete(e), n;
109
122
  });
110
- let d = N.current + 1;
111
- N.current = d, E({
123
+ let l = M.current + 1;
124
+ M.current = l, T({
112
125
  type: "start",
113
126
  messageId: e,
114
- requestId: d
115
- }), S.speak(r(t), {
116
- voice: c(a, o, H[i]),
127
+ requestId: l
128
+ }), x.speak(i(t), {
129
+ voice: c(a, o, V[r]),
117
130
  lang: o,
118
- rate: q(i)
131
+ rate: K(r)
119
132
  }, {
120
- onEnd: () => E({
133
+ onEnd: () => T({
121
134
  type: "finished",
122
- requestId: d
135
+ requestId: l
123
136
  }),
124
- onError: () => E({
137
+ onError: () => T({
125
138
  type: "failed",
126
- requestId: d
139
+ requestId: l
127
140
  })
128
141
  });
129
142
  }, [
130
- S,
131
- w,
132
- H,
133
- q,
134
- K,
143
+ x,
135
144
  C,
136
- k,
137
- pe
145
+ V,
146
+ K,
147
+ G,
148
+ S,
149
+ O,
150
+ ge
138
151
  ]);
139
- _(() => {
140
- F.current = Q;
141
- }, [Q]);
142
- let $ = h((e, t, n) => {
143
- if (!B) return;
144
- let r = te(i(t, { labels: ue }), n ?? G), o = i(t, { labels: a(r, Y) });
145
- o && Q(e, o, D, r);
152
+ g(() => {
153
+ P.current = Z;
154
+ }, [Z]);
155
+ let Q = m((e, t, n) => {
156
+ if (!z) return;
157
+ let r = re(a(t, { labels: fe }), n ?? W), i = a(t, { labels: o(r, J) });
158
+ i && Z(e, i, E, r);
146
159
  }, [
147
- B,
148
- Y,
149
- G,
150
- Q,
151
- D
152
- ]), me = h((e, t, n) => {
153
- if (p(T, e)) {
154
- X();
160
+ z,
161
+ J,
162
+ W,
163
+ Z,
164
+ E
165
+ ]), _e = m((e, t, n) => {
166
+ if (f(w, e)) {
167
+ Y();
155
168
  return;
156
169
  }
157
- $(e, t, n);
170
+ Q(e, t, n);
158
171
  }, [
159
- T,
160
- $,
161
- X
172
+ w,
173
+ Q,
174
+ Y
162
175
  ]);
163
- _(() => {
164
- g || X();
165
- }, [g, X]), _(() => {
166
- X(), M(/* @__PURE__ */ new Map());
167
- }, [fe, X]), _(() => {
168
- M((e) => e.size === 0 ? e : /* @__PURE__ */ new Map()), X();
169
- }, [G, X]), _(() => () => {
170
- P.current?.(), P.current = null, S.cancel();
171
- }, [S]), _(() => {
176
+ g(() => {
177
+ h || Y();
178
+ }, [h, Y]), g(() => {
179
+ Y(), j(/* @__PURE__ */ new Map());
180
+ }, [me, Y]), g(() => {
181
+ j((e) => e.size === 0 ? e : /* @__PURE__ */ new Map()), Y();
182
+ }, [W, Y]), g(() => () => {
183
+ N.current?.(), N.current = null, x.cancel();
184
+ }, [x]), g(() => {
172
185
  if (typeof window > "u") return;
173
- let e = () => S.cancel();
186
+ let e = () => x.cancel();
174
187
  return window.addEventListener("pagehide", e), () => window.removeEventListener("pagehide", e);
175
- }, [S]), _(() => {
176
- if (typeof document > "u" || !B) return;
188
+ }, [x]), g(() => {
189
+ if (typeof document > "u" || !z) return;
177
190
  let e = () => {
178
191
  if (document.visibilityState !== "visible") return;
179
- let e = S.listVoices();
180
- e.length > 0 && I(), O(e), A(!1), M((e) => e.size === 0 ? e : /* @__PURE__ */ new Map());
192
+ let e = x.listVoices();
193
+ e.length > 0 && F(), D(e), k(!1), j((e) => e.size === 0 ? e : /* @__PURE__ */ new Map());
181
194
  };
182
195
  return document.addEventListener("visibilitychange", e), window.addEventListener("focus", e), () => {
183
196
  document.removeEventListener("visibilitychange", e), window.removeEventListener("focus", e);
184
197
  };
185
198
  }, [
186
- I,
187
- S,
188
- B
199
+ F,
200
+ x,
201
+ z
189
202
  ]);
190
- let he = y($);
191
- _(() => {
192
- he.current = $;
193
- }, [$]), _(() => {
194
- if (!(!L && !z || !g || !B)) return t.subscribe((e, t) => {
203
+ let ve = v(Q);
204
+ g(() => {
205
+ ve.current = Q;
206
+ }, [Q]), g(() => {
207
+ if (!(!I && !R || !h || !z)) return t.subscribe((e, t) => {
195
208
  let n = e.activeConversationId;
196
209
  if (!n || n !== t.activeConversationId) return;
197
210
  let r = e.processingByConversationId[n], i = t.processingByConversationId[n];
198
- if (r?.status !== "complete" || !ae(i?.status)) return;
211
+ if (r?.status !== "complete" || !se(i?.status)) return;
199
212
  let a = r.messageId ?? i?.messageId ?? null;
200
213
  if (!a) return;
201
214
  let o = e.conversations.find((e) => e.id === n)?.messages.find((e) => e.id === a);
202
215
  if (!o || o.role !== "assistant") return;
203
- let { text: s } = oe(o.content);
204
- s.trim() && he.current(a, s, o.metadata?.lang);
216
+ let { text: s } = ce(o.content);
217
+ s.trim() && ve.current(a, s, o.metadata?.lang);
205
218
  });
206
219
  }, [
207
- L,
220
+ I,
221
+ R,
208
222
  z,
209
- B,
210
- g
223
+ h
211
224
  ]);
212
- let ge = v(() => d(D, W.tag), [D, W]), _e = v(() => c(D, W.tag, H[G]), [
213
- D,
214
- W,
215
- H,
216
- G
217
- ]), ve = v(() => ({
218
- isSupported: B,
219
- availability: J,
220
- isBlocked: J === "no-voices",
221
- disabledReason: J === "no-voices" ? C("healthybowl.assistant.speech.noVoicesOnDevice", "This device has no speech voices installed. Add one in your device speech or accessibility settings.") : null,
222
- blockedFor: Z,
223
- voiceChoices: ge,
224
- activeVoiceName: _e?.name ?? null,
225
- preferredVoiceName: H[G] ?? null,
226
- setVoice: (e) => U(G, e),
227
- speakingMessageId: T.status === "speaking" ? T.messageId : null,
228
- isSpeaking: (e) => p(T, e),
229
- toggle: me,
230
- stop: X,
231
- autoSpeakEnabled: L,
232
- setAutoSpeak: R,
233
- sessionSpeaking: z,
234
- setSessionSpeaking: de
225
+ let ye = _(() => ne(E, U.tag), [E, U]), $ = _(() => c(E, U.tag, V[W]), [
226
+ E,
227
+ U,
228
+ V,
229
+ W
230
+ ]), be = _(() => ({
231
+ isSupported: z,
232
+ availability: q,
233
+ isBlocked: q === "no-voices",
234
+ disabledReason: q === "no-voices" ? S("healthybowl.assistant.speech.noVoicesOnDevice", "This device has no speech voices installed. Add one in your device speech or accessibility settings.") : null,
235
+ blockedFor: he,
236
+ voiceChoices: ye,
237
+ activeVoiceName: $?.name ?? null,
238
+ preferredVoiceName: V[W] ?? null,
239
+ setVoice: (e) => H(W, e),
240
+ speakingMessageId: w.status === "speaking" ? w.messageId : null,
241
+ isSpeaking: (e) => f(w, e),
242
+ toggle: _e,
243
+ stop: Y,
244
+ autoSpeakEnabled: I,
245
+ setAutoSpeak: L,
246
+ sessionSpeaking: R,
247
+ setSessionSpeaking: pe,
248
+ previewVoice: X
235
249
  }), [
236
- B,
237
- J,
238
- Z,
239
- ge,
240
- _e,
250
+ z,
251
+ q,
252
+ he,
253
+ ye,
254
+ $,
255
+ V,
241
256
  H,
242
- U,
243
- G,
244
- T,
245
- me,
246
- X,
257
+ W,
258
+ w,
259
+ _e,
260
+ Y,
261
+ I,
247
262
  L,
248
263
  R,
249
- z,
250
- C
264
+ X,
265
+ S
251
266
  ]);
252
- return /* @__PURE__ */ le(x.Provider, {
253
- value: ve,
254
- children: m
267
+ return /* @__PURE__ */ de(b.Provider, {
268
+ value: be,
269
+ children: p
255
270
  });
256
271
  };
257
272
  //#endregion
258
- export { C as AssistantSpeechProvider, S as useAssistantSpeech };
273
+ export { S as AssistantSpeechProvider, x as useAssistantSpeech };
259
274
 
260
275
  //# 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 { getSpeechEngine } from '../../services/speech';\nimport type { SpeechEngine, SpeechVoiceLike } from '../../services/speech';\nimport { chunkForSpeech, toSpeakableText, type SpeakableLabels } from '../../utils/speakableText';\nimport { speechLabelsFor } from '../../config/speechLabels';\n\n/**\n * The speakable transformation with nothing of ours added — used ONLY to decide\n * the reply's language.\n *\n * Detection needs the prose that will be spoken: code blocks and URLs stripped\n * (they are never read aloud, and their Latin identifiers would outvote short\n * non-Latin prose), but no substitute wording introduced either (that would let\n * our own app-locale words vote instead).\n */\nconst SILENT_LABELS: SpeakableLabels = {\n codeBlock: '',\n image: '',\n link: '',\n largeTable: '',\n truncated: '',\n emailAt: 'at',\n emailDot: 'dot',\n nestedItem: '',\n};\nimport {\n VOICE_LIST_TIMEOUT_MS,\n languageDisplayName,\n selectVoiceForLocale,\n voicesForLocale,\n speechGate,\n speechLangForLocale,\n voiceAvailability,\n type VoiceAvailability,\n} from '../../utils/speechVoices';\nimport { resolveSpeechLocale } from '../../utils/replyLanguage';\nimport { DEFAULT_SPEECH_RATE, findAssistantLanguage, resolveAssistantLanguage } from '../../config/assistantLanguages';\nimport { IDLE_PLAYBACK, isSpeakingMessage, speechPlaybackReducer } from '../../utils/speechPlayback';\nimport { isTurnInFlight } from '../../utils/assistantTurnState';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport interface AssistantSpeechContextValue {\n /** False when the platform has no speech output — hide the control entirely. */\n isSupported: boolean;\n availability: VoiceAvailability;\n /**\n * True when nothing can be spoken in the app language, so every control that\n * starts playback — the per-message button AND the header toggle — must be\n * inert. `pending` is not blocked: see `speechGate`.\n */\n isBlocked: boolean;\n /** Explains a disabled control (no installed voice for the app language). */\n disabledReason: string | null;\n /**\n * Why THIS message cannot be spoken, when the app language is fine but the\n * reply is not in it — a Tamil answer in an English UI on a device with no\n * Tamil voice. `isBlocked` cannot see that: it is computed before any reply\n * exists. Without this the control looks enabled and silently refuses, which\n * is the dead-button bug all over again (BOFF-7106).\n */\n blockedFor: (messageId: string) => string | null;\n /**\n * Every installed voice that can read the language the user speaks, best\n * first. Empty when there is no choice to offer — the picker hides itself\n * rather than showing a one-item dropdown.\n */\n voiceChoices: readonly SpeechVoiceLike[];\n /** The voice that will actually be used, resolved from the pick + ranking. */\n activeVoiceName: string | null;\n /**\n * The RAW stored pick: `null` means \"use the ranked default\".\n *\n * The picker must be driven by this rather than by `activeVoiceName`, or the\n * two states collapse — with nothing stored, the ranked winner is already the\n * shown option, so choosing it fires no change event and the pick can never\n * be made. The user's voice would then silently move the next time the device\n * installs a higher-ranked one. Same trap as the language selector.\n */\n preferredVoiceName: string | null;\n /** `null` restores the ranked default for the current language. */\n setVoice: (voiceName: string | null) => void;\n /** The message currently being spoken, if any. */\n speakingMessageId: string | null;\n isSpeaking: (messageId: string) => boolean;\n /**\n * Speak this message, or stop if it is already the one speaking.\n *\n * `turnLocale` is the language the reply was GENERATED under, from the\n * message's own metadata. It matters because script detection cannot separate\n * Latin-script languages, so without it an old French reply would be read\n * with whatever voice the CURRENT preference selects.\n */\n toggle: (messageId: string, markdown: string, turnLocale?: string) => void;\n stop: () => void;\n autoSpeakEnabled: boolean;\n setAutoSpeak: (enabled: boolean) => void;\n /**\n * 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}\n\nconst INERT_SPEECH: AssistantSpeechContextValue = {\n isSupported: false,\n availability: 'unsupported',\n isBlocked: true,\n disabledReason: null,\n blockedFor: () => null,\n voiceChoices: [],\n activeVoiceName: null,\n preferredVoiceName: null,\n setVoice: () => {},\n speakingMessageId: null,\n isSpeaking: () => false,\n toggle: () => {},\n stop: () => {},\n autoSpeakEnabled: false,\n setAutoSpeak: () => {},\n sessionSpeaking: false,\n setSessionSpeaking: () => {},\n};\n\nconst AssistantSpeechContext = createContext<AssistantSpeechContextValue>(INERT_SPEECH);\n\nexport function useAssistantSpeech(): AssistantSpeechContextValue {\n return useContext(AssistantSpeechContext);\n}\n\ninterface Props {\n children: ReactNode;\n /** Panel visibility. Hiding the panel stops the voice. */\n visible?: boolean;\n /**\n * Injectable for tests and local experiments. The default routes between the\n * device engine and the hosted one; with hosted TTS unconfigured it IS the\n * device engine, unchanged.\n */\n engine?: SpeechEngine;\n}\n\nexport const AssistantSpeechProvider: FC<Props> = ({ children, visible = true, engine = getSpeechEngine() }) => {\n const tr = useTr();\n const { locale } = useI18n();\n const [playback, dispatch] = useReducer(speechPlaybackReducer, IDLE_PLAYBACK);\n const [voices, setVoices] = useState<SpeechVoiceLike[]>(() => engine.listVoices());\n /**\n * True once we have waited out the voice list and it was still empty.\n *\n * Turns an indefinite `pending` into a terminal `no-voices`, which is what\n * lets the control be disabled with a reason instead of silently doing\n * nothing on every press.\n */\n const [voiceProbeSettled, setVoiceProbeSettled] = useState(false);\n /**\n * Every message we have refused, and why — keyed by id (see `blockedFor`).\n *\n * A single record could only describe one refusal: refusing a second reply\n * silently re-enabled the first, whose voice was still just as missing, so\n * pressing the buttons walked the disabled state around the transcript.\n */\n const [unspeakable, setUnspeakable] = useState<ReadonlyMap<string, string>>(() => new Map());\n const requestRef = useRef(0);\n /** Cancels a playback that is waiting for the engine's voice list, if any. */\n const pendingRef = useRef<(() => void) | null>(null);\n const speakWithRef = useRef<\n (messageId: string, text: string, voices: readonly SpeechVoiceLike[], speechLocale: string) => void\n >(() => {});\n\n const cancelPending = useCallback(() => {\n pendingRef.current?.();\n pendingRef.current = null;\n }, []);\n\n const autoSpeakEnabled = useAssistantStore((state) => state.autoSpeakEnabled);\n const setAutoSpeak = useAssistantStore((state) => state.setAutoSpeak);\n // 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 the user chose to converse in — not the interface language.\n // Completes the \"one selection drives three things\" promise: recogniser,\n // reply, and the voice that reads it (BOFF-7108).\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const preferredVoices = useAssistantStore((state) => state.preferredVoices);\n const setPreferredVoice = useAssistantStore((state) => state.setPreferredVoice);\n const spokenLanguage = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale),\n [assistantLanguage, locale]\n );\n const spokenLocale = spokenLanguage.code;\n\n /**\n * BCP-47 tag to ask the engine for, given a resolved language CODE.\n *\n * Resolved through the catalogue for ANY known code, not merely the currently\n * selected one — a historical Bengali reply must still get `bn-IN` after the\n * user switches to Tamil, or with both `bn-IN` and `bn-BD` installed the\n * engine's own order decides, and picks the wrong country.\n *\n * Falls back to the generic table for codes the catalogue does not carry.\n */\n const tagFor = useCallback((code: string) => findAssistantLanguage(code)?.tag ?? speechLangForLocale(code), []);\n\n /** Speaking rate for a resolved language code — see `AssistantLanguage.rate`. */\n const rateFor = useCallback((code: string) => findAssistantLanguage(code)?.rate ?? DEFAULT_SPEECH_RATE, []);\n\n const availability = useMemo(\n () => voiceAvailability(isSupported, voices, spokenLanguage.tag, voiceProbeSettled),\n [isSupported, voices, spokenLanguage, voiceProbeSettled]\n );\n\n // Spoken placeholders follow the app locale like the rest of the copy; the\n // transformation itself stays a pure function by taking them as arguments.\n const labels = useMemo<SpeakableLabels>(\n () => ({\n codeBlock: tr('healthybowl.assistant.speech.codeBlock', 'Code block'),\n image: tr('healthybowl.assistant.speech.image', 'image'),\n link: tr('healthybowl.assistant.speech.link', 'link'),\n largeTable: tr('healthybowl.assistant.speech.largeTable', 'Table with {{rows}} rows and {{columns}} columns'),\n truncated: tr('healthybowl.assistant.speech.truncated', 'The rest of this message is not read aloud'),\n nestedItem: tr('healthybowl.assistant.speech.nestedItem', 'Sub-item {{ordinal}}'),\n emailAt: tr('healthybowl.assistant.speech.emailAt', 'at'),\n emailDot: tr('healthybowl.assistant.speech.emailDot', 'dot'),\n }),\n [tr]\n );\n\n const stop = useCallback(() => {\n cancelPending();\n engine.cancel();\n dispatch({ type: 'stop' });\n }, [cancelPending, engine]);\n\n const blockedFor = useCallback((messageId: string) => unspeakable.get(messageId) ?? null, [unspeakable]);\n\n /**\n * Hold one playback until the engine publishes its voice list.\n *\n * Bounded: on timeout we take one last look and decide with whatever is\n * there, so an engine that never fires `voiceschanged` costs a two-second\n * wait rather than a control that is disabled forever. Nothing is spoken from\n * here unless a list actually arrives — an empty list means the engine would\n * pick its own default voice, which is the cross-language read this feature\n * promises never to do.\n */\n const waitForVoices = useCallback(\n (messageId: string, text: string, speechLocale: string) => {\n cancelPending();\n\n let settled = false;\n let unsubscribe = () => {};\n const finish = (available: SpeechVoiceLike[]) => {\n if (settled) return;\n settled = true;\n pendingRef.current = null;\n clearTimeout(timer);\n unsubscribe();\n if (available.length === 0) {\n // We waited and looked again: this device has no voices at all.\n // Record it so `availability` becomes `no-voices` and the control\n // explains itself, instead of returning silently every press.\n setVoiceProbeSettled(true);\n return;\n }\n setVoices(available);\n speakWithRef.current(messageId, text, available, speechLocale);\n };\n\n const timer = setTimeout(() => finish(engine.listVoices()), VOICE_LIST_TIMEOUT_MS);\n unsubscribe = engine.subscribeVoices(() => finish(engine.listVoices()));\n\n pendingRef.current = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n unsubscribe();\n pendingRef.current = null;\n };\n },\n [cancelPending, engine]\n );\n\n /**\n * Speak text against a KNOWN voice list.\n *\n * Every playback path funnels through here — the per-message button, the\n * header toggle's auto-speak, the store subscription — so the language gate\n * cannot be bypassed by any of them. Reading a Tamil reply with an English\n * voice is confident nonsense; it has to be impossible, not merely unlikely.\n */\n const speakWith = useCallback(\n (messageId: string, text: string, available: readonly SpeechVoiceLike[], speechLocale: string) => {\n let known = available;\n\n // Chrome answers the FIRST getVoices() with [] and fills the list in\n // asynchronously. One more synchronous read usually settles it.\n if (known.length === 0) {\n const refreshed = engine.listVoices();\n if (refreshed.length > 0) {\n known = refreshed;\n setVoices(refreshed);\n }\n }\n\n const speechLang = tagFor(speechLocale);\n\n const gate = speechGate(voiceAvailability(true, known, speechLocale, voiceProbeSettled));\n if (gate === 'block') {\n // Recorded for THIS message, always. Availability is resolved per reply\n // now, so a global \"your language has no voice\" cannot stand in for it:\n // the language the user chose to converse in says nothing about the one\n // this particular reply came back in.\n const reason = tr(\n 'healthybowl.assistant.speech.noVoiceForReply',\n 'This reply is in {{language}}, and no {{language}} voice is installed on this device.',\n { language: languageDisplayName(speechLang, locale) }\n );\n setUnspeakable((current) => new Map(current).set(messageId, reason));\n return;\n }\n if (gate === 'wait-for-voices') {\n waitForVoices(messageId, text, speechLocale);\n return;\n }\n\n setUnspeakable((current) => {\n if (!current.has(messageId)) return current;\n const next = new Map(current);\n next.delete(messageId);\n return next;\n });\n\n const requestId = requestRef.current + 1;\n requestRef.current = requestId;\n dispatch({ type: 'start', messageId, requestId });\n\n engine.speak(\n chunkForSpeech(text),\n // The TAG, not the code — so exact regional matching gets its chance\n // before the same-language fallback. `rate` had never been passed at\n // all, so every reply was read at the engine default.\n {\n voice: selectVoiceForLocale(known, speechLang, preferredVoices[speechLocale]),\n lang: speechLang,\n rate: rateFor(speechLocale),\n },\n {\n onEnd: () => dispatch({ type: 'finished', requestId }),\n // Includes the 'cancelled' every queued utterance reports when we\n // pre-empt a batch; the request-id guard drops those as stale.\n onError: () => dispatch({ type: 'failed', requestId }),\n }\n );\n },\n [engine, locale, preferredVoices, rateFor, tagFor, tr, voiceProbeSettled, waitForVoices]\n );\n\n // `waitForVoices` resumes through this ref, so the two do not become a\n // circular hook dependency.\n useEffect(() => {\n speakWithRef.current = speakWith;\n }, [speakWith]);\n\n const speak = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (!isSupported) return;\n\n // Resolve the reply's language BEFORE building the spoken text, because\n // the stand-in words must be in that language. Detection deliberately runs\n // on a SILENT_LABELS pass — our own words must not vote on which language\n // the reply is in — so it does not depend on the labels chosen here.\n const replyLocale = resolveSpeechLocale(\n toSpeakableText(markdown, { labels: SILENT_LABELS }),\n turnLocale ?? spokenLocale\n );\n\n // ★ Labels in the REPLY's language, not the interface's. An English\n // interface reading a Tamil answer used to say \"Code block\" and \"image\" in\n // English, mid-Tamil-sentence — the same defect the email `at`/`dot` fix\n // addressed and did not generalise.\n const text = toSpeakableText(markdown, { labels: speechLabelsFor(replyLocale, labels) });\n if (!text) return;\n\n // Detect on the text that will actually be SPOKEN, with our own words\n // removed — neither the raw markdown nor the finished transformation.\n //\n // The transformation injects app-locale placeholders (\"Code block\"), which\n // let English chrome outvote short non-Latin prose. The raw markdown keeps\n // fenced code, whose Latin identifiers do the same thing — and that code is\n // never spoken at all. Running the same transformation with EMPTY labels\n // strips the unspoken constructs while contributing no words of its own,\n // which is exactly the denominator the decision needs.\n // The turn's OWN language first — the preference is only a stand-in for\n // replies that predate it. Resolved above, and reused rather than\n // recomputed.\n speakWith(messageId, text, voices, replyLocale);\n },\n [isSupported, labels, spokenLocale, speakWith, voices]\n );\n\n const toggle = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (isSpeakingMessage(playback, messageId)) {\n stop();\n return;\n }\n speak(messageId, markdown, turnLocale);\n },\n [playback, speak, stop]\n );\n\n // ── Never leave a voice talking to an empty room ─────────────────────────\n useEffect(() => {\n if (!visible) stop();\n }, [visible, stop]);\n\n useEffect(() => {\n // Switching (or creating) a conversation abandons the reply being read —\n // and the refusal explained a message that is no longer on screen.\n stop();\n setUnspeakable(new Map());\n }, [activeConversationId, stop]);\n\n useEffect(() => {\n // Every refusal was decided against the locale in force at the time, which\n // is what a Latin-script reply falls back to. Change the locale and those\n // verdicts may simply be wrong — an English reply refused on a\n // Spanish-only device would stay disabled forever after switching the UI to\n // Spanish, with the voice that could read it already installed.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n // And stop anything mid-sentence. The new language can make this message\n // unspeakable, which disables its button — leaving it reading \"Stop\" with no\n // way to actually stop, short of closing the panel.\n stop();\n }, [spokenLocale, stop]);\n\n useEffect(() => {\n return () => {\n pendingRef.current?.();\n pendingRef.current = null;\n engine.cancel();\n };\n }, [engine]);\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n // Chrome carries speech across a same-tab navigation and a bfcache restore\n // would otherwise come back mid-sentence.\n const handlePageHide = () => engine.cancel();\n window.addEventListener('pagehide', handlePageHide);\n return () => window.removeEventListener('pagehide', handlePageHide);\n }, [engine]);\n\n // ── One timeout is not a life sentence ───────────────────────────────────\n //\n // `no-voices` disables the control, and a disabled control can never reach\n // `speakWith` — the only path that re-reads `engine.listVoices()`. So without\n // this, a user who follows our own advice, leaves to install a voice and comes\n // back stays blocked until a reload: we would be telling them how to fix it\n // and then refusing to notice that they had.\n //\n // Returning to the tab is exactly when that happens, and it costs one\n // synchronous read of an already-populated list.\n useEffect(() => {\n if (typeof document === 'undefined' || !isSupported) return;\n const reprobe = () => {\n if (document.visibilityState !== 'visible') return;\n // Adopt the list UNCONDITIONALLY, including an empty one. Keeping the old\n // cache on an empty read means a user who uninstalled their last voice\n // stays `ready`, and playback then hands the engine a voice object that no\n // longer exists instead of explaining the problem.\n //\n // Safe to accept an empty read here precisely because the probe verdict is\n // cleared on the next line: empty + unsettled is `pending`, which leaves\n // the control ENABLED and defers the real decision to the next press.\n const available = engine.listVoices();\n // A Listen press may still be inside its two-second wait. Adopting voices\n // here flips the control to `ready`, so the user can press again and start\n // playback — and then the original timer fires, calls back into\n // `speakWith` for the same message, and the engine cancels and restarts it\n // mid-sentence. Retire the waiter as part of adopting the list.\n if (available.length > 0) cancelPending();\n setVoices(available);\n setVoiceProbeSettled(false);\n // Same reason the `voiceschanged` path clears them: every refusal meant\n // \"no voice for this language\", and this is the moment a user who went\n // away to install one comes back. `subscribeVoices` does not fire on an\n // eventless engine, which is precisely why this re-probe exists — so it\n // has to expire the refusals too.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n document.addEventListener('visibilitychange', reprobe);\n window.addEventListener('focus', reprobe);\n return () => {\n document.removeEventListener('visibilitychange', reprobe);\n window.removeEventListener('focus', reprobe);\n };\n }, [cancelPending, engine, isSupported]);\n\n // ── Opt-in auto-speak ────────────────────────────────────────────────────\n const speakRef = useRef(speak);\n useEffect(() => {\n speakRef.current = speak;\n }, [speak]);\n\n useEffect(() => {\n // `isBlocked` is the same gate the per-message button uses. Without it the\n // subscription fires on a device with no voice for the app language and the\n // engine reads a Tamil reply in English — the one thing this feature says\n // it will never do. `pending` is allowed through because `speakWith` waits\n // for the list before deciding.\n // NOT gated on `isSpeechBlocked(availability)` any more: that is the APP\n // language's availability, and it would suppress auto-speak for a reply in\n // a language this device CAN speak. `speakWith` resolves the reply's own\n // language and refuses safely there, which is the only place that can know.\n // 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 // 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 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 }),\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 tr,\n ]\n );\n\n return <AssistantSpeechContext.Provider value={value}>{children}</AssistantSpeechContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAqDA,IAAM,KAAiC;CACrC,WAAW;CACX,OAAO;CACP,MAAM;CACN,YAAY;CACZ,WAAW;CACX,SAAS;CACT,UAAU;CACV,YAAY;AACd,GA+GM,IAAyB,EAA2C;CAnBxE,aAAa;CACb,cAAc;CACd,WAAW;CACX,gBAAgB;CAChB,kBAAkB;CAClB,cAAc,CAAC;CACf,iBAAiB;CACjB,oBAAoB;CACpB,gBAAgB,CAAC;CACjB,mBAAmB;CACnB,kBAAkB;CAClB,cAAc,CAAC;CACf,YAAY,CAAC;CACb,kBAAkB;CAClB,oBAAoB,CAAC;CACrB,iBAAiB;CACjB,0BAA0B,CAAC;AAG6C,CAAY;AAEtF,SAAgB,IAAkD;CAChE,OAAO,EAAW,CAAsB;AAC1C;AAcA,IAAa,KAAsC,EAAE,aAAU,aAAU,IAAM,YAAS,EAAgB,QAAQ;CAC9G,IAAM,IAAK,EAAM,GACX,EAAE,cAAW,GAAQ,GACrB,CAAC,GAAU,KAAY,GAAW,IAAuB,EAAa,GACtE,CAAC,GAAQ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D,WAAW,MAA6B,EAAkB,GAAc,CAAS;EACjF,mBAAmB,EAAS,WAAW,aAAa,EAAS,YAAY;EACzE,aAAa,MAAsB,EAAkB,GAAU,CAAS;EACxE;EACA;EACA;EACA;EACA;EACA;CACF,IACA;EACE;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, resolveAssistantLanguage } from '../../config/assistantLanguages';\nimport { IDLE_PLAYBACK, isSpeakingMessage, speechPlaybackReducer } from '../../utils/speechPlayback';\nimport { isTurnInFlight } from '../../utils/assistantTurnState';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport interface AssistantSpeechContextValue {\n /** False when the platform has no speech output — hide the control entirely. */\n isSupported: boolean;\n availability: VoiceAvailability;\n /**\n * True when nothing can be spoken in the app language, so every control that\n * starts playback — the per-message button AND the header toggle — must be\n * inert. `pending` is not blocked: see `speechGate`.\n */\n isBlocked: boolean;\n /** Explains a disabled control (no installed voice for the app language). */\n disabledReason: string | null;\n /**\n * Why THIS message cannot be spoken, when the app language is fine but the\n * reply is not in it — a Tamil answer in an English UI on a device with no\n * Tamil voice. `isBlocked` cannot see that: it is computed before any reply\n * exists. Without this the control looks enabled and silently refuses, which\n * is the dead-button bug all over again (BOFF-7106).\n */\n blockedFor: (messageId: string) => string | null;\n /**\n * Every installed voice that can read the language the user speaks, best\n * first. Empty when there is no choice to offer — the picker hides itself\n * rather than showing a one-item dropdown.\n */\n voiceChoices: readonly SpeechVoiceLike[];\n /** The voice that will actually be used, resolved from the pick + ranking. */\n activeVoiceName: string | null;\n /**\n * The RAW stored pick: `null` means \"use the ranked default\".\n *\n * The picker must be driven by this rather than by `activeVoiceName`, or the\n * two states collapse — with nothing stored, the ranked winner is already the\n * shown option, so choosing it fires no change event and the pick can never\n * be made. The user's voice would then silently move the next time the device\n * installs a higher-ranked one. Same trap as the language selector.\n */\n preferredVoiceName: string | null;\n /** `null` restores the ranked default for the current language. */\n setVoice: (voiceName: string | null) => void;\n /** The message currently being spoken, if any. */\n speakingMessageId: string | null;\n isSpeaking: (messageId: string) => boolean;\n /**\n * Speak this message, or stop if it is already the one speaking.\n *\n * `turnLocale` is the language the reply was GENERATED under, from the\n * message's own metadata. It matters because script detection cannot separate\n * Latin-script languages, so without it an old French reply would be read\n * with whatever voice the CURRENT preference selects.\n */\n toggle: (messageId: string, markdown: string, turnLocale?: string) => void;\n stop: () => void;\n autoSpeakEnabled: boolean;\n setAutoSpeak: (enabled: boolean) => void;\n /**\n * 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 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 /** 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 the user chose to converse in — not the interface language.\n // Completes the \"one selection drives three things\" promise: recogniser,\n // reply, and the voice that reads it (BOFF-7108).\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const preferredVoices = useAssistantStore((state) => state.preferredVoices);\n const setPreferredVoice = useAssistantStore((state) => state.setPreferredVoice);\n const spokenLanguage = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale),\n [assistantLanguage, locale]\n );\n const spokenLocale = spokenLanguage.code;\n\n /**\n * BCP-47 tag to ask the engine for, given a resolved language CODE.\n *\n * Resolved through the catalogue for ANY known code, not merely the currently\n * selected one — a historical Bengali reply must still get `bn-IN` after the\n * user switches to Tamil, or with both `bn-IN` and `bn-BD` installed the\n * engine's own order decides, and picks the wrong country.\n *\n * Falls back to the generic table for codes the catalogue does not carry.\n */\n const tagFor = useCallback((code: string) => findAssistantLanguage(code)?.tag ?? speechLangForLocale(code), []);\n\n /** Speaking rate for a resolved language code — see `AssistantLanguage.rate`. */\n const rateFor = useCallback((code: string) => findAssistantLanguage(code)?.rate ?? DEFAULT_SPEECH_RATE, []);\n\n const availability = useMemo(\n () => voiceAvailability(isSupported, voices, spokenLanguage.tag, voiceProbeSettled),\n [isSupported, voices, spokenLanguage, voiceProbeSettled]\n );\n\n // Spoken placeholders follow the app locale like the rest of the copy; the\n // transformation itself stays a pure function by taking them as arguments.\n const labels = useMemo<SpeakableLabels>(\n () => ({\n codeBlock: tr('healthybowl.assistant.speech.codeBlock', 'Code block'),\n image: tr('healthybowl.assistant.speech.image', 'image'),\n link: tr('healthybowl.assistant.speech.link', 'link'),\n largeTable: tr('healthybowl.assistant.speech.largeTable', 'Table with {{rows}} rows and {{columns}} columns'),\n truncated: tr('healthybowl.assistant.speech.truncated', 'The rest of this message is not read aloud'),\n nestedItem: tr('healthybowl.assistant.speech.nestedItem', 'Sub-item {{ordinal}}'),\n emailAt: tr('healthybowl.assistant.speech.emailAt', 'at'),\n emailDot: tr('healthybowl.assistant.speech.emailDot', 'dot'),\n }),\n [tr]\n );\n\n const stop = useCallback(() => {\n cancelPending();\n engine.cancel();\n dispatch({ type: 'stop' });\n }, [cancelPending, engine]);\n\n /**\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 engine.speak(\n chunkForSpeech(text),\n // The TAG, not the code — so exact regional matching gets its chance\n // before the same-language fallback. `rate` had never been passed at\n // all, so every reply was read at the engine default.\n {\n voice: selectVoiceForLocale(known, speechLang, preferredVoices[speechLocale]),\n lang: speechLang,\n rate: rateFor(speechLocale),\n },\n {\n onEnd: () => dispatch({ type: 'finished', requestId }),\n // Includes the 'cancelled' every queued utterance reports when we\n // pre-empt a batch; the request-id guard drops those as stale.\n onError: () => dispatch({ type: 'failed', requestId }),\n }\n );\n },\n [engine, locale, preferredVoices, rateFor, tagFor, tr, voiceProbeSettled, waitForVoices]\n );\n\n // `waitForVoices` resumes through this ref, so the two do not become a\n // circular hook dependency.\n useEffect(() => {\n speakWithRef.current = speakWith;\n }, [speakWith]);\n\n const speak = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (!isSupported) return;\n\n // Resolve the reply's language BEFORE building the spoken text, because\n // the stand-in words must be in that language. Detection deliberately runs\n // on a SILENT_LABELS pass — our own words must not vote on which language\n // the reply is in — so it does not depend on the labels chosen here.\n const replyLocale = resolveSpeechLocale(\n toSpeakableText(markdown, { labels: SILENT_LABELS }),\n turnLocale ?? spokenLocale\n );\n\n // ★ Labels in the REPLY's language, not the interface's. An English\n // interface reading a Tamil answer used to say \"Code block\" and \"image\" in\n // English, mid-Tamil-sentence — the same defect the email `at`/`dot` fix\n // addressed and did not generalise.\n const text = toSpeakableText(markdown, { labels: speechLabelsFor(replyLocale, labels) });\n if (!text) return;\n\n // Detect on the text that will actually be SPOKEN, with our own words\n // removed — neither the raw markdown nor the finished transformation.\n //\n // The transformation injects app-locale placeholders (\"Code block\"), which\n // let English chrome outvote short non-Latin prose. The raw markdown keeps\n // fenced code, whose Latin identifiers do the same thing — and that code is\n // never spoken at all. Running the same transformation with EMPTY labels\n // strips the unspoken constructs while contributing no words of its own,\n // which is exactly the denominator the decision needs.\n // The turn's OWN language first — the preference is only a stand-in for\n // replies that predate it. Resolved above, and reused rather than\n // recomputed.\n speakWith(messageId, text, voices, replyLocale);\n },\n [isSupported, labels, spokenLocale, speakWith, voices]\n );\n\n const toggle = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (isSpeakingMessage(playback, messageId)) {\n stop();\n return;\n }\n speak(messageId, markdown, turnLocale);\n },\n [playback, speak, stop]\n );\n\n // ── Never leave a voice talking to an empty room ─────────────────────────\n useEffect(() => {\n if (!visible) stop();\n }, [visible, stop]);\n\n useEffect(() => {\n // Switching (or creating) a conversation abandons the reply being read —\n // and the refusal explained a message that is no longer on screen.\n stop();\n setUnspeakable(new Map());\n }, [activeConversationId, stop]);\n\n useEffect(() => {\n // Every refusal was decided against the locale in force at the time, which\n // is what a Latin-script reply falls back to. Change the locale and those\n // verdicts may simply be wrong — an English reply refused on a\n // Spanish-only device would stay disabled forever after switching the UI to\n // Spanish, with the voice that could read it already installed.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n // And stop anything mid-sentence. The new language can make this message\n // unspeakable, which disables its button — leaving it reading \"Stop\" with no\n // way to actually stop, short of closing the panel.\n stop();\n }, [spokenLocale, stop]);\n\n useEffect(() => {\n return () => {\n pendingRef.current?.();\n pendingRef.current = null;\n engine.cancel();\n };\n }, [engine]);\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n // Chrome carries speech across a same-tab navigation and a bfcache restore\n // would otherwise come back mid-sentence.\n const handlePageHide = () => engine.cancel();\n window.addEventListener('pagehide', handlePageHide);\n return () => window.removeEventListener('pagehide', handlePageHide);\n }, [engine]);\n\n // ── One timeout is not a life sentence ───────────────────────────────────\n //\n // `no-voices` disables the control, and a disabled control can never reach\n // `speakWith` — the only path that re-reads `engine.listVoices()`. So without\n // this, a user who follows our own advice, leaves to install a voice and comes\n // back stays blocked until a reload: we would be telling them how to fix it\n // and then refusing to notice that they had.\n //\n // Returning to the tab is exactly when that happens, and it costs one\n // synchronous read of an already-populated list.\n useEffect(() => {\n if (typeof document === 'undefined' || !isSupported) return;\n const reprobe = () => {\n if (document.visibilityState !== 'visible') return;\n // Adopt the list UNCONDITIONALLY, including an empty one. Keeping the old\n // cache on an empty read means a user who uninstalled their last voice\n // stays `ready`, and playback then hands the engine a voice object that no\n // longer exists instead of explaining the problem.\n //\n // Safe to accept an empty read here precisely because the probe verdict is\n // cleared on the next line: empty + unsettled is `pending`, which leaves\n // the control ENABLED and defers the real decision to the next press.\n const available = engine.listVoices();\n // A Listen press may still be inside its two-second wait. Adopting voices\n // here flips the control to `ready`, so the user can press again and start\n // playback — and then the original timer fires, calls back into\n // `speakWith` for the same message, and the engine cancels and restarts it\n // mid-sentence. Retire the waiter as part of adopting the list.\n if (available.length > 0) cancelPending();\n setVoices(available);\n setVoiceProbeSettled(false);\n // Same reason the `voiceschanged` path clears them: every refusal meant\n // \"no voice for this language\", and this is the moment a user who went\n // away to install one comes back. `subscribeVoices` does not fire on an\n // eventless engine, which is precisely why this re-probe exists — so it\n // has to expire the refusals too.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n document.addEventListener('visibilitychange', reprobe);\n window.addEventListener('focus', reprobe);\n return () => {\n document.removeEventListener('visibilitychange', reprobe);\n window.removeEventListener('focus', reprobe);\n };\n }, [cancelPending, engine, isSupported]);\n\n // ── Opt-in auto-speak ────────────────────────────────────────────────────\n const speakRef = useRef(speak);\n useEffect(() => {\n speakRef.current = speak;\n }, [speak]);\n\n useEffect(() => {\n // `isBlocked` is the same gate the per-message button uses. Without it the\n // subscription fires on a device with no voice for the app language and the\n // engine reads a Tamil reply in English — the one thing this feature says\n // it will never do. `pending` is allowed through because `speakWith` waits\n // for the list before deciding.\n // NOT gated on `isSpeechBlocked(availability)` any more: that is the APP\n // language's availability, and it would suppress auto-speak for a reply in\n // a language this device CAN speak. `speakWith` resolves the reply's own\n // language and refuses safely there, which is the only place that can know.\n // 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 // 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 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,GAkHM,IAAyB,EAA2C;CApBxE,aAAa;CACb,cAAc;CACd,WAAW;CACX,gBAAgB;CAChB,kBAAkB;CAClB,cAAc,CAAC;CACf,iBAAiB;CACj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GAAW;GAEhB,IAAM,IAAU,EAAK,cAClB,MAAM,MAAiB,EAAa,OAAO,CAAc,GACxD,SAAS,MAAM,MAAc,EAAU,OAAO,CAAS;GAC3D,IAAI,CAAC,KAAW,EAAQ,SAAS,aAAa;GAG9C,IAAM,EAAE,YAAS,GAAkB,EAAQ,OAAO;GAC7C,EAAK,KAAK,KAEf,GAAS,QAAQ,GAAW,GAAO,EAAQ,UAA4C,IAAI;EAC7F,CAAC;CACH,GAAG;EAAC;EAAkB;EAAiB;EAAa;CAAO,CAAC;CAI5D,IAAM,KAAe,QAAc,GAAgB,GAAQ,EAAe,GAAG,GAAG,CAAC,GAAQ,CAAc,CAAC,GAClG,IAAc,QACZ,EAAqB,GAAQ,EAAe,KAAK,EAAgB,EAAa,GACpF;EAAC;EAAQ;EAAgB;EAAiB;CAAY,CACxD,GAEM,KAAQ,SACL;EACL;EACA;EAKA,WAAW,MAAiB;EAI5B,gBACE,MAAiB,cACb,EACE,iDACA,sGACF,IACA;EACN;EACA;EACA,iBAAiB,GAAa,QAAQ;EACtC,oBAAoB,EAAgB,MAAiB;EACrD,WAAW,MAA6B,EAAkB,GAAc,CAAS;EACjF,mBAAmB,EAAS,WAAW,aAAa,EAAS,YAAY;EACzE,aAAa,MAAsB,EAAkB,GAAU,CAAS;EACxE;EACA;EACA;EACA;EACA;EACA;EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,OAAO,mBAAC,EAAuB,UAAxB;EAAwC;EAAQ;CAA0C,CAAA;AACnG"}
@@ -0,0 +1,28 @@
1
+ //#region src/utils/voicePreview.ts
2
+ var e = {
3
+ en: "Hello! I am your HealthyBowl assistant.",
4
+ ta: "வணக்கம்! நான் உங்கள் HealthyBowl உதவியாளர்.",
5
+ hi: "नमस्ते! मैं आपका HealthyBowl सहायक हूँ।",
6
+ bn: "নমস্কার! আমি আপনার HealthyBowl সহায়ক।",
7
+ te: "నమస్కారం! నేను మీ HealthyBowl సహాయకుడిని.",
8
+ mr: "नमस्कार! मी तुमचा HealthyBowl सहाय्यक आहे.",
9
+ gu: "નમસ્તે! હું તમારો HealthyBowl સહાયક છું.",
10
+ kn: "ನಮಸ್ಕಾರ! ನಾನು ನಿಮ್ಮ HealthyBowl ಸಹಾಯಕ.",
11
+ ml: "നമസ്കാരം! ഞാൻ നിങ്ങളുടെ HealthyBowl സഹായിയാണ്.",
12
+ pa: "ਸਤ ਸ੍ਰੀ ਅਕਾਲ! ਮੈਂ ਤੁਹਾਡਾ HealthyBowl ਸਹਾਇਕ ਹਾਂ।",
13
+ ur: "السلام علیکم! میں آپ کا HealthyBowl معاون ہوں۔",
14
+ ar: "مرحبًا! أنا مساعد HealthyBowl الخاص بك.",
15
+ es: "¡Hola! Soy tu asistente de HealthyBowl.",
16
+ fr: "Bonjour ! Je suis votre assistant HealthyBowl.",
17
+ de: "Hallo! Ich bin Ihr HealthyBowl-Assistent.",
18
+ ja: "こんにちは!HealthyBowl のアシスタントです。",
19
+ zh: "你好!我是您的 HealthyBowl 助手。"
20
+ };
21
+ function t(t) {
22
+ let n = t.trim().toLowerCase().split(/[-_]/)[0];
23
+ return n && e[n] || e.en;
24
+ }
25
+ //#endregion
26
+ export { t as voicePreviewText };
27
+
28
+ //# sourceMappingURL=voicePreview.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"voicePreview.js","names":[],"sources":["../../src/utils/voicePreview.ts"],"sourcesContent":["/**\n * What a voice says when you audition it.\n *\n * Picking a voice used to be silent: you chose one, nothing happened, and the\n * first time you heard it was after asking the assistant a real question and\n * waiting out a round trip. Auditioning a voice should not cost a model call.\n *\n * ★ The sample is in the SPOKEN language, not the interface language. A voice is\n * being judged on how it reads Tamil, so making it read English tells the\n * listener nothing about the decision they are making — and the two are\n * independent settings here anyway.\n *\n * ★ Carried as a static table rather than through `tr()`, for the same reason\n * `speechLabels` is: the i18n provider only ever fetches the ACTIVE locale, so\n * there is nothing to ask for a Tamil string while the interface is English.\n * These are one short sentence each and they are needed synchronously.\n *\n * Deliberately short. Long enough to hear timbre and cadence, short enough that\n * auditioning four voices is not a chore, and it names the product so the\n * listener hears the one word this voice will say most often.\n */\n\nconst PREVIEW_BY_LANGUAGE: Record<string, string> = {\n en: 'Hello! I am your HealthyBowl assistant.',\n ta: 'வணக்கம்! நான் உங்கள் HealthyBowl உதவியாளர்.',\n hi: 'नमस्ते! मैं आपका HealthyBowl सहायक हूँ।',\n bn: 'নমস্কার! আমি আপনার HealthyBowl সহায়ক।',\n te: 'నమస్కారం! నేను మీ HealthyBowl సహాయకుడిని.',\n mr: 'नमस्कार! मी तुमचा HealthyBowl सहाय्यक आहे.',\n gu: 'નમસ્તે! હું તમારો HealthyBowl સહાયક છું.',\n kn: 'ನಮಸ್ಕಾರ! ನಾನು ನಿಮ್ಮ HealthyBowl ಸಹಾಯಕ.',\n ml: 'നമസ്കാരം! ഞാൻ നിങ്ങളുടെ HealthyBowl സഹായിയാണ്.',\n pa: 'ਸਤ ਸ੍ਰੀ ਅਕਾਲ! ਮੈਂ ਤੁਹਾਡਾ HealthyBowl ਸਹਾਇਕ ਹਾਂ।',\n ur: 'السلام علیکم! میں آپ کا HealthyBowl معاون ہوں۔',\n ar: 'مرحبًا! أنا مساعد HealthyBowl الخاص بك.',\n es: '¡Hola! Soy tu asistente de HealthyBowl.',\n fr: 'Bonjour ! Je suis votre assistant HealthyBowl.',\n de: 'Hallo! Ich bin Ihr HealthyBowl-Assistent.',\n ja: 'こんにちは!HealthyBowl のアシスタントです。',\n zh: '你好!我是您的 HealthyBowl 助手。',\n};\n\n/**\n * The audition sentence for a locale.\n *\n * Falls back to English rather than to silence: a voice the listener can hear\n * saying the wrong language still answers \"what does this voice sound like\",\n * which is the question being asked. Region subtags are ignored — `ta-IN` and\n * `ta-LK` want the same sentence.\n */\nexport function voicePreviewText(locale: string): string {\n const primary = locale.trim().toLowerCase().split(/[-_]/)[0];\n return (primary && PREVIEW_BY_LANGUAGE[primary]) || PREVIEW_BY_LANGUAGE.en!;\n}\n\n/** Exposed for tests: which languages have their own audition sentence. */\nexport const PREVIEW_LANGUAGES = Object.keys(PREVIEW_BY_LANGUAGE);\n"],"mappings":";AAsBA,IAAM,IAA8C;CAClD,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;AACN;AAUA,SAAgB,EAAiB,GAAwB;CACvD,IAAM,IAAU,EAAO,KAAK,EAAE,YAAY,EAAE,MAAM,MAAM,EAAE;CAC1D,OAAQ,KAAW,EAAoB,MAAa,EAAoB;AAC1E"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/microfe-healthybowl",
3
- "version": "2026.902.15",
3
+ "version": "2026.902.16",
4
4
  "description": "Burdenoff HealthyBowl Microfrontend - Comprehensive organic farming and agro-foods management platform",
5
5
  "type": "module",
6
6
  "files": [