@burdenoff/microfe-healthybowl 2026.828.2 → 2026.829.1

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.
@@ -134,12 +134,18 @@ var T = ({ message: C, isStreaming: T, isFailed: E, isLastAssistant: D, onRetry:
134
134
  "data-testid": "assistant-message-copy",
135
135
  children: I ? /* @__PURE__ */ _(h, { children: [/* @__PURE__ */ g(d, { className: "size-3 text-status-success-text" }), /* @__PURE__ */ g("span", { children: k("healthybowl.assistant.message.copied", "Copied") })] }) : /* @__PURE__ */ _(h, { children: [/* @__PURE__ */ g(f, { className: "size-3" }), /* @__PURE__ */ g("span", { children: k("healthybowl.assistant.message.copy", "Copy") })] })
136
136
  }),
137
- H && N.isSupported && /* @__PURE__ */ g(c, {
137
+ H && N.isSupported && /* @__PURE__ */ _(h, { children: [/* @__PURE__ */ g(c, {
138
138
  isSpeaking: N.isSpeaking(C.id),
139
139
  disabled: N.isBlocked,
140
140
  disabledReason: N.disabledReason,
141
+ describedById: N.disabledReason && D ? `speak-reason-${C.id}` : void 0,
141
142
  onClick: () => N.toggle(C.id, H)
142
- }),
143
+ }), N.disabledReason && D && /* @__PURE__ */ g("span", {
144
+ id: `speak-reason-${C.id}`,
145
+ className: "text-[11px] text-text-muted",
146
+ "data-testid": "assistant-speak-reason",
147
+ children: N.disabledReason
148
+ })] }),
143
149
  (E || D) && O && /* @__PURE__ */ _("button", {
144
150
  type: "button",
145
151
  onClick: O,
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantMessageItem.js","names":[],"sources":["../../../src/components/assistant/AssistantMessageItem.tsx"],"sourcesContent":["import { useMemo, useState, type FC } from 'react';\nimport { Sparkles, Copy, Check, RotateCcw } from 'lucide-react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { SaveToFilesButton } from '@burdenoff/fe-libs/storage';\nimport { AssistantMarkdownRenderer } from './AssistantMarkdownRenderer';\nimport { AssistantMessageAttachments } from './AssistantMessageAttachments';\nimport { AssistantSpeakButton } from './AssistantSpeakButton';\nimport { useAssistantSpeech } from './AssistantSpeechProvider';\nimport { AssistantToolActivity, parseToolActivity } from './AssistantToolActivity';\nimport { downloadAssistantArtifact } from '@/services/assistantApi';\nimport type { AssistantArtifact, AssistantMessageMetadata, Message } from '@/types/assistant';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { copyToClipboard } from '../../utils/clipboard';\n\ninterface Props {\n message: Message;\n isStreaming?: boolean;\n /** This assistant message ended in an error — show the Retry affordance. */\n isFailed?: boolean;\n /**\n * The most recent assistant turn. Retry is offered here too — a turn can\n * \"complete\" with an apology (e.g. a gateway 403 the model reports as text)\n * without ever tripping `isFailed`, and the user still needs a way to re-run.\n */\n isLastAssistant?: boolean;\n /** Re-send the last user prompt (wired by AssistantChatArea). */\n onRetry?: () => void;\n}\n\nfunction getAssistantMetadata(message: Message): AssistantMessageMetadata | undefined {\n return message.role === 'assistant' ? message.metadata : undefined;\n}\n\nfunction getArtifacts(metadata: AssistantMessageMetadata | undefined): AssistantArtifact[] {\n return metadata?.artifacts ?? [];\n}\n\nfunction decodeBase64(base64: string): string {\n return window.atob(base64);\n}\n\nfunction downloadBase64File(base64: string, filename: string, mimeType: string): void {\n const binary = decodeBase64(base64);\n const bytes = new Uint8Array(binary.length);\n\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n\n const blob = new Blob([bytes], { type: mimeType });\n const url = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = url;\n link.download = filename;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n\nexport const AssistantMessageItem: FC<Props> = ({ message, isStreaming, isFailed, isLastAssistant, onRetry }) => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken } = useAuthToken();\n const speech = useAssistantSpeech();\n const [downloadingArtifactPath, setDownloadingArtifactPath] = useState<string | null>(null);\n const [copied, setCopied] = useState(false);\n const isUser = message.role === 'user';\n const metadata = useMemo(() => getAssistantMetadata(message), [message]);\n const artifacts = useMemo(() => getArtifacts(metadata), [metadata]);\n // Separate the streamed tool-progress lines from the assistant's prose so the\n // former renders as a structured activity card (see AssistantToolActivity).\n const { steps, text } = useMemo(\n () => (isUser ? { steps: [], text: message.content } : parseToolActivity(message.content)),\n [isUser, message.content]\n );\n\n const handleCopy = () => {\n // Confirm only on a real copy — see copyToClipboard.\n void copyToClipboard(text || message.content).then((ok) => {\n if (!ok) return;\n setCopied(true);\n setTimeout(() => setCopied(false), 2000);\n });\n };\n\n const handleArtifactDownload = async (artifact: AssistantArtifact) => {\n if (!metadata?.sandboxId || !metadata.sessionId) return;\n\n const workspaceId = new URLSearchParams(window.location.search).get('workspace') ?? '';\n if (!workspaceId) return;\n\n setDownloadingArtifactPath(artifact.path);\n\n try {\n const result = await downloadAssistantArtifact(\n apollo,\n metadata.sandboxId,\n workspaceId,\n metadata.sessionId,\n artifact.path,\n {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n }\n );\n\n downloadBase64File(result.contentBase64, result.filename, result.mimeType);\n } finally {\n setDownloadingArtifactPath(null);\n }\n };\n\n const timeLabel = new Date(message.timestamp).toLocaleTimeString([], {\n hour: '2-digit',\n minute: '2-digit',\n });\n\n // ── User message: soft filled bubble, right-aligned ──────────────────\n if (isUser) {\n const attachments = message.metadata?.attachments ?? [];\n return (\n <div className=\"flex justify-end\" data-testid=\"assistant-message-user\">\n <div className=\"max-w-[85%]\">\n {/* An attachments-only turn (a photo with no words) has no bubble to\n draw — skip it rather than rendering an empty green pill. */}\n {message.content && (\n <div className=\"rounded-2xl rounded-br-md bg-action-primary-bg/12 px-3.5 py-2.5 text-[15px] leading-relaxed text-text-primary\">\n <p className=\"whitespace-pre-wrap\">{message.content}</p>\n </div>\n )}\n <AssistantMessageAttachments attachments={attachments} />\n <div className=\"mt-1 pr-1 text-right text-[10px] text-text-muted\">{timeLabel}</div>\n </div>\n </div>\n );\n }\n\n // ── Assistant message: open editorial style with a brand avatar ──────\n return (\n <div className=\"flex gap-2.5\" data-testid=\"assistant-message-assistant\">\n <div className=\"mt-0.5 flex size-6 flex-shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-action-primary-bg/25 to-action-primary-bg/5 text-action-primary-bg\">\n <Sparkles className=\"size-3.5\" />\n </div>\n\n <div className=\"min-w-0 flex-1\">\n {steps.length > 0 && <AssistantToolActivity steps={steps} />}\n\n {text && (\n <div className=\"text-[15px] leading-relaxed text-text-primary\">\n <AssistantMarkdownRenderer content={text} />\n </div>\n )}\n\n {isStreaming && (\n // Purely decorative \"still typing\" caret: hidden from assistive tech\n // (the list's aria-busy already conveys the state) and motion-safe so\n // it does not pulse for a reduced-motion user.\n <span\n aria-hidden=\"true\"\n className=\"ml-0.5 inline-block h-4 w-1.5 rounded-sm bg-text-secondary align-middle motion-safe:animate-pulse\"\n />\n )}\n\n {artifacts.length > 0 && metadata?.sandboxId && metadata.sessionId && (\n <div className=\"mt-3 space-y-2 border-t border-border-subtle pt-2\">\n <p className=\"text-[10px] font-medium uppercase tracking-wide text-text-muted\">\n {tr('healthybowl.assistant.message.downloads', 'Downloads')}\n </p>\n <div className=\"flex flex-wrap gap-2\">\n {artifacts.map((artifact) => {\n const displayName = `${artifact.name}${artifact.type === 'directory' ? '.tar.gz' : ''}`;\n const isDownloading = downloadingArtifactPath === artifact.path;\n return (\n <SaveToFilesButton\n key={artifact.path}\n label={displayName}\n disabled={isDownloading}\n testId={`assistant-artifact-${artifact.name}`}\n source={{\n kind: 'sandbox-artifact',\n sandboxId: metadata.sandboxId!,\n sessionId: metadata.sessionId!,\n path: artifact.path,\n filename: displayName,\n }}\n defaultFolderPath=\"/HealthyBowl/AI Assistant/Artifacts\"\n onDownload={() => handleArtifactDownload(artifact)}\n />\n );\n })}\n </div>\n </div>\n )}\n\n {/* Action row: Copy + Read aloud (any settled assistant text) + Retry (failed OR latest turn) */}\n {!isStreaming && (text || isFailed || isLastAssistant) && (\n <div className=\"mt-1.5 flex items-center gap-1\">\n {text && (\n <button\n type=\"button\"\n onClick={handleCopy}\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\"\n aria-label={tr('healthybowl.assistant.message.copy', 'Copy message')}\n data-testid=\"assistant-message-copy\"\n >\n {copied ? (\n <>\n <Check className=\"size-3 text-status-success-text\" />\n <span>{tr('healthybowl.assistant.message.copied', 'Copied')}</span>\n </>\n ) : (\n <>\n <Copy className=\"size-3\" />\n <span>{tr('healthybowl.assistant.message.copy', 'Copy')}</span>\n </>\n )}\n </button>\n )}\n {/* Playback is always user-initiated — nothing here autoplays. The\n control is absent (not disabled) where the browser has no speech\n output, matching how the composer treats the microphone. */}\n {text && speech.isSupported && (\n <AssistantSpeakButton\n isSpeaking={speech.isSpeaking(message.id)}\n disabled={speech.isBlocked}\n disabledReason={speech.disabledReason}\n onClick={() => speech.toggle(message.id, text)}\n />\n )}\n {(isFailed || isLastAssistant) && onRetry && (\n <button\n type=\"button\"\n onClick={onRetry}\n className={`flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] transition-colors hover:bg-bg-elevated ${\n isFailed ? 'text-status-error-text' : 'text-text-muted hover:text-text-secondary'\n }`}\n aria-label={tr('healthybowl.assistant.message.retry', 'Retry')}\n data-testid=\"assistant-message-retry\"\n >\n <RotateCcw className=\"size-3\" />\n <span>{tr('healthybowl.assistant.message.retry', 'Retry')}</span>\n </button>\n )}\n </div>\n )}\n\n <div className=\"mt-1 text-[10px] text-text-muted\">\n {timeLabel}\n {message.tokens && <span className=\"ml-2\">{message.tokens.input + message.tokens.output} tokens</span>}\n </div>\n </div>\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,SAAS,EAAqB,GAAwD;CACpF,OAAO,EAAQ,SAAS,cAAc,EAAQ,WAAW,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W,EAAQ,EAAE;OACxC,UAAU,EAAO;OACjB,gBAAgB,EAAO;OACvB,eAAe,EAAO,OAAO,EAAQ,IAAI,CAAI;MAC9C,CAAA;OAED,KAAY,MAAoB,KAChC,kBAAC,UAAD;OACE,MAAK;OACL,SAAS;OACT,WAAW,qGACT,IAAW,2BAA2B;OAExC,cAAY,EAAG,uCAAuC,OAAO;OAC7D,eAAY;iBAPd,CASE,kBAAC,GAAD,EAAW,WAAU,SAAU,CAAA,GAC/B,kBAAC,QAAD,EAAA,UAAO,EAAG,uCAAuC,OAAO,EAAQ,CAAA,CAC1D;;KAEP;;IAGP,kBAAC,OAAD;KAAK,WAAU;eAAf,CACG,GACA,EAAQ,UAAU,kBAAC,QAAD;MAAM,WAAU;gBAAhB,CAAwB,EAAQ,OAAO,QAAQ,EAAQ,OAAO,QAAO,SAAa;OAClG;;GACF;IACF;;AAET"}
1
+ {"version":3,"file":"AssistantMessageItem.js","names":[],"sources":["../../../src/components/assistant/AssistantMessageItem.tsx"],"sourcesContent":["import { useMemo, useState, type FC } from 'react';\nimport { Sparkles, Copy, Check, RotateCcw } from 'lucide-react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { SaveToFilesButton } from '@burdenoff/fe-libs/storage';\nimport { AssistantMarkdownRenderer } from './AssistantMarkdownRenderer';\nimport { AssistantMessageAttachments } from './AssistantMessageAttachments';\nimport { AssistantSpeakButton } from './AssistantSpeakButton';\nimport { useAssistantSpeech } from './AssistantSpeechProvider';\nimport { AssistantToolActivity, parseToolActivity } from './AssistantToolActivity';\nimport { downloadAssistantArtifact } from '@/services/assistantApi';\nimport type { AssistantArtifact, AssistantMessageMetadata, Message } from '@/types/assistant';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { copyToClipboard } from '../../utils/clipboard';\n\ninterface Props {\n message: Message;\n isStreaming?: boolean;\n /** This assistant message ended in an error — show the Retry affordance. */\n isFailed?: boolean;\n /**\n * The most recent assistant turn. Retry is offered here too — a turn can\n * \"complete\" with an apology (e.g. a gateway 403 the model reports as text)\n * without ever tripping `isFailed`, and the user still needs a way to re-run.\n */\n isLastAssistant?: boolean;\n /** Re-send the last user prompt (wired by AssistantChatArea). */\n onRetry?: () => void;\n}\n\nfunction getAssistantMetadata(message: Message): AssistantMessageMetadata | undefined {\n return message.role === 'assistant' ? message.metadata : undefined;\n}\n\nfunction getArtifacts(metadata: AssistantMessageMetadata | undefined): AssistantArtifact[] {\n return metadata?.artifacts ?? [];\n}\n\nfunction decodeBase64(base64: string): string {\n return window.atob(base64);\n}\n\nfunction downloadBase64File(base64: string, filename: string, mimeType: string): void {\n const binary = decodeBase64(base64);\n const bytes = new Uint8Array(binary.length);\n\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n\n const blob = new Blob([bytes], { type: mimeType });\n const url = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = url;\n link.download = filename;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n\nexport const AssistantMessageItem: FC<Props> = ({ message, isStreaming, isFailed, isLastAssistant, onRetry }) => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken } = useAuthToken();\n const speech = useAssistantSpeech();\n const [downloadingArtifactPath, setDownloadingArtifactPath] = useState<string | null>(null);\n const [copied, setCopied] = useState(false);\n const isUser = message.role === 'user';\n const metadata = useMemo(() => getAssistantMetadata(message), [message]);\n const artifacts = useMemo(() => getArtifacts(metadata), [metadata]);\n // Separate the streamed tool-progress lines from the assistant's prose so the\n // former renders as a structured activity card (see AssistantToolActivity).\n const { steps, text } = useMemo(\n () => (isUser ? { steps: [], text: message.content } : parseToolActivity(message.content)),\n [isUser, message.content]\n );\n\n const handleCopy = () => {\n // Confirm only on a real copy — see copyToClipboard.\n void copyToClipboard(text || message.content).then((ok) => {\n if (!ok) return;\n setCopied(true);\n setTimeout(() => setCopied(false), 2000);\n });\n };\n\n const handleArtifactDownload = async (artifact: AssistantArtifact) => {\n if (!metadata?.sandboxId || !metadata.sessionId) return;\n\n const workspaceId = new URLSearchParams(window.location.search).get('workspace') ?? '';\n if (!workspaceId) return;\n\n setDownloadingArtifactPath(artifact.path);\n\n try {\n const result = await downloadAssistantArtifact(\n apollo,\n metadata.sandboxId,\n workspaceId,\n metadata.sessionId,\n artifact.path,\n {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n }\n );\n\n downloadBase64File(result.contentBase64, result.filename, result.mimeType);\n } finally {\n setDownloadingArtifactPath(null);\n }\n };\n\n const timeLabel = new Date(message.timestamp).toLocaleTimeString([], {\n hour: '2-digit',\n minute: '2-digit',\n });\n\n // ── User message: soft filled bubble, right-aligned ──────────────────\n if (isUser) {\n const attachments = message.metadata?.attachments ?? [];\n return (\n <div className=\"flex justify-end\" data-testid=\"assistant-message-user\">\n <div className=\"max-w-[85%]\">\n {/* An attachments-only turn (a photo with no words) has no bubble to\n draw — skip it rather than rendering an empty green pill. */}\n {message.content && (\n <div className=\"rounded-2xl rounded-br-md bg-action-primary-bg/12 px-3.5 py-2.5 text-[15px] leading-relaxed text-text-primary\">\n <p className=\"whitespace-pre-wrap\">{message.content}</p>\n </div>\n )}\n <AssistantMessageAttachments attachments={attachments} />\n <div className=\"mt-1 pr-1 text-right text-[10px] text-text-muted\">{timeLabel}</div>\n </div>\n </div>\n );\n }\n\n // ── Assistant message: open editorial style with a brand avatar ──────\n return (\n <div className=\"flex gap-2.5\" data-testid=\"assistant-message-assistant\">\n <div className=\"mt-0.5 flex size-6 flex-shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-action-primary-bg/25 to-action-primary-bg/5 text-action-primary-bg\">\n <Sparkles className=\"size-3.5\" />\n </div>\n\n <div className=\"min-w-0 flex-1\">\n {steps.length > 0 && <AssistantToolActivity steps={steps} />}\n\n {text && (\n <div className=\"text-[15px] leading-relaxed text-text-primary\">\n <AssistantMarkdownRenderer content={text} />\n </div>\n )}\n\n {isStreaming && (\n // Purely decorative \"still typing\" caret: hidden from assistive tech\n // (the list's aria-busy already conveys the state) and motion-safe so\n // it does not pulse for a reduced-motion user.\n <span\n aria-hidden=\"true\"\n className=\"ml-0.5 inline-block h-4 w-1.5 rounded-sm bg-text-secondary align-middle motion-safe:animate-pulse\"\n />\n )}\n\n {artifacts.length > 0 && metadata?.sandboxId && metadata.sessionId && (\n <div className=\"mt-3 space-y-2 border-t border-border-subtle pt-2\">\n <p className=\"text-[10px] font-medium uppercase tracking-wide text-text-muted\">\n {tr('healthybowl.assistant.message.downloads', 'Downloads')}\n </p>\n <div className=\"flex flex-wrap gap-2\">\n {artifacts.map((artifact) => {\n const displayName = `${artifact.name}${artifact.type === 'directory' ? '.tar.gz' : ''}`;\n const isDownloading = downloadingArtifactPath === artifact.path;\n return (\n <SaveToFilesButton\n key={artifact.path}\n label={displayName}\n disabled={isDownloading}\n testId={`assistant-artifact-${artifact.name}`}\n source={{\n kind: 'sandbox-artifact',\n sandboxId: metadata.sandboxId!,\n sessionId: metadata.sessionId!,\n path: artifact.path,\n filename: displayName,\n }}\n defaultFolderPath=\"/HealthyBowl/AI Assistant/Artifacts\"\n onDownload={() => handleArtifactDownload(artifact)}\n />\n );\n })}\n </div>\n </div>\n )}\n\n {/* Action row: Copy + Read aloud (any settled assistant text) + Retry (failed OR latest turn) */}\n {!isStreaming && (text || isFailed || isLastAssistant) && (\n <div className=\"mt-1.5 flex items-center gap-1\">\n {text && (\n <button\n type=\"button\"\n onClick={handleCopy}\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\"\n aria-label={tr('healthybowl.assistant.message.copy', 'Copy message')}\n data-testid=\"assistant-message-copy\"\n >\n {copied ? (\n <>\n <Check className=\"size-3 text-status-success-text\" />\n <span>{tr('healthybowl.assistant.message.copied', 'Copied')}</span>\n </>\n ) : (\n <>\n <Copy className=\"size-3\" />\n <span>{tr('healthybowl.assistant.message.copy', 'Copy')}</span>\n </>\n )}\n </button>\n )}\n {/* Playback is always user-initiated — nothing here autoplays. The\n control is absent (not disabled) where the browser has no speech\n output, matching how the composer treats the microphone. */}\n {text && speech.isSupported && (\n <>\n <AssistantSpeakButton\n isSpeaking={speech.isSpeaking(message.id)}\n disabled={speech.isBlocked}\n disabledReason={speech.disabledReason}\n // Only when the element below is actually rendered. A\n // describedby pointing at a missing id is worse than none:\n // assistive tech follows the reference and finds nothing.\n describedById={speech.disabledReason && isLastAssistant ? `speak-reason-${message.id}` : undefined}\n onClick={() => speech.toggle(message.id, text)}\n />\n {/* The reason has to be READABLE, not just a `title`. A native\n tooltip on a DISABLED button cannot be reached by touch and\n cannot take keyboard focus — i.e. it is invisible to exactly\n the phone and screen-reader users this explanation exists\n for. Rendered only on the newest reply so it explains once\n rather than repeating down the whole transcript. */}\n {speech.disabledReason && isLastAssistant && (\n <span\n id={`speak-reason-${message.id}`}\n className=\"text-[11px] text-text-muted\"\n data-testid=\"assistant-speak-reason\"\n >\n {speech.disabledReason}\n </span>\n )}\n </>\n )}\n {(isFailed || isLastAssistant) && onRetry && (\n <button\n type=\"button\"\n onClick={onRetry}\n className={`flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] transition-colors hover:bg-bg-elevated ${\n isFailed ? 'text-status-error-text' : 'text-text-muted hover:text-text-secondary'\n }`}\n aria-label={tr('healthybowl.assistant.message.retry', 'Retry')}\n data-testid=\"assistant-message-retry\"\n >\n <RotateCcw className=\"size-3\" />\n <span>{tr('healthybowl.assistant.message.retry', 'Retry')}</span>\n </button>\n )}\n </div>\n )}\n\n <div className=\"mt-1 text-[10px] text-text-muted\">\n {timeLabel}\n {message.tokens && <span className=\"ml-2\">{message.tokens.input + message.tokens.output} tokens</span>}\n </div>\n </div>\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,SAAS,EAAqB,GAAwD;CACpF,OAAO,EAA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A,GAAA,EAAA,UAAA,CACE,kBAAC,GAAD;OACE,YAAY,EAAO,WAAW,EAAQ,EAAE;OACxC,UAAU,EAAO;OACjB,gBAAgB,EAAO;OAIvB,eAAe,EAAO,kBAAkB,IAAkB,gBAAgB,EAAQ,OAAO,KAAA;OACzF,eAAe,EAAO,OAAO,EAAQ,IAAI,CAAI;MAC9C,CAAA,GAOA,EAAO,kBAAkB,KACxB,kBAAC,QAAD;OACE,IAAI,gBAAgB,EAAQ;OAC5B,WAAU;OACV,eAAY;iBAEX,EAAO;MACJ,CAAA,CAER,EAAA,CAAA;OAEF,KAAY,MAAoB,KAChC,kBAAC,UAAD;OACE,MAAK;OACL,SAAS;OACT,WAAW,qGACT,IAAW,2BAA2B;OAExC,cAAY,EAAG,uCAAuC,OAAO;OAC7D,eAAY;iBAPd,CASE,kBAAC,GAAD,EAAW,WAAU,SAAU,CAAA,GAC/B,kBAAC,QAAD,EAAA,UAAO,EAAG,uCAAuC,OAAO,EAAQ,CAAA,CAC1D;;KAEP;;IAGP,kBAAC,OAAD;KAAK,WAAU;eAAf,CACG,GACA,EAAQ,UAAU,kBAAC,QAAD;MAAM,WAAU;gBAAhB,CAAwB,EAAQ,OAAO,QAAQ,EAAQ,OAAO,QAAO,SAAa;OAClG;;GACF;IACF;;AAET"}
@@ -2,18 +2,19 @@ import { useTr as e } from "../../shared/hooks/useTr.js";
2
2
  import { Square as t, Volume2 as n } from "lucide-react";
3
3
  import { jsx as r, jsxs as i } from "react/jsx-runtime";
4
4
  //#region src/components/assistant/AssistantSpeakButton.tsx
5
- var a = ({ isSpeaking: a, disabled: o = !1, disabledReason: s, onClick: c }) => {
6
- let l = e(), u = a ? l("healthybowl.assistant.message.stopSpeakingShort", "Stop") : l("healthybowl.assistant.message.speakShort", "Listen"), d = a ? l("healthybowl.assistant.message.stopSpeaking", "Stop reading aloud") : l("healthybowl.assistant.message.speak", "Read this reply aloud");
5
+ var a = ({ isSpeaking: a, disabled: o = !1, disabledReason: s, describedById: c, onClick: l }) => {
6
+ let u = e(), d = a ? u("healthybowl.assistant.message.stopSpeakingShort", "Stop") : u("healthybowl.assistant.message.speakShort", "Listen"), f = a ? u("healthybowl.assistant.message.stopSpeaking", "Stop reading aloud") : u("healthybowl.assistant.message.speak", "Read this reply aloud");
7
7
  return /* @__PURE__ */ i("button", {
8
8
  type: "button",
9
- onClick: c,
9
+ onClick: l,
10
10
  disabled: o,
11
- title: o ? s ?? d : d,
12
- "aria-label": d,
11
+ title: o ? s ?? f : f,
12
+ "aria-label": f,
13
13
  "aria-pressed": a,
14
+ "aria-describedby": c,
14
15
  className: `flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] transition-colors hover:bg-bg-elevated disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent ${a ? "text-action-primary-bg" : "text-text-muted hover:text-text-secondary"}`,
15
16
  "data-testid": "assistant-message-speak",
16
- children: [a ? /* @__PURE__ */ r(t, { className: "size-3 fill-current" }) : /* @__PURE__ */ r(n, { className: "size-3" }), /* @__PURE__ */ r("span", { children: u })]
17
+ children: [a ? /* @__PURE__ */ r(t, { className: "size-3 fill-current" }) : /* @__PURE__ */ r(n, { className: "size-3" }), /* @__PURE__ */ r("span", { children: d })]
17
18
  });
18
19
  };
19
20
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantSpeakButton.js","names":[],"sources":["../../../src/components/assistant/AssistantSpeakButton.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { Volume2, Square } from 'lucide-react';\nimport { useTr } from '../../shared/hooks/useTr';\n\ninterface Props {\n isSpeaking: boolean;\n /** No installed voice for the app language — stays visible, but inert. */\n disabled?: boolean;\n /** Why it is disabled; surfaced as the tooltip so it is never a dead control. */\n disabledReason?: string | null;\n onClick: () => void;\n}\n\n/**\n * \"Read aloud\" control on an assistant message (BOFF-6290).\n *\n * A real `<button>`, sitting in the same action row as Copy and Retry, whose\n * accessible name is the ACTION it will perform next — \"Read aloud\" when idle,\n * \"Stop reading\" while speaking — with `aria-pressed` carrying the state. It\n * never moves focus and never renders a live region: a screen-reader user is\n * already having the message read to them by their own software, and a second\n * announcement would talk over it.\n *\n * The parent hides this entirely when the platform has no speech output, so an\n * unsupported browser gets no dead affordance (same rule as the composer mic).\n */\nexport const AssistantSpeakButton: FC<Props> = ({ isSpeaking, disabled = false, disabledReason, onClick }) => {\n const tr = useTr();\n\n // Short visible text (the action row is narrow in a docked panel) with a fuller\n // accessible name — both change with state, so the name always describes what\n // pressing it will do next.\n const text = isSpeaking\n ? tr('healthybowl.assistant.message.stopSpeakingShort', 'Stop')\n : tr('healthybowl.assistant.message.speakShort', 'Listen');\n const label = isSpeaking\n ? tr('healthybowl.assistant.message.stopSpeaking', 'Stop reading aloud')\n : tr('healthybowl.assistant.message.speak', 'Read this reply aloud');\n\n return (\n <button\n type=\"button\"\n onClick={onClick}\n disabled={disabled}\n title={disabled ? (disabledReason ?? label) : label}\n aria-label={label}\n aria-pressed={isSpeaking}\n className={`flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] transition-colors hover:bg-bg-elevated disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent ${\n isSpeaking ? 'text-action-primary-bg' : 'text-text-muted hover:text-text-secondary'\n }`}\n data-testid=\"assistant-message-speak\"\n >\n {isSpeaking ? <Square className=\"size-3 fill-current\" /> : <Volume2 className=\"size-3\" />}\n <span>{text}</span>\n </button>\n );\n};\n"],"mappings":";;;;AA0BA,IAAa,KAAmC,EAAE,eAAY,cAAW,IAAO,mBAAgB,iBAAc;CAC5G,IAAM,IAAK,EAAM,GAKX,IAAO,IACT,EAAG,mDAAmD,MAAM,IAC5D,EAAG,4CAA4C,QAAQ,GACrD,IAAQ,IACV,EAAG,8CAA8C,oBAAoB,IACrE,EAAG,uCAAuC,uBAAuB;CAErE,OACE,kBAAC,UAAD;EACE,MAAK;EACI;EACC;EACV,OAAO,IAAY,KAAkB,IAAS;EAC9C,cAAY;EACZ,gBAAc;EACd,WAAW,mLACT,IAAa,2BAA2B;EAE1C,eAAY;YAVd,CAYG,IAAa,kBAAC,GAAD,EAAQ,WAAU,sBAAuB,CAAA,IAAI,kBAAC,GAAD,EAAS,WAAU,SAAU,CAAA,GACxF,kBAAC,QAAD,EAAA,UAAO,EAAW,CAAA,CACZ;;AAEZ"}
1
+ {"version":3,"file":"AssistantSpeakButton.js","names":[],"sources":["../../../src/components/assistant/AssistantSpeakButton.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { Volume2, Square } from 'lucide-react';\nimport { useTr } from '../../shared/hooks/useTr';\n\ninterface Props {\n isSpeaking: boolean;\n /** No installed voice for the app language — stays visible, but inert. */\n disabled?: boolean;\n /** Why it is disabled; surfaced as the tooltip so it is never a dead control. */\n disabledReason?: string | null;\n /**\n * Id of the element carrying that reason as VISIBLE text.\n *\n * `title` alone is not an explanation: on a disabled button it cannot be\n * reached by touch and cannot take keyboard focus, so assistive tech and\n * phone users — the ones this feature is for — never see it.\n */\n describedById?: string | undefined;\n onClick: () => void;\n}\n\n/**\n * \"Read aloud\" control on an assistant message (BOFF-6290).\n *\n * A real `<button>`, sitting in the same action row as Copy and Retry, whose\n * accessible name is the ACTION it will perform next — \"Read aloud\" when idle,\n * \"Stop reading\" while speaking — with `aria-pressed` carrying the state. It\n * never moves focus and never renders a live region: a screen-reader user is\n * already having the message read to them by their own software, and a second\n * announcement would talk over it.\n *\n * The parent hides this entirely when the platform has no speech output, so an\n * unsupported browser gets no dead affordance (same rule as the composer mic).\n */\nexport const AssistantSpeakButton: FC<Props> = ({\n isSpeaking,\n disabled = false,\n disabledReason,\n describedById,\n onClick,\n}) => {\n const tr = useTr();\n\n // Short visible text (the action row is narrow in a docked panel) with a fuller\n // accessible name — both change with state, so the name always describes what\n // pressing it will do next.\n const text = isSpeaking\n ? tr('healthybowl.assistant.message.stopSpeakingShort', 'Stop')\n : tr('healthybowl.assistant.message.speakShort', 'Listen');\n const label = isSpeaking\n ? tr('healthybowl.assistant.message.stopSpeaking', 'Stop reading aloud')\n : tr('healthybowl.assistant.message.speak', 'Read this reply aloud');\n\n return (\n <button\n type=\"button\"\n onClick={onClick}\n disabled={disabled}\n title={disabled ? (disabledReason ?? label) : label}\n aria-label={label}\n aria-pressed={isSpeaking}\n aria-describedby={describedById}\n className={`flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] transition-colors hover:bg-bg-elevated disabled:cursor-not-allowed disabled:opacity-50 disabled:hover:bg-transparent ${\n isSpeaking ? 'text-action-primary-bg' : 'text-text-muted hover:text-text-secondary'\n }`}\n data-testid=\"assistant-message-speak\"\n >\n {isSpeaking ? <Square className=\"size-3 fill-current\" /> : <Volume2 className=\"size-3\" />}\n <span>{text}</span>\n </button>\n );\n};\n"],"mappings":";;;;AAkCA,IAAa,KAAmC,EAC9C,eACA,cAAW,IACX,mBACA,kBACA,iBACI;CACJ,IAAM,IAAK,EAAM,GAKX,IAAO,IACT,EAAG,mDAAmD,MAAM,IAC5D,EAAG,4CAA4C,QAAQ,GACrD,IAAQ,IACV,EAAG,8CAA8C,oBAAoB,IACrE,EAAG,uCAAuC,uBAAuB;CAErE,OACE,kBAAC,UAAD;EACE,MAAK;EACI;EACC;EACV,OAAO,IAAY,KAAkB,IAAS;EAC9C,cAAY;EACZ,gBAAc;EACd,oBAAkB;EAClB,WAAW,mLACT,IAAa,2BAA2B;EAE1C,eAAY;YAXd,CAaG,IAAa,kBAAC,GAAD,EAAQ,WAAU,sBAAuB,CAAA,IAAI,kBAAC,GAAD,EAAS,WAAU,SAAU,CAAA,GACxF,kBAAC,QAAD,EAAA,UAAO,EAAW,CAAA,CACZ;;AAEZ"}
@@ -2,15 +2,15 @@ import { useAssistantStore as e } from "../../store/assistantStore.js";
2
2
  import { useTr as t } from "../../shared/hooks/useTr.js";
3
3
  import { browserSpeechEngine as n } from "../../services/speech/browserSpeechEngine.js";
4
4
  import { chunkForSpeech as r, toSpeakableText as i } from "../../utils/speakableText.js";
5
- import { VOICE_LIST_TIMEOUT_MS as a, isSpeechBlocked as o, selectVoiceForLocale as s, speechGate as c, speechLangForLocale as l, voiceAvailability as u } from "../../utils/speechVoices.js";
6
- import { IDLE_PLAYBACK as d, isSpeakingMessage as f, speechPlaybackReducer as p } from "../../utils/speechPlayback.js";
7
- import { isTurnInFlight as m } from "../../utils/assistantTurnState.js";
8
- import { parseToolActivity as h } from "./AssistantToolActivity.js";
9
- import { createContext as g, useCallback as _, useContext as v, useEffect as y, useMemo as b, useReducer as x, useRef as S, useState as C } from "react";
5
+ import { VOICE_LIST_TIMEOUT_MS as a, isSpeechBlocked as o, languageDisplayName as s, selectVoiceForLocale as c, speechGate as l, speechLangForLocale as u, voiceAvailability as d } from "../../utils/speechVoices.js";
6
+ import { IDLE_PLAYBACK as f, isSpeakingMessage as p, speechPlaybackReducer as m } from "../../utils/speechPlayback.js";
7
+ import { isTurnInFlight as h } from "../../utils/assistantTurnState.js";
8
+ import { parseToolActivity as g } from "./AssistantToolActivity.js";
9
+ import { createContext as _, useCallback as v, useContext as y, useEffect as b, useMemo as x, useReducer as ee, useRef as S, useState as C } from "react";
10
10
  import { useI18n as w } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
11
11
  import { jsx as T } from "react/jsx-runtime";
12
12
  //#region src/components/assistant/AssistantSpeechProvider.tsx
13
- var E = g({
13
+ var E = _({
14
14
  isSupported: !1,
15
15
  availability: "unsupported",
16
16
  isBlocked: !0,
@@ -23,58 +23,65 @@ var E = g({
23
23
  setAutoSpeak: () => {}
24
24
  });
25
25
  function D() {
26
- return v(E);
26
+ return y(E);
27
27
  }
28
- var O = ({ children: g, visible: v = !0, engine: D = n }) => {
29
- let O = t(), { locale: k } = w(), [A, j] = x(p, d), [M, N] = C(() => D.listVoices()), P = S(0), F = S(null), I = S(() => {}), L = _(() => {
30
- F.current?.(), F.current = null;
31
- }, []), R = e((e) => e.autoSpeakEnabled), z = e((e) => e.setAutoSpeak), B = e((e) => e.activeConversationId), V = b(() => D.isSupported(), [D]);
32
- y(() => {
33
- if (!V) return;
28
+ var O = ({ children: _, visible: y = !0, engine: D = n }) => {
29
+ let O = t(), { locale: k } = w(), [A, j] = ee(m, f), [M, N] = C(() => D.listVoices()), [P, F] = C(!1), I = S(0), L = S(null), R = S(() => {}), z = v(() => {
30
+ L.current?.(), L.current = null;
31
+ }, []), B = e((e) => e.autoSpeakEnabled), V = e((e) => e.setAutoSpeak), H = e((e) => e.activeConversationId), U = x(() => D.isSupported(), [D]);
32
+ b(() => {
33
+ if (!U) return;
34
34
  let e = () => N(D.listVoices());
35
35
  return e(), D.subscribeVoices(e);
36
- }, [D, V]);
37
- let H = b(() => u(V, M, k), [
38
- V,
36
+ }, [D, U]);
37
+ let W = x(() => d(U, M, k, P), [
38
+ U,
39
39
  M,
40
- k
41
- ]), U = b(() => l(k), [k]), W = b(() => ({
40
+ k,
41
+ P
42
+ ]), G = x(() => u(k), [k]), K = x(() => s(G, k), [G, k]), q = x(() => ({
42
43
  codeBlock: O("healthybowl.assistant.speech.codeBlock", "Code block"),
43
44
  image: O("healthybowl.assistant.speech.image", "image"),
44
45
  link: O("healthybowl.assistant.speech.link", "link"),
45
46
  largeTable: O("healthybowl.assistant.speech.largeTable", "Table with {{rows}} rows and {{columns}} columns"),
46
47
  truncated: O("healthybowl.assistant.speech.truncated", "The rest of this message is not read aloud"),
47
48
  nestedItem: O("healthybowl.assistant.speech.nestedItem", "Sub-item {{ordinal}}")
48
- }), [O]), G = _(() => {
49
- L(), D.cancel(), j({ type: "stop" });
50
- }, [L, D]), K = _((e, t) => {
51
- L();
49
+ }), [O]), J = v(() => {
50
+ z(), D.cancel(), j({ type: "stop" });
51
+ }, [z, D]), Y = v((e, t) => {
52
+ z();
52
53
  let n = !1, r = () => {}, i = (i) => {
53
- n || (n = !0, F.current = null, clearTimeout(o), r(), i.length !== 0 && (N(i), I.current(e, t, i)));
54
+ if (!n) {
55
+ if (n = !0, L.current = null, clearTimeout(o), r(), i.length === 0) {
56
+ F(!0);
57
+ return;
58
+ }
59
+ N(i), R.current(e, t, i);
60
+ }
54
61
  }, o = setTimeout(() => i(D.listVoices()), a);
55
- r = D.subscribeVoices(() => i(D.listVoices())), F.current = () => {
56
- n || (n = !0, clearTimeout(o), r(), F.current = null);
62
+ r = D.subscribeVoices(() => i(D.listVoices())), L.current = () => {
63
+ n || (n = !0, clearTimeout(o), r(), L.current = null);
57
64
  };
58
- }, [L, D]), q = _((e, t, n) => {
65
+ }, [z, D]), X = v((e, t, n) => {
59
66
  let i = n;
60
67
  if (i.length === 0) {
61
68
  let e = D.listVoices();
62
69
  e.length > 0 && (i = e, N(e));
63
70
  }
64
- let a = c(u(!0, i, k));
71
+ let a = l(d(!0, i, k, P));
65
72
  if (a === "block") return;
66
73
  if (a === "wait-for-voices") {
67
- K(e, t);
74
+ Y(e, t);
68
75
  return;
69
76
  }
70
- let o = P.current + 1;
71
- P.current = o, j({
77
+ let o = I.current + 1;
78
+ I.current = o, j({
72
79
  type: "start",
73
80
  messageId: e,
74
81
  requestId: o
75
82
  }), D.speak(r(t), {
76
- voice: s(i, k),
77
- lang: U
83
+ voice: c(i, k),
84
+ lang: G
78
85
  }, {
79
86
  onEnd: () => j({
80
87
  type: "finished",
@@ -87,90 +94,106 @@ var O = ({ children: g, visible: v = !0, engine: D = n }) => {
87
94
  });
88
95
  }, [
89
96
  D,
90
- U,
97
+ G,
91
98
  k,
92
- K
99
+ P,
100
+ Y
93
101
  ]);
94
- y(() => {
95
- I.current = q;
96
- }, [q]);
97
- let J = _((e, t) => {
98
- if (!V) return;
99
- let n = i(t, { labels: W });
100
- n && q(e, n, M);
102
+ b(() => {
103
+ R.current = X;
104
+ }, [X]);
105
+ let Z = v((e, t) => {
106
+ if (!U) return;
107
+ let n = i(t, { labels: q });
108
+ n && X(e, n, M);
101
109
  }, [
102
- V,
103
- W,
110
+ U,
104
111
  q,
112
+ X,
105
113
  M
106
- ]), Y = _((e, t) => {
107
- if (f(A, e)) {
108
- G();
114
+ ]), Q = v((e, t) => {
115
+ if (p(A, e)) {
116
+ J();
109
117
  return;
110
118
  }
111
- J(e, t);
119
+ Z(e, t);
112
120
  }, [
113
121
  A,
114
- J,
115
- G
122
+ Z,
123
+ J
116
124
  ]);
117
- y(() => {
118
- v || G();
119
- }, [v, G]), y(() => {
120
- G();
121
- }, [B, G]), y(() => () => {
122
- F.current?.(), F.current = null, D.cancel();
123
- }, [D]), y(() => {
125
+ b(() => {
126
+ y || J();
127
+ }, [y, J]), b(() => {
128
+ J();
129
+ }, [H, J]), b(() => () => {
130
+ L.current?.(), L.current = null, D.cancel();
131
+ }, [D]), b(() => {
124
132
  if (typeof window > "u") return;
125
133
  let e = () => D.cancel();
126
134
  return window.addEventListener("pagehide", e), () => window.removeEventListener("pagehide", e);
127
- }, [D]);
128
- let X = S(J);
129
- y(() => {
130
- X.current = J;
131
- }, [J]), y(() => {
132
- if (!(!R || !v || !V || o(H))) return e.subscribe((e, t) => {
135
+ }, [D]), b(() => {
136
+ if (typeof document > "u" || !U) return;
137
+ let e = () => {
138
+ if (document.visibilityState !== "visible") return;
139
+ let e = D.listVoices();
140
+ e.length > 0 && z(), N(e), F(!1);
141
+ };
142
+ return document.addEventListener("visibilitychange", e), window.addEventListener("focus", e), () => {
143
+ document.removeEventListener("visibilitychange", e), window.removeEventListener("focus", e);
144
+ };
145
+ }, [
146
+ z,
147
+ D,
148
+ U
149
+ ]);
150
+ let $ = S(Z);
151
+ b(() => {
152
+ $.current = Z;
153
+ }, [Z]), b(() => {
154
+ if (!(!B || !y || !U || o(W))) return e.subscribe((e, t) => {
133
155
  let n = e.activeConversationId;
134
156
  if (!n || n !== t.activeConversationId) return;
135
157
  let r = e.processingByConversationId[n], i = t.processingByConversationId[n];
136
- if (r?.status !== "complete" || !m(i?.status)) return;
158
+ if (r?.status !== "complete" || !h(i?.status)) return;
137
159
  let a = r.messageId ?? i?.messageId ?? null;
138
160
  if (!a) return;
139
161
  let o = e.conversations.find((e) => e.id === n)?.messages.find((e) => e.id === a);
140
162
  if (!o || o.role !== "assistant") return;
141
- let { text: s } = h(o.content);
142
- s.trim() && X.current(a, s);
163
+ let { text: s } = g(o.content);
164
+ s.trim() && $.current(a, s);
143
165
  });
144
166
  }, [
145
- R,
146
- H,
147
- V,
148
- v
167
+ B,
168
+ W,
169
+ U,
170
+ y
149
171
  ]);
150
- let Z = b(() => ({
151
- isSupported: V,
152
- availability: H,
153
- isBlocked: o(H),
154
- disabledReason: o(H) ? O("healthybowl.assistant.speech.noVoiceInstalled", "No voice for this language is installed on this device") : null,
172
+ let te = x(() => ({
173
+ isSupported: U,
174
+ availability: W,
175
+ isBlocked: o(W),
176
+ disabledReason: W === "no-voices" ? O("healthybowl.assistant.speech.noVoicesOnDevice", "This device has no speech voices installed. Add one in your device speech or accessibility settings.") : W === "missing-voice" ? O("healthybowl.assistant.speech.noVoiceForLanguage", "No {{language}} voice is installed on this device. Add one in your device speech or accessibility settings.", { language: K }) : null,
155
177
  speakingMessageId: A.status === "speaking" ? A.messageId : null,
156
- isSpeaking: (e) => f(A, e),
157
- toggle: Y,
158
- stop: G,
159
- autoSpeakEnabled: R,
160
- setAutoSpeak: z
178
+ isSpeaking: (e) => p(A, e),
179
+ toggle: Q,
180
+ stop: J,
181
+ autoSpeakEnabled: B,
182
+ setAutoSpeak: V
161
183
  }), [
162
- V,
163
- H,
184
+ U,
185
+ W,
186
+ K,
164
187
  A,
165
- Y,
166
- G,
167
- R,
168
- z,
188
+ Q,
189
+ J,
190
+ B,
191
+ V,
169
192
  O
170
193
  ]);
171
194
  return /* @__PURE__ */ T(E.Provider, {
172
- value: Z,
173
- children: g
195
+ value: te,
196
+ children: _
174
197
  });
175
198
  };
176
199
  //#endregion
@@ -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 { browserSpeechEngine } from '../../services/speech';\nimport type { SpeechEngine, SpeechVoiceLike } from '../../services/speech';\nimport { chunkForSpeech, toSpeakableText, type SpeakableLabels } from '../../utils/speakableText';\nimport {\n VOICE_LIST_TIMEOUT_MS,\n isSpeechBlocked,\n selectVoiceForLocale,\n speechGate,\n speechLangForLocale,\n voiceAvailability,\n type VoiceAvailability,\n} from '../../utils/speechVoices';\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 /** The message currently being spoken, if any. */\n speakingMessageId: string | null;\n isSpeaking: (messageId: string) => boolean;\n /** Speak this message, or stop if it is already the one speaking. */\n toggle: (messageId: string, markdown: string) => void;\n stop: () => void;\n autoSpeakEnabled: boolean;\n setAutoSpeak: (enabled: boolean) => void;\n}\n\nconst INERT_SPEECH: AssistantSpeechContextValue = {\n isSupported: false,\n availability: 'unsupported',\n isBlocked: true,\n disabledReason: null,\n speakingMessageId: null,\n isSpeaking: () => false,\n toggle: () => {},\n stop: () => {},\n autoSpeakEnabled: false,\n setAutoSpeak: () => {},\n};\n\nconst AssistantSpeechContext = createContext<AssistantSpeechContextValue>(INERT_SPEECH);\n\nexport function useAssistantSpeech(): AssistantSpeechContextValue {\n return useContext(AssistantSpeechContext);\n}\n\ninterface Props {\n children: ReactNode;\n /** Panel visibility. Hiding the panel stops the voice. */\n visible?: boolean;\n /** Injectable for a future hosted engine (and for local experiments). */\n engine?: SpeechEngine;\n}\n\nexport const AssistantSpeechProvider: FC<Props> = ({ children, visible = true, engine = browserSpeechEngine }) => {\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 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<(messageId: string, text: string, voices: readonly SpeechVoiceLike[]) => void>(() => {});\n\n const cancelPending = useCallback(() => {\n pendingRef.current?.();\n pendingRef.current = null;\n }, []);\n\n const autoSpeakEnabled = useAssistantStore((state) => state.autoSpeakEnabled);\n const setAutoSpeak = useAssistantStore((state) => state.setAutoSpeak);\n const activeConversationId = useAssistantStore((state) => state.activeConversationId);\n\n const isSupported = useMemo(() => engine.isSupported(), [engine]);\n\n // getVoices() is empty on the first call in Chrome and only fills in when\n // 'voiceschanged' fires; Safari populates it synchronously and may never fire\n // the event. Read eagerly AND subscribe, so both engines end up correct.\n useEffect(() => {\n if (!isSupported) return;\n const sync = () => setVoices(engine.listVoices());\n sync();\n return engine.subscribeVoices(sync);\n }, [engine, isSupported]);\n\n const availability = useMemo(() => voiceAvailability(isSupported, voices, locale), [isSupported, voices, locale]);\n const lang = useMemo(() => speechLangForLocale(locale), [locale]);\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 }),\n [tr]\n );\n\n const stop = useCallback(() => {\n cancelPending();\n engine.cancel();\n dispatch({ type: 'stop' });\n }, [cancelPending, engine]);\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) => {\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) return;\n setVoices(available);\n speakWithRef.current(messageId, text, available);\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[]) => {\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 gate = speechGate(voiceAvailability(true, known, locale));\n if (gate === 'block') return;\n if (gate === 'wait-for-voices') {\n waitForVoices(messageId, text);\n return;\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 { voice: selectVoiceForLocale(known, locale), lang },\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, lang, locale, 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) => {\n if (!isSupported) return;\n\n const text = toSpeakableText(markdown, { labels });\n if (!text) return;\n\n speakWith(messageId, text, voices);\n },\n [isSupported, labels, speakWith, voices]\n );\n\n const toggle = useCallback(\n (messageId: string, markdown: string) => {\n if (isSpeakingMessage(playback, messageId)) {\n stop();\n return;\n }\n speak(messageId, markdown);\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 stop();\n }, [activeConversationId, 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 // ── 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 if (!autoSpeakEnabled || !visible || !isSupported || isSpeechBlocked(availability)) 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);\n });\n }, [autoSpeakEnabled, availability, isSupported, visible]);\n\n const value = useMemo<AssistantSpeechContextValue>(\n () => ({\n isSupported,\n availability,\n isBlocked: isSpeechBlocked(availability),\n disabledReason: isSpeechBlocked(availability)\n ? tr('healthybowl.assistant.speech.noVoiceInstalled', 'No voice for this language is installed on this device')\n : null,\n speakingMessageId: playback.status === 'speaking' ? playback.messageId : null,\n isSpeaking: (messageId: string) => isSpeakingMessage(playback, messageId),\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n }),\n [isSupported, availability, playback, toggle, stop, autoSpeakEnabled, setAutoSpeak, tr]\n );\n\n return <AssistantSpeechContext.Provider value={value}>{children}</AssistantSpeechContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;AA2FA,IAAM,IAAyB,EAA2C;CAZxE,aAAa;CACb,cAAc;CACd,WAAW;CACX,gBAAgB;CAChB,mBAAmB;CACnB,kBAAkB;CAClB,cAAc,CAAC;CACf,YAAY,CAAC;CACb,kBAAkB;CAClB,oBAAoB,CAAC;AAGmD,CAAY;AAEtF,SAAgB,IAAkD;CAChE,OAAO,EAAW,CAAsB;AAC1C;AAUA,IAAa,KAAsC,EAAE,aAAU,aAAU,IAAM,YAAS,QAA0B;CAChH,IAAM,IAAK,EAAM,GACX,EAAE,cAAW,EAAQ,GACrB,CAAC,GAAU,KAAY,EAAW,GAAuB,CAAa,GACtE,CAAC,GAAQ,KAAa,QAAkC,EAAO,WAAW,CAAC,GAC3E,IAAa,EAAO,CAAC,GAErB,IAAa,EAA4B,IAAI,GAC7C,IAAe,QAA4F,CAAC,CAAC,GAE7G,IAAgB,QAAkB;EAEtC,AADA,EAAW,UAAU,GACrB,EAAW,UAAU;CACvB,GAAG,CAAC,CAAC,GAEC,IAAmB,GAAmB,MAAU,EAAM,gBAAgB,GACtE,IAAe,GAAmB,MAAU,EAAM,YAAY,GAC9D,IAAuB,GAAmB,MAAU,EAAM,oBAAoB,GAE9E,IAAc,QAAc,EAAO,YAAY,GAAG,CAAC,CAAM,CAAC;CAKhE,QAAgB;EACd,IAAI,CAAC,GAAa;EAClB,IAAM,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AAE,CACxF;CAEA,OAAO,kBAAC,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 { browserSpeechEngine } from '../../services/speech';\nimport type { SpeechEngine, SpeechVoiceLike } from '../../services/speech';\nimport { chunkForSpeech, toSpeakableText, type SpeakableLabels } from '../../utils/speakableText';\nimport {\n VOICE_LIST_TIMEOUT_MS,\n isSpeechBlocked,\n languageDisplayName,\n selectVoiceForLocale,\n speechGate,\n speechLangForLocale,\n voiceAvailability,\n type VoiceAvailability,\n} from '../../utils/speechVoices';\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 /** The message currently being spoken, if any. */\n speakingMessageId: string | null;\n isSpeaking: (messageId: string) => boolean;\n /** Speak this message, or stop if it is already the one speaking. */\n toggle: (messageId: string, markdown: string) => void;\n stop: () => void;\n autoSpeakEnabled: boolean;\n setAutoSpeak: (enabled: boolean) => void;\n}\n\nconst INERT_SPEECH: AssistantSpeechContextValue = {\n isSupported: false,\n availability: 'unsupported',\n isBlocked: true,\n disabledReason: null,\n speakingMessageId: null,\n isSpeaking: () => false,\n toggle: () => {},\n stop: () => {},\n autoSpeakEnabled: false,\n setAutoSpeak: () => {},\n};\n\nconst AssistantSpeechContext = createContext<AssistantSpeechContextValue>(INERT_SPEECH);\n\nexport function useAssistantSpeech(): AssistantSpeechContextValue {\n return useContext(AssistantSpeechContext);\n}\n\ninterface Props {\n children: ReactNode;\n /** Panel visibility. Hiding the panel stops the voice. */\n visible?: boolean;\n /** Injectable for a future hosted engine (and for local experiments). */\n engine?: SpeechEngine;\n}\n\nexport const AssistantSpeechProvider: FC<Props> = ({ children, visible = true, engine = browserSpeechEngine }) => {\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 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<(messageId: string, text: string, voices: readonly SpeechVoiceLike[]) => void>(() => {});\n\n const cancelPending = useCallback(() => {\n pendingRef.current?.();\n pendingRef.current = null;\n }, []);\n\n const autoSpeakEnabled = useAssistantStore((state) => state.autoSpeakEnabled);\n const setAutoSpeak = useAssistantStore((state) => state.setAutoSpeak);\n const activeConversationId = useAssistantStore((state) => state.activeConversationId);\n\n const isSupported = useMemo(() => engine.isSupported(), [engine]);\n\n // getVoices() is empty on the first call in Chrome and only fills in when\n // 'voiceschanged' fires; Safari populates it synchronously and may never fire\n // the event. Read eagerly AND subscribe, so both engines end up correct.\n useEffect(() => {\n if (!isSupported) return;\n const sync = () => setVoices(engine.listVoices());\n sync();\n return engine.subscribeVoices(sync);\n }, [engine, isSupported]);\n\n const availability = useMemo(\n () => voiceAvailability(isSupported, voices, locale, voiceProbeSettled),\n [isSupported, voices, locale, voiceProbeSettled]\n );\n const lang = useMemo(() => speechLangForLocale(locale), [locale]);\n /** \"Tamil\", in the reader's own locale — for copy that names what is missing. */\n const languageName = useMemo(() => languageDisplayName(lang, locale), [lang, locale]);\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 }),\n [tr]\n );\n\n const stop = useCallback(() => {\n cancelPending();\n engine.cancel();\n dispatch({ type: 'stop' });\n }, [cancelPending, engine]);\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) => {\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);\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[]) => {\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 gate = speechGate(voiceAvailability(true, known, locale, voiceProbeSettled));\n if (gate === 'block') return;\n if (gate === 'wait-for-voices') {\n waitForVoices(messageId, text);\n return;\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 { voice: selectVoiceForLocale(known, locale), lang },\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, lang, locale, 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) => {\n if (!isSupported) return;\n\n const text = toSpeakableText(markdown, { labels });\n if (!text) return;\n\n speakWith(messageId, text, voices);\n },\n [isSupported, labels, speakWith, voices]\n );\n\n const toggle = useCallback(\n (messageId: string, markdown: string) => {\n if (isSpeakingMessage(playback, messageId)) {\n stop();\n return;\n }\n speak(messageId, markdown);\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 stop();\n }, [activeConversationId, 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 };\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 if (!autoSpeakEnabled || !visible || !isSupported || isSpeechBlocked(availability)) 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);\n });\n }, [autoSpeakEnabled, availability, isSupported, visible]);\n\n const value = useMemo<AssistantSpeechContextValue>(\n () => ({\n isSupported,\n availability,\n isBlocked: isSpeechBlocked(availability),\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 : availability === 'missing-voice'\n ? tr(\n 'healthybowl.assistant.speech.noVoiceForLanguage',\n 'No {{language}} voice is installed on this device. Add one in your device speech or accessibility settings.',\n { language: languageName }\n )\n : null,\n speakingMessageId: playback.status === 'speaking' ? playback.messageId : null,\n isSpeaking: (messageId: string) => isSpeakingMessage(playback, messageId),\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n }),\n [isSupported, availability, languageName, playback, toggle, stop, autoSpeakEnabled, setAutoSpeak, tr]\n );\n\n return <AssistantSpeechContext.Provider value={value}>{children}</AssistantSpeechContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;AA4FA,IAAM,IAAyB,EAA2C;CAZxE,aAAa;CACb,cAAc;CACd,WAAW;CACX,gBAAgB;CAChB,mBAAmB;CACnB,kBAAkB;CAClB,cAAc,CAAC;CACf,YAAY,CAAC;CACb,kBAAkB;CAClB,oBAAoB,CAAC;AAGmD,CAAY;AAEtF,SAAgB,IAAkD;CAChE,OAAO,EAAW,CAAsB;AAC1C;AAUA,IAAa,KAAsC,EAAE,aAAU,aAAU,IAAM,YAAS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kBAAC,EAAuB,UAAxB;EAAwC;EAAQ;CAA0C,CAAA;AACnG"}
@@ -1,154 +1,157 @@
1
1
  import { useTr as e } from "../../../shared/hooks/useTr.js";
2
- import { getSendableAttachments as t } from "../../../utils/assistantAttachments.js";
2
+ import { languageDisplayName as t } from "../../../utils/speechVoices.js";
3
+ import { getSendableAttachments as n } from "../../../utils/assistantAttachments.js";
3
4
  import { useVoiceInput as ee } from "../../../hooks/useVoiceInput.js";
4
- import { useAssistantAttachments as n } from "../../../hooks/useAssistantAttachments.js";
5
- import { AssistantAttachmentButton as r } from "./AssistantAttachmentButton.js";
6
- import { AssistantAttachmentChips as i } from "./AssistantAttachmentChips.js";
7
- import { AssistantVoiceButton as a } from "./AssistantVoiceButton.js";
8
- import { AssistantModeSelector as o } from "./AssistantModeSelector.js";
9
- import { useCallback as s, useLayoutEffect as c, useRef as l, useState as u } from "react";
10
- import { ArrowUp as d, Loader2 as f } from "lucide-react";
11
- import { jsx as p, jsxs as m } from "react/jsx-runtime";
5
+ import { useAssistantAttachments as r } from "../../../hooks/useAssistantAttachments.js";
6
+ import { AssistantAttachmentButton as i } from "./AssistantAttachmentButton.js";
7
+ import { AssistantAttachmentChips as a } from "./AssistantAttachmentChips.js";
8
+ import { AssistantVoiceButton as o } from "./AssistantVoiceButton.js";
9
+ import { AssistantModeSelector as s } from "./AssistantModeSelector.js";
10
+ import { useCallback as c, useLayoutEffect as l, useRef as u, useState as d } from "react";
11
+ import { useI18n as f } from "@burdenoff/fe-libs/shared/providers/shell/I18nProvider";
12
+ import { ArrowUp as p, Loader2 as m } from "lucide-react";
13
+ import { jsx as h, jsxs as g } from "react/jsx-runtime";
12
14
  //#region src/components/assistant/composer/AssistantComposer.tsx
13
- var h = 200, g = ({ onSend: g, disabled: _ = !1, placeholder: v, mode: y, availableModes: b, onModeChange: x }) => {
14
- let S = e(), C = l(null), [w, T] = u(""), [E, D] = u(!1), O = l(0), { attachments: k, isBusy: A, sendBlocker: j, rejection: M, addFiles: N, remove: P, retry: F, clear: I, clearRejection: L, canAddMore: R } = n(), z = ee({ onFinalize: s((e) => {
15
- T((t) => t ? `${t.replace(/\s+$/, "")} ${e}` : e);
16
- }, []) }), B = v ?? S("healthybowl.assistant.composer.placeholder", "Ask HealthyBowl anything…"), V = w.trim(), H = t(k), U = k.filter((e) => e.status === "error"), W = (V.length > 0 || H.length > 0) && !_ && j === null;
17
- c(() => {
18
- let e = C.current;
19
- e && (e.style.height = "auto", e.style.height = `${Math.min(e.scrollHeight, h)}px`);
20
- }, [w]);
21
- let G = s(() => {
22
- W && (z.isListening && z.stop(), g(w.trim(), H), T(""), I());
15
+ var _ = 200, v = ({ onSend: v, disabled: y = !1, placeholder: b, mode: x, availableModes: S, onModeChange: C }) => {
16
+ let w = e(), { locale: T } = f(), E = u(null), [D, O] = d(""), [k, A] = d(!1), j = u(0), { attachments: M, isBusy: N, sendBlocker: P, rejection: F, addFiles: I, remove: L, retry: R, clear: z, clearRejection: B, canAddMore: V } = r(), H = ee({ onFinalize: c((e) => {
17
+ O((t) => t ? `${t.replace(/\s+$/, "")} ${e}` : e);
18
+ }, []) }), U = b ?? w("healthybowl.assistant.composer.placeholder", "Ask HealthyBowl anything…"), W = D.trim(), G = n(M), K = M.filter((e) => e.status === "error"), q = (W.length > 0 || G.length > 0) && !y && P === null;
19
+ l(() => {
20
+ let e = E.current;
21
+ e && (e.style.height = "auto", e.style.height = `${Math.min(e.scrollHeight, _)}px`);
22
+ }, [D]);
23
+ let J = c(() => {
24
+ q && (H.isListening && H.stop(), v(D.trim(), G), O(""), z());
23
25
  }, [
24
- W,
25
- g,
26
- w,
27
- H,
28
- I,
29
- z
30
- ]), K = s((e) => {
31
- e.key === "Enter" && !e.shiftKey && (e.preventDefault(), G());
32
- }, [G]), q = s((e) => {
26
+ q,
27
+ v,
28
+ D,
29
+ G,
30
+ z,
31
+ H
32
+ ]), Y = c((e) => {
33
+ e.key === "Enter" && !e.shiftKey && (e.preventDefault(), J());
34
+ }, [J]), X = c((e) => {
33
35
  let t = Array.from(e.clipboardData?.files ?? []);
34
- t.length !== 0 && (e.preventDefault(), N(t));
35
- }, [N]), J = s((e) => {
36
- Array.from(e.dataTransfer?.types ?? []).includes("Files") && (O.current += 1, D(!0));
37
- }, []), Y = s(() => {
38
- O.current = Math.max(0, O.current - 1), O.current === 0 && D(!1);
39
- }, []), X = s((e) => {
36
+ t.length !== 0 && (e.preventDefault(), I(t));
37
+ }, [I]), Z = c((e) => {
38
+ Array.from(e.dataTransfer?.types ?? []).includes("Files") && (j.current += 1, A(!0));
39
+ }, []), Q = c(() => {
40
+ j.current = Math.max(0, j.current - 1), j.current === 0 && A(!1);
41
+ }, []), te = c((e) => {
40
42
  Array.from(e.dataTransfer?.types ?? []).includes("Files") && e.preventDefault();
41
- }, []), Z = s((e) => {
42
- e.preventDefault(), O.current = 0, D(!1), N(e.dataTransfer?.files ?? null);
43
- }, [N]), Q = (e) => {
43
+ }, []), ne = c((e) => {
44
+ e.preventDefault(), j.current = 0, A(!1), I(e.dataTransfer?.files ?? null);
45
+ }, [I]), re = (e) => {
44
46
  switch (e) {
45
- case "too-many": return S("healthybowl.assistant.attachments.tooMany", "You can attach up to {{max}} files per message.", { max: 5 });
46
- case "too-large": return S("healthybowl.assistant.attachments.tooLarge", "That file is larger than 10 MB.");
47
- case "empty": return S("healthybowl.assistant.attachments.empty", "That file is empty.");
48
- case "unreadable": return S("healthybowl.assistant.attachments.unreadable", "That file could not be read.");
49
- case "unsupported-image": return S("healthybowl.assistant.attachments.unsupportedImage", "This device can't read that image format, so it can't be resized to send. Save it as JPEG and try again.");
47
+ case "too-many": return w("healthybowl.assistant.attachments.tooMany", "You can attach up to {{max}} files per message.", { max: 5 });
48
+ case "too-large": return w("healthybowl.assistant.attachments.tooLarge", "That file is larger than 10 MB.");
49
+ case "empty": return w("healthybowl.assistant.attachments.empty", "That file is empty.");
50
+ case "unreadable": return w("healthybowl.assistant.attachments.unreadable", "That file could not be read.");
51
+ case "unsupported-image": return w("healthybowl.assistant.attachments.unsupportedImage", "This device can't read that image format, so it can't be resized to send. Save it as JPEG and try again.");
50
52
  }
51
53
  }, $ = (() => {
52
- switch (z.error) {
53
- case "not-allowed": return S("healthybowl.assistant.voice.denied", "Microphone access is blocked. Allow it in your browser settings to dictate.");
54
- case "audio-capture": return S("healthybowl.assistant.voice.noMic", "No microphone was found.");
55
- case "network": return S("healthybowl.assistant.voice.network", "Speech recognition is offline right now.");
56
- case "unknown": return S("healthybowl.assistant.voice.failed", "Dictation stopped unexpectedly.");
54
+ switch (H.error) {
55
+ case "not-allowed": return w("healthybowl.assistant.voice.denied", "Microphone access is blocked. Allow it in your browser settings to dictate.");
56
+ case "audio-capture": return w("healthybowl.assistant.voice.noMic", "No microphone was found.");
57
+ case "network": return w("healthybowl.assistant.voice.network", "Speech recognition is offline right now.");
58
+ case "language-not-supported": return w("healthybowl.assistant.voice.languageNotSupported", "This browser cannot recognise spoken {{language}}. Try a different browser, or type instead.", { language: t(H.language, T) });
59
+ case "unknown": return w("healthybowl.assistant.voice.failed", "Dictation stopped unexpectedly.");
57
60
  default: return null;
58
61
  }
59
62
  })();
60
- return /* @__PURE__ */ m("div", {
63
+ return /* @__PURE__ */ g("div", {
61
64
  className: "flex-shrink-0 px-3 pb-3 pt-1.5",
62
- children: [/* @__PURE__ */ m("div", {
63
- onDragEnter: J,
64
- onDragLeave: Y,
65
- onDragOver: X,
66
- onDrop: Z,
67
- className: `rounded-2xl border p-2 shadow-sm transition-colors focus-within:border-action-primary-bg focus-within:ring-2 focus-within:ring-action-primary-bg/15 ${E ? "border-action-primary-bg border-dashed bg-action-primary-bg/5" : "border-border-default bg-bg-sunken"}`,
65
+ children: [/* @__PURE__ */ g("div", {
66
+ onDragEnter: Z,
67
+ onDragLeave: Q,
68
+ onDragOver: te,
69
+ onDrop: ne,
70
+ className: `rounded-2xl border p-2 shadow-sm transition-colors focus-within:border-action-primary-bg focus-within:ring-2 focus-within:ring-action-primary-bg/15 ${k ? "border-action-primary-bg border-dashed bg-action-primary-bg/5" : "border-border-default bg-bg-sunken"}`,
68
71
  "data-testid": "assistant-composer",
69
72
  children: [
70
- /* @__PURE__ */ p(i, {
71
- attachments: k,
72
- onRemove: P,
73
- onRetry: F,
74
- disabled: _
73
+ /* @__PURE__ */ h(a, {
74
+ attachments: M,
75
+ onRemove: L,
76
+ onRetry: R,
77
+ disabled: y
75
78
  }),
76
- /* @__PURE__ */ m("div", {
79
+ /* @__PURE__ */ g("div", {
77
80
  className: "flex items-end gap-2",
78
81
  children: [
79
- /* @__PURE__ */ p(r, {
80
- onFiles: N,
81
- canAddMore: R,
82
- disabled: _
82
+ /* @__PURE__ */ h(i, {
83
+ onFiles: I,
84
+ canAddMore: V,
85
+ disabled: y
83
86
  }),
84
- /* @__PURE__ */ p("textarea", {
85
- ref: C,
86
- value: w,
87
- onChange: (e) => T(e.target.value),
88
- onKeyDown: K,
89
- onPaste: q,
90
- disabled: _,
91
- placeholder: E ? S("healthybowl.assistant.composer.dropHere", "Drop files to attach") : B,
87
+ /* @__PURE__ */ h("textarea", {
88
+ ref: E,
89
+ value: D,
90
+ onChange: (e) => O(e.target.value),
91
+ onKeyDown: Y,
92
+ onPaste: X,
93
+ disabled: y,
94
+ placeholder: k ? w("healthybowl.assistant.composer.dropHere", "Drop files to attach") : U,
92
95
  rows: 1,
93
96
  className: "min-h-[36px] flex-1 resize-none self-center bg-transparent px-1 py-2 text-[15px] leading-relaxed text-text-primary placeholder:text-text-muted focus:outline-none disabled:opacity-50",
94
- "aria-label": S("healthybowl.assistant.chatInput.ariaLabel", "Message input"),
97
+ "aria-label": w("healthybowl.assistant.chatInput.ariaLabel", "Message input"),
95
98
  "data-testid": "assistant-input"
96
99
  }),
97
- z.isSupported && /* @__PURE__ */ p(a, {
98
- isListening: z.isListening,
99
- onToggle: z.toggle,
100
- disabled: _
100
+ H.isSupported && /* @__PURE__ */ h(o, {
101
+ isListening: H.isListening,
102
+ onToggle: H.toggle,
103
+ disabled: y
101
104
  }),
102
- /* @__PURE__ */ p("button", {
105
+ /* @__PURE__ */ h("button", {
103
106
  type: "button",
104
- onClick: G,
105
- disabled: !W,
106
- className: `flex size-9 flex-shrink-0 items-center justify-center rounded-full shadow-sm transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong ${W ? "bg-action-primary-bg text-action-primary-text hover:scale-105 hover:bg-action-primary-bg-hover" : "bg-bg-elevated text-text-muted"}`,
107
- "aria-label": S("healthybowl.assistant.chatInput.send", "Send message"),
107
+ onClick: J,
108
+ disabled: !q,
109
+ className: `flex size-9 flex-shrink-0 items-center justify-center rounded-full shadow-sm transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong ${q ? "bg-action-primary-bg text-action-primary-text hover:scale-105 hover:bg-action-primary-bg-hover" : "bg-bg-elevated text-text-muted"}`,
110
+ "aria-label": w("healthybowl.assistant.chatInput.send", "Send message"),
108
111
  "data-testid": "assistant-send",
109
- children: _ || A ? /* @__PURE__ */ p(f, { className: "size-4 animate-spin" }) : /* @__PURE__ */ p(d, { className: "size-4" })
112
+ children: y || N ? /* @__PURE__ */ h(m, { className: "size-4 animate-spin" }) : /* @__PURE__ */ h(p, { className: "size-4" })
110
113
  })
111
114
  ]
112
115
  }),
113
- b.length > 1 && /* @__PURE__ */ p("div", {
116
+ S.length > 1 && /* @__PURE__ */ h("div", {
114
117
  className: "mt-2 px-0.5",
115
- children: /* @__PURE__ */ p(o, {
116
- mode: y,
117
- availableModes: b,
118
- onModeChange: x,
119
- disabled: _
118
+ children: /* @__PURE__ */ h(s, {
119
+ mode: x,
120
+ availableModes: S,
121
+ onModeChange: C,
122
+ disabled: y
120
123
  })
121
124
  })
122
125
  ]
123
- }), /* @__PURE__ */ p("div", {
126
+ }), /* @__PURE__ */ h("div", {
124
127
  className: "mt-1.5 px-1 text-center text-[11px]",
125
128
  "aria-live": "polite",
126
- children: z.isListening ? /* @__PURE__ */ m("p", {
129
+ children: H.isListening ? /* @__PURE__ */ g("p", {
127
130
  className: "text-status-error-text",
128
131
  "data-testid": "assistant-voice-status",
129
- children: [/* @__PURE__ */ p("span", { className: "mr-1 inline-block size-1.5 rounded-full bg-status-error-text align-middle motion-safe:animate-pulse" }), z.interim || S("healthybowl.assistant.voice.listening", "Listening… speak now, tap the square to stop")]
130
- }) : $ ? /* @__PURE__ */ p("p", {
132
+ children: [/* @__PURE__ */ h("span", { className: "mr-1 inline-block size-1.5 rounded-full bg-status-error-text align-middle motion-safe:animate-pulse" }), H.interim || w("healthybowl.assistant.voice.listening", "Listening… speak now, tap the square to stop")]
133
+ }) : $ ? /* @__PURE__ */ h("p", {
131
134
  className: "text-status-error-text",
132
135
  "data-testid": "assistant-voice-error",
133
136
  children: $
134
- }) : M ? /* @__PURE__ */ p("button", {
137
+ }) : F ? /* @__PURE__ */ h("button", {
135
138
  type: "button",
136
- onClick: L,
139
+ onClick: B,
137
140
  className: "text-status-error-text underline-offset-2 hover:underline",
138
141
  "data-testid": "assistant-attachment-rejection",
139
- children: Q(M)
140
- }) : j === "failed" ? /* @__PURE__ */ p("p", {
142
+ children: re(F)
143
+ }) : P === "failed" ? /* @__PURE__ */ h("p", {
141
144
  className: "text-status-error-text",
142
145
  "data-testid": "assistant-attachment-blocked",
143
- children: U.length === 1 ? S("healthybowl.assistant.attachments.blockedOne", "{{name}} didn't upload. Retry or remove it before sending.", { name: U[0].filename }) : S("healthybowl.assistant.attachments.blockedMany", "{{count}} attachments didn't upload. Retry or remove them before sending.", { count: U.length })
144
- }) : /* @__PURE__ */ p("p", {
146
+ children: K.length === 1 ? w("healthybowl.assistant.attachments.blockedOne", "{{name}} didn't upload. Retry or remove it before sending.", { name: K[0].filename }) : w("healthybowl.assistant.attachments.blockedMany", "{{count}} attachments didn't upload. Retry or remove them before sending.", { count: K.length })
147
+ }) : /* @__PURE__ */ h("p", {
145
148
  className: "text-text-muted",
146
- children: S("healthybowl.assistant.composer.hint", "Enter to send · Shift+Enter for newline · drag or paste files to attach")
149
+ children: w("healthybowl.assistant.composer.hint", "Enter to send · Shift+Enter for newline · drag or paste files to attach")
147
150
  })
148
151
  })]
149
152
  });
150
153
  };
151
154
  //#endregion
152
- export { g as AssistantComposer };
155
+ export { v as AssistantComposer };
153
156
 
154
157
  //# sourceMappingURL=AssistantComposer.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantComposer.js","names":[],"sources":["../../../../src/components/assistant/composer/AssistantComposer.tsx"],"sourcesContent":["import {\n useCallback,\n useLayoutEffect,\n useRef,\n useState,\n type ClipboardEvent,\n type DragEvent,\n type FC,\n type KeyboardEvent,\n} from 'react';\nimport { ArrowUp, Loader2 } from 'lucide-react';\nimport type { AssistantMode, AssistantModeConfig } from '@/types/assistant';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { useVoiceInput } from '@/hooks/useVoiceInput';\nimport { useAssistantAttachments } from '@/hooks/useAssistantAttachments';\nimport {\n MAX_ATTACHMENTS,\n getSendableAttachments,\n type AssistantAttachment,\n type AttachmentRejection,\n} from '@/utils/assistantAttachments';\nimport { AssistantAttachmentButton } from './AssistantAttachmentButton';\nimport { AssistantAttachmentChips } from './AssistantAttachmentChips';\nimport { AssistantVoiceButton } from './AssistantVoiceButton';\nimport { AssistantModeSelector } from './AssistantModeSelector';\n\ninterface Props {\n /**\n * Send the message. `attachments` are already uploaded and ready; the chat\n * area folds them into the prompt and onto the user bubble.\n */\n onSend: (message: string, attachments: AssistantAttachment[]) => void;\n /** True while a turn is in-flight (assistant busy) — disables send + shows the spinner. */\n disabled?: boolean;\n placeholder?: string;\n mode: AssistantMode;\n /** Role-filtered list of modes the user may pick. */\n availableModes: AssistantModeConfig[];\n onModeChange: (mode: AssistantMode) => void;\n}\n\nconst MAX_TEXTAREA_HEIGHT = 200;\n\n/**\n * AssistantComposer — the v2 input surface (per the ai-assistant-v2 mockups).\n *\n * A rounded card with, on the input row: a leading circular \"+\" attach control,\n * an auto-growing textarea, a microphone, and a prominent filled forest-green\n * circular send button. BELOW the input sit the mode pills (\"Ask\" active-green /\n * \"Take action\" outline); ABOVE it, chips for any pending attachments.\n *\n * Multimodal input (Workstreams 2–3) arrives through three converging paths —\n * the attach button, drag-and-drop onto the card, and paste (a screenshot from\n * the clipboard is the single most common way a user shares one) — plus voice\n * dictation, which appends recognised speech to the draft so it can still be\n * edited before sending.\n *\n * Fully controlled (React state for the text) with auto-grow via a layout\n * effect. Enter sends, Shift+Enter inserts a newline.\n */\nexport const AssistantComposer: FC<Props> = ({\n onSend,\n disabled = false,\n placeholder,\n mode,\n availableModes,\n onModeChange,\n}) => {\n const tr = useTr();\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const [text, setText] = useState('');\n const [isDraggingOver, setIsDraggingOver] = useState(false);\n // Nested drag-enter/leave pairs fire for every child element; count them so\n // the highlight survives dragging across the textarea and buttons.\n const dragDepthRef = useRef(0);\n\n const {\n attachments,\n isBusy: attachmentsBusy,\n sendBlocker,\n rejection,\n addFiles,\n remove,\n retry,\n clear,\n clearRejection,\n canAddMore,\n } = useAssistantAttachments();\n\n const appendTranscript = useCallback((phrase: string) => {\n setText((current) => (current ? `${current.replace(/\\s+$/, '')} ${phrase}` : phrase));\n }, []);\n\n const voice = useVoiceInput({ onFinalize: appendTranscript });\n\n const resolvedPlaceholder =\n placeholder ?? tr('healthybowl.assistant.composer.placeholder', 'Ask HealthyBowl anything…');\n const trimmed = text.trim();\n // Exactly what the model will be given — see `getSendableAttachments`.\n const sendableAttachments = getSendableAttachments(attachments);\n const failedAttachments = attachments.filter((attachment) => attachment.status === 'error');\n // A message may be attachments-only (\"what's wrong with this leaf?\" is often\n // just the photo), but never sends while an upload is in flight OR has failed:\n // `sendBlocker` covers both. Gating on the blocker rather than on\n // `attachmentsBusy` is what stops a turn going out that quietly omits a file\n // the user can still see attached — the chips are cleared by `clear()` below,\n // so the evidence would disappear at the same instant.\n const canSend = (trimmed.length > 0 || sendableAttachments.length > 0) && !disabled && sendBlocker === null;\n\n // Auto-grow the textarea to fit its content (capped), re-measured after every\n // value change so the card breathes as the user types.\n useLayoutEffect(() => {\n const textarea = textareaRef.current;\n if (!textarea) return;\n textarea.style.height = 'auto';\n textarea.style.height = `${Math.min(textarea.scrollHeight, MAX_TEXTAREA_HEIGHT)}px`;\n }, [text]);\n\n const handleSend = useCallback(() => {\n if (!canSend) return;\n // Dictation left running into a send would keep appending to a cleared\n // draft; stop it so the mic state matches what the user sees.\n if (voice.isListening) voice.stop();\n onSend(text.trim(), sendableAttachments);\n setText('');\n clear();\n }, [canSend, onSend, text, sendableAttachments, clear, voice]);\n\n const handleKeyDown = useCallback(\n (event: KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n handleSend();\n }\n },\n [handleSend]\n );\n\n const handlePaste = useCallback(\n (event: ClipboardEvent<HTMLTextAreaElement>) => {\n const files = Array.from(event.clipboardData?.files ?? []);\n if (files.length === 0) return;\n // Only claim the paste when it carried files; a normal text paste (which\n // also exposes an empty `files`) must still land in the textarea.\n event.preventDefault();\n addFiles(files);\n },\n [addFiles]\n );\n\n const handleDragEnter = useCallback((event: DragEvent<HTMLDivElement>) => {\n if (!Array.from(event.dataTransfer?.types ?? []).includes('Files')) return;\n dragDepthRef.current += 1;\n setIsDraggingOver(true);\n }, []);\n\n const handleDragLeave = useCallback(() => {\n dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);\n if (dragDepthRef.current === 0) setIsDraggingOver(false);\n }, []);\n\n const handleDragOver = useCallback((event: DragEvent<HTMLDivElement>) => {\n if (!Array.from(event.dataTransfer?.types ?? []).includes('Files')) return;\n // Required for a drop to fire at all, and stops the browser from navigating\n // away to the dropped file.\n event.preventDefault();\n }, []);\n\n const handleDrop = useCallback(\n (event: DragEvent<HTMLDivElement>) => {\n event.preventDefault();\n dragDepthRef.current = 0;\n setIsDraggingOver(false);\n addFiles(event.dataTransfer?.files ?? null);\n },\n [addFiles]\n );\n\n const rejectionMessage = (reason: AttachmentRejection): string => {\n switch (reason) {\n case 'too-many':\n return tr('healthybowl.assistant.attachments.tooMany', 'You can attach up to {{max}} files per message.', {\n max: MAX_ATTACHMENTS,\n });\n case 'too-large':\n return tr('healthybowl.assistant.attachments.tooLarge', 'That file is larger than 10 MB.');\n case 'empty':\n return tr('healthybowl.assistant.attachments.empty', 'That file is empty.');\n case 'unreadable':\n return tr('healthybowl.assistant.attachments.unreadable', 'That file could not be read.');\n case 'unsupported-image':\n return tr(\n 'healthybowl.assistant.attachments.unsupportedImage',\n \"This device can't read that image format, so it can't be resized to send. Save it as JPEG and try again.\"\n );\n }\n };\n\n const voiceErrorMessage = (): string | null => {\n switch (voice.error) {\n case 'not-allowed':\n return tr(\n 'healthybowl.assistant.voice.denied',\n 'Microphone access is blocked. Allow it in your browser settings to dictate.'\n );\n case 'audio-capture':\n return tr('healthybowl.assistant.voice.noMic', 'No microphone was found.');\n case 'network':\n return tr('healthybowl.assistant.voice.network', 'Speech recognition is offline right now.');\n case 'unknown':\n return tr('healthybowl.assistant.voice.failed', 'Dictation stopped unexpectedly.');\n default:\n return null;\n }\n };\n\n const voiceError = voiceErrorMessage();\n\n return (\n <div className=\"flex-shrink-0 px-3 pb-3 pt-1.5\">\n <div\n onDragEnter={handleDragEnter}\n onDragLeave={handleDragLeave}\n onDragOver={handleDragOver}\n onDrop={handleDrop}\n className={`rounded-2xl border p-2 shadow-sm transition-colors focus-within:border-action-primary-bg focus-within:ring-2 focus-within:ring-action-primary-bg/15 ${\n isDraggingOver\n ? 'border-action-primary-bg border-dashed bg-action-primary-bg/5'\n : 'border-border-default bg-bg-sunken'\n }`}\n data-testid=\"assistant-composer\"\n >\n <AssistantAttachmentChips attachments={attachments} onRemove={remove} onRetry={retry} disabled={disabled} />\n\n {/* Input row: attach · textarea · mic · send */}\n <div className=\"flex items-end gap-2\">\n <AssistantAttachmentButton onFiles={addFiles} canAddMore={canAddMore} disabled={disabled} />\n\n <textarea\n ref={textareaRef}\n value={text}\n onChange={(event) => setText(event.target.value)}\n onKeyDown={handleKeyDown}\n onPaste={handlePaste}\n disabled={disabled}\n placeholder={\n isDraggingOver\n ? tr('healthybowl.assistant.composer.dropHere', 'Drop files to attach')\n : resolvedPlaceholder\n }\n rows={1}\n className=\"min-h-[36px] flex-1 resize-none self-center bg-transparent px-1 py-2 text-[15px] leading-relaxed text-text-primary placeholder:text-text-muted focus:outline-none disabled:opacity-50\"\n aria-label={tr('healthybowl.assistant.chatInput.ariaLabel', 'Message input')}\n data-testid=\"assistant-input\"\n />\n\n {voice.isSupported && (\n <AssistantVoiceButton isListening={voice.isListening} onToggle={voice.toggle} disabled={disabled} />\n )}\n\n <button\n type=\"button\"\n onClick={handleSend}\n disabled={!canSend}\n className={`flex size-9 flex-shrink-0 items-center justify-center rounded-full shadow-sm transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong ${\n canSend\n ? 'bg-action-primary-bg text-action-primary-text hover:scale-105 hover:bg-action-primary-bg-hover'\n : 'bg-bg-elevated text-text-muted'\n }`}\n aria-label={tr('healthybowl.assistant.chatInput.send', 'Send message')}\n data-testid=\"assistant-send\"\n >\n {disabled || attachmentsBusy ? <Loader2 className=\"size-4 animate-spin\" /> : <ArrowUp className=\"size-4\" />}\n </button>\n </div>\n\n {/* Mode pills */}\n {availableModes.length > 1 && (\n <div className=\"mt-2 px-0.5\">\n <AssistantModeSelector\n mode={mode}\n availableModes={availableModes}\n onModeChange={onModeChange}\n disabled={disabled}\n />\n </div>\n )}\n </div>\n\n {/* One status line under the card: live dictation > voice error >\n attachment rejection > failed upload > the keyboard hint. Announced\n politely so a screen-reader user hears dictation land without losing\n their place.\n\n The failed-upload line ranks below `rejection` (which is transient and\n describes the file the user just picked) but above the hint, because a\n disabled send button with no stated reason is the thing this whole\n change exists to avoid. */}\n <div className=\"mt-1.5 px-1 text-center text-[11px]\" aria-live=\"polite\">\n {voice.isListening ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-voice-status\">\n <span className=\"mr-1 inline-block size-1.5 rounded-full bg-status-error-text align-middle motion-safe:animate-pulse\" />\n {voice.interim ||\n tr('healthybowl.assistant.voice.listening', 'Listening… speak now, tap the square to stop')}\n </p>\n ) : voiceError ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-voice-error\">\n {voiceError}\n </p>\n ) : rejection ? (\n <button\n type=\"button\"\n onClick={clearRejection}\n className=\"text-status-error-text underline-offset-2 hover:underline\"\n data-testid=\"assistant-attachment-rejection\"\n >\n {rejectionMessage(rejection)}\n </button>\n ) : sendBlocker === 'failed' ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-attachment-blocked\">\n {failedAttachments.length === 1\n ? tr(\n 'healthybowl.assistant.attachments.blockedOne',\n \"{{name}} didn't upload. Retry or remove it before sending.\",\n { name: failedAttachments[0].filename }\n )\n : tr(\n 'healthybowl.assistant.attachments.blockedMany',\n \"{{count}} attachments didn't upload. Retry or remove them before sending.\",\n { count: failedAttachments.length }\n )}\n </p>\n ) : (\n <p className=\"text-text-muted\">\n {tr(\n 'healthybowl.assistant.composer.hint',\n 'Enter to send · Shift+Enter for newline · drag or paste files to attach'\n )}\n </p>\n )}\n </div>\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;AAyCA,IAAM,IAAsB,KAmBf,KAAgC,EAC3C,WACA,cAAW,IACX,gBACA,SACA,mBACA,sBACI;CACJ,IAAM,IAAK,EAAM,GACX,IAAc,EAA4B,IAAI,GAC9C,CAAC,GAAM,KAAW,EAAS,EAAE,GAC7B,CAAC,GAAgB,KAAqB,EAAS,EAAK,GAGpD,IAAe,EAAO,CAAC,GAEvB,EACJ,gBACA,QAAQ,GACR,gBACA,cACA,aACA,WACA,UACA,UACA,mBACA,kBACE,EAAwB,GAMtB,IAAQ,GAAc,EAAE,YAJL,GAAa,MAAmB;EACvD,GAAS,MAAa,IAAU,GAAG,EAAQ,QAAQ,QAAQ,EAAE,EAAE,GAAG,MAAW,CAAO;CACtF,GAAG,CAAC,CAEsC,EAAiB,CAAC,GAEtD,IACJ,KAAe,EAAG,8CAA8C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ACN,WAAU;OACV,cAAY,EAAG,6CAA6C,eAAe;OAC3E,eAAY;MACb,CAAA;MAEA,EAAM,eACL,kBAAC,GAAD;OAAsB,aAAa,EAAM;OAAa,UAAU,EAAM;OAAkB;MAAW,CAAA;MAGrG,kBAAC,UAAD;OACE,MAAK;OACL,SAAS;OACT,UAAU,CAAC;OACX,WAAW,wKACT,IACI,mGACA;OAEN,cAAY,EAAG,wCAAwC,cAAc;OACrE,eAAY;iBAEX,KAAY,IAAkB,kBAAC,GAAD,EAAS,WAAU,sBAAuB,CAAA,IAAI,kBAAC,GAAD,EAAS,WAAU,SAAU,CAAA;MACpG,CAAA;KACL;;IAGJ,EAAe,SAAS,KACvB,kBAAC,OAAD;KAAK,WAAU;eACb,kBAAC,GAAD;MACQ;MACU;MACF;MACJ;KACX,CAAA;IACE,CAAA;GAEJ;MAWL,kBAAC,OAAD;GAAK,WAAU;GAAsC,aAAU;aAC5D,EAAM,cACL,kBAAC,KAAD;IAAG,WAAU;IAAyB,eAAY;cAAlD,CACE,kBAAC,QAAD,EAAM,WAAU,sGAAuG,CAAA,GACtH,EAAM,WACL,EAAG,yCAAyC,8CAA8C,CAC3F;QACD,IACF,kBAAC,KAAD;IAAG,WAAU;IAAyB,eAAY;cAC/C;GACA,CAAA,IACD,IACF,kBAAC,UAAD;IACE,MAAK;IACL,SAAS;IACT,WAAU;IACV,eAAY;cAEX,EAAiB,CAAS;GACrB,CAAA,IACN,MAAgB,WAClB,kBAAC,KAAD;IAAG,WAAU;IAAyB,eAAY;cAC/C,EAAkB,WAAW,IAC1B,EACE,gDACA,8DACA,EAAE,MAAM,EAAkB,GAAG,SAAS,CACxC,IACA,EACE,iDACA,6EACA,EAAE,OAAO,EAAkB,OAAO,CACpC;GACH,CAAA,IAEH,kBAAC,KAAD;IAAG,WAAU;cACV,EACC,uCACA,yEACF;GACC,CAAA;EAEF,CAAA,CACF;;AAET"}
1
+ {"version":3,"file":"AssistantComposer.js","names":[],"sources":["../../../../src/components/assistant/composer/AssistantComposer.tsx"],"sourcesContent":["import {\n useCallback,\n useLayoutEffect,\n useRef,\n useState,\n type ClipboardEvent,\n type DragEvent,\n type FC,\n type KeyboardEvent,\n} from 'react';\nimport { ArrowUp, Loader2 } from 'lucide-react';\nimport type { AssistantMode, AssistantModeConfig } from '@/types/assistant';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { languageDisplayName } from '@/utils/speechVoices';\nimport { useVoiceInput } from '@/hooks/useVoiceInput';\nimport { useAssistantAttachments } from '@/hooks/useAssistantAttachments';\nimport {\n MAX_ATTACHMENTS,\n getSendableAttachments,\n type AssistantAttachment,\n type AttachmentRejection,\n} from '@/utils/assistantAttachments';\nimport { AssistantAttachmentButton } from './AssistantAttachmentButton';\nimport { AssistantAttachmentChips } from './AssistantAttachmentChips';\nimport { AssistantVoiceButton } from './AssistantVoiceButton';\nimport { AssistantModeSelector } from './AssistantModeSelector';\n\ninterface Props {\n /**\n * Send the message. `attachments` are already uploaded and ready; the chat\n * area folds them into the prompt and onto the user bubble.\n */\n onSend: (message: string, attachments: AssistantAttachment[]) => void;\n /** True while a turn is in-flight (assistant busy) — disables send + shows the spinner. */\n disabled?: boolean;\n placeholder?: string;\n mode: AssistantMode;\n /** Role-filtered list of modes the user may pick. */\n availableModes: AssistantModeConfig[];\n onModeChange: (mode: AssistantMode) => void;\n}\n\nconst MAX_TEXTAREA_HEIGHT = 200;\n\n/**\n * AssistantComposer — the v2 input surface (per the ai-assistant-v2 mockups).\n *\n * A rounded card with, on the input row: a leading circular \"+\" attach control,\n * an auto-growing textarea, a microphone, and a prominent filled forest-green\n * circular send button. BELOW the input sit the mode pills (\"Ask\" active-green /\n * \"Take action\" outline); ABOVE it, chips for any pending attachments.\n *\n * Multimodal input (Workstreams 2–3) arrives through three converging paths —\n * the attach button, drag-and-drop onto the card, and paste (a screenshot from\n * the clipboard is the single most common way a user shares one) — plus voice\n * dictation, which appends recognised speech to the draft so it can still be\n * edited before sending.\n *\n * Fully controlled (React state for the text) with auto-grow via a layout\n * effect. Enter sends, Shift+Enter inserts a newline.\n */\nexport const AssistantComposer: FC<Props> = ({\n onSend,\n disabled = false,\n placeholder,\n mode,\n availableModes,\n onModeChange,\n}) => {\n const tr = useTr();\n const { locale } = useI18n();\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const [text, setText] = useState('');\n const [isDraggingOver, setIsDraggingOver] = useState(false);\n // Nested drag-enter/leave pairs fire for every child element; count them so\n // the highlight survives dragging across the textarea and buttons.\n const dragDepthRef = useRef(0);\n\n const {\n attachments,\n isBusy: attachmentsBusy,\n sendBlocker,\n rejection,\n addFiles,\n remove,\n retry,\n clear,\n clearRejection,\n canAddMore,\n } = useAssistantAttachments();\n\n const appendTranscript = useCallback((phrase: string) => {\n setText((current) => (current ? `${current.replace(/\\s+$/, '')} ${phrase}` : phrase));\n }, []);\n\n const voice = useVoiceInput({ onFinalize: appendTranscript });\n\n const resolvedPlaceholder =\n placeholder ?? tr('healthybowl.assistant.composer.placeholder', 'Ask HealthyBowl anything…');\n const trimmed = text.trim();\n // Exactly what the model will be given — see `getSendableAttachments`.\n const sendableAttachments = getSendableAttachments(attachments);\n const failedAttachments = attachments.filter((attachment) => attachment.status === 'error');\n // A message may be attachments-only (\"what's wrong with this leaf?\" is often\n // just the photo), but never sends while an upload is in flight OR has failed:\n // `sendBlocker` covers both. Gating on the blocker rather than on\n // `attachmentsBusy` is what stops a turn going out that quietly omits a file\n // the user can still see attached — the chips are cleared by `clear()` below,\n // so the evidence would disappear at the same instant.\n const canSend = (trimmed.length > 0 || sendableAttachments.length > 0) && !disabled && sendBlocker === null;\n\n // Auto-grow the textarea to fit its content (capped), re-measured after every\n // value change so the card breathes as the user types.\n useLayoutEffect(() => {\n const textarea = textareaRef.current;\n if (!textarea) return;\n textarea.style.height = 'auto';\n textarea.style.height = `${Math.min(textarea.scrollHeight, MAX_TEXTAREA_HEIGHT)}px`;\n }, [text]);\n\n const handleSend = useCallback(() => {\n if (!canSend) return;\n // Dictation left running into a send would keep appending to a cleared\n // draft; stop it so the mic state matches what the user sees.\n if (voice.isListening) voice.stop();\n onSend(text.trim(), sendableAttachments);\n setText('');\n clear();\n }, [canSend, onSend, text, sendableAttachments, clear, voice]);\n\n const handleKeyDown = useCallback(\n (event: KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n handleSend();\n }\n },\n [handleSend]\n );\n\n const handlePaste = useCallback(\n (event: ClipboardEvent<HTMLTextAreaElement>) => {\n const files = Array.from(event.clipboardData?.files ?? []);\n if (files.length === 0) return;\n // Only claim the paste when it carried files; a normal text paste (which\n // also exposes an empty `files`) must still land in the textarea.\n event.preventDefault();\n addFiles(files);\n },\n [addFiles]\n );\n\n const handleDragEnter = useCallback((event: DragEvent<HTMLDivElement>) => {\n if (!Array.from(event.dataTransfer?.types ?? []).includes('Files')) return;\n dragDepthRef.current += 1;\n setIsDraggingOver(true);\n }, []);\n\n const handleDragLeave = useCallback(() => {\n dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);\n if (dragDepthRef.current === 0) setIsDraggingOver(false);\n }, []);\n\n const handleDragOver = useCallback((event: DragEvent<HTMLDivElement>) => {\n if (!Array.from(event.dataTransfer?.types ?? []).includes('Files')) return;\n // Required for a drop to fire at all, and stops the browser from navigating\n // away to the dropped file.\n event.preventDefault();\n }, []);\n\n const handleDrop = useCallback(\n (event: DragEvent<HTMLDivElement>) => {\n event.preventDefault();\n dragDepthRef.current = 0;\n setIsDraggingOver(false);\n addFiles(event.dataTransfer?.files ?? null);\n },\n [addFiles]\n );\n\n const rejectionMessage = (reason: AttachmentRejection): string => {\n switch (reason) {\n case 'too-many':\n return tr('healthybowl.assistant.attachments.tooMany', 'You can attach up to {{max}} files per message.', {\n max: MAX_ATTACHMENTS,\n });\n case 'too-large':\n return tr('healthybowl.assistant.attachments.tooLarge', 'That file is larger than 10 MB.');\n case 'empty':\n return tr('healthybowl.assistant.attachments.empty', 'That file is empty.');\n case 'unreadable':\n return tr('healthybowl.assistant.attachments.unreadable', 'That file could not be read.');\n case 'unsupported-image':\n return tr(\n 'healthybowl.assistant.attachments.unsupportedImage',\n \"This device can't read that image format, so it can't be resized to send. Save it as JPEG and try again.\"\n );\n }\n };\n\n const voiceErrorMessage = (): string | null => {\n switch (voice.error) {\n case 'not-allowed':\n return tr(\n 'healthybowl.assistant.voice.denied',\n 'Microphone access is blocked. Allow it in your browser settings to dictate.'\n );\n case 'audio-capture':\n return tr('healthybowl.assistant.voice.noMic', 'No microphone was found.');\n case 'network':\n return tr('healthybowl.assistant.voice.network', 'Speech recognition is offline right now.');\n case 'language-not-supported':\n // The recogniser's language list is the browser vendor's, not ours, so\n // name the language and point at the browser rather than implying the\n // assistant is broken.\n return tr(\n 'healthybowl.assistant.voice.languageNotSupported',\n 'This browser cannot recognise spoken {{language}}. Try a different browser, or type instead.',\n { language: languageDisplayName(voice.language, locale) }\n );\n case 'unknown':\n return tr('healthybowl.assistant.voice.failed', 'Dictation stopped unexpectedly.');\n default:\n return null;\n }\n };\n\n const voiceError = voiceErrorMessage();\n\n return (\n <div className=\"flex-shrink-0 px-3 pb-3 pt-1.5\">\n <div\n onDragEnter={handleDragEnter}\n onDragLeave={handleDragLeave}\n onDragOver={handleDragOver}\n onDrop={handleDrop}\n className={`rounded-2xl border p-2 shadow-sm transition-colors focus-within:border-action-primary-bg focus-within:ring-2 focus-within:ring-action-primary-bg/15 ${\n isDraggingOver\n ? 'border-action-primary-bg border-dashed bg-action-primary-bg/5'\n : 'border-border-default bg-bg-sunken'\n }`}\n data-testid=\"assistant-composer\"\n >\n <AssistantAttachmentChips attachments={attachments} onRemove={remove} onRetry={retry} disabled={disabled} />\n\n {/* Input row: attach · textarea · mic · send */}\n <div className=\"flex items-end gap-2\">\n <AssistantAttachmentButton onFiles={addFiles} canAddMore={canAddMore} disabled={disabled} />\n\n <textarea\n ref={textareaRef}\n value={text}\n onChange={(event) => setText(event.target.value)}\n onKeyDown={handleKeyDown}\n onPaste={handlePaste}\n disabled={disabled}\n placeholder={\n isDraggingOver\n ? tr('healthybowl.assistant.composer.dropHere', 'Drop files to attach')\n : resolvedPlaceholder\n }\n rows={1}\n className=\"min-h-[36px] flex-1 resize-none self-center bg-transparent px-1 py-2 text-[15px] leading-relaxed text-text-primary placeholder:text-text-muted focus:outline-none disabled:opacity-50\"\n aria-label={tr('healthybowl.assistant.chatInput.ariaLabel', 'Message input')}\n data-testid=\"assistant-input\"\n />\n\n {voice.isSupported && (\n <AssistantVoiceButton isListening={voice.isListening} onToggle={voice.toggle} disabled={disabled} />\n )}\n\n <button\n type=\"button\"\n onClick={handleSend}\n disabled={!canSend}\n className={`flex size-9 flex-shrink-0 items-center justify-center rounded-full shadow-sm transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong ${\n canSend\n ? 'bg-action-primary-bg text-action-primary-text hover:scale-105 hover:bg-action-primary-bg-hover'\n : 'bg-bg-elevated text-text-muted'\n }`}\n aria-label={tr('healthybowl.assistant.chatInput.send', 'Send message')}\n data-testid=\"assistant-send\"\n >\n {disabled || attachmentsBusy ? <Loader2 className=\"size-4 animate-spin\" /> : <ArrowUp className=\"size-4\" />}\n </button>\n </div>\n\n {/* Mode pills */}\n {availableModes.length > 1 && (\n <div className=\"mt-2 px-0.5\">\n <AssistantModeSelector\n mode={mode}\n availableModes={availableModes}\n onModeChange={onModeChange}\n disabled={disabled}\n />\n </div>\n )}\n </div>\n\n {/* One status line under the card: live dictation > voice error >\n attachment rejection > failed upload > the keyboard hint. Announced\n politely so a screen-reader user hears dictation land without losing\n their place.\n\n The failed-upload line ranks below `rejection` (which is transient and\n describes the file the user just picked) but above the hint, because a\n disabled send button with no stated reason is the thing this whole\n change exists to avoid. */}\n <div className=\"mt-1.5 px-1 text-center text-[11px]\" aria-live=\"polite\">\n {voice.isListening ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-voice-status\">\n <span className=\"mr-1 inline-block size-1.5 rounded-full bg-status-error-text align-middle motion-safe:animate-pulse\" />\n {voice.interim ||\n tr('healthybowl.assistant.voice.listening', 'Listening… speak now, tap the square to stop')}\n </p>\n ) : voiceError ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-voice-error\">\n {voiceError}\n </p>\n ) : rejection ? (\n <button\n type=\"button\"\n onClick={clearRejection}\n className=\"text-status-error-text underline-offset-2 hover:underline\"\n data-testid=\"assistant-attachment-rejection\"\n >\n {rejectionMessage(rejection)}\n </button>\n ) : sendBlocker === 'failed' ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-attachment-blocked\">\n {failedAttachments.length === 1\n ? tr(\n 'healthybowl.assistant.attachments.blockedOne',\n \"{{name}} didn't upload. Retry or remove it before sending.\",\n { name: failedAttachments[0].filename }\n )\n : tr(\n 'healthybowl.assistant.attachments.blockedMany',\n \"{{count}} attachments didn't upload. Retry or remove them before sending.\",\n { count: failedAttachments.length }\n )}\n </p>\n ) : (\n <p className=\"text-text-muted\">\n {tr(\n 'healthybowl.assistant.composer.hint',\n 'Enter to send · Shift+Enter for newline · drag or paste files to attach'\n )}\n </p>\n )}\n </div>\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;AA2CA,IAAM,IAAsB,KAmBf,KAAgC,EAC3C,WACA,cAAW,IACX,gBACA,SACA,mBACA,sBACI;CACJ,IAAM,IAAK,EAAM,GACX,EAAE,cAAW,EAAQ,GACrB,IAAc,EAA4B,IAAI,GAC9C,CAAC,GAAM,KAAW,EAAS,EAAE,GAC7B,CAAC,GAAgB,KAAqB,EAAS,EAAK,GAGpD,IAAe,EAAO,CAAC,GAEvB,EACJ,gBACA,QAAQ,GACR,gBACA,cACA,aACA,WACA,UACA,UACA,mBACA,kBACE,EAAwB,GAMtB,IAAQ,GAAc,EAAE,YAJL,GAAa,MAAmB;EACvD,GAAS,MAAa,IAAU,GAAG,EAAQ,QAAQ,QAAQ,EAAE,EAAE,GAAG,MAAW,CAA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OAAO,CACpC;GACH,CAAA,IAEH,kBAAC,KAAD;IAAG,WAAU;cACV,EACC,uCACA,yEACF;GACC,CAAA;EAEF,CAAA,CACF;;AAET"}
@@ -24,6 +24,7 @@ function s(e) {
24
24
  case "no-speech": return "no-speech";
25
25
  case "audio-capture": return "audio-capture";
26
26
  case "network": return "network";
27
+ case "language-not-supported": return "language-not-supported";
27
28
  default: return "unknown";
28
29
  }
29
30
  }
@@ -32,15 +33,15 @@ function c({ onFinalize: c }) {
32
33
  t(() => {
33
34
  v.current = c;
34
35
  }, [c]);
35
- let y = o() !== null;
36
+ let y = o() !== null, b = a[l] ?? "en-US";
36
37
  t(() => () => {
37
38
  g.current?.abort(), g.current = null;
38
39
  }, []);
39
- let b = e(() => {
40
+ let x = e(() => {
40
41
  let e = o();
41
42
  if (!e || g.current) return;
42
43
  let t = new e();
43
- t.continuous = !0, t.interimResults = !0, t.lang = a[l] ?? "en-US";
44
+ t.continuous = !0, t.interimResults = !0, t.lang = b;
44
45
  let n = _.current;
45
46
  t.onresult = (e) => {
46
47
  if (n !== _.current) return;
@@ -64,23 +65,26 @@ function c({ onFinalize: c }) {
64
65
  return;
65
66
  }
66
67
  g.current = t, h(null), p(""), d(!0);
67
- }, [l]), x = e(() => {
68
+ }, [b]), S = e(() => {
68
69
  let e = g.current;
69
70
  g.current = null, _.current += 1, e?.stop(), d(!1), p("");
70
- }, []);
71
- return {
71
+ }, []), C = n(b);
72
+ return t(() => {
73
+ C.current !== b && (C.current = b, S(), h(null));
74
+ }, [b, S]), {
72
75
  isSupported: y,
73
76
  isListening: u,
74
77
  interim: f,
75
78
  error: m,
76
- start: b,
77
- stop: x,
79
+ language: b,
80
+ start: x,
81
+ stop: S,
78
82
  toggle: e(() => {
79
- u ? x() : b();
83
+ u ? S() : x();
80
84
  }, [
81
85
  u,
82
- b,
83
- x
86
+ x,
87
+ S
84
88
  ]),
85
89
  clearError: e(() => h(null), [])
86
90
  };
@@ -1 +1 @@
1
- {"version":3,"file":"useVoiceInput.js","names":[],"sources":["../../src/hooks/useVoiceInput.ts"],"sourcesContent":["/**\n * Speech-to-text for the assistant composer (Workstream 2 of the AI Assistant\n * V2 multimodal effort).\n *\n * Input-only, browser-native (Web Speech API) — no audio ever leaves the device\n * through us, and there is no text-to-speech here by design (the assistant does\n * not read replies aloud). It degrades gracefully: `isSupported` is false on\n * engines without SpeechRecognition (notably Firefox), and the composer hides\n * the mic entirely in that case rather than showing a dead control.\n *\n * Differences from the fe-libs `assistantWidget/useVoiceInput` this is modelled\n * on, all of which the composer needs:\n * - **interim results are exposed**, so the user sees words appear while\n * speaking instead of staring at a silent button until a phrase finalises;\n * - **errors are surfaced** (`error`) so a denied mic permission can be\n * explained rather than looking like a no-op;\n * - **the recogniser language follows the app locale** (a Tamil or Hindi\n * farmer dictating into an `en-US` recogniser gets garbage);\n * - **`stop()` resolves the final transcript** through `onFinalize`, so the\n * composer can commit exactly once when the user stops.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport type { Locale } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\n\ninterface SpeechRecognitionEventLike extends Event {\n results: SpeechRecognitionResultList;\n resultIndex: number;\n}\n\ninterface SpeechRecognitionErrorEventLike extends Event {\n error: string;\n message: string;\n}\n\ninterface SpeechRecognitionInstance extends EventTarget {\n continuous: boolean;\n interimResults: boolean;\n lang: string;\n start(): void;\n stop(): void;\n abort(): void;\n onresult: ((event: SpeechRecognitionEventLike) => void) | null;\n onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;\n onend: (() => void) | null;\n}\n\ntype SpeechRecognitionConstructor = new () => SpeechRecognitionInstance;\n\n/**\n * BCP-47 tag for the recogniser, per app locale. Regional choices follow where\n * HealthyBowl actually operates (India for ta/hi) rather than a generic tag,\n * because the recogniser's acoustic model is region-specific.\n */\nconst RECOGNITION_LANG: Record<Locale, string> = {\n en: 'en-US',\n es: 'es-ES',\n fr: 'fr-FR',\n de: 'de-DE',\n ja: 'ja-JP',\n zh: 'zh-CN',\n ta: 'ta-IN',\n hi: 'hi-IN',\n ar: 'ar-SA',\n};\n\nfunction getSpeechRecognitionConstructor(): SpeechRecognitionConstructor | null {\n if (typeof window === 'undefined') return null;\n const win = window as unknown as Record<string, unknown>;\n return (\n (win.SpeechRecognition as SpeechRecognitionConstructor | undefined) ??\n (win.webkitSpeechRecognition as SpeechRecognitionConstructor | undefined) ??\n null\n );\n}\n\nexport type VoiceInputError = 'not-allowed' | 'no-speech' | 'audio-capture' | 'network' | 'unknown';\n\n/**\n * Map the spec's `SpeechRecognitionErrorEvent.error` codes onto the four cases\n * the UI actually distinguishes. Anything else is 'unknown' (generic copy).\n */\nfunction toVoiceInputError(code: string): VoiceInputError {\n switch (code) {\n case 'not-allowed':\n case 'service-not-allowed':\n return 'not-allowed';\n case 'no-speech':\n return 'no-speech';\n case 'audio-capture':\n return 'audio-capture';\n case 'network':\n return 'network';\n default:\n return 'unknown';\n }\n}\n\nexport interface UseVoiceInputOptions {\n /**\n * Called with each newly finalised phrase. The composer appends it to the\n * draft; keeping the committed text in the caller (rather than accumulating\n * here) means the user can freely edit while dictation continues.\n */\n onFinalize: (text: string) => void;\n}\n\nexport interface UseVoiceInputResult {\n isSupported: boolean;\n isListening: boolean;\n /** Words recognised but not yet finalised — render as a live hint. */\n interim: string;\n error: VoiceInputError | null;\n start: () => void;\n stop: () => void;\n /** Start if idle, stop if listening — what the mic button binds to. */\n toggle: () => void;\n clearError: () => void;\n}\n\nexport function useVoiceInput({ onFinalize }: UseVoiceInputOptions): UseVoiceInputResult {\n const { locale } = useI18n();\n const [isListening, setIsListening] = useState(false);\n const [interim, setInterim] = useState('');\n const [error, setError] = useState<VoiceInputError | null>(null);\n const recognitionRef = useRef<SpeechRecognitionInstance | null>(null);\n // Incremented on every stop. Handlers capture the session they were created\n // under and ignore events that arrive after it ends.\n const sessionRef = useRef(0);\n\n // Keep the newest callback reachable from the recogniser's long-lived event\n // handlers without re-creating the recogniser on every parent render.\n const onFinalizeRef = useRef(onFinalize);\n useEffect(() => {\n onFinalizeRef.current = onFinalize;\n }, [onFinalize]);\n\n const isSupported = getSpeechRecognitionConstructor() !== null;\n\n // Abort (not stop) on unmount: the panel is closing, so a trailing final\n // result would be committed into a draft nobody can see.\n useEffect(() => {\n return () => {\n recognitionRef.current?.abort();\n recognitionRef.current = null;\n };\n }, []);\n\n const start = useCallback(() => {\n const Ctor = getSpeechRecognitionConstructor();\n if (!Ctor || recognitionRef.current) return;\n\n const recognition = new Ctor();\n recognition.continuous = true;\n recognition.interimResults = true;\n recognition.lang = RECOGNITION_LANG[locale] ?? 'en-US';\n\n const session = sessionRef.current;\n\n recognition.onresult = (event) => {\n if (session !== sessionRef.current) return;\n let finalText = '';\n let interimText = '';\n for (let index = event.resultIndex; index < event.results.length; index += 1) {\n const result = event.results[index];\n const alternative = result[0]?.transcript ?? '';\n if (result.isFinal) {\n finalText += alternative;\n } else {\n interimText += alternative;\n }\n }\n if (finalText.trim()) onFinalizeRef.current(finalText.trim());\n setInterim(interimText.trim());\n };\n\n recognition.onerror = (event) => {\n if (session !== sessionRef.current) return;\n const mapped = toVoiceInputError(event.error);\n // 'no-speech' fires routinely during a natural pause and the recogniser\n // keeps running — surfacing it would flash a scary message mid-sentence.\n if (mapped !== 'no-speech') setError(mapped);\n };\n\n recognition.onend = () => {\n if (session !== sessionRef.current) return;\n recognitionRef.current = null;\n setIsListening(false);\n setInterim('');\n };\n\n try {\n recognition.start();\n } catch {\n // start() throws if a recogniser is somehow already running — treat the\n // session as not started rather than leaving the button stuck \"live\".\n recognitionRef.current = null;\n setIsListening(false);\n return;\n }\n\n recognitionRef.current = recognition;\n setError(null);\n setInterim('');\n setIsListening(true);\n }, [locale]);\n\n const stop = useCallback(() => {\n // Detach BEFORE stopping. `onend` is what used to clear this ref, but it\n // arrives asynchronously — so a user who tapped stop and immediately tapped\n // the mic again hit `start()`'s `if (recognitionRef.current) return` guard\n // and got a silent no-op. Bumping the session also makes any trailing final\n // phrase the engine flushes on stop land on a dead session, instead of\n // reappearing in a draft the composer has already sent and cleared.\n const recognition = recognitionRef.current;\n recognitionRef.current = null;\n sessionRef.current += 1;\n recognition?.stop();\n setIsListening(false);\n setInterim('');\n }, []);\n\n const toggle = useCallback(() => {\n if (isListening) stop();\n else start();\n }, [isListening, start, stop]);\n\n const clearError = useCallback(() => setError(null), []);\n\n return { isSupported, isListening, interim, error, start, stop, toggle, clearError };\n}\n"],"mappings":";;;AAuDA,IAAM,IAA2C;CAC/C,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;AACN;AAEA,SAAS,IAAuE;CAC9E,IAAI,OAAO,SAAW,KAAa,OAAO;CAC1C,IAAM,IAAM;CACZ,OACG,EAAI,qBACJ,EAAI,2BACL;AAEJ;AAQA,SAAS,EAAkB,GAA+B;CACxD,QAAQ,GAAR;EACE,KAAK;EACL,KAAK,uBACH,OAAO;EACT,KAAK,aACH,OAAO;EACT,KAAK,iBACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAwBA,SAAgB,EAAc,EAAE,iBAAyD;CACvF,IAAM,EAAE,cAAW,EAAQ,GACrB,CAAC,GAAa,KAAkB,EAAS,EAAK,GAC9C,CAAC,GAAS,KAAc,EAAS,EAAE,GACnC,CAAC,GAAO,KAAY,EAAiC,IAAI,GACzD,IAAiB,EAAyC,IAAI,GAG9D,IAAa,EAAO,CAAC,GAIrB,IAAgB,EAAO,CAAU;CACvC,QAAgB;EACd,EAAc,UAAU;CAC1B,GAAG,CAAC,CAAU,CAAC;CAEf,IAAM,IAAc,EAAgC,MAAM;CAI1D,cACe;EAEX,AADA,EAAe,SAAS,MAAM,GAC9B,EAAe,UAAU;CAC3B,GACC,CAAC,CAAC;CAEL,IAAM,IAAQ,QAAkB;EAC9B,IAAM,IAAO,EA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AAI,IAAa,EAAK,IACjB,EAAM;EACb,GAAG;GAAC;GAAa;GAAO;EAAI,CAIoC;EAAQ,YAFrD,QAAkB,EAAS,IAAI,GAAG,CAAC,CAEkB;CAAW;AACrF"}
1
+ {"version":3,"file":"useVoiceInput.js","names":[],"sources":["../../src/hooks/useVoiceInput.ts"],"sourcesContent":["/**\n * Speech-to-text for the assistant composer (Workstream 2 of the AI Assistant\n * V2 multimodal effort).\n *\n * Input-only, browser-native (Web Speech API). It degrades gracefully:\n * `isSupported` is false on engines without SpeechRecognition (notably Firefox),\n * and the composer hides the mic entirely in that case rather than showing a\n * dead control.\n *\n * ⚠️ This does NOT mean the audio stays on the device. Chrome's\n * `webkitSpeechRecognition` is a NETWORK service — the audio is streamed to the\n * browser vendor for recognition, and the supported language list is theirs, not\n * ours. We neither receive nor store it, which is all an earlier version of this\n * comment (\"no audio ever leaves the device through us\") actually claimed; read\n * literally it implied something stronger and untrue. Whether recording farmers'\n * speech this way needs disclosure or consent is a product/legal call, not a\n * code one.\n *\n * Output (reading replies aloud) is a separate concern and lives in\n * `AssistantSpeechProvider`; an earlier version of this note said the assistant\n * does not speak, which stopped being true when BOFF-6290 shipped.\n *\n * Differences from the fe-libs `assistantWidget/useVoiceInput` this is modelled\n * on, all of which the composer needs:\n * - **interim results are exposed**, so the user sees words appear while\n * speaking instead of staring at a silent button until a phrase finalises;\n * - **errors are surfaced** (`error`) so a denied mic permission can be\n * explained rather than looking like a no-op;\n * - **the recogniser language follows the app locale** (a Tamil or Hindi\n * farmer dictating into an `en-US` recogniser gets garbage);\n * - **`stop()` resolves the final transcript** through `onFinalize`, so the\n * composer can commit exactly once when the user stops.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport type { Locale } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\n\ninterface SpeechRecognitionEventLike extends Event {\n results: SpeechRecognitionResultList;\n resultIndex: number;\n}\n\ninterface SpeechRecognitionErrorEventLike extends Event {\n error: string;\n message: string;\n}\n\ninterface SpeechRecognitionInstance extends EventTarget {\n continuous: boolean;\n interimResults: boolean;\n lang: string;\n start(): void;\n stop(): void;\n abort(): void;\n onresult: ((event: SpeechRecognitionEventLike) => void) | null;\n onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;\n onend: (() => void) | null;\n}\n\ntype SpeechRecognitionConstructor = new () => SpeechRecognitionInstance;\n\n/**\n * BCP-47 tag for the recogniser, per app locale. Regional choices follow where\n * HealthyBowl actually operates (India for ta/hi) rather than a generic tag,\n * because the recogniser's acoustic model is region-specific.\n */\nconst RECOGNITION_LANG: Record<Locale, string> = {\n en: 'en-US',\n es: 'es-ES',\n fr: 'fr-FR',\n de: 'de-DE',\n ja: 'ja-JP',\n zh: 'zh-CN',\n ta: 'ta-IN',\n hi: 'hi-IN',\n ar: 'ar-SA',\n};\n\nfunction getSpeechRecognitionConstructor(): SpeechRecognitionConstructor | null {\n if (typeof window === 'undefined') return null;\n const win = window as unknown as Record<string, unknown>;\n return (\n (win.SpeechRecognition as SpeechRecognitionConstructor | undefined) ??\n (win.webkitSpeechRecognition as SpeechRecognitionConstructor | undefined) ??\n null\n );\n}\n\nexport type VoiceInputError =\n 'not-allowed' | 'no-speech' | 'audio-capture' | 'network' | 'language-not-supported' | 'unknown';\n\n/**\n * Map the spec's `SpeechRecognitionErrorEvent.error` codes onto the cases the UI\n * actually distinguishes. Anything else is 'unknown' (generic copy).\n *\n * `language-not-supported` is called out separately because it is the single\n * most likely failure for the users this feature exists for: the recogniser's\n * language list belongs to the browser vendor, not to us, so a Tamil or Hindi\n * speaker can hit it on a browser that simply does not offer their language.\n * Folding it into 'unknown' produced \"Dictation stopped unexpectedly\", which\n * tells them nothing and reads like a bug in HealthyBowl.\n */\nfunction toVoiceInputError(code: string): VoiceInputError {\n switch (code) {\n case 'not-allowed':\n case 'service-not-allowed':\n return 'not-allowed';\n case 'no-speech':\n return 'no-speech';\n case 'audio-capture':\n return 'audio-capture';\n case 'network':\n return 'network';\n case 'language-not-supported':\n return 'language-not-supported';\n default:\n return 'unknown';\n }\n}\n\nexport interface UseVoiceInputOptions {\n /**\n * Called with each newly finalised phrase. The composer appends it to the\n * draft; keeping the committed text in the caller (rather than accumulating\n * here) means the user can freely edit while dictation continues.\n */\n onFinalize: (text: string) => void;\n}\n\nexport interface UseVoiceInputResult {\n isSupported: boolean;\n isListening: boolean;\n /** Words recognised but not yet finalised — render as a live hint. */\n interim: string;\n error: VoiceInputError | null;\n /**\n * BCP-47 tag the recogniser was asked for. Exposed so error copy can name the\n * language that failed (\"Tamil dictation is not supported…\") rather than\n * leaving the user to guess which language the browser rejected.\n */\n language: string;\n start: () => void;\n stop: () => void;\n /** Start if idle, stop if listening — what the mic button binds to. */\n toggle: () => void;\n clearError: () => void;\n}\n\nexport function useVoiceInput({ onFinalize }: UseVoiceInputOptions): UseVoiceInputResult {\n const { locale } = useI18n();\n const [isListening, setIsListening] = useState(false);\n const [interim, setInterim] = useState('');\n const [error, setError] = useState<VoiceInputError | null>(null);\n const recognitionRef = useRef<SpeechRecognitionInstance | null>(null);\n // Incremented on every stop. Handlers capture the session they were created\n // under and ignore events that arrive after it ends.\n const sessionRef = useRef(0);\n\n // Keep the newest callback reachable from the recogniser's long-lived event\n // handlers without re-creating the recogniser on every parent render.\n const onFinalizeRef = useRef(onFinalize);\n useEffect(() => {\n onFinalizeRef.current = onFinalize;\n }, [onFinalize]);\n\n const isSupported = getSpeechRecognitionConstructor() !== null;\n const language = RECOGNITION_LANG[locale] ?? 'en-US';\n\n // Abort (not stop) on unmount: the panel is closing, so a trailing final\n // result would be committed into a draft nobody can see.\n useEffect(() => {\n return () => {\n recognitionRef.current?.abort();\n recognitionRef.current = null;\n };\n }, []);\n\n const start = useCallback(() => {\n const Ctor = getSpeechRecognitionConstructor();\n if (!Ctor || recognitionRef.current) return;\n\n const recognition = new Ctor();\n recognition.continuous = true;\n recognition.interimResults = true;\n recognition.lang = language;\n\n const session = sessionRef.current;\n\n recognition.onresult = (event) => {\n if (session !== sessionRef.current) return;\n let finalText = '';\n let interimText = '';\n for (let index = event.resultIndex; index < event.results.length; index += 1) {\n const result = event.results[index];\n const alternative = result[0]?.transcript ?? '';\n if (result.isFinal) {\n finalText += alternative;\n } else {\n interimText += alternative;\n }\n }\n if (finalText.trim()) onFinalizeRef.current(finalText.trim());\n setInterim(interimText.trim());\n };\n\n recognition.onerror = (event) => {\n if (session !== sessionRef.current) return;\n const mapped = toVoiceInputError(event.error);\n // 'no-speech' fires routinely during a natural pause and the recogniser\n // keeps running — surfacing it would flash a scary message mid-sentence.\n if (mapped !== 'no-speech') setError(mapped);\n };\n\n recognition.onend = () => {\n if (session !== sessionRef.current) return;\n recognitionRef.current = null;\n setIsListening(false);\n setInterim('');\n };\n\n try {\n recognition.start();\n } catch {\n // start() throws if a recogniser is somehow already running — treat the\n // session as not started rather than leaving the button stuck \"live\".\n recognitionRef.current = null;\n setIsListening(false);\n return;\n }\n\n recognitionRef.current = recognition;\n setError(null);\n setInterim('');\n setIsListening(true);\n }, [language]);\n\n const stop = useCallback(() => {\n // Detach BEFORE stopping. `onend` is what used to clear this ref, but it\n // arrives asynchronously — so a user who tapped stop and immediately tapped\n // the mic again hit `start()`'s `if (recognitionRef.current) return` guard\n // and got a silent no-op. Bumping the session also makes any trailing final\n // phrase the engine flushes on stop land on a dead session, instead of\n // reappearing in a draft the composer has already sent and cleared.\n const recognition = recognitionRef.current;\n recognitionRef.current = null;\n sessionRef.current += 1;\n recognition?.stop();\n setIsListening(false);\n setInterim('');\n }, []);\n\n // Changing language must END the session it no longer describes.\n //\n // A running recogniser keeps the `lang` it was constructed with, so after a\n // switch the in-flight session is still listening in the OLD language while\n // this hook already reports the new one. A late `language-not-supported` from\n // that session would then be rendered as though the browser had rejected the\n // language the user just picked. Clearing the error is not enough — the\n // session producing it has to go too.\n const languageRef = useRef(language);\n useEffect(() => {\n if (languageRef.current === language) return;\n languageRef.current = language;\n stop();\n setError(null);\n }, [language, stop]);\n\n const toggle = useCallback(() => {\n if (isListening) stop();\n else start();\n }, [isListening, start, stop]);\n\n const clearError = useCallback(() => setError(null), []);\n\n return { isSupported, isListening, interim, error, language, start, stop, toggle, clearError };\n}\n"],"mappings":";;;AAmEA,IAAM,IAA2C;CAC/C,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;AACN;AAEA,SAAS,IAAuE;CAC9E,IAAI,OAAO,SAAW,KAAa,OAAO;CAC1C,IAAM,IAAM;CACZ,OACG,EAAI,qBACJ,EAAI,2BACL;AAEJ;AAgBA,SAAS,EAAkB,GAA+B;CACxD,QAAQ,GAAR;EACE,KAAK;EACL,KAAK,uBACH,OAAO;EACT,KAAK,aACH,OAAO;EACT,KAAK,iBACH,OAAO;EACT,KAAK,WACH,OAAO;EACT,KAAK,0BACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AA8BA,SAAgB,EAAc,EAAE,iBAAyD;CACvF,IAAM,EAAE,cAAW,EAAQ,GACrB,CAAC,GAAa,KAAkB,EAAS,EAAK,GAC9C,CAAC,GAAS,KAAc,EAAS,EAAE,GACnC,CAAC,GAAO,KAAY,EAAiC,IAAI,GACzD,IAAiB,EAAyC,IAAI,GAG9D,IAAa,EAAO,CAAC,GAIrB,IAAgB,EAAO,CAAU;CACvC,QAAgB;EACd,EAAc,UAAU;CAC1B,GAAG,CAAC,CAAU,CAAC;CAEf,IAAM,IAAc,EAAgC,MAAM,MACpD,IAAW,EAAiB,MAAW;CAI7C,cACe;EAEX,AADA,EAAe,SAAS,MAAM,GAC9B,EAAe,UAAU;CAC3B,GACC,CAAC,CAAC;CAEL,IAAM,IAAQ,QAAkB;EAC9B,IAAM,IAAO,EAAgC;EAC7C,IAAI,CAAC,KAAQ,EAAe,SAAS;EAErC,IAAM,IAAc,IAAI,EAAK;EAG7B,AAFA,EAAY,aAAa,IACzB,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EAAM,QAP3D,QAAkB;GAC/B,AAAI,IAAa,EAAK,IACjB,EAAM;EACb,GAAG;GAAC;GAAa;GAAO;EAAI,CAI8C;EAAQ,YAF/D,QAAkB,EAAS,IAAI,GAAG,CAAC,CAE4B;CAAW;AAC/F"}
@@ -27,17 +27,26 @@ function i(e, i) {
27
27
  let c = s.filter((e) => t(e.lang) === a), l = c.length > 0 ? c : s;
28
28
  return l.find((e) => e.default) ?? l.find((e) => e.localService) ?? l[0];
29
29
  }
30
- function a(e, t, n) {
31
- return e ? t.length === 0 ? "pending" : i(t, n) ? "ready" : "missing-voice" : "unsupported";
30
+ function a(e, t, n, r = !1) {
31
+ return e ? t.length === 0 ? r ? "no-voices" : "pending" : i(t, n) ? "ready" : "missing-voice" : "unsupported";
32
32
  }
33
- function o(e) {
34
- return e === "ready" ? "speak" : e === "pending" ? "wait-for-voices" : "block";
33
+ function o(e, t) {
34
+ let r = n(e);
35
+ if (!r) return e;
36
+ try {
37
+ return new Intl.DisplayNames([t], { type: "language" }).of(r) ?? r;
38
+ } catch {
39
+ return r;
40
+ }
35
41
  }
36
42
  function s(e) {
37
- return e === "missing-voice";
43
+ return e === "ready" ? "speak" : e === "pending" ? "wait-for-voices" : "block";
44
+ }
45
+ function c(e) {
46
+ return e === "missing-voice" || e === "no-voices";
38
47
  }
39
- var c = 2e3;
48
+ var l = 2e3;
40
49
  //#endregion
41
- export { c as VOICE_LIST_TIMEOUT_MS, s as isSpeechBlocked, i as selectVoiceForLocale, o as speechGate, r as speechLangForLocale, a as voiceAvailability };
50
+ export { l as VOICE_LIST_TIMEOUT_MS, c as isSpeechBlocked, o as languageDisplayName, i as selectVoiceForLocale, s as speechGate, r as speechLangForLocale, a as voiceAvailability };
42
51
 
43
52
  //# sourceMappingURL=speechVoices.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"speechVoices.js","names":[],"sources":["../../src/utils/speechVoices.ts"],"sourcesContent":["/**\n * Locale → voice matching for the assistant's spoken reply (BOFF-6290).\n *\n * Pure and engine-agnostic: it works on a structural `SpeechVoiceLike`, which a\n * real `SpeechSynthesisVoice` satisfies, so the selection ladder is unit-testable\n * in this repo's node-environment vitest with plain objects — the browser's\n * voice list is not reachable from a test here.\n *\n * `import type` only, so nothing from fe-libs is loaded at runtime by the suite.\n */\n\nimport type { Locale } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\n\n/**\n * BCP-47 tag we ask the engine for, per app locale.\n *\n * Deliberately identical to `useVoiceInput`'s RECOGNITION_LANG: regional choices\n * follow where HealthyBowl actually operates (India for ta/hi), because a voice's\n * pronunciation model is region-specific. Typed `Record<Locale, …>` so adding a\n * locale to fe-libs fails the build here rather than silently falling back to\n * English.\n */\nexport const SPEECH_LANG: Record<Locale, string> = {\n en: 'en-US',\n es: 'es-ES',\n fr: 'fr-FR',\n de: 'de-DE',\n ja: 'ja-JP',\n zh: 'zh-CN',\n ta: 'ta-IN',\n hi: 'hi-IN',\n ar: 'ar-SA',\n};\n\n/**\n * The subset of `SpeechSynthesisVoice` this module needs. Structural on purpose:\n * `selectVoiceForLocale` returns the caller's own array element, so the browser\n * engine gets back the real `SpeechSynthesisVoice` instance it must assign to\n * `utterance.voice`, while tests pass literals.\n */\nexport interface SpeechVoiceLike {\n readonly name: string;\n readonly lang: string;\n /** The engine's default voice (usually the OS UI language). */\n readonly default?: boolean;\n /** On-device rather than server-side — no network, no latency, no vendor. */\n readonly localService?: boolean;\n}\n\n/** `en_GB`, `EN-gb` and `en-GB` are the same tag as far as matching goes. */\nexport function normalizeLangTag(tag: string): string {\n return tag.trim().toLowerCase().replace(/_/g, '-');\n}\n\n/** `ta-IN` → `ta`. The part that decides whether a voice is intelligible at all. */\nexport function primaryLanguageSubtag(tag: string): string {\n return normalizeLangTag(tag).split('-')[0];\n}\n\nexport function speechLangForLocale(locale: string): string {\n return SPEECH_LANG[locale as Locale] ?? locale;\n}\n\n/**\n * Pick the best installed voice for an app locale, or `null` when the device has\n * no voice for that language at all.\n *\n * The ladder, in order:\n * 1. exact tag (`ta-IN` for Tamil);\n * 2. same language, any region (`en-GB` when only `en-US` was asked for) —\n * an accent is a far smaller problem than the wrong language;\n * 3. within whichever tier matched: the engine's default voice, then an\n * on-device voice, then engine order.\n *\n * There is intentionally NO cross-language fallback. Reading a Tamil reply with\n * an English voice produces confident nonsense; the caller disables the control\n * and says why instead (see `AssistantSpeechProvider`).\n */\nexport function selectVoiceForLocale<T extends SpeechVoiceLike>(voices: readonly T[], locale: string): T | null {\n const target = normalizeLangTag(speechLangForLocale(locale));\n const targetPrimary = primaryLanguageSubtag(target);\n if (!targetPrimary) return null;\n\n const sameLanguage = voices.filter((voice) => primaryLanguageSubtag(voice.lang) === targetPrimary);\n if (sameLanguage.length === 0) return null;\n\n const exact = sameLanguage.filter((voice) => normalizeLangTag(voice.lang) === target);\n const pool = exact.length > 0 ? exact : sameLanguage;\n\n return pool.find((voice) => voice.default) ?? pool.find((voice) => voice.localService) ?? pool[0];\n}\n\n/**\n * What the UI should do with the speak control, given what the engine reports.\n *\n * `pending` matters: `speechSynthesis.getVoices()` famously returns `[]` on the\n * first call in Chrome and only fills in after `voiceschanged`. Treating an\n * empty list as \"no voice\" would disable the button for a moment on every load\n * and, on engines that never fire the event, forever — so an empty list stays\n * enabled and we let the engine resolve `utterance.lang` itself.\n */\nexport type VoiceAvailability = 'unsupported' | 'pending' | 'ready' | 'missing-voice';\n\nexport function voiceAvailability(\n isSupported: boolean,\n voices: readonly SpeechVoiceLike[],\n locale: string\n): VoiceAvailability {\n if (!isSupported) return 'unsupported';\n if (voices.length === 0) return 'pending';\n return selectVoiceForLocale(voices, locale) ? 'ready' : 'missing-voice';\n}\n\n/**\n * What a caller that wants to speak RIGHT NOW should do.\n *\n * The one decision every playback path has to make, in one place, because\n * having it in three (the per-message button, the header toggle, the auto-speak\n * subscription) is how \"there is no cross-language fallback\" stopped being true\n * on two of them: an empty or unmatched voice list means the engine picks its\n * own default, and a Tamil reply comes out in an English voice.\n *\n * - `speak` — a voice for this language exists; go.\n * - `wait-for-voices` — the list has not arrived yet (Chrome's first\n * `getVoices()` returns `[]`). Speaking now would gamble on the engine\n * default, and refusing forever would disable the control on engines that\n * never fire `voiceschanged`; so the caller waits for the list, briefly, and\n * asks again. The control stays enabled throughout.\n * - `block` — unsupported, or no voice for this language. Say nothing.\n */\nexport type SpeechGate = 'speak' | 'wait-for-voices' | 'block';\n\nexport function speechGate(availability: VoiceAvailability): SpeechGate {\n if (availability === 'ready') return 'speak';\n if (availability === 'pending') return 'wait-for-voices';\n return 'block';\n}\n\n/**\n * Should the control be visible but inert?\n *\n * `pending` deliberately is NOT disabled — see `speechGate`.\n */\nexport function isSpeechBlocked(availability: VoiceAvailability): boolean {\n return availability === 'missing-voice';\n}\n\n/** How long to wait for a late voice list before giving up on one attempt. */\nexport const VOICE_LIST_TIMEOUT_MS = 2_000;\n"],"mappings":";AAsBA,IAAa,IAAsC;CACjD,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;AACN;AAkBA,SAAgB,EAAiB,GAAqB;CACpD,OAAO,EAAI,KAAK,EAAE,YAAY,EAAE,QAAQ,MAAM,GAAG;AACnD;AAGA,SAAgB,EAAsB,GAAqB;CACzD,OAAO,EAAiB,CAAG,EAAE,MAAM,GAAG,EAAE;AAC1C;AAEA,SAAgB,EAAoB,GAAwB;CAC1D,OAAO,EAAY,MAAqB;AAC1C;AAiBA,SAAgB,EAAgD,GAAsB,GAA0B;CAC9G,IAAM,IAAS,EAAiB,EAAoB,CAAM,CAAC,GACrD,IAAgB,EAAsB,CAAM;CAClD,IAAI,CAAC,GAAe,OAAO;CAE3B,IAAM,IAAe,EAAO,QAAQ,MAAU,EAAsB,EAAM,IAAI,MAAM,CAAa;CACjG,IAAI,EAAa,WAAW,GAAG,OAAO;CAEtC,IAAM,IAAQ,EAAa,QAAQ,MAAU,EAAiB,EAAM,IAAI,MAAM,CAAM,GAC9E,IAAO,EAAM,SAAS,IAAI,IAAQ;CAExC,OAAO,EAAK,MAAM,MAAU,EAAM,OAAO,KAAK,EAAK,MAAM,MAAU,EAAM,YAAY,KAAK,EAAK;AACjG;AAaA,SAAgB,EACd,GACA,GACA,GACmB;CAGnB,OAFK,IACD,EAAO,WAAW,IAAU,YACzB,EAAqB,GAAQ,CAAM,IAAI,UAAU,kBAF/B;AAG3B;AAqBA,SAAgB,EAAW,GAA6C;CAGtE,OAFI,MAAiB,UAAgB,UACjC,MAAiB,YAAkB,oBAChC;AACT;AAOA,SAAgB,EAAgB,GAA0C;CACxE,OAAO,MAAiB;AAC1B;AAGA,IAAa,IAAwB"}
1
+ {"version":3,"file":"speechVoices.js","names":[],"sources":["../../src/utils/speechVoices.ts"],"sourcesContent":["/**\n * Locale → voice matching for the assistant's spoken reply (BOFF-6290).\n *\n * Pure and engine-agnostic: it works on a structural `SpeechVoiceLike`, which a\n * real `SpeechSynthesisVoice` satisfies, so the selection ladder is unit-testable\n * in this repo's node-environment vitest with plain objects — the browser's\n * voice list is not reachable from a test here.\n *\n * `import type` only, so nothing from fe-libs is loaded at runtime by the suite.\n */\n\nimport type { Locale } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\n\n/**\n * BCP-47 tag we ask the engine for, per app locale.\n *\n * Deliberately identical to `useVoiceInput`'s RECOGNITION_LANG: regional choices\n * follow where HealthyBowl actually operates (India for ta/hi), because a voice's\n * pronunciation model is region-specific. Typed `Record<Locale, …>` so adding a\n * locale to fe-libs fails the build here rather than silently falling back to\n * English.\n */\nexport const SPEECH_LANG: Record<Locale, string> = {\n en: 'en-US',\n es: 'es-ES',\n fr: 'fr-FR',\n de: 'de-DE',\n ja: 'ja-JP',\n zh: 'zh-CN',\n ta: 'ta-IN',\n hi: 'hi-IN',\n ar: 'ar-SA',\n};\n\n/**\n * The subset of `SpeechSynthesisVoice` this module needs. Structural on purpose:\n * `selectVoiceForLocale` returns the caller's own array element, so the browser\n * engine gets back the real `SpeechSynthesisVoice` instance it must assign to\n * `utterance.voice`, while tests pass literals.\n */\nexport interface SpeechVoiceLike {\n readonly name: string;\n readonly lang: string;\n /** The engine's default voice (usually the OS UI language). */\n readonly default?: boolean;\n /** On-device rather than server-side — no network, no latency, no vendor. */\n readonly localService?: boolean;\n}\n\n/** `en_GB`, `EN-gb` and `en-GB` are the same tag as far as matching goes. */\nexport function normalizeLangTag(tag: string): string {\n return tag.trim().toLowerCase().replace(/_/g, '-');\n}\n\n/** `ta-IN` → `ta`. The part that decides whether a voice is intelligible at all. */\nexport function primaryLanguageSubtag(tag: string): string {\n return normalizeLangTag(tag).split('-')[0];\n}\n\nexport function speechLangForLocale(locale: string): string {\n return SPEECH_LANG[locale as Locale] ?? locale;\n}\n\n/**\n * Pick the best installed voice for an app locale, or `null` when the device has\n * no voice for that language at all.\n *\n * The ladder, in order:\n * 1. exact tag (`ta-IN` for Tamil);\n * 2. same language, any region (`en-GB` when only `en-US` was asked for) —\n * an accent is a far smaller problem than the wrong language;\n * 3. within whichever tier matched: the engine's default voice, then an\n * on-device voice, then engine order.\n *\n * There is intentionally NO cross-language fallback. Reading a Tamil reply with\n * an English voice produces confident nonsense; the caller disables the control\n * and says why instead (see `AssistantSpeechProvider`).\n */\nexport function selectVoiceForLocale<T extends SpeechVoiceLike>(voices: readonly T[], locale: string): T | null {\n const target = normalizeLangTag(speechLangForLocale(locale));\n const targetPrimary = primaryLanguageSubtag(target);\n if (!targetPrimary) return null;\n\n const sameLanguage = voices.filter((voice) => primaryLanguageSubtag(voice.lang) === targetPrimary);\n if (sameLanguage.length === 0) return null;\n\n const exact = sameLanguage.filter((voice) => normalizeLangTag(voice.lang) === target);\n const pool = exact.length > 0 ? exact : sameLanguage;\n\n return pool.find((voice) => voice.default) ?? pool.find((voice) => voice.localService) ?? pool[0];\n}\n\n/**\n * What the UI should do with the speak control, given what the engine reports.\n *\n * `pending` matters: `speechSynthesis.getVoices()` famously returns `[]` on the\n * first call in Chrome and only fills in after `voiceschanged`. Treating an\n * empty list as \"no voice\" would disable the button for a moment on every load\n * and, on engines that never fire the event, forever — so an empty list stays\n * enabled and we let the engine resolve `utterance.lang` itself.\n */\nexport type VoiceAvailability = 'unsupported' | 'pending' | 'ready' | 'missing-voice' | 'no-voices';\n\n/**\n * `probeSettled` is what separates \"the list has not arrived yet\" from \"this\n * device genuinely has none\".\n *\n * Both look like `voices.length === 0`, and the difference is not knowable from\n * the list alone — only the caller, having waited out `VOICE_LIST_TIMEOUT_MS`\n * and looked again, can tell them apart. Defaulting to `false` keeps the\n * optimistic reading (`pending`, control stays enabled) for every caller that\n * has not probed, which is the pre-existing behaviour.\n *\n * Without this distinction the empty list stays `pending` forever, `speechGate`\n * keeps answering `wait-for-voices`, and the button is enabled but does nothing\n * on every press — a dead control with no explanation, which is exactly how\n * this feature looked on any Linux box or bare container.\n */\nexport function voiceAvailability(\n isSupported: boolean,\n voices: readonly SpeechVoiceLike[],\n locale: string,\n probeSettled = false\n): VoiceAvailability {\n if (!isSupported) return 'unsupported';\n if (voices.length === 0) return probeSettled ? 'no-voices' : 'pending';\n return selectVoiceForLocale(voices, locale) ? 'ready' : 'missing-voice';\n}\n\n/**\n * Human name for the language we would have spoken, in the reader's own locale\n * (\"Tamil\" for an English UI, \"தமிழ்\" for a Tamil one).\n *\n * Used to make the disabled reason actionable: \"No Tamil voice is installed\"\n * tells a user what to go and install; \"no voice is installed\" does not.\n * `Intl.DisplayNames` is unavailable in some embedded webviews, so the subtag\n * itself is the fallback — degraded copy beats a thrown render.\n */\nexport function languageDisplayName(languageTag: string, inLocale: string): string {\n const subtag = primaryLanguageSubtag(languageTag);\n if (!subtag) return languageTag;\n try {\n return new Intl.DisplayNames([inLocale], { type: 'language' }).of(subtag) ?? subtag;\n } catch {\n return subtag;\n }\n}\n\n/**\n * What a caller that wants to speak RIGHT NOW should do.\n *\n * The one decision every playback path has to make, in one place, because\n * having it in three (the per-message button, the header toggle, the auto-speak\n * subscription) is how \"there is no cross-language fallback\" stopped being true\n * on two of them: an empty or unmatched voice list means the engine picks its\n * own default, and a Tamil reply comes out in an English voice.\n *\n * - `speak` — a voice for this language exists; go.\n * - `wait-for-voices` — the list has not arrived yet (Chrome's first\n * `getVoices()` returns `[]`). Speaking now would gamble on the engine\n * default, and refusing forever would disable the control on engines that\n * never fire `voiceschanged`; so the caller waits for the list, briefly, and\n * asks again. The control stays enabled throughout.\n * - `block` — unsupported, or no voice for this language. Say nothing.\n */\nexport type SpeechGate = 'speak' | 'wait-for-voices' | 'block';\n\nexport function speechGate(availability: VoiceAvailability): SpeechGate {\n if (availability === 'ready') return 'speak';\n if (availability === 'pending') return 'wait-for-voices';\n return 'block';\n}\n\n/**\n * Should the control be visible but inert?\n *\n * `pending` deliberately is NOT disabled — see `speechGate`. `no-voices` is,\n * because by then we have waited and looked again: staying enabled would leave\n * the user pressing a button that can never do anything.\n */\nexport function isSpeechBlocked(availability: VoiceAvailability): boolean {\n return availability === 'missing-voice' || availability === 'no-voices';\n}\n\n/** How long to wait for a late voice list before giving up on one attempt. */\nexport const VOICE_LIST_TIMEOUT_MS = 2_000;\n"],"mappings":";AAsBA,IAAa,IAAsC;CACjD,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;AACN;AAkBA,SAAgB,EAAiB,GAAqB;CACpD,OAAO,EAAI,KAAK,EAAE,YAAY,EAAE,QAAQ,MAAM,GAAG;AACnD;AAGA,SAAgB,EAAsB,GAAqB;CACzD,OAAO,EAAiB,CAAG,EAAE,MAAM,GAAG,EAAE;AAC1C;AAEA,SAAgB,EAAoB,GAAwB;CAC1D,OAAO,EAAY,MAAqB;AAC1C;AAiBA,SAAgB,EAAgD,GAAsB,GAA0B;CAC9G,IAAM,IAAS,EAAiB,EAAoB,CAAM,CAAC,GACrD,IAAgB,EAAsB,CAAM;CAClD,IAAI,CAAC,GAAe,OAAO;CAE3B,IAAM,IAAe,EAAO,QAAQ,MAAU,EAAsB,EAAM,IAAI,MAAM,CAAa;CACjG,IAAI,EAAa,WAAW,GAAG,OAAO;CAEtC,IAAM,IAAQ,EAAa,QAAQ,MAAU,EAAiB,EAAM,IAAI,MAAM,CAAM,GAC9E,IAAO,EAAM,SAAS,IAAI,IAAQ;CAExC,OAAO,EAAK,MAAM,MAAU,EAAM,OAAO,KAAK,EAAK,MAAM,MAAU,EAAM,YAAY,KAAK,EAAK;AACjG;AA4BA,SAAgB,EACd,GACA,GACA,GACA,IAAe,IACI;CAGnB,OAFK,IACD,EAAO,WAAW,IAAU,IAAe,cAAc,YACtD,EAAqB,GAAQ,CAAM,IAAI,UAAU,kBAF/B;AAG3B;AAWA,SAAgB,EAAoB,GAAqB,GAA0B;CACjF,IAAM,IAAS,EAAsB,CAAW;CAChD,IAAI,CAAC,GAAQ,OAAO;CACpB,IAAI;EACF,OAAO,IAAI,KAAK,aAAa,CAAC,CAAQ,GAAG,EAAE,MAAM,WAAW,CAAC,EAAE,GAAG,CAAM,KAAK;CAC/E,QAAQ;EACN,OAAO;CACT;AACF;AAqBA,SAAgB,EAAW,GAA6C;CAGtE,OAFI,MAAiB,UAAgB,UACjC,MAAiB,YAAkB,oBAChC;AACT;AASA,SAAgB,EAAgB,GAA0C;CACxE,OAAO,MAAiB,mBAAmB,MAAiB;AAC9D;AAGA,IAAa,IAAwB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/microfe-healthybowl",
3
- "version": "2026.828.2",
3
+ "version": "2026.829.1",
4
4
  "description": "Burdenoff HealthyBowl Microfrontend - Comprehensive organic farming and agro-foods management platform",
5
5
  "type": "module",
6
6
  "files": [