@burdenoff/microfe-healthybowl 2026.902.6 → 2026.902.8

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.
@@ -28,7 +28,7 @@ var _ = 200, v = ({ onSend: v, disabled: y = !1, placeholder: b, mode: oe, avail
28
28
  e && (e.style.height = "auto", e.style.height = `${Math.min(e.scrollHeight, _)}px`);
29
29
  }, [E]);
30
30
  let Z = s(() => {
31
- X && (G.isListening && G.stop(), v(E.trim(), J), D(""), R());
31
+ X && (G.isActive && G.stop(), v(E.trim(), J), D(""), R());
32
32
  }, [
33
33
  X,
34
34
  v,
@@ -108,14 +108,15 @@ var _ = 200, v = ({ onSend: v, disabled: y = !1, placeholder: b, mode: oe, avail
108
108
  current: W,
109
109
  selected: H,
110
110
  onChange: U,
111
- disabled: y || G.isListening
111
+ disabled: y || G.isActive
112
112
  }),
113
113
  G.isSupported && /* @__PURE__ */ h(ne, {
114
114
  isListening: G.isListening,
115
+ isStarting: G.isStarting,
115
116
  onToggle: G.toggle,
116
117
  disabled: y
117
118
  }),
118
- S && q.length === 0 && j.length === 0 && !G.isListening ? /* @__PURE__ */ h(ie, {
119
+ S && q.length === 0 && j.length === 0 && !G.isActive ? /* @__PURE__ */ h(ie, {
119
120
  onStart: S,
120
121
  disabled: y
121
122
  }) : /* @__PURE__ */ h("button", {
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantComposer.js","names":[],"sources":["../../../../src/components/assistant/composer/AssistantComposer.tsx"],"sourcesContent":["import {\n useCallback,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type ClipboardEvent,\n type DragEvent,\n type FC,\n type KeyboardEvent,\n} from 'react';\nimport { ArrowUp, Loader2 } from 'lucide-react';\nimport type { AssistantMode, AssistantModeConfig } from '@/types/assistant';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { languageDisplayName } from '@/utils/speechVoices';\nimport { resolveAssistantLanguage } from '@/config/assistantLanguages';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { useVoiceInput } from '@/hooks/useVoiceInput';\nimport { useAssistantAttachments } from '@/hooks/useAssistantAttachments';\nimport {\n MAX_ATTACHMENTS,\n getSendableAttachments,\n type AssistantAttachment,\n type AttachmentRejection,\n} from '@/utils/assistantAttachments';\nimport { AssistantAttachmentButton } from './AssistantAttachmentButton';\nimport { AssistantAttachmentChips } from './AssistantAttachmentChips';\nimport { AssistantVoiceButton } from './AssistantVoiceButton';\nimport { AssistantLanguageSelector } from './AssistantLanguageSelector';\nimport { AssistantVoiceSessionButton } from '../voice/AssistantVoiceSessionButton';\nimport { AssistantModeSelector } from './AssistantModeSelector';\n\ninterface Props {\n /**\n * Send the message. `attachments` are already uploaded and ready; the chat\n * area folds them into the prompt and onto the user bubble.\n */\n onSend: (message: string, attachments: AssistantAttachment[]) => void;\n /** True while a turn is in-flight (assistant busy) — disables send + shows the spinner. */\n disabled?: boolean;\n placeholder?: string;\n mode: AssistantMode;\n /** Role-filtered list of modes the user may pick. */\n availableModes: AssistantModeConfig[];\n onModeChange: (mode: AssistantMode) => void;\n /**\n * Opens the hands-free voice conversation. Omitted where a voice session\n * cannot work at all (no speech input, or nothing able to speak the reply),\n * which is what hides the control rather than offering a dead button.\n */\n onStartVoiceSession?: () => void;\n}\n\nconst MAX_TEXTAREA_HEIGHT = 200;\n\n/**\n * AssistantComposer — the v2 input surface (per the ai-assistant-v2 mockups).\n *\n * A rounded card with, on the input row: a leading circular \"+\" attach control,\n * an auto-growing textarea, a microphone, and a prominent filled forest-green\n * circular send button. BELOW the input sit the mode pills (\"Ask\" active-green /\n * \"Take action\" outline); ABOVE it, chips for any pending attachments.\n *\n * Multimodal input (Workstreams 2–3) arrives through three converging paths —\n * the attach button, drag-and-drop onto the card, and paste (a screenshot from\n * the clipboard is the single most common way a user shares one) — plus voice\n * dictation, which appends recognised speech to the draft so it can still be\n * edited before sending.\n *\n * Fully controlled (React state for the text) with auto-grow via a layout\n * effect. Enter sends, Shift+Enter inserts a newline.\n */\nexport const AssistantComposer: FC<Props> = ({\n onSend,\n disabled = false,\n placeholder,\n mode,\n availableModes,\n onModeChange,\n onStartVoiceSession,\n}) => {\n const tr = useTr();\n const { locale } = useI18n();\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const [text, setText] = useState('');\n const [isDraggingOver, setIsDraggingOver] = useState(false);\n // Nested drag-enter/leave pairs fire for every child element; count them so\n // the highlight survives dragging across the textarea and buttons.\n const dragDepthRef = useRef(0);\n\n const {\n attachments,\n isBusy: attachmentsBusy,\n sendBlocker,\n rejection,\n addFiles,\n remove,\n retry,\n clear,\n clearRejection,\n canAddMore,\n } = useAssistantAttachments();\n\n const appendTranscript = useCallback((phrase: string) => {\n setText((current) => (current ? `${current.replace(/\\s+$/, '')} ${phrase}` : phrase));\n }, []);\n\n // One selection drives the recogniser, the reply language and the voice —\n // see `assistantLanguages`. `null` follows the interface language, which is\n // what this did unconditionally before.\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const setAssistantLanguage = useAssistantStore((state) => state.setAssistantLanguage);\n const spokenLanguage = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale),\n [assistantLanguage, locale]\n );\n\n const voice = useVoiceInput({ onFinalize: appendTranscript, language: spokenLanguage.tag });\n\n const resolvedPlaceholder =\n placeholder ?? tr('healthybowl.assistant.composer.placeholder', 'Ask HealthyBowl anything…');\n const trimmed = text.trim();\n // Exactly what the model will be given — see `getSendableAttachments`.\n const sendableAttachments = getSendableAttachments(attachments);\n const failedAttachments = attachments.filter((attachment) => attachment.status === 'error');\n // A message may be attachments-only (\"what's wrong with this leaf?\" is often\n // just the photo), but never sends while an upload is in flight OR has failed:\n // `sendBlocker` covers both. Gating on the blocker rather than on\n // `attachmentsBusy` is what stops a turn going out that quietly omits a file\n // the user can still see attached — the chips are cleared by `clear()` below,\n // so the evidence would disappear at the same instant.\n const canSend = (trimmed.length > 0 || sendableAttachments.length > 0) && !disabled && sendBlocker === null;\n\n // Auto-grow the textarea to fit its content (capped), re-measured after every\n // value change so the card breathes as the user types.\n useLayoutEffect(() => {\n const textarea = textareaRef.current;\n if (!textarea) return;\n textarea.style.height = 'auto';\n textarea.style.height = `${Math.min(textarea.scrollHeight, MAX_TEXTAREA_HEIGHT)}px`;\n }, [text]);\n\n const handleSend = useCallback(() => {\n if (!canSend) return;\n // Dictation left running into a send would keep appending to a cleared\n // draft; stop it so the mic state matches what the user sees.\n if (voice.isListening) voice.stop();\n onSend(text.trim(), sendableAttachments);\n setText('');\n clear();\n }, [canSend, onSend, text, sendableAttachments, clear, voice]);\n\n const handleKeyDown = useCallback(\n (event: KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n handleSend();\n }\n },\n [handleSend]\n );\n\n const handlePaste = useCallback(\n (event: ClipboardEvent<HTMLTextAreaElement>) => {\n const files = Array.from(event.clipboardData?.files ?? []);\n if (files.length === 0) return;\n // Only claim the paste when it carried files; a normal text paste (which\n // also exposes an empty `files`) must still land in the textarea.\n event.preventDefault();\n addFiles(files);\n },\n [addFiles]\n );\n\n const handleDragEnter = useCallback((event: DragEvent<HTMLDivElement>) => {\n if (!Array.from(event.dataTransfer?.types ?? []).includes('Files')) return;\n dragDepthRef.current += 1;\n setIsDraggingOver(true);\n }, []);\n\n const handleDragLeave = useCallback(() => {\n dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);\n if (dragDepthRef.current === 0) setIsDraggingOver(false);\n }, []);\n\n const handleDragOver = useCallback((event: DragEvent<HTMLDivElement>) => {\n if (!Array.from(event.dataTransfer?.types ?? []).includes('Files')) return;\n // Required for a drop to fire at all, and stops the browser from navigating\n // away to the dropped file.\n event.preventDefault();\n }, []);\n\n const handleDrop = useCallback(\n (event: DragEvent<HTMLDivElement>) => {\n event.preventDefault();\n dragDepthRef.current = 0;\n setIsDraggingOver(false);\n addFiles(event.dataTransfer?.files ?? null);\n },\n [addFiles]\n );\n\n const rejectionMessage = (reason: AttachmentRejection): string => {\n switch (reason) {\n case 'too-many':\n return tr('healthybowl.assistant.attachments.tooMany', 'You can attach up to {{max}} files per message.', {\n max: MAX_ATTACHMENTS,\n });\n case 'too-large':\n return tr('healthybowl.assistant.attachments.tooLarge', 'That file is larger than 10 MB.');\n case 'empty':\n return tr('healthybowl.assistant.attachments.empty', 'That file is empty.');\n case 'unreadable':\n return tr('healthybowl.assistant.attachments.unreadable', 'That file could not be read.');\n case 'unsupported-image':\n return tr(\n 'healthybowl.assistant.attachments.unsupportedImage',\n \"This device can't read that image format, so it can't be resized to send. Save it as JPEG and try again.\"\n );\n }\n };\n\n const voiceErrorMessage = (): string | null => {\n switch (voice.error) {\n case 'not-allowed':\n return tr(\n 'healthybowl.assistant.voice.denied',\n 'Microphone access is blocked. Allow it in your browser settings to dictate.'\n );\n case 'audio-capture':\n return tr('healthybowl.assistant.voice.noMic', 'No microphone was found.');\n case 'network':\n return tr('healthybowl.assistant.voice.network', 'Speech recognition is offline right now.');\n case 'language-not-supported':\n // The recogniser's language list is the browser vendor's, not ours, so\n // name the language and point at the browser rather than implying the\n // assistant is broken.\n return tr(\n 'healthybowl.assistant.voice.languageNotSupported',\n 'This browser cannot recognise spoken {{language}}. Try a different browser, or type instead.',\n { language: languageDisplayName(voice.language, locale) }\n );\n case 'unknown':\n return tr('healthybowl.assistant.voice.failed', 'Dictation stopped unexpectedly.');\n default:\n return null;\n }\n };\n\n const voiceError = voiceErrorMessage();\n\n return (\n <div className=\"flex-shrink-0 px-3 pb-3 pt-1.5\">\n <div\n onDragEnter={handleDragEnter}\n onDragLeave={handleDragLeave}\n onDragOver={handleDragOver}\n onDrop={handleDrop}\n className={`rounded-2xl border p-2 shadow-sm transition-colors focus-within:border-action-primary-bg focus-within:ring-2 focus-within:ring-action-primary-bg/15 ${\n isDraggingOver\n ? 'border-action-primary-bg border-dashed bg-action-primary-bg/5'\n : 'border-border-default bg-bg-sunken'\n }`}\n data-testid=\"assistant-composer\"\n >\n <AssistantAttachmentChips attachments={attachments} onRemove={remove} onRetry={retry} disabled={disabled} />\n\n {/* Input row: attach · textarea · mic · send */}\n <div className=\"flex items-end gap-2\">\n <AssistantAttachmentButton onFiles={addFiles} canAddMore={canAddMore} disabled={disabled} />\n\n <textarea\n ref={textareaRef}\n value={text}\n onChange={(event) => setText(event.target.value)}\n onKeyDown={handleKeyDown}\n onPaste={handlePaste}\n disabled={disabled}\n placeholder={\n isDraggingOver\n ? tr('healthybowl.assistant.composer.dropHere', 'Drop files to attach')\n : resolvedPlaceholder\n }\n rows={1}\n className=\"min-h-[36px] flex-1 resize-none self-center bg-transparent px-1 py-2 text-[15px] leading-relaxed text-text-primary placeholder:text-text-muted focus:outline-none disabled:opacity-50\"\n aria-label={tr('healthybowl.assistant.chatInput.ariaLabel', 'Message input')}\n data-testid=\"assistant-input\"\n />\n\n {/* Outside the dictation guard on purpose: this preference also\n decides what language the assistant REPLIES in, which works\n perfectly well on a browser with no speech recognition at all.\n Hiding it there left Firefox users unable to choose a reply\n language, which is most of what it is for. */}\n <AssistantLanguageSelector\n current={spokenLanguage}\n selected={assistantLanguage}\n onChange={setAssistantLanguage}\n disabled={disabled || voice.isListening}\n />\n\n {voice.isSupported && (\n <AssistantVoiceButton isListening={voice.isListening} onToggle={voice.toggle} disabled={disabled} />\n )}\n\n {/* The voice button takes the send slot while there is nothing to\n send — see AssistantVoiceSessionButton for why swapping rather\n than adding is the only option that fits. */}\n {/* Genuinely empty, NOT merely unsendable: `canSend` is also false\n while an attachment uploads or a turn is in flight, so keying off\n it would replace send even with a draft typed and ready. */}\n {onStartVoiceSession && trimmed.length === 0 && attachments.length === 0 && !voice.isListening ? (\n <AssistantVoiceSessionButton onStart={onStartVoiceSession} disabled={disabled} />\n ) : (\n <button\n type=\"button\"\n onClick={handleSend}\n disabled={!canSend}\n className={`flex size-9 flex-shrink-0 items-center justify-center rounded-full shadow-sm transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong ${\n canSend\n ? 'bg-action-primary-bg text-action-primary-text hover:scale-105 hover:bg-action-primary-bg-hover'\n : 'bg-bg-elevated text-text-muted'\n }`}\n aria-label={tr('healthybowl.assistant.chatInput.send', 'Send message')}\n data-testid=\"assistant-send\"\n >\n {disabled || attachmentsBusy ? (\n <Loader2 className=\"size-4 animate-spin\" />\n ) : (\n <ArrowUp className=\"size-4\" />\n )}\n </button>\n )}\n </div>\n\n {/* Mode pills */}\n {availableModes.length > 1 && (\n <div className=\"mt-2 px-0.5\">\n <AssistantModeSelector\n mode={mode}\n availableModes={availableModes}\n onModeChange={onModeChange}\n disabled={disabled}\n />\n </div>\n )}\n </div>\n\n {/* One status line under the card: live dictation > voice error >\n attachment rejection > failed upload > the keyboard hint. Announced\n politely so a screen-reader user hears dictation land without losing\n their place.\n\n The failed-upload line ranks below `rejection` (which is transient and\n describes the file the user just picked) but above the hint, because a\n disabled send button with no stated reason is the thing this whole\n change exists to avoid. */}\n <div className=\"mt-1.5 px-1 text-center text-[11px]\" aria-live=\"polite\">\n {/* ★ Three states, not two. `isListening` now waits for the recogniser's\n own `onstart`, which is the honest signal — but it left this line\n showing the idle hint after the user had already tapped the\n microphone, for the whole permission-prompt window. */}\n {voice.isStarting && !voice.isListening ? (\n <p className=\"text-text-muted\" data-testid=\"assistant-voice-starting\">\n {tr('healthybowl.assistant.voice.starting', 'Starting the microphone…')}\n </p>\n ) : voice.isListening ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-voice-status\">\n <span className=\"mr-1 inline-block size-1.5 rounded-full bg-status-error-text align-middle motion-safe:animate-pulse\" />\n {voice.interim ||\n tr('healthybowl.assistant.voice.listening', 'Listening… speak now, tap the square to stop')}\n </p>\n ) : voiceError ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-voice-error\">\n {voiceError}\n </p>\n ) : rejection ? (\n <button\n type=\"button\"\n onClick={clearRejection}\n className=\"text-status-error-text underline-offset-2 hover:underline\"\n data-testid=\"assistant-attachment-rejection\"\n >\n {rejectionMessage(rejection)}\n </button>\n ) : sendBlocker === 'failed' ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-attachment-blocked\">\n {failedAttachments.length === 1\n ? tr(\n 'healthybowl.assistant.attachments.blockedOne',\n \"{{name}} didn't upload. Retry or remove it before sending.\",\n { name: failedAttachments[0].filename }\n )\n : tr(\n 'healthybowl.assistant.attachments.blockedMany',\n \"{{count}} attachments didn't upload. Retry or remove them before sending.\",\n { count: failedAttachments.length }\n )}\n </p>\n ) : (\n <p className=\"text-text-muted\">\n {tr(\n 'healthybowl.assistant.composer.hint',\n 'Enter to send · Shift+Enter for newline · drag or paste files to attach'\n )}\n </p>\n )}\n </div>\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsDA,IAAM,IAAsB,KAmBf,KAAgC,EAC3C,WACA,cAAW,IACX,gBACA,UACA,mBACA,kBACA,6BACI;CACJ,IAAM,IAAK,EAAM,GACX,EAAE,cAAW,EAAQ,GACrB,IAAc,EAA4B,IAAI,GAC9C,CAAC,GAAM,KAAW,EAAS,EAAE,GAC7B,CAAC,GAAgB,KAAqB,EAAS,EAAK,GAGpD,IAAe,EAAO,CAAC,GAEvB,EACJ,gBACA,QAAQ,GACR,gBACA,cACA,aACA,WACA,UACA,UACA,mBACA,kBACE,EAAwB,GAEtB,IAAmB,GAAa,MAAmB;EACvD,GAAS,MAAa,IAAU,GAAG,EAAQ,QAAQ,QAAQ,EAAE,EAAE,GAAG,MAAW,CAAO;CACtF,GAAG,CAAC,CAAC,GAKC,IAAoB,GAAmB,MAAU,EAAM,iBAAiB,GACxE,IAAuB,GAAmB,MAAU,EAAM,oBAAoB,GAC9E,IAAiB,QACf,EAAyB,GAAmB,CAAM,GACxD,CAAC,GAAmB,CAAM,CAC5B,GAEM,IAAQ,EAAc;EAAE,YAAY;EAAkB,UAAU,EAAe;CAAI,CAAC,GAEpF,IACJ,KAAe,EAAG,8CAA8C,2BAA2B,GACvF,I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,WAAU;IACV,eAAY;cAEX,GAAiB,CAAS;GACrB,CAAA,IACN,MAAgB,WAClB,kBAAC,KAAD;IAAG,WAAU;IAAyB,eAAY;cAC/C,EAAkB,WAAW,IAC1B,EACE,gDACA,8DACA,EAAE,MAAM,EAAkB,GAAG,SAAS,CACxC,IACA,EACE,iDACA,6EACA,EAAE,OAAO,EAAkB,OAAO,CACpC;GACH,CAAA,IAEH,kBAAC,KAAD;IAAG,WAAU;cACV,EACC,uCACA,yEACF;GACC,CAAA;EAEF,CAAA,CACF;;AAET"}
1
+ {"version":3,"file":"AssistantComposer.js","names":[],"sources":["../../../../src/components/assistant/composer/AssistantComposer.tsx"],"sourcesContent":["import {\n useCallback,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n type ClipboardEvent,\n type DragEvent,\n type FC,\n type KeyboardEvent,\n} from 'react';\nimport { ArrowUp, Loader2 } from 'lucide-react';\nimport type { AssistantMode, AssistantModeConfig } from '@/types/assistant';\nimport { useI18n } from '@burdenoff/fe-libs/shared/providers/shell/I18nProvider';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { languageDisplayName } from '@/utils/speechVoices';\nimport { resolveAssistantLanguage } from '@/config/assistantLanguages';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { useVoiceInput } from '@/hooks/useVoiceInput';\nimport { useAssistantAttachments } from '@/hooks/useAssistantAttachments';\nimport {\n MAX_ATTACHMENTS,\n getSendableAttachments,\n type AssistantAttachment,\n type AttachmentRejection,\n} from '@/utils/assistantAttachments';\nimport { AssistantAttachmentButton } from './AssistantAttachmentButton';\nimport { AssistantAttachmentChips } from './AssistantAttachmentChips';\nimport { AssistantVoiceButton } from './AssistantVoiceButton';\nimport { AssistantLanguageSelector } from './AssistantLanguageSelector';\nimport { AssistantVoiceSessionButton } from '../voice/AssistantVoiceSessionButton';\nimport { AssistantModeSelector } from './AssistantModeSelector';\n\ninterface Props {\n /**\n * Send the message. `attachments` are already uploaded and ready; the chat\n * area folds them into the prompt and onto the user bubble.\n */\n onSend: (message: string, attachments: AssistantAttachment[]) => void;\n /** True while a turn is in-flight (assistant busy) — disables send + shows the spinner. */\n disabled?: boolean;\n placeholder?: string;\n mode: AssistantMode;\n /** Role-filtered list of modes the user may pick. */\n availableModes: AssistantModeConfig[];\n onModeChange: (mode: AssistantMode) => void;\n /**\n * Opens the hands-free voice conversation. Omitted where a voice session\n * cannot work at all (no speech input, or nothing able to speak the reply),\n * which is what hides the control rather than offering a dead button.\n */\n onStartVoiceSession?: () => void;\n}\n\nconst MAX_TEXTAREA_HEIGHT = 200;\n\n/**\n * AssistantComposer — the v2 input surface (per the ai-assistant-v2 mockups).\n *\n * A rounded card with, on the input row: a leading circular \"+\" attach control,\n * an auto-growing textarea, a microphone, and a prominent filled forest-green\n * circular send button. BELOW the input sit the mode pills (\"Ask\" active-green /\n * \"Take action\" outline); ABOVE it, chips for any pending attachments.\n *\n * Multimodal input (Workstreams 2–3) arrives through three converging paths —\n * the attach button, drag-and-drop onto the card, and paste (a screenshot from\n * the clipboard is the single most common way a user shares one) — plus voice\n * dictation, which appends recognised speech to the draft so it can still be\n * edited before sending.\n *\n * Fully controlled (React state for the text) with auto-grow via a layout\n * effect. Enter sends, Shift+Enter inserts a newline.\n */\nexport const AssistantComposer: FC<Props> = ({\n onSend,\n disabled = false,\n placeholder,\n mode,\n availableModes,\n onModeChange,\n onStartVoiceSession,\n}) => {\n const tr = useTr();\n const { locale } = useI18n();\n const textareaRef = useRef<HTMLTextAreaElement>(null);\n const [text, setText] = useState('');\n const [isDraggingOver, setIsDraggingOver] = useState(false);\n // Nested drag-enter/leave pairs fire for every child element; count them so\n // the highlight survives dragging across the textarea and buttons.\n const dragDepthRef = useRef(0);\n\n const {\n attachments,\n isBusy: attachmentsBusy,\n sendBlocker,\n rejection,\n addFiles,\n remove,\n retry,\n clear,\n clearRejection,\n canAddMore,\n } = useAssistantAttachments();\n\n const appendTranscript = useCallback((phrase: string) => {\n setText((current) => (current ? `${current.replace(/\\s+$/, '')} ${phrase}` : phrase));\n }, []);\n\n // One selection drives the recogniser, the reply language and the voice —\n // see `assistantLanguages`. `null` follows the interface language, which is\n // what this did unconditionally before.\n const assistantLanguage = useAssistantStore((state) => state.assistantLanguage);\n const setAssistantLanguage = useAssistantStore((state) => state.setAssistantLanguage);\n const spokenLanguage = useMemo(\n () => resolveAssistantLanguage(assistantLanguage, locale),\n [assistantLanguage, locale]\n );\n\n const voice = useVoiceInput({ onFinalize: appendTranscript, language: spokenLanguage.tag });\n\n const resolvedPlaceholder =\n placeholder ?? tr('healthybowl.assistant.composer.placeholder', 'Ask HealthyBowl anything…');\n const trimmed = text.trim();\n // Exactly what the model will be given — see `getSendableAttachments`.\n const sendableAttachments = getSendableAttachments(attachments);\n const failedAttachments = attachments.filter((attachment) => attachment.status === 'error');\n // A message may be attachments-only (\"what's wrong with this leaf?\" is often\n // just the photo), but never sends while an upload is in flight OR has failed:\n // `sendBlocker` covers both. Gating on the blocker rather than on\n // `attachmentsBusy` is what stops a turn going out that quietly omits a file\n // the user can still see attached — the chips are cleared by `clear()` below,\n // so the evidence would disappear at the same instant.\n const canSend = (trimmed.length > 0 || sendableAttachments.length > 0) && !disabled && sendBlocker === null;\n\n // Auto-grow the textarea to fit its content (capped), re-measured after every\n // value change so the card breathes as the user types.\n useLayoutEffect(() => {\n const textarea = textareaRef.current;\n if (!textarea) return;\n textarea.style.height = 'auto';\n textarea.style.height = `${Math.min(textarea.scrollHeight, MAX_TEXTAREA_HEIGHT)}px`;\n }, [text]);\n\n const handleSend = useCallback(() => {\n if (!canSend) return;\n // Dictation left running into a send would keep appending to a cleared\n // draft; stop it so the mic state matches what the user sees.\n // ★ `isActive`, not `isListening`. Sending during the permission window left\n // the recogniser running, and its trailing phrase landed in the draft this\n // line had just cleared — precisely what the comment above says it prevents.\n if (voice.isActive) voice.stop();\n onSend(text.trim(), sendableAttachments);\n setText('');\n clear();\n }, [canSend, onSend, text, sendableAttachments, clear, voice]);\n\n const handleKeyDown = useCallback(\n (event: KeyboardEvent<HTMLTextAreaElement>) => {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault();\n handleSend();\n }\n },\n [handleSend]\n );\n\n const handlePaste = useCallback(\n (event: ClipboardEvent<HTMLTextAreaElement>) => {\n const files = Array.from(event.clipboardData?.files ?? []);\n if (files.length === 0) return;\n // Only claim the paste when it carried files; a normal text paste (which\n // also exposes an empty `files`) must still land in the textarea.\n event.preventDefault();\n addFiles(files);\n },\n [addFiles]\n );\n\n const handleDragEnter = useCallback((event: DragEvent<HTMLDivElement>) => {\n if (!Array.from(event.dataTransfer?.types ?? []).includes('Files')) return;\n dragDepthRef.current += 1;\n setIsDraggingOver(true);\n }, []);\n\n const handleDragLeave = useCallback(() => {\n dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);\n if (dragDepthRef.current === 0) setIsDraggingOver(false);\n }, []);\n\n const handleDragOver = useCallback((event: DragEvent<HTMLDivElement>) => {\n if (!Array.from(event.dataTransfer?.types ?? []).includes('Files')) return;\n // Required for a drop to fire at all, and stops the browser from navigating\n // away to the dropped file.\n event.preventDefault();\n }, []);\n\n const handleDrop = useCallback(\n (event: DragEvent<HTMLDivElement>) => {\n event.preventDefault();\n dragDepthRef.current = 0;\n setIsDraggingOver(false);\n addFiles(event.dataTransfer?.files ?? null);\n },\n [addFiles]\n );\n\n const rejectionMessage = (reason: AttachmentRejection): string => {\n switch (reason) {\n case 'too-many':\n return tr('healthybowl.assistant.attachments.tooMany', 'You can attach up to {{max}} files per message.', {\n max: MAX_ATTACHMENTS,\n });\n case 'too-large':\n return tr('healthybowl.assistant.attachments.tooLarge', 'That file is larger than 10 MB.');\n case 'empty':\n return tr('healthybowl.assistant.attachments.empty', 'That file is empty.');\n case 'unreadable':\n return tr('healthybowl.assistant.attachments.unreadable', 'That file could not be read.');\n case 'unsupported-image':\n return tr(\n 'healthybowl.assistant.attachments.unsupportedImage',\n \"This device can't read that image format, so it can't be resized to send. Save it as JPEG and try again.\"\n );\n }\n };\n\n const voiceErrorMessage = (): string | null => {\n switch (voice.error) {\n case 'not-allowed':\n return tr(\n 'healthybowl.assistant.voice.denied',\n 'Microphone access is blocked. Allow it in your browser settings to dictate.'\n );\n case 'audio-capture':\n return tr('healthybowl.assistant.voice.noMic', 'No microphone was found.');\n case 'network':\n return tr('healthybowl.assistant.voice.network', 'Speech recognition is offline right now.');\n case 'language-not-supported':\n // The recogniser's language list is the browser vendor's, not ours, so\n // name the language and point at the browser rather than implying the\n // assistant is broken.\n return tr(\n 'healthybowl.assistant.voice.languageNotSupported',\n 'This browser cannot recognise spoken {{language}}. Try a different browser, or type instead.',\n { language: languageDisplayName(voice.language, locale) }\n );\n case 'unknown':\n return tr('healthybowl.assistant.voice.failed', 'Dictation stopped unexpectedly.');\n default:\n return null;\n }\n };\n\n const voiceError = voiceErrorMessage();\n\n return (\n <div className=\"flex-shrink-0 px-3 pb-3 pt-1.5\">\n <div\n onDragEnter={handleDragEnter}\n onDragLeave={handleDragLeave}\n onDragOver={handleDragOver}\n onDrop={handleDrop}\n className={`rounded-2xl border p-2 shadow-sm transition-colors focus-within:border-action-primary-bg focus-within:ring-2 focus-within:ring-action-primary-bg/15 ${\n isDraggingOver\n ? 'border-action-primary-bg border-dashed bg-action-primary-bg/5'\n : 'border-border-default bg-bg-sunken'\n }`}\n data-testid=\"assistant-composer\"\n >\n <AssistantAttachmentChips attachments={attachments} onRemove={remove} onRetry={retry} disabled={disabled} />\n\n {/* Input row: attach · textarea · mic · send */}\n <div className=\"flex items-end gap-2\">\n <AssistantAttachmentButton onFiles={addFiles} canAddMore={canAddMore} disabled={disabled} />\n\n <textarea\n ref={textareaRef}\n value={text}\n onChange={(event) => setText(event.target.value)}\n onKeyDown={handleKeyDown}\n onPaste={handlePaste}\n disabled={disabled}\n placeholder={\n isDraggingOver\n ? tr('healthybowl.assistant.composer.dropHere', 'Drop files to attach')\n : resolvedPlaceholder\n }\n rows={1}\n className=\"min-h-[36px] flex-1 resize-none self-center bg-transparent px-1 py-2 text-[15px] leading-relaxed text-text-primary placeholder:text-text-muted focus:outline-none disabled:opacity-50\"\n aria-label={tr('healthybowl.assistant.chatInput.ariaLabel', 'Message input')}\n data-testid=\"assistant-input\"\n />\n\n {/* Outside the dictation guard on purpose: this preference also\n decides what language the assistant REPLIES in, which works\n perfectly well on a browser with no speech recognition at all.\n Hiding it there left Firefox users unable to choose a reply\n language, which is most of what it is for. */}\n <AssistantLanguageSelector\n current={spokenLanguage}\n selected={assistantLanguage}\n onChange={setAssistantLanguage}\n disabled={disabled || voice.isActive}\n />\n\n {voice.isSupported && (\n <AssistantVoiceButton\n isListening={voice.isListening}\n isStarting={voice.isStarting}\n onToggle={voice.toggle}\n disabled={disabled}\n />\n )}\n\n {/* The voice button takes the send slot while there is nothing to\n send — see AssistantVoiceSessionButton for why swapping rather\n than adding is the only option that fits. */}\n {/* Genuinely empty, NOT merely unsendable: `canSend` is also false\n while an attachment uploads or a turn is in flight, so keying off\n it would replace send even with a draft typed and ready. */}\n {onStartVoiceSession && trimmed.length === 0 && attachments.length === 0 && !voice.isActive ? (\n <AssistantVoiceSessionButton onStart={onStartVoiceSession} disabled={disabled} />\n ) : (\n <button\n type=\"button\"\n onClick={handleSend}\n disabled={!canSend}\n className={`flex size-9 flex-shrink-0 items-center justify-center rounded-full shadow-sm transition-all focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong ${\n canSend\n ? 'bg-action-primary-bg text-action-primary-text hover:scale-105 hover:bg-action-primary-bg-hover'\n : 'bg-bg-elevated text-text-muted'\n }`}\n aria-label={tr('healthybowl.assistant.chatInput.send', 'Send message')}\n data-testid=\"assistant-send\"\n >\n {disabled || attachmentsBusy ? (\n <Loader2 className=\"size-4 animate-spin\" />\n ) : (\n <ArrowUp className=\"size-4\" />\n )}\n </button>\n )}\n </div>\n\n {/* Mode pills */}\n {availableModes.length > 1 && (\n <div className=\"mt-2 px-0.5\">\n <AssistantModeSelector\n mode={mode}\n availableModes={availableModes}\n onModeChange={onModeChange}\n disabled={disabled}\n />\n </div>\n )}\n </div>\n\n {/* One status line under the card: live dictation > voice error >\n attachment rejection > failed upload > the keyboard hint. Announced\n politely so a screen-reader user hears dictation land without losing\n their place.\n\n The failed-upload line ranks below `rejection` (which is transient and\n describes the file the user just picked) but above the hint, because a\n disabled send button with no stated reason is the thing this whole\n change exists to avoid. */}\n <div className=\"mt-1.5 px-1 text-center text-[11px]\" aria-live=\"polite\">\n {/* ★ Three states, not two. `isListening` now waits for the recogniser's\n own `onstart`, which is the honest signal — but it left this line\n showing the idle hint after the user had already tapped the\n microphone, for the whole permission-prompt window. */}\n {voice.isStarting && !voice.isListening ? (\n <p className=\"text-text-muted\" data-testid=\"assistant-voice-starting\">\n {tr('healthybowl.assistant.voice.starting', 'Starting the microphone…')}\n </p>\n ) : voice.isListening ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-voice-status\">\n <span className=\"mr-1 inline-block size-1.5 rounded-full bg-status-error-text align-middle motion-safe:animate-pulse\" />\n {voice.interim ||\n tr('healthybowl.assistant.voice.listening', 'Listening… speak now, tap the square to stop')}\n </p>\n ) : voiceError ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-voice-error\">\n {voiceError}\n </p>\n ) : rejection ? (\n <button\n type=\"button\"\n onClick={clearRejection}\n className=\"text-status-error-text underline-offset-2 hover:underline\"\n data-testid=\"assistant-attachment-rejection\"\n >\n {rejectionMessage(rejection)}\n </button>\n ) : sendBlocker === 'failed' ? (\n <p className=\"text-status-error-text\" data-testid=\"assistant-attachment-blocked\">\n {failedAttachments.length === 1\n ? tr(\n 'healthybowl.assistant.attachments.blockedOne',\n \"{{name}} didn't upload. Retry or remove it before sending.\",\n { name: failedAttachments[0].filename }\n )\n : tr(\n 'healthybowl.assistant.attachments.blockedMany',\n \"{{count}} attachments didn't upload. Retry or remove them before sending.\",\n { count: failedAttachments.length }\n )}\n </p>\n ) : (\n <p className=\"text-text-muted\">\n {tr(\n 'healthybowl.assistant.composer.hint',\n 'Enter to send · Sh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.js";
2
2
  import { Mic as t, Square as n } from "lucide-react";
3
3
  import { jsx as r, jsxs as i } from "react/jsx-runtime";
4
4
  //#region src/components/assistant/composer/AssistantVoiceButton.tsx
5
- var a = ({ isListening: a, onToggle: o, disabled: s = !1 }) => {
6
- let c = e(), l = a ? c("healthybowl.assistant.composer.voiceStop", "Stop dictation") : c("healthybowl.assistant.composer.voiceStart", "Dictate a message");
5
+ var a = ({ isListening: a, isStarting: o = !1, onToggle: s, disabled: c = !1 }) => {
6
+ let l = e(), u = a ? l("healthybowl.assistant.composer.voiceStop", "Stop dictation") : o ? l("healthybowl.assistant.composer.voiceStarting", "Starting the microphone — tap to cancel") : l("healthybowl.assistant.composer.voiceStart", "Dictate a message");
7
7
  return /* @__PURE__ */ r("button", {
8
8
  type: "button",
9
- onClick: o,
10
- disabled: s,
11
- title: l,
12
- "aria-label": l,
13
- "aria-pressed": a,
14
- className: `flex size-9 flex-shrink-0 items-center justify-center rounded-full border transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-not-allowed disabled:opacity-50 ${a ? "border-status-error-text/40 bg-status-error-bg/10 text-status-error-text" : "border-border-subtle bg-bg-elevated text-text-secondary hover:bg-bg-sunken hover:text-text-primary"}`,
9
+ onClick: s,
10
+ disabled: c,
11
+ title: u,
12
+ "aria-label": u,
13
+ "aria-pressed": a || o,
14
+ className: `flex size-9 flex-shrink-0 items-center justify-center rounded-full border transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-not-allowed disabled:opacity-50 ${a ? "border-status-error-text/40 bg-status-error-bg/10 text-status-error-text" : o ? "border-border-strong bg-bg-elevated text-text-secondary" : "border-border-subtle bg-bg-elevated text-text-secondary hover:bg-bg-sunken hover:text-text-primary"}`,
15
15
  "data-testid": "assistant-voice",
16
- children: a ? /* @__PURE__ */ i("span", {
16
+ "data-state": a ? "listening" : o ? "starting" : "idle",
17
+ children: o && !a ? /* @__PURE__ */ r(t, { className: "size-4 motion-safe:animate-pulse opacity-70" }) : a ? /* @__PURE__ */ i("span", {
17
18
  className: "relative flex items-center justify-center",
18
19
  children: [/* @__PURE__ */ r("span", { className: "absolute inline-flex size-7 rounded-full bg-status-error-bg/20 motion-safe:animate-ping" }), /* @__PURE__ */ r(n, { className: "relative size-3 fill-current" })]
19
20
  }) : /* @__PURE__ */ r(t, { className: "size-4" })
@@ -1 +1 @@
1
- {"version":3,"file":"AssistantVoiceButton.js","names":[],"sources":["../../../../src/components/assistant/composer/AssistantVoiceButton.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { Mic, Square } from 'lucide-react';\nimport { useTr } from '../../../shared/hooks/useTr';\n\ninterface Props {\n isListening: boolean;\n onToggle: () => void;\n disabled?: boolean;\n}\n\n/**\n * Microphone control in the composer — real speech-to-text (Workstream 2),\n * driven by `useVoiceInput`. While listening it becomes a stop button with a\n * live ring, so the control that starts dictation is also the one that ends it\n * (no hunting for a second affordance mid-sentence).\n *\n * The composer renders this only when the browser supports SpeechRecognition;\n * an unsupported engine gets no dead control at all.\n */\nexport const AssistantVoiceButton: FC<Props> = ({ isListening, onToggle, disabled = false }) => {\n const tr = useTr();\n const label = isListening\n ? tr('healthybowl.assistant.composer.voiceStop', 'Stop dictation')\n : tr('healthybowl.assistant.composer.voiceStart', 'Dictate a message');\n\n return (\n <button\n type=\"button\"\n onClick={onToggle}\n disabled={disabled}\n title={label}\n aria-label={label}\n aria-pressed={isListening}\n className={`flex size-9 flex-shrink-0 items-center justify-center rounded-full border transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-not-allowed disabled:opacity-50 ${\n isListening\n ? 'border-status-error-text/40 bg-status-error-bg/10 text-status-error-text'\n : 'border-border-subtle bg-bg-elevated text-text-secondary hover:bg-bg-sunken hover:text-text-primary'\n }`}\n data-testid=\"assistant-voice\"\n >\n {isListening ? (\n <span className=\"relative flex items-center justify-center\">\n {/* Pulsing ring reads as \"live\" at a glance; motion-safe so a\n reduced-motion user gets the colour change without the throb. */}\n <span className=\"absolute inline-flex size-7 rounded-full bg-status-error-bg/20 motion-safe:animate-ping\" />\n <Square className=\"relative size-3 fill-current\" />\n </span>\n ) : (\n <Mic className=\"size-4\" />\n )}\n </button>\n );\n};\n"],"mappings":";;;;AAmBA,IAAa,KAAmC,EAAE,gBAAa,aAAU,cAAW,SAAY;CAC9F,IAAM,IAAK,EAAM,GACX,IAAQ,IACV,EAAG,4CAA4C,gBAAgB,IAC/D,EAAG,6CAA6C,mBAAmB;CAEvE,OACE,kBAAC,UAAD;EACE,MAAK;EACL,SAAS;EACC;EACV,OAAO;EACP,cAAY;EACZ,gBAAc;EACd,WAAW,wNACT,IACI,6EACA;EAEN,eAAY;YAEX,IACC,kBAAC,QAAD;GAAM,WAAU;aAAhB,CAGE,kBAAC,QAAD,EAAM,WAAU,0FAA2F,CAAA,GAC3G,kBAAC,GAAD,EAAQ,WAAU,+BAAgC,CAAA,CAC9C;OAEN,kBAAC,GAAD,EAAK,WAAU,SAAU,CAAA;CAErB,CAAA;AAEZ"}
1
+ {"version":3,"file":"AssistantVoiceButton.js","names":[],"sources":["../../../../src/components/assistant/composer/AssistantVoiceButton.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { Mic, Square } from 'lucide-react';\nimport { useTr } from '../../../shared/hooks/useTr';\n\ninterface Props {\n isListening: boolean;\n /** Requested, not yet capturing — the permission prompt / start-up window. */\n isStarting?: boolean;\n onToggle: () => void;\n disabled?: boolean;\n}\n\n/**\n * Microphone control in the composer — real speech-to-text (Workstream 2),\n * driven by `useVoiceInput`. While listening it becomes a stop button with a\n * live ring, so the control that starts dictation is also the one that ends it\n * (no hunting for a second affordance mid-sentence).\n *\n * The composer renders this only when the browser supports SpeechRecognition;\n * an unsupported engine gets no dead control at all.\n */\nexport const AssistantVoiceButton: FC<Props> = ({ isListening, isStarting = false, onToggle, disabled = false }) => {\n const tr = useTr();\n // ★ Three states. Rendering the idle microphone while the browser is still\n // asking for permission told the user nothing had happened, so they pressed it\n // again — and the press was a no-op until `toggle` learned to cancel a pending\n // start. The icon now says which of the three it is.\n const label = isListening\n ? tr('healthybowl.assistant.composer.voiceStop', 'Stop dictation')\n : isStarting\n ? tr('healthybowl.assistant.composer.voiceStarting', 'Starting the microphone — tap to cancel')\n : tr('healthybowl.assistant.composer.voiceStart', 'Dictate a message');\n\n return (\n <button\n type=\"button\"\n onClick={onToggle}\n disabled={disabled}\n title={label}\n aria-label={label}\n aria-pressed={isListening || isStarting}\n className={`flex size-9 flex-shrink-0 items-center justify-center rounded-full border transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-not-allowed disabled:opacity-50 ${\n isListening\n ? 'border-status-error-text/40 bg-status-error-bg/10 text-status-error-text'\n : isStarting\n ? 'border-border-strong bg-bg-elevated text-text-secondary'\n : 'border-border-subtle bg-bg-elevated text-text-secondary hover:bg-bg-sunken hover:text-text-primary'\n }`}\n data-testid=\"assistant-voice\"\n data-state={isListening ? 'listening' : isStarting ? 'starting' : 'idle'}\n >\n {isStarting && !isListening ? (\n // Deliberately NOT disabled: this is the one moment the user most wants\n // a way out, and `toggle` now cancels the pending start.\n <Mic className=\"size-4 motion-safe:animate-pulse opacity-70\" />\n ) : isListening ? (\n <span className=\"relative flex items-center justify-center\">\n {/* Pulsing ring reads as \"live\" at a glance; motion-safe so a\n reduced-motion user gets the colour change without the throb. */}\n <span className=\"absolute inline-flex size-7 rounded-full bg-status-error-bg/20 motion-safe:animate-ping\" />\n <Square className=\"relative size-3 fill-current\" />\n </span>\n ) : (\n <Mic className=\"size-4\" />\n )}\n </button>\n );\n};\n"],"mappings":";;;;AAqBA,IAAa,KAAmC,EAAE,gBAAa,gBAAa,IAAO,aAAU,cAAW,SAAY;CAClH,IAAM,IAAK,EAAM,GAKX,IAAQ,IACV,EAAG,4CAA4C,gBAAgB,IAC/D,IACE,EAAG,gDAAgD,yCAAyC,IAC5F,EAAG,6CAA6C,mBAAmB;CAEzE,OACE,kBAAC,UAAD;EACE,MAAK;EACL,SAAS;EACC;EACV,OAAO;EACP,cAAY;EACZ,gBAAc,KAAe;EAC7B,WAAW,wNACT,IACI,6EACA,IACE,4DACA;EAER,eAAY;EACZ,cAAY,IAAc,cAAc,IAAa,aAAa;YAEjE,KAAc,CAAC,IAGd,kBAAC,GAAD,EAAK,WAAU,8CAA+C,CAAA,IAC5D,IACF,kBAAC,QAAD;GAAM,WAAU;aAAhB,CAGE,kBAAC,QAAD,EAAM,WAAU,0FAA2F,CAAA,GAC3G,kBAAC,GAAD,EAAQ,WAAU,+BAAgC,CAAA,CAC9C;OAEN,kBAAC,GAAD,EAAK,WAAU,SAAU,CAAA;CAErB,CAAA;AAEZ"}
@@ -1 +1 @@
1
- {"version":3,"file":"graphql.js","names":[],"sources":["../../../src/healthybowl/offline/graphql.ts"],"sourcesContent":["/**\n * GraphQL operations for the offline sync engine (BOFF-2883).\n *\n * These replay through fe-libs `graphqlFetch` (gateway: 'workspace'), which\n * re-derives auth (bearer + workspace dual-token + context headers) from\n * profile storage on every call — so the outbox never freezes a rotating token.\n * The workspaces public gateway enforces the `@rbac` directives.\n */\nimport { graphqlFetch } from '@burdenoff/fe-libs/shared/graphql';\nimport type { ServerObservation } from './types';\n\ninterface GqlError {\n message: string;\n extensions?: { code?: string; userMessage?: string };\n}\n\n/** Thrown when the gateway returns GraphQL errors (vs a transport failure). */\nexport class SyncGraphQLError extends Error {\n code: string;\n constructor(message: string, code: string) {\n super(message);\n this.name = 'SyncGraphQLError';\n this.code = code;\n }\n}\n\nfunction firstError(errors: GqlError[] | undefined): SyncGraphQLError | null {\n if (!errors || errors.length === 0) return null;\n const e = errors[0];\n return new SyncGraphQLError(e.extensions?.userMessage ?? e.message, e.extensions?.code ?? 'INTERNAL_SERVER_ERROR');\n}\n\ntype Ctx = { workspaceId: string };\n\nconst OBSERVATION_FIELDS = `\n id clientId fieldId fieldName observationType title note severity quantity unit\n cropName animalTag latitude longitude gpsAccuracy photoFileIds capturedAt\n capturedOffline syncedAt version createdBy createdAt updatedAt\n`;\n\nexport interface SyncInputItem {\n clientId: string;\n observationType: string;\n fieldId?: string | null;\n fieldName?: string | null;\n title?: string | null;\n note?: string | null;\n severity?: string | null;\n quantity?: number | null;\n unit?: string | null;\n cropName?: string | null;\n animalTag?: string | null;\n latitude?: number | null;\n longitude?: number | null;\n gpsAccuracy?: number | null;\n photoFileIds?: string[];\n capturedAt: string;\n capturedOffline?: boolean;\n baseVersion?: number | null;\n}\n\nexport interface SyncResultItem {\n clientId: string;\n outcome: 'SYNCED' | 'DUPLICATE' | 'CONFLICT' | 'FAILED';\n observation: ServerObservation | null;\n serverVersion: ServerObservation | null;\n message: string | null;\n}\n\nexport interface SyncResult {\n items: SyncResultItem[];\n syncedCount: number;\n duplicateCount: number;\n conflictCount: number;\n failedCount: number;\n}\n\nconst SYNC_MUTATION = `\n mutation SyncFieldObservations($input: SyncFieldObservationsInput!) {\n syncHealthyBowlFieldObservations(input: $input) {\n syncedCount duplicateCount conflictCount failedCount\n items {\n clientId outcome message\n observation { ${OBSERVATION_FIELDS} }\n serverVersion { ${OBSERVATION_FIELDS} }\n }\n }\n }\n`;\n\nexport async function syncObservations(ctx: Ctx, observations: SyncInputItem[]): Promise<SyncResult> {\n const res = await graphqlFetch<{ syncHealthyBowlFieldObservations: SyncResult }>({\n gateway: 'workspace',\n query: SYNC_MUTATION,\n variables: { input: { context: ctx, observations } },\n // The workspaces gateway enforces @rbac(scopeType:\"wspace\"); attach the workspace\n // dual-token + x-workspace-id so the call is authorized for this workspace.\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n const err = firstError(res.errors as GqlError[] | undefined);\n if (err) throw err;\n const data = res.data?.syncHealthyBowlFieldObservations;\n if (!data) throw new SyncGraphQLError('Empty sync response', 'INTERNAL_SERVER_ERROR');\n return data;\n}\n\n// ── Queued scheme applications (BOFF-6179) ───────────────────────────────────\n\nexport interface SchemeApplicationInput {\n schemeId: string;\n applicantName: string;\n farmName: string;\n declarationAccepted: true;\n /**\n * The idempotency key. The server holds a unique index on\n * (workspace, clientMutationId), so a replay after a dropped connection\n * returns the ORIGINAL application rather than lodging a second one.\n */\n clientMutationId: string;\n notes?: string | null;\n amount?: number | null;\n}\n\nexport interface SchemeApplicationResult {\n id: string;\n clientMutationId: string | null;\n status: string;\n}\n\nconst CREATE_SCHEME_APPLICATION = `\n mutation CreateHealthyBowlSchemeApplicationOffline($input: CreateSchemeApplicationInput!) {\n createHealthyBowlSchemeApplication(input: $input) {\n id\n clientMutationId\n status\n }\n }\n`;\n\n/**\n * Replay a queued scheme application.\n *\n * Deliberately NOT the Apollo hook in `useHealthyBowlData`: replay runs from the\n * sync engine, outside React, where no hook can be called. `status` and\n * `schemeName` are not sent — the resolver ignores both, and passing a\n * client-invented status would imply an authority the client does not have.\n */\nexport async function createSchemeApplication(\n ctx: Ctx,\n input: SchemeApplicationInput\n): Promise<SchemeApplicationResult> {\n const res = await graphqlFetch<{ createHealthyBowlSchemeApplication: SchemeApplicationResult }>({\n gateway: 'workspace',\n query: CREATE_SCHEME_APPLICATION,\n variables: { input: { ...input, context: ctx } },\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n const err = firstError(res.errors as GqlError[] | undefined);\n if (err) throw err;\n const data = res.data?.createHealthyBowlSchemeApplication;\n if (!data) throw new SyncGraphQLError('Empty application response', 'INTERNAL_SERVER_ERROR');\n return data;\n}\n\nexport interface ResolveInput {\n clientId: string;\n resolution: 'KEEP_MINE' | 'KEEP_SERVER' | 'MERGE';\n baseVersion: number;\n fieldId?: string | null;\n note?: string | null;\n severity?: string | null;\n quantity?: number | null;\n unit?: string | null;\n cropName?: string | null;\n animalTag?: string | null;\n latitude?: number | null;\n longitude?: number | null;\n photoFileIds?: string[];\n}\n\nconst RESOLVE_MUTATION = `\n mutation ResolveFieldObservationConflict($input: ResolveFieldObservationConflictInput!) {\n resolveHealthyBowlFieldObservationConflict(input: $input) { ${OBSERVATION_FIELDS} }\n }\n`;\n\nexport async function resolveConflict(ctx: Ctx, input: ResolveInput): Promise<ServerObservation> {\n const res = await graphqlFetch<{ resolveHealthyBowlFieldObservationConflict: ServerObservation }>({\n gateway: 'workspace',\n query: RESOLVE_MUTATION,\n variables: { input: { ...input, context: ctx } },\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n const err = firstError(res.errors as GqlError[] | undefined);\n if (err) throw err;\n const data = res.data?.resolveHealthyBowlFieldObservationConflict;\n if (!data) throw new SyncGraphQLError('Empty resolve response', 'INTERNAL_SERVER_ERROR');\n return data;\n}\n\nexport interface FieldCaptureData {\n fields: Array<{ id: string; name: string; cropNames: string[] }>;\n recentObservations: ServerObservation[];\n stats: {\n totalObservations: number;\n observationsToday: number;\n byType: Array<{ observationType: string; count: number }>;\n };\n updatedAt: string;\n}\n\nconst CAPTURE_DATA_QUERY = `\n query FieldCaptureData($context: ContextInput!) {\n getHealthyBowlFieldCaptureData(context: $context) {\n fields { id name cropNames }\n recentObservations { ${OBSERVATION_FIELDS} }\n stats { totalObservations observationsToday byType { observationType count } }\n updatedAt\n }\n }\n`;\n\nexport async function fetchFieldCaptureData(ctx: Ctx): Promise<FieldCaptureData | null> {\n const res = await graphqlFetch<{ getHealthyBowlFieldCaptureData: FieldCaptureData }>({\n gateway: 'workspace',\n query: CAPTURE_DATA_QUERY,\n variables: { context: ctx },\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n if (res.errors && res.errors.length) return null;\n return res.data?.getHealthyBowlFieldCaptureData ?? null;\n}\n\n// ── The server-backed observation log (BOFF-6048) ────────────────────────────────────────────\n//\n// `syncHealthyBowlFieldObservations` writes a real FieldObservation row, and until now that row\n// had NO READER anywhere in the product: every Field Capture screen showed the device-local\n// IndexedDB outbox. A capture was therefore invisible from a second device or browser, and\n// unreachable entirely once local storage was cleared, while the server row lived on with no way\n// to view or delete it. On a farm where workers capture on their own phones, a manager had no\n// server-backed view of any of it.\n//\n// These two are the ops that were already deployed and never called.\n\nexport interface ObservationFilter {\n observationType?: string | null;\n fieldId?: string | null;\n limit?: number;\n offset?: number;\n}\n\nconst OBSERVATIONS_QUERY = `\n query HealthyBowlFieldObservations($context: ContextInput!, $filter: FieldObservationFilterInput) {\n getHealthyBowlFieldObservations(context: $context, filter: $filter) { ${OBSERVATION_FIELDS} }\n }\n`;\n\n/**\n * The workspace's synced observations, straight from the server — not the device outbox.\n * Returns null on error so a failed read leaves the page rendering rather than blanking it.\n */\nexport async function fetchServerObservations(\n ctx: Ctx,\n filter: ObservationFilter = {}\n): Promise<ServerObservation[] | null> {\n const res = await graphqlFetch<{ getHealthyBowlFieldObservations: ServerObservation[] }>({\n gateway: 'workspace',\n query: OBSERVATIONS_QUERY,\n variables: { context: ctx, filter },\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n if (res.errors && res.errors.length) return null;\n return res.data?.getHealthyBowlFieldObservations ?? null;\n}\n\nconst DELETE_OBSERVATION_MUTATION = `\n mutation DeleteHealthyBowlFieldObservation($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlFieldObservation(id: $id, context: $context)\n }\n`;\n\n/** Delete a SERVER observation. Throws on failure — a delete that silently no-ops is worse. */\nexport async function deleteServerObservation(ctx: Ctx, id: string): Promise<boolean> {\n const res = await graphqlFetch<{ deleteHealthyBowlFieldObservation: boolean }>({\n gateway: 'workspace',\n query: DELETE_OBSERVATION_MUTATION,\n variables: { id, context: ctx },\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n const err = firstError(res.errors as GqlError[] | undefined);\n if (err) throw err;\n return res.data?.deleteHealthyBowlFieldObservation ?? false;\n}\n\nconst DOWNLOAD_URL_QUERY = `\n query HealthyBowlObservationPhotoUrl($id: ID!) {\n getFileDownloadUrl(id: $id, expiresIn: 21600)\n }\n`;\n\n/** Presigned URL for a synced photo (6h TTL, well under the S3 7-day cap). */\nexport async function fetchPhotoUrl(id: string): Promise<string | null> {\n try {\n const res = await graphqlFetch<{ getFileDownloadUrl: string | null }>({\n gateway: 'workspace',\n query: DOWNLOAD_URL_QUERY,\n variables: { id },\n workspaceToken: true,\n workspaceId: true,\n suppressGlobalErrorEvent: true,\n });\n if (res.errors && res.errors.length) return null;\n return res.data?.getFileDownloadUrl ?? null;\n } catch {\n return null;\n }\n}\n"],"mappings":";;AAiBA,IAAa,IAAb,cAAsC,MAAM;CAC1C;CACA,YAAY,GAAiB,GAAc;EAGzC,AAFA,MAAM,CAAO,GACb,KAAK,OAAO,oBACZ,KAAK,OAAO;CACd;AACF;AAEA,SAAS,EAAW,GAAyD;CAC3E,IAAI,CAAC,KAAU,EAAO,WAAW,GAAG,OAAO;CAC3C,IAAM,IAAI,EAAO;CACjB,OAAO,IAAI,EAAiB,EAAE,YAAY,eAAe,EAAE,SAAS,EAAE,YAAY,QAAQ,uBAAuB;AACnH;AAIA,IAAM,IAAqB,wOA2CrB,IAAgB;;;;;;wBAME,EAAmB;0BACjB,EAAmB;;;;;AAM7C,eAAsB,EAAiB,GAAU,GAAoD;CACnG,IAAM,IAAM,MAAM,EAA+D;EAC/E,SAAS;EACT,OAAO;EACP,WAAW,EAAE,OAAO;GAAE,SAAS;GAAK;EAAa,EAAE;EAGnD,gBAAgB;EAChB,aAAa,EAAI;EACjB,0BAA0B;CAC5B,CAAC,GACK,IAAM,EAAW,EAAI,MAAgC;CAC3D,IAAI,GAAK,MAAM;CACf,IAAM,IAAO,EAAI,MAAM;CACvB,IAAI,CAAC,GAAM,MAAM,IAAI,EAAiB,uBAAuB,uBAAuB;CACpF,OAAO;AACT;AAyBA,IAAM,IAA4B;AAkBlC,eAAsB,EACpB,GACA,GACkC;CAClC,IAAM,IAAM,MAAM,EAA8E;EAC9F,SAAS;EACT,OAAO;EACP,WAAW,EAAE,OAAO;GAAE,GAAG;GAAO,SAAS;EAAI,EAAE;EAC/C,gBAAgB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8B;AAOpC,eAAsB,EAAwB,GAAU,GAA8B;CACpF,IAAM,IAAM,MAAM,EAA6D;EAC7E,SAAS;EACT,OAAO;EACP,WAAW;GAAE;GAAI,SAAS;EAAI;EAC9B,gBAAgB;EAChB,aAAa,EAAI;EACjB,0BAA0B;CAC5B,CAAC,GACK,IAAM,EAAW,EAAI,MAAgC;CAC3D,IAAI,GAAK,MAAM;CACf,OAAO,EAAI,MAAM,qCAAqC;AACxD"}
1
+ {"version":3,"file":"graphql.js","names":[],"sources":["../../../src/healthybowl/offline/graphql.ts"],"sourcesContent":["/**\n * GraphQL operations for the offline sync engine (BOFF-2883).\n *\n * These replay through fe-libs `graphqlFetch` (gateway: 'workspace'), which\n * re-derives auth (bearer + workspace dual-token + context headers) from\n * profile storage on every call — so the outbox never freezes a rotating token.\n * The workspaces public gateway enforces the `@rbac` directives.\n */\nimport { graphqlFetch } from '@burdenoff/fe-libs/shared/graphql';\nimport type { ServerObservation } from './types';\n\ninterface GqlError {\n message: string;\n extensions?: { code?: string; userMessage?: string };\n}\n\n/** Thrown when the gateway returns GraphQL errors (vs a transport failure). */\nexport class SyncGraphQLError extends Error {\n code: string;\n constructor(message: string, code: string) {\n super(message);\n this.name = 'SyncGraphQLError';\n this.code = code;\n }\n}\n\nfunction firstError(errors: GqlError[] | undefined): SyncGraphQLError | null {\n if (!errors || errors.length === 0) return null;\n const e = errors[0];\n return new SyncGraphQLError(e.extensions?.userMessage ?? e.message, e.extensions?.code ?? 'INTERNAL_SERVER_ERROR');\n}\n\ntype Ctx = { workspaceId: string };\n\nconst OBSERVATION_FIELDS = `\n id clientId fieldId fieldName observationType title note severity quantity unit\n cropName animalTag latitude longitude gpsAccuracy photoFileIds capturedAt\n capturedOffline syncedAt version createdBy createdAt updatedAt\n`;\n\nexport interface SyncInputItem {\n clientId: string;\n observationType: string;\n fieldId?: string | null;\n fieldName?: string | null;\n title?: string | null;\n note?: string | null;\n severity?: string | null;\n quantity?: number | null;\n unit?: string | null;\n cropName?: string | null;\n animalTag?: string | null;\n latitude?: number | null;\n longitude?: number | null;\n gpsAccuracy?: number | null;\n photoFileIds?: string[];\n capturedAt: string;\n capturedOffline?: boolean;\n baseVersion?: number | null;\n}\n\nexport interface SyncResultItem {\n clientId: string;\n outcome: 'SYNCED' | 'DUPLICATE' | 'CONFLICT' | 'FAILED';\n observation: ServerObservation | null;\n serverVersion: ServerObservation | null;\n message: string | null;\n}\n\nexport interface SyncResult {\n items: SyncResultItem[];\n syncedCount: number;\n duplicateCount: number;\n conflictCount: number;\n failedCount: number;\n}\n\nconst SYNC_MUTATION = `\n mutation SyncFieldObservations($input: SyncFieldObservationsInput!) {\n syncHealthyBowlFieldObservations(input: $input) {\n syncedCount duplicateCount conflictCount failedCount\n items {\n clientId outcome message\n observation { ${OBSERVATION_FIELDS} }\n serverVersion { ${OBSERVATION_FIELDS} }\n }\n }\n }\n`;\n\nexport async function syncObservations(ctx: Ctx, observations: SyncInputItem[]): Promise<SyncResult> {\n const res = await graphqlFetch<{ syncHealthyBowlFieldObservations: SyncResult }>({\n gateway: 'workspace',\n query: SYNC_MUTATION,\n variables: { input: { context: ctx, observations } },\n // The workspaces gateway enforces @rbac(scopeType:\"wspace\"); attach the workspace\n // dual-token + x-workspace-id so the call is authorized for this workspace.\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n const err = firstError(res.errors as GqlError[] | undefined);\n if (err) throw err;\n const data = res.data?.syncHealthyBowlFieldObservations;\n if (!data) throw new SyncGraphQLError('Empty sync response', 'INTERNAL_SERVER_ERROR');\n return data;\n}\n\n// ── Queued scheme applications (BOFF-6179) ───────────────────────────────────\n\nexport interface SchemeDocumentInput {\n slot: string;\n fileId: string;\n fileName?: string | null;\n uploadedAt?: string | null;\n}\n\nexport interface SchemeApplicationInput {\n schemeId: string;\n applicantName: string;\n farmName: string;\n declarationAccepted: true;\n /**\n * The idempotency key. The server holds a unique index on\n * (workspace, clientMutationId), so a replay after a dropped connection\n * returns the ORIGINAL application rather than lodging a second one.\n */\n clientMutationId: string;\n notes?: string | null;\n amount?: number | null;\n /**\n * Supporting evidence (BOFF-6111). The server refuses a PARTIAL set — an application that\n * attaches some required documents but not all — and accepts an empty one, so an older queued\n * mutation replayed after this ships still drains rather than failing forever.\n */\n documents?: SchemeDocumentInput[];\n}\n\nexport interface SchemeApplicationResult {\n id: string;\n clientMutationId: string | null;\n status: string;\n}\n\nconst CREATE_SCHEME_APPLICATION = `\n mutation CreateHealthyBowlSchemeApplicationOffline($input: CreateSchemeApplicationInput!) {\n createHealthyBowlSchemeApplication(input: $input) {\n id\n clientMutationId\n status\n }\n }\n`;\n\n/**\n * Replay a queued scheme application.\n *\n * Deliberately NOT the Apollo hook in `useHealthyBowlData`: replay runs from the\n * sync engine, outside React, where no hook can be called. `status` and\n * `schemeName` are not sent — the resolver ignores both, and passing a\n * client-invented status would imply an authority the client does not have.\n */\nexport async function createSchemeApplication(\n ctx: Ctx,\n input: SchemeApplicationInput\n): Promise<SchemeApplicationResult> {\n const res = await graphqlFetch<{ createHealthyBowlSchemeApplication: SchemeApplicationResult }>({\n gateway: 'workspace',\n query: CREATE_SCHEME_APPLICATION,\n variables: { input: { ...input, context: ctx } },\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n const err = firstError(res.errors as GqlError[] | undefined);\n if (err) throw err;\n const data = res.data?.createHealthyBowlSchemeApplication;\n if (!data) throw new SyncGraphQLError('Empty application response', 'INTERNAL_SERVER_ERROR');\n return data;\n}\n\nexport interface ResolveInput {\n clientId: string;\n resolution: 'KEEP_MINE' | 'KEEP_SERVER' | 'MERGE';\n baseVersion: number;\n fieldId?: string | null;\n note?: string | null;\n severity?: string | null;\n quantity?: number | null;\n unit?: string | null;\n cropName?: string | null;\n animalTag?: string | null;\n latitude?: number | null;\n longitude?: number | null;\n photoFileIds?: string[];\n}\n\nconst RESOLVE_MUTATION = `\n mutation ResolveFieldObservationConflict($input: ResolveFieldObservationConflictInput!) {\n resolveHealthyBowlFieldObservationConflict(input: $input) { ${OBSERVATION_FIELDS} }\n }\n`;\n\nexport async function resolveConflict(ctx: Ctx, input: ResolveInput): Promise<ServerObservation> {\n const res = await graphqlFetch<{ resolveHealthyBowlFieldObservationConflict: ServerObservation }>({\n gateway: 'workspace',\n query: RESOLVE_MUTATION,\n variables: { input: { ...input, context: ctx } },\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n const err = firstError(res.errors as GqlError[] | undefined);\n if (err) throw err;\n const data = res.data?.resolveHealthyBowlFieldObservationConflict;\n if (!data) throw new SyncGraphQLError('Empty resolve response', 'INTERNAL_SERVER_ERROR');\n return data;\n}\n\nexport interface FieldCaptureData {\n fields: Array<{ id: string; name: string; cropNames: string[] }>;\n recentObservations: ServerObservation[];\n stats: {\n totalObservations: number;\n observationsToday: number;\n byType: Array<{ observationType: string; count: number }>;\n };\n updatedAt: string;\n}\n\nconst CAPTURE_DATA_QUERY = `\n query FieldCaptureData($context: ContextInput!) {\n getHealthyBowlFieldCaptureData(context: $context) {\n fields { id name cropNames }\n recentObservations { ${OBSERVATION_FIELDS} }\n stats { totalObservations observationsToday byType { observationType count } }\n updatedAt\n }\n }\n`;\n\nexport async function fetchFieldCaptureData(ctx: Ctx): Promise<FieldCaptureData | null> {\n const res = await graphqlFetch<{ getHealthyBowlFieldCaptureData: FieldCaptureData }>({\n gateway: 'workspace',\n query: CAPTURE_DATA_QUERY,\n variables: { context: ctx },\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n if (res.errors && res.errors.length) return null;\n return res.data?.getHealthyBowlFieldCaptureData ?? null;\n}\n\n// ── The server-backed observation log (BOFF-6048) ────────────────────────────────────────────\n//\n// `syncHealthyBowlFieldObservations` writes a real FieldObservation row, and until now that row\n// had NO READER anywhere in the product: every Field Capture screen showed the device-local\n// IndexedDB outbox. A capture was therefore invisible from a second device or browser, and\n// unreachable entirely once local storage was cleared, while the server row lived on with no way\n// to view or delete it. On a farm where workers capture on their own phones, a manager had no\n// server-backed view of any of it.\n//\n// These two are the ops that were already deployed and never called.\n\nexport interface ObservationFilter {\n observationType?: string | null;\n fieldId?: string | null;\n limit?: number;\n offset?: number;\n}\n\nconst OBSERVATIONS_QUERY = `\n query HealthyBowlFieldObservations($context: ContextInput!, $filter: FieldObservationFilterInput) {\n getHealthyBowlFieldObservations(context: $context, filter: $filter) { ${OBSERVATION_FIELDS} }\n }\n`;\n\n/**\n * The workspace's synced observations, straight from the server — not the device outbox.\n * Returns null on error so a failed read leaves the page rendering rather than blanking it.\n */\nexport async function fetchServerObservations(\n ctx: Ctx,\n filter: ObservationFilter = {}\n): Promise<ServerObservation[] | null> {\n const res = await graphqlFetch<{ getHealthyBowlFieldObservations: ServerObservation[] }>({\n gateway: 'workspace',\n query: OBSERVATIONS_QUERY,\n variables: { context: ctx, filter },\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n if (res.errors && res.errors.length) return null;\n return res.data?.getHealthyBowlFieldObservations ?? null;\n}\n\nconst DELETE_OBSERVATION_MUTATION = `\n mutation DeleteHealthyBowlFieldObservation($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlFieldObservation(id: $id, context: $context)\n }\n`;\n\n/** Delete a SERVER observation. Throws on failure — a delete that silently no-ops is worse. */\nexport async function deleteServerObservation(ctx: Ctx, id: string): Promise<boolean> {\n const res = await graphqlFetch<{ deleteHealthyBowlFieldObservation: boolean }>({\n gateway: 'workspace',\n query: DELETE_OBSERVATION_MUTATION,\n variables: { id, context: ctx },\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n const err = firstError(res.errors as GqlError[] | undefined);\n if (err) throw err;\n return res.data?.deleteHealthyBowlFieldObservation ?? false;\n}\n\nconst DOWNLOAD_URL_QUERY = `\n query HealthyBowlObservationPhotoUrl($id: ID!) {\n getFileDownloadUrl(id: $id, expiresIn: 21600)\n }\n`;\n\n/** Presigned URL for a synced photo (6h TTL, well under the S3 7-day cap). */\nexport async function fetchPhotoUrl(id: string): Promise<string | null> {\n try {\n const res = await graphqlFetch<{ getFileDownloadUrl: string | null }>({\n gateway: 'workspace',\n query: DOWNLOAD_URL_QUERY,\n variables: { id },\n workspaceToken: true,\n workspaceId: true,\n suppressGlobalErrorEvent: true,\n });\n if (res.errors && res.errors.length) return null;\n return res.data?.getFileDownloadUrl ?? null;\n } catch {\n return null;\n }\n}\n"],"mappings":";;AAiBA,IAAa,IAAb,cAAsC,MAAM;CAC1C;CACA,YAAY,GAAiB,GAAc;EAGzC,AAFA,MAAM,CAAO,GACb,KAAK,OAAO,oBACZ,KAAK,OAAO;CACd;AACF;AAEA,SAAS,EAAW,GAAyD;CAC3E,IAAI,CAAC,KAAU,EAAO,WAAW,GAAG,OAAO;CAC3C,IAAM,IAAI,EAAO;CACjB,OAAO,IAAI,EAAiB,EAAE,YAAY,eAAe,EAAE,SAAS,EAAE,YAAY,QAAQ,uBAAuB;AACnH;AAIA,IAAM,IAAqB,wOA2CrB,IAAgB;;;;;;wBAME,EAAmB;0BACjB,EAAmB;;;;;AAM7C,eAAsB,EAAiB,GAAU,GAAoD;CACnG,IAAM,IAAM,MAAM,EAA+D;EAC/E,SAAS;EACT,OAAO;EACP,WAAW,EAAE,OAAO;GAAE,SAAS;GAAK;EAAa,EAAE;EAGnD,gBAAgB;EAChB,aAAa,EAAI;EACjB,0BAA0B;CAC5B,CAAC,GACK,IAAM,EAAW,EAAI,MAAgC;CAC3D,IAAI,GAAK,MAAM;CACf,IAAM,IAAO,EAAI,MAAM;CACvB,IAAI,CAAC,GAAM,MAAM,IAAI,EAAiB,uBAAuB,uBAAuB;CACpF,OAAO;AACT;AAsCA,IAAM,IAA4B;AAkBlC,eAAsB,EACpB,GACA,GACkC;CAClC,IAAM,IAAM,MAAM,EAA8E;EAC9F,SAAS;EACT,OAAO;EACP,WAAW,EAAE,OAA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AAe,OACrC,EAAI,MAAM,mCAAmC;AACtD;AAEA,IAAM,IAA8B;AAOpC,eAAsB,EAAwB,GAAU,GAA8B;CACpF,IAAM,IAAM,MAAM,EAA6D;EAC7E,SAAS;EACT,OAAO;EACP,WAAW;GAAE;GAAI,SAAS;EAAI;EAC9B,gBAAgB;EAChB,aAAa,EAAI;EACjB,0BAA0B;CAC5B,CAAC,GACK,IAAM,EAAW,EAAI,MAAgC;CAC3D,IAAI,GAAK,MAAM;CACf,OAAO,EAAI,MAAM,qCAAqC;AACxD"}
@@ -87,7 +87,8 @@ async function y(e, t) {
87
87
  declarationAccepted: r.payload.declarationAccepted,
88
88
  clientMutationId: r.clientId,
89
89
  notes: r.payload.notes ?? null,
90
- amount: r.payload.amount ?? null
90
+ amount: r.payload.amount ?? null,
91
+ ...r.payload.documents && r.payload.documents.length > 0 ? { documents: r.payload.documents } : {}
91
92
  });
92
93
  r.status = "SYNCED", r.serverId = n.id, r.serverStatus = n.status, r.syncedAt = f(), r.message = null, t.mutationsSynced += 1;
93
94
  } catch (e) {
@@ -1 +1 @@
1
- {"version":3,"file":"syncEngine.js","names":[],"sources":["../../../src/healthybowl/offline/syncEngine.ts"],"sourcesContent":["/**\n * Sync engine (BOFF-2883).\n *\n * Drains the local outbox when connectivity returns: uploads any offline-captured\n * photo blobs to files-svc, then replays the queued observations through the\n * idempotent `syncHealthyBowlFieldObservations` mutation and reconciles each\n * record's local status from the per-item outcome (Synced / Conflict / Failed).\n *\n * The engine is dependency-injected (workspace id, the fe-libs file-upload\n * function, current settings + network state) so it stays pure and testable and\n * can be driven from the OfflineSyncProvider.\n */\nimport type {\n LocalObservation,\n LocalPhoto,\n OfflineSettings,\n NetworkState,\n PendingMutation,\n SyncHistoryEntry,\n} from './types';\nimport {\n getAllObservations,\n saveObservation,\n getPhoto,\n savePhoto,\n addHistoryEntry,\n getAllPendingMutations,\n savePendingMutation,\n} from './store';\nimport {\n syncObservations,\n createSchemeApplication,\n SyncGraphQLError,\n type SyncInputItem,\n type SyncResultItem,\n} from './graphql';\nimport { isWifi } from './network';\n\n/** fe-libs `useSaveToFiles().save` shape — uploads a blob, returns its files-svc id. */\nexport type SaveToFiles = (args: {\n source: {\n kind: 'blob';\n filename: string;\n mimeType: string;\n getBlob: () => Promise<{ blob: Blob; filename: string; mimeType: string }>;\n };\n folderPath: string;\n}) => Promise<{ id: string }>;\n\nexport interface SyncDeps {\n workspaceId: string;\n saveToFiles: SaveToFiles;\n settings: OfflineSettings;\n network: NetworkState;\n}\n\nexport interface DrainSummary {\n attempted: number;\n synced: number;\n duplicate: number;\n conflict: number;\n failed: number;\n /**\n * Failures that have used up every retry (BOFF-6364 review).\n *\n * A record at `MAX_ATTEMPTS` is excluded by `isSyncable` from every subsequent drain, so\n * it will never be retried. Counting it separately keeps the toast from promising a retry\n * that cannot happen — the exact class of dishonest status this ticket exists to remove.\n * These are a SUBSET of `failed`, not an addition to it.\n */\n exhausted: number;\n /**\n * Every record left in the outbox that can never sync again — including ones that used up\n * their retries in an EARLIER drain (BOFF-6364 review).\n *\n * `exhausted` only counts records that became terminal during THIS drain, so on the next\n * Sync Now `isSyncable` filters the stranded record out, the summary comes back empty, and\n * the toast would fall through to \"All synced — nothing is waiting\" while Pending Sync\n * still lists it. That is the original BOFF-6364 lie, re-entered by the back door. This\n * counter is read from the store, so it survives across drains.\n */\n terminalPending: number;\n skipped: number;\n photosUploaded: number;\n /** Queued non-observation writes that reached the server (BOFF-6179). */\n mutationsSynced: number;\n /** Queued non-observation writes that did not. */\n mutationsFailed: number;\n}\n\nconst PHOTO_FOLDER = '/HealthyBowl/FieldObservation';\n/**\n * Retry cap. Exported so the UI can tell a record that is merely failing from one that can\n * never be sent again — the two need different affordances, not just different wording.\n */\nexport const MAX_ATTEMPTS = 8;\n\nfunction now(): string {\n return new Date().toISOString();\n}\n\nfunction uid(prefix: string): string {\n const rand =\n typeof crypto !== 'undefined' && crypto.randomUUID\n ? crypto.randomUUID()\n : `${Date.now()}-${Math.round(Math.random() * 1e9)}`;\n return `${prefix}-${rand}`;\n}\n\n/** Records eligible to sync now (queued or previously-failed, under the retry cap). */\nfunction isSyncable(o: LocalObservation): boolean {\n return (o.status === 'QUEUED' || o.status === 'FAILED') && o.attempts < MAX_ATTEMPTS;\n}\n\n/**\n * Upload any not-yet-uploaded photo blobs for a record and return the resolved\n * files-svc ids. Honors the \"upload photos on Wi-Fi only\" setting by signalling\n * a defer (returns null) when the record still has local blobs and we're metered.\n */\nasync function resolvePhotoFileIds(\n obs: LocalObservation,\n deps: SyncDeps\n): Promise<{ fileIds: string[]; uploaded: number } | null> {\n // Rebuild the fileId list from the AUTHORITATIVE per-photo records (in capture\n // order), not from the possibly-stale obs.photoFileIds snapshot. A prior partial\n // upload persists each photo's fileId on its own record, so already-uploaded\n // photos are never dropped on retry.\n const photos: LocalPhoto[] = [];\n for (const pid of obs.photoLocalIds) {\n const p = await getPhoto(pid);\n if (p) photos.push(p);\n }\n const needsUpload = photos.some((p) => !p.fileId);\n\n // Metered connection + Wi-Fi-only preference → defer the whole record so its\n // photos and observation reach the server together on Wi-Fi.\n if (needsUpload && deps.settings.uploadPhotosOnWifiOnly && !isWifi(deps.network)) {\n return null;\n }\n\n let uploaded = 0;\n const fileIds: string[] = [];\n for (const photo of photos) {\n if (photo.fileId) {\n fileIds.push(photo.fileId);\n continue;\n }\n const saved = await deps.saveToFiles({\n source: {\n kind: 'blob',\n filename: photo.filename,\n mimeType: photo.mimeType,\n getBlob: async () => ({ blob: photo.blob, filename: photo.filename, mimeType: photo.mimeType }),\n },\n folderPath: PHOTO_FOLDER,\n });\n // Persist the fileId immediately so a later failure in this loop never re-uploads\n // this photo or loses its id.\n photo.fileId = saved.id;\n await savePhoto(photo);\n fileIds.push(saved.id);\n uploaded += 1;\n }\n return { fileIds, uploaded };\n}\n\nfunction toSyncInput(obs: LocalObservation, photoFileIds: string[]): SyncInputItem {\n return {\n clientId: obs.clientId,\n observationType: obs.observationType,\n fieldId: obs.fieldId ?? null,\n fieldName: obs.fieldName ?? null,\n title: obs.title ?? null,\n note: obs.note ?? null,\n severity: obs.severity ?? null,\n quantity: obs.quantity ?? null,\n unit: obs.unit ?? null,\n cropName: obs.cropName ?? null,\n animalTag: obs.animalTag ?? null,\n latitude: obs.latitude ?? null,\n longitude: obs.longitude ?? null,\n gpsAccuracy: obs.gpsAccuracy ?? null,\n photoFileIds,\n capturedAt: obs.capturedAt,\n capturedOffline: obs.capturedOffline,\n baseVersion: obs.baseVersion,\n };\n}\n\nasync function applyOutcome(obs: LocalObservation, item: SyncResultItem | undefined): Promise<void> {\n const ts = now();\n if (!item) {\n obs.status = 'FAILED';\n obs.message = 'No result returned for this record';\n obs.attempts += 1;\n } else if (item.outcome === 'SYNCED' || item.outcome === 'DUPLICATE') {\n obs.status = 'SYNCED';\n obs.serverId = item.observation?.id ?? obs.serverId ?? null;\n obs.baseVersion = item.observation?.version ?? obs.baseVersion;\n obs.syncedAt = item.observation?.syncedAt ?? ts;\n obs.serverVersion = null;\n obs.message = null;\n } else if (item.outcome === 'CONFLICT') {\n obs.status = 'CONFLICT';\n obs.serverVersion = item.serverVersion ?? item.observation ?? null;\n obs.message = item.message ?? 'Record changed since capture — review';\n } else {\n obs.status = 'FAILED';\n obs.message = item.message ?? 'Sync failed';\n obs.attempts += 1;\n }\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n}\n\n/** Queued mutations eligible to replay now (same retry cap as observations). */\nfunction isMutationSyncable(m: PendingMutation): boolean {\n return !m.requiresUserReview && (m.status === 'QUEUED' || m.status === 'FAILED') && m.attempts < MAX_ATTEMPTS;\n}\n\n/**\n * Replay queued non-observation writes (BOFF-6179).\n *\n * Runs BEFORE the observation path's early returns, because an application\n * queued on a device that captured no observations would otherwise never drain.\n *\n * ── A refusal is not a retry ─────────────────────────────────────────────────\n *\n * A `SyncGraphQLError` is the server declining — RBAC, validation, or the\n * soft-deleted-original case where the replay lookup filters `deletedAt: null`\n * but the unique index does not, surfacing as a P2002 masked as \"Unexpected\n * error\". Retrying cannot change any of those answers; it would spin to the\n * attempt cap while hiding the reason. Those land FAILED with the message.\n * Only a transport failure — the connection dropping again — is re-queued.\n */\nasync function drainPendingMutations(deps: SyncDeps, summary: DrainSummary): Promise<void> {\n const all = await getAllPendingMutations();\n\n // Recover anything stranded UPLOADING by an interrupted drain. Replay is\n // idempotent on clientMutationId, so a request that did reach the server\n // simply returns the original row.\n for (const m of all) {\n if (m.status === 'UPLOADING') {\n m.status = 'QUEUED';\n m.updatedAt = Date.now();\n await savePendingMutation(m);\n }\n }\n\n for (const mutation of all.filter(isMutationSyncable)) {\n mutation.status = 'UPLOADING';\n mutation.updatedAt = Date.now();\n await savePendingMutation(mutation);\n\n try {\n const result = await createSchemeApplication(\n { workspaceId: deps.workspaceId },\n {\n schemeId: mutation.payload.schemeId,\n applicantName: mutation.payload.applicantName,\n farmName: mutation.payload.farmName,\n declarationAccepted: mutation.payload.declarationAccepted,\n clientMutationId: mutation.clientId,\n notes: mutation.payload.notes ?? null,\n amount: mutation.payload.amount ?? null,\n }\n );\n mutation.status = 'SYNCED';\n mutation.serverId = result.id;\n mutation.serverStatus = result.status;\n mutation.syncedAt = now();\n mutation.message = null;\n summary.mutationsSynced += 1;\n } catch (err) {\n if (err instanceof SyncGraphQLError) {\n // NOT counted as exhausted: `isMutationSyncable` selects (FAILED && attempts <\n // MAX_ATTEMPTS), so a server-rejected mutation is still picked up by later drains.\n // Whether replaying an unchanged rejected payload is worthwhile is a separate\n // question — but while the engine does retry it, the counter must say so.\n mutation.status = 'FAILED';\n mutation.message = err.message;\n mutation.attempts += 1;\n if (mutation.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\n } else {\n mutation.attempts += 1;\n mutation.status = mutation.attempts >= MAX_ATTEMPTS ? 'FAILED' : 'QUEUED';\n if (mutation.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\n mutation.message = err instanceof Error ? err.message : 'Sync failed';\n }\n summary.mutationsFailed += 1;\n }\n mutation.updatedAt = Date.now();\n await savePendingMutation(mutation);\n }\n}\n\n/**\n * Drain the outbox once. Safe to call repeatedly (idempotent server-side via\n * clientId). Returns a summary; also appends a device-local history entry.\n */\n\n/**\n * How the history line describes outstanding failures.\n *\n * \"still queued\" is false for a record at the retry cap — `isSyncable` excludes it, so the\n * timeline would permanently contradict Pending Sync and the toast (BOFF-6364 review).\n */\nfunction describeFailedForHistory(summary: DrainSummary): string {\n const failed = summary.failed + summary.mutationsFailed;\n const exhausted = Math.min(Math.max(summary.exhausted, 0), failed);\n if (exhausted === 0) return `${failed} record(s) still queued`;\n if (exhausted >= failed) return `${failed} record(s) out of retries`;\n return `${failed - exhausted} record(s) still queued, ${exhausted} out of retries`;\n}\n\n/**\n * Count everything left in the outbox that can never sync again.\n *\n * Read from the store rather than accumulated during the drain, because a record that used\n * up its retries in a previous pass is invisible to this one — `isSyncable` filters it out\n * before the drain ever sees it.\n */\nasync function stampTerminalPending(\n summary: DrainSummary,\n known?: { observations?: LocalObservation[] }\n): Promise<DrainSummary> {\n // Reuse the observation list the caller already loaded where there is one — the main drain\n // path reads the whole outbox anyway, and scanning it twice per sync is pure waste on a\n // device with a large queue. The mutation list is small and is not loaded on this path.\n const observations = known?.observations ?? (await getAllObservations());\n const mutations = await getAllPendingMutations();\n summary.terminalPending =\n observations.filter((o) => o.status === 'FAILED' && !isSyncable(o)).length +\n mutations.filter((m) => m.status === 'FAILED' && !isMutationSyncable(m)).length;\n return summary;\n}\n\nexport async function drainQueue(deps: SyncDeps): Promise<DrainSummary> {\n const summary: DrainSummary = {\n attempted: 0,\n synced: 0,\n duplicate: 0,\n conflict: 0,\n failed: 0,\n exhausted: 0,\n terminalPending: 0,\n skipped: 0,\n photosUploaded: 0,\n mutationsSynced: 0,\n mutationsFailed: 0,\n };\n if (!deps.network.online || !deps.workspaceId) return stampTerminalPending(summary);\n\n // Recover any records stranded in UPLOADING by a previous drain that was\n // interrupted (tab closed / crashed mid-sync). Re-queue them — the server sync is\n // idempotent (clientId), so a record that actually did reach the server just comes\n // back as DUPLICATE. Without this, an interrupted upload would strand forever.\n const stranded = await getAllObservations();\n for (const obs of stranded) {\n if (obs.status === 'UPLOADING') {\n obs.status = 'QUEUED';\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n }\n }\n\n // Queued applications drain first, and unconditionally — the two early\n // returns below are about the OBSERVATION outbox, and a device with a queued\n // application but no observations hits them on every pass.\n await drainPendingMutations(deps, summary);\n\n const all = await getAllObservations();\n const pending = all.filter(isSyncable);\n if (pending.length === 0) {\n await recordMutationOnlyHistory(deps, summary);\n // Nothing was written since `all` was read, so it is still an accurate snapshot.\n return stampTerminalPending(summary, { observations: all });\n }\n\n const batch: Array<{ obs: LocalObservation; input: SyncInputItem }> = [];\n for (const obs of pending) {\n let resolved: { fileIds: string[]; uploaded: number } | null;\n try {\n resolved = await resolvePhotoFileIds(obs, deps);\n } catch (err) {\n // A photo upload failed — mark THIS record failed (re-queueable) and keep\n // draining the rest of the outbox rather than aborting the whole batch.\n obs.attempts += 1;\n obs.status = obs.attempts >= MAX_ATTEMPTS ? 'FAILED' : 'QUEUED';\n if (obs.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\n obs.message = err instanceof Error ? err.message : 'Photo upload failed';\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n summary.failed += 1;\n continue;\n }\n if (!resolved) {\n summary.skipped += 1;\n continue; // deferred (Wi-Fi-only photos on a metered link)\n }\n summary.photosUploaded += resolved.uploaded;\n // Persist resolved fileIds even if the network sync later fails.\n obs.photoFileIds = resolved.fileIds;\n obs.status = 'UPLOADING';\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n batch.push({ obs, input: toSyncInput(obs, resolved.fileIds) });\n }\n\n if (batch.length === 0) {\n await recordMutationOnlyHistory(deps, summary);\n return stampTerminalPending(summary);\n }\n summary.attempted = batch.length;\n\n try {\n const result = await syncObservations(\n { workspaceId: deps.workspaceId },\n batch.map((b) => b.input)\n );\n const byClientId = new Map(result.items.map((i) => [i.clientId, i]));\n for (const { obs } of batch) {\n const item = byClientId.get(obs.clientId);\n await applyOutcome(obs, item);\n if (item?.outcome === 'SYNCED') summary.synced += 1;\n else if (item?.outcome === 'DUPLICATE') summary.duplicate += 1;\n else if (item?.outcome === 'CONFLICT') summary.conflict += 1;\n else {\n summary.failed += 1;\n // `applyOutcome` has already bumped `attempts`; a record that crossed the cap here is\n // just as terminal as one that failed in transport, and the toast must not promise it\n // a retry `isSyncable` will refuse.\n if (obs.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\n }\n }\n await recordHistory(deps, summary, 'complete');\n } catch (err) {\n // Transport / gateway failure — put everything back to QUEUED (or keep FAILED\n // after enough retries) so a later reconnect retries. Never lose a capture.\n const message = err instanceof Error ? err.message : 'Sync failed';\n for (const { obs } of batch) {\n obs.attempts += 1;\n obs.status = obs.attempts >= MAX_ATTEMPTS ? 'FAILED' : 'QUEUED';\n if (obs.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\n obs.message = message;\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n summary.failed += 1;\n }\n await recordHistory(deps, summary, 'failed', message);\n }\n\n return stampTerminalPending(summary);\n}\n\n/**\n * History for a drain that moved ONLY queued mutations.\n *\n * The observation path returns early when its outbox is empty, so without this\n * a farmer whose only queued item was an application would see the sync happen\n * and the timeline stay blank.\n */\nasync function recordMutationOnlyHistory(deps: SyncDeps, summary: DrainSummary): Promise<void> {\n // A drain that uploaded nothing because every record FAILED still happened, and used to\n // leave the timeline blank — so a farmer chasing a stuck record found no trace of the\n // three attempts that had already failed (BOFF-6364). Deferred records are a setting\n // working as configured, not an event, so they are still not written here.\n const touchedSomething = summary.mutationsSynced + summary.mutationsFailed + summary.failed > 0;\n if (!touchedSomething) return;\n await recordHistory(deps, summary, summary.mutationsFailed + summary.failed > 0 ? 'failed' : 'complete');\n}\n\nasync function recordHistory(\n deps: SyncDeps,\n summary: DrainSummary,\n mode: 'complete' | 'failed',\n message?: string\n): Promise<void> {\n const all = await getAllObservations();\n const touched = all.filter((o) => o.updatedAt >= Date.now() - 5000);\n const types: string[] = Array.from(new Set<string>(touched.map((o) => o.observationType)));\n // `observationType` has no meaning for a queued application, so the chip is a\n // constant rather than a borrowed observation type.\n if (summary.mutationsSynced + summary.mutationsFailed > 0) types.push('SCHEME_APPLICATION');\n const entry: SyncHistoryEntry = {\n id: uid('hist'),\n at: Date.now(),\n kind: mode === 'failed' ? 'SYNC_FAILED' : summary.conflict > 0 ? 'CONFLICT' : 'SYNC_COMPLETE',\n syncedCount: summary.synced + summary.duplicate + summary.mutationsSynced,\n duplicateCount: summary.duplicate,\n conflictCount: summary.conflict,\n failedCount: summary.failed + summary.mutationsFailed,\n photoCount: summary.photosUploaded,\n message:\n mode === 'failed'\n ? `Sync failed${message ? ` — ${message}` : ''} · ${describeFailedForHistory(summary)}`\n : `${summary.synced + summary.duplicate + summary.mutationsSynced} record(s) synced` +\n (summary.photosUploaded ? `, ${summary.photosUploaded} photo(s) uploaded` : '') +\n (summary.mutationsSynced ? `, ${summary.mutationsSynced} application(s) submitted` : '') +\n (summary.conflict ? `, ${summary.conflict} conflict(s)` : ''),\n types,\n };\n await addHistoryEntry(entry);\n}\n"],"mappings":";;;;AA0FA,IAAM,IAAe;AAOrB,SAAS,IAAc;CACrB,wBAAO,IAAI,KAAK,GAAE,YAAY;AAChC;AAEA,SAAS,EAAI,GAAwB;CAKnC,OAAO,GAAG,EAAO,GAHf,OAAO,SAAW,OAAe,OAAO,aACpC,OAAO,WAAW,IAClB,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,MAAM,KAAK,OAAO,IAAI,GAAG;AAEvD;AAGA,SAAS,EAAW,GAA8B;CAChD,QAAQ,EAAE,WAAW,YAAY,EAAE,WAAW,aAAa,EAAE,WAAA;AAC/D;AAOA,eAAe,EACb,GACA,GACyD;CAKzD,IAAM,IAAuB,CAAC;CAC9B,KAAK,IAAM,KAAO,EAAI,eAAe;EACnC,IAAM,IAAI,MAAM,EAAS,CAAG;EAC5B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AI,EAAI,MAAM;EACd,IAAI,KAAK,IAAI;EACb,MAAM,MAAS,WAAW,gBAAgB,EAAQ,WAAW,IAAI,aAAa;EAC9E,aAAa,EAAQ,SAAS,EAAQ,YAAY,EAAQ;EAC1D,gBAAgB,EAAQ;EACxB,eAAe,EAAQ;EACvB,aAAa,EAAQ,SAAS,EAAQ;EACtC,YAAY,EAAQ;EACpB,SACE,MAAS,WACL,cAAc,IAAU,MAAM,MAAY,GAAG,KAAK,EAAyB,CAAO,MAClF,GAAG,EAAQ,SAAS,EAAQ,YAAY,EAAQ,gBAAgB,sBAC/D,EAAQ,iBAAiB,KAAK,EAAQ,eAAe,sBAAsB,OAC3E,EAAQ,kBAAkB,KAAK,EAAQ,gBAAgB,6BAA6B,OACpF,EAAQ,WAAW,KAAK,EAAQ,SAAS,gBAAgB;EAChE;CAEoB,CAAK;AAC7B"}
1
+ {"version":3,"file":"syncEngine.js","names":[],"sources":["../../../src/healthybowl/offline/syncEngine.ts"],"sourcesContent":["/**\n * Sync engine (BOFF-2883).\n *\n * Drains the local outbox when connectivity returns: uploads any offline-captured\n * photo blobs to files-svc, then replays the queued observations through the\n * idempotent `syncHealthyBowlFieldObservations` mutation and reconciles each\n * record's local status from the per-item outcome (Synced / Conflict / Failed).\n *\n * The engine is dependency-injected (workspace id, the fe-libs file-upload\n * function, current settings + network state) so it stays pure and testable and\n * can be driven from the OfflineSyncProvider.\n */\nimport type {\n LocalObservation,\n LocalPhoto,\n OfflineSettings,\n NetworkState,\n PendingMutation,\n SyncHistoryEntry,\n} from './types';\nimport {\n getAllObservations,\n saveObservation,\n getPhoto,\n savePhoto,\n addHistoryEntry,\n getAllPendingMutations,\n savePendingMutation,\n} from './store';\nimport {\n syncObservations,\n createSchemeApplication,\n SyncGraphQLError,\n type SyncInputItem,\n type SyncResultItem,\n} from './graphql';\nimport { isWifi } from './network';\n\n/** fe-libs `useSaveToFiles().save` shape — uploads a blob, returns its files-svc id. */\nexport type SaveToFiles = (args: {\n source: {\n kind: 'blob';\n filename: string;\n mimeType: string;\n getBlob: () => Promise<{ blob: Blob; filename: string; mimeType: string }>;\n };\n folderPath: string;\n}) => Promise<{ id: string }>;\n\nexport interface SyncDeps {\n workspaceId: string;\n saveToFiles: SaveToFiles;\n settings: OfflineSettings;\n network: NetworkState;\n}\n\nexport interface DrainSummary {\n attempted: number;\n synced: number;\n duplicate: number;\n conflict: number;\n failed: number;\n /**\n * Failures that have used up every retry (BOFF-6364 review).\n *\n * A record at `MAX_ATTEMPTS` is excluded by `isSyncable` from every subsequent drain, so\n * it will never be retried. Counting it separately keeps the toast from promising a retry\n * that cannot happen — the exact class of dishonest status this ticket exists to remove.\n * These are a SUBSET of `failed`, not an addition to it.\n */\n exhausted: number;\n /**\n * Every record left in the outbox that can never sync again — including ones that used up\n * their retries in an EARLIER drain (BOFF-6364 review).\n *\n * `exhausted` only counts records that became terminal during THIS drain, so on the next\n * Sync Now `isSyncable` filters the stranded record out, the summary comes back empty, and\n * the toast would fall through to \"All synced — nothing is waiting\" while Pending Sync\n * still lists it. That is the original BOFF-6364 lie, re-entered by the back door. This\n * counter is read from the store, so it survives across drains.\n */\n terminalPending: number;\n skipped: number;\n photosUploaded: number;\n /** Queued non-observation writes that reached the server (BOFF-6179). */\n mutationsSynced: number;\n /** Queued non-observation writes that did not. */\n mutationsFailed: number;\n}\n\nconst PHOTO_FOLDER = '/HealthyBowl/FieldObservation';\n/**\n * Retry cap. Exported so the UI can tell a record that is merely failing from one that can\n * never be sent again — the two need different affordances, not just different wording.\n */\nexport const MAX_ATTEMPTS = 8;\n\nfunction now(): string {\n return new Date().toISOString();\n}\n\nfunction uid(prefix: string): string {\n const rand =\n typeof crypto !== 'undefined' && crypto.randomUUID\n ? crypto.randomUUID()\n : `${Date.now()}-${Math.round(Math.random() * 1e9)}`;\n return `${prefix}-${rand}`;\n}\n\n/** Records eligible to sync now (queued or previously-failed, under the retry cap). */\nfunction isSyncable(o: LocalObservation): boolean {\n return (o.status === 'QUEUED' || o.status === 'FAILED') && o.attempts < MAX_ATTEMPTS;\n}\n\n/**\n * Upload any not-yet-uploaded photo blobs for a record and return the resolved\n * files-svc ids. Honors the \"upload photos on Wi-Fi only\" setting by signalling\n * a defer (returns null) when the record still has local blobs and we're metered.\n */\nasync function resolvePhotoFileIds(\n obs: LocalObservation,\n deps: SyncDeps\n): Promise<{ fileIds: string[]; uploaded: number } | null> {\n // Rebuild the fileId list from the AUTHORITATIVE per-photo records (in capture\n // order), not from the possibly-stale obs.photoFileIds snapshot. A prior partial\n // upload persists each photo's fileId on its own record, so already-uploaded\n // photos are never dropped on retry.\n const photos: LocalPhoto[] = [];\n for (const pid of obs.photoLocalIds) {\n const p = await getPhoto(pid);\n if (p) photos.push(p);\n }\n const needsUpload = photos.some((p) => !p.fileId);\n\n // Metered connection + Wi-Fi-only preference → defer the whole record so its\n // photos and observation reach the server together on Wi-Fi.\n if (needsUpload && deps.settings.uploadPhotosOnWifiOnly && !isWifi(deps.network)) {\n return null;\n }\n\n let uploaded = 0;\n const fileIds: string[] = [];\n for (const photo of photos) {\n if (photo.fileId) {\n fileIds.push(photo.fileId);\n continue;\n }\n const saved = await deps.saveToFiles({\n source: {\n kind: 'blob',\n filename: photo.filename,\n mimeType: photo.mimeType,\n getBlob: async () => ({ blob: photo.blob, filename: photo.filename, mimeType: photo.mimeType }),\n },\n folderPath: PHOTO_FOLDER,\n });\n // Persist the fileId immediately so a later failure in this loop never re-uploads\n // this photo or loses its id.\n photo.fileId = saved.id;\n await savePhoto(photo);\n fileIds.push(saved.id);\n uploaded += 1;\n }\n return { fileIds, uploaded };\n}\n\nfunction toSyncInput(obs: LocalObservation, photoFileIds: string[]): SyncInputItem {\n return {\n clientId: obs.clientId,\n observationType: obs.observationType,\n fieldId: obs.fieldId ?? null,\n fieldName: obs.fieldName ?? null,\n title: obs.title ?? null,\n note: obs.note ?? null,\n severity: obs.severity ?? null,\n quantity: obs.quantity ?? null,\n unit: obs.unit ?? null,\n cropName: obs.cropName ?? null,\n animalTag: obs.animalTag ?? null,\n latitude: obs.latitude ?? null,\n longitude: obs.longitude ?? null,\n gpsAccuracy: obs.gpsAccuracy ?? null,\n photoFileIds,\n capturedAt: obs.capturedAt,\n capturedOffline: obs.capturedOffline,\n baseVersion: obs.baseVersion,\n };\n}\n\nasync function applyOutcome(obs: LocalObservation, item: SyncResultItem | undefined): Promise<void> {\n const ts = now();\n if (!item) {\n obs.status = 'FAILED';\n obs.message = 'No result returned for this record';\n obs.attempts += 1;\n } else if (item.outcome === 'SYNCED' || item.outcome === 'DUPLICATE') {\n obs.status = 'SYNCED';\n obs.serverId = item.observation?.id ?? obs.serverId ?? null;\n obs.baseVersion = item.observation?.version ?? obs.baseVersion;\n obs.syncedAt = item.observation?.syncedAt ?? ts;\n obs.serverVersion = null;\n obs.message = null;\n } else if (item.outcome === 'CONFLICT') {\n obs.status = 'CONFLICT';\n obs.serverVersion = item.serverVersion ?? item.observation ?? null;\n obs.message = item.message ?? 'Record changed since capture — review';\n } else {\n obs.status = 'FAILED';\n obs.message = item.message ?? 'Sync failed';\n obs.attempts += 1;\n }\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n}\n\n/** Queued mutations eligible to replay now (same retry cap as observations). */\nfunction isMutationSyncable(m: PendingMutation): boolean {\n return !m.requiresUserReview && (m.status === 'QUEUED' || m.status === 'FAILED') && m.attempts < MAX_ATTEMPTS;\n}\n\n/**\n * Replay queued non-observation writes (BOFF-6179).\n *\n * Runs BEFORE the observation path's early returns, because an application\n * queued on a device that captured no observations would otherwise never drain.\n *\n * ── A refusal is not a retry ─────────────────────────────────────────────────\n *\n * A `SyncGraphQLError` is the server declining — RBAC, validation, or the\n * soft-deleted-original case where the replay lookup filters `deletedAt: null`\n * but the unique index does not, surfacing as a P2002 masked as \"Unexpected\n * error\". Retrying cannot change any of those answers; it would spin to the\n * attempt cap while hiding the reason. Those land FAILED with the message.\n * Only a transport failure — the connection dropping again — is re-queued.\n */\nasync function drainPendingMutations(deps: SyncDeps, summary: DrainSummary): Promise<void> {\n const all = await getAllPendingMutations();\n\n // Recover anything stranded UPLOADING by an interrupted drain. Replay is\n // idempotent on clientMutationId, so a request that did reach the server\n // simply returns the original row.\n for (const m of all) {\n if (m.status === 'UPLOADING') {\n m.status = 'QUEUED';\n m.updatedAt = Date.now();\n await savePendingMutation(m);\n }\n }\n\n for (const mutation of all.filter(isMutationSyncable)) {\n mutation.status = 'UPLOADING';\n mutation.updatedAt = Date.now();\n await savePendingMutation(mutation);\n\n try {\n const result = await createSchemeApplication(\n { workspaceId: deps.workspaceId },\n {\n schemeId: mutation.payload.schemeId,\n applicantName: mutation.payload.applicantName,\n farmName: mutation.payload.farmName,\n declarationAccepted: mutation.payload.declarationAccepted,\n clientMutationId: mutation.clientId,\n notes: mutation.payload.notes ?? null,\n amount: mutation.payload.amount ?? null,\n // Omitted entirely when absent, so a mutation queued before BOFF-6111 replays exactly as\n // it always did rather than sending an empty list the server would have to interpret.\n ...(mutation.payload.documents && mutation.payload.documents.length > 0\n ? { documents: mutation.payload.documents }\n : {}),\n }\n );\n mutation.status = 'SYNCED';\n mutation.serverId = result.id;\n mutation.serverStatus = result.status;\n mutation.syncedAt = now();\n mutation.message = null;\n summary.mutationsSynced += 1;\n } catch (err) {\n if (err instanceof SyncGraphQLError) {\n // NOT counted as exhausted: `isMutationSyncable` selects (FAILED && attempts <\n // MAX_ATTEMPTS), so a server-rejected mutation is still picked up by later drains.\n // Whether replaying an unchanged rejected payload is worthwhile is a separate\n // question — but while the engine does retry it, the counter must say so.\n mutation.status = 'FAILED';\n mutation.message = err.message;\n mutation.attempts += 1;\n if (mutation.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\n } else {\n mutation.attempts += 1;\n mutation.status = mutation.attempts >= MAX_ATTEMPTS ? 'FAILED' : 'QUEUED';\n if (mutation.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\n mutation.message = err instanceof Error ? err.message : 'Sync failed';\n }\n summary.mutationsFailed += 1;\n }\n mutation.updatedAt = Date.now();\n await savePendingMutation(mutation);\n }\n}\n\n/**\n * Drain the outbox once. Safe to call repeatedly (idempotent server-side via\n * clientId). Returns a summary; also appends a device-local history entry.\n */\n\n/**\n * How the history line describes outstanding failures.\n *\n * \"still queued\" is false for a record at the retry cap — `isSyncable` excludes it, so the\n * timeline would permanently contradict Pending Sync and the toast (BOFF-6364 review).\n */\nfunction describeFailedForHistory(summary: DrainSummary): string {\n const failed = summary.failed + summary.mutationsFailed;\n const exhausted = Math.min(Math.max(summary.exhausted, 0), failed);\n if (exhausted === 0) return `${failed} record(s) still queued`;\n if (exhausted >= failed) return `${failed} record(s) out of retries`;\n return `${failed - exhausted} record(s) still queued, ${exhausted} out of retries`;\n}\n\n/**\n * Count everything left in the outbox that can never sync again.\n *\n * Read from the store rather than accumulated during the drain, because a record that used\n * up its retries in a previous pass is invisible to this one — `isSyncable` filters it out\n * before the drain ever sees it.\n */\nasync function stampTerminalPending(\n summary: DrainSummary,\n known?: { observations?: LocalObservation[] }\n): Promise<DrainSummary> {\n // Reuse the observation list the caller already loaded where there is one — the main drain\n // path reads the whole outbox anyway, and scanning it twice per sync is pure waste on a\n // device with a large queue. The mutation list is small and is not loaded on this path.\n const observations = known?.observations ?? (await getAllObservations());\n const mutations = await getAllPendingMutations();\n summary.terminalPending =\n observations.filter((o) => o.status === 'FAILED' && !isSyncable(o)).length +\n mutations.filter((m) => m.status === 'FAILED' && !isMutationSyncable(m)).length;\n return summary;\n}\n\nexport async function drainQueue(deps: SyncDeps): Promise<DrainSummary> {\n const summary: DrainSummary = {\n attempted: 0,\n synced: 0,\n duplicate: 0,\n conflict: 0,\n failed: 0,\n exhausted: 0,\n terminalPending: 0,\n skipped: 0,\n photosUploaded: 0,\n mutationsSynced: 0,\n mutationsFailed: 0,\n };\n if (!deps.network.online || !deps.workspaceId) return stampTerminalPending(summary);\n\n // Recover any records stranded in UPLOADING by a previous drain that was\n // interrupted (tab closed / crashed mid-sync). Re-queue them — the server sync is\n // idempotent (clientId), so a record that actually did reach the server just comes\n // back as DUPLICATE. Without this, an interrupted upload would strand forever.\n const stranded = await getAllObservations();\n for (const obs of stranded) {\n if (obs.status === 'UPLOADING') {\n obs.status = 'QUEUED';\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n }\n }\n\n // Queued applications drain first, and unconditionally — the two early\n // returns below are about the OBSERVATION outbox, and a device with a queued\n // application but no observations hits them on every pass.\n await drainPendingMutations(deps, summary);\n\n const all = await getAllObservations();\n const pending = all.filter(isSyncable);\n if (pending.length === 0) {\n await recordMutationOnlyHistory(deps, summary);\n // Nothing was written since `all` was read, so it is still an accurate snapshot.\n return stampTerminalPending(summary, { observations: all });\n }\n\n const batch: Array<{ obs: LocalObservation; input: SyncInputItem }> = [];\n for (const obs of pending) {\n let resolved: { fileIds: string[]; uploaded: number } | null;\n try {\n resolved = await resolvePhotoFileIds(obs, deps);\n } catch (err) {\n // A photo upload failed — mark THIS record failed (re-queueable) and keep\n // draining the rest of the outbox rather than aborting the whole batch.\n obs.attempts += 1;\n obs.status = obs.attempts >= MAX_ATTEMPTS ? 'FAILED' : 'QUEUED';\n if (obs.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\n obs.message = err instanceof Error ? err.message : 'Photo upload failed';\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n summary.failed += 1;\n continue;\n }\n if (!resolved) {\n summary.skipped += 1;\n continue; // deferred (Wi-Fi-only photos on a metered link)\n }\n summary.photosUploaded += resolved.uploaded;\n // Persist resolved fileIds even if the network sync later fails.\n obs.photoFileIds = resolved.fileIds;\n obs.status = 'UPLOADING';\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n batch.push({ obs, input: toSyncInput(obs, resolved.fileIds) });\n }\n\n if (batch.length === 0) {\n await recordMutationOnlyHistory(deps, summary);\n return stampTerminalPending(summary);\n }\n summary.attempted = batch.length;\n\n try {\n const result = await syncObservations(\n { workspaceId: deps.workspaceId },\n batch.map((b) => b.input)\n );\n const byClientId = new Map(result.items.map((i) => [i.clientId, i]));\n for (const { obs } of batch) {\n const item = byClientId.get(obs.clientId);\n await applyOutcome(obs, item);\n if (item?.outcome === 'SYNCED') summary.synced += 1;\n else if (item?.outcome === 'DUPLICATE') summary.duplicate += 1;\n else if (item?.outcome === 'CONFLICT') summary.conflict += 1;\n else {\n summary.failed += 1;\n // `applyOutcome` has already bumped `attempts`; a record that crossed the cap here is\n // just as terminal as one that failed in transport, and the toast must not promise it\n // a retry `isSyncable` will refuse.\n if (obs.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\n }\n }\n await recordHistory(deps, summary, 'complete');\n } catch (err) {\n // Transport / gateway failure — put everything back to QUEUED (or keep FAILED\n // after enough retries) so a later reconnect retries. Never lose a capture.\n const message = err instanceof Error ? err.message : 'Sync failed';\n for (const { obs } of batch) {\n obs.attempts += 1;\n obs.status = obs.attempts >= MAX_ATTEMPTS ? 'FAILED' : 'QUEUED';\n if (obs.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\n obs.message = message;\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n summary.failed += 1;\n }\n await recordHistory(deps, summary, 'failed', message);\n }\n\n return stampTerminalPending(summary);\n}\n\n/**\n * History for a drain that moved ONLY queued mutations.\n *\n * The observation path returns early when its outbox is empty, so without this\n * a farmer whose only queued item was an application would see the sync happen\n * and the timeline stay blank.\n */\nasync function recordMutationOnlyHistory(deps: SyncDeps, summary: DrainSummary): Promise<void> {\n // A drain that uploaded nothing because every record FAILED still happened, and used to\n // leave the timeline blank — so a farmer chasing a stuck record found no trace of the\n // three attempts that had already failed (BOFF-6364). Deferred records are a setting\n // working as configured, not an event, so they are still not written here.\n const touchedSomething = summary.mutationsSynced + summary.mutationsFailed + summary.failed > 0;\n if (!touchedSomething) return;\n await recordHistory(deps, summary, summary.mutationsFailed + summary.failed > 0 ? 'failed' : 'complete');\n}\n\nasync function recordHistory(\n deps: SyncDeps,\n summary: DrainSummary,\n mode: 'complete' | 'failed',\n message?: string\n): Promise<void> {\n const all = await getAllObservations();\n const touched = all.filter((o) => o.updatedAt >= Date.now() - 5000);\n const types: string[] = Array.from(new Set<string>(touched.map((o) => o.observationType)));\n // `observationType` has no meaning for a queued application, so the chip is a\n // constant rather than a borrowed observation type.\n if (summary.mutationsSynced + summary.mutationsFailed > 0) types.push('SCHEME_APPLICATION');\n const entry: SyncHistoryEntry = {\n id: uid('hist'),\n at: Date.now(),\n kind: mode === 'failed' ? 'SYNC_FAILED' : summary.conflict > 0 ? 'CONFLICT' : 'SYNC_COMPLETE',\n syncedCount: summary.synced + summary.duplicate + summary.mutationsSynced,\n duplicateCount: summary.duplicate,\n conflictCount: summary.conflict,\n failedCount: summary.failed + summary.mutationsFailed,\n photoCount: summary.photosUploaded,\n message:\n mode === 'failed'\n ? `Sync failed${message ? ` — ${message}` : ''} · ${describeFailedForHistory(summary)}`\n : `${summary.synced + summary.duplicate + summary.mutationsSynced} record(s) synced` +\n (summary.photosUploaded ? `, ${summary.photosUploaded} photo(s) uploaded` : '') +\n (summary.mutationsSynced ? `, ${summary.mutationsSynced} application(s) submitted` : '') +\n (summary.conflict ? `, ${summary.conflict} conflict(s)` : ''),\n types,\n };\n await addHistoryEntry(entry);\n}\n"],"mappings":";;;;AA0FA,IAAM,IAAe;AAOrB,SAAS,IAAc;CACrB,wBAAO,IAAI,KAAK,GAAE,YAAY;AAChC;AAEA,SAAS,EAAI,GAAwB;CAKnC,OAAO,GAAG,EAAO,GAHf,OAAO,SAAW,OAAe,OAAO,aACpC,OAAO,WAAW,IAClB,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,MAAM,KAAK,OAAO,IAAI,GAAG;AAEvD;AAGA,SAAS,EAAW,GAA8B;CAChD,QAAQ,EAAE,WAAW,YAAY,EAAE,WAAW,aAAa,EAAE,WAAA;AAC/D;AAOA,eAAe,EACb,GACA,GACyD;CAKzD,IAAM,IAAuB,CAAC;CAC9B,KAAK,IAAM,KAAO,EAAI,eAAe;EACnC,IAAM,IAAI,MAAM,EAAS,CAAG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,CAAC;CAsBzF,AAnBI,EAAQ,kBAAkB,EAAQ,kBAAkB,KAAG,EAAM,KAAK,oBAAoB,GAmB1F,MAAM,EAAgB;EAjBpB,IAAI,EAAI,MAAM;EACd,IAAI,KAAK,IAAI;EACb,MAAM,MAAS,WAAW,gBAAgB,EAAQ,WAAW,IAAI,aAAa;EAC9E,aAAa,EAAQ,SAAS,EAAQ,YAAY,EAAQ;EAC1D,gBAAgB,EAAQ;EACxB,eAAe,EAAQ;EACvB,aAAa,EAAQ,SAAS,EAAQ;EACtC,YAAY,EAAQ;EACpB,SACE,MAAS,WACL,cAAc,IAAU,MAAM,MAAY,GAAG,KAAK,EAAyB,CAAO,MAClF,GAAG,EAAQ,SAAS,EAAQ,YAAY,EAAQ,gBAAgB,sBAC/D,EAAQ,iBAAiB,KAAK,EAAQ,eAAe,sBAAsB,OAC3E,EAAQ,kBAAkB,KAAK,EAAQ,gBAAgB,6BAA6B,OACpF,EAAQ,WAAW,KAAK,EAAQ,SAAS,gBAAgB;EAChE;CAEoB,CAAK;AAC7B"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../../../src/healthybowl/offline/types.ts"],"sourcesContent":["/**\n * Offline field data capture & sync (BOFF-2883) — shared types.\n *\n * The device is the source of truth until a write reaches the server: every\n * capture is written to IndexedDB first, sits in a durable outbox, and is\n * replayed idempotently when connectivity returns.\n */\n\n/** The five field-observation types a farmer can capture. */\nexport type ObservationType = 'PEST' | 'CROP_HEALTH' | 'SOIL' | 'HARVEST' | 'LIVESTOCK';\n\n/** Per-record lifecycle in the local outbox. */\nexport type SyncStatus = 'QUEUED' | 'UPLOADING' | 'SYNCED' | 'CONFLICT' | 'FAILED';\n\n/** A photo captured offline, blob held locally until it uploads to files-svc. */\nexport interface LocalPhoto {\n /** Local id (also the IndexedDB key). */\n id: string;\n /** The observation this photo belongs to. */\n clientId: string;\n blob: Blob;\n filename: string;\n mimeType: string;\n /** files-svc id once uploaded on sync (undefined while still local-only). */\n fileId?: string;\n createdAt: number;\n}\n\n/** The server's view of a conflicting record, kept for the review screen. */\nexport interface ServerObservation {\n id: string;\n clientId: string;\n fieldId?: string | null;\n fieldName?: string | null;\n observationType: string;\n title?: string | null;\n note?: string | null;\n severity?: string | null;\n quantity?: number | null;\n unit?: string | null;\n cropName?: string | null;\n animalTag?: string | null;\n latitude?: number | null;\n longitude?: number | null;\n photoFileIds: string[];\n version: number;\n syncedAt?: string | null;\n updatedAt?: string | null;\n createdBy?: string | null;\n}\n\n/**\n * A locally-captured observation (the outbox record). `clientId` is the stable\n * idempotency key sent to the server; `version` mirrors the last-known server\n * version so an edit can be conflict-checked on replay.\n */\nexport interface LocalObservation {\n clientId: string;\n observationType: ObservationType;\n fieldId?: string | null;\n fieldName?: string | null;\n title?: string | null;\n note?: string | null;\n severity?: string | null;\n quantity?: number | null;\n unit?: string | null;\n cropName?: string | null;\n animalTag?: string | null;\n latitude?: number | null;\n longitude?: number | null;\n gpsAccuracy?: number | null;\n /** Local photo ids (blobs live in the `photos` store until uploaded). */\n photoLocalIds: string[];\n /** files-svc ids already resolved for this record's photos. */\n photoFileIds: string[];\n capturedAt: string;\n capturedOffline: boolean;\n /** Local lifecycle status. */\n status: SyncStatus;\n /** Server version this record is based on (null for a never-synced capture). */\n baseVersion: number | null;\n /** Server row id once synced. */\n serverId?: string | null;\n syncedAt?: string | null;\n /** Human-readable reason for a FAILED/CONFLICT status. */\n message?: string | null;\n /** The conflicting server record, populated when status === 'CONFLICT'. */\n serverVersion?: ServerObservation | null;\n /** Retry bookkeeping. */\n attempts: number;\n createdAt: number;\n updatedAt: number;\n workspaceId: string;\n}\n\n/**\n * A queued write that is NOT a field observation (BOFF-6179).\n *\n * The outbox shipped scoped to observations, so everything else — including\n * applying for a government scheme — needed a live gateway and simply failed\n * with no signal. This is the generic queue row that fixes that.\n *\n * ── Why the key is called `clientId` ─────────────────────────────────────────\n *\n * It IS the `clientMutationId` sent to the server, but `store.ts` derives every\n * memory-fallback key as `.clientId ?? .id`. Naming it `clientMutationId` here\n * would silently break the in-memory path used in private mode and SSR, where\n * IndexedDB is unavailable — the UI would appear to queue and then lose the row.\n *\n * ── Only ops the SERVER can deduplicate belong here ──────────────────────────\n *\n * `createHealthyBowlSchemeApplication` is the one HB mutation that carries\n * `clientMutationId` with a unique index behind it, so a replay returns the\n * original row. Queueing a mutation WITHOUT that guarantee would turn one\n * dropped connection into duplicate government applications — strictly worse\n * than today's honest failure. Adding a second kind means adding the backend\n * key first.\n */\nexport type PendingMutationKind = 'SCHEME_APPLICATION';\n\n/** Exactly the fields the resolver reads — it ignores `status` and `schemeName`. */\nexport interface SchemeApplicationPayload {\n schemeId: string;\n applicantName: string;\n farmName: string;\n declarationAccepted: true;\n notes?: string | null;\n amount?: number | null;\n}\n\nexport interface PendingMutation {\n /**\n * Stable idempotency key, sent as `clientMutationId`. Capped at 64 chars to\n * match the column.\n */\n clientId: string;\n kind: PendingMutationKind;\n payload: SchemeApplicationPayload;\n /**\n * Row text for the queue surfaces. Held locally because the scheme's name is\n * not readable offline — the queued row would otherwise be an opaque id.\n */\n label: string;\n /**\n * Reuses the observation lifecycle minus CONFLICT: a SchemeApplication has no\n * version column to compare, so there is nothing to review. Replay is\n * dedupe-only, which the server's unique index already guarantees.\n */\n status: Exclude<SyncStatus, 'CONFLICT'>;\n /**\n * Set by a storage migration when a legacy payload cannot be completed safely.\n * Such a row stays visible and discardable but is never sent with invented data.\n */\n requiresUserReview?: boolean;\n /** Server row id once it drains. */\n serverId?: string | null;\n /** Server-reported status once it drains (e.g. SUBMITTED). */\n serverStatus?: string | null;\n syncedAt?: string | null;\n /** Human-readable reason for a FAILED status. */\n message?: string | null;\n attempts: number;\n createdAt: number;\n updatedAt: number;\n workspaceId: string;\n}\n\n/** One entry in the device-local sync history timeline. */\nexport interface SyncHistoryEntry {\n id: string;\n at: number;\n kind: 'SYNC_COMPLETE' | 'AUTO_SYNC' | 'MANUAL_SYNC' | 'SYNC_FAILED' | 'CONFLICT';\n syncedCount: number;\n duplicateCount: number;\n conflictCount: number;\n failedCount: number;\n photoCount: number;\n message: string;\n /** Observation types touched, for the timeline chips. */\n types: string[];\n}\n\n/** User-configurable offline & sync settings (persisted locally). */\nexport interface OfflineSettings {\n autoSyncOnReconnect: boolean;\n syncOverMobileData: boolean;\n /** Auto-sync interval in ms while online (0 = only on events / manual). */\n syncFrequencyMs: number;\n uploadPhotosOnWifiOnly: boolean;\n photoQuality: 'original' | 'compressed';\n autoStampGps: boolean;\n highAccuracyGps: boolean;\n /** How to handle a server-side conflict. */\n conflictHandling: 'review' | 'keepMine' | 'keepServer';\n}\n\nexport const DEFAULT_SETTINGS: OfflineSettings = {\n autoSyncOnReconnect: true,\n syncOverMobileData: true,\n syncFrequencyMs: 5 * 60 * 1000,\n uploadPhotosOnWifiOnly: false,\n photoQuality: 'compressed',\n autoStampGps: true,\n highAccuracyGps: false,\n conflictHandling: 'review',\n};\n\n/** Live connectivity snapshot. */\nexport interface NetworkState {\n online: boolean;\n /** 'wifi' | 'cellular' | 'none' | 'unknown' — best-effort from @capacitor/network. */\n connectionType: string;\n}\n\nexport const OBSERVATION_TYPE_LABELS: Record<ObservationType, string> = {\n PEST: 'Pest Sighting',\n CROP_HEALTH: 'Crop Health',\n SOIL: 'Soil Note',\n HARVEST: 'Harvest Count',\n LIVESTOCK: 'Livestock Health',\n};\n"],"mappings":";AAoMA,IAAa,IAAoC;CAC/C,qBAAqB;CACrB,oBAAoB;CACpB,iBAAiB,MAAS;CAC1B,wBAAwB;CACxB,cAAc;CACd,cAAc;CACd,iBAAiB;CACjB,kBAAkB;AACpB"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../../src/healthybowl/offline/types.ts"],"sourcesContent":["/**\n * Offline field data capture & sync (BOFF-2883) — shared types.\n *\n * The device is the source of truth until a write reaches the server: every\n * capture is written to IndexedDB first, sits in a durable outbox, and is\n * replayed idempotently when connectivity returns.\n */\n\n/** The five field-observation types a farmer can capture. */\nexport type ObservationType = 'PEST' | 'CROP_HEALTH' | 'SOIL' | 'HARVEST' | 'LIVESTOCK';\n\n/** Per-record lifecycle in the local outbox. */\nexport type SyncStatus = 'QUEUED' | 'UPLOADING' | 'SYNCED' | 'CONFLICT' | 'FAILED';\n\n/** A photo captured offline, blob held locally until it uploads to files-svc. */\nexport interface LocalPhoto {\n /** Local id (also the IndexedDB key). */\n id: string;\n /** The observation this photo belongs to. */\n clientId: string;\n blob: Blob;\n filename: string;\n mimeType: string;\n /** files-svc id once uploaded on sync (undefined while still local-only). */\n fileId?: string;\n createdAt: number;\n}\n\n/** The server's view of a conflicting record, kept for the review screen. */\nexport interface ServerObservation {\n id: string;\n clientId: string;\n fieldId?: string | null;\n fieldName?: string | null;\n observationType: string;\n title?: string | null;\n note?: string | null;\n severity?: string | null;\n quantity?: number | null;\n unit?: string | null;\n cropName?: string | null;\n animalTag?: string | null;\n latitude?: number | null;\n longitude?: number | null;\n photoFileIds: string[];\n version: number;\n syncedAt?: string | null;\n updatedAt?: string | null;\n createdBy?: string | null;\n}\n\n/**\n * A locally-captured observation (the outbox record). `clientId` is the stable\n * idempotency key sent to the server; `version` mirrors the last-known server\n * version so an edit can be conflict-checked on replay.\n */\nexport interface LocalObservation {\n clientId: string;\n observationType: ObservationType;\n fieldId?: string | null;\n fieldName?: string | null;\n title?: string | null;\n note?: string | null;\n severity?: string | null;\n quantity?: number | null;\n unit?: string | null;\n cropName?: string | null;\n animalTag?: string | null;\n latitude?: number | null;\n longitude?: number | null;\n gpsAccuracy?: number | null;\n /** Local photo ids (blobs live in the `photos` store until uploaded). */\n photoLocalIds: string[];\n /** files-svc ids already resolved for this record's photos. */\n photoFileIds: string[];\n capturedAt: string;\n capturedOffline: boolean;\n /** Local lifecycle status. */\n status: SyncStatus;\n /** Server version this record is based on (null for a never-synced capture). */\n baseVersion: number | null;\n /** Server row id once synced. */\n serverId?: string | null;\n syncedAt?: string | null;\n /** Human-readable reason for a FAILED/CONFLICT status. */\n message?: string | null;\n /** The conflicting server record, populated when status === 'CONFLICT'. */\n serverVersion?: ServerObservation | null;\n /** Retry bookkeeping. */\n attempts: number;\n createdAt: number;\n updatedAt: number;\n workspaceId: string;\n}\n\n/**\n * A queued write that is NOT a field observation (BOFF-6179).\n *\n * The outbox shipped scoped to observations, so everything else — including\n * applying for a government scheme — needed a live gateway and simply failed\n * with no signal. This is the generic queue row that fixes that.\n *\n * ── Why the key is called `clientId` ─────────────────────────────────────────\n *\n * It IS the `clientMutationId` sent to the server, but `store.ts` derives every\n * memory-fallback key as `.clientId ?? .id`. Naming it `clientMutationId` here\n * would silently break the in-memory path used in private mode and SSR, where\n * IndexedDB is unavailable — the UI would appear to queue and then lose the row.\n *\n * ── Only ops the SERVER can deduplicate belong here ──────────────────────────\n *\n * `createHealthyBowlSchemeApplication` is the one HB mutation that carries\n * `clientMutationId` with a unique index behind it, so a replay returns the\n * original row. Queueing a mutation WITHOUT that guarantee would turn one\n * dropped connection into duplicate government applications — strictly worse\n * than today's honest failure. Adding a second kind means adding the backend\n * key first.\n */\nexport type PendingMutationKind = 'SCHEME_APPLICATION';\n\n/** Exactly the fields the resolver reads — it ignores `status` and `schemeName`. */\n/**\n * One supporting document queued with a scheme application (BOFF-6111).\n *\n * Holds the wspace-files-svc id of a file that has ALREADY uploaded — the upload happens while the\n * farmer is still filling in the form, so a queued application carries a real reference rather than\n * a promise to upload something later. That matters offline: the outbox replays a mutation, not a\n * file transfer.\n */\nexport interface SchemeDocumentPayload {\n slot: string;\n fileId: string;\n fileName?: string | null;\n uploadedAt?: string | null;\n}\n\nexport interface SchemeApplicationPayload {\n schemeId: string;\n applicantName: string;\n farmName: string;\n declarationAccepted: true;\n notes?: string | null;\n amount?: number | null;\n documents?: SchemeDocumentPayload[];\n}\n\nexport interface PendingMutation {\n /**\n * Stable idempotency key, sent as `clientMutationId`. Capped at 64 chars to\n * match the column.\n */\n clientId: string;\n kind: PendingMutationKind;\n payload: SchemeApplicationPayload;\n /**\n * Row text for the queue surfaces. Held locally because the scheme's name is\n * not readable offline — the queued row would otherwise be an opaque id.\n */\n label: string;\n /**\n * Reuses the observation lifecycle minus CONFLICT: a SchemeApplication has no\n * version column to compare, so there is nothing to review. Replay is\n * dedupe-only, which the server's unique index already guarantees.\n */\n status: Exclude<SyncStatus, 'CONFLICT'>;\n /**\n * Set by a storage migration when a legacy payload cannot be completed safely.\n * Such a row stays visible and discardable but is never sent with invented data.\n */\n requiresUserReview?: boolean;\n /** Server row id once it drains. */\n serverId?: string | null;\n /** Server-reported status once it drains (e.g. SUBMITTED). */\n serverStatus?: string | null;\n syncedAt?: string | null;\n /** Human-readable reason for a FAILED status. */\n message?: string | null;\n attempts: number;\n createdAt: number;\n updatedAt: number;\n workspaceId: string;\n}\n\n/** One entry in the device-local sync history timeline. */\nexport interface SyncHistoryEntry {\n id: string;\n at: number;\n kind: 'SYNC_COMPLETE' | 'AUTO_SYNC' | 'MANUAL_SYNC' | 'SYNC_FAILED' | 'CONFLICT';\n syncedCount: number;\n duplicateCount: number;\n conflictCount: number;\n failedCount: number;\n photoCount: number;\n message: string;\n /** Observation types touched, for the timeline chips. */\n types: string[];\n}\n\n/** User-configurable offline & sync settings (persisted locally). */\nexport interface OfflineSettings {\n autoSyncOnReconnect: boolean;\n syncOverMobileData: boolean;\n /** Auto-sync interval in ms while online (0 = only on events / manual). */\n syncFrequencyMs: number;\n uploadPhotosOnWifiOnly: boolean;\n photoQuality: 'original' | 'compressed';\n autoStampGps: boolean;\n highAccuracyGps: boolean;\n /** How to handle a server-side conflict. */\n conflictHandling: 'review' | 'keepMine' | 'keepServer';\n}\n\nexport const DEFAULT_SETTINGS: OfflineSettings = {\n autoSyncOnReconnect: true,\n syncOverMobileData: true,\n syncFrequencyMs: 5 * 60 * 1000,\n uploadPhotosOnWifiOnly: false,\n photoQuality: 'compressed',\n autoStampGps: true,\n highAccuracyGps: false,\n conflictHandling: 'review',\n};\n\n/** Live connectivity snapshot. */\nexport interface NetworkState {\n online: boolean;\n /** 'wifi' | 'cellular' | 'none' | 'unknown' — best-effort from @capacitor/network. */\n connectionType: string;\n}\n\nexport const OBSERVATION_TYPE_LABELS: Record<ObservationType, string> = {\n PEST: 'Pest Sighting',\n CROP_HEALTH: 'Crop Health',\n SOIL: 'Soil Note',\n HARVEST: 'Harvest Count',\n LIVESTOCK: 'Livestock Health',\n};\n"],"mappings":";AAoNA,IAAa,IAAoC;CAC/C,qBAAqB;CACrB,oBAAoB;CACpB,iBAAiB,MAAS;CAC1B,wBAAwB;CACxB,cAAc;CACd,cAAc;CACd,iBAAiB;CACjB,kBAAkB;AACpB"}