@burdenoff/microfe-healthybowl 2026.828.1 → 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.
- package/dist/components/assistant/AssistantMessageItem.js +8 -2
- package/dist/components/assistant/AssistantMessageItem.js.map +1 -1
- package/dist/components/assistant/AssistantSpeakButton.js +7 -6
- package/dist/components/assistant/AssistantSpeakButton.js.map +1 -1
- package/dist/components/assistant/AssistantSpeechProvider.js +110 -87
- package/dist/components/assistant/AssistantSpeechProvider.js.map +1 -1
- package/dist/components/assistant/composer/AssistantComposer.js +104 -101
- package/dist/components/assistant/composer/AssistantComposer.js.map +1 -1
- package/dist/healthybowl/components/HBEntityImages.js.map +1 -1
- package/dist/healthybowl/hooks/useTraceScanActivity.js +68 -0
- package/dist/healthybowl/hooks/useTraceScanActivity.js.map +1 -0
- package/dist/healthybowl/pages/compliance/IcsGrowerDetailPage.js +174 -129
- package/dist/healthybowl/pages/compliance/IcsGrowerDetailPage.js.map +1 -1
- package/dist/healthybowl/pages/crops/FieldDetailsPage.js +858 -803
- package/dist/healthybowl/pages/crops/FieldDetailsPage.js.map +1 -1
- package/dist/healthybowl/pages/traceability/QRCodesPage.js +320 -220
- package/dist/healthybowl/pages/traceability/QRCodesPage.js.map +1 -1
- package/dist/healthybowl/pages/traceability/TraceLedgerPage.js +261 -98
- package/dist/healthybowl/pages/traceability/TraceLedgerPage.js.map +1 -1
- package/dist/hooks/useVoiceInput.js +15 -11
- package/dist/hooks/useVoiceInput.js.map +1 -1
- package/dist/utils/speechVoices.js +16 -7
- package/dist/utils/speechVoices.js.map +1 -1
- package/package.json +1 -1
|
@@ -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,KAAA;AAC3D;AAEA,SAAS,EAAa,GAAqE;CACzF,OAAO,GAAU,aAAa,CAAC;AACjC;AAEA,SAAS,EAAa,GAAwB;CAC5C,OAAO,OAAO,KAAK,CAAM;AAC3B;AAEA,SAAS,EAAmB,GAAgB,GAAkB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ACT,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,EAAQ,SAAS,cAAc,EAAQ,WAAW,KAAA;AAC3D;AAEA,SAAS,EAAa,GAAqE;CACzF,OAAO,GAAU,aAAa,CAAC;AACjC;AAEA,SAAS,EAAa,GAAwB;CAC5C,OAAO,OAAO,KAAK,CAAM;AAC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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,
|
|
6
|
-
let
|
|
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:
|
|
9
|
+
onClick: l,
|
|
10
10
|
disabled: o,
|
|
11
|
-
title: o ? s ??
|
|
12
|
-
"aria-label":
|
|
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:
|
|
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> = ({
|
|
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,
|
|
6
|
-
import { IDLE_PLAYBACK as
|
|
7
|
-
import { isTurnInFlight as
|
|
8
|
-
import { parseToolActivity as
|
|
9
|
-
import { createContext as
|
|
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 =
|
|
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
|
|
26
|
+
return y(E);
|
|
27
27
|
}
|
|
28
|
-
var O = ({ children:
|
|
29
|
-
let O = t(), { locale: k } = w(), [A, j] =
|
|
30
|
-
|
|
31
|
-
}, []),
|
|
32
|
-
|
|
33
|
-
if (!
|
|
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,
|
|
37
|
-
let
|
|
38
|
-
|
|
36
|
+
}, [D, U]);
|
|
37
|
+
let W = x(() => d(U, M, k, P), [
|
|
38
|
+
U,
|
|
39
39
|
M,
|
|
40
|
-
k
|
|
41
|
-
|
|
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]),
|
|
49
|
-
|
|
50
|
-
}, [
|
|
51
|
-
|
|
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
|
-
|
|
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())),
|
|
56
|
-
n || (n = !0, clearTimeout(o), r(),
|
|
62
|
+
r = D.subscribeVoices(() => i(D.listVoices())), L.current = () => {
|
|
63
|
+
n || (n = !0, clearTimeout(o), r(), L.current = null);
|
|
57
64
|
};
|
|
58
|
-
}, [
|
|
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 =
|
|
71
|
+
let a = l(d(!0, i, k, P));
|
|
65
72
|
if (a === "block") return;
|
|
66
73
|
if (a === "wait-for-voices") {
|
|
67
|
-
|
|
74
|
+
Y(e, t);
|
|
68
75
|
return;
|
|
69
76
|
}
|
|
70
|
-
let o =
|
|
71
|
-
|
|
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:
|
|
77
|
-
lang:
|
|
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
|
-
|
|
97
|
+
G,
|
|
91
98
|
k,
|
|
92
|
-
|
|
99
|
+
P,
|
|
100
|
+
Y
|
|
93
101
|
]);
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
}, [
|
|
97
|
-
let
|
|
98
|
-
if (!
|
|
99
|
-
let n = i(t, { labels:
|
|
100
|
-
n &&
|
|
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
|
-
|
|
103
|
-
W,
|
|
110
|
+
U,
|
|
104
111
|
q,
|
|
112
|
+
X,
|
|
105
113
|
M
|
|
106
|
-
]),
|
|
107
|
-
if (
|
|
108
|
-
|
|
114
|
+
]), Q = v((e, t) => {
|
|
115
|
+
if (p(A, e)) {
|
|
116
|
+
J();
|
|
109
117
|
return;
|
|
110
118
|
}
|
|
111
|
-
|
|
119
|
+
Z(e, t);
|
|
112
120
|
}, [
|
|
113
121
|
A,
|
|
114
|
-
|
|
115
|
-
|
|
122
|
+
Z,
|
|
123
|
+
J
|
|
116
124
|
]);
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
}, [
|
|
120
|
-
|
|
121
|
-
}, [
|
|
122
|
-
|
|
123
|
-
}, [D]),
|
|
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
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
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" || !
|
|
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 } =
|
|
142
|
-
s.trim() &&
|
|
163
|
+
let { text: s } = g(o.content);
|
|
164
|
+
s.trim() && $.current(a, s);
|
|
143
165
|
});
|
|
144
166
|
}, [
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
167
|
+
B,
|
|
168
|
+
W,
|
|
169
|
+
U,
|
|
170
|
+
y
|
|
149
171
|
]);
|
|
150
|
-
let
|
|
151
|
-
isSupported:
|
|
152
|
-
availability:
|
|
153
|
-
isBlocked: o(
|
|
154
|
-
disabledReason:
|
|
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) =>
|
|
157
|
-
toggle:
|
|
158
|
-
stop:
|
|
159
|
-
autoSpeakEnabled:
|
|
160
|
-
setAutoSpeak:
|
|
178
|
+
isSpeaking: (e) => p(A, e),
|
|
179
|
+
toggle: Q,
|
|
180
|
+
stop: J,
|
|
181
|
+
autoSpeakEnabled: B,
|
|
182
|
+
setAutoSpeak: V
|
|
161
183
|
}), [
|
|
162
|
-
|
|
163
|
-
|
|
184
|
+
U,
|
|
185
|
+
W,
|
|
186
|
+
K,
|
|
164
187
|
A,
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
188
|
+
Q,
|
|
189
|
+
J,
|
|
190
|
+
B,
|
|
191
|
+
V,
|
|
169
192
|
O
|
|
170
193
|
]);
|
|
171
194
|
return /* @__PURE__ */ T(E.Provider, {
|
|
172
|
-
value:
|
|
173
|
-
children:
|
|
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,g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AAK,2BAA2B,IAC1C,IAAS,EAAS,2BAA2B;GACnD,IAAI,GAAS,WAAW,cAAc,CAAC,EAAe,GAAQ,MAAM,GAAG;GAEvE,IAAM,IAAY,EAAQ,aAAa,GAAQ,aAAa;GAC5D,IAAI,CAAC,GAAW;GAEhB,IAAM,IAAU,EAAK,cAClB,MAAM,MAAiB,EAAa,OAAO,CAAc,GACxD,SAAS,MAAM,MAAc,EAAU,OAAO,CAAS;GAC3D,IAAI,CAAC,KAAW,EAAQ,SAAS,aAAa;GAG9C,IAAM,EAAE,YAAS,EAAkB,EAAQ,OAAO;GAC7C,EAAK,KAAK,KAEf,EAAS,QAAQ,GAAW,CAAI;EAClC,CAAC;CACH,GAAG;EAAC;EAAkB;EAAc;EAAa;CAAO,CAAC;CAEzD,IAAM,IAAQ,SACL;EACL;EACA;EACA,WAAW,EAAgB,CAAY;EACvC,gBAAgB,EAAgB,CAAY,IACxC,EAAG,iDAAiD,wDAAwD,IAC5G;EACJ,mBAAmB,EAAS,WAAW,aAAa,EAAS,YAAY;EACzE,aAAa,MAAsB,EAAkB,GAAU,CAAS;EACxE;EACA;EACA;EACA;CACF,IACA;EAAC;EAAa;EAAc;EAAU;EAAQ;EAAM;EAAkB;EAAc;CAAE,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,QAA0B;CAChH,IAAM,IAAK,EAAM,GACX,EAAE,cAAW,EAAQ,GACrB,CAAC,GAAU,KAAY,GAAW,GAAuB,CAAa,GACtE,CAAC,GAAQ,KAAa,QAAkC,EAAO,WAAW,CAAC,GAQ3E,CAAC,GAAmB,KAAwB,EAAS,EAAK,GAC1D,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,GAA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