@burdenoff/microfe-healthybowl 2026.903.21 → 2026.904.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.
Files changed (66) hide show
  1. package/dist/components/assistant/AIAssistantPanel.js +25 -21
  2. package/dist/components/assistant/AIAssistantPanel.js.map +1 -1
  3. package/dist/components/assistant/AssistantApiCallsConsentDialog.js +8 -8
  4. package/dist/components/assistant/AssistantApiCallsConsentDialog.js.map +1 -1
  5. package/dist/components/assistant/AssistantAutoSpeakToggle.js +1 -1
  6. package/dist/components/assistant/AssistantChatArea.js +248 -249
  7. package/dist/components/assistant/AssistantChatArea.js.map +1 -1
  8. package/dist/components/assistant/AssistantConversationList.js +31 -31
  9. package/dist/components/assistant/AssistantConversationList.js.map +1 -1
  10. package/dist/components/assistant/AssistantEmptyState.js +9 -9
  11. package/dist/components/assistant/AssistantEmptyState.js.map +1 -1
  12. package/dist/components/assistant/AssistantHeader.js +17 -17
  13. package/dist/components/assistant/AssistantHeader.js.map +1 -1
  14. package/dist/components/assistant/AssistantMarkdownImage.js +14 -14
  15. package/dist/components/assistant/AssistantMarkdownImage.js.map +1 -1
  16. package/dist/components/assistant/AssistantMarkdownRenderer.js +25 -25
  17. package/dist/components/assistant/AssistantMarkdownRenderer.js.map +1 -1
  18. package/dist/components/assistant/AssistantMessageAttachments.js +29 -29
  19. package/dist/components/assistant/AssistantMessageAttachments.js.map +1 -1
  20. package/dist/components/assistant/AssistantMessageItem.js +28 -28
  21. package/dist/components/assistant/AssistantMessageItem.js.map +1 -1
  22. package/dist/components/assistant/AssistantMessageList.js +14 -14
  23. package/dist/components/assistant/AssistantMessageList.js.map +1 -1
  24. package/dist/components/assistant/AssistantMoreMenu.js +25 -25
  25. package/dist/components/assistant/AssistantMoreMenu.js.map +1 -1
  26. package/dist/components/assistant/AssistantPendingWriteCard.js +8 -8
  27. package/dist/components/assistant/AssistantPendingWriteCard.js.map +1 -1
  28. package/dist/components/assistant/AssistantReplyLanguageSelector.js +11 -11
  29. package/dist/components/assistant/AssistantReplyLanguageSelector.js.map +1 -1
  30. package/dist/components/assistant/AssistantSpeakButton.js +4 -4
  31. package/dist/components/assistant/AssistantSpeakButton.js.map +1 -1
  32. package/dist/components/assistant/AssistantSpeechProvider.js +188 -188
  33. package/dist/components/assistant/AssistantSpeechProvider.js.map +1 -1
  34. package/dist/components/assistant/AssistantSpokenTurnsNotice.js +5 -5
  35. package/dist/components/assistant/AssistantSpokenTurnsNotice.js.map +1 -1
  36. package/dist/components/assistant/AssistantToolActivity.js +16 -16
  37. package/dist/components/assistant/AssistantToolActivity.js.map +1 -1
  38. package/dist/components/assistant/composer/AssistantAttachmentButton.js +20 -20
  39. package/dist/components/assistant/composer/AssistantAttachmentButton.js.map +1 -1
  40. package/dist/components/assistant/composer/AssistantAttachmentChips.js +23 -23
  41. package/dist/components/assistant/composer/AssistantAttachmentChips.js.map +1 -1
  42. package/dist/components/assistant/composer/AssistantComposer.js +44 -44
  43. package/dist/components/assistant/composer/AssistantComposer.js.map +1 -1
  44. package/dist/components/assistant/composer/AssistantLanguageSelector.js +7 -7
  45. package/dist/components/assistant/composer/AssistantLanguageSelector.js.map +1 -1
  46. package/dist/components/assistant/composer/AssistantModeSelector.js +28 -28
  47. package/dist/components/assistant/composer/AssistantModeSelector.js.map +1 -1
  48. package/dist/components/assistant/composer/AssistantVoiceButton.js +6 -6
  49. package/dist/components/assistant/composer/AssistantVoiceButton.js.map +1 -1
  50. package/dist/components/assistant/composer/AssistantVoiceSelector.js +7 -7
  51. package/dist/components/assistant/composer/AssistantVoiceSelector.js.map +1 -1
  52. package/dist/components/assistant/voice/AssistantVoiceSession.js +77 -77
  53. package/dist/components/assistant/voice/AssistantVoiceSession.js.map +1 -1
  54. package/dist/components/assistant/voice/AssistantVoiceSessionButton.js +6 -6
  55. package/dist/components/assistant/voice/AssistantVoiceSessionButton.js.map +1 -1
  56. package/dist/components/assistant/voice/VoiceConversationView.js +11 -11
  57. package/dist/components/assistant/voice/VoiceConversationView.js.map +1 -1
  58. package/dist/components/assistant/voice/VoiceTranscriptDrawer.js +13 -13
  59. package/dist/components/assistant/voice/VoiceTranscriptDrawer.js.map +1 -1
  60. package/dist/hooks/useAssistantAttachments.js +94 -94
  61. package/dist/hooks/useAssistantAttachments.js.map +1 -1
  62. package/dist/services/assistantApi.js +1 -1
  63. package/dist/services/assistantApi.js.map +1 -1
  64. package/dist/utils/attachmentSources.js +4 -4
  65. package/dist/utils/attachmentSources.js.map +1 -1
  66. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantSpeechProvider.js","names":[],"sources":["../../../src/components/assistant/AssistantSpeechProvider.tsx"],"sourcesContent":["/**\n * Speech-output context for the assistant panel (BOFF-6290).\n *\n * The assistant could already hear (`useVoiceInput`); this is the other half —\n * it can now answer out loud. That matters for a farming product where the user\n * is outdoors with dirty hands, a phone in a pocket and sun on the screen, and\n * it is a plain accessibility win everywhere else.\n *\n * Everything stateful about playback lives here, once, so that:\n *\n * - **playback is never orphaned.** A voice that keeps talking after the UI is\n * gone is a bug, so speech is cancelled when the panel hides, when the\n * conversation changes, on unmount, and on `pagehide` (Chrome keeps speaking\n * across a navigation otherwise);\n * - **only one message speaks at a time.** Starting a new playback cancels the\n * previous one — enforced by the engine and by the request-id guard in\n * `speechPlaybackReducer`;\n * - **nothing ever autoplays.** Playback starts from a button press. The\n * persisted auto-speak preference defaults OFF and is opt-in from the header.\n *\n * Components consume this through `useAssistantSpeech()`, which falls back to an\n * inert value when there is no provider (Storybook, a header rendered on its\n * own) rather than throwing.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type FC,\n type ReactNode,\n} from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { voicePreviewText } from '@/utils/voicePreview';\nimport { getSpeechEngine } from '../../services/speech';\nimport type { SpeechEngine, SpeechVoiceLike } from '../../services/speech';\nimport { chunkForSpeech, toSpeakableText, type SpeakableLabels } from '../../utils/speakableText';\nimport { speechLabelsFor } from '../../config/speechLabels';\n\n/**\n * The speakable transformation with nothing of ours added — used ONLY to decide\n * the reply's language.\n *\n * Detection needs the prose that will be spoken: code blocks and URLs stripped\n * (they are never read aloud, and their Latin identifiers would outvote short\n * non-Latin prose), but no substitute wording introduced either (that would let\n * our own app-locale words vote instead).\n */\nconst SILENT_LABELS: SpeakableLabels = {\n codeBlock: '',\n image: '',\n link: '',\n largeTable: '',\n truncated: '',\n emailAt: 'at',\n emailDot: 'dot',\n nestedItem: '',\n};\nimport {\n VOICE_LIST_TIMEOUT_MS,\n languageDisplayName,\n selectVoiceForLocale,\n voicesForLocale,\n speechGate,\n speechLangForLocale,\n voiceAvailability,\n type VoiceAvailability,\n} from '../../utils/speechVoices';\nimport { resolveSpeechLocale } from '../../utils/replyLanguage';\nimport { DEFAULT_SPEECH_RATE, findAssistantLanguage } from '../../config/assistantLanguages';\nimport { resolveLanguagePair } from '../../config/assistantLanguagePair';\nimport { IDLE_PLAYBACK, isSpeakingMessage, speechPlaybackReducer } from '../../utils/speechPlayback';\nimport { isVoiceTurn } from '../../utils/voiceTurnVisibility';\nimport { isTurnInFlight } from '../../utils/assistantTurnState';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport interface AssistantSpeechContextValue {\n /** False when the platform has no speech output — hide the control entirely. */\n isSupported: boolean;\n availability: VoiceAvailability;\n /**\n * True when nothing can be spoken in the app language, so every control that\n * starts playback — the per-message button AND the header toggle — must be\n * inert. `pending` is not blocked: see `speechGate`.\n */\n isBlocked: boolean;\n /** Explains a disabled control (no installed voice for the app language). */\n disabledReason: string | null;\n /**\n * Why THIS message cannot be spoken, when the app language is fine but the\n * reply is not in it — a Tamil answer in an English UI on a device with no\n * Tamil voice. `isBlocked` cannot see that: it is computed before any reply\n * exists. Without this the control looks enabled and silently refuses, which\n * is the dead-button bug all over again (BOFF-7106).\n */\n blockedFor: (messageId: string) => string | null;\n /**\n * Every installed voice that can read the language the user speaks, best\n * first. Empty when there is no choice to offer — the picker hides itself\n * rather than showing a one-item dropdown.\n */\n voiceChoices: readonly SpeechVoiceLike[];\n /** The voice that will actually be used, resolved from the pick + ranking. */\n /**\n * The reply as it is being SPOKEN: every chunk, plus the one sounding now.\n *\n * `null` when nothing is playing. `index: -1` means chunked but not yet\n * audible. Consumers reveal `chunks[0..index]` — anything beyond that is the\n * caption running ahead of the voice.\n */\n spokenChunks: { chunks: string[]; index: number } | null;\n activeVoiceName: string | null;\n /**\n * The RAW stored pick: `null` means \"use the ranked default\".\n *\n * The picker must be driven by this rather than by `activeVoiceName`, or the\n * two states collapse — with nothing stored, the ranked winner is already the\n * shown option, so choosing it fires no change event and the pick can never\n * be made. The user's voice would then silently move the next time the device\n * installs a higher-ranked one. Same trap as the language selector.\n */\n preferredVoiceName: string | null;\n /** `null` restores the ranked default for the current language. */\n setVoice: (voiceName: string | null) => void;\n /** The message currently being spoken, if any. */\n speakingMessageId: string | null;\n isSpeaking: (messageId: string) => boolean;\n /**\n * Speak this message, or stop if it is already the one speaking.\n *\n * `turnLocale` is the language the reply was GENERATED under, from the\n * message's own metadata. It matters because script detection cannot separate\n * Latin-script languages, so without it an old French reply would be read\n * with whatever voice the CURRENT preference selects.\n */\n toggle: (messageId: string, markdown: string, turnLocale?: string) => void;\n stop: () => void;\n autoSpeakEnabled: boolean;\n setAutoSpeak: (enabled: boolean) => void;\n /**\n * Speak replies for the duration of a live voice session, WITHOUT touching the\n * user's saved preference.\n *\n * ★ Live Voice used to force `autoSpeakEnabled` true and restore it on exit.\n * That field is PERSISTED (assistantStore partialize), and the restore only\n * ran on a clean `end()` — so a reload, a closed tab or a backgrounded webview\n * during a session left auto-speak switched ON for the user permanently, in\n * normal typed chat, with the toggle showing a state they never chose. The\n * default was never wrong; the session was overwriting it.\n *\n * Session-scoped React state instead: it cannot outlive the page, so there is\n * nothing to restore and nothing to leak.\n */\n sessionSpeaking: boolean;\n setSessionSpeaking: (enabled: boolean) => void;\n /** Play a short sample in a named voice. No model call, no message, no tokens. */\n previewVoice: (voiceName: string) => void;\n}\n\nconst INERT_SPEECH: AssistantSpeechContextValue = {\n isSupported: false,\n availability: 'unsupported',\n isBlocked: true,\n disabledReason: null,\n blockedFor: () => null,\n voiceChoices: [],\n spokenChunks: null,\n activeVoiceName: null,\n preferredVoiceName: null,\n setVoice: () => {},\n speakingMessageId: null,\n isSpeaking: () => false,\n toggle: () => {},\n stop: () => {},\n autoSpeakEnabled: false,\n setAutoSpeak: () => {},\n sessionSpeaking: false,\n setSessionSpeaking: () => {},\n previewVoice: () => {},\n};\n\nconst AssistantSpeechContext = createContext<AssistantSpeechContextValue>(INERT_SPEECH);\n\nexport function useAssistantSpeech(): AssistantSpeechContextValue {\n return useContext(AssistantSpeechContext);\n}\n\ninterface Props {\n children: ReactNode;\n /** Panel visibility. Hiding the panel stops the voice. */\n visible?: boolean;\n /**\n * Injectable for tests and local experiments. The default routes between the\n * device engine and the hosted one; with hosted TTS unconfigured it IS the\n * device engine, unchanged.\n */\n engine?: SpeechEngine;\n}\n\nexport const AssistantSpeechProvider: FC<Props> = ({ children, visible = true, engine = getSpeechEngine() }) => {\n const tr = useTr();\n const { locale } = useI18n();\n const [playback, dispatch] = useReducer(speechPlaybackReducer, IDLE_PLAYBACK);\n const [voices, setVoices] = useState<SpeechVoiceLike[]>(() => engine.listVoices());\n /**\n * True once we have waited out the voice list and it was still empty.\n *\n * Turns an indefinite `pending` into a terminal `no-voices`, which is what\n * lets the control be disabled with a reason instead of silently doing\n * nothing on every press.\n */\n const [voiceProbeSettled, setVoiceProbeSettled] = useState(false);\n /**\n * Every message we have refused, and why — keyed by id (see `blockedFor`).\n *\n * A single record could only describe one refusal: refusing a second reply\n * silently re-enabled the first, whose voice was still just as missing, so\n * pressing the buttons walked the disabled state around the transcript.\n */\n const [unspeakable, setUnspeakable] = useState<ReadonlyMap<string, string>>(() => new Map());\n const requestRef = useRef(0);\n\n /**\n * Which chunk of the current reply is sounding right now.\n *\n * ★ `index: -1` means \"chunked, nothing playing yet\" — distinct from no\n * progress at all, so the caption can stay empty until audio genuinely starts\n * instead of flashing the first sentence while the engine is still fetching.\n */\n const [spokenProgress, setSpokenProgress] = useState<{\n requestId: number;\n chunks: string[];\n index: number;\n } | null>(null);\n /** Cancels a playback that is waiting for the engine's voice list, if any. */\n const pendingRef = useRef<(() => void) | null>(null);\n const speakWithRef = useRef<\n (messageId: string, text: string, voices: readonly SpeechVoiceLike[], speechLocale: string) => void\n >(() => {});\n\n const cancelPending = useCallback(() => {\n pendingRef.current?.();\n pendingRef.current = null;\n }, []);\n\n const autoSpeakEnabled = useAssistantStore((state) => state.autoSpeakEnabled);\n const setAutoSpeak = useAssistantStore((state) => state.setAutoSpeak);\n // Not in the store on purpose — see `sessionSpeaking` on the context type.\n const [sessionSpeaking, setSessionSpeaking] = useState(false);\n const activeConversationId = useAssistantStore((state) => state.activeConversationId);\n\n const isSupported = useMemo(() => engine.isSupported(), [engine]);\n\n // getVoices() is empty on the first call in Chrome and only fills in when\n // 'voiceschanged' fires; Safari populates it synchronously and may never fire\n // the event. Read eagerly AND subscribe, so both engines end up correct.\n useEffect(() => {\n if (!isSupported) return;\n const sync = () => {\n setVoices(engine.listVoices());\n // Every recorded refusal was \"no voice for this language\". A new voice\n // list may well have supplied one — most likely because the user just\n // followed our instructions and installed it. Keeping the refusals would\n // leave those buttons disabled with no way back except a reload.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n sync();\n return engine.subscribeVoices(sync);\n }, [engine, isSupported]);\n\n // The language being SPOKEN ALOUD — which is the language of the reply, not\n // of the input and not of the interface. The two were one field until the\n // reply language was split out (BOFF-7108).\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const replyLanguage = useAssistantStore((state) => state.replyLanguage);\n const preferredVoices = useAssistantStore((state) => state.preferredVoices);\n const setPreferredVoice = useAssistantStore((state) => state.setPreferredVoice);\n const spokenLanguage = useMemo(\n // ★ The REPLY language, not the input. This is the language of the text\n // being spoken, so wiring it to the input would give a Tamil voice reading\n // an English answer the moment the two are set differently — the single\n // worst outcome available here, and the reason they were split at all.\n () => resolveLanguagePair(assistantLanguage, replyLanguage, locale).reply,\n [assistantLanguage, replyLanguage, locale]\n );\n const spokenLocale = spokenLanguage.code;\n\n /**\n * BCP-47 tag to ask the engine for, given a resolved language CODE.\n *\n * Resolved through the catalogue for ANY known code, not merely the currently\n * selected one — a historical Bengali reply must still get `bn-IN` after the\n * user switches to Tamil, or with both `bn-IN` and `bn-BD` installed the\n * engine's own order decides, and picks the wrong country.\n *\n * Falls back to the generic table for codes the catalogue does not carry.\n */\n const tagFor = useCallback((code: string) => findAssistantLanguage(code)?.tag ?? speechLangForLocale(code), []);\n\n /** Speaking rate for a resolved language code — see `AssistantLanguage.rate`. */\n const rateFor = useCallback((code: string) => findAssistantLanguage(code)?.rate ?? DEFAULT_SPEECH_RATE, []);\n\n const availability = useMemo(\n () => voiceAvailability(isSupported, voices, spokenLanguage.tag, voiceProbeSettled),\n [isSupported, voices, spokenLanguage, voiceProbeSettled]\n );\n\n // Spoken placeholders follow the app locale like the rest of the copy; the\n // transformation itself stays a pure function by taking them as arguments.\n const labels = useMemo<SpeakableLabels>(\n () => ({\n codeBlock: tr('healthybowl.assistant.speech.codeBlock', 'Code block'),\n image: tr('healthybowl.assistant.speech.image', 'image'),\n link: tr('healthybowl.assistant.speech.link', 'link'),\n largeTable: tr('healthybowl.assistant.speech.largeTable', 'Table with {{rows}} rows and {{columns}} columns'),\n truncated: tr('healthybowl.assistant.speech.truncated', 'The rest of this message is not read aloud'),\n nestedItem: tr('healthybowl.assistant.speech.nestedItem', 'Sub-item {{ordinal}}'),\n emailAt: tr('healthybowl.assistant.speech.emailAt', 'at'),\n emailDot: tr('healthybowl.assistant.speech.emailDot', 'dot'),\n }),\n [tr]\n );\n\n const stop = useCallback(() => {\n cancelPending();\n engine.cancel();\n dispatch({ type: 'stop' });\n }, [cancelPending, engine]);\n\n /**\n * Audition a voice — no model call, no message, no tokens.\n *\n * ★ Speaks through the engine DIRECTLY rather than through `speakWith`. That\n * path is built around a message: it resolves the reply's language, records\n * per-message \"cannot speak this\" state, and drives `speakingMessageId` so a\n * Listen button can light up. A preview has no message, so borrowing it would\n * mean inventing a fake id and then teaching every consumer to ignore it.\n *\n * Consequently it deliberately does NOT touch playback state: auditioning a\n * voice must not make a Listen button in the thread appear to be playing.\n *\n * Speaks the sample in the language being spoken, not the interface language —\n * the listener is judging how this voice reads THAT language.\n */\n const previewVoice = useCallback(\n (voiceName: string) => {\n const voice = engine.listVoices().find((candidate) => candidate.name === voiceName) ?? null;\n // An unknown name means the list changed under us (a download finished, a\n // profile switched). Silence is the right answer — better than falling\n // back to some other voice and auditioning the wrong one.\n if (!voice) return;\n // Whatever is speaking now is not what the user asked to hear.\n stop();\n engine.speak([voicePreviewText(spokenLocale)], { voice, lang: tagFor(spokenLocale) });\n },\n [engine, spokenLocale, stop, tagFor]\n );\n\n const blockedFor = useCallback((messageId: string) => unspeakable.get(messageId) ?? null, [unspeakable]);\n\n /**\n * Hold one playback until the engine publishes its voice list.\n *\n * Bounded: on timeout we take one last look and decide with whatever is\n * there, so an engine that never fires `voiceschanged` costs a two-second\n * wait rather than a control that is disabled forever. Nothing is spoken from\n * here unless a list actually arrives — an empty list means the engine would\n * pick its own default voice, which is the cross-language read this feature\n * promises never to do.\n */\n const waitForVoices = useCallback(\n (messageId: string, text: string, speechLocale: string) => {\n cancelPending();\n\n let settled = false;\n let unsubscribe = () => {};\n const finish = (available: SpeechVoiceLike[]) => {\n if (settled) return;\n settled = true;\n pendingRef.current = null;\n clearTimeout(timer);\n unsubscribe();\n if (available.length === 0) {\n // We waited and looked again: this device has no voices at all.\n // Record it so `availability` becomes `no-voices` and the control\n // explains itself, instead of returning silently every press.\n setVoiceProbeSettled(true);\n return;\n }\n setVoices(available);\n speakWithRef.current(messageId, text, available, speechLocale);\n };\n\n const timer = setTimeout(() => finish(engine.listVoices()), VOICE_LIST_TIMEOUT_MS);\n unsubscribe = engine.subscribeVoices(() => finish(engine.listVoices()));\n\n pendingRef.current = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n unsubscribe();\n pendingRef.current = null;\n };\n },\n [cancelPending, engine]\n );\n\n /**\n * Speak text against a KNOWN voice list.\n *\n * Every playback path funnels through here — the per-message button, the\n * header toggle's auto-speak, the store subscription — so the language gate\n * cannot be bypassed by any of them. Reading a Tamil reply with an English\n * voice is confident nonsense; it has to be impossible, not merely unlikely.\n */\n const speakWith = useCallback(\n (messageId: string, text: string, available: readonly SpeechVoiceLike[], speechLocale: string) => {\n let known = available;\n\n // Chrome answers the FIRST getVoices() with [] and fills the list in\n // asynchronously. One more synchronous read usually settles it.\n if (known.length === 0) {\n const refreshed = engine.listVoices();\n if (refreshed.length > 0) {\n known = refreshed;\n setVoices(refreshed);\n }\n }\n\n const speechLang = tagFor(speechLocale);\n\n const gate = speechGate(voiceAvailability(true, known, speechLocale, voiceProbeSettled));\n if (gate === 'block') {\n // Recorded for THIS message, always. Availability is resolved per reply\n // now, so a global \"your language has no voice\" cannot stand in for it:\n // the language the user chose to converse in says nothing about the one\n // this particular reply came back in.\n const reason = tr(\n 'healthybowl.assistant.speech.noVoiceForReply',\n 'This reply is in {{language}}, and no {{language}} voice is installed on this device.',\n { language: languageDisplayName(speechLang, locale) }\n );\n setUnspeakable((current) => new Map(current).set(messageId, reason));\n return;\n }\n if (gate === 'wait-for-voices') {\n waitForVoices(messageId, text, speechLocale);\n return;\n }\n\n setUnspeakable((current) => {\n if (!current.has(messageId)) return current;\n const next = new Map(current);\n next.delete(messageId);\n return next;\n });\n\n const requestId = requestRef.current + 1;\n requestRef.current = requestId;\n dispatch({ type: 'start', messageId, requestId });\n\n // ★ Chunked ONCE and kept, so the caption can show exactly what is being\n // spoken rather than a parallel rendering of the same markdown. A live\n // caption whose words differ from the audio is not a caption.\n const chunks = chunkForSpeech(text);\n setSpokenProgress({ requestId, chunks, index: -1 });\n\n engine.speak(\n chunks,\n // The TAG, not the code — so exact regional matching gets its chance\n // before the same-language fallback. `rate` had never been passed at\n // all, so every reply was read at the engine default.\n {\n voice: selectVoiceForLocale(known, speechLang, preferredVoices[speechLocale]),\n lang: speechLang,\n rate: rateFor(speechLocale),\n },\n {\n // Guarded on the request id like every other handler here: a stale\n // batch that has not noticed its cancellation must not drive the\n // caption of the reply that replaced it.\n onChunkStart: (index) =>\n setSpokenProgress((current) => (current?.requestId === requestId ? { ...current, index } : current)),\n onEnd: () => dispatch({ type: 'finished', requestId }),\n // Includes the 'cancelled' every queued utterance reports when we\n // pre-empt a batch; the request-id guard drops those as stale.\n onError: () => dispatch({ type: 'failed', requestId }),\n }\n );\n },\n [engine, locale, preferredVoices, rateFor, tagFor, tr, voiceProbeSettled, waitForVoices]\n );\n\n // `waitForVoices` resumes through this ref, so the two do not become a\n // circular hook dependency.\n useEffect(() => {\n speakWithRef.current = speakWith;\n }, [speakWith]);\n\n const speak = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (!isSupported) return;\n\n // Resolve the reply's language BEFORE building the spoken text, because\n // the stand-in words must be in that language. Detection deliberately runs\n // on a SILENT_LABELS pass — our own words must not vote on which language\n // the reply is in — so it does not depend on the labels chosen here.\n const replyLocale = resolveSpeechLocale(\n toSpeakableText(markdown, { labels: SILENT_LABELS }),\n turnLocale ?? spokenLocale\n );\n\n // ★ Labels in the REPLY's language, not the interface's. An English\n // interface reading a Tamil answer used to say \"Code block\" and \"image\" in\n // English, mid-Tamil-sentence — the same defect the email `at`/`dot` fix\n // addressed and did not generalise.\n const text = toSpeakableText(markdown, { labels: speechLabelsFor(replyLocale, labels) });\n if (!text) return;\n\n // Detect on the text that will actually be SPOKEN, with our own words\n // removed — neither the raw markdown nor the finished transformation.\n //\n // The transformation injects app-locale placeholders (\"Code block\"), which\n // let English chrome outvote short non-Latin prose. The raw markdown keeps\n // fenced code, whose Latin identifiers do the same thing — and that code is\n // never spoken at all. Running the same transformation with EMPTY labels\n // strips the unspoken constructs while contributing no words of its own,\n // which is exactly the denominator the decision needs.\n // The turn's OWN language first — the preference is only a stand-in for\n // replies that predate it. Resolved above, and reused rather than\n // recomputed.\n speakWith(messageId, text, voices, replyLocale);\n },\n [isSupported, labels, spokenLocale, speakWith, voices]\n );\n\n const toggle = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (isSpeakingMessage(playback, messageId)) {\n stop();\n return;\n }\n speak(messageId, markdown, turnLocale);\n },\n [playback, speak, stop]\n );\n\n // ── Never leave a voice talking to an empty room ─────────────────────────\n useEffect(() => {\n if (!visible) stop();\n }, [visible, stop]);\n\n useEffect(() => {\n // Switching (or creating) a conversation abandons the reply being read —\n // and the refusal explained a message that is no longer on screen.\n stop();\n setUnspeakable(new Map());\n }, [activeConversationId, stop]);\n\n useEffect(() => {\n // Every refusal was decided against the locale in force at the time, which\n // is what a Latin-script reply falls back to. Change the locale and those\n // verdicts may simply be wrong — an English reply refused on a\n // Spanish-only device would stay disabled forever after switching the UI to\n // Spanish, with the voice that could read it already installed.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n // And stop anything mid-sentence. The new language can make this message\n // unspeakable, which disables its button — leaving it reading \"Stop\" with no\n // way to actually stop, short of closing the panel.\n stop();\n }, [spokenLocale, stop]);\n\n useEffect(() => {\n return () => {\n pendingRef.current?.();\n pendingRef.current = null;\n engine.cancel();\n };\n }, [engine]);\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n // Chrome carries speech across a same-tab navigation and a bfcache restore\n // would otherwise come back mid-sentence.\n const handlePageHide = () => engine.cancel();\n window.addEventListener('pagehide', handlePageHide);\n return () => window.removeEventListener('pagehide', handlePageHide);\n }, [engine]);\n\n // ── One timeout is not a life sentence ───────────────────────────────────\n //\n // `no-voices` disables the control, and a disabled control can never reach\n // `speakWith` — the only path that re-reads `engine.listVoices()`. So without\n // this, a user who follows our own advice, leaves to install a voice and comes\n // back stays blocked until a reload: we would be telling them how to fix it\n // and then refusing to notice that they had.\n //\n // Returning to the tab is exactly when that happens, and it costs one\n // synchronous read of an already-populated list.\n useEffect(() => {\n if (typeof document === 'undefined' || !isSupported) return;\n const reprobe = () => {\n if (document.visibilityState !== 'visible') return;\n // Adopt the list UNCONDITIONALLY, including an empty one. Keeping the old\n // cache on an empty read means a user who uninstalled their last voice\n // stays `ready`, and playback then hands the engine a voice object that no\n // longer exists instead of explaining the problem.\n //\n // Safe to accept an empty read here precisely because the probe verdict is\n // cleared on the next line: empty + unsettled is `pending`, which leaves\n // the control ENABLED and defers the real decision to the next press.\n const available = engine.listVoices();\n // A Listen press may still be inside its two-second wait. Adopting voices\n // here flips the control to `ready`, so the user can press again and start\n // playback — and then the original timer fires, calls back into\n // `speakWith` for the same message, and the engine cancels and restarts it\n // mid-sentence. Retire the waiter as part of adopting the list.\n if (available.length > 0) cancelPending();\n setVoices(available);\n setVoiceProbeSettled(false);\n // Same reason the `voiceschanged` path clears them: every refusal meant\n // \"no voice for this language\", and this is the moment a user who went\n // away to install one comes back. `subscribeVoices` does not fire on an\n // eventless engine, which is precisely why this re-probe exists — so it\n // has to expire the refusals too.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n document.addEventListener('visibilitychange', reprobe);\n window.addEventListener('focus', reprobe);\n return () => {\n document.removeEventListener('visibilitychange', reprobe);\n window.removeEventListener('focus', reprobe);\n };\n }, [cancelPending, engine, isSupported]);\n\n // ── Opt-in auto-speak ────────────────────────────────────────────────────\n const speakRef = useRef(speak);\n useEffect(() => {\n speakRef.current = speak;\n }, [speak]);\n\n useEffect(() => {\n // `isBlocked` is the same gate the per-message button uses. Without it the\n // subscription fires on a device with no voice for the app language and the\n // engine reads a Tamil reply in English — the one thing this feature says\n // it will never do. `pending` is allowed through because `speakWith` waits\n // for the list before deciding.\n // NOT gated on `isSpeechBlocked(availability)` any more: that is the APP\n // language's availability, and it would suppress auto-speak for a reply in\n // a language this device CAN speak. `speakWith` resolves the reply's own\n // language and refuses safely there, which is the only place that can know.\n // Either the user's own preference, or a live voice session — which speaks\n // by definition and must not have to change that preference to do it.\n if ((!autoSpeakEnabled && !sessionSpeaking) || !visible || !isSupported) return;\n\n // Deliberately a store subscription keyed on the processing TRANSITION\n // rather than an effect over the message list: it fires only on the\n // in-flight → complete edge of the active conversation, so mounting the\n // panel, loading history or switching chats can never start talking.\n return useAssistantStore.subscribe((next, previous) => {\n const conversationId = next.activeConversationId;\n if (!conversationId || conversationId !== previous.activeConversationId) return;\n\n const current = next.processingByConversationId[conversationId];\n const before = previous.processingByConversationId[conversationId];\n if (current?.status !== 'complete' || !isTurnInFlight(before?.status)) return;\n\n const messageId = current.messageId ?? before?.messageId ?? null;\n if (!messageId) return;\n\n const message = next.conversations\n .find((conversation) => conversation.id === conversationId)\n ?.messages.find((candidate) => candidate.id === messageId);\n if (!message || message.role !== 'assistant') return;\n\n // ★ Speak a turn only if it belongs to the surface currently doing the\n // speaking. This subscription IS the live session's audio path —\n // `useVoiceSession` never calls `speak` itself, it flips `sessionSpeaking`\n // and lets this fire — and it had no channel check, so a TYPED reply\n // completing mid-session was read aloud as the answer to a spoken\n // question. Reachable with no typing at all: a host page queues work\n // through `pendingPrompt`, which is store-driven and fires past the voice\n // overlay.\n //\n // The mirror case matters too: after End, a reply still in flight must not\n // be spoken by ordinary auto-read — the user closed the conversation.\n if (isVoiceTurn(message) !== sessionSpeaking) return;\n\n // Same split the transcript uses: speak the prose, not the tool log.\n const { text } = parseToolActivity(message.content);\n if (!text.trim()) return;\n\n speakRef.current(messageId, text, (message.metadata as { lang?: string } | undefined)?.lang);\n });\n }, [autoSpeakEnabled, sessionSpeaking, isSupported, visible]);\n\n // The candidates for the language the user SPEAKS — the picker is a setting,\n // so it must not follow whatever language the last reply happened to be in.\n const voiceChoices = useMemo(() => voicesForLocale(voices, spokenLanguage.tag), [voices, spokenLanguage]);\n const activeVoice = useMemo(\n () => selectVoiceForLocale(voices, spokenLanguage.tag, preferredVoices[spokenLocale]),\n [voices, spokenLanguage, preferredVoices, spokenLocale]\n );\n\n const value = useMemo<AssistantSpeechContextValue>(\n () => ({\n isSupported,\n availability,\n // ONLY `no-voices` — a device with no voices at all can never speak\n // anything. `missing-voice` means the APP language has none, which says\n // nothing about the language a given reply came back in; that case is\n // resolved per message by `blockedFor`.\n isBlocked: availability === 'no-voices',\n // Both blocked states are the user's device, not our bug — so the copy\n // names the language and says where to fix it. \"Nothing happened\" was\n // the old behaviour and it read as a broken feature.\n disabledReason:\n availability === 'no-voices'\n ? tr(\n 'healthybowl.assistant.speech.noVoicesOnDevice',\n 'This device has no speech voices installed. Add one in your device speech or accessibility settings.'\n )\n : null,\n blockedFor,\n voiceChoices,\n spokenChunks: spokenProgress ? { chunks: spokenProgress.chunks, index: spokenProgress.index } : null,\n activeVoiceName: activeVoice?.name ?? null,\n preferredVoiceName: preferredVoices[spokenLocale] ?? null,\n setVoice: (voiceName: string | null) => setPreferredVoice(spokenLocale, voiceName),\n speakingMessageId: playback.status === 'speaking' ? playback.messageId : null,\n isSpeaking: (messageId: string) => isSpeakingMessage(playback, messageId),\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n setSessionSpeaking,\n previewVoice,\n }),\n [\n isSupported,\n availability,\n blockedFor,\n voiceChoices,\n activeVoice,\n preferredVoices,\n setPreferredVoice,\n spokenLocale,\n playback,\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n previewVoice,\n tr,\n ]\n );\n\n return <AssistantSpeechContext.Provider value={value}>{children}</AssistantSpeechContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsDA,IAAM,KAAiC;CACrC,WAAW;CACX,OAAO;CACP,MAAM;CACN,YAAY;CACZ,WAAW;CACX,SAAS;CACT,UAAU;CACV,YAAY;AACd,GA6HM,KAAyB,EAA2C;CArBxE,aAAa;CACb,cAAc;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U,CAAS;EACxE;EACA;EACA;EACA;EACA;EACA;EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,OAAO,mBAAC,GAAuB,UAAxB;EAAwC;EAAQ;CAA0C,CAAA;AACnG"}
1
+ {"version":3,"file":"AssistantSpeechProvider.js","names":[],"sources":["../../../src/components/assistant/AssistantSpeechProvider.tsx"],"sourcesContent":["/**\n * Speech-output context for the assistant panel (BOFF-6290).\n *\n * The assistant could already hear (`useVoiceInput`); this is the other half —\n * it can now answer out loud. That matters for a farming product where the user\n * is outdoors with dirty hands, a phone in a pocket and sun on the screen, and\n * it is a plain accessibility win everywhere else.\n *\n * Everything stateful about playback lives here, once, so that:\n *\n * - **playback is never orphaned.** A voice that keeps talking after the UI is\n * gone is a bug, so speech is cancelled when the panel hides, when the\n * conversation changes, on unmount, and on `pagehide` (Chrome keeps speaking\n * across a navigation otherwise);\n * - **only one message speaks at a time.** Starting a new playback cancels the\n * previous one — enforced by the engine and by the request-id guard in\n * `speechPlaybackReducer`;\n * - **nothing ever autoplays.** Playback starts from a button press. The\n * persisted auto-speak preference defaults OFF and is opt-in from the header.\n *\n * Components consume this through `useAssistantSpeech()`, which falls back to an\n * inert value when there is no provider (Storybook, a header rendered on its\n * own) rather than throwing.\n */\n\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useReducer,\n useRef,\n useState,\n type FC,\n type ReactNode,\n} from 'react';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { voicePreviewText } from '@/utils/voicePreview';\nimport { getSpeechEngine } from '../../services/speech';\nimport type { SpeechEngine, SpeechVoiceLike } from '../../services/speech';\nimport { chunkForSpeech, toSpeakableText, type SpeakableLabels } from '../../utils/speakableText';\nimport { speechLabelsFor } from '../../config/speechLabels';\n\n/**\n * The speakable transformation with nothing of ours added — used ONLY to decide\n * the reply's language.\n *\n * Detection needs the prose that will be spoken: code blocks and URLs stripped\n * (they are never read aloud, and their Latin identifiers would outvote short\n * non-Latin prose), but no substitute wording introduced either (that would let\n * our own app-locale words vote instead).\n */\nconst SILENT_LABELS: SpeakableLabels = {\n codeBlock: '',\n image: '',\n link: '',\n largeTable: '',\n truncated: '',\n emailAt: 'at',\n emailDot: 'dot',\n nestedItem: '',\n};\nimport {\n VOICE_LIST_TIMEOUT_MS,\n languageDisplayName,\n selectVoiceForLocale,\n voicesForLocale,\n speechGate,\n speechLangForLocale,\n voiceAvailability,\n type VoiceAvailability,\n} from '../../utils/speechVoices';\nimport { resolveSpeechLocale } from '../../utils/replyLanguage';\nimport { DEFAULT_SPEECH_RATE, findAssistantLanguage } from '../../config/assistantLanguages';\nimport { resolveLanguagePair } from '../../config/assistantLanguagePair';\nimport { IDLE_PLAYBACK, isSpeakingMessage, speechPlaybackReducer } from '../../utils/speechPlayback';\nimport { isVoiceTurn } from '../../utils/voiceTurnVisibility';\nimport { isTurnInFlight } from '../../utils/assistantTurnState';\nimport { parseToolActivity } from './AssistantToolActivity';\nimport { useAssistantTr } from '@burdenoff/fe-libs/shared/assistant';\n\nexport interface AssistantSpeechContextValue {\n /** False when the platform has no speech output — hide the control entirely. */\n isSupported: boolean;\n availability: VoiceAvailability;\n /**\n * True when nothing can be spoken in the app language, so every control that\n * starts playback — the per-message button AND the header toggle — must be\n * inert. `pending` is not blocked: see `speechGate`.\n */\n isBlocked: boolean;\n /** Explains a disabled control (no installed voice for the app language). */\n disabledReason: string | null;\n /**\n * Why THIS message cannot be spoken, when the app language is fine but the\n * reply is not in it — a Tamil answer in an English UI on a device with no\n * Tamil voice. `isBlocked` cannot see that: it is computed before any reply\n * exists. Without this the control looks enabled and silently refuses, which\n * is the dead-button bug all over again (BOFF-7106).\n */\n blockedFor: (messageId: string) => string | null;\n /**\n * Every installed voice that can read the language the user speaks, best\n * first. Empty when there is no choice to offer — the picker hides itself\n * rather than showing a one-item dropdown.\n */\n voiceChoices: readonly SpeechVoiceLike[];\n /** The voice that will actually be used, resolved from the pick + ranking. */\n /**\n * The reply as it is being SPOKEN: every chunk, plus the one sounding now.\n *\n * `null` when nothing is playing. `index: -1` means chunked but not yet\n * audible. Consumers reveal `chunks[0..index]` — anything beyond that is the\n * caption running ahead of the voice.\n */\n spokenChunks: { chunks: string[]; index: number } | null;\n activeVoiceName: string | null;\n /**\n * The RAW stored pick: `null` means \"use the ranked default\".\n *\n * The picker must be driven by this rather than by `activeVoiceName`, or the\n * two states collapse — with nothing stored, the ranked winner is already the\n * shown option, so choosing it fires no change event and the pick can never\n * be made. The user's voice would then silently move the next time the device\n * installs a higher-ranked one. Same trap as the language selector.\n */\n preferredVoiceName: string | null;\n /** `null` restores the ranked default for the current language. */\n setVoice: (voiceName: string | null) => void;\n /** The message currently being spoken, if any. */\n speakingMessageId: string | null;\n isSpeaking: (messageId: string) => boolean;\n /**\n * Speak this message, or stop if it is already the one speaking.\n *\n * `turnLocale` is the language the reply was GENERATED under, from the\n * message's own metadata. It matters because script detection cannot separate\n * Latin-script languages, so without it an old French reply would be read\n * with whatever voice the CURRENT preference selects.\n */\n toggle: (messageId: string, markdown: string, turnLocale?: string) => void;\n stop: () => void;\n autoSpeakEnabled: boolean;\n setAutoSpeak: (enabled: boolean) => void;\n /**\n * Speak replies for the duration of a live voice session, WITHOUT touching the\n * user's saved preference.\n *\n * ★ Live Voice used to force `autoSpeakEnabled` true and restore it on exit.\n * That field is PERSISTED (assistantStore partialize), and the restore only\n * ran on a clean `end()` — so a reload, a closed tab or a backgrounded webview\n * during a session left auto-speak switched ON for the user permanently, in\n * normal typed chat, with the toggle showing a state they never chose. The\n * default was never wrong; the session was overwriting it.\n *\n * Session-scoped React state instead: it cannot outlive the page, so there is\n * nothing to restore and nothing to leak.\n */\n sessionSpeaking: boolean;\n setSessionSpeaking: (enabled: boolean) => void;\n /** Play a short sample in a named voice. No model call, no message, no tokens. */\n previewVoice: (voiceName: string) => void;\n}\n\nconst INERT_SPEECH: AssistantSpeechContextValue = {\n isSupported: false,\n availability: 'unsupported',\n isBlocked: true,\n disabledReason: null,\n blockedFor: () => null,\n voiceChoices: [],\n spokenChunks: null,\n activeVoiceName: null,\n preferredVoiceName: null,\n setVoice: () => {},\n speakingMessageId: null,\n isSpeaking: () => false,\n toggle: () => {},\n stop: () => {},\n autoSpeakEnabled: false,\n setAutoSpeak: () => {},\n sessionSpeaking: false,\n setSessionSpeaking: () => {},\n previewVoice: () => {},\n};\n\nconst AssistantSpeechContext = createContext<AssistantSpeechContextValue>(INERT_SPEECH);\n\nexport function useAssistantSpeech(): AssistantSpeechContextValue {\n return useContext(AssistantSpeechContext);\n}\n\ninterface Props {\n children: ReactNode;\n /** Panel visibility. Hiding the panel stops the voice. */\n visible?: boolean;\n /**\n * Injectable for tests and local experiments. The default routes between the\n * device engine and the hosted one; with hosted TTS unconfigured it IS the\n * device engine, unchanged.\n */\n engine?: SpeechEngine;\n}\n\nexport const AssistantSpeechProvider: FC<Props> = ({ children, visible = true, engine = getSpeechEngine() }) => {\n const tr = useAssistantTr();\n const { locale } = useI18n();\n const [playback, dispatch] = useReducer(speechPlaybackReducer, IDLE_PLAYBACK);\n const [voices, setVoices] = useState<SpeechVoiceLike[]>(() => engine.listVoices());\n /**\n * True once we have waited out the voice list and it was still empty.\n *\n * Turns an indefinite `pending` into a terminal `no-voices`, which is what\n * lets the control be disabled with a reason instead of silently doing\n * nothing on every press.\n */\n const [voiceProbeSettled, setVoiceProbeSettled] = useState(false);\n /**\n * Every message we have refused, and why — keyed by id (see `blockedFor`).\n *\n * A single record could only describe one refusal: refusing a second reply\n * silently re-enabled the first, whose voice was still just as missing, so\n * pressing the buttons walked the disabled state around the transcript.\n */\n const [unspeakable, setUnspeakable] = useState<ReadonlyMap<string, string>>(() => new Map());\n const requestRef = useRef(0);\n\n /**\n * Which chunk of the current reply is sounding right now.\n *\n * ★ `index: -1` means \"chunked, nothing playing yet\" — distinct from no\n * progress at all, so the caption can stay empty until audio genuinely starts\n * instead of flashing the first sentence while the engine is still fetching.\n */\n const [spokenProgress, setSpokenProgress] = useState<{\n requestId: number;\n chunks: string[];\n index: number;\n } | null>(null);\n /** Cancels a playback that is waiting for the engine's voice list, if any. */\n const pendingRef = useRef<(() => void) | null>(null);\n const speakWithRef = useRef<\n (messageId: string, text: string, voices: readonly SpeechVoiceLike[], speechLocale: string) => void\n >(() => {});\n\n const cancelPending = useCallback(() => {\n pendingRef.current?.();\n pendingRef.current = null;\n }, []);\n\n const autoSpeakEnabled = useAssistantStore((state) => state.autoSpeakEnabled);\n const setAutoSpeak = useAssistantStore((state) => state.setAutoSpeak);\n // Not in the store on purpose — see `sessionSpeaking` on the context type.\n const [sessionSpeaking, setSessionSpeaking] = useState(false);\n const activeConversationId = useAssistantStore((state) => state.activeConversationId);\n\n const isSupported = useMemo(() => engine.isSupported(), [engine]);\n\n // getVoices() is empty on the first call in Chrome and only fills in when\n // 'voiceschanged' fires; Safari populates it synchronously and may never fire\n // the event. Read eagerly AND subscribe, so both engines end up correct.\n useEffect(() => {\n if (!isSupported) return;\n const sync = () => {\n setVoices(engine.listVoices());\n // Every recorded refusal was \"no voice for this language\". A new voice\n // list may well have supplied one — most likely because the user just\n // followed our instructions and installed it. Keeping the refusals would\n // leave those buttons disabled with no way back except a reload.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n sync();\n return engine.subscribeVoices(sync);\n }, [engine, isSupported]);\n\n // The language being SPOKEN ALOUD — which is the language of the reply, not\n // of the input and not of the interface. The two were one field until the\n // reply language was split out (BOFF-7108).\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const replyLanguage = useAssistantStore((state) => state.replyLanguage);\n const preferredVoices = useAssistantStore((state) => state.preferredVoices);\n const setPreferredVoice = useAssistantStore((state) => state.setPreferredVoice);\n const spokenLanguage = useMemo(\n // ★ The REPLY language, not the input. This is the language of the text\n // being spoken, so wiring it to the input would give a Tamil voice reading\n // an English answer the moment the two are set differently — the single\n // worst outcome available here, and the reason they were split at all.\n () => resolveLanguagePair(assistantLanguage, replyLanguage, locale).reply,\n [assistantLanguage, replyLanguage, locale]\n );\n const spokenLocale = spokenLanguage.code;\n\n /**\n * BCP-47 tag to ask the engine for, given a resolved language CODE.\n *\n * Resolved through the catalogue for ANY known code, not merely the currently\n * selected one — a historical Bengali reply must still get `bn-IN` after the\n * user switches to Tamil, or with both `bn-IN` and `bn-BD` installed the\n * engine's own order decides, and picks the wrong country.\n *\n * Falls back to the generic table for codes the catalogue does not carry.\n */\n const tagFor = useCallback((code: string) => findAssistantLanguage(code)?.tag ?? speechLangForLocale(code), []);\n\n /** Speaking rate for a resolved language code — see `AssistantLanguage.rate`. */\n const rateFor = useCallback((code: string) => findAssistantLanguage(code)?.rate ?? DEFAULT_SPEECH_RATE, []);\n\n const availability = useMemo(\n () => voiceAvailability(isSupported, voices, spokenLanguage.tag, voiceProbeSettled),\n [isSupported, voices, spokenLanguage, voiceProbeSettled]\n );\n\n // Spoken placeholders follow the app locale like the rest of the copy; the\n // transformation itself stays a pure function by taking them as arguments.\n const labels = useMemo<SpeakableLabels>(\n () => ({\n codeBlock: tr('speech.codeBlock', 'Code block'),\n image: tr('speech.image', 'image'),\n link: tr('speech.link', 'link'),\n largeTable: tr('speech.largeTable', 'Table with {{rows}} rows and {{columns}} columns'),\n truncated: tr('speech.truncated', 'The rest of this message is not read aloud'),\n nestedItem: tr('speech.nestedItem', 'Sub-item {{ordinal}}'),\n emailAt: tr('speech.emailAt', 'at'),\n emailDot: tr('speech.emailDot', 'dot'),\n }),\n [tr]\n );\n\n const stop = useCallback(() => {\n cancelPending();\n engine.cancel();\n dispatch({ type: 'stop' });\n }, [cancelPending, engine]);\n\n /**\n * Audition a voice — no model call, no message, no tokens.\n *\n * ★ Speaks through the engine DIRECTLY rather than through `speakWith`. That\n * path is built around a message: it resolves the reply's language, records\n * per-message \"cannot speak this\" state, and drives `speakingMessageId` so a\n * Listen button can light up. A preview has no message, so borrowing it would\n * mean inventing a fake id and then teaching every consumer to ignore it.\n *\n * Consequently it deliberately does NOT touch playback state: auditioning a\n * voice must not make a Listen button in the thread appear to be playing.\n *\n * Speaks the sample in the language being spoken, not the interface language —\n * the listener is judging how this voice reads THAT language.\n */\n const previewVoice = useCallback(\n (voiceName: string) => {\n const voice = engine.listVoices().find((candidate) => candidate.name === voiceName) ?? null;\n // An unknown name means the list changed under us (a download finished, a\n // profile switched). Silence is the right answer — better than falling\n // back to some other voice and auditioning the wrong one.\n if (!voice) return;\n // Whatever is speaking now is not what the user asked to hear.\n stop();\n engine.speak([voicePreviewText(spokenLocale)], { voice, lang: tagFor(spokenLocale) });\n },\n [engine, spokenLocale, stop, tagFor]\n );\n\n const blockedFor = useCallback((messageId: string) => unspeakable.get(messageId) ?? null, [unspeakable]);\n\n /**\n * Hold one playback until the engine publishes its voice list.\n *\n * Bounded: on timeout we take one last look and decide with whatever is\n * there, so an engine that never fires `voiceschanged` costs a two-second\n * wait rather than a control that is disabled forever. Nothing is spoken from\n * here unless a list actually arrives — an empty list means the engine would\n * pick its own default voice, which is the cross-language read this feature\n * promises never to do.\n */\n const waitForVoices = useCallback(\n (messageId: string, text: string, speechLocale: string) => {\n cancelPending();\n\n let settled = false;\n let unsubscribe = () => {};\n const finish = (available: SpeechVoiceLike[]) => {\n if (settled) return;\n settled = true;\n pendingRef.current = null;\n clearTimeout(timer);\n unsubscribe();\n if (available.length === 0) {\n // We waited and looked again: this device has no voices at all.\n // Record it so `availability` becomes `no-voices` and the control\n // explains itself, instead of returning silently every press.\n setVoiceProbeSettled(true);\n return;\n }\n setVoices(available);\n speakWithRef.current(messageId, text, available, speechLocale);\n };\n\n const timer = setTimeout(() => finish(engine.listVoices()), VOICE_LIST_TIMEOUT_MS);\n unsubscribe = engine.subscribeVoices(() => finish(engine.listVoices()));\n\n pendingRef.current = () => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n unsubscribe();\n pendingRef.current = null;\n };\n },\n [cancelPending, engine]\n );\n\n /**\n * Speak text against a KNOWN voice list.\n *\n * Every playback path funnels through here — the per-message button, the\n * header toggle's auto-speak, the store subscription — so the language gate\n * cannot be bypassed by any of them. Reading a Tamil reply with an English\n * voice is confident nonsense; it has to be impossible, not merely unlikely.\n */\n const speakWith = useCallback(\n (messageId: string, text: string, available: readonly SpeechVoiceLike[], speechLocale: string) => {\n let known = available;\n\n // Chrome answers the FIRST getVoices() with [] and fills the list in\n // asynchronously. One more synchronous read usually settles it.\n if (known.length === 0) {\n const refreshed = engine.listVoices();\n if (refreshed.length > 0) {\n known = refreshed;\n setVoices(refreshed);\n }\n }\n\n const speechLang = tagFor(speechLocale);\n\n const gate = speechGate(voiceAvailability(true, known, speechLocale, voiceProbeSettled));\n if (gate === 'block') {\n // Recorded for THIS message, always. Availability is resolved per reply\n // now, so a global \"your language has no voice\" cannot stand in for it:\n // the language the user chose to converse in says nothing about the one\n // this particular reply came back in.\n const reason = tr(\n 'speech.noVoiceForReply',\n 'This reply is in {{language}}, and no {{language}} voice is installed on this device.',\n { language: languageDisplayName(speechLang, locale) }\n );\n setUnspeakable((current) => new Map(current).set(messageId, reason));\n return;\n }\n if (gate === 'wait-for-voices') {\n waitForVoices(messageId, text, speechLocale);\n return;\n }\n\n setUnspeakable((current) => {\n if (!current.has(messageId)) return current;\n const next = new Map(current);\n next.delete(messageId);\n return next;\n });\n\n const requestId = requestRef.current + 1;\n requestRef.current = requestId;\n dispatch({ type: 'start', messageId, requestId });\n\n // ★ Chunked ONCE and kept, so the caption can show exactly what is being\n // spoken rather than a parallel rendering of the same markdown. A live\n // caption whose words differ from the audio is not a caption.\n const chunks = chunkForSpeech(text);\n setSpokenProgress({ requestId, chunks, index: -1 });\n\n engine.speak(\n chunks,\n // The TAG, not the code — so exact regional matching gets its chance\n // before the same-language fallback. `rate` had never been passed at\n // all, so every reply was read at the engine default.\n {\n voice: selectVoiceForLocale(known, speechLang, preferredVoices[speechLocale]),\n lang: speechLang,\n rate: rateFor(speechLocale),\n },\n {\n // Guarded on the request id like every other handler here: a stale\n // batch that has not noticed its cancellation must not drive the\n // caption of the reply that replaced it.\n onChunkStart: (index) =>\n setSpokenProgress((current) => (current?.requestId === requestId ? { ...current, index } : current)),\n onEnd: () => dispatch({ type: 'finished', requestId }),\n // Includes the 'cancelled' every queued utterance reports when we\n // pre-empt a batch; the request-id guard drops those as stale.\n onError: () => dispatch({ type: 'failed', requestId }),\n }\n );\n },\n [engine, locale, preferredVoices, rateFor, tagFor, tr, voiceProbeSettled, waitForVoices]\n );\n\n // `waitForVoices` resumes through this ref, so the two do not become a\n // circular hook dependency.\n useEffect(() => {\n speakWithRef.current = speakWith;\n }, [speakWith]);\n\n const speak = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (!isSupported) return;\n\n // Resolve the reply's language BEFORE building the spoken text, because\n // the stand-in words must be in that language. Detection deliberately runs\n // on a SILENT_LABELS pass — our own words must not vote on which language\n // the reply is in — so it does not depend on the labels chosen here.\n const replyLocale = resolveSpeechLocale(\n toSpeakableText(markdown, { labels: SILENT_LABELS }),\n turnLocale ?? spokenLocale\n );\n\n // ★ Labels in the REPLY's language, not the interface's. An English\n // interface reading a Tamil answer used to say \"Code block\" and \"image\" in\n // English, mid-Tamil-sentence — the same defect the email `at`/`dot` fix\n // addressed and did not generalise.\n const text = toSpeakableText(markdown, { labels: speechLabelsFor(replyLocale, labels) });\n if (!text) return;\n\n // Detect on the text that will actually be SPOKEN, with our own words\n // removed — neither the raw markdown nor the finished transformation.\n //\n // The transformation injects app-locale placeholders (\"Code block\"), which\n // let English chrome outvote short non-Latin prose. The raw markdown keeps\n // fenced code, whose Latin identifiers do the same thing — and that code is\n // never spoken at all. Running the same transformation with EMPTY labels\n // strips the unspoken constructs while contributing no words of its own,\n // which is exactly the denominator the decision needs.\n // The turn's OWN language first — the preference is only a stand-in for\n // replies that predate it. Resolved above, and reused rather than\n // recomputed.\n speakWith(messageId, text, voices, replyLocale);\n },\n [isSupported, labels, spokenLocale, speakWith, voices]\n );\n\n const toggle = useCallback(\n (messageId: string, markdown: string, turnLocale?: string) => {\n if (isSpeakingMessage(playback, messageId)) {\n stop();\n return;\n }\n speak(messageId, markdown, turnLocale);\n },\n [playback, speak, stop]\n );\n\n // ── Never leave a voice talking to an empty room ─────────────────────────\n useEffect(() => {\n if (!visible) stop();\n }, [visible, stop]);\n\n useEffect(() => {\n // Switching (or creating) a conversation abandons the reply being read —\n // and the refusal explained a message that is no longer on screen.\n stop();\n setUnspeakable(new Map());\n }, [activeConversationId, stop]);\n\n useEffect(() => {\n // Every refusal was decided against the locale in force at the time, which\n // is what a Latin-script reply falls back to. Change the locale and those\n // verdicts may simply be wrong — an English reply refused on a\n // Spanish-only device would stay disabled forever after switching the UI to\n // Spanish, with the voice that could read it already installed.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n // And stop anything mid-sentence. The new language can make this message\n // unspeakable, which disables its button — leaving it reading \"Stop\" with no\n // way to actually stop, short of closing the panel.\n stop();\n }, [spokenLocale, stop]);\n\n useEffect(() => {\n return () => {\n pendingRef.current?.();\n pendingRef.current = null;\n engine.cancel();\n };\n }, [engine]);\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n // Chrome carries speech across a same-tab navigation and a bfcache restore\n // would otherwise come back mid-sentence.\n const handlePageHide = () => engine.cancel();\n window.addEventListener('pagehide', handlePageHide);\n return () => window.removeEventListener('pagehide', handlePageHide);\n }, [engine]);\n\n // ── One timeout is not a life sentence ───────────────────────────────────\n //\n // `no-voices` disables the control, and a disabled control can never reach\n // `speakWith` — the only path that re-reads `engine.listVoices()`. So without\n // this, a user who follows our own advice, leaves to install a voice and comes\n // back stays blocked until a reload: we would be telling them how to fix it\n // and then refusing to notice that they had.\n //\n // Returning to the tab is exactly when that happens, and it costs one\n // synchronous read of an already-populated list.\n useEffect(() => {\n if (typeof document === 'undefined' || !isSupported) return;\n const reprobe = () => {\n if (document.visibilityState !== 'visible') return;\n // Adopt the list UNCONDITIONALLY, including an empty one. Keeping the old\n // cache on an empty read means a user who uninstalled their last voice\n // stays `ready`, and playback then hands the engine a voice object that no\n // longer exists instead of explaining the problem.\n //\n // Safe to accept an empty read here precisely because the probe verdict is\n // cleared on the next line: empty + unsettled is `pending`, which leaves\n // the control ENABLED and defers the real decision to the next press.\n const available = engine.listVoices();\n // A Listen press may still be inside its two-second wait. Adopting voices\n // here flips the control to `ready`, so the user can press again and start\n // playback — and then the original timer fires, calls back into\n // `speakWith` for the same message, and the engine cancels and restarts it\n // mid-sentence. Retire the waiter as part of adopting the list.\n if (available.length > 0) cancelPending();\n setVoices(available);\n setVoiceProbeSettled(false);\n // Same reason the `voiceschanged` path clears them: every refusal meant\n // \"no voice for this language\", and this is the moment a user who went\n // away to install one comes back. `subscribeVoices` does not fire on an\n // eventless engine, which is precisely why this re-probe exists — so it\n // has to expire the refusals too.\n setUnspeakable((current) => (current.size === 0 ? current : new Map()));\n };\n document.addEventListener('visibilitychange', reprobe);\n window.addEventListener('focus', reprobe);\n return () => {\n document.removeEventListener('visibilitychange', reprobe);\n window.removeEventListener('focus', reprobe);\n };\n }, [cancelPending, engine, isSupported]);\n\n // ── Opt-in auto-speak ────────────────────────────────────────────────────\n const speakRef = useRef(speak);\n useEffect(() => {\n speakRef.current = speak;\n }, [speak]);\n\n useEffect(() => {\n // `isBlocked` is the same gate the per-message button uses. Without it the\n // subscription fires on a device with no voice for the app language and the\n // engine reads a Tamil reply in English — the one thing this feature says\n // it will never do. `pending` is allowed through because `speakWith` waits\n // for the list before deciding.\n // NOT gated on `isSpeechBlocked(availability)` any more: that is the APP\n // language's availability, and it would suppress auto-speak for a reply in\n // a language this device CAN speak. `speakWith` resolves the reply's own\n // language and refuses safely there, which is the only place that can know.\n // Either the user's own preference, or a live voice session — which speaks\n // by definition and must not have to change that preference to do it.\n if ((!autoSpeakEnabled && !sessionSpeaking) || !visible || !isSupported) return;\n\n // Deliberately a store subscription keyed on the processing TRANSITION\n // rather than an effect over the message list: it fires only on the\n // in-flight → complete edge of the active conversation, so mounting the\n // panel, loading history or switching chats can never start talking.\n return useAssistantStore.subscribe((next, previous) => {\n const conversationId = next.activeConversationId;\n if (!conversationId || conversationId !== previous.activeConversationId) return;\n\n const current = next.processingByConversationId[conversationId];\n const before = previous.processingByConversationId[conversationId];\n if (current?.status !== 'complete' || !isTurnInFlight(before?.status)) return;\n\n const messageId = current.messageId ?? before?.messageId ?? null;\n if (!messageId) return;\n\n const message = next.conversations\n .find((conversation) => conversation.id === conversationId)\n ?.messages.find((candidate) => candidate.id === messageId);\n if (!message || message.role !== 'assistant') return;\n\n // ★ Speak a turn only if it belongs to the surface currently doing the\n // speaking. This subscription IS the live session's audio path —\n // `useVoiceSession` never calls `speak` itself, it flips `sessionSpeaking`\n // and lets this fire — and it had no channel check, so a TYPED reply\n // completing mid-session was read aloud as the answer to a spoken\n // question. Reachable with no typing at all: a host page queues work\n // through `pendingPrompt`, which is store-driven and fires past the voice\n // overlay.\n //\n // The mirror case matters too: after End, a reply still in flight must not\n // be spoken by ordinary auto-read — the user closed the conversation.\n if (isVoiceTurn(message) !== sessionSpeaking) return;\n\n // Same split the transcript uses: speak the prose, not the tool log.\n const { text } = parseToolActivity(message.content);\n if (!text.trim()) return;\n\n speakRef.current(messageId, text, (message.metadata as { lang?: string } | undefined)?.lang);\n });\n }, [autoSpeakEnabled, sessionSpeaking, isSupported, visible]);\n\n // The candidates for the language the user SPEAKS — the picker is a setting,\n // so it must not follow whatever language the last reply happened to be in.\n const voiceChoices = useMemo(() => voicesForLocale(voices, spokenLanguage.tag), [voices, spokenLanguage]);\n const activeVoice = useMemo(\n () => selectVoiceForLocale(voices, spokenLanguage.tag, preferredVoices[spokenLocale]),\n [voices, spokenLanguage, preferredVoices, spokenLocale]\n );\n\n const value = useMemo<AssistantSpeechContextValue>(\n () => ({\n isSupported,\n availability,\n // ONLY `no-voices` — a device with no voices at all can never speak\n // anything. `missing-voice` means the APP language has none, which says\n // nothing about the language a given reply came back in; that case is\n // resolved per message by `blockedFor`.\n isBlocked: availability === 'no-voices',\n // Both blocked states are the user's device, not our bug — so the copy\n // names the language and says where to fix it. \"Nothing happened\" was\n // the old behaviour and it read as a broken feature.\n disabledReason:\n availability === 'no-voices'\n ? tr(\n 'speech.noVoicesOnDevice',\n 'This device has no speech voices installed. Add one in your device speech or accessibility settings.'\n )\n : null,\n blockedFor,\n voiceChoices,\n spokenChunks: spokenProgress ? { chunks: spokenProgress.chunks, index: spokenProgress.index } : null,\n activeVoiceName: activeVoice?.name ?? null,\n preferredVoiceName: preferredVoices[spokenLocale] ?? null,\n setVoice: (voiceName: string | null) => setPreferredVoice(spokenLocale, voiceName),\n speakingMessageId: playback.status === 'speaking' ? playback.messageId : null,\n isSpeaking: (messageId: string) => isSpeakingMessage(playback, messageId),\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n setSessionSpeaking,\n previewVoice,\n }),\n [\n isSupported,\n availability,\n blockedFor,\n voiceChoices,\n activeVoice,\n preferredVoices,\n setPreferredVoice,\n spokenLocale,\n playback,\n toggle,\n stop,\n autoSpeakEnabled,\n setAutoSpeak,\n sessionSpeaking,\n previewVoice,\n tr,\n ]\n );\n\n return <AssistantSpeechContext.Provider value={value}>{children}</AssistantSpeechContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsDA,IAAM,KAAiC;CACrC,WAAW;CACX,OAAO;CACP,MAAM;CACN,YAAY;CACZ,WAAW;CACX,SAAS;CACT,UAAU;CACV,YAAY;AACd,GA6HM,KAAyB,EAA2C;CArBxE,aAAa;CACb,cAAc;CACd,WAAW;CACX,gBAAgB;CAChB,kBAAkB;CAClB,cAAc,CAAC;CACf,cAAc;CACd,iBAAiB;CACjB,oBAAoB;CACpB,gBAAgB,CAAC;CACjB,mBAAmB;CACnB,kBAAkB;CAClB,cAAc,CAAC;CACf,YAAY,CAAC;CACb,kBAAkB;CAClB,oBAAoB,CAAC;CACrB,iBAAiB;CACjB,0BAA0B,CA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"../../shared/hooks/useTr.js";
2
- import { AudioLines as t } from "lucide-react";
1
+ import { AudioLines as e } from "lucide-react";
2
+ import { useAssistantTr as t } from "@burdenoff/fe-libs/shared/assistant";
3
3
  import { jsx as n, jsxs as r } from "react/jsx-runtime";
4
4
  //#region src/components/assistant/AssistantSpokenTurnsNotice.tsx
5
5
  var i = ({ count: i, onOpenTranscript: a }) => {
6
- let o = e(), s = i === 1 ? o("healthybowl.assistant.spokenTurns.one", "1 spoken turn is kept out of this thread") : o("healthybowl.assistant.spokenTurns.many", "{{count}} spoken turns are kept out of this thread", { count: i });
6
+ let o = t(), s = i === 1 ? o("spokenTurns.one", "1 spoken turn is kept out of this thread") : o("spokenTurns.many", "{{count}} spoken turns are kept out of this thread", { count: i });
7
7
  return /* @__PURE__ */ r("div", {
8
8
  className: "flex items-center gap-2 border-b border-border-subtle bg-bg-sunken/60 px-3 py-2 text-xs",
9
9
  "data-testid": "assistant-spoken-turns-notice",
10
10
  children: [
11
- /* @__PURE__ */ n(t, {
11
+ /* @__PURE__ */ n(e, {
12
12
  className: "size-3.5 flex-shrink-0 text-text-secondary",
13
13
  "aria-hidden": "true"
14
14
  }),
@@ -22,7 +22,7 @@ var i = ({ count: i, onOpenTranscript: a }) => {
22
22
  onClick: a,
23
23
  className: "flex-shrink-0 rounded-md px-2 py-1 font-medium text-action-primary-bg transition-colors hover:bg-bg-elevated focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong",
24
24
  "data-testid": "assistant-open-transcript",
25
- children: o("healthybowl.assistant.spokenTurns.view", "View transcript")
25
+ children: o("spokenTurns.view", "View transcript")
26
26
  })
27
27
  ]
28
28
  });
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantSpokenTurnsNotice.js","names":[],"sources":["../../../src/components/assistant/AssistantSpokenTurnsNotice.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { AudioLines } from 'lucide-react';\nimport { useTr } from '../../shared/hooks/useTr';\n\ninterface Props {\n /** How many spoken turns this conversation holds. Never rendered at 0. */\n count: number;\n onOpenTranscript: () => void;\n}\n\n/**\n * \"You said things here that this thread is not showing you.\"\n *\n * ★ The assistant and the typed thread share ONE backend session, and the\n * client sends no history array — the model's memory IS that session. So a\n * spoken turn is in the model's context permanently, whether or not the chat\n * panel draws it. Hiding those turns without saying so produced the worst\n * possible combination: replies that open \"as I mentioned about your urea dose\"\n * with no such message anywhere on screen, and an Export button on a chat that\n * looks empty.\n *\n * The fix is not to hide harder. It is to stop the thread implying that what it\n * shows is everything it knows.\n *\n * ★ Deliberately NOT a message bubble. Putting spoken content back in the\n * timeline is the exact leak the split was built to stop; this is a pointer to\n * the other surface, and it carries a count rather than any spoken words.\n *\n * Renders above both the message list and the empty state, because the empty\n * state is where it matters most — a voice-only conversation otherwise reads as\n * \"nothing here\" while holding a full exchange.\n */\nexport const AssistantSpokenTurnsNotice: FC<Props> = ({ count, onOpenTranscript }) => {\n const tr = useTr();\n\n const label =\n count === 1\n ? tr('healthybowl.assistant.spokenTurns.one', '1 spoken turn is kept out of this thread')\n : tr('healthybowl.assistant.spokenTurns.many', '{{count}} spoken turns are kept out of this thread', {\n count,\n });\n\n return (\n <div\n className=\"flex items-center gap-2 border-b border-border-subtle bg-bg-sunken/60 px-3 py-2 text-xs\"\n data-testid=\"assistant-spoken-turns-notice\"\n >\n <AudioLines className=\"size-3.5 flex-shrink-0 text-text-secondary\" aria-hidden=\"true\" />\n <span className=\"min-w-0 flex-1 truncate text-text-secondary\" title={label}>\n {label}\n </span>\n <button\n type=\"button\"\n onClick={onOpenTranscript}\n className=\"flex-shrink-0 rounded-md px-2 py-1 font-medium text-action-primary-bg transition-colors hover:bg-bg-elevated focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong\"\n data-testid=\"assistant-open-transcript\"\n >\n {tr('healthybowl.assistant.spokenTurns.view', 'View transcript')}\n </button>\n </div>\n );\n};\n"],"mappings":";;;;AAgCA,IAAa,KAAyC,EAAE,UAAO,0BAAuB;CACpF,IAAM,IAAK,EAAM,GAEX,IACJ,MAAU,IACN,EAAG,yCAAyC,0CAA0C,IACtF,EAAG,0CAA0C,sDAAsD,EACjG,SACF,CAAC;CAEP,OACE,kBAAC,OAAD;EACE,WAAU;EACV,eAAY;YAFd;GAIE,kBAAC,GAAD;IAAY,WAAU;IAA6C,eAAY;GAAQ,CAAA;GACvF,kBAAC,QAAD;IAAM,WAAU;IAA8C,OAAO;cAClE;GACG,CAAA;GACN,kBAAC,UAAD;IACE,MAAK;IACL,SAAS;IACT,WAAU;IACV,eAAY;cAEX,EAAG,0CAA0C,iBAAiB;GACzD,CAAA;EACL;;AAET"}
1
+ {"version":3,"file":"AssistantSpokenTurnsNotice.js","names":[],"sources":["../../../src/components/assistant/AssistantSpokenTurnsNotice.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { AudioLines } from 'lucide-react';\nimport { useAssistantTr } from '@burdenoff/fe-libs/shared/assistant';\n\ninterface Props {\n /** How many spoken turns this conversation holds. Never rendered at 0. */\n count: number;\n onOpenTranscript: () => void;\n}\n\n/**\n * \"You said things here that this thread is not showing you.\"\n *\n * ★ The assistant and the typed thread share ONE backend session, and the\n * client sends no history array — the model's memory IS that session. So a\n * spoken turn is in the model's context permanently, whether or not the chat\n * panel draws it. Hiding those turns without saying so produced the worst\n * possible combination: replies that open \"as I mentioned about your urea dose\"\n * with no such message anywhere on screen, and an Export button on a chat that\n * looks empty.\n *\n * The fix is not to hide harder. It is to stop the thread implying that what it\n * shows is everything it knows.\n *\n * ★ Deliberately NOT a message bubble. Putting spoken content back in the\n * timeline is the exact leak the split was built to stop; this is a pointer to\n * the other surface, and it carries a count rather than any spoken words.\n *\n * Renders above both the message list and the empty state, because the empty\n * state is where it matters most — a voice-only conversation otherwise reads as\n * \"nothing here\" while holding a full exchange.\n */\nexport const AssistantSpokenTurnsNotice: FC<Props> = ({ count, onOpenTranscript }) => {\n const tr = useAssistantTr();\n\n const label =\n count === 1\n ? tr('spokenTurns.one', '1 spoken turn is kept out of this thread')\n : tr('spokenTurns.many', '{{count}} spoken turns are kept out of this thread', {\n count,\n });\n\n return (\n <div\n className=\"flex items-center gap-2 border-b border-border-subtle bg-bg-sunken/60 px-3 py-2 text-xs\"\n data-testid=\"assistant-spoken-turns-notice\"\n >\n <AudioLines className=\"size-3.5 flex-shrink-0 text-text-secondary\" aria-hidden=\"true\" />\n <span className=\"min-w-0 flex-1 truncate text-text-secondary\" title={label}>\n {label}\n </span>\n <button\n type=\"button\"\n onClick={onOpenTranscript}\n className=\"flex-shrink-0 rounded-md px-2 py-1 font-medium text-action-primary-bg transition-colors hover:bg-bg-elevated focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong\"\n data-testid=\"assistant-open-transcript\"\n >\n {tr('spokenTurns.view', 'View transcript')}\n </button>\n </div>\n );\n};\n"],"mappings":";;;;AAgCA,IAAa,KAAyC,EAAE,UAAO,0BAAuB;CACpF,IAAM,IAAK,EAAe,GAEpB,IACJ,MAAU,IACN,EAAG,mBAAmB,0CAA0C,IAChE,EAAG,oBAAoB,sDAAsD,EAC3E,SACF,CAAC;CAEP,OACE,kBAAC,OAAD;EACE,WAAU;EACV,eAAY;YAFd;GAIE,kBAAC,GAAD;IAAY,WAAU;IAA6C,eAAY;GAAQ,CAAA;GACvF,kBAAC,QAAD;IAAM,WAAU;IAA8C,OAAO;cAClE;GACG,CAAA;GACN,kBAAC,UAAD;IACE,MAAK;IACL,SAAS;IACT,WAAU;IACV,eAAY;cAEX,EAAG,oBAAoB,iBAAiB;GACnC,CAAA;EACL;;AAET"}
@@ -1,5 +1,5 @@
1
- import { useTr as e } from "../../shared/hooks/useTr.js";
2
- import { Check as t, Circle as n, Loader2 as r, Wrench as i, X as a } from "lucide-react";
1
+ import { Check as e, Circle as t, Loader2 as n, Wrench as r, X as i } from "lucide-react";
2
+ import { useAssistantTr as a } from "@burdenoff/fe-libs/shared/assistant";
3
3
  import { jsx as o, jsxs as s } from "react/jsx-runtime";
4
4
  //#region src/components/assistant/AssistantToolActivity.tsx
5
5
  var c = /^(Running|Completed|Failed):\s*(.+)$/, l = {
@@ -33,44 +33,44 @@ function d(e) {
33
33
  text: n.join("\n").trim()
34
34
  };
35
35
  }
36
- function f({ status: e }) {
37
- switch (e) {
38
- case "completed": return /* @__PURE__ */ o(t, {
36
+ function f({ status: r }) {
37
+ switch (r) {
38
+ case "completed": return /* @__PURE__ */ o(e, {
39
39
  className: "size-3.5 text-status-success-text",
40
40
  "aria-hidden": "true"
41
41
  });
42
- case "failed": return /* @__PURE__ */ o(a, {
42
+ case "failed": return /* @__PURE__ */ o(i, {
43
43
  className: "size-3.5 text-status-error-text",
44
44
  "aria-hidden": "true"
45
45
  });
46
- case "running": return /* @__PURE__ */ o(r, {
46
+ case "running": return /* @__PURE__ */ o(n, {
47
47
  className: "size-3.5 animate-spin text-action-primary-bg",
48
48
  "aria-hidden": "true"
49
49
  });
50
- default: return /* @__PURE__ */ o(n, {
50
+ default: return /* @__PURE__ */ o(t, {
51
51
  className: "size-3.5 text-text-muted",
52
52
  "aria-hidden": "true"
53
53
  });
54
54
  }
55
55
  }
56
- var p = ({ steps: t }) => {
57
- let n = e();
58
- if (t.length === 0) return null;
59
- let r = t.some((e) => e.status === "failed"), a = t.some((e) => e.status === "running" || e.status === "queued"), c = r ? n("healthybowl.assistant.tool.failed", "Some steps failed") : a ? n("healthybowl.assistant.tool.working", "Working on it…") : n("healthybowl.assistant.tool.done", "Done");
56
+ var p = ({ steps: e }) => {
57
+ let t = a();
58
+ if (e.length === 0) return null;
59
+ let n = e.some((e) => e.status === "failed"), i = e.some((e) => e.status === "running" || e.status === "queued"), c = n ? t("tool.failed", "Some steps failed") : i ? t("tool.working", "Working on it…") : t("tool.done", "Done");
60
60
  return /* @__PURE__ */ s("div", {
61
61
  className: "my-1.5 rounded-xl border border-border-subtle bg-bg-sunken px-3 py-2.5",
62
62
  "data-testid": "assistant-tool-activity",
63
63
  children: [
64
64
  /* @__PURE__ */ s("div", {
65
65
  className: "flex items-center gap-1.5 text-[12px] font-medium text-text-secondary",
66
- children: [/* @__PURE__ */ o(i, {
66
+ children: [/* @__PURE__ */ o(r, {
67
67
  className: "size-3.5 text-text-muted",
68
68
  "aria-hidden": "true"
69
69
  }), /* @__PURE__ */ o("span", { children: c })]
70
70
  }),
71
71
  /* @__PURE__ */ o("ul", {
72
72
  className: "mt-2 space-y-1.5",
73
- children: t.map((e) => /* @__PURE__ */ s("li", {
73
+ children: e.map((e) => /* @__PURE__ */ s("li", {
74
74
  className: "flex items-center gap-2 text-[13px] text-text-primary",
75
75
  children: [/* @__PURE__ */ o("span", {
76
76
  className: "flex size-3.5 flex-shrink-0 items-center justify-center",
@@ -85,10 +85,10 @@ var p = ({ steps: t }) => {
85
85
  className: "group mt-2",
86
86
  children: [/* @__PURE__ */ o("summary", {
87
87
  className: "cursor-pointer list-none text-[11px] text-text-muted transition-colors hover:text-text-secondary",
88
- children: n("healthybowl.assistant.tool.details", "Details")
88
+ children: t("tool.details", "Details")
89
89
  }), /* @__PURE__ */ o("ul", {
90
90
  className: "mt-1.5 space-y-0.5 border-t border-border-subtle pt-1.5",
91
- children: t.map((e) => /* @__PURE__ */ s("li", {
91
+ children: e.map((e) => /* @__PURE__ */ s("li", {
92
92
  className: "font-mono text-[11px] text-text-muted",
93
93
  children: [
94
94
  e.status,
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantToolActivity.js","names":[],"sources":["../../../src/components/assistant/AssistantToolActivity.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { Circle, Check, X, Loader2, Wrench } from 'lucide-react';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport type AssistantToolStepStatus = 'queued' | 'running' | 'completed' | 'failed';\n\nexport interface AssistantToolStep {\n /** Stable key within the message. */\n id: string;\n /** Humanised label shown in the step row. */\n label: string;\n /** Raw tool name (surfaced in the collapsed \"Details\"). */\n tool: string;\n status: AssistantToolStepStatus;\n}\n\n// AssistantChatArea's `getToolProgress` emits one line per tool part as\n// \"Running: <tool>\" / \"Completed: <tool>\" / \"Failed: <tool>\", which\n// `buildAssistantProgress` then joins into the streamed message content. We\n// re-parse those lines here so they render as a structured activity card\n// instead of plain text.\nconst TOOL_LINE = /^(Running|Completed|Failed):\\s*(.+)$/;\n\nconst STATUS_BY_VERB: Record<string, AssistantToolStepStatus> = {\n Running: 'running',\n Completed: 'completed',\n Failed: 'failed',\n};\n\n/** Turn a raw tool name (`graphql_query`, `read-file`) into a readable label. */\nfunction humaniseTool(tool: string): string {\n const spaced = tool.replace(/[_-]+/g, ' ').replace(/\\s+/g, ' ').trim();\n if (!spaced) return tool;\n return spaced.charAt(0).toUpperCase() + spaced.slice(1);\n}\n\n/**\n * Split streamed assistant content into its tool-progress steps and the\n * remaining prose. Called by AssistantMessageItem so the tool lines render as an\n * AssistantToolActivity card while the rest renders as markdown.\n */\nexport function parseToolActivity(content: string): { steps: AssistantToolStep[]; text: string } {\n if (!content.includes(':')) return { steps: [], text: content };\n\n const steps: AssistantToolStep[] = [];\n const rest: string[] = [];\n\n content.split('\\n').forEach((line, index) => {\n const match = line.match(TOOL_LINE);\n if (match) {\n const tool = match[2].trim();\n steps.push({\n id: `${index}-${tool}`,\n label: humaniseTool(tool),\n tool,\n status: STATUS_BY_VERB[match[1]] ?? 'running',\n });\n } else {\n rest.push(line);\n }\n });\n\n return { steps, text: rest.join('\\n').trim() };\n}\n\nfunction StepIcon({ status }: { status: AssistantToolStepStatus }) {\n switch (status) {\n case 'completed':\n return <Check className=\"size-3.5 text-status-success-text\" aria-hidden=\"true\" />;\n case 'failed':\n return <X className=\"size-3.5 text-status-error-text\" aria-hidden=\"true\" />;\n case 'running':\n return <Loader2 className=\"size-3.5 animate-spin text-action-primary-bg\" aria-hidden=\"true\" />;\n default:\n return <Circle className=\"size-3.5 text-text-muted\" aria-hidden=\"true\" />;\n }\n}\n\n/**\n * AssistantToolActivity — compact progress card for a turn's tool run (per the\n * ai-assistant-v2 \"tool-progress\" mockup). Renders each step in one of four\n * states (queued / running / completed / failed) with a hollow circle, spinner,\n * green check or red x, plus a collapsed \"Details\" listing the raw tool names.\n */\nexport const AssistantToolActivity: FC<{ steps: AssistantToolStep[] }> = ({ steps }) => {\n const tr = useTr();\n if (steps.length === 0) return null;\n\n const hasFailure = steps.some((step) => step.status === 'failed');\n const isRunning = steps.some((step) => step.status === 'running' || step.status === 'queued');\n const headline = hasFailure\n ? tr('healthybowl.assistant.tool.failed', 'Some steps failed')\n : isRunning\n ? tr('healthybowl.assistant.tool.working', 'Working on it…')\n : tr('healthybowl.assistant.tool.done', 'Done');\n\n return (\n <div\n className=\"my-1.5 rounded-xl border border-border-subtle bg-bg-sunken px-3 py-2.5\"\n data-testid=\"assistant-tool-activity\"\n >\n <div className=\"flex items-center gap-1.5 text-[12px] font-medium text-text-secondary\">\n <Wrench className=\"size-3.5 text-text-muted\" aria-hidden=\"true\" />\n <span>{headline}</span>\n </div>\n\n <ul className=\"mt-2 space-y-1.5\">\n {steps.map((step) => (\n <li key={step.id} className=\"flex items-center gap-2 text-[13px] text-text-primary\">\n <span className=\"flex size-3.5 flex-shrink-0 items-center justify-center\">\n <StepIcon status={step.status} />\n </span>\n <span className={step.status === 'completed' ? 'text-text-secondary' : ''}>{step.label}</span>\n </li>\n ))}\n </ul>\n\n <details className=\"group mt-2\">\n <summary className=\"cursor-pointer list-none text-[11px] text-text-muted transition-colors hover:text-text-secondary\">\n {tr('healthybowl.assistant.tool.details', 'Details')}\n </summary>\n <ul className=\"mt-1.5 space-y-0.5 border-t border-border-subtle pt-1.5\">\n {steps.map((step) => (\n <li key={`raw-${step.id}`} className=\"font-mono text-[11px] text-text-muted\">\n {step.status}\n <span aria-hidden=\"true\"> · </span>\n {step.tool}\n </li>\n ))}\n </ul>\n </details>\n </div>\n );\n};\n"],"mappings":";;;;AAqBA,IAAM,IAAY,wCAEZ,IAA0D;CAC9D,SAAS;CACT,WAAW;CACX,QAAQ;AACV;AAGA,SAAS,EAAa,GAAsB;CAC1C,IAAM,IAAS,EAAK,QAAQ,UAAU,GAAG,E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,GACtF,IAAW,IACb,EAAG,qCAAqC,mBAAmB,IAC3D,IACE,EAAG,sCAAsC,gBAAgB,IACzD,EAAG,mCAAmC,MAAM;CAElD,OACE,kBAAC,OAAD;EACE,WAAU;EACV,eAAY;YAFd;GAIE,kBAAC,OAAD;IAAK,WAAU;cAAf,CACE,kBAAC,GAAD;KAAQ,WAAU;KAA2B,eAAY;IAAQ,CAAA,GACjE,kBAAC,QAAD,EAAA,UAAO,EAAe,CAAA,CACnB;;GAEL,kBAAC,MAAD;IAAI,WAAU;cACX,EAAM,KAAK,MACV,kBAAC,MAAD;KAAkB,WAAU;eAA5B,CACE,kBAAC,QAAD;MAAM,WAAU;gBACd,kBAAC,GAAD,EAAU,QAAQ,EAAK,OAAS,CAAA;KAC5B,CAAA,GACN,kBAAC,QAAD;MAAM,WAAW,EAAK,WAAW,cAAc,wBAAwB;gBAAK,EAAK;KAAY,CAAA,CAC3F;OALK,EAAK,EAKV,CACL;GACC,CAAA;GAEJ,kBAAC,WAAD;IAAS,WAAU;cAAnB,CACE,kBAAC,WAAD;KAAS,WAAU;eAChB,EAAG,sCAAsC,SAAS;IAC5C,CAAA,GACT,kBAAC,MAAD;KAAI,WAAU;eACX,EAAM,KAAK,MACV,kBAAC,MAAD;MAA2B,WAAU;gBAArC;OACG,EAAK;OACN,kBAAC,QAAD;QAAM,eAAY;kBAAO;OAAS,CAAA;OACjC,EAAK;MACJ;QAJK,OAAO,EAAK,IAIjB,CACL;IACC,CAAA,CACG;;EACN;;AAET"}
1
+ {"version":3,"file":"AssistantToolActivity.js","names":[],"sources":["../../../src/components/assistant/AssistantToolActivity.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { Circle, Check, X, Loader2, Wrench } from 'lucide-react';\nimport { useAssistantTr } from '@burdenoff/fe-libs/shared/assistant';\n\nexport type AssistantToolStepStatus = 'queued' | 'running' | 'completed' | 'failed';\n\nexport interface AssistantToolStep {\n /** Stable key within the message. */\n id: string;\n /** Humanised label shown in the step row. */\n label: string;\n /** Raw tool name (surfaced in the collapsed \"Details\"). */\n tool: string;\n status: AssistantToolStepStatus;\n}\n\n// AssistantChatArea's `getToolProgress` emits one line per tool part as\n// \"Running: <tool>\" / \"Completed: <tool>\" / \"Failed: <tool>\", which\n// `buildAssistantProgress` then joins into the streamed message content. We\n// re-parse those lines here so they render as a structured activity card\n// instead of plain text.\nconst TOOL_LINE = /^(Running|Completed|Failed):\\s*(.+)$/;\n\nconst STATUS_BY_VERB: Record<string, AssistantToolStepStatus> = {\n Running: 'running',\n Completed: 'completed',\n Failed: 'failed',\n};\n\n/** Turn a raw tool name (`graphql_query`, `read-file`) into a readable label. */\nfunction humaniseTool(tool: string): string {\n const spaced = tool.replace(/[_-]+/g, ' ').replace(/\\s+/g, ' ').trim();\n if (!spaced) return tool;\n return spaced.charAt(0).toUpperCase() + spaced.slice(1);\n}\n\n/**\n * Split streamed assistant content into its tool-progress steps and the\n * remaining prose. Called by AssistantMessageItem so the tool lines render as an\n * AssistantToolActivity card while the rest renders as markdown.\n */\nexport function parseToolActivity(content: string): { steps: AssistantToolStep[]; text: string } {\n if (!content.includes(':')) return { steps: [], text: content };\n\n const steps: AssistantToolStep[] = [];\n const rest: string[] = [];\n\n content.split('\\n').forEach((line, index) => {\n const match = line.match(TOOL_LINE);\n if (match) {\n const tool = match[2].trim();\n steps.push({\n id: `${index}-${tool}`,\n label: humaniseTool(tool),\n tool,\n status: STATUS_BY_VERB[match[1]] ?? 'running',\n });\n } else {\n rest.push(line);\n }\n });\n\n return { steps, text: rest.join('\\n').trim() };\n}\n\nfunction StepIcon({ status }: { status: AssistantToolStepStatus }) {\n switch (status) {\n case 'completed':\n return <Check className=\"size-3.5 text-status-success-text\" aria-hidden=\"true\" />;\n case 'failed':\n return <X className=\"size-3.5 text-status-error-text\" aria-hidden=\"true\" />;\n case 'running':\n return <Loader2 className=\"size-3.5 animate-spin text-action-primary-bg\" aria-hidden=\"true\" />;\n default:\n return <Circle className=\"size-3.5 text-text-muted\" aria-hidden=\"true\" />;\n }\n}\n\n/**\n * AssistantToolActivity — compact progress card for a turn's tool run (per the\n * ai-assistant-v2 \"tool-progress\" mockup). Renders each step in one of four\n * states (queued / running / completed / failed) with a hollow circle, spinner,\n * green check or red x, plus a collapsed \"Details\" listing the raw tool names.\n */\nexport const AssistantToolActivity: FC<{ steps: AssistantToolStep[] }> = ({ steps }) => {\n const tr = useAssistantTr();\n if (steps.length === 0) return null;\n\n const hasFailure = steps.some((step) => step.status === 'failed');\n const isRunning = steps.some((step) => step.status === 'running' || step.status === 'queued');\n const headline = hasFailure\n ? tr('tool.failed', 'Some steps failed')\n : isRunning\n ? tr('tool.working', 'Working on it…')\n : tr('tool.done', 'Done');\n\n return (\n <div\n className=\"my-1.5 rounded-xl border border-border-subtle bg-bg-sunken px-3 py-2.5\"\n data-testid=\"assistant-tool-activity\"\n >\n <div className=\"flex items-center gap-1.5 text-[12px] font-medium text-text-secondary\">\n <Wrench className=\"size-3.5 text-text-muted\" aria-hidden=\"true\" />\n <span>{headline}</span>\n </div>\n\n <ul className=\"mt-2 space-y-1.5\">\n {steps.map((step) => (\n <li key={step.id} className=\"flex items-center gap-2 text-[13px] text-text-primary\">\n <span className=\"flex size-3.5 flex-shrink-0 items-center justify-center\">\n <StepIcon status={step.status} />\n </span>\n <span className={step.status === 'completed' ? 'text-text-secondary' : ''}>{step.label}</span>\n </li>\n ))}\n </ul>\n\n <details className=\"group mt-2\">\n <summary className=\"cursor-pointer list-none text-[11px] text-text-muted transition-colors hover:text-text-secondary\">\n {tr('tool.details', 'Details')}\n </summary>\n <ul className=\"mt-1.5 space-y-0.5 border-t border-border-subtle pt-1.5\">\n {steps.map((step) => (\n <li key={`raw-${step.id}`} className=\"font-mono text-[11px] text-text-muted\">\n {step.status}\n <span aria-hidden=\"true\"> · </span>\n {step.tool}\n </li>\n ))}\n </ul>\n </details>\n </div>\n );\n};\n"],"mappings":";;;;AAqBA,IAAM,IAAY,wCAEZ,IAA0D;CAC9D,SAAS;CACT,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M,MAAS,EAAK,WAAW,QAAQ,GAC1D,IAAY,EAAM,MAAM,MAAS,EAAK,WAAW,aAAa,EAAK,WAAW,QAAQ,GACtF,IAAW,IACb,EAAG,eAAe,mBAAmB,IACrC,IACE,EAAG,gBAAgB,gBAAgB,IACnC,EAAG,aAAa,MAAM;CAE5B,OACE,kBAAC,OAAD;EACE,WAAU;EACV,eAAY;YAFd;GAIE,kBAAC,OAAD;IAAK,WAAU;cAAf,CACE,kBAAC,GAAD;KAAQ,WAAU;KAA2B,eAAY;IAAQ,CAAA,GACjE,kBAAC,QAAD,EAAA,UAAO,EAAe,CAAA,CACnB;;GAEL,kBAAC,MAAD;IAAI,WAAU;cACX,EAAM,KAAK,MACV,kBAAC,MAAD;KAAkB,WAAU;eAA5B,CACE,kBAAC,QAAD;MAAM,WAAU;gBACd,kBAAC,GAAD,EAAU,QAAQ,EAAK,OAAS,CAAA;KAC5B,CAAA,GACN,kBAAC,QAAD;MAAM,WAAW,EAAK,WAAW,cAAc,wBAAwB;gBAAK,EAAK;KAAY,CAAA,CAC3F;OALK,EAAK,EAKV,CACL;GACC,CAAA;GAEJ,kBAAC,WAAD;IAAS,WAAU;cAAnB,CACE,kBAAC,WAAD;KAAS,WAAU;eAChB,EAAG,gBAAgB,SAAS;IACtB,CAAA,GACT,kBAAC,MAAD;KAAI,WAAU;eACX,EAAM,KAAK,MACV,kBAAC,MAAD;MAA2B,WAAU;gBAArC;OACG,EAAK;OACN,kBAAC,QAAD;QAAM,eAAY;kBAAO;OAAS,CAAA;OACjC,EAAK;MACJ;QAJK,OAAO,EAAK,IAIjB,CACL;IACC,CAAA,CACG;;EACN;;AAET"}
@@ -1,20 +1,20 @@
1
- import { useTr as e } from "../../../shared/hooks/useTr.js";
2
1
  import "../../../utils/assistantAttachments.js";
3
- import { availableAttachmentSources as t, deviceHasCamera as n } from "../../../utils/attachmentSources.js";
4
- import { useCallback as r, useEffect as i, useMemo as a, useRef as o, useState as s } from "react";
5
- import { Camera as c, FileText as l, FolderOpen as u, ImageIcon as d, Plus as f } from "lucide-react";
2
+ import { availableAttachmentSources as e, deviceHasCamera as t } from "../../../utils/attachmentSources.js";
3
+ import { useCallback as n, useEffect as r, useMemo as i, useRef as a, useState as o } from "react";
4
+ import { Camera as s, FileText as c, FolderOpen as l, ImageIcon as u, Plus as d } from "lucide-react";
5
+ import { useAssistantTr as f } from "@burdenoff/fe-libs/shared/assistant";
6
6
  import { jsx as p, jsxs as m } from "react/jsx-runtime";
7
7
  //#region src/components/assistant/composer/AssistantAttachmentButton.tsx
8
8
  var h = {
9
- camera: c,
10
- gallery: d,
11
- documents: l,
12
- files: u
13
- }, g = ({ onFiles: c, onPickerOpen: l, direction: u = "up", canAddMore: d, disabled: g = !1 }) => {
14
- let _ = e(), v = o(null), y = o(null), b = o(null), [x, S] = s(!1), C = o(l);
15
- C.current = l;
16
- let w = a(() => t(n()), []), T = d ? _("healthybowl.assistant.composer.attach", "Attach files or photos") : _("healthybowl.assistant.composer.attachFull", "Attachment limit reached ({{max}})", { max: 5 });
17
- i(() => {
9
+ camera: s,
10
+ gallery: u,
11
+ documents: c,
12
+ files: l
13
+ }, g = ({ onFiles: s, onPickerOpen: c, direction: l = "up", canAddMore: u, disabled: g = !1 }) => {
14
+ let _ = f(), v = a(null), y = a(null), b = a(null), [x, S] = o(!1), C = a(c);
15
+ C.current = c;
16
+ let w = i(() => e(t()), []), T = u ? _("composer.attach", "Attach files or photos") : _("composer.attachFull", "Attachment limit reached ({{max}})", { max: 5 });
17
+ r(() => {
18
18
  if (!x) return;
19
19
  let e = (e) => {
20
20
  e.key === "Escape" && (S(!1), b.current?.focus());
@@ -26,9 +26,9 @@ var h = {
26
26
  window.removeEventListener("keydown", e), window.removeEventListener("mousedown", t);
27
27
  };
28
28
  }, [x]);
29
- let E = r((e) => {
30
- c(e.target.files), e.target.value = "";
31
- }, [c]), D = r((e) => {
29
+ let E = n((e) => {
30
+ s(e.target.files), e.target.value = "";
31
+ }, [s]), D = n((e) => {
32
32
  let t = v.current;
33
33
  t && (t.accept = e.accept, t.multiple = e.multiple, e.capture ? t.setAttribute("capture", e.capture) : t.removeAttribute("capture"), S(!1), C.current?.(), t.click());
34
34
  }, []);
@@ -49,20 +49,20 @@ var h = {
49
49
  ref: b,
50
50
  type: "button",
51
51
  onClick: () => S((e) => !e),
52
- disabled: g || !d,
52
+ disabled: g || !u,
53
53
  title: T,
54
54
  "aria-label": T,
55
55
  "aria-haspopup": "menu",
56
56
  "aria-expanded": x,
57
57
  className: "flex size-9 items-center justify-center rounded-full border border-border-subtle bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-sunken hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-not-allowed disabled:text-text-muted disabled:hover:bg-bg-elevated",
58
58
  "data-testid": "assistant-attach",
59
- children: /* @__PURE__ */ p(f, { className: "size-4" })
59
+ children: /* @__PURE__ */ p(d, { className: "size-4" })
60
60
  }),
61
61
  x ? /* @__PURE__ */ p("div", {
62
62
  ref: y,
63
63
  role: "menu",
64
- "aria-label": _("healthybowl.assistant.composer.attachSource", "Attach from"),
65
- className: `absolute ${u === "up" ? "bottom-full mb-2" : "top-full mt-2"} left-0 z-30 min-w-44 overflow-hidden rounded-xl border border-border-default bg-bg-elevated py-1 shadow-lg`,
64
+ "aria-label": _("composer.attachSource", "Attach from"),
65
+ className: `absolute ${l === "up" ? "bottom-full mb-2" : "top-full mt-2"} left-0 z-30 min-w-44 overflow-hidden rounded-xl border border-border-default bg-bg-elevated py-1 shadow-lg`,
66
66
  "data-testid": "assistant-attach-menu",
67
67
  children: w.map((e) => {
68
68
  let t = h[e.id];
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantAttachmentButton.js","names":[],"sources":["../../../../src/components/assistant/composer/AssistantAttachmentButton.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState, type ChangeEvent, type FC } from 'react';\nimport { Camera, FileText, FolderOpen, ImageIcon, Plus } from 'lucide-react';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { MAX_ATTACHMENTS } from '@/utils/assistantAttachments';\nimport {\n availableAttachmentSources,\n deviceHasCamera,\n type AttachmentSource,\n type AttachmentSourceId,\n} from '@/utils/attachmentSources';\n\ninterface Props {\n onFiles: (files: FileList | null) => void;\n /**\n * The OS picker is about to take over the screen.\n *\n * ★ Exists for the voice session, which must release the microphone before the\n * camera app claims it. Fired on the `.click()` rather than on selection,\n * because by the time a file arrives the damage is done — and a CANCELLED\n * picker never reports anything at all.\n */\n onPickerOpen?: () => void;\n /**\n * Which way the source menu opens.\n *\n * ★ 'up' is right for the COMPOSER, which sits at the bottom of the panel — a\n * downward menu there is clipped by the panel edge at every size. It is wrong\n * for the voice session, whose attach control is anchored at the TOP: the menu\n * would open above the button, outside the panel, and all four sources would be\n * unreachable. The control would look present and do nothing.\n */\n direction?: 'up' | 'down';\n /** False once MAX_ATTACHMENTS is reached — the control explains why. */\n canAddMore: boolean;\n disabled?: boolean;\n}\n\nconst SOURCE_ICONS: Record<AttachmentSourceId, typeof Camera> = {\n camera: Camera,\n gallery: ImageIcon,\n documents: FileText,\n files: FolderOpen,\n};\n\n/**\n * Leading circular \"+\" attach control in the composer.\n *\n * ★ Opens a SOURCE MENU rather than the OS picker directly. One picker had to\n * stand in for every source, and on a phone it lands in Files — so\n * photographing a diseased leaf, the single most likely thing a farmer wants to\n * show the assistant, meant leaving for the camera app and coming back.\n *\n * ★ One input, reconfigured per source, rather than one input each. `accept` and\n * `capture` are set immediately before `.click()`, so there is exactly one place\n * a change event can arrive from and the existing `onFiles` contract — shared\n * with drag-drop and paste — is untouched.\n *\n * ★ Camera uses the `capture` attribute rather than a bespoke `getUserMedia`\n * viewfinder. That hands capture → preview → retake → use to the OS camera,\n * which does it better, is already localised, and cannot be exercised on a\n * desktop CI box at all; on a device without a camera the attribute is ignored\n * and the picker opens as usual, so it degrades instead of breaking.\n *\n * `accept` is advisory — the picker still allows \"All files\" on most platforms —\n * so validation lives in `validateFile`, not here.\n */\nexport const AssistantAttachmentButton: FC<Props> = ({\n onFiles,\n onPickerOpen,\n direction = 'up',\n canAddMore,\n disabled = false,\n}) => {\n const tr = useTr();\n const inputRef = useRef<HTMLInputElement>(null);\n const menuRef = useRef<HTMLDivElement>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n const [open, setOpen] = useState(false);\n // Ref so `pick` keeps its stable identity — it is passed to every menu item.\n const onPickerOpenRef = useRef(onPickerOpen);\n onPickerOpenRef.current = onPickerOpen;\n\n // Read once per mount: a device does not sprout a camera mid-session, and\n // matchMedia in render would run on every keystroke in the composer.\n const sources = useMemo(() => availableAttachmentSources(deviceHasCamera()), []);\n\n const label = canAddMore\n ? tr('healthybowl.assistant.composer.attach', 'Attach files or photos')\n : tr('healthybowl.assistant.composer.attachFull', 'Attachment limit reached ({{max}})', {\n max: MAX_ATTACHMENTS,\n });\n\n // Escape closes, and a click anywhere else closes — the same contract as the\n // export menu, so the two dropdowns in this panel behave identically.\n useEffect(() => {\n if (!open) return;\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n setOpen(false);\n buttonRef.current?.focus();\n }\n };\n const onPointerDown = (event: MouseEvent) => {\n const target = event.target as Node;\n if (menuRef.current?.contains(target) || buttonRef.current?.contains(target)) return;\n setOpen(false);\n };\n window.addEventListener('keydown', onKeyDown);\n window.addEventListener('mousedown', onPointerDown);\n return () => {\n window.removeEventListener('keydown', onKeyDown);\n window.removeEventListener('mousedown', onPointerDown);\n };\n }, [open]);\n\n const handleChange = useCallback(\n (event: ChangeEvent<HTMLInputElement>) => {\n onFiles(event.target.files);\n // Reset so picking the SAME file twice in a row still fires a change event.\n event.target.value = '';\n },\n [onFiles]\n );\n\n const pick = useCallback((source: AttachmentSource) => {\n const input = inputRef.current;\n if (!input) return;\n input.accept = source.accept;\n input.multiple = source.multiple;\n // A property, not an attribute: `capture=\"\"` still means \"use the camera\",\n // so it has to be removed rather than blanked when the source is not camera.\n if (source.capture) input.setAttribute('capture', source.capture);\n else input.removeAttribute('capture');\n setOpen(false);\n onPickerOpenRef.current?.();\n input.click();\n }, []);\n\n return (\n <div className=\"relative flex-shrink-0\">\n <input\n ref={inputRef}\n type=\"file\"\n multiple\n className=\"hidden\"\n onChange={handleChange}\n tabIndex={-1}\n aria-hidden=\"true\"\n data-testid=\"assistant-attach-input\"\n />\n <button\n ref={buttonRef}\n type=\"button\"\n onClick={() => setOpen((wasOpen) => !wasOpen)}\n disabled={disabled || !canAddMore}\n title={label}\n aria-label={label}\n aria-haspopup=\"menu\"\n aria-expanded={open}\n className=\"flex size-9 items-center justify-center rounded-full border border-border-subtle bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-sunken hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-not-allowed disabled:text-text-muted disabled:hover:bg-bg-elevated\"\n data-testid=\"assistant-attach\"\n >\n <Plus className=\"size-4\" />\n </button>\n\n {open ? (\n <div\n ref={menuRef}\n role=\"menu\"\n aria-label={tr('healthybowl.assistant.composer.attachSource', 'Attach from')}\n // Direction follows the ANCHOR, not the component — see the prop.\n className={`absolute ${\n direction === 'up' ? 'bottom-full mb-2' : 'top-full mt-2'\n } left-0 z-30 min-w-44 overflow-hidden rounded-xl border border-border-default bg-bg-elevated py-1 shadow-lg`}\n data-testid=\"assistant-attach-menu\"\n >\n {sources.map((source) => {\n const Icon = SOURCE_ICONS[source.id];\n return (\n <button\n key={source.id}\n type=\"button\"\n role=\"menuitem\"\n onClick={() => pick(source)}\n className=\"flex w-full items-center gap-2.5 px-3 py-2 text-left text-sm text-text-primary transition-colors hover:bg-bg-sunken focus:outline-none focus-visible:bg-bg-sunken\"\n data-testid={`assistant-attach-source-${source.id}`}\n >\n <Icon className=\"size-4 flex-shrink-0 text-text-secondary\" aria-hidden=\"true\" />\n {tr(source.labelKey, source.labelFallback)}\n </button>\n );\n })}\n </div>\n ) : null}\n </div>\n );\n};\n"],"mappings":";;;;;;;AAqCA,IAAM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,GACb,EAAgB,UAAU,GAC1B,EAAM,MAAM;CACd,GAAG,CAAC,CAAC;CAEL,OACE,kBAAC,OAAD;EAAK,WAAU;YAAf;GACE,kBAAC,SAAD;IACE,KAAK;IACL,MAAK;IACL,UAAA;IACA,WAAU;IACV,UAAU;IACV,UAAU;IACV,eAAY;IACZ,eAAY;GACb,CAAA;GACD,kBAAC,UAAD;IACE,KAAK;IACL,MAAK;IACL,eAAe,GAAS,MAAY,CAAC,CAAO;IAC5C,UAAU,KAAY,CAAC;IACvB,OAAO;IACP,cAAY;IACZ,iBAAc;IACd,iBAAe;IACf,WAAU;IACV,eAAY;cAEZ,kBAAC,GAAD,EAAM,WAAU,SAAU,CAAA;GACpB,CAAA;GAEP,IACC,kBAAC,OAAD;IACE,KAAK;IACL,MAAK;IACL,cAAY,EAAG,+CAA+C,aAAa;IAE3E,WAAW,YACT,MAAc,OAAO,qBAAqB,gBAC3C;IACD,eAAY;cAEX,EAAQ,KAAK,MAAW;KACvB,IAAM,IAAO,EAAa,EAAO;KACjC,OACE,kBAAC,UAAD;MAEE,MAAK;MACL,MAAK;MACL,eAAe,EAAK,CAAM;MAC1B,WAAU;MACV,eAAa,2BAA2B,EAAO;gBANjD,CAQE,kBAAC,GAAD;OAAM,WAAU;OAA2C,eAAY;MAAQ,CAAA,GAC9E,EAAG,EAAO,UAAU,EAAO,aAAa,CACnC;QATD,EAAO,EASN;IAEZ,CAAC;GACE,CAAA,IACH;EACD;;AAET"}
1
+ {"version":3,"file":"AssistantAttachmentButton.js","names":[],"sources":["../../../../src/components/assistant/composer/AssistantAttachmentButton.tsx"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState, type ChangeEvent, type FC } from 'react';\nimport { Camera, FileText, FolderOpen, ImageIcon, Plus } from 'lucide-react';\nimport { useAssistantTr } from '@burdenoff/fe-libs/shared/assistant';\nimport { MAX_ATTACHMENTS } from '@/utils/assistantAttachments';\nimport {\n availableAttachmentSources,\n deviceHasCamera,\n type AttachmentSource,\n type AttachmentSourceId,\n} from '@/utils/attachmentSources';\n\ninterface Props {\n onFiles: (files: FileList | null) => void;\n /**\n * The OS picker is about to take over the screen.\n *\n * ★ Exists for the voice session, which must release the microphone before the\n * camera app claims it. Fired on the `.click()` rather than on selection,\n * because by the time a file arrives the damage is done — and a CANCELLED\n * picker never reports anything at all.\n */\n onPickerOpen?: () => void;\n /**\n * Which way the source menu opens.\n *\n * ★ 'up' is right for the COMPOSER, which sits at the bottom of the panel — a\n * downward menu there is clipped by the panel edge at every size. It is wrong\n * for the voice session, whose attach control is anchored at the TOP: the menu\n * would open above the button, outside the panel, and all four sources would be\n * unreachable. The control would look present and do nothing.\n */\n direction?: 'up' | 'down';\n /** False once MAX_ATTACHMENTS is reached — the control explains why. */\n canAddMore: boolean;\n disabled?: boolean;\n}\n\nconst SOURCE_ICONS: Record<AttachmentSourceId, typeof Camera> = {\n camera: Camera,\n gallery: ImageIcon,\n documents: FileText,\n files: FolderOpen,\n};\n\n/**\n * Leading circular \"+\" attach control in the composer.\n *\n * ★ Opens a SOURCE MENU rather than the OS picker directly. One picker had to\n * stand in for every source, and on a phone it lands in Files — so\n * photographing a diseased leaf, the single most likely thing a farmer wants to\n * show the assistant, meant leaving for the camera app and coming back.\n *\n * ★ One input, reconfigured per source, rather than one input each. `accept` and\n * `capture` are set immediately before `.click()`, so there is exactly one place\n * a change event can arrive from and the existing `onFiles` contract — shared\n * with drag-drop and paste — is untouched.\n *\n * ★ Camera uses the `capture` attribute rather than a bespoke `getUserMedia`\n * viewfinder. That hands capture → preview → retake → use to the OS camera,\n * which does it better, is already localised, and cannot be exercised on a\n * desktop CI box at all; on a device without a camera the attribute is ignored\n * and the picker opens as usual, so it degrades instead of breaking.\n *\n * `accept` is advisory — the picker still allows \"All files\" on most platforms —\n * so validation lives in `validateFile`, not here.\n */\nexport const AssistantAttachmentButton: FC<Props> = ({\n onFiles,\n onPickerOpen,\n direction = 'up',\n canAddMore,\n disabled = false,\n}) => {\n const tr = useAssistantTr();\n const inputRef = useRef<HTMLInputElement>(null);\n const menuRef = useRef<HTMLDivElement>(null);\n const buttonRef = useRef<HTMLButtonElement>(null);\n const [open, setOpen] = useState(false);\n // Ref so `pick` keeps its stable identity — it is passed to every menu item.\n const onPickerOpenRef = useRef(onPickerOpen);\n onPickerOpenRef.current = onPickerOpen;\n\n // Read once per mount: a device does not sprout a camera mid-session, and\n // matchMedia in render would run on every keystroke in the composer.\n const sources = useMemo(() => availableAttachmentSources(deviceHasCamera()), []);\n\n const label = canAddMore\n ? tr('composer.attach', 'Attach files or photos')\n : tr('composer.attachFull', 'Attachment limit reached ({{max}})', {\n max: MAX_ATTACHMENTS,\n });\n\n // Escape closes, and a click anywhere else closes — the same contract as the\n // export menu, so the two dropdowns in this panel behave identically.\n useEffect(() => {\n if (!open) return;\n const onKeyDown = (event: KeyboardEvent) => {\n if (event.key === 'Escape') {\n setOpen(false);\n buttonRef.current?.focus();\n }\n };\n const onPointerDown = (event: MouseEvent) => {\n const target = event.target as Node;\n if (menuRef.current?.contains(target) || buttonRef.current?.contains(target)) return;\n setOpen(false);\n };\n window.addEventListener('keydown', onKeyDown);\n window.addEventListener('mousedown', onPointerDown);\n return () => {\n window.removeEventListener('keydown', onKeyDown);\n window.removeEventListener('mousedown', onPointerDown);\n };\n }, [open]);\n\n const handleChange = useCallback(\n (event: ChangeEvent<HTMLInputElement>) => {\n onFiles(event.target.files);\n // Reset so picking the SAME file twice in a row still fires a change event.\n event.target.value = '';\n },\n [onFiles]\n );\n\n const pick = useCallback((source: AttachmentSource) => {\n const input = inputRef.current;\n if (!input) return;\n input.accept = source.accept;\n input.multiple = source.multiple;\n // A property, not an attribute: `capture=\"\"` still means \"use the camera\",\n // so it has to be removed rather than blanked when the source is not camera.\n if (source.capture) input.setAttribute('capture', source.capture);\n else input.removeAttribute('capture');\n setOpen(false);\n onPickerOpenRef.current?.();\n input.click();\n }, []);\n\n return (\n <div className=\"relative flex-shrink-0\">\n <input\n ref={inputRef}\n type=\"file\"\n multiple\n className=\"hidden\"\n onChange={handleChange}\n tabIndex={-1}\n aria-hidden=\"true\"\n data-testid=\"assistant-attach-input\"\n />\n <button\n ref={buttonRef}\n type=\"button\"\n onClick={() => setOpen((wasOpen) => !wasOpen)}\n disabled={disabled || !canAddMore}\n title={label}\n aria-label={label}\n aria-haspopup=\"menu\"\n aria-expanded={open}\n className=\"flex size-9 items-center justify-center rounded-full border border-border-subtle bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-sunken hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-not-allowed disabled:text-text-muted disabled:hover:bg-bg-elevated\"\n data-testid=\"assistant-attach\"\n >\n <Plus className=\"size-4\" />\n </button>\n\n {open ? (\n <div\n ref={menuRef}\n role=\"menu\"\n aria-label={tr('composer.attachSource', 'Attach from')}\n // Direction follows the ANCHOR, not the component — see the prop.\n className={`absolute ${\n direction === 'up' ? 'bottom-full mb-2' : 'top-full mt-2'\n } left-0 z-30 min-w-44 overflow-hidden rounded-xl border border-border-default bg-bg-elevated py-1 shadow-lg`}\n data-testid=\"assistant-attach-menu\"\n >\n {sources.map((source) => {\n const Icon = SOURCE_ICONS[source.id];\n return (\n <button\n key={source.id}\n type=\"button\"\n role=\"menuitem\"\n onClick={() => pick(source)}\n className=\"flex w-full items-center gap-2.5 px-3 py-2 text-left text-sm text-text-primary transition-colors hover:bg-bg-sunken focus:outline-none focus-visible:bg-bg-sunken\"\n data-testid={`assistant-attach-source-${source.id}`}\n >\n <Icon className=\"size-4 flex-shrink-0 text-text-secondary\" aria-hidden=\"true\" />\n {tr(source.labelKey, source.labelFallback)}\n </button>\n );\n })}\n </div>\n ) : null}\n </div>\n );\n};\n"],"mappings":";;;;;;;AAqCA,IAAM,IAA0D;CAC9D,QAAQ;CACR,SAAS;CACT,WAAW;CACX,OAAO;AACT,GAwBa,KAAwC,EACnD,YACA,iBACA,eAAY,MACZ,eACA,cAAW,SACP;CACJ,IAAM,IAAK,EAAe,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AK;IACL,UAAA;IACA,WAAU;IACV,UAAU;IACV,UAAU;IACV,eAAY;IACZ,eAAY;GACb,CAAA;GACD,kBAAC,UAAD;IACE,KAAK;IACL,MAAK;IACL,eAAe,GAAS,MAAY,CAAC,CAAO;IAC5C,UAAU,KAAY,CAAC;IACvB,OAAO;IACP,cAAY;IACZ,iBAAc;IACd,iBAAe;IACf,WAAU;IACV,eAAY;cAEZ,kBAAC,GAAD,EAAM,WAAU,SAAU,CAAA;GACpB,CAAA;GAEP,IACC,kBAAC,OAAD;IACE,KAAK;IACL,MAAK;IACL,cAAY,EAAG,yBAAyB,aAAa;IAErD,WAAW,YACT,MAAc,OAAO,qBAAqB,gBAC3C;IACD,eAAY;cAEX,EAAQ,KAAK,MAAW;KACvB,IAAM,IAAO,EAAa,EAAO;KACjC,OACE,kBAAC,UAAD;MAEE,MAAK;MACL,MAAK;MACL,eAAe,EAAK,CAAM;MAC1B,WAAU;MACV,eAAa,2BAA2B,EAAO;gBANjD,CAQE,kBAAC,GAAD;OAAM,WAAU;OAA2C,eAAY;MAAQ,CAAA,GAC9E,EAAG,EAAO,UAAU,EAAO,aAAa,CACnC;QATD,EAAO,EASN;IAEZ,CAAC;GACE,CAAA,IACH;EACD;;AAET"}
@@ -1,68 +1,68 @@
1
- import { useTr as e } from "../../../shared/hooks/useTr.js";
2
- import { formatBytes as t } from "../../../utils/assistantAttachments.js";
3
- import { AlertCircle as n, FileText as r, Loader2 as i, Paperclip as a, RotateCcw as o, X as s } from "lucide-react";
1
+ import { formatBytes as e } from "../../../utils/assistantAttachments.js";
2
+ import { AlertCircle as t, FileText as n, Loader2 as r, Paperclip as i, RotateCcw as a, X as o } from "lucide-react";
3
+ import { useAssistantTr as s } from "@burdenoff/fe-libs/shared/assistant";
4
4
  import { jsx as c, jsxs as l } from "react/jsx-runtime";
5
5
  //#region src/components/assistant/composer/AssistantAttachmentChips.tsx
6
6
  var u = ({ attachments: u, onRemove: d, onRetry: f, preparingCount: p = 0, disabled: m = !1 }) => {
7
- let h = e();
7
+ let h = s();
8
8
  return u.length === 0 && p === 0 ? null : /* @__PURE__ */ l("ul", {
9
9
  className: "mb-1.5 flex flex-wrap gap-1.5 px-0.5",
10
- "aria-label": h("healthybowl.assistant.attachments.listLabel", "Attached files"),
10
+ "aria-label": h("attachments.listLabel", "Attached files"),
11
11
  "data-testid": "assistant-attachment-chips",
12
- children: [u.map((e) => {
13
- let u = e.status === "pending" || e.status === "uploading", p = e.status === "error";
12
+ children: [u.map((s) => {
13
+ let u = s.status === "pending" || s.status === "uploading", p = s.status === "error";
14
14
  return /* @__PURE__ */ l("li", {
15
15
  className: `flex max-w-[220px] items-center gap-1.5 rounded-lg border py-1 pl-1 pr-1.5 ${p ? "border-status-error-text/40 bg-status-error-bg/10" : "border-border-subtle bg-bg-surface"}`,
16
16
  "data-testid": "assistant-attachment-chip",
17
17
  children: [
18
18
  /* @__PURE__ */ c("span", {
19
19
  className: "flex size-7 flex-shrink-0 items-center justify-center overflow-hidden rounded-md bg-bg-sunken text-text-muted",
20
- children: e.previewUrl ? /* @__PURE__ */ c("img", {
21
- src: e.previewUrl,
20
+ children: s.previewUrl ? /* @__PURE__ */ c("img", {
21
+ src: s.previewUrl,
22
22
  alt: "",
23
23
  className: "size-full object-cover"
24
- }) : p ? /* @__PURE__ */ c(n, { className: "size-3.5 text-status-error-text" }) : e.kind === "text" ? /* @__PURE__ */ c(r, { className: "size-3.5" }) : /* @__PURE__ */ c(a, { className: "size-3.5" })
24
+ }) : p ? /* @__PURE__ */ c(t, { className: "size-3.5 text-status-error-text" }) : s.kind === "text" ? /* @__PURE__ */ c(n, { className: "size-3.5" }) : /* @__PURE__ */ c(i, { className: "size-3.5" })
25
25
  }),
26
26
  /* @__PURE__ */ l("span", {
27
27
  className: "min-w-0 flex-1",
28
28
  children: [/* @__PURE__ */ c("span", {
29
29
  className: "block truncate text-[11px] font-medium leading-tight text-text-primary",
30
- children: e.filename
30
+ children: s.filename
31
31
  }), /* @__PURE__ */ c("span", {
32
32
  className: "block truncate text-[10px] leading-tight text-text-muted",
33
- children: p ? e.error ?? h("healthybowl.assistant.attachments.failed", "Upload failed") : u ? e.progressNote ?? h("healthybowl.assistant.attachments.uploading", "Uploading…") : t(e.size)
33
+ children: p ? s.error ?? h("attachments.failed", "Upload failed") : u ? s.progressNote ?? h("attachments.uploading", "Uploading…") : e(s.size)
34
34
  })]
35
35
  }),
36
36
  p && /* @__PURE__ */ c("button", {
37
37
  type: "button",
38
- onClick: () => f(e.id),
38
+ onClick: () => f(s.id),
39
39
  disabled: m,
40
40
  className: "flex size-5 flex-shrink-0 items-center justify-center rounded-full text-status-error-text transition-colors hover:bg-bg-sunken focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-not-allowed",
41
- "aria-label": h("healthybowl.assistant.attachments.retry", "Retry uploading {{name}}", { name: e.filename }),
41
+ "aria-label": h("attachments.retry", "Retry uploading {{name}}", { name: s.filename }),
42
42
  "data-testid": "assistant-attachment-retry",
43
- children: /* @__PURE__ */ c(o, { className: "size-3" })
43
+ children: /* @__PURE__ */ c(a, { className: "size-3" })
44
44
  }),
45
- u ? /* @__PURE__ */ c(i, {
45
+ u ? /* @__PURE__ */ c(r, {
46
46
  className: "size-3.5 flex-shrink-0 animate-spin text-text-muted",
47
- "aria-label": h("healthybowl.assistant.attachments.uploading", "Uploading…")
47
+ "aria-label": h("attachments.uploading", "Uploading…")
48
48
  }) : /* @__PURE__ */ c("button", {
49
49
  type: "button",
50
- onClick: () => d(e.id),
50
+ onClick: () => d(s.id),
51
51
  disabled: m,
52
52
  className: "flex size-5 flex-shrink-0 items-center justify-center rounded-full text-text-muted transition-colors hover:bg-bg-sunken hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-not-allowed",
53
- "aria-label": h("healthybowl.assistant.attachments.remove", "Remove {{name}}", { name: e.filename }),
53
+ "aria-label": h("attachments.remove", "Remove {{name}}", { name: s.filename }),
54
54
  "data-testid": "assistant-attachment-remove",
55
- children: /* @__PURE__ */ c(s, { className: "size-3" })
55
+ children: /* @__PURE__ */ c(o, { className: "size-3" })
56
56
  })
57
57
  ]
58
- }, e.id);
58
+ }, s.id);
59
59
  }), Array.from({ length: p }, (e, t) => /* @__PURE__ */ l("li", {
60
60
  className: "flex items-center gap-1.5 rounded-lg border border-border-subtle bg-bg-sunken px-2 py-1 text-xs text-text-muted",
61
61
  "data-testid": "assistant-attachment-preparing",
62
- children: [/* @__PURE__ */ c(i, {
62
+ children: [/* @__PURE__ */ c(r, {
63
63
  className: "size-3 animate-spin",
64
64
  "aria-hidden": "true"
65
- }), h("healthybowl.assistant.attachments.preparing", "Reading file…")]
65
+ }), h("attachments.preparing", "Reading file…")]
66
66
  }, `preparing-${t}`))]
67
67
  });
68
68
  };