@burdenoff/microfe-healthybowl 2026.813.18 → 2026.813.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/assistant/AIAssistantPanel.js +19 -18
- package/dist/components/assistant/AIAssistantPanel.js.map +1 -1
- package/dist/components/assistant/composer/AssistantAttachmentChips.js +1 -1
- package/dist/components/assistant/composer/AssistantAttachmentChips.js.map +1 -1
- package/dist/hooks/useAssistantAttachments.js +140 -117
- package/dist/hooks/useAssistantAttachments.js.map +1 -1
- package/dist/utils/assistantAttachments.js.map +1 -1
- package/package.json +2 -2
|
@@ -9,40 +9,41 @@ import { AssistantChatArea as s } from "./AssistantChatArea.js";
|
|
|
9
9
|
import { AssistantConversationList as c } from "./AssistantConversationList.js";
|
|
10
10
|
import { useMemo as l, useRef as u } from "react";
|
|
11
11
|
import { jsx as d, jsxs as f } from "react/jsx-runtime";
|
|
12
|
+
import { useFilesServiceWarmup as p } from "@burdenoff/fe-libs/storage";
|
|
12
13
|
//#region src/components/assistant/AIAssistantPanel.tsx
|
|
13
|
-
var
|
|
14
|
-
let
|
|
15
|
-
r(
|
|
16
|
-
let
|
|
14
|
+
var m = ({ onClose: m, visible: h, docked: g, onToggleDock: _ }) => {
|
|
15
|
+
let v = t(), y = u(null), { conversations: b, activeConversationId: x, conversationListOpen: S, toggleConversationList: C, createConversation: w } = e(), T = b.find((e) => e.id === x);
|
|
16
|
+
r(T?.backendSessionId ?? null, T?.mode ?? null, h ?? !0), p(h ?? !0);
|
|
17
|
+
let E = l(() => i(), []);
|
|
17
18
|
return n({
|
|
18
|
-
panelRef:
|
|
19
|
-
onClose:
|
|
19
|
+
panelRef: y,
|
|
20
|
+
onClose: m
|
|
20
21
|
}), /* @__PURE__ */ d(a, {
|
|
21
|
-
visible:
|
|
22
|
+
visible: h ?? !0,
|
|
22
23
|
children: /* @__PURE__ */ f("div", {
|
|
23
|
-
ref:
|
|
24
|
+
ref: y,
|
|
24
25
|
className: "relative flex h-full w-full flex-col bg-bg-surface",
|
|
25
26
|
role: "complementary",
|
|
26
|
-
"aria-label":
|
|
27
|
+
"aria-label": v("healthybowl.assistant.panel.ariaLabel", "AI Assistant"),
|
|
27
28
|
"data-testid": "ai-assistant-panel",
|
|
28
29
|
tabIndex: -1,
|
|
29
30
|
children: [
|
|
30
31
|
/* @__PURE__ */ d(o, {
|
|
31
|
-
contextLabel:
|
|
32
|
-
onNewConversation: () =>
|
|
33
|
-
onOpenHistory:
|
|
34
|
-
historyOpen:
|
|
35
|
-
onClose:
|
|
36
|
-
docked:
|
|
37
|
-
onToggleDock:
|
|
32
|
+
contextLabel: E,
|
|
33
|
+
onNewConversation: () => w(),
|
|
34
|
+
onOpenHistory: C,
|
|
35
|
+
historyOpen: S,
|
|
36
|
+
onClose: m,
|
|
37
|
+
docked: g,
|
|
38
|
+
onToggleDock: _
|
|
38
39
|
}),
|
|
39
|
-
|
|
40
|
+
S && /* @__PURE__ */ d(c, {}),
|
|
40
41
|
/* @__PURE__ */ d(s, {})
|
|
41
42
|
]
|
|
42
43
|
})
|
|
43
44
|
});
|
|
44
45
|
};
|
|
45
46
|
//#endregion
|
|
46
|
-
export {
|
|
47
|
+
export { m as AIAssistantPanel };
|
|
47
48
|
|
|
48
49
|
//# sourceMappingURL=AIAssistantPanel.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AIAssistantPanel.js","names":[],"sources":["../../../src/components/assistant/AIAssistantPanel.tsx"],"sourcesContent":["/**\n * AI Assistant Panel — top-level component for the in-page assistant.\n *\n * Layout (v2): a fixed identity header (AssistantHeader) with the brand mark,\n * an availability/context subtitle and icon actions (new conversation, history,\n * export, dock, close), an always-visible transcript, and the composer pinned\n * to the bottom. Conversation history opens as an overlay drawer over the panel\n * — never as an accordion over the transcript.\n *\n * The external prop contract ({ onClose, visible, docked, onToggleDock }) is\n * unchanged; the sandbox/session/transport logic lives in AssistantChatArea.\n */\n\nimport { useMemo, useRef, type FC } from 'react';\nimport type { PanelProps } from '@burdenoff/fe-libs/shared/plugins';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { useAssistantKeyboardShortcuts } from '@/hooks/useAssistantKeyboardShortcuts';\nimport { useAssistantHeartbeat } from '@/hooks/useAssistantHeartbeat';\nimport { describeCurrentPage } from '@/utils/pageContext';\nimport { AssistantHeader } from './AssistantHeader';\nimport { AssistantChatArea } from './AssistantChatArea';\nimport { AssistantConversationList } from './AssistantConversationList';\nimport { AssistantSpeechProvider } from './AssistantSpeechProvider';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport type AIAssistantPanelProps = PanelProps & {\n /** When provided, renders a dock/float toggle in the header. */\n docked?: boolean;\n onToggleDock?: () => void;\n};\n\nexport const AIAssistantPanel: FC<AIAssistantPanelProps> = ({ onClose, visible, docked, onToggleDock }) => {\n const tr = useTr();\n const panelRef = useRef<HTMLDivElement>(null);\n\n const { conversations, activeConversationId, conversationListOpen, toggleConversationList, createConversation } =\n useAssistantStore();\n\n const activeConversation = conversations.find((c) => c.id === activeConversationId);\n const activeSessionId = activeConversation?.backendSessionId ?? null;\n\n // Keep sandbox alive while panel is open\n useAssistantHeartbeat(activeSessionId, activeConversation?.mode ?? null, visible ?? true);\n\n const contextLabel = useMemo(() => describeCurrentPage(), []);\n\n useAssistantKeyboardShortcuts({\n panelRef,\n onClose,\n });\n\n return (\n // Speech output (BOFF-6290) is provided at the panel root so that hiding the\n // panel — not only unmounting it — stops the voice, and so the header toggle\n // and every message's speak button share one playback state.\n <AssistantSpeechProvider visible={visible ?? true}>\n <div\n ref={panelRef}\n className=\"relative flex h-full w-full flex-col bg-bg-surface\"\n role=\"complementary\"\n aria-label={tr('healthybowl.assistant.panel.ariaLabel', 'AI Assistant')}\n data-testid=\"ai-assistant-panel\"\n tabIndex={-1}\n >\n <AssistantHeader\n contextLabel={contextLabel}\n onNewConversation={() => createConversation()}\n onOpenHistory={toggleConversationList}\n historyOpen={conversationListOpen}\n onClose={onClose}\n docked={docked}\n onToggleDock={onToggleDock}\n />\n\n {/* Conversation history overlay drawer (switch between chats) */}\n {conversationListOpen && <AssistantConversationList />}\n\n <AssistantChatArea />\n </div>\n </AssistantSpeechProvider>\n );\n};\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"AIAssistantPanel.js","names":[],"sources":["../../../src/components/assistant/AIAssistantPanel.tsx"],"sourcesContent":["/**\n * AI Assistant Panel — top-level component for the in-page assistant.\n *\n * Layout (v2): a fixed identity header (AssistantHeader) with the brand mark,\n * an availability/context subtitle and icon actions (new conversation, history,\n * export, dock, close), an always-visible transcript, and the composer pinned\n * to the bottom. Conversation history opens as an overlay drawer over the panel\n * — never as an accordion over the transcript.\n *\n * The external prop contract ({ onClose, visible, docked, onToggleDock }) is\n * unchanged; the sandbox/session/transport logic lives in AssistantChatArea.\n */\n\nimport { useMemo, useRef, type FC } from 'react';\nimport type { PanelProps } from '@burdenoff/fe-libs/shared/plugins';\nimport { useFilesServiceWarmup } from '@burdenoff/fe-libs/storage';\nimport { useAssistantStore } from '@/store/assistantStore';\nimport { useAssistantKeyboardShortcuts } from '@/hooks/useAssistantKeyboardShortcuts';\nimport { useAssistantHeartbeat } from '@/hooks/useAssistantHeartbeat';\nimport { describeCurrentPage } from '@/utils/pageContext';\nimport { AssistantHeader } from './AssistantHeader';\nimport { AssistantChatArea } from './AssistantChatArea';\nimport { AssistantConversationList } from './AssistantConversationList';\nimport { AssistantSpeechProvider } from './AssistantSpeechProvider';\nimport { useTr } from '../../shared/hooks/useTr';\n\nexport type AIAssistantPanelProps = PanelProps & {\n /** When provided, renders a dock/float toggle in the header. */\n docked?: boolean;\n onToggleDock?: () => void;\n};\n\nexport const AIAssistantPanel: FC<AIAssistantPanelProps> = ({ onClose, visible, docked, onToggleDock }) => {\n const tr = useTr();\n const panelRef = useRef<HTMLDivElement>(null);\n\n const { conversations, activeConversationId, conversationListOpen, toggleConversationList, createConversation } =\n useAssistantStore();\n\n const activeConversation = conversations.find((c) => c.id === activeConversationId);\n const activeSessionId = activeConversation?.backendSessionId ?? null;\n\n // Keep sandbox alive while panel is open\n useAssistantHeartbeat(activeSessionId, activeConversation?.mode ?? null, visible ?? true);\n\n // Wake wspace-files-svc the moment the panel opens. It runs at minReplicas 0 and\n // needs >=51s to bind its port (prisma migrate deploy 26.0s + boot ~25.5s) against\n // the gateway's 15s budget, so the first attachment after any quiet period would\n // otherwise fail outright. Firing here means the container boots while the user is\n // still typing. Best-effort by construction: single-flighted, rate-limited, and it\n // never surfaces an error — see fe-libs `warmFilesService`.\n useFilesServiceWarmup(visible ?? true);\n\n const contextLabel = useMemo(() => describeCurrentPage(), []);\n\n useAssistantKeyboardShortcuts({\n panelRef,\n onClose,\n });\n\n return (\n // Speech output (BOFF-6290) is provided at the panel root so that hiding the\n // panel — not only unmounting it — stops the voice, and so the header toggle\n // and every message's speak button share one playback state.\n <AssistantSpeechProvider visible={visible ?? true}>\n <div\n ref={panelRef}\n className=\"relative flex h-full w-full flex-col bg-bg-surface\"\n role=\"complementary\"\n aria-label={tr('healthybowl.assistant.panel.ariaLabel', 'AI Assistant')}\n data-testid=\"ai-assistant-panel\"\n tabIndex={-1}\n >\n <AssistantHeader\n contextLabel={contextLabel}\n onNewConversation={() => createConversation()}\n onOpenHistory={toggleConversationList}\n historyOpen={conversationListOpen}\n onClose={onClose}\n docked={docked}\n onToggleDock={onToggleDock}\n />\n\n {/* Conversation history overlay drawer (switch between chats) */}\n {conversationListOpen && <AssistantConversationList />}\n\n <AssistantChatArea />\n </div>\n </AssistantSpeechProvider>\n );\n};\n"],"mappings":";;;;;;;;;;;;;AAgCA,IAAa,KAA+C,EAAE,YAAS,YAAS,WAAQ,sBAAmB;CACzG,IAAM,IAAK,GAAO,EACZ,IAAW,EAAuB,KAAK,EAEvC,EAAE,kBAAe,yBAAsB,yBAAsB,2BAAwB,0BACzF,GAAmB,EAEf,IAAqB,EAAc,MAAM,MAAM,EAAE,OAAO,EAAqB;AAYnF,CARA,EAHwB,GAAoB,oBAAoB,MAGzB,GAAoB,QAAQ,MAAM,KAAW,GAAK,EAQzF,EAAsB,KAAW,GAAK;CAEtC,IAAM,IAAe,QAAc,GAAqB,EAAE,EAAE,CAAC;AAO7D,QALA,EAA8B;EAC5B;EACA;EACD,CAAC,EAMA,kBAAC,GAAD;EAAyB,SAAS,KAAW;YAC3C,kBAAC,OAAD;GACE,KAAK;GACL,WAAU;GACV,MAAK;GACL,cAAY,EAAG,yCAAyC,eAAe;GACvE,eAAY;GACZ,UAAU;aANZ;IAQE,kBAAC,GAAD;KACgB;KACd,yBAAyB,GAAoB;KAC7C,eAAe;KACf,aAAa;KACJ;KACD;KACM;KACd,CAAA;IAGD,KAAwB,kBAAC,GAAD,EAA6B,CAAA;IAEtD,kBAAC,GAAD,EAAqB,CAAA;IACjB;;EACkB,CAAA"}
|
|
@@ -30,7 +30,7 @@ var u = ({ attachments: u, onRemove: d, onRetry: f, disabled: p = !1 }) => {
|
|
|
30
30
|
children: e.filename
|
|
31
31
|
}), /* @__PURE__ */ c("span", {
|
|
32
32
|
className: "block truncate text-[10px] leading-tight text-text-muted",
|
|
33
|
-
children: h ? e.error ?? m("healthybowl.assistant.attachments.failed", "Upload failed") : u ? m("healthybowl.assistant.attachments.uploading", "Uploading…") : t(e.size)
|
|
33
|
+
children: h ? e.error ?? m("healthybowl.assistant.attachments.failed", "Upload failed") : u ? e.progressNote ?? m("healthybowl.assistant.attachments.uploading", "Uploading…") : t(e.size)
|
|
34
34
|
})]
|
|
35
35
|
}),
|
|
36
36
|
h && /* @__PURE__ */ c("button", {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantAttachmentChips.js","names":[],"sources":["../../../../src/components/assistant/composer/AssistantAttachmentChips.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { AlertCircle, FileText, Loader2, Paperclip, RotateCcw, X } from 'lucide-react';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { formatBytes, type AssistantAttachment } from '@/utils/assistantAttachments';\n\ninterface Props {\n attachments: AssistantAttachment[];\n onRemove: (id: string) => void;\n /** Re-upload a failed attachment from the bytes already prepared. */\n onRetry: (id: string) => void;\n disabled?: boolean;\n}\n\n/**\n * Pending-attachment strip above the composer input (Workstream 3).\n *\n * Images get a thumbnail, everything else a typed icon chip. Upload state is\n * shown on the chip itself — a spinner while it is in flight, a red outline plus\n * the reason when it fails — so a farmer on a weak connection can see which\n * photo is still going up instead of guessing why send is disabled.\n */\nexport const AssistantAttachmentChips: FC<Props> = ({ attachments, onRemove, onRetry, disabled = false }) => {\n const tr = useTr();\n if (attachments.length === 0) return null;\n\n return (\n <ul\n className=\"mb-1.5 flex flex-wrap gap-1.5 px-0.5\"\n aria-label={tr('healthybowl.assistant.attachments.listLabel', 'Attached files')}\n data-testid=\"assistant-attachment-chips\"\n >\n {attachments.map((attachment) => {\n const isBusy = attachment.status === 'pending' || attachment.status === 'uploading';\n const isError = attachment.status === 'error';\n\n return (\n <li\n key={attachment.id}\n className={`flex max-w-[220px] items-center gap-1.5 rounded-lg border py-1 pl-1 pr-1.5 ${\n isError ? 'border-status-error-text/40 bg-status-error-bg/10' : 'border-border-subtle bg-bg-surface'\n }`}\n data-testid=\"assistant-attachment-chip\"\n >\n <span className=\"flex size-7 flex-shrink-0 items-center justify-center overflow-hidden rounded-md bg-bg-sunken text-text-muted\">\n {attachment.previewUrl ? (\n <img src={attachment.previewUrl} alt=\"\" className=\"size-full object-cover\" />\n ) : isError ? (\n <AlertCircle className=\"size-3.5 text-status-error-text\" />\n ) : attachment.kind === 'text' ? (\n <FileText className=\"size-3.5\" />\n ) : (\n <Paperclip className=\"size-3.5\" />\n )}\n </span>\n\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate text-[11px] font-medium leading-tight text-text-primary\">\n {attachment.filename}\n </span>\n <span className=\"block truncate text-[10px] leading-tight text-text-muted\">\n {isError\n ? (attachment.error ?? tr('healthybowl.assistant.attachments.failed', 'Upload failed'))\n : isBusy\n ? tr('healthybowl.assistant.attachments.uploading', 'Uploading…')\n : formatBytes(attachment.size)}\n </span>\n </span>\n\n {isError && (\n <button\n type=\"button\"\n onClick={() => onRetry(attachment.id)}\n disabled={disabled}\n className=\"flex size-5 flex-shrink-0 items-center justify-center rounded-full text-status-error-text transition-colors hover:bg-bg-sunken focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-not-allowed\"\n aria-label={tr('healthybowl.assistant.attachments.retry', 'Retry uploading {{name}}', {\n name: attachment.filename,\n })}\n data-testid=\"assistant-attachment-retry\"\n >\n <RotateCcw className=\"size-3\" />\n </button>\n )}\n\n {isBusy ? (\n <Loader2\n className=\"size-3.5 flex-shrink-0 animate-spin text-text-muted\"\n aria-label={tr('healthybowl.assistant.attachments.uploading', 'Uploading…')}\n />\n ) : (\n <button\n type=\"button\"\n onClick={() => onRemove(attachment.id)}\n disabled={disabled}\n className=\"flex size-5 flex-shrink-0 items-center justify-center rounded-full text-text-muted transition-colors hover:bg-bg-sunken hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-not-allowed\"\n aria-label={tr('healthybowl.assistant.attachments.remove', 'Remove {{name}}', {\n name: attachment.filename,\n })}\n data-testid=\"assistant-attachment-remove\"\n >\n <X className=\"size-3\" />\n </button>\n )}\n </li>\n );\n })}\n </ul>\n );\n};\n"],"mappings":";;;;;AAqBA,IAAa,KAAuC,EAAE,gBAAa,aAAU,YAAS,cAAW,SAAY;CAC3G,IAAM,IAAK,GAAO;AAGlB,QAFI,EAAY,WAAW,IAAU,OAGnC,kBAAC,MAAD;EACE,WAAU;EACV,cAAY,EAAG,+CAA+C,iBAAiB;EAC/E,eAAY;YAEX,EAAY,KAAK,MAAe;GAC/B,IAAM,IAAS,EAAW,WAAW,aAAa,EAAW,WAAW,aAClE,IAAU,EAAW,WAAW;AAEtC,UACE,kBAAC,MAAD;IAEE,WAAW,8EACT,IAAU,sDAAsD;IAElE,eAAY;cALd;KAOE,kBAAC,QAAD;MAAM,WAAU;gBACb,EAAW,aACV,kBAAC,OAAD;OAAK,KAAK,EAAW;OAAY,KAAI;OAAG,WAAU;OAA2B,CAAA,GAC3E,IACF,kBAAC,GAAD,EAAa,WAAU,mCAAoC,CAAA,GACzD,EAAW,SAAS,SACtB,kBAAC,GAAD,EAAU,WAAU,YAAa,CAAA,GAEjC,kBAAC,GAAD,EAAW,WAAU,YAAa,CAAA;MAE/B,CAAA;KAEP,kBAAC,QAAD;MAAM,WAAU;gBAAhB,CACE,kBAAC,QAAD;OAAM,WAAU;iBACb,EAAW;OACP,CAAA,EACP,kBAAC,QAAD;OAAM,WAAU;iBACb,IACI,EAAW,SAAS,EAAG,4CAA4C,gBAAgB,GACpF,
|
|
1
|
+
{"version":3,"file":"AssistantAttachmentChips.js","names":[],"sources":["../../../../src/components/assistant/composer/AssistantAttachmentChips.tsx"],"sourcesContent":["import type { FC } from 'react';\nimport { AlertCircle, FileText, Loader2, Paperclip, RotateCcw, X } from 'lucide-react';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { formatBytes, type AssistantAttachment } from '@/utils/assistantAttachments';\n\ninterface Props {\n attachments: AssistantAttachment[];\n onRemove: (id: string) => void;\n /** Re-upload a failed attachment from the bytes already prepared. */\n onRetry: (id: string) => void;\n disabled?: boolean;\n}\n\n/**\n * Pending-attachment strip above the composer input (Workstream 3).\n *\n * Images get a thumbnail, everything else a typed icon chip. Upload state is\n * shown on the chip itself — a spinner while it is in flight, a red outline plus\n * the reason when it fails — so a farmer on a weak connection can see which\n * photo is still going up instead of guessing why send is disabled.\n */\nexport const AssistantAttachmentChips: FC<Props> = ({ attachments, onRemove, onRetry, disabled = false }) => {\n const tr = useTr();\n if (attachments.length === 0) return null;\n\n return (\n <ul\n className=\"mb-1.5 flex flex-wrap gap-1.5 px-0.5\"\n aria-label={tr('healthybowl.assistant.attachments.listLabel', 'Attached files')}\n data-testid=\"assistant-attachment-chips\"\n >\n {attachments.map((attachment) => {\n const isBusy = attachment.status === 'pending' || attachment.status === 'uploading';\n const isError = attachment.status === 'error';\n\n return (\n <li\n key={attachment.id}\n className={`flex max-w-[220px] items-center gap-1.5 rounded-lg border py-1 pl-1 pr-1.5 ${\n isError ? 'border-status-error-text/40 bg-status-error-bg/10' : 'border-border-subtle bg-bg-surface'\n }`}\n data-testid=\"assistant-attachment-chip\"\n >\n <span className=\"flex size-7 flex-shrink-0 items-center justify-center overflow-hidden rounded-md bg-bg-sunken text-text-muted\">\n {attachment.previewUrl ? (\n <img src={attachment.previewUrl} alt=\"\" className=\"size-full object-cover\" />\n ) : isError ? (\n <AlertCircle className=\"size-3.5 text-status-error-text\" />\n ) : attachment.kind === 'text' ? (\n <FileText className=\"size-3.5\" />\n ) : (\n <Paperclip className=\"size-3.5\" />\n )}\n </span>\n\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate text-[11px] font-medium leading-tight text-text-primary\">\n {attachment.filename}\n </span>\n <span className=\"block truncate text-[10px] leading-tight text-text-muted\">\n {isError\n ? (attachment.error ?? tr('healthybowl.assistant.attachments.failed', 'Upload failed'))\n : isBusy\n ? // `progressNote` explains a long wait (a scale-to-zero files-svc\n // container needs ~51s to boot, so fe-libs retries for about a\n // minute). Still an upload in progress, never an error.\n (attachment.progressNote ?? tr('healthybowl.assistant.attachments.uploading', 'Uploading…'))\n : formatBytes(attachment.size)}\n </span>\n </span>\n\n {isError && (\n <button\n type=\"button\"\n onClick={() => onRetry(attachment.id)}\n disabled={disabled}\n className=\"flex size-5 flex-shrink-0 items-center justify-center rounded-full text-status-error-text transition-colors hover:bg-bg-sunken focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-not-allowed\"\n aria-label={tr('healthybowl.assistant.attachments.retry', 'Retry uploading {{name}}', {\n name: attachment.filename,\n })}\n data-testid=\"assistant-attachment-retry\"\n >\n <RotateCcw className=\"size-3\" />\n </button>\n )}\n\n {isBusy ? (\n <Loader2\n className=\"size-3.5 flex-shrink-0 animate-spin text-text-muted\"\n aria-label={tr('healthybowl.assistant.attachments.uploading', 'Uploading…')}\n />\n ) : (\n <button\n type=\"button\"\n onClick={() => onRemove(attachment.id)}\n disabled={disabled}\n className=\"flex size-5 flex-shrink-0 items-center justify-center rounded-full text-text-muted transition-colors hover:bg-bg-sunken hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-not-allowed\"\n aria-label={tr('healthybowl.assistant.attachments.remove', 'Remove {{name}}', {\n name: attachment.filename,\n })}\n data-testid=\"assistant-attachment-remove\"\n >\n <X className=\"size-3\" />\n </button>\n )}\n </li>\n );\n })}\n </ul>\n );\n};\n"],"mappings":";;;;;AAqBA,IAAa,KAAuC,EAAE,gBAAa,aAAU,YAAS,cAAW,SAAY;CAC3G,IAAM,IAAK,GAAO;AAGlB,QAFI,EAAY,WAAW,IAAU,OAGnC,kBAAC,MAAD;EACE,WAAU;EACV,cAAY,EAAG,+CAA+C,iBAAiB;EAC/E,eAAY;YAEX,EAAY,KAAK,MAAe;GAC/B,IAAM,IAAS,EAAW,WAAW,aAAa,EAAW,WAAW,aAClE,IAAU,EAAW,WAAW;AAEtC,UACE,kBAAC,MAAD;IAEE,WAAW,8EACT,IAAU,sDAAsD;IAElE,eAAY;cALd;KAOE,kBAAC,QAAD;MAAM,WAAU;gBACb,EAAW,aACV,kBAAC,OAAD;OAAK,KAAK,EAAW;OAAY,KAAI;OAAG,WAAU;OAA2B,CAAA,GAC3E,IACF,kBAAC,GAAD,EAAa,WAAU,mCAAoC,CAAA,GACzD,EAAW,SAAS,SACtB,kBAAC,GAAD,EAAU,WAAU,YAAa,CAAA,GAEjC,kBAAC,GAAD,EAAW,WAAU,YAAa,CAAA;MAE/B,CAAA;KAEP,kBAAC,QAAD;MAAM,WAAU;gBAAhB,CACE,kBAAC,QAAD;OAAM,WAAU;iBACb,EAAW;OACP,CAAA,EACP,kBAAC,QAAD;OAAM,WAAU;iBACb,IACI,EAAW,SAAS,EAAG,4CAA4C,gBAAgB,GACpF,IAIG,EAAW,gBAAgB,EAAG,+CAA+C,aAAa,GAC3F,EAAY,EAAW,KAAK;OAC7B,CAAA,CACF;;KAEN,KACC,kBAAC,UAAD;MACE,MAAK;MACL,eAAe,EAAQ,EAAW,GAAG;MAC3B;MACV,WAAU;MACV,cAAY,EAAG,2CAA2C,4BAA4B,EACpF,MAAM,EAAW,UAClB,CAAC;MACF,eAAY;gBAEZ,kBAAC,GAAD,EAAW,WAAU,UAAW,CAAA;MACzB,CAAA;KAGV,IACC,kBAAC,GAAD;MACE,WAAU;MACV,cAAY,EAAG,+CAA+C,aAAa;MAC3E,CAAA,GAEF,kBAAC,UAAD;MACE,MAAK;MACL,eAAe,EAAS,EAAW,GAAG;MAC5B;MACV,WAAU;MACV,cAAY,EAAG,4CAA4C,mBAAmB,EAC5E,MAAM,EAAW,UAClB,CAAC;MACF,eAAY;gBAEZ,kBAAC,GAAD,EAAG,WAAU,UAAW,CAAA;MACjB,CAAA;KAER;MApEE,EAAW,GAoEb;IAEP;EACC,CAAA"}
|
|
@@ -1,18 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
1
|
+
import { useTr as e } from "../shared/hooks/useTr.js";
|
|
2
|
+
import { getWorkspaceId as t } from "../utils/assistantContext.js";
|
|
3
|
+
import { AttachmentRejectedError as n, INLINE_IMAGE_QUALITY as r, MAX_INLINE_CHARS_PER_FILE as i, classifyAttachment as a, detectDocumentFormat as o, getAttachmentSendBlocker as s, truncateForInline as c, validateFile as l } from "../utils/assistantAttachments.js";
|
|
4
|
+
import { downscaleImage as u } from "../healthybowl/utils/imageDownscale.js";
|
|
5
|
+
import { extractDocumentText as d } from "../utils/documentExtract.js";
|
|
6
|
+
import { useCallback as f, useEffect as p, useRef as m, useState as h } from "react";
|
|
7
|
+
import { useSaveToFiles as g } from "@burdenoff/fe-libs/storage";
|
|
8
|
+
import { graphqlFetch as _ } from "@burdenoff/fe-libs/shared/graphql";
|
|
8
9
|
//#region src/hooks/useAssistantAttachments.ts
|
|
9
|
-
var
|
|
10
|
-
async function
|
|
10
|
+
var v = "/HealthyBowl/AI Assistant/Attachments", y = "\n query HealthyBowlAssistantAttachmentUrl($id: ID!) {\n getFileDownloadUrl(id: $id)\n }\n";
|
|
11
|
+
async function b(e, t) {
|
|
11
12
|
if (!e || !t) return null;
|
|
12
13
|
try {
|
|
13
|
-
return (await
|
|
14
|
+
return (await _({
|
|
14
15
|
gateway: "workspace",
|
|
15
|
-
query:
|
|
16
|
+
query: y,
|
|
16
17
|
variables: { id: e },
|
|
17
18
|
workspaceToken: !0,
|
|
18
19
|
workspaceId: t,
|
|
@@ -22,175 +23,197 @@ async function y(e, t) {
|
|
|
22
23
|
return null;
|
|
23
24
|
}
|
|
24
25
|
}
|
|
25
|
-
var
|
|
26
|
-
function
|
|
27
|
-
return
|
|
26
|
+
var x = 0;
|
|
27
|
+
function S() {
|
|
28
|
+
return x += 1, `att-${Date.now()}-${x}`;
|
|
28
29
|
}
|
|
29
|
-
async function
|
|
30
|
-
let
|
|
31
|
-
id:
|
|
30
|
+
async function C(e) {
|
|
31
|
+
let t = a(e.type, e.name), s = {
|
|
32
|
+
id: S(),
|
|
32
33
|
status: "pending"
|
|
33
34
|
};
|
|
34
|
-
if (
|
|
35
|
-
let
|
|
35
|
+
if (t === "image") {
|
|
36
|
+
let i = await u(e, {
|
|
36
37
|
encodeFallback: !1,
|
|
37
38
|
inline: {
|
|
38
39
|
maxDim: 768,
|
|
39
|
-
quality:
|
|
40
|
+
quality: r
|
|
40
41
|
}
|
|
41
42
|
});
|
|
42
|
-
if (!
|
|
43
|
+
if (!i.downscaled && i.blob.size > 10485760) throw new n("unsupported-image");
|
|
43
44
|
return {
|
|
44
45
|
attachment: {
|
|
45
|
-
...
|
|
46
|
-
filename:
|
|
47
|
-
mimeType:
|
|
48
|
-
size:
|
|
49
|
-
kind:
|
|
50
|
-
previewUrl:
|
|
51
|
-
inlineDataUrl:
|
|
46
|
+
...s,
|
|
47
|
+
filename: i.filename,
|
|
48
|
+
mimeType: i.mimeType,
|
|
49
|
+
size: i.blob.size,
|
|
50
|
+
kind: t,
|
|
51
|
+
previewUrl: i.dataUrl || void 0,
|
|
52
|
+
inlineDataUrl: i.inlineDataUrl
|
|
52
53
|
},
|
|
53
|
-
blob:
|
|
54
|
+
blob: i.blob
|
|
54
55
|
};
|
|
55
56
|
}
|
|
56
|
-
if (
|
|
57
|
-
let { text:
|
|
57
|
+
if (t === "text") {
|
|
58
|
+
let { text: n, truncated: r } = c(await e.text(), i);
|
|
58
59
|
return {
|
|
59
60
|
attachment: {
|
|
60
|
-
...
|
|
61
|
+
...s,
|
|
61
62
|
filename: e.name,
|
|
62
63
|
mimeType: e.type || "text/plain",
|
|
63
64
|
size: e.size,
|
|
64
|
-
kind:
|
|
65
|
-
textContent:
|
|
66
|
-
textTruncated:
|
|
65
|
+
kind: t,
|
|
66
|
+
textContent: n,
|
|
67
|
+
textTruncated: r
|
|
67
68
|
},
|
|
68
69
|
blob: e
|
|
69
70
|
};
|
|
70
71
|
}
|
|
71
|
-
let
|
|
72
|
-
if (
|
|
73
|
-
let
|
|
72
|
+
let l = o(e.type, e.name);
|
|
73
|
+
if (l) {
|
|
74
|
+
let n = await d(e, l);
|
|
74
75
|
return {
|
|
75
76
|
attachment: {
|
|
76
|
-
...
|
|
77
|
+
...s,
|
|
77
78
|
filename: e.name,
|
|
78
79
|
mimeType: e.type || "application/octet-stream",
|
|
79
80
|
size: e.size,
|
|
80
|
-
kind:
|
|
81
|
-
extraction:
|
|
82
|
-
textContent:
|
|
83
|
-
textTruncated:
|
|
84
|
-
documentPages:
|
|
81
|
+
kind: t,
|
|
82
|
+
extraction: n.extraction,
|
|
83
|
+
textContent: n.textContent,
|
|
84
|
+
textTruncated: n.textTruncated,
|
|
85
|
+
documentPages: n.documentPages
|
|
85
86
|
},
|
|
86
87
|
blob: e
|
|
87
88
|
};
|
|
88
89
|
}
|
|
89
90
|
return {
|
|
90
91
|
attachment: {
|
|
91
|
-
...
|
|
92
|
+
...s,
|
|
92
93
|
filename: e.name,
|
|
93
94
|
mimeType: e.type || "application/octet-stream",
|
|
94
95
|
size: e.size,
|
|
95
|
-
kind:
|
|
96
|
+
kind: t
|
|
96
97
|
},
|
|
97
98
|
blob: e
|
|
98
99
|
};
|
|
99
100
|
}
|
|
100
|
-
function
|
|
101
|
-
let { save:
|
|
102
|
-
|
|
103
|
-
|
|
101
|
+
function w() {
|
|
102
|
+
let r = e(), { save: i } = g(), [a, o] = h([]), [c, u] = h(null), d = m(Promise.resolve()), [_, y] = h(0), x = m(0), S = m(/* @__PURE__ */ new Map()), w = m(/* @__PURE__ */ new Set()), T = m(0), E = m(!0);
|
|
103
|
+
p(() => () => {
|
|
104
|
+
E.current = !1;
|
|
104
105
|
}, []);
|
|
105
|
-
let
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
}, [
|
|
109
|
-
let
|
|
110
|
-
|
|
106
|
+
let D = m([]);
|
|
107
|
+
p(() => {
|
|
108
|
+
D.current = a;
|
|
109
|
+
}, [a]);
|
|
110
|
+
let O = f((e, t) => {
|
|
111
|
+
E.current && o((n) => n.map((n) => n.id === e ? {
|
|
111
112
|
...n,
|
|
112
113
|
...t
|
|
113
114
|
} : n));
|
|
114
|
-
}, []),
|
|
115
|
-
if (!
|
|
116
|
-
|
|
115
|
+
}, []), k = f(async ({ attachment: e, blob: n }) => {
|
|
116
|
+
if (!w.current.has(e.id)) {
|
|
117
|
+
O(e.id, {
|
|
118
|
+
status: "uploading",
|
|
119
|
+
progressNote: void 0
|
|
120
|
+
});
|
|
117
121
|
try {
|
|
118
|
-
let
|
|
122
|
+
let a = await i({
|
|
119
123
|
source: {
|
|
120
124
|
kind: "blob",
|
|
121
|
-
filename:
|
|
122
|
-
mimeType:
|
|
125
|
+
filename: e.filename,
|
|
126
|
+
mimeType: e.mimeType,
|
|
123
127
|
getBlob: async () => ({
|
|
124
|
-
blob:
|
|
125
|
-
filename:
|
|
126
|
-
mimeType:
|
|
128
|
+
blob: n,
|
|
129
|
+
filename: e.filename,
|
|
130
|
+
mimeType: e.mimeType
|
|
127
131
|
})
|
|
128
132
|
},
|
|
129
|
-
folderPath:
|
|
133
|
+
folderPath: v,
|
|
134
|
+
onRetry: (t) => {
|
|
135
|
+
w.current.has(e.id) || O(e.id, { progressNote: t.kind === "cold-start" ? r("healthybowl.assistant.attachments.waking", "File service is starting up — retry {{attempt}} of {{max}}", {
|
|
136
|
+
attempt: String(t.attempt),
|
|
137
|
+
max: String(t.maxAttempts)
|
|
138
|
+
}) : r("healthybowl.assistant.attachments.retrying", "Retrying {{attempt}} of {{max}}", {
|
|
139
|
+
attempt: String(t.attempt),
|
|
140
|
+
max: String(t.maxAttempts)
|
|
141
|
+
}) });
|
|
142
|
+
}
|
|
130
143
|
});
|
|
131
|
-
if (
|
|
132
|
-
let
|
|
133
|
-
if (
|
|
134
|
-
|
|
144
|
+
if (w.current.has(e.id)) return;
|
|
145
|
+
let o = a?.id ? await b(a.id, t()) : null;
|
|
146
|
+
if (w.current.has(e.id)) return;
|
|
147
|
+
O(e.id, {
|
|
135
148
|
status: "ready",
|
|
136
|
-
fileId:
|
|
137
|
-
downloadUrl:
|
|
149
|
+
fileId: a?.id,
|
|
150
|
+
downloadUrl: o ?? void 0,
|
|
151
|
+
progressNote: void 0
|
|
138
152
|
});
|
|
139
|
-
} catch (
|
|
140
|
-
if (
|
|
141
|
-
if (
|
|
142
|
-
|
|
153
|
+
} catch (t) {
|
|
154
|
+
if (w.current.has(e.id)) return;
|
|
155
|
+
if (e.kind === "text" || e.textContent) {
|
|
156
|
+
O(e.id, {
|
|
157
|
+
status: "ready",
|
|
158
|
+
progressNote: void 0
|
|
159
|
+
});
|
|
143
160
|
return;
|
|
144
161
|
}
|
|
145
|
-
|
|
162
|
+
O(e.id, {
|
|
146
163
|
status: "error",
|
|
147
|
-
error:
|
|
164
|
+
error: t instanceof Error ? t.message : "Upload failed",
|
|
165
|
+
progressNote: void 0
|
|
148
166
|
});
|
|
149
167
|
}
|
|
150
168
|
}
|
|
151
|
-
}, [
|
|
169
|
+
}, [
|
|
170
|
+
O,
|
|
171
|
+
i,
|
|
172
|
+
r
|
|
173
|
+
]), A = f((e) => {
|
|
152
174
|
if (!e) return;
|
|
153
|
-
let
|
|
154
|
-
if (
|
|
155
|
-
|
|
175
|
+
let t = Array.from(e);
|
|
176
|
+
if (t.length === 0) return;
|
|
177
|
+
u(null);
|
|
156
178
|
let r = [];
|
|
157
|
-
for (let e of
|
|
158
|
-
let t =
|
|
179
|
+
for (let e of t) {
|
|
180
|
+
let t = l(e, T.current);
|
|
159
181
|
if (t) {
|
|
160
|
-
|
|
182
|
+
u(t);
|
|
161
183
|
continue;
|
|
162
184
|
}
|
|
163
|
-
r.push(e),
|
|
185
|
+
r.push(e), T.current += 1;
|
|
164
186
|
}
|
|
165
187
|
if (r.length !== 0) {
|
|
166
|
-
|
|
188
|
+
y((e) => e + r.length);
|
|
167
189
|
for (let e of r) {
|
|
168
|
-
let
|
|
169
|
-
|
|
190
|
+
let t = x.current;
|
|
191
|
+
d.current = d.current.then(async () => {
|
|
170
192
|
let r = null;
|
|
171
193
|
try {
|
|
172
|
-
r = await
|
|
194
|
+
r = await C(e);
|
|
173
195
|
} catch (e) {
|
|
174
|
-
|
|
196
|
+
T.current = Math.max(0, T.current - 1), E.current && u(e instanceof n ? e.reason : "unreadable");
|
|
175
197
|
}
|
|
176
|
-
if (!
|
|
177
|
-
if (
|
|
178
|
-
|
|
198
|
+
if (!E.current || (y((e) => Math.max(0, e - 1)), !r)) return;
|
|
199
|
+
if (t !== x.current) {
|
|
200
|
+
T.current = Math.max(0, T.current - 1);
|
|
179
201
|
return;
|
|
180
202
|
}
|
|
181
|
-
let
|
|
182
|
-
|
|
203
|
+
let i = r;
|
|
204
|
+
S.current.set(i.attachment.id, i.blob), o((e) => [...e, i.attachment]), await k(i);
|
|
183
205
|
});
|
|
184
206
|
}
|
|
185
207
|
}
|
|
186
|
-
}, [
|
|
187
|
-
|
|
188
|
-
}, []),
|
|
189
|
-
let t =
|
|
190
|
-
!t || t.status !== "error" || !n || (
|
|
208
|
+
}, [k]), j = f((e) => {
|
|
209
|
+
w.current.add(e), S.current.delete(e), T.current = Math.max(0, T.current - 1), o((t) => t.filter((t) => t.id !== e));
|
|
210
|
+
}, []), M = f((e) => {
|
|
211
|
+
let t = D.current.find((t) => t.id === e), n = S.current.get(e);
|
|
212
|
+
!t || t.status !== "error" || !n || (w.current.delete(e), O(e, {
|
|
191
213
|
status: "pending",
|
|
192
|
-
error: void 0
|
|
193
|
-
|
|
214
|
+
error: void 0,
|
|
215
|
+
progressNote: void 0
|
|
216
|
+
}), d.current = d.current.then(() => k({
|
|
194
217
|
attachment: {
|
|
195
218
|
...t,
|
|
196
219
|
status: "pending",
|
|
@@ -198,23 +221,23 @@ function C() {
|
|
|
198
221
|
},
|
|
199
222
|
blob: n
|
|
200
223
|
})));
|
|
201
|
-
}, [
|
|
202
|
-
|
|
203
|
-
}, []),
|
|
224
|
+
}, [O, k]), N = f(() => {
|
|
225
|
+
x.current += 1, T.current = 0, D.current.forEach((e) => w.current.add(e.id)), S.current.clear(), o([]);
|
|
226
|
+
}, []), P = s(_, a);
|
|
204
227
|
return {
|
|
205
|
-
attachments:
|
|
206
|
-
isBusy:
|
|
207
|
-
sendBlocker:
|
|
208
|
-
rejection:
|
|
209
|
-
addFiles:
|
|
210
|
-
remove:
|
|
211
|
-
retry:
|
|
212
|
-
clear:
|
|
213
|
-
clearRejection:
|
|
214
|
-
canAddMore:
|
|
228
|
+
attachments: a,
|
|
229
|
+
isBusy: P === "in-flight",
|
|
230
|
+
sendBlocker: P,
|
|
231
|
+
rejection: c,
|
|
232
|
+
addFiles: A,
|
|
233
|
+
remove: j,
|
|
234
|
+
retry: M,
|
|
235
|
+
clear: N,
|
|
236
|
+
clearRejection: f(() => u(null), []),
|
|
237
|
+
canAddMore: T.current < 5
|
|
215
238
|
};
|
|
216
239
|
}
|
|
217
240
|
//#endregion
|
|
218
|
-
export {
|
|
241
|
+
export { w as useAssistantAttachments };
|
|
219
242
|
|
|
220
243
|
//# sourceMappingURL=useAssistantAttachments.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useAssistantAttachments.js","names":[],"sources":["../../src/hooks/useAssistantAttachments.ts"],"sourcesContent":["/**\n * Draft-attachment state for the assistant composer (Workstream 3).\n *\n * Owns the whole lifecycle of a file the user attached but has not sent yet:\n * validate → (images) downscale / (PDF, DOCX, XLSX) extract text → preview →\n * upload to the workspace file library → resolve a presigned URL → ready. Each\n * attachment carries its own status, so one slow or failed upload never blocks\n * the others.\n *\n * Uploads run **sequentially**. `useSaveToFiles` exposes a single shared\n * `isPending`/`progress` pair, so firing several at once would leave that state\n * last-write-wins; a queue also keeps a farmer on a rural connection from having\n * five uploads compete for the same narrow uplink.\n *\n * Anything whose content is already inlined degrades gracefully: a text file,\n * or a PDF/DOCX/XLSX we managed to extract, is marked `ready` even when its\n * upload fails, because losing the upload costs it only its URL. Images, and\n * documents we could NOT read, have nothing to fall back on and are marked\n * failed — and a failed attachment blocks sending (`sendBlocker`) until the user\n * retries or removes it, so a turn can never go out silently missing a file\n * whose chip the user can still see.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { useSaveToFiles } from '@burdenoff/fe-libs/storage';\nimport { graphqlFetch } from '@burdenoff/fe-libs/shared/graphql';\nimport { downscaleImage } from '@/healthybowl/utils/imageDownscale';\nimport { getWorkspaceId } from '@/utils/assistantContext';\nimport {\n AttachmentRejectedError,\n INLINE_IMAGE_MAX_DIM,\n INLINE_IMAGE_QUALITY,\n MAX_ATTACHMENTS,\n MAX_FILE_BYTES,\n MAX_INLINE_CHARS_PER_FILE,\n classifyAttachment,\n detectDocumentFormat,\n getAttachmentSendBlocker,\n truncateForInline,\n validateFile,\n type AssistantAttachment,\n type AttachmentRejection,\n type AttachmentSendBlocker,\n} from '@/utils/assistantAttachments';\nimport { extractDocumentText } from '@/utils/documentExtract';\n\n/** Where assistant attachments land in the workspace file library. */\nconst ATTACHMENT_FOLDER = '/HealthyBowl/AI Assistant/Attachments';\n\nconst DOWNLOAD_URL_QUERY = `\n query HealthyBowlAssistantAttachmentUrl($id: ID!) {\n getFileDownloadUrl(id: $id)\n }\n`;\n\nasync function resolveDownloadUrl(fileId: string, workspaceId: string): Promise<string | null> {\n if (!fileId || !workspaceId) return null;\n try {\n const res = await graphqlFetch<{ getFileDownloadUrl?: string | null }>({\n gateway: 'workspace',\n query: DOWNLOAD_URL_QUERY,\n variables: { id: fileId },\n workspaceToken: true,\n workspaceId,\n suppressGlobalErrorEvent: true,\n });\n return res.data?.getFileDownloadUrl ?? null;\n } catch {\n return null;\n }\n}\n\nlet attachmentSeq = 0;\nfunction nextAttachmentId(): string {\n attachmentSeq += 1;\n return `att-${Date.now()}-${attachmentSeq}`;\n}\n\ninterface PreparedFile {\n attachment: AssistantAttachment;\n /** Bytes to upload — the downscaled JPEG for images, the original otherwise. */\n blob: Blob;\n}\n\nasync function prepareFile(file: File): Promise<PreparedFile> {\n const kind = classifyAttachment(file.type, file.name);\n const base = {\n id: nextAttachmentId(),\n status: 'pending' as const,\n };\n\n if (kind === 'image') {\n // Reuses the pest-scan downscaler: a phone photo goes from several MB to a\n // ~1280px JPEG, which keeps the upload quick on a field connection, plus a\n // second, smaller encode sized to survive the gateway's request-body cap.\n const down = await downscaleImage(file, {\n encodeFallback: false,\n inline: { maxDim: INLINE_IMAGE_MAX_DIM, quality: INLINE_IMAGE_QUALITY },\n });\n\n // The browser could not decode this format (HEIC is the case that happens),\n // so nothing was resized. `validateFile` waved the file through on the\n // promise that it would be — honour the real ceiling now that we know.\n if (!down.downscaled && down.blob.size > MAX_FILE_BYTES) {\n // Reported as a FORMAT problem, not a size one. \"Larger than 10 MB\" would\n // be true but misleading: a 12 MB JPEG is accepted happily — it is the\n // undecodable format that stops us shrinking this one to fit.\n throw new AttachmentRejectedError('unsupported-image');\n }\n\n return {\n attachment: {\n ...base,\n filename: down.filename,\n mimeType: down.mimeType,\n size: down.blob.size,\n kind,\n // Never '': an empty <img src> re-requests the document URL. Undefined\n // degrades to the generic file icon, which is what an undecodable image\n // should look like.\n previewUrl: down.dataUrl || undefined,\n inlineDataUrl: down.inlineDataUrl,\n },\n blob: down.blob,\n };\n }\n\n if (kind === 'text') {\n const raw = await file.text();\n const { text, truncated } = truncateForInline(raw, MAX_INLINE_CHARS_PER_FILE);\n return {\n attachment: {\n ...base,\n filename: file.name,\n mimeType: file.type || 'text/plain',\n size: file.size,\n kind,\n textContent: text,\n textTruncated: truncated,\n },\n blob: file,\n };\n }\n\n // PDF / DOCX / XLSX: open the container here, in the SAME prepare step, so the\n // extracted text joins the text-file inline path and the composer's existing\n // send-gating covers it. `preparingCount` was incremented before this ran and\n // is only decremented once this promise settles, so a slow 50-page PDF holds\n // the send button disabled for exactly as long as it takes — which is the\n // whole reason extraction belongs here and not at send time.\n const format = detectDocumentFormat(file.type, file.name);\n if (format) {\n // Never throws — a scanned, encrypted or corrupt file still becomes an\n // attachment, it just carries the reason instead of the text.\n const extracted = await extractDocumentText(file, format);\n return {\n attachment: {\n ...base,\n filename: file.name,\n mimeType: file.type || 'application/octet-stream',\n size: file.size,\n kind,\n extraction: extracted.extraction,\n textContent: extracted.textContent,\n textTruncated: extracted.textTruncated,\n documentPages: extracted.documentPages,\n },\n blob: file,\n };\n }\n\n return {\n attachment: {\n ...base,\n filename: file.name,\n mimeType: file.type || 'application/octet-stream',\n size: file.size,\n kind,\n },\n blob: file,\n };\n}\n\nexport interface UseAssistantAttachmentsResult {\n attachments: AssistantAttachment[];\n /** True while any attachment is still being prepared or uploaded. */\n isBusy: boolean;\n /**\n * Why the current attachments block sending, or `null` when they do not.\n * Strictly wider than `isBusy`: it also reports the terminal 'failed' state,\n * which is not busy but must still stop a send. See\n * `getAttachmentSendBlocker`.\n */\n sendBlocker: AttachmentSendBlocker | null;\n /** Most recent rejection, for a transient inline message. */\n rejection: AttachmentRejection | null;\n addFiles: (files: FileList | File[] | null | undefined) => void;\n remove: (id: string) => void;\n /** Re-upload a single failed attachment, reusing the bytes already prepared. */\n retry: (id: string) => void;\n clear: () => void;\n clearRejection: () => void;\n canAddMore: boolean;\n}\n\nexport function useAssistantAttachments(): UseAssistantAttachmentsResult {\n const { save } = useSaveToFiles();\n const [attachments, setAttachments] = useState<AssistantAttachment[]>([]);\n const [rejection, setRejection] = useState<AttachmentRejection | null>(null);\n\n // Serialises uploads: each new batch chains onto the tail of this promise.\n const uploadChainRef = useRef<Promise<void>>(Promise.resolve());\n // Files accepted but not yet PREPARED (image downscale / text read). They have\n // no id and no row yet, so nothing else can see them — which is exactly why\n // they need their own counter: without it `isBusy` reads false, the composer\n // lets the user send, and the file lands on the NEXT message instead.\n const [preparingCount, setPreparingCount] = useState(0);\n // Bumped by `clear()`. A queued prepare closure captures the epoch it was\n // enqueued under and bails if it no longer matches, so a file whose draft was\n // already sent can never append itself afterwards.\n const epochRef = useRef(0);\n // Prepared bytes kept by id so a failed upload can be retried WITHOUT asking\n // the user to pick the file again — re-reading it is impossible anyway, the\n // original File handle is gone once the picker closes.\n const blobsRef = useRef<Map<string, Blob>>(new Map());\n // Ids dropped while their upload was in flight — the result is discarded so a\n // removed attachment never reappears as 'ready'.\n const removedIdsRef = useRef<Set<string>>(new Set());\n // Authoritative slot count for validation. `attachments.length` lags: a file\n // is accepted synchronously but only appears once its async prepare (image\n // downscale / text read) resolves, so counting rendered rows would let a\n // multi-file drop overshoot MAX_ATTACHMENTS.\n const countRef = useRef(0);\n const mountedRef = useRef(true);\n useEffect(\n () => () => {\n mountedRef.current = false;\n },\n []\n );\n\n // Render-value mirror, so `clear()` can cancel in-flight uploads without\n // reaching for their ids from inside a state updater (updaters must be pure).\n const attachmentsRef = useRef<AssistantAttachment[]>([]);\n useEffect(() => {\n attachmentsRef.current = attachments;\n }, [attachments]);\n\n const patch = useCallback((id: string, changes: Partial<AssistantAttachment>) => {\n if (!mountedRef.current) return;\n setAttachments((current) =>\n current.map((attachment) => (attachment.id === id ? { ...attachment, ...changes } : attachment))\n );\n }, []);\n\n const upload = useCallback(\n async ({ attachment, blob }: PreparedFile): Promise<void> => {\n if (removedIdsRef.current.has(attachment.id)) return;\n patch(attachment.id, { status: 'uploading' });\n\n try {\n const saved = await save({\n source: {\n kind: 'blob',\n filename: attachment.filename,\n mimeType: attachment.mimeType,\n getBlob: async () => ({\n blob,\n filename: attachment.filename,\n mimeType: attachment.mimeType,\n }),\n },\n folderPath: ATTACHMENT_FOLDER,\n });\n if (removedIdsRef.current.has(attachment.id)) return;\n\n const downloadUrl = saved?.id ? await resolveDownloadUrl(saved.id, getWorkspaceId()) : null;\n if (removedIdsRef.current.has(attachment.id)) return;\n\n patch(attachment.id, {\n status: 'ready',\n fileId: saved?.id,\n downloadUrl: downloadUrl ?? undefined,\n });\n } catch (error) {\n if (removedIdsRef.current.has(attachment.id)) return;\n // Anything whose content is already inlined in the prompt — a text file,\n // or a document we extracted — loses only the URL when the upload fails,\n // so it is still worth sending. An image is dead weight without its\n // bytes, and so is a document we could not read.\n if (attachment.kind === 'text' || Boolean(attachment.textContent)) {\n patch(attachment.id, { status: 'ready' });\n return;\n }\n patch(attachment.id, {\n status: 'error',\n error: error instanceof Error ? error.message : 'Upload failed',\n });\n }\n },\n [patch, save]\n );\n\n const addFiles = useCallback(\n (files: FileList | File[] | null | undefined) => {\n if (!files) return;\n const incoming = Array.from(files);\n if (incoming.length === 0) return;\n\n setRejection(null);\n\n // Take the accepted prefix of the batch: dropping six files at once keeps\n // the first five and reports the overflow, rather than rejecting the drop.\n const accepted: File[] = [];\n for (const file of incoming) {\n const problem = validateFile(file, countRef.current);\n if (problem) {\n setRejection(problem);\n continue;\n }\n accepted.push(file);\n countRef.current += 1;\n }\n if (accepted.length === 0) return;\n\n // Preparation (downscale / text read) is async; each file appends itself\n // as soon as it is prepared, then uploads in turn. Count them as busy NOW\n // rather than when they finish preparing — otherwise send stays live\n // through the whole downscale and the photo silently misses the message it\n // was attached to.\n setPreparingCount((count) => count + accepted.length);\n\n for (const file of accepted) {\n const epoch = epochRef.current;\n uploadChainRef.current = uploadChainRef.current.then(async () => {\n let prepared: PreparedFile | null = null;\n try {\n prepared = await prepareFile(file);\n } catch (error) {\n countRef.current = Math.max(0, countRef.current - 1);\n // A rejection decided during preparation (e.g. an un-downscalable\n // image that is genuinely too big) carries its own reason; anything\n // else really is an unreadable file.\n if (mountedRef.current) {\n setRejection(error instanceof AttachmentRejectedError ? error.reason : 'unreadable');\n }\n }\n if (!mountedRef.current) return;\n setPreparingCount((count) => Math.max(0, count - 1));\n if (!prepared) return;\n // The draft this file belonged to has already been sent or cleared.\n if (epoch !== epochRef.current) {\n countRef.current = Math.max(0, countRef.current - 1);\n return;\n }\n const ready = prepared;\n blobsRef.current.set(ready.attachment.id, ready.blob);\n setAttachments((list) => [...list, ready.attachment]);\n await upload(ready);\n });\n }\n },\n [upload]\n );\n\n const remove = useCallback((id: string) => {\n removedIdsRef.current.add(id);\n blobsRef.current.delete(id);\n countRef.current = Math.max(0, countRef.current - 1);\n setAttachments((current) => current.filter((attachment) => attachment.id !== id));\n }, []);\n\n const retry = useCallback(\n (id: string) => {\n const attachment = attachmentsRef.current.find((candidate) => candidate.id === id);\n const blob = blobsRef.current.get(id);\n if (!attachment || attachment.status !== 'error' || !blob) return;\n\n // A previous `clear()` may have tombstoned this id; un-tombstone it or the\n // retry would upload successfully and then discard its own result.\n removedIdsRef.current.delete(id);\n patch(id, { status: 'pending', error: undefined });\n uploadChainRef.current = uploadChainRef.current.then(() =>\n upload({ attachment: { ...attachment, status: 'pending', error: undefined }, blob })\n );\n },\n [patch, upload]\n );\n\n const clear = useCallback(() => {\n // Invalidate every prepare still in flight: those files belong to the draft\n // being cleared, not to whatever the user types next.\n epochRef.current += 1;\n countRef.current = 0;\n attachmentsRef.current.forEach((attachment) => removedIdsRef.current.add(attachment.id));\n blobsRef.current.clear();\n setAttachments([]);\n }, []);\n\n const sendBlocker = getAttachmentSendBlocker(preparingCount, attachments);\n\n return {\n attachments,\n isBusy: sendBlocker === 'in-flight',\n sendBlocker,\n rejection,\n addFiles,\n remove,\n retry,\n clear,\n clearRejection: useCallback(() => setRejection(null), []),\n // countRef is authoritative — unlike `attachments`, it already counts files\n // that are still being prepared.\n canAddMore: countRef.current < MAX_ATTACHMENTS,\n };\n}\n"],"mappings":";;;;;;;;AA+CA,IAAM,IAAoB,yCAEpB,IAAqB;AAM3B,eAAe,EAAmB,GAAgB,GAA6C;AAC7F,KAAI,CAAC,KAAU,CAAC,EAAa,QAAO;AACpC,KAAI;AASF,UARY,MAAM,EAAqD;GACrE,SAAS;GACT,OAAO;GACP,WAAW,EAAE,IAAI,GAAQ;GACzB,gBAAgB;GAChB;GACA,0BAA0B;GAC3B,CAAC,EACS,MAAM,sBAAsB;SACjC;AACN,SAAO;;;AAIX,IAAI,IAAgB;AACpB,SAAS,IAA2B;AAElC,QADA,KAAiB,GACV,OAAO,KAAK,KAAK,CAAC,GAAG;;AAS9B,eAAe,EAAY,GAAmC;CAC5D,IAAM,IAAO,EAAmB,EAAK,MAAM,EAAK,KAAK,EAC/C,IAAO;EACX,IAAI,GAAkB;EACtB,QAAQ;EACT;AAED,KAAI,MAAS,SAAS;EAIpB,IAAM,IAAO,MAAM,EAAe,GAAM;GACtC,gBAAgB;GAChB,QAAQ;IAAE,QAAA;IAA8B,SAAS;IAAsB;GACxE,CAAC;AAKF,MAAI,CAAC,EAAK,cAAc,EAAK,KAAK,OAAA,SAIhC,OAAM,IAAI,EAAwB,oBAAoB;AAGxD,SAAO;GACL,YAAY;IACV,GAAG;IACH,UAAU,EAAK;IACf,UAAU,EAAK;IACf,MAAM,EAAK,KAAK;IAChB;IAIA,YAAY,EAAK,WAAW,KAAA;IAC5B,eAAe,EAAK;IACrB;GACD,MAAM,EAAK;GACZ;;AAGH,KAAI,MAAS,QAAQ;EAEnB,IAAM,EAAE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GAAW,OAAO,KAAA;GAAW,CAAC,EAClD,EAAe,UAAU,EAAe,QAAQ,WAC9C,EAAO;GAAE,YAAY;IAAE,GAAG;IAAY,QAAQ;IAAW,OAAO,KAAA;IAAW;GAAE;GAAM,CAAC,CACrF;IAEH,CAAC,GAAO,EAAO,CAChB,EAEK,IAAQ,QAAkB;AAO9B,EAJA,EAAS,WAAW,GACpB,EAAS,UAAU,GACnB,EAAe,QAAQ,SAAS,MAAe,EAAc,QAAQ,IAAI,EAAW,GAAG,CAAC,EACxF,EAAS,QAAQ,OAAO,EACxB,EAAe,EAAE,CAAC;IACjB,EAAE,CAAC,EAEA,IAAc,EAAyB,GAAgB,EAAY;AAEzE,QAAO;EACL;EACA,QAAQ,MAAgB;EACxB;EACA;EACA;EACA;EACA;EACA;EACA,gBAAgB,QAAkB,EAAa,KAAK,EAAE,EAAE,CAAC;EAGzD,YAAY,EAAS,UAAA;EACtB"}
|
|
1
|
+
{"version":3,"file":"useAssistantAttachments.js","names":[],"sources":["../../src/hooks/useAssistantAttachments.ts"],"sourcesContent":["/**\n * Draft-attachment state for the assistant composer (Workstream 3).\n *\n * Owns the whole lifecycle of a file the user attached but has not sent yet:\n * validate → (images) downscale / (PDF, DOCX, XLSX) extract text → preview →\n * upload to the workspace file library → resolve a presigned URL → ready. Each\n * attachment carries its own status, so one slow or failed upload never blocks\n * the others.\n *\n * Uploads run **sequentially**. `useSaveToFiles` exposes a single shared\n * `isPending`/`progress` pair, so firing several at once would leave that state\n * last-write-wins; a queue also keeps a farmer on a rural connection from having\n * five uploads compete for the same narrow uplink.\n *\n * Anything whose content is already inlined degrades gracefully: a text file,\n * or a PDF/DOCX/XLSX we managed to extract, is marked `ready` even when its\n * upload fails, because losing the upload costs it only its URL. Images, and\n * documents we could NOT read, have nothing to fall back on and are marked\n * failed — and a failed attachment blocks sending (`sendBlocker`) until the user\n * retries or removes it, so a turn can never go out silently missing a file\n * whose chip the user can still see.\n */\n\nimport { useCallback, useEffect, useRef, useState } from 'react';\nimport { useSaveToFiles } from '@burdenoff/fe-libs/storage';\nimport { graphqlFetch } from '@burdenoff/fe-libs/shared/graphql';\nimport { downscaleImage } from '@/healthybowl/utils/imageDownscale';\nimport { getWorkspaceId } from '@/utils/assistantContext';\nimport {\n AttachmentRejectedError,\n INLINE_IMAGE_MAX_DIM,\n INLINE_IMAGE_QUALITY,\n MAX_ATTACHMENTS,\n MAX_FILE_BYTES,\n MAX_INLINE_CHARS_PER_FILE,\n classifyAttachment,\n detectDocumentFormat,\n getAttachmentSendBlocker,\n truncateForInline,\n validateFile,\n type AssistantAttachment,\n type AttachmentRejection,\n type AttachmentSendBlocker,\n} from '@/utils/assistantAttachments';\nimport { extractDocumentText } from '@/utils/documentExtract';\nimport { useTr } from '@/shared/hooks/useTr';\n\n/** Where assistant attachments land in the workspace file library. */\nconst ATTACHMENT_FOLDER = '/HealthyBowl/AI Assistant/Attachments';\n\nconst DOWNLOAD_URL_QUERY = `\n query HealthyBowlAssistantAttachmentUrl($id: ID!) {\n getFileDownloadUrl(id: $id)\n }\n`;\n\nasync function resolveDownloadUrl(fileId: string, workspaceId: string): Promise<string | null> {\n if (!fileId || !workspaceId) return null;\n try {\n const res = await graphqlFetch<{ getFileDownloadUrl?: string | null }>({\n gateway: 'workspace',\n query: DOWNLOAD_URL_QUERY,\n variables: { id: fileId },\n workspaceToken: true,\n workspaceId,\n suppressGlobalErrorEvent: true,\n });\n return res.data?.getFileDownloadUrl ?? null;\n } catch {\n return null;\n }\n}\n\nlet attachmentSeq = 0;\nfunction nextAttachmentId(): string {\n attachmentSeq += 1;\n return `att-${Date.now()}-${attachmentSeq}`;\n}\n\ninterface PreparedFile {\n attachment: AssistantAttachment;\n /** Bytes to upload — the downscaled JPEG for images, the original otherwise. */\n blob: Blob;\n}\n\nasync function prepareFile(file: File): Promise<PreparedFile> {\n const kind = classifyAttachment(file.type, file.name);\n const base = {\n id: nextAttachmentId(),\n status: 'pending' as const,\n };\n\n if (kind === 'image') {\n // Reuses the pest-scan downscaler: a phone photo goes from several MB to a\n // ~1280px JPEG, which keeps the upload quick on a field connection, plus a\n // second, smaller encode sized to survive the gateway's request-body cap.\n const down = await downscaleImage(file, {\n encodeFallback: false,\n inline: { maxDim: INLINE_IMAGE_MAX_DIM, quality: INLINE_IMAGE_QUALITY },\n });\n\n // The browser could not decode this format (HEIC is the case that happens),\n // so nothing was resized. `validateFile` waved the file through on the\n // promise that it would be — honour the real ceiling now that we know.\n if (!down.downscaled && down.blob.size > MAX_FILE_BYTES) {\n // Reported as a FORMAT problem, not a size one. \"Larger than 10 MB\" would\n // be true but misleading: a 12 MB JPEG is accepted happily — it is the\n // undecodable format that stops us shrinking this one to fit.\n throw new AttachmentRejectedError('unsupported-image');\n }\n\n return {\n attachment: {\n ...base,\n filename: down.filename,\n mimeType: down.mimeType,\n size: down.blob.size,\n kind,\n // Never '': an empty <img src> re-requests the document URL. Undefined\n // degrades to the generic file icon, which is what an undecodable image\n // should look like.\n previewUrl: down.dataUrl || undefined,\n inlineDataUrl: down.inlineDataUrl,\n },\n blob: down.blob,\n };\n }\n\n if (kind === 'text') {\n const raw = await file.text();\n const { text, truncated } = truncateForInline(raw, MAX_INLINE_CHARS_PER_FILE);\n return {\n attachment: {\n ...base,\n filename: file.name,\n mimeType: file.type || 'text/plain',\n size: file.size,\n kind,\n textContent: text,\n textTruncated: truncated,\n },\n blob: file,\n };\n }\n\n // PDF / DOCX / XLSX: open the container here, in the SAME prepare step, so the\n // extracted text joins the text-file inline path and the composer's existing\n // send-gating covers it. `preparingCount` was incremented before this ran and\n // is only decremented once this promise settles, so a slow 50-page PDF holds\n // the send button disabled for exactly as long as it takes — which is the\n // whole reason extraction belongs here and not at send time.\n const format = detectDocumentFormat(file.type, file.name);\n if (format) {\n // Never throws — a scanned, encrypted or corrupt file still becomes an\n // attachment, it just carries the reason instead of the text.\n const extracted = await extractDocumentText(file, format);\n return {\n attachment: {\n ...base,\n filename: file.name,\n mimeType: file.type || 'application/octet-stream',\n size: file.size,\n kind,\n extraction: extracted.extraction,\n textContent: extracted.textContent,\n textTruncated: extracted.textTruncated,\n documentPages: extracted.documentPages,\n },\n blob: file,\n };\n }\n\n return {\n attachment: {\n ...base,\n filename: file.name,\n mimeType: file.type || 'application/octet-stream',\n size: file.size,\n kind,\n },\n blob: file,\n };\n}\n\nexport interface UseAssistantAttachmentsResult {\n attachments: AssistantAttachment[];\n /** True while any attachment is still being prepared or uploaded. */\n isBusy: boolean;\n /**\n * Why the current attachments block sending, or `null` when they do not.\n * Strictly wider than `isBusy`: it also reports the terminal 'failed' state,\n * which is not busy but must still stop a send. See\n * `getAttachmentSendBlocker`.\n */\n sendBlocker: AttachmentSendBlocker | null;\n /** Most recent rejection, for a transient inline message. */\n rejection: AttachmentRejection | null;\n addFiles: (files: FileList | File[] | null | undefined) => void;\n remove: (id: string) => void;\n /** Re-upload a single failed attachment, reusing the bytes already prepared. */\n retry: (id: string) => void;\n clear: () => void;\n clearRejection: () => void;\n canAddMore: boolean;\n}\n\nexport function useAssistantAttachments(): UseAssistantAttachmentsResult {\n const tr = useTr();\n const { save } = useSaveToFiles();\n const [attachments, setAttachments] = useState<AssistantAttachment[]>([]);\n const [rejection, setRejection] = useState<AttachmentRejection | null>(null);\n\n // Serialises uploads: each new batch chains onto the tail of this promise.\n const uploadChainRef = useRef<Promise<void>>(Promise.resolve());\n // Files accepted but not yet PREPARED (image downscale / text read). They have\n // no id and no row yet, so nothing else can see them — which is exactly why\n // they need their own counter: without it `isBusy` reads false, the composer\n // lets the user send, and the file lands on the NEXT message instead.\n const [preparingCount, setPreparingCount] = useState(0);\n // Bumped by `clear()`. A queued prepare closure captures the epoch it was\n // enqueued under and bails if it no longer matches, so a file whose draft was\n // already sent can never append itself afterwards.\n const epochRef = useRef(0);\n // Prepared bytes kept by id so a failed upload can be retried WITHOUT asking\n // the user to pick the file again — re-reading it is impossible anyway, the\n // original File handle is gone once the picker closes.\n const blobsRef = useRef<Map<string, Blob>>(new Map());\n // Ids dropped while their upload was in flight — the result is discarded so a\n // removed attachment never reappears as 'ready'.\n const removedIdsRef = useRef<Set<string>>(new Set());\n // Authoritative slot count for validation. `attachments.length` lags: a file\n // is accepted synchronously but only appears once its async prepare (image\n // downscale / text read) resolves, so counting rendered rows would let a\n // multi-file drop overshoot MAX_ATTACHMENTS.\n const countRef = useRef(0);\n const mountedRef = useRef(true);\n useEffect(\n () => () => {\n mountedRef.current = false;\n },\n []\n );\n\n // Render-value mirror, so `clear()` can cancel in-flight uploads without\n // reaching for their ids from inside a state updater (updaters must be pure).\n const attachmentsRef = useRef<AssistantAttachment[]>([]);\n useEffect(() => {\n attachmentsRef.current = attachments;\n }, [attachments]);\n\n const patch = useCallback((id: string, changes: Partial<AssistantAttachment>) => {\n if (!mountedRef.current) return;\n setAttachments((current) =>\n current.map((attachment) => (attachment.id === id ? { ...attachment, ...changes } : attachment))\n );\n }, []);\n\n const upload = useCallback(\n async ({ attachment, blob }: PreparedFile): Promise<void> => {\n if (removedIdsRef.current.has(attachment.id)) return;\n patch(attachment.id, { status: 'uploading', progressNote: undefined });\n\n try {\n const saved = await save({\n source: {\n kind: 'blob',\n filename: attachment.filename,\n mimeType: attachment.mimeType,\n getBlob: async () => ({\n blob,\n filename: attachment.filename,\n mimeType: attachment.mimeType,\n }),\n },\n folderPath: ATTACHMENT_FOLDER,\n // A cold wspace-files-svc container needs ~51s to boot against a 15s\n // gateway budget, so fe-libs waits it out. Say so on the chip — this is\n // still `uploading`, not an error, and a silent minute reads as a hang.\n onRetry: (notice) => {\n if (removedIdsRef.current.has(attachment.id)) return;\n patch(attachment.id, {\n progressNote:\n notice.kind === 'cold-start'\n ? tr(\n 'healthybowl.assistant.attachments.waking',\n 'File service is starting up — retry {{attempt}} of {{max}}',\n { attempt: String(notice.attempt), max: String(notice.maxAttempts) }\n )\n : tr('healthybowl.assistant.attachments.retrying', 'Retrying {{attempt}} of {{max}}', {\n attempt: String(notice.attempt),\n max: String(notice.maxAttempts),\n }),\n });\n },\n });\n if (removedIdsRef.current.has(attachment.id)) return;\n\n const downloadUrl = saved?.id ? await resolveDownloadUrl(saved.id, getWorkspaceId()) : null;\n if (removedIdsRef.current.has(attachment.id)) return;\n\n patch(attachment.id, {\n status: 'ready',\n fileId: saved?.id,\n downloadUrl: downloadUrl ?? undefined,\n progressNote: undefined,\n });\n } catch (error) {\n if (removedIdsRef.current.has(attachment.id)) return;\n // Anything whose content is already inlined in the prompt — a text file,\n // or a document we extracted — loses only the URL when the upload fails,\n // so it is still worth sending. An image is dead weight without its\n // bytes, and so is a document we could not read.\n if (attachment.kind === 'text' || Boolean(attachment.textContent)) {\n patch(attachment.id, { status: 'ready', progressNote: undefined });\n return;\n }\n // The retry note must not outlive the attempt: once this has failed the chip\n // shows the real reason, never \"still retrying\".\n patch(attachment.id, {\n status: 'error',\n error: error instanceof Error ? error.message : 'Upload failed',\n progressNote: undefined,\n });\n }\n },\n [patch, save, tr]\n );\n\n const addFiles = useCallback(\n (files: FileList | File[] | null | undefined) => {\n if (!files) return;\n const incoming = Array.from(files);\n if (incoming.length === 0) return;\n\n setRejection(null);\n\n // Take the accepted prefix of the batch: dropping six files at once keeps\n // the first five and reports the overflow, rather than rejecting the drop.\n const accepted: File[] = [];\n for (const file of incoming) {\n const problem = validateFile(file, countRef.current);\n if (problem) {\n setRejection(problem);\n continue;\n }\n accepted.push(file);\n countRef.current += 1;\n }\n if (accepted.length === 0) return;\n\n // Preparation (downscale / text read) is async; each file appends itself\n // as soon as it is prepared, then uploads in turn. Count them as busy NOW\n // rather than when they finish preparing — otherwise send stays live\n // through the whole downscale and the photo silently misses the message it\n // was attached to.\n setPreparingCount((count) => count + accepted.length);\n\n for (const file of accepted) {\n const epoch = epochRef.current;\n uploadChainRef.current = uploadChainRef.current.then(async () => {\n let prepared: PreparedFile | null = null;\n try {\n prepared = await prepareFile(file);\n } catch (error) {\n countRef.current = Math.max(0, countRef.current - 1);\n // A rejection decided during preparation (e.g. an un-downscalable\n // image that is genuinely too big) carries its own reason; anything\n // else really is an unreadable file.\n if (mountedRef.current) {\n setRejection(error instanceof AttachmentRejectedError ? error.reason : 'unreadable');\n }\n }\n if (!mountedRef.current) return;\n setPreparingCount((count) => Math.max(0, count - 1));\n if (!prepared) return;\n // The draft this file belonged to has already been sent or cleared.\n if (epoch !== epochRef.current) {\n countRef.current = Math.max(0, countRef.current - 1);\n return;\n }\n const ready = prepared;\n blobsRef.current.set(ready.attachment.id, ready.blob);\n setAttachments((list) => [...list, ready.attachment]);\n await upload(ready);\n });\n }\n },\n [upload]\n );\n\n const remove = useCallback((id: string) => {\n removedIdsRef.current.add(id);\n blobsRef.current.delete(id);\n countRef.current = Math.max(0, countRef.current - 1);\n setAttachments((current) => current.filter((attachment) => attachment.id !== id));\n }, []);\n\n const retry = useCallback(\n (id: string) => {\n const attachment = attachmentsRef.current.find((candidate) => candidate.id === id);\n const blob = blobsRef.current.get(id);\n if (!attachment || attachment.status !== 'error' || !blob) return;\n\n // A previous `clear()` may have tombstoned this id; un-tombstone it or the\n // retry would upload successfully and then discard its own result.\n removedIdsRef.current.delete(id);\n patch(id, { status: 'pending', error: undefined, progressNote: undefined });\n uploadChainRef.current = uploadChainRef.current.then(() =>\n upload({ attachment: { ...attachment, status: 'pending', error: undefined }, blob })\n );\n },\n [patch, upload]\n );\n\n const clear = useCallback(() => {\n // Invalidate every prepare still in flight: those files belong to the draft\n // being cleared, not to whatever the user types next.\n epochRef.current += 1;\n countRef.current = 0;\n attachmentsRef.current.forEach((attachment) => removedIdsRef.current.add(attachment.id));\n blobsRef.current.clear();\n setAttachments([]);\n }, []);\n\n const sendBlocker = getAttachmentSendBlocker(preparingCount, attachments);\n\n return {\n attachments,\n isBusy: sendBlocker === 'in-flight',\n sendBlocker,\n rejection,\n addFiles,\n remove,\n retry,\n clear,\n clearRejection: useCallback(() => setRejection(null), []),\n // countRef is authoritative — unlike `attachments`, it already counts files\n // that are still being prepared.\n canAddMore: countRef.current < MAX_ATTACHMENTS,\n };\n}\n"],"mappings":";;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AS,QAAQ,IAAI,EAAG;AACjC,GAAC,KAAc,EAAW,WAAW,WAAW,CAAC,MAIrD,EAAc,QAAQ,OAAO,EAAG,EAChC,EAAM,GAAI;GAAE,QAAQ;GAAW,OAAO,KAAA;GAAW,cAAc,KAAA;GAAW,CAAC,EAC3E,EAAe,UAAU,EAAe,QAAQ,WAC9C,EAAO;GAAE,YAAY;IAAE,GAAG;IAAY,QAAQ;IAAW,OAAO,KAAA;IAAW;GAAE;GAAM,CAAC,CACrF;IAEH,CAAC,GAAO,EAAO,CAChB,EAEK,IAAQ,QAAkB;AAO9B,EAJA,EAAS,WAAW,GACpB,EAAS,UAAU,GACnB,EAAe,QAAQ,SAAS,MAAe,EAAc,QAAQ,IAAI,EAAW,GAAG,CAAC,EACxF,EAAS,QAAQ,OAAO,EACxB,EAAe,EAAE,CAAC;IACjB,EAAE,CAAC,EAEA,IAAc,EAAyB,GAAgB,EAAY;AAEzE,QAAO;EACL;EACA,QAAQ,MAAgB;EACxB;EACA;EACA;EACA;EACA;EACA;EACA,gBAAgB,QAAkB,EAAa,KAAK,EAAE,EAAE,CAAC;EAGzD,YAAY,EAAS,UAAA;EACtB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assistantAttachments.js","names":[],"sources":["../../src/utils/assistantAttachments.ts"],"sourcesContent":["/**\n * Attachment model for the assistant composer (Workstream 3 of the AI Assistant\n * V2 multimodal effort) — pure logic, no React, so it is unit-testable.\n *\n * ## How an attachment reaches the model today\n *\n * The sandbox transport carries exactly one user-authored field per turn:\n * a `prompt` **string** (`POST /sessions/:id/prompt-async`). The in-sandbox\n * agent's message parts are `text | tool` only. So there is no native file or\n * image part to put bytes into, and adding one means changing the out-of-repo\n * `ai-assistant-*` bridge image — that is Workstream 4, and it is not shipped.\n *\n * What this module does instead is the honest L1: every attachment is uploaded\n * to the workspace file library (wspace-files-svc) so it durably exists and has\n * a URL, and a compact, clearly-delimited block describing the attachments is\n * appended to the outgoing prompt. For **text-like** files the actual content is\n * inlined (bounded), which makes them fully usable by the model right now. For\n * images and binaries only the metadata and a presigned URL go across, and the\n * block says plainly that the bytes were not inlined — so the assistant asks\n * rather than hallucinating a description of a photo it cannot see.\n *\n * Whether the sandbox can egress to the presigned URL is **not verified** — the\n * wording therefore makes fetching conditional (\"if you can fetch URLs\") rather\n * than promising it. Vision on the image itself lands with Workstream 4.\n */\n\n/** Hard cap on attachments per message — keeps the prompt block bounded. */\nimport { MAX_REQUEST_BODY_BYTES } from './gatewayLimits';\nimport {\n formatPageRanges,\n isMostlyImagePages,\n truncatePagesForInline,\n type DocumentExtraction,\n type DocumentFormat,\n} from './documentText';\n\nexport const MAX_ATTACHMENTS = 5;\n\n/** Per-file ceiling before downscaling (images) / rejection (everything else). */\nexport const MAX_FILE_BYTES = 10 * 1024 * 1024;\n\n/** Per-file inline budget for text-like content, in characters. */\nexport const MAX_INLINE_CHARS_PER_FILE = 8_000;\n\n/** Total inline budget across all attachments in one turn. */\nexport const MAX_INLINE_CHARS_TOTAL = 20_000;\n\nexport type AssistantAttachmentKind = 'image' | 'text' | 'document';\n\nexport type AssistantAttachmentStatus = 'pending' | 'uploading' | 'ready' | 'error';\n\nexport type AttachmentRejection = 'too-many' | 'too-large' | 'empty' | 'unreadable' | 'unsupported-image';\n\n/**\n * Thrown while PREPARING a file (after it passed `validateFile`) to reject it\n * with a specific reason rather than the generic 'unreadable'.\n *\n * `validateFile` runs before the bytes have been touched, so it cannot know\n * whether an oversized image will actually survive the downscale — that verdict\n * only exists once the browser has tried to rasterise it.\n */\nexport class AttachmentRejectedError extends Error {\n constructor(readonly reason: AttachmentRejection) {\n super(reason);\n this.name = 'AttachmentRejectedError';\n }\n}\n\nexport interface AssistantAttachment {\n /** Client-side id; stable for the lifetime of the draft + the sent message. */\n id: string;\n filename: string;\n mimeType: string;\n /** Size of the bytes we actually kept (post-downscale for images). */\n size: number;\n kind: AssistantAttachmentKind;\n status: AssistantAttachmentStatus;\n /** Object/data URL for the composer thumbnail. Images only; never persisted. */\n previewUrl?: string;\n /**\n * A smaller `data:` URL of the same image, sized for the request body rather\n * than for the eye. Preferred over `previewUrl` when building the multimodal\n * parts; see `MAX_TURN_BODY_BYTES`. Images only; never persisted.\n */\n inlineDataUrl?: string;\n /** wspace-files-svc id, once the upload lands. */\n fileId?: string;\n /** Short-lived presigned URL, resolved at send time. */\n downloadUrl?: string;\n /**\n * Inlined content for this attachment, already truncated to\n * `MAX_INLINE_CHARS_PER_FILE`. Text files carry the file itself; PDF/DOCX/XLSX\n * carry whatever `extractDocumentText` pulled out of them (BOFF-6291).\n */\n textContent?: string;\n /** True when `textContent` is a prefix of a longer file. */\n textTruncated?: boolean;\n /**\n * Outcome of the client-side document extraction. Present on every `document`\n * we ATTEMPTED to read — including the failures, which is the point: a scanned\n * or encrypted PDF has to reach the model as a sentence rather than as\n * nothing. Absent means no extractor exists for the type.\n */\n extraction?: DocumentExtraction;\n /**\n * Per-page text for a PDF, kept so the SHARED inline budget can also cut on a\n * page boundary rather than mid-sentence. Already trimmed to the per-file\n * budget at prepare time, so this never holds a whole 50-page document.\n * Draft-only; `toMessageAttachment` never carries it to storage.\n */\n documentPages?: string[];\n /** Human-readable failure reason when `status === 'error'`. */\n error?: string;\n}\n\n/**\n * The slice of an attachment that is safe to keep on a sent message.\n *\n * Conversations are persisted to (profile-scoped) localStorage by the assistant\n * store, so the heavy fields — the base64 `previewUrl` and the inlined\n * `textContent` — MUST NOT travel here: five 1280px JPEG data URLs would exhaust\n * the ~5 MB quota on their own and take the whole conversation history down with\n * them. The bubble re-resolves a thumbnail from `fileId` on demand instead, the\n * same way the pest-scan list does.\n */\nexport interface AssistantMessageAttachment {\n id: string;\n filename: string;\n mimeType: string;\n size: number;\n kind: AssistantAttachmentKind;\n fileId?: string;\n}\n\nexport function toMessageAttachment(attachment: AssistantAttachment): AssistantMessageAttachment {\n return {\n id: attachment.id,\n filename: attachment.filename,\n mimeType: attachment.mimeType,\n size: attachment.size,\n kind: attachment.kind,\n fileId: attachment.fileId,\n };\n}\n\n/**\n * Extensions we treat as text even when the browser reports a useless MIME type\n * (`application/octet-stream` is common for `.log`, `.yml`, `.env` on Windows).\n */\nconst TEXT_EXTENSIONS = new Set([\n 'txt',\n 'md',\n 'markdown',\n 'csv',\n 'tsv',\n 'json',\n 'yaml',\n 'yml',\n 'xml',\n 'log',\n 'sql',\n 'html',\n 'css',\n 'js',\n 'ts',\n 'tsx',\n 'jsx',\n 'py',\n 'sh',\n 'ini',\n 'toml',\n 'conf',\n]);\n\nexport function getExtension(filename: string): string {\n const dot = filename.lastIndexOf('.');\n return dot >= 0 ? filename.slice(dot + 1).toLowerCase() : '';\n}\n\nexport function classifyAttachment(mimeType: string, filename: string): AssistantAttachmentKind {\n if (mimeType.startsWith('image/')) return 'image';\n if (\n mimeType.startsWith('text/') ||\n mimeType === 'application/json' ||\n mimeType === 'application/xml' ||\n mimeType === 'application/x-yaml' ||\n TEXT_EXTENSIONS.has(getExtension(filename))\n ) {\n return 'text';\n }\n return 'document';\n}\n\n/**\n * Document formats we can turn into text in the browser (BOFF-6291).\n *\n * Anything else stays a `document` with no extraction, and the prompt block\n * says so — the honest fallback that used to be the ONLY behaviour.\n */\nexport type { DocumentFormat } from './documentText';\n\nconst DOCUMENT_MIME_TYPES: Record<string, DocumentFormat> = {\n 'application/pdf': 'pdf',\n 'application/x-pdf': 'pdf',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',\n};\n\nconst DOCUMENT_EXTENSIONS: Record<string, DocumentFormat> = {\n pdf: 'pdf',\n docx: 'docx',\n xlsx: 'xlsx',\n};\n\n/**\n * Which extractor (if any) can read this file.\n *\n * MIME first, extension second — same order as `classifyAttachment`, and for\n * the same reason: Windows reports `application/octet-stream` for plenty of\n * files whose extension is perfectly informative.\n */\nexport function detectDocumentFormat(mimeType: string, filename: string): DocumentFormat | null {\n return DOCUMENT_MIME_TYPES[mimeType.toLowerCase()] ?? DOCUMENT_EXTENSIONS[getExtension(filename)] ?? null;\n}\n\n/**\n * The composer's `<input accept>` — DERIVED from what we can actually read.\n *\n * It used to be a hand-written list (`…,.pdf,.csv,.json,.md,.txt,.xlsx,.docx`)\n * that invited exactly the files the model could not see: a farmer picked a\n * soil-test PDF because the picker offered it, and the assistant then asked\n * them to paste it as text. Building the list from `TEXT_EXTENSIONS` and\n * `DOCUMENT_EXTENSIONS` makes that class of mismatch a compile-time\n * impossibility rather than a thing to remember.\n */\nexport const ATTACHMENT_ACCEPT = [\n 'image/*',\n 'text/*',\n ...[...TEXT_EXTENSIONS].map((extension) => `.${extension}`),\n ...Object.keys(DOCUMENT_EXTENSIONS).map((extension) => `.${extension}`),\n].join(',');\n\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Is there attachment work in flight that must block sending?\n *\n * `preparingCount` counts files the user has ALREADY dropped/picked but whose\n * image-downscale or text-read has not resolved yet. Those files have no id and\n * no row in `attachments`, so a check that looked only at `attachments` reported\n * \"idle\" during the whole preparation window — the composer stayed sendable, the\n * turn went out without the photo, and the photo then attached itself to the\n * user's NEXT message. Both halves must be counted.\n */\nexport function hasAttachmentWorkInFlight(preparingCount: number, attachments: AssistantAttachment[]): boolean {\n return (\n preparingCount > 0 ||\n attachments.some((attachment) => attachment.status === 'pending' || attachment.status === 'uploading')\n );\n}\n\n/**\n * The attachments a send would ACTUALLY carry to the model.\n *\n * This is the single definition of \"sendable\" — `buildAttachmentPromptBlock`,\n * `buildPromptParts`, `countInlineImageCandidates` and the composer's send\n * handler all route through it, so the set the user is shown and the set the\n * model receives cannot drift apart by one of them being updated and the others\n * not.\n *\n * `status` is the whole test, and that is deliberate rather than lazy: an\n * attachment whose content is already inlined does not need its upload to have\n * worked, so `useAssistantAttachments` marks a text file — and, since\n * BOFF-6291, a document whose text WAS extracted — `ready` even when the upload\n * failed. Such a file is sendable and does not block: its contents travel in\n * the prompt block, and all it lost is the URL. Only attachments with nothing\n * left to send (an image, or a document that could not be read) reach 'error',\n * and those are exactly the ones worth stopping a turn for.\n */\nexport function getSendableAttachments(attachments: AssistantAttachment[]): AssistantAttachment[] {\n return attachments.filter((attachment) => attachment.status === 'ready');\n}\n\n/** Why a draft cannot be sent yet, as far as its attachments are concerned. */\nexport type AttachmentSendBlocker = 'in-flight' | 'failed';\n\n/**\n * Whether the attachments block sending, and why — `null` when they do not.\n *\n * Two distinct reasons, deliberately not collapsed into one boolean:\n *\n * - `'in-flight'` is momentary and resolves itself; the composer shows a\n * spinner and the user just waits.\n * - `'failed'` never resolves on its own. It is the case this function was\n * added for: a failed attachment is omitted from the outgoing turn by\n * `getSendableAttachments`, but send used to stay enabled as long as there\n * was message text, and `clear()` then wiped the failed chip along with the\n * draft. So the user watched their photo's chip vanish into a sent message\n * that never contained it, and the assistant answered a question about an\n * image it was never given. Blocking is the honest response: the chip offers\n * both retry and remove, so the user picks whether the file matters, and\n * whichever they pick the UI and the model end up agreeing.\n *\n * In-flight is reported first: while an upload is still running the failure is\n * not yet final, and \"wait\" is better advice than \"retry or remove\".\n *\n * Nothing here needs to special-case text files or extracted documents: they\n * never reach 'error' in the first place (see `getSendableAttachments`), so a\n * soil-test PDF the browser read but the file library refused still sends, with\n * its text, and never blocks.\n */\nexport function getAttachmentSendBlocker(\n preparingCount: number,\n attachments: AssistantAttachment[]\n): AttachmentSendBlocker | null {\n if (hasAttachmentWorkInFlight(preparingCount, attachments)) return 'in-flight';\n if (attachments.some((attachment) => attachment.status === 'error')) return 'failed';\n return null;\n}\n\n/**\n * Gate a candidate file. Images over the ceiling are still accepted — the\n * composer downscales them before upload, so a 12 MB phone photo is fine while\n * a 12 MB PDF is not.\n *\n * That exemption is a PROMISE, not a fact: it holds only if the browser can\n * actually rasterise the image. When it cannot (HEIC), `prepareFile` re-applies\n * this ceiling to the original bytes and rejects there instead.\n */\nexport function validateFile(file: File, currentCount: number): AttachmentRejection | null {\n if (currentCount >= MAX_ATTACHMENTS) return 'too-many';\n if (file.size === 0) return 'empty';\n if (file.size > MAX_FILE_BYTES && !file.type.startsWith('image/')) return 'too-large';\n return null;\n}\n\n/**\n * Truncate on a line boundary where possible, so an inlined CSV/JSON prefix ends\n * at a row rather than mid-token (which reads as corrupt data to the model).\n */\nexport function truncateForInline(content: string, limit: number): { text: string; truncated: boolean } {\n if (content.length <= limit) return { text: content, truncated: false };\n const head = content.slice(0, limit);\n const lastNewline = head.lastIndexOf('\\n');\n return { text: lastNewline > limit * 0.5 ? head.slice(0, lastNewline) : head, truncated: true };\n}\n\n/** Indented fenced block holding an attachment's inlined content. */\nfunction fencedContent(content: string): string[] {\n return [' ```', ...content.split('\\n').map((line) => ` ${line}`), ' ```'];\n}\n\n/**\n * The pages whose text is actually in front of the model.\n *\n * `pageNumbers` is the truth when the extractor produced it. `pagesIncluded` is\n * the older, coarser field — how FAR into the document we got — and is only a\n * fallback, because on a document with image pages the two differ and reporting\n * the coarser one is what lets a 40-page certificate with 3 readable pages\n * describe itself as \"40 pages\".\n */\nfunction pagesActuallyRead(extraction: DocumentExtraction | undefined): number[] {\n if (extraction?.pageNumbers?.length) return extraction.pageNumbers;\n if (extraction?.pagesIncluded) return Array.from({ length: extraction.pagesIncluded }, (_, index) => index + 1);\n return [];\n}\n\n/**\n * The parenthetical after \"Extracted text\" — what the model is looking at, and\n * what it is NOT.\n *\n * Deliberately the same shape as the text path's \"first N characters of M;\n * truncated\", because a partial document presented as whole is the single most\n * expensive way this feature can fail: the assistant reads eight thousand\n * characters of a forty-page organic-certification audit and tells the farmer\n * it is compliant.\n *\n * The page fact counts PAGES READ, never pages processed. \"40 pages\" is only\n * ever emitted when all forty are genuinely below.\n */\nfunction extractionScope(attachment: AssistantAttachment): string {\n const extraction = attachment.extraction;\n const facts: string[] = [];\n\n if (extraction?.pageCount) {\n const read = pagesActuallyRead(extraction);\n if (read.length >= extraction.pageCount) {\n facts.push(`${extraction.pageCount} page${extraction.pageCount === 1 ? '' : 's'}`);\n } else if (read.length === 1) {\n facts.push(`page ${read[0]} of ${extraction.pageCount}`);\n } else {\n facts.push(`pages ${formatPageRanges(read)} of ${extraction.pageCount}`);\n }\n }\n if (extraction?.sheetNames?.length) {\n facts.push(`sheets: ${extraction.sheetNames.join(', ')}`);\n }\n if (attachment.textTruncated && attachment.textContent) {\n const total = extraction?.sourceChars;\n facts.push(\n total && total > attachment.textContent.length\n ? `first ${attachment.textContent.length} characters of ${total}; truncated`\n : `first ${attachment.textContent.length} characters; truncated`\n );\n }\n\n return facts.length > 0 ? ` (${facts.join('; ')})` : '';\n}\n\n/**\n * The one sentence every \"you have not seen this\" branch ends on. Kept as a\n * constant so no branch can be added without it.\n */\nconst DO_NOT_GUESS = ' Do NOT guess at, summarise or characterise its contents — you have not seen them.';\n\n/** Closing instruction shared by every \"we could not read this\" branch. */\nconst NO_TEXT_ADVICE = [\n ' Fetch the URL above if you can; otherwise ask the user to paste the relevant section as text.',\n DO_NOT_GUESS,\n];\n\n/**\n * Name the pages that were NOT read, so a document is never presented as whole.\n *\n * Two ways a page goes unread, and the model needs both: it had no text layer\n * (an image page), or it fell outside what we processed — the 100-page scan cap\n * or the inline budget.\n */\nfunction unreadPageDisclosure(attachment: AssistantAttachment): string[] {\n const extraction = attachment.extraction;\n if (!extraction?.pageCount) return [];\n\n const read = new Set(pagesActuallyRead(extraction));\n const known = new Set(extraction.imagePages ?? []);\n const imagePages = [...known].filter((page) => !read.has(page)).sort((left, right) => left - right);\n const lines: string[] = [];\n\n if (imagePages.length > 0) {\n const label = imagePages.length === 1 ? `Page ${imagePages[0]}` : `Pages ${formatPageRanges(imagePages)}`;\n lines.push(\n ` ${label} of this document contain no extractable text — they are images.`,\n ' Nothing about those pages is available to you.'\n );\n }\n\n const notProcessed: number[] = [];\n for (let page = 1; page <= extraction.pageCount; page += 1) {\n if (!read.has(page) && !known.has(page)) notProcessed.push(page);\n }\n if (notProcessed.length > 0) {\n const label = notProcessed.length === 1 ? `Page ${notProcessed[0]}` : `Pages ${formatPageRanges(notProcessed)}`;\n lines.push(` ${label} of this document ${notProcessed.length === 1 ? 'was' : 'were'} not read at all.`);\n }\n\n if (lines.length > 0) lines.push(DO_NOT_GUESS);\n return lines;\n}\n\n/**\n * What a PDF/DOCX/XLSX attachment says to the model.\n *\n * Every branch is a positive statement. The one thing this must never do is\n * emit an attachment header with nothing after it, because a file that is\n * merely *listed* reads to the model as a file it may reason about.\n */\nfunction describeDocument(attachment: AssistantAttachment): string[] {\n const extraction = attachment.extraction;\n\n // No extractor ran at all (.zip, .pptx, a legacy .doc). Unchanged behaviour.\n if (!extraction || extraction.status === 'unsupported') {\n return [\n ' Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user',\n ' to paste the relevant section as text.',\n ];\n }\n\n if (extraction.status === 'no-text') {\n // A PDF with no text layer is a scan. A .docx or .xlsx with no text is\n // simply empty (or holds only images and charts) — saying \"scanned\" there\n // would be a confident, checkable falsehood.\n if (extraction.format === 'docx' || extraction.format === 'xlsx') {\n return [\n ' NO TEXT AVAILABLE — this document holds no readable text; it is either empty or contains only',\n ' images, charts or drawings, none of which carry text. No text could be extracted.',\n ...NO_TEXT_ADVICE,\n ];\n }\n const scanned =\n extraction.pagesScanned && extraction.pageCount && extraction.pagesScanned < extraction.pageCount\n ? ` (the first ${extraction.pagesScanned} of ${extraction.pageCount} pages were checked)`\n : '';\n return [\n ` NO TEXT AVAILABLE — this document appears to be scanned images; no text could be extracted${scanned}.`,\n ' There is no text layer to read, so nothing about its contents is available to you.',\n ...NO_TEXT_ADVICE,\n ];\n }\n\n if (extraction.status === 'encrypted') {\n return [\n ' NO TEXT AVAILABLE — this document is encrypted or password-protected; it could not be opened',\n ' and no text could be extracted.',\n ...NO_TEXT_ADVICE,\n ];\n }\n\n if (extraction.status === 'corrupt') {\n const detail = extraction.detail ? ` (${extraction.detail})` : '';\n return [\n ` NO TEXT AVAILABLE — this file could not be read${detail}; no text could be extracted.`,\n ...NO_TEXT_ADVICE,\n ];\n }\n\n // status === 'ok' but the shared inline budget went to earlier attachments.\n if (!attachment.textContent) {\n return [\n ' Text WAS extracted from this document but is omitted because this turn ran out of inline budget,',\n ' not because it is unavailable. Ask the user which part matters so they can re-send just that',\n ' section, or fetch the URL above if you can.',\n DO_NOT_GUESS,\n ];\n }\n\n // Mostly images: a text layer exists, but on so few pages that presenting the\n // fragment as \"the document\" is the same falsehood as reading a scan. The\n // fragment is still handed over — throwing away three real pages of audit\n // findings would be its own kind of dishonesty — but the header refuses on\n // the document's behalf, so the model cannot treat it as read.\n //\n // Gated on `textPageCount` being PRESENT, never defaulted: an extraction that\n // predates the density pass knows nothing about image pages, and treating\n // \"unknown\" as \"zero text pages\" would refuse a document we read perfectly.\n const scanned = extraction.pagesScanned ?? extraction.pageCount ?? 0;\n const textPages = extraction.textPageCount;\n if (extraction.pageCount && textPages !== undefined && isMostlyImagePages(textPages, scanned)) {\n const imageCount = scanned - textPages;\n return [\n ` NOT READ — this document is mostly images. Only ${textPages} of its ${extraction.pageCount} page${\n extraction.pageCount === 1 ? '' : 's'\n } carr${textPages === 1 ? 'ies' : 'y'} a text layer;`,\n ` the other ${imageCount} contain no extractable text at all. Treat this as a document you have NOT`,\n ' read: the fragment below is the whole of what was available, not a summary of the document.',\n ...unreadPageDisclosure(attachment),\n ` The only extractable text${extractionScope(attachment)}:`,\n ...fencedContent(attachment.textContent),\n ];\n }\n\n return [\n ` Extracted text${extractionScope(attachment)}:`,\n ...fencedContent(attachment.textContent),\n ...unreadPageDisclosure(attachment),\n ];\n}\n\nfunction describeAttachment(\n attachment: AssistantAttachment,\n index: number,\n demotedImageIds: ReadonlySet<string> = EMPTY_IDS\n): string {\n const lines = [`[${index + 1}] ${attachment.filename} — ${attachment.mimeType}, ${formatBytes(attachment.size)}`];\n\n if (attachment.downloadUrl) {\n lines.push(` URL: ${attachment.downloadUrl}`);\n }\n\n if (attachment.kind === 'text' && attachment.textContent) {\n lines.push(\n attachment.textTruncated\n ? ` Contents (first ${attachment.textContent.length} characters of ${formatBytes(attachment.size)}; truncated):`\n : ' Contents:',\n ...fencedContent(attachment.textContent)\n );\n } else if (attachment.kind === 'document') {\n lines.push(...describeDocument(attachment));\n } else if (attachment.kind === 'image') {\n if (demotedImageIds.has(attachment.id)) {\n // This photo COULD have travelled as pixels and does not, because the\n // turn would otherwise exceed the gateway's body cap. That decision is\n // invisible unless it is said, and an answer written as if the model had\n // looked at a photo it never received is the worst outcome here.\n lines.push(\n ' NOT VIEWABLE IN THIS MESSAGE — this image did not fit the request-size budget, so only its URL',\n ' travelled; its pixels are NOT attached. Fetch the URL above if you can; otherwise ask the user',\n ' to describe it.',\n DO_NOT_GUESS\n );\n } else {\n // Deliberately regime-neutral wording. This same block is sent whether or\n // not the bridge understands `parts`, so it must not assert either that the\n // model CAN see the image (it would then invent a description on the old\n // bridge) or that it CANNOT (it would then refuse to look on the new one).\n lines.push(\n ' If this image is attached to the message as an image you can view, answer from what you see in it.',\n ' If you cannot view attached images, say so plainly and ask the user to describe it — never guess.'\n );\n }\n } else if (attachment.kind === 'text') {\n // A text file with no `textContent` did not lose its type — it lost its slot\n // in the shared inline budget. Calling it \"binary\" here had the assistant ask\n // the farmer to paste text it already knew was text.\n lines.push(\n ' Text file — contents omitted because this turn ran out of inline budget, not because they are',\n ' unavailable. Fetch the URL above if you can; otherwise ask the user which part matters so they',\n ' can re-send just that section.'\n );\n } else {\n lines.push(\n ' Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user',\n ' to paste the relevant section as text.'\n );\n }\n\n return lines.join('\\n');\n}\n\nconst EMPTY_IDS: ReadonlySet<string> = new Set<string>();\n\n/**\n * Spend the shared inline budget.\n *\n * ## Order: verified capabilities first, the new one last\n *\n * Attachments are still served in the order the user picked them, but in TWO\n * passes — text files, then extracted document text. Both of the other two ways\n * an attachment reaches the model (a photo's pixels, a `.csv`'s contents) work\n * in production today; BOFF-6291's extracted document text is new. So when they\n * cannot all fit, the new one yields. A single in-order pass let a dense PDF\n * picked first take 8,000 characters off the `.csv` behind it, which is a\n * regression in a shipped path paid for by a feature nobody had yet.\n *\n * ## Two ceilings, both of which have to hold HERE\n *\n * - `MAX_INLINE_CHARS_PER_FILE`. It used to be applied only by the extractor,\n * and this pass then re-ran the page fit against the whole 20,000-character\n * TOTAL — so a PDF whose page 1 was 30,000 characters came out of prepare at\n * 8,000, went back up to 20,000 here, and the `.csv` attached beside it got\n * nothing at all. The clamp below is the invariant; the extractor storing\n * only the already-fitted pages (`FittedPages.pages`) is its belt.\n * - `documentLimit` — how much document text the request BODY can afford once\n * the images have been paid for. See `fitInlineBudget`.\n */\nfunction applyInlineBudget(usable: AssistantAttachment[], documentLimit: number): AssistantAttachment[] {\n let remaining = MAX_INLINE_CHARS_TOTAL;\n let documentRemaining = documentLimit;\n const budgeted: AssistantAttachment[] = [...usable];\n\n const spend = (attachment: AssistantAttachment): AssistantAttachment => {\n const isDocument = Boolean(attachment.extraction);\n const limit = Math.min(\n remaining,\n MAX_INLINE_CHARS_PER_FILE,\n isDocument ? documentRemaining : Number.POSITIVE_INFINITY\n );\n if (limit <= 0) {\n return { ...attachment, textContent: undefined, textTruncated: true };\n }\n\n // A PDF still knows its page boundaries here, so the shared budget cuts on\n // one too rather than undoing the page-aligned trim done at prepare time.\n if (attachment.documentPages?.length) {\n const fitted = truncatePagesForInline(attachment.documentPages, limit);\n if (fitted.text === '') {\n return { ...attachment, textContent: undefined, textTruncated: true };\n }\n remaining -= fitted.text.length;\n documentRemaining -= fitted.text.length;\n return {\n ...attachment,\n textContent: fitted.text,\n textTruncated: attachment.textTruncated || fitted.truncated,\n ...(attachment.extraction\n ? {\n extraction: {\n ...attachment.extraction,\n pagesIncluded: fitted.pagesIncluded,\n pageNumbers: fitted.pageNumbers,\n },\n }\n : {}),\n };\n }\n\n const { text, truncated } = truncateForInline(attachment.textContent ?? '', limit);\n remaining -= text.length;\n if (isDocument) documentRemaining -= text.length;\n return { ...attachment, textContent: text, textTruncated: attachment.textTruncated || truncated };\n };\n\n for (const documents of [false, true]) {\n usable.forEach((attachment, index) => {\n if (!attachment.textContent) return;\n if (Boolean(attachment.extraction) !== documents) return;\n budgeted[index] = spend(attachment);\n });\n }\n\n return budgeted;\n}\n\nfunction renderAttachmentBlock(\n usable: AssistantAttachment[],\n documentLimit: number,\n demotedImageIds: ReadonlySet<string>\n): string {\n const budgeted = applyInlineBudget(usable, documentLimit);\n return [\n '',\n `--- Attachments (${usable.length}) ---`,\n 'The user attached the following file(s) to this message.',\n ...budgeted.map((attachment, index) => describeAttachment(attachment, index, demotedImageIds)),\n '--- End attachments ---',\n ].join('\\n');\n}\n\n/**\n * The one thing the modelled body genuinely misses: `buildPromptForMode`\n * prepends its 493-character api-calls preamble AFTER this block is built, and\n * `parts[0]` duplicates the whole prompt, so it is charged twice — 986 bytes.\n * The GraphQL document and page context are already covered many times over by\n * `TURN_BODY_HEADROOM_BYTES`, so this reserve stays small on purpose: every\n * byte of it is a byte of document text a farmer does not get.\n */\nexport const PROMPT_ENVELOPE_RESERVE_BYTES = 1_024;\n\n/**\n * How much extracted document text this turn can afford, and which photos will\n * therefore still carry pixels.\n *\n * ## The problem\n *\n * `buildPromptParts` demotes inline images to url-only until the body fits the\n * gateway's 256 KB cap. The prompt it measures already contains the attachment\n * block, and `parts[0]` duplicates the whole prompt — so 20,000 characters of\n * extracted document text costs ~41,000 bytes of the budget and can push a\n * perfectly ordinary 80 KB photo out of the turn. Before BOFF-6291 documents\n * contributed no text at all, so this is new pressure on the one attachment\n * capability that is verified working in production, and it is silent.\n *\n * ## The policy\n *\n * Images win. Document text is cut — to zero if that is what it takes — before\n * a single photo loses its pixels. Only if the turn will not fit even with NO\n * document text do we fall back to the pre-existing demotion, and then the\n * prompt block says so on that image (see `describeAttachment`) so the model\n * knows it is not seeing everything.\n *\n * Measured rather than modelled: each candidate budget is rendered and weighed\n * with `estimateTurnBodyBytes`, the same function `buildPromptParts` uses, so\n * the two cannot drift. At most five attachments and ~15 probes per send.\n */\nfunction fitInlineBudget(\n usable: AssistantAttachment[],\n userText: string\n): { documentChars: number; demotedImageIds: ReadonlySet<string> } {\n const candidates = inlineImageCandidates(usable);\n // No pixels at stake: keep the pre-existing behaviour byte for byte.\n if (candidates.length === 0) {\n return { documentChars: MAX_INLINE_CHARS_TOTAL, demotedImageIds: EMPTY_IDS };\n }\n\n const fits = (keep: number, documentChars: number, demoted: ReadonlySet<string>): boolean => {\n const allowed = new Set(candidates.slice(0, keep).map((attachment) => attachment.id));\n const block = renderAttachmentBlock(usable, documentChars, demoted);\n const promptText = userText ? `${userText}\\n${block}` : block.trimStart();\n const { media } = composeMedia(usable, allowed);\n const body = estimateTurnBodyBytes(promptText, [{ type: 'text', text: promptText }, ...media]);\n return body + PROMPT_ENVELOPE_RESERVE_BYTES <= MAX_INLINE_TURN_BODY_BYTES;\n };\n\n // `buildPromptParts` pops its inline images from the END, so the first photo —\n // the one the question is usually about — is the last to lose its pixels.\n // Walk the same order, so the set we reserve for is the set it will inline.\n for (let keep = candidates.length; keep >= 0; keep -= 1) {\n const demoted: ReadonlySet<string> = new Set(candidates.slice(keep).map((attachment) => attachment.id));\n if (fits(keep, MAX_INLINE_CHARS_TOTAL, demoted)) {\n return { documentChars: MAX_INLINE_CHARS_TOTAL, demotedImageIds: demoted };\n }\n if (!fits(keep, 0, demoted)) continue;\n\n // Largest document budget that still leaves every one of these images its\n // pixels. Monotone in `documentChars`, so a binary search is exact.\n let low = 0;\n let high = MAX_INLINE_CHARS_TOTAL;\n while (low < high) {\n const mid = Math.ceil((low + high) / 2);\n if (fits(keep, mid, demoted)) low = mid;\n else high = mid - 1;\n }\n return { documentChars: low, demotedImageIds: demoted };\n }\n\n // Not even an image-free, text-free turn fits — the user's own message is\n // over the cap. `buildPromptParts` drops `parts` wholesale in that case, which\n // halves the body, so trimming the document here would buy nothing.\n return {\n documentChars: MAX_INLINE_CHARS_TOTAL,\n demotedImageIds: new Set(candidates.map((attachment) => attachment.id)),\n };\n}\n\n/**\n * Render the attachment block appended to the outgoing prompt. Returns '' when\n * there is nothing to say, so callers can concatenate unconditionally.\n *\n * `userText` is the user's own message — the rest of the prompt this block will\n * be concatenated with. It is optional only so existing callers and tests keep\n * compiling; passing it is what lets the budget be measured against the real\n * turn rather than against the block alone.\n *\n * Attachments that failed to upload are omitted: the user already sees the\n * failure in the composer, and a half-described file only confuses the model.\n */\nexport function buildAttachmentPromptBlock(attachments: AssistantAttachment[], userText = ''): string {\n const usable = getSendableAttachments(attachments);\n if (usable.length === 0) return '';\n\n const budget = fitInlineBudget(usable, userText);\n return renderAttachmentBlock(usable, budget.documentChars, budget.demotedImageIds);\n}\n\n/**\n * Compose the text actually sent to the agent: the user's words, then the\n * attachment block. The user-facing bubble keeps the raw text (attachments are\n * rendered as chips there), matching how `buildPromptForMode` already separates\n * agent-only preamble from displayed content.\n */\nexport function buildPromptWithAttachments(content: string, attachments: AssistantAttachment[]): string {\n const block = buildAttachmentPromptBlock(attachments, content);\n if (!block) return content;\n return content ? `${content}\\n${block}` : block.trimStart();\n}\n\n// ── Multimodal parts (Workstream 4, client half) ─────────────────────────────\n\n/**\n * Structural mirror of fe-libs' `AssistantPromptPart`\n * (`@burdenoff/fe-libs/shared/assistant`). Declared locally so this module —\n * and its tests — stay pure and importable without the transport, and so the\n * builder compiles against a fe-libs pin that predates the widening. The\n * assignment at the call site is what proves the two agree.\n */\nexport type AssistantPromptPart =\n | { type: 'text'; text: string }\n | { type: 'image'; mimeType: string; url?: string; data?: string; name?: string }\n | { type: 'file'; mimeType: string; url?: string; data?: string; name?: string };\n\n/**\n * How many images may travel INLINE in one turn.\n *\n * Inline bytes are what make vision work without the sandbox needing egress to\n * our storage. Images beyond the budget still travel, by URL only, and the\n * prompt block still describes them.\n */\nexport const MAX_INLINE_IMAGE_PARTS = 3;\n\n/**\n * Belt-and-braces per-turn ceiling on base64 characters.\n *\n * Kept as a cheap guard against a pathological single image, but it is NO\n * LONGER the operative limit — `MAX_TURN_BODY_BYTES` is. See below for why the\n * previous 1.5M-character budget was a fiction.\n */\nexport const MAX_INLINE_IMAGE_BASE64_CHARS = 1_500_000;\n\n/**\n * The real ceiling: what the gateway will accept as a request body.\n *\n * `wspace-public-gateway` enforces `MAX_REQUEST_BODY_SIZE`, and both the alpha\n * and prod configs set it to **256kb** (`burdenoff-gitops`\n * `apps/config-workspace{,-prod}/wspace-public-gateway-config.yaml`). It is\n * checked against `Content-Length` before authentication and before anything is\n * forwarded, and it answers 413 with a JSON body — which fe-libs' `graphqlFetch`\n * maps to the generic 4xx sentence, discarding the status. So an oversized turn\n * does not degrade: it dies, and the user is told to refresh.\n *\n * The old budget (1.5M base64 characters ≈ 1.43 MB) was ~5.7x that cap, so a\n * single ordinary 1280px photo — 150-400 KB, i.e. 200-530 KB of base64 — was\n * enough to lose the whole turn. Measure the body instead of guessing at it.\n */\nexport const MAX_TURN_BODY_BYTES = MAX_REQUEST_BODY_BYTES;\n\n/**\n * Headroom left for everything `estimateTurnBodyBytes` does not model: the\n * GraphQL query document, the operation name, the sandbox id / path / method,\n * the context input and the page context.\n *\n * Measured, that overhead is under 1 KB — the ProxySandboxRequest document is\n * ~150 bytes and the page context a few hundred. 32 KB is therefore deliberately\n * ~30x the real figure, because the two ways of being wrong are not\n * symmetrical: reserve too much and one photo travels as a link instead of as\n * pixels; reserve too little and the entire turn is rejected and the farmer's\n * question is lost.\n */\nexport const TURN_BODY_HEADROOM_BYTES = 32_768;\n\n/** What the modelled part of the body must fit inside. */\nexport const MAX_INLINE_TURN_BODY_BYTES = MAX_TURN_BODY_BYTES - TURN_BODY_HEADROOM_BYTES;\n\n/**\n * Encode settings for the copy of an image that travels INSIDE the turn.\n *\n * Separate from the upload encode (1280px / q0.72) on purpose: the file that\n * lands in the farmer's file library should not be degraded to fit a transport\n * limit. At 768px / q0.6 a photo is typically 40-90 KB — 53-120 KB of base64 —\n * so one image fits inside `MAX_INLINE_TURN_BODY_BYTES` with room for the\n * prompt, and often two do. Vision models downsample to roughly this size\n * anyway, so the diagnostic detail that matters survives.\n */\nexport const INLINE_IMAGE_MAX_DIM = 768;\nexport const INLINE_IMAGE_QUALITY = 0.6;\n\n/** Reused across calls — the demotion loop measures the body once per image. */\nconst textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : null;\n\n/** UTF-8 byte length, with a graceful degradation where TextEncoder is absent. */\nfunction utf8ByteLength(value: string): number {\n return textEncoder ? textEncoder.encode(value).length : value.length;\n}\n\n/**\n * Estimate the bytes the prompt + parts will occupy in the POSTed body.\n *\n * Shaped like the JSON fe-libs actually builds (`{ mode, prompt, pageContext,\n * parts }` inside `proxySandboxRequest.body`), so the number tracks the thing\n * being limited rather than a proxy for it. Deliberately an UNDER-estimate of\n * the full request — `TURN_BODY_HEADROOM_BYTES` covers the difference.\n */\nexport function estimateTurnBodyBytes(promptText: string, parts?: AssistantPromptPart[]): number {\n return utf8ByteLength(JSON.stringify({ prompt: promptText, parts: parts ?? [] }));\n}\n\n/**\n * How many attachments COULD have travelled as pixels — i.e. are ready images\n * that have a `data:` URL to inline.\n *\n * Compared against how many actually did, this is what tells the user their\n * photo was demoted to a link. Without it the deterministic budget path is\n * silent, and only the transport-rejection path ever admits to anything.\n */\nexport function countInlineImageCandidates(attachments: AssistantAttachment[]): number {\n return getSendableAttachments(attachments).filter(\n (attachment) => attachment.kind === 'image' && Boolean(attachment.inlineDataUrl ?? attachment.previewUrl)\n ).length;\n}\n\n/** How many parts actually carry image bytes. */\nexport function countInlinedImageParts(parts: AssistantPromptPart[] | undefined): number {\n return (parts ?? []).filter((part) => part.type === 'image' && Boolean(part.data)).length;\n}\n\n/** Split a `data:<mime>;base64,<payload>` URL. Returns null for anything else. */\nexport function parseDataUrl(dataUrl: string): { mimeType: string; base64: string } | null {\n const match = /^data:([a-z0-9.+/-]+);base64,(.*)$/i.exec(dataUrl);\n return match ? { mimeType: match[1], base64: match[2] } : null;\n}\n\n/**\n * The ready images that COULD travel as pixels, in turn order, after the two\n * static budgets (`MAX_INLINE_IMAGE_PARTS`, `MAX_INLINE_IMAGE_BASE64_CHARS`).\n *\n * Factored out so `fitInlineBudget` reserves body space for exactly the set\n * `buildPromptParts` will try to inline, rather than for its own guess at it.\n */\nfunction inlineImageCandidates(usable: AssistantAttachment[]): AssistantAttachment[] {\n const chosen: AssistantAttachment[] = [];\n let inlineChars = 0;\n\n for (const attachment of usable) {\n if (attachment.kind !== 'image') continue;\n // The transport-sized encode when there is one, else the thumbnail.\n const inlineSource = attachment.inlineDataUrl ?? attachment.previewUrl;\n const parsed = inlineSource ? parseDataUrl(inlineSource) : null;\n if (!parsed) continue;\n if (chosen.length >= MAX_INLINE_IMAGE_PARTS) continue;\n if (inlineChars + parsed.base64.length > MAX_INLINE_IMAGE_BASE64_CHARS) continue;\n chosen.push(attachment);\n inlineChars += parsed.base64.length;\n }\n\n return chosen;\n}\n\n/**\n * The media parts for a turn, given which images are allowed to carry bytes.\n *\n * Everything not in `inlinedImageIds` degrades to url-only, exactly as the\n * demotion loop would leave it — so weighing a hypothetical turn and building\n * the real one go through the same code.\n */\nfunction composeMedia(\n usable: AssistantAttachment[],\n inlinedImageIds: ReadonlySet<string>\n): { media: AssistantPromptPart[]; inlinedIndices: number[] } {\n const media: AssistantPromptPart[] = [];\n // Positions in `media` that carry inline bytes, in the order they were added.\n // Demotion pops from the END, so the first photo — the one the farmer's\n // question is usually about — is the last to lose its pixels.\n const inlinedIndices: number[] = [];\n\n for (const attachment of usable) {\n if (attachment.kind === 'image') {\n const inlineSource = attachment.inlineDataUrl ?? attachment.previewUrl;\n const parsed = inlineSource ? parseDataUrl(inlineSource) : null;\n\n if (parsed && inlinedImageIds.has(attachment.id)) {\n inlinedIndices.push(media.length);\n media.push({\n type: 'image',\n mimeType: parsed.mimeType,\n data: parsed.base64,\n // Sent alongside the bytes: a bridge that would rather fetch than\n // carry base64 through its own pipeline can, and the reference\n // outlives this turn.\n ...(attachment.downloadUrl ? { url: attachment.downloadUrl } : {}),\n name: attachment.filename,\n });\n continue;\n }\n\n if (attachment.downloadUrl) {\n media.push({\n type: 'image',\n mimeType: attachment.mimeType,\n url: attachment.downloadUrl,\n name: attachment.filename,\n });\n }\n continue;\n }\n\n // Document BYTES are never inlined: a PDF is not an image, and 10 MB of it\n // would not fit the body anyway. Its TEXT already travels in the prompt\n // block (BOFF-6291 extracts it client-side), so what a part adds here is\n // only the reference — same as for text files, and a missing URL costs\n // nothing because the content is already across.\n if (attachment.downloadUrl) {\n media.push({\n type: 'file',\n mimeType: attachment.mimeType,\n url: attachment.downloadUrl,\n name: attachment.filename,\n });\n }\n }\n\n return { media, inlinedIndices };\n}\n\n/**\n * Build the structured multimodal turn.\n *\n * `promptText` MUST be the exact string also sent as `prompt`, so the two\n * channels are equivalent: a bridge that understands `parts` sees everything a\n * text-only bridge sees, plus the images. Returns `undefined` when there is\n * nothing an image/file part could add, which keeps the wire body byte-identical\n * to a pre-multimodal client for every ordinary text turn.\n */\nexport function buildPromptParts(\n promptText: string,\n attachments: AssistantAttachment[]\n): AssistantPromptPart[] | undefined {\n const usable = getSendableAttachments(attachments);\n if (usable.length === 0) return undefined;\n\n const candidates = new Set(inlineImageCandidates(usable).map((attachment) => attachment.id));\n const { media, inlinedIndices } = composeMedia(usable, candidates);\n\n if (media.length === 0) return undefined;\n\n // ── Fit the body ───────────────────────────────────────────────────────────\n // Everything above decides what we WANT to send; this decides what the\n // gateway will accept. Demote inline images to url-only (dropping the part\n // entirely if it has no URL to fall back to) until the modelled body fits.\n // Doing it here, deterministically, is what keeps the 413 fallback in\n // AssistantChatArea a genuine safety net rather than the normal path.\n while (\n inlinedIndices.length > 0 &&\n estimateTurnBodyBytes(promptText, [{ type: 'text', text: promptText }, ...media]) > MAX_INLINE_TURN_BODY_BYTES\n ) {\n const index = inlinedIndices.pop();\n if (index === undefined) break;\n const part = media[index];\n if (!part || part.type === 'text') continue;\n if (part.url) {\n media[index] = { type: part.type, mimeType: part.mimeType, url: part.url, name: part.name };\n } else {\n // Safe to splice: we always pop the highest remaining index, so no index\n // still in `inlinedIndices` can be shifted by this removal.\n media.splice(index, 1);\n }\n }\n\n if (media.length === 0) return undefined;\n\n // Nothing left to demote and still over the cap. Sending anyway would be a\n // CERTAIN 413, and `parts[0]` duplicates the whole prompt — so a long message\n // with one attachment can exceed the cap on prompt text alone, in a case\n // where the identical message with no attachment would have gone through.\n // Drop the parts entirely: the attachment block and its URLs are still in the\n // prompt, so the model keeps everything except the pixels.\n if (estimateTurnBodyBytes(promptText, [{ type: 'text', text: promptText }, ...media]) > MAX_INLINE_TURN_BODY_BYTES) {\n return undefined;\n }\n\n return [{ type: 'text', text: promptText }, ...media];\n}\n"],"mappings":";;AAuCA,IAAa,IAAiB,KAAK,OAAO,MAG7B,IAA4B,KAG5B,IAAyB,KAgBzB,IAAb,cAA6C,MAAM;CACjD,YAAY,GAAsC;AAEhD,EADA,MAAM,EAAO,EADM,KAAA,SAAA,GAEnB,KAAK,OAAO;;;AAsEhB,SAAgB,EAAoB,GAA6D;AAC/F,QAAO;EACL,IAAI,EAAW;EACf,UAAU,EAAW;EACrB,UAAU,EAAW;EACrB,MAAM,EAAW;EACjB,MAAM,EAAW;EACjB,QAAQ,EAAW;EACpB;;AAOH,IAAM,IAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAgB,EAAa,GAA0B;CACrD,IAAM,IAAM,EAAS,YAAY,IAAI;AACrC,QAAO,KAAO,IAAI,EAAS,MAAM,IAAM,EAAE,CAAC,aAAa,GAAG;;AAG5D,SAAgB,EAAmB,GAAkB,GAA2C;AAW9F,QAVI,EAAS,WAAW,SAAS,GAAS,UAExC,EAAS,WAAW,QAAQ,IAC5B,MAAa,sBACb,MAAa,qBACb,MAAa,wBACb,EAAgB,IAAI,EAAa,EAA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GACA,IAAM,IAAQ,EAAe,KAAK;AAClC,OAAI,MAAU,KAAA,EAAW;GACzB,IAAM,IAAO,EAAM;AACf,IAAC,KAAQ,EAAK,SAAS,WACvB,EAAK,MACP,EAAM,KAAS;IAAE,MAAM,EAAK;IAAM,UAAU,EAAK;IAAU,KAAK,EAAK;IAAK,MAAM,EAAK;IAAM,GAI3F,EAAM,OAAO,GAAO,EAAE;;AAItB,QAAM,WAAW,KAQjB,IAAsB,GAAY,CAAC;GAAE,MAAM;GAAQ,MAAM;GAAY,EAAE,GAAG,EAAM,CAAC,GAAG,GAIxF,QAAO,CAAC;GAAE,MAAM;GAAQ,MAAM;GAAY,EAAE,GAAG,EAAM"}
|
|
1
|
+
{"version":3,"file":"assistantAttachments.js","names":[],"sources":["../../src/utils/assistantAttachments.ts"],"sourcesContent":["/**\n * Attachment model for the assistant composer (Workstream 3 of the AI Assistant\n * V2 multimodal effort) — pure logic, no React, so it is unit-testable.\n *\n * ## How an attachment reaches the model today\n *\n * The sandbox transport carries exactly one user-authored field per turn:\n * a `prompt` **string** (`POST /sessions/:id/prompt-async`). The in-sandbox\n * agent's message parts are `text | tool` only. So there is no native file or\n * image part to put bytes into, and adding one means changing the out-of-repo\n * `ai-assistant-*` bridge image — that is Workstream 4, and it is not shipped.\n *\n * What this module does instead is the honest L1: every attachment is uploaded\n * to the workspace file library (wspace-files-svc) so it durably exists and has\n * a URL, and a compact, clearly-delimited block describing the attachments is\n * appended to the outgoing prompt. For **text-like** files the actual content is\n * inlined (bounded), which makes them fully usable by the model right now. For\n * images and binaries only the metadata and a presigned URL go across, and the\n * block says plainly that the bytes were not inlined — so the assistant asks\n * rather than hallucinating a description of a photo it cannot see.\n *\n * Whether the sandbox can egress to the presigned URL is **not verified** — the\n * wording therefore makes fetching conditional (\"if you can fetch URLs\") rather\n * than promising it. Vision on the image itself lands with Workstream 4.\n */\n\n/** Hard cap on attachments per message — keeps the prompt block bounded. */\nimport { MAX_REQUEST_BODY_BYTES } from './gatewayLimits';\nimport {\n formatPageRanges,\n isMostlyImagePages,\n truncatePagesForInline,\n type DocumentExtraction,\n type DocumentFormat,\n} from './documentText';\n\nexport const MAX_ATTACHMENTS = 5;\n\n/** Per-file ceiling before downscaling (images) / rejection (everything else). */\nexport const MAX_FILE_BYTES = 10 * 1024 * 1024;\n\n/** Per-file inline budget for text-like content, in characters. */\nexport const MAX_INLINE_CHARS_PER_FILE = 8_000;\n\n/** Total inline budget across all attachments in one turn. */\nexport const MAX_INLINE_CHARS_TOTAL = 20_000;\n\nexport type AssistantAttachmentKind = 'image' | 'text' | 'document';\n\nexport type AssistantAttachmentStatus = 'pending' | 'uploading' | 'ready' | 'error';\n\nexport type AttachmentRejection = 'too-many' | 'too-large' | 'empty' | 'unreadable' | 'unsupported-image';\n\n/**\n * Thrown while PREPARING a file (after it passed `validateFile`) to reject it\n * with a specific reason rather than the generic 'unreadable'.\n *\n * `validateFile` runs before the bytes have been touched, so it cannot know\n * whether an oversized image will actually survive the downscale — that verdict\n * only exists once the browser has tried to rasterise it.\n */\nexport class AttachmentRejectedError extends Error {\n constructor(readonly reason: AttachmentRejection) {\n super(reason);\n this.name = 'AttachmentRejectedError';\n }\n}\n\nexport interface AssistantAttachment {\n /** Client-side id; stable for the lifetime of the draft + the sent message. */\n id: string;\n filename: string;\n mimeType: string;\n /** Size of the bytes we actually kept (post-downscale for images). */\n size: number;\n kind: AssistantAttachmentKind;\n status: AssistantAttachmentStatus;\n /** Object/data URL for the composer thumbnail. Images only; never persisted. */\n previewUrl?: string;\n /**\n * A smaller `data:` URL of the same image, sized for the request body rather\n * than for the eye. Preferred over `previewUrl` when building the multimodal\n * parts; see `MAX_TURN_BODY_BYTES`. Images only; never persisted.\n */\n inlineDataUrl?: string;\n /** wspace-files-svc id, once the upload lands. */\n fileId?: string;\n /** Short-lived presigned URL, resolved at send time. */\n downloadUrl?: string;\n /**\n * Inlined content for this attachment, already truncated to\n * `MAX_INLINE_CHARS_PER_FILE`. Text files carry the file itself; PDF/DOCX/XLSX\n * carry whatever `extractDocumentText` pulled out of them (BOFF-6291).\n */\n textContent?: string;\n /** True when `textContent` is a prefix of a longer file. */\n textTruncated?: boolean;\n /**\n * Outcome of the client-side document extraction. Present on every `document`\n * we ATTEMPTED to read — including the failures, which is the point: a scanned\n * or encrypted PDF has to reach the model as a sentence rather than as\n * nothing. Absent means no extractor exists for the type.\n */\n extraction?: DocumentExtraction;\n /**\n * Per-page text for a PDF, kept so the SHARED inline budget can also cut on a\n * page boundary rather than mid-sentence. Already trimmed to the per-file\n * budget at prepare time, so this never holds a whole 50-page document.\n * Draft-only; `toMessageAttachment` never carries it to storage.\n */\n documentPages?: string[];\n /** Human-readable failure reason when `status === 'error'`. */\n error?: string;\n /**\n * Why an upload that is still `uploading` is taking so long — e.g. \"File service\n * is starting up — retry 2 of 3\".\n *\n * wspace-files-svc runs at minReplicas 0 and needs >=51s to bind its port against\n * the gateway's 15s budget, so the first attachment after a quiet period\n * legitimately sits for about a minute while fe-libs walks its retry ladder. A\n * spinner alone reads as a hang. Draft-only, and NEVER a failure: `status` is still\n * `uploading` and `error` is still unset.\n */\n progressNote?: string;\n}\n\n/**\n * The slice of an attachment that is safe to keep on a sent message.\n *\n * Conversations are persisted to (profile-scoped) localStorage by the assistant\n * store, so the heavy fields — the base64 `previewUrl` and the inlined\n * `textContent` — MUST NOT travel here: five 1280px JPEG data URLs would exhaust\n * the ~5 MB quota on their own and take the whole conversation history down with\n * them. The bubble re-resolves a thumbnail from `fileId` on demand instead, the\n * same way the pest-scan list does.\n */\nexport interface AssistantMessageAttachment {\n id: string;\n filename: string;\n mimeType: string;\n size: number;\n kind: AssistantAttachmentKind;\n fileId?: string;\n}\n\nexport function toMessageAttachment(attachment: AssistantAttachment): AssistantMessageAttachment {\n return {\n id: attachment.id,\n filename: attachment.filename,\n mimeType: attachment.mimeType,\n size: attachment.size,\n kind: attachment.kind,\n fileId: attachment.fileId,\n };\n}\n\n/**\n * Extensions we treat as text even when the browser reports a useless MIME type\n * (`application/octet-stream` is common for `.log`, `.yml`, `.env` on Windows).\n */\nconst TEXT_EXTENSIONS = new Set([\n 'txt',\n 'md',\n 'markdown',\n 'csv',\n 'tsv',\n 'json',\n 'yaml',\n 'yml',\n 'xml',\n 'log',\n 'sql',\n 'html',\n 'css',\n 'js',\n 'ts',\n 'tsx',\n 'jsx',\n 'py',\n 'sh',\n 'ini',\n 'toml',\n 'conf',\n]);\n\nexport function getExtension(filename: string): string {\n const dot = filename.lastIndexOf('.');\n return dot >= 0 ? filename.slice(dot + 1).toLowerCase() : '';\n}\n\nexport function classifyAttachment(mimeType: string, filename: string): AssistantAttachmentKind {\n if (mimeType.startsWith('image/')) return 'image';\n if (\n mimeType.startsWith('text/') ||\n mimeType === 'application/json' ||\n mimeType === 'application/xml' ||\n mimeType === 'application/x-yaml' ||\n TEXT_EXTENSIONS.has(getExtension(filename))\n ) {\n return 'text';\n }\n return 'document';\n}\n\n/**\n * Document formats we can turn into text in the browser (BOFF-6291).\n *\n * Anything else stays a `document` with no extraction, and the prompt block\n * says so — the honest fallback that used to be the ONLY behaviour.\n */\nexport type { DocumentFormat } from './documentText';\n\nconst DOCUMENT_MIME_TYPES: Record<string, DocumentFormat> = {\n 'application/pdf': 'pdf',\n 'application/x-pdf': 'pdf',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',\n};\n\nconst DOCUMENT_EXTENSIONS: Record<string, DocumentFormat> = {\n pdf: 'pdf',\n docx: 'docx',\n xlsx: 'xlsx',\n};\n\n/**\n * Which extractor (if any) can read this file.\n *\n * MIME first, extension second — same order as `classifyAttachment`, and for\n * the same reason: Windows reports `application/octet-stream` for plenty of\n * files whose extension is perfectly informative.\n */\nexport function detectDocumentFormat(mimeType: string, filename: string): DocumentFormat | null {\n return DOCUMENT_MIME_TYPES[mimeType.toLowerCase()] ?? DOCUMENT_EXTENSIONS[getExtension(filename)] ?? null;\n}\n\n/**\n * The composer's `<input accept>` — DERIVED from what we can actually read.\n *\n * It used to be a hand-written list (`…,.pdf,.csv,.json,.md,.txt,.xlsx,.docx`)\n * that invited exactly the files the model could not see: a farmer picked a\n * soil-test PDF because the picker offered it, and the assistant then asked\n * them to paste it as text. Building the list from `TEXT_EXTENSIONS` and\n * `DOCUMENT_EXTENSIONS` makes that class of mismatch a compile-time\n * impossibility rather than a thing to remember.\n */\nexport const ATTACHMENT_ACCEPT = [\n 'image/*',\n 'text/*',\n ...[...TEXT_EXTENSIONS].map((extension) => `.${extension}`),\n ...Object.keys(DOCUMENT_EXTENSIONS).map((extension) => `.${extension}`),\n].join(',');\n\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/**\n * Is there attachment work in flight that must block sending?\n *\n * `preparingCount` counts files the user has ALREADY dropped/picked but whose\n * image-downscale or text-read has not resolved yet. Those files have no id and\n * no row in `attachments`, so a check that looked only at `attachments` reported\n * \"idle\" during the whole preparation window — the composer stayed sendable, the\n * turn went out without the photo, and the photo then attached itself to the\n * user's NEXT message. Both halves must be counted.\n */\nexport function hasAttachmentWorkInFlight(preparingCount: number, attachments: AssistantAttachment[]): boolean {\n return (\n preparingCount > 0 ||\n attachments.some((attachment) => attachment.status === 'pending' || attachment.status === 'uploading')\n );\n}\n\n/**\n * The attachments a send would ACTUALLY carry to the model.\n *\n * This is the single definition of \"sendable\" — `buildAttachmentPromptBlock`,\n * `buildPromptParts`, `countInlineImageCandidates` and the composer's send\n * handler all route through it, so the set the user is shown and the set the\n * model receives cannot drift apart by one of them being updated and the others\n * not.\n *\n * `status` is the whole test, and that is deliberate rather than lazy: an\n * attachment whose content is already inlined does not need its upload to have\n * worked, so `useAssistantAttachments` marks a text file — and, since\n * BOFF-6291, a document whose text WAS extracted — `ready` even when the upload\n * failed. Such a file is sendable and does not block: its contents travel in\n * the prompt block, and all it lost is the URL. Only attachments with nothing\n * left to send (an image, or a document that could not be read) reach 'error',\n * and those are exactly the ones worth stopping a turn for.\n */\nexport function getSendableAttachments(attachments: AssistantAttachment[]): AssistantAttachment[] {\n return attachments.filter((attachment) => attachment.status === 'ready');\n}\n\n/** Why a draft cannot be sent yet, as far as its attachments are concerned. */\nexport type AttachmentSendBlocker = 'in-flight' | 'failed';\n\n/**\n * Whether the attachments block sending, and why — `null` when they do not.\n *\n * Two distinct reasons, deliberately not collapsed into one boolean:\n *\n * - `'in-flight'` is momentary and resolves itself; the composer shows a\n * spinner and the user just waits.\n * - `'failed'` never resolves on its own. It is the case this function was\n * added for: a failed attachment is omitted from the outgoing turn by\n * `getSendableAttachments`, but send used to stay enabled as long as there\n * was message text, and `clear()` then wiped the failed chip along with the\n * draft. So the user watched their photo's chip vanish into a sent message\n * that never contained it, and the assistant answered a question about an\n * image it was never given. Blocking is the honest response: the chip offers\n * both retry and remove, so the user picks whether the file matters, and\n * whichever they pick the UI and the model end up agreeing.\n *\n * In-flight is reported first: while an upload is still running the failure is\n * not yet final, and \"wait\" is better advice than \"retry or remove\".\n *\n * Nothing here needs to special-case text files or extracted documents: they\n * never reach 'error' in the first place (see `getSendableAttachments`), so a\n * soil-test PDF the browser read but the file library refused still sends, with\n * its text, and never blocks.\n */\nexport function getAttachmentSendBlocker(\n preparingCount: number,\n attachments: AssistantAttachment[]\n): AttachmentSendBlocker | null {\n if (hasAttachmentWorkInFlight(preparingCount, attachments)) return 'in-flight';\n if (attachments.some((attachment) => attachment.status === 'error')) return 'failed';\n return null;\n}\n\n/**\n * Gate a candidate file. Images over the ceiling are still accepted — the\n * composer downscales them before upload, so a 12 MB phone photo is fine while\n * a 12 MB PDF is not.\n *\n * That exemption is a PROMISE, not a fact: it holds only if the browser can\n * actually rasterise the image. When it cannot (HEIC), `prepareFile` re-applies\n * this ceiling to the original bytes and rejects there instead.\n */\nexport function validateFile(file: File, currentCount: number): AttachmentRejection | null {\n if (currentCount >= MAX_ATTACHMENTS) return 'too-many';\n if (file.size === 0) return 'empty';\n if (file.size > MAX_FILE_BYTES && !file.type.startsWith('image/')) return 'too-large';\n return null;\n}\n\n/**\n * Truncate on a line boundary where possible, so an inlined CSV/JSON prefix ends\n * at a row rather than mid-token (which reads as corrupt data to the model).\n */\nexport function truncateForInline(content: string, limit: number): { text: string; truncated: boolean } {\n if (content.length <= limit) return { text: content, truncated: false };\n const head = content.slice(0, limit);\n const lastNewline = head.lastIndexOf('\\n');\n return { text: lastNewline > limit * 0.5 ? head.slice(0, lastNewline) : head, truncated: true };\n}\n\n/** Indented fenced block holding an attachment's inlined content. */\nfunction fencedContent(content: string): string[] {\n return [' ```', ...content.split('\\n').map((line) => ` ${line}`), ' ```'];\n}\n\n/**\n * The pages whose text is actually in front of the model.\n *\n * `pageNumbers` is the truth when the extractor produced it. `pagesIncluded` is\n * the older, coarser field — how FAR into the document we got — and is only a\n * fallback, because on a document with image pages the two differ and reporting\n * the coarser one is what lets a 40-page certificate with 3 readable pages\n * describe itself as \"40 pages\".\n */\nfunction pagesActuallyRead(extraction: DocumentExtraction | undefined): number[] {\n if (extraction?.pageNumbers?.length) return extraction.pageNumbers;\n if (extraction?.pagesIncluded) return Array.from({ length: extraction.pagesIncluded }, (_, index) => index + 1);\n return [];\n}\n\n/**\n * The parenthetical after \"Extracted text\" — what the model is looking at, and\n * what it is NOT.\n *\n * Deliberately the same shape as the text path's \"first N characters of M;\n * truncated\", because a partial document presented as whole is the single most\n * expensive way this feature can fail: the assistant reads eight thousand\n * characters of a forty-page organic-certification audit and tells the farmer\n * it is compliant.\n *\n * The page fact counts PAGES READ, never pages processed. \"40 pages\" is only\n * ever emitted when all forty are genuinely below.\n */\nfunction extractionScope(attachment: AssistantAttachment): string {\n const extraction = attachment.extraction;\n const facts: string[] = [];\n\n if (extraction?.pageCount) {\n const read = pagesActuallyRead(extraction);\n if (read.length >= extraction.pageCount) {\n facts.push(`${extraction.pageCount} page${extraction.pageCount === 1 ? '' : 's'}`);\n } else if (read.length === 1) {\n facts.push(`page ${read[0]} of ${extraction.pageCount}`);\n } else {\n facts.push(`pages ${formatPageRanges(read)} of ${extraction.pageCount}`);\n }\n }\n if (extraction?.sheetNames?.length) {\n facts.push(`sheets: ${extraction.sheetNames.join(', ')}`);\n }\n if (attachment.textTruncated && attachment.textContent) {\n const total = extraction?.sourceChars;\n facts.push(\n total && total > attachment.textContent.length\n ? `first ${attachment.textContent.length} characters of ${total}; truncated`\n : `first ${attachment.textContent.length} characters; truncated`\n );\n }\n\n return facts.length > 0 ? ` (${facts.join('; ')})` : '';\n}\n\n/**\n * The one sentence every \"you have not seen this\" branch ends on. Kept as a\n * constant so no branch can be added without it.\n */\nconst DO_NOT_GUESS = ' Do NOT guess at, summarise or characterise its contents — you have not seen them.';\n\n/** Closing instruction shared by every \"we could not read this\" branch. */\nconst NO_TEXT_ADVICE = [\n ' Fetch the URL above if you can; otherwise ask the user to paste the relevant section as text.',\n DO_NOT_GUESS,\n];\n\n/**\n * Name the pages that were NOT read, so a document is never presented as whole.\n *\n * Two ways a page goes unread, and the model needs both: it had no text layer\n * (an image page), or it fell outside what we processed — the 100-page scan cap\n * or the inline budget.\n */\nfunction unreadPageDisclosure(attachment: AssistantAttachment): string[] {\n const extraction = attachment.extraction;\n if (!extraction?.pageCount) return [];\n\n const read = new Set(pagesActuallyRead(extraction));\n const known = new Set(extraction.imagePages ?? []);\n const imagePages = [...known].filter((page) => !read.has(page)).sort((left, right) => left - right);\n const lines: string[] = [];\n\n if (imagePages.length > 0) {\n const label = imagePages.length === 1 ? `Page ${imagePages[0]}` : `Pages ${formatPageRanges(imagePages)}`;\n lines.push(\n ` ${label} of this document contain no extractable text — they are images.`,\n ' Nothing about those pages is available to you.'\n );\n }\n\n const notProcessed: number[] = [];\n for (let page = 1; page <= extraction.pageCount; page += 1) {\n if (!read.has(page) && !known.has(page)) notProcessed.push(page);\n }\n if (notProcessed.length > 0) {\n const label = notProcessed.length === 1 ? `Page ${notProcessed[0]}` : `Pages ${formatPageRanges(notProcessed)}`;\n lines.push(` ${label} of this document ${notProcessed.length === 1 ? 'was' : 'were'} not read at all.`);\n }\n\n if (lines.length > 0) lines.push(DO_NOT_GUESS);\n return lines;\n}\n\n/**\n * What a PDF/DOCX/XLSX attachment says to the model.\n *\n * Every branch is a positive statement. The one thing this must never do is\n * emit an attachment header with nothing after it, because a file that is\n * merely *listed* reads to the model as a file it may reason about.\n */\nfunction describeDocument(attachment: AssistantAttachment): string[] {\n const extraction = attachment.extraction;\n\n // No extractor ran at all (.zip, .pptx, a legacy .doc). Unchanged behaviour.\n if (!extraction || extraction.status === 'unsupported') {\n return [\n ' Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user',\n ' to paste the relevant section as text.',\n ];\n }\n\n if (extraction.status === 'no-text') {\n // A PDF with no text layer is a scan. A .docx or .xlsx with no text is\n // simply empty (or holds only images and charts) — saying \"scanned\" there\n // would be a confident, checkable falsehood.\n if (extraction.format === 'docx' || extraction.format === 'xlsx') {\n return [\n ' NO TEXT AVAILABLE — this document holds no readable text; it is either empty or contains only',\n ' images, charts or drawings, none of which carry text. No text could be extracted.',\n ...NO_TEXT_ADVICE,\n ];\n }\n const scanned =\n extraction.pagesScanned && extraction.pageCount && extraction.pagesScanned < extraction.pageCount\n ? ` (the first ${extraction.pagesScanned} of ${extraction.pageCount} pages were checked)`\n : '';\n return [\n ` NO TEXT AVAILABLE — this document appears to be scanned images; no text could be extracted${scanned}.`,\n ' There is no text layer to read, so nothing about its contents is available to you.',\n ...NO_TEXT_ADVICE,\n ];\n }\n\n if (extraction.status === 'encrypted') {\n return [\n ' NO TEXT AVAILABLE — this document is encrypted or password-protected; it could not be opened',\n ' and no text could be extracted.',\n ...NO_TEXT_ADVICE,\n ];\n }\n\n if (extraction.status === 'corrupt') {\n const detail = extraction.detail ? ` (${extraction.detail})` : '';\n return [\n ` NO TEXT AVAILABLE — this file could not be read${detail}; no text could be extracted.`,\n ...NO_TEXT_ADVICE,\n ];\n }\n\n // status === 'ok' but the shared inline budget went to earlier attachments.\n if (!attachment.textContent) {\n return [\n ' Text WAS extracted from this document but is omitted because this turn ran out of inline budget,',\n ' not because it is unavailable. Ask the user which part matters so they can re-send just that',\n ' section, or fetch the URL above if you can.',\n DO_NOT_GUESS,\n ];\n }\n\n // Mostly images: a text layer exists, but on so few pages that presenting the\n // fragment as \"the document\" is the same falsehood as reading a scan. The\n // fragment is still handed over — throwing away three real pages of audit\n // findings would be its own kind of dishonesty — but the header refuses on\n // the document's behalf, so the model cannot treat it as read.\n //\n // Gated on `textPageCount` being PRESENT, never defaulted: an extraction that\n // predates the density pass knows nothing about image pages, and treating\n // \"unknown\" as \"zero text pages\" would refuse a document we read perfectly.\n const scanned = extraction.pagesScanned ?? extraction.pageCount ?? 0;\n const textPages = extraction.textPageCount;\n if (extraction.pageCount && textPages !== undefined && isMostlyImagePages(textPages, scanned)) {\n const imageCount = scanned - textPages;\n return [\n ` NOT READ — this document is mostly images. Only ${textPages} of its ${extraction.pageCount} page${\n extraction.pageCount === 1 ? '' : 's'\n } carr${textPages === 1 ? 'ies' : 'y'} a text layer;`,\n ` the other ${imageCount} contain no extractable text at all. Treat this as a document you have NOT`,\n ' read: the fragment below is the whole of what was available, not a summary of the document.',\n ...unreadPageDisclosure(attachment),\n ` The only extractable text${extractionScope(attachment)}:`,\n ...fencedContent(attachment.textContent),\n ];\n }\n\n return [\n ` Extracted text${extractionScope(attachment)}:`,\n ...fencedContent(attachment.textContent),\n ...unreadPageDisclosure(attachment),\n ];\n}\n\nfunction describeAttachment(\n attachment: AssistantAttachment,\n index: number,\n demotedImageIds: ReadonlySet<string> = EMPTY_IDS\n): string {\n const lines = [`[${index + 1}] ${attachment.filename} — ${attachment.mimeType}, ${formatBytes(attachment.size)}`];\n\n if (attachment.downloadUrl) {\n lines.push(` URL: ${attachment.downloadUrl}`);\n }\n\n if (attachment.kind === 'text' && attachment.textContent) {\n lines.push(\n attachment.textTruncated\n ? ` Contents (first ${attachment.textContent.length} characters of ${formatBytes(attachment.size)}; truncated):`\n : ' Contents:',\n ...fencedContent(attachment.textContent)\n );\n } else if (attachment.kind === 'document') {\n lines.push(...describeDocument(attachment));\n } else if (attachment.kind === 'image') {\n if (demotedImageIds.has(attachment.id)) {\n // This photo COULD have travelled as pixels and does not, because the\n // turn would otherwise exceed the gateway's body cap. That decision is\n // invisible unless it is said, and an answer written as if the model had\n // looked at a photo it never received is the worst outcome here.\n lines.push(\n ' NOT VIEWABLE IN THIS MESSAGE — this image did not fit the request-size budget, so only its URL',\n ' travelled; its pixels are NOT attached. Fetch the URL above if you can; otherwise ask the user',\n ' to describe it.',\n DO_NOT_GUESS\n );\n } else {\n // Deliberately regime-neutral wording. This same block is sent whether or\n // not the bridge understands `parts`, so it must not assert either that the\n // model CAN see the image (it would then invent a description on the old\n // bridge) or that it CANNOT (it would then refuse to look on the new one).\n lines.push(\n ' If this image is attached to the message as an image you can view, answer from what you see in it.',\n ' If you cannot view attached images, say so plainly and ask the user to describe it — never guess.'\n );\n }\n } else if (attachment.kind === 'text') {\n // A text file with no `textContent` did not lose its type — it lost its slot\n // in the shared inline budget. Calling it \"binary\" here had the assistant ask\n // the farmer to paste text it already knew was text.\n lines.push(\n ' Text file — contents omitted because this turn ran out of inline budget, not because they are',\n ' unavailable. Fetch the URL above if you can; otherwise ask the user which part matters so they',\n ' can re-send just that section.'\n );\n } else {\n lines.push(\n ' Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user',\n ' to paste the relevant section as text.'\n );\n }\n\n return lines.join('\\n');\n}\n\nconst EMPTY_IDS: ReadonlySet<string> = new Set<string>();\n\n/**\n * Spend the shared inline budget.\n *\n * ## Order: verified capabilities first, the new one last\n *\n * Attachments are still served in the order the user picked them, but in TWO\n * passes — text files, then extracted document text. Both of the other two ways\n * an attachment reaches the model (a photo's pixels, a `.csv`'s contents) work\n * in production today; BOFF-6291's extracted document text is new. So when they\n * cannot all fit, the new one yields. A single in-order pass let a dense PDF\n * picked first take 8,000 characters off the `.csv` behind it, which is a\n * regression in a shipped path paid for by a feature nobody had yet.\n *\n * ## Two ceilings, both of which have to hold HERE\n *\n * - `MAX_INLINE_CHARS_PER_FILE`. It used to be applied only by the extractor,\n * and this pass then re-ran the page fit against the whole 20,000-character\n * TOTAL — so a PDF whose page 1 was 30,000 characters came out of prepare at\n * 8,000, went back up to 20,000 here, and the `.csv` attached beside it got\n * nothing at all. The clamp below is the invariant; the extractor storing\n * only the already-fitted pages (`FittedPages.pages`) is its belt.\n * - `documentLimit` — how much document text the request BODY can afford once\n * the images have been paid for. See `fitInlineBudget`.\n */\nfunction applyInlineBudget(usable: AssistantAttachment[], documentLimit: number): AssistantAttachment[] {\n let remaining = MAX_INLINE_CHARS_TOTAL;\n let documentRemaining = documentLimit;\n const budgeted: AssistantAttachment[] = [...usable];\n\n const spend = (attachment: AssistantAttachment): AssistantAttachment => {\n const isDocument = Boolean(attachment.extraction);\n const limit = Math.min(\n remaining,\n MAX_INLINE_CHARS_PER_FILE,\n isDocument ? documentRemaining : Number.POSITIVE_INFINITY\n );\n if (limit <= 0) {\n return { ...attachment, textContent: undefined, textTruncated: true };\n }\n\n // A PDF still knows its page boundaries here, so the shared budget cuts on\n // one too rather than undoing the page-aligned trim done at prepare time.\n if (attachment.documentPages?.length) {\n const fitted = truncatePagesForInline(attachment.documentPages, limit);\n if (fitted.text === '') {\n return { ...attachment, textContent: undefined, textTruncated: true };\n }\n remaining -= fitted.text.length;\n documentRemaining -= fitted.text.length;\n return {\n ...attachment,\n textContent: fitted.text,\n textTruncated: attachment.textTruncated || fitted.truncated,\n ...(attachment.extraction\n ? {\n extraction: {\n ...attachment.extraction,\n pagesIncluded: fitted.pagesIncluded,\n pageNumbers: fitted.pageNumbers,\n },\n }\n : {}),\n };\n }\n\n const { text, truncated } = truncateForInline(attachment.textContent ?? '', limit);\n remaining -= text.length;\n if (isDocument) documentRemaining -= text.length;\n return { ...attachment, textContent: text, textTruncated: attachment.textTruncated || truncated };\n };\n\n for (const documents of [false, true]) {\n usable.forEach((attachment, index) => {\n if (!attachment.textContent) return;\n if (Boolean(attachment.extraction) !== documents) return;\n budgeted[index] = spend(attachment);\n });\n }\n\n return budgeted;\n}\n\nfunction renderAttachmentBlock(\n usable: AssistantAttachment[],\n documentLimit: number,\n demotedImageIds: ReadonlySet<string>\n): string {\n const budgeted = applyInlineBudget(usable, documentLimit);\n return [\n '',\n `--- Attachments (${usable.length}) ---`,\n 'The user attached the following file(s) to this message.',\n ...budgeted.map((attachment, index) => describeAttachment(attachment, index, demotedImageIds)),\n '--- End attachments ---',\n ].join('\\n');\n}\n\n/**\n * The one thing the modelled body genuinely misses: `buildPromptForMode`\n * prepends its 493-character api-calls preamble AFTER this block is built, and\n * `parts[0]` duplicates the whole prompt, so it is charged twice — 986 bytes.\n * The GraphQL document and page context are already covered many times over by\n * `TURN_BODY_HEADROOM_BYTES`, so this reserve stays small on purpose: every\n * byte of it is a byte of document text a farmer does not get.\n */\nexport const PROMPT_ENVELOPE_RESERVE_BYTES = 1_024;\n\n/**\n * How much extracted document text this turn can afford, and which photos will\n * therefore still carry pixels.\n *\n * ## The problem\n *\n * `buildPromptParts` demotes inline images to url-only until the body fits the\n * gateway's 256 KB cap. The prompt it measures already contains the attachment\n * block, and `parts[0]` duplicates the whole prompt — so 20,000 characters of\n * extracted document text costs ~41,000 bytes of the budget and can push a\n * perfectly ordinary 80 KB photo out of the turn. Before BOFF-6291 documents\n * contributed no text at all, so this is new pressure on the one attachment\n * capability that is verified working in production, and it is silent.\n *\n * ## The policy\n *\n * Images win. Document text is cut — to zero if that is what it takes — before\n * a single photo loses its pixels. Only if the turn will not fit even with NO\n * document text do we fall back to the pre-existing demotion, and then the\n * prompt block says so on that image (see `describeAttachment`) so the model\n * knows it is not seeing everything.\n *\n * Measured rather than modelled: each candidate budget is rendered and weighed\n * with `estimateTurnBodyBytes`, the same function `buildPromptParts` uses, so\n * the two cannot drift. At most five attachments and ~15 probes per send.\n */\nfunction fitInlineBudget(\n usable: AssistantAttachment[],\n userText: string\n): { documentChars: number; demotedImageIds: ReadonlySet<string> } {\n const candidates = inlineImageCandidates(usable);\n // No pixels at stake: keep the pre-existing behaviour byte for byte.\n if (candidates.length === 0) {\n return { documentChars: MAX_INLINE_CHARS_TOTAL, demotedImageIds: EMPTY_IDS };\n }\n\n const fits = (keep: number, documentChars: number, demoted: ReadonlySet<string>): boolean => {\n const allowed = new Set(candidates.slice(0, keep).map((attachment) => attachment.id));\n const block = renderAttachmentBlock(usable, documentChars, demoted);\n const promptText = userText ? `${userText}\\n${block}` : block.trimStart();\n const { media } = composeMedia(usable, allowed);\n const body = estimateTurnBodyBytes(promptText, [{ type: 'text', text: promptText }, ...media]);\n return body + PROMPT_ENVELOPE_RESERVE_BYTES <= MAX_INLINE_TURN_BODY_BYTES;\n };\n\n // `buildPromptParts` pops its inline images from the END, so the first photo —\n // the one the question is usually about — is the last to lose its pixels.\n // Walk the same order, so the set we reserve for is the set it will inline.\n for (let keep = candidates.length; keep >= 0; keep -= 1) {\n const demoted: ReadonlySet<string> = new Set(candidates.slice(keep).map((attachment) => attachment.id));\n if (fits(keep, MAX_INLINE_CHARS_TOTAL, demoted)) {\n return { documentChars: MAX_INLINE_CHARS_TOTAL, demotedImageIds: demoted };\n }\n if (!fits(keep, 0, demoted)) continue;\n\n // Largest document budget that still leaves every one of these images its\n // pixels. Monotone in `documentChars`, so a binary search is exact.\n let low = 0;\n let high = MAX_INLINE_CHARS_TOTAL;\n while (low < high) {\n const mid = Math.ceil((low + high) / 2);\n if (fits(keep, mid, demoted)) low = mid;\n else high = mid - 1;\n }\n return { documentChars: low, demotedImageIds: demoted };\n }\n\n // Not even an image-free, text-free turn fits — the user's own message is\n // over the cap. `buildPromptParts` drops `parts` wholesale in that case, which\n // halves the body, so trimming the document here would buy nothing.\n return {\n documentChars: MAX_INLINE_CHARS_TOTAL,\n demotedImageIds: new Set(candidates.map((attachment) => attachment.id)),\n };\n}\n\n/**\n * Render the attachment block appended to the outgoing prompt. Returns '' when\n * there is nothing to say, so callers can concatenate unconditionally.\n *\n * `userText` is the user's own message — the rest of the prompt this block will\n * be concatenated with. It is optional only so existing callers and tests keep\n * compiling; passing it is what lets the budget be measured against the real\n * turn rather than against the block alone.\n *\n * Attachments that failed to upload are omitted: the user already sees the\n * failure in the composer, and a half-described file only confuses the model.\n */\nexport function buildAttachmentPromptBlock(attachments: AssistantAttachment[], userText = ''): string {\n const usable = getSendableAttachments(attachments);\n if (usable.length === 0) return '';\n\n const budget = fitInlineBudget(usable, userText);\n return renderAttachmentBlock(usable, budget.documentChars, budget.demotedImageIds);\n}\n\n/**\n * Compose the text actually sent to the agent: the user's words, then the\n * attachment block. The user-facing bubble keeps the raw text (attachments are\n * rendered as chips there), matching how `buildPromptForMode` already separates\n * agent-only preamble from displayed content.\n */\nexport function buildPromptWithAttachments(content: string, attachments: AssistantAttachment[]): string {\n const block = buildAttachmentPromptBlock(attachments, content);\n if (!block) return content;\n return content ? `${content}\\n${block}` : block.trimStart();\n}\n\n// ── Multimodal parts (Workstream 4, client half) ─────────────────────────────\n\n/**\n * Structural mirror of fe-libs' `AssistantPromptPart`\n * (`@burdenoff/fe-libs/shared/assistant`). Declared locally so this module —\n * and its tests — stay pure and importable without the transport, and so the\n * builder compiles against a fe-libs pin that predates the widening. The\n * assignment at the call site is what proves the two agree.\n */\nexport type AssistantPromptPart =\n | { type: 'text'; text: string }\n | { type: 'image'; mimeType: string; url?: string; data?: string; name?: string }\n | { type: 'file'; mimeType: string; url?: string; data?: string; name?: string };\n\n/**\n * How many images may travel INLINE in one turn.\n *\n * Inline bytes are what make vision work without the sandbox needing egress to\n * our storage. Images beyond the budget still travel, by URL only, and the\n * prompt block still describes them.\n */\nexport const MAX_INLINE_IMAGE_PARTS = 3;\n\n/**\n * Belt-and-braces per-turn ceiling on base64 characters.\n *\n * Kept as a cheap guard against a pathological single image, but it is NO\n * LONGER the operative limit — `MAX_TURN_BODY_BYTES` is. See below for why the\n * previous 1.5M-character budget was a fiction.\n */\nexport const MAX_INLINE_IMAGE_BASE64_CHARS = 1_500_000;\n\n/**\n * The real ceiling: what the gateway will accept as a request body.\n *\n * `wspace-public-gateway` enforces `MAX_REQUEST_BODY_SIZE`, and both the alpha\n * and prod configs set it to **256kb** (`burdenoff-gitops`\n * `apps/config-workspace{,-prod}/wspace-public-gateway-config.yaml`). It is\n * checked against `Content-Length` before authentication and before anything is\n * forwarded, and it answers 413 with a JSON body — which fe-libs' `graphqlFetch`\n * maps to the generic 4xx sentence, discarding the status. So an oversized turn\n * does not degrade: it dies, and the user is told to refresh.\n *\n * The old budget (1.5M base64 characters ≈ 1.43 MB) was ~5.7x that cap, so a\n * single ordinary 1280px photo — 150-400 KB, i.e. 200-530 KB of base64 — was\n * enough to lose the whole turn. Measure the body instead of guessing at it.\n */\nexport const MAX_TURN_BODY_BYTES = MAX_REQUEST_BODY_BYTES;\n\n/**\n * Headroom left for everything `estimateTurnBodyBytes` does not model: the\n * GraphQL query document, the operation name, the sandbox id / path / method,\n * the context input and the page context.\n *\n * Measured, that overhead is under 1 KB — the ProxySandboxRequest document is\n * ~150 bytes and the page context a few hundred. 32 KB is therefore deliberately\n * ~30x the real figure, because the two ways of being wrong are not\n * symmetrical: reserve too much and one photo travels as a link instead of as\n * pixels; reserve too little and the entire turn is rejected and the farmer's\n * question is lost.\n */\nexport const TURN_BODY_HEADROOM_BYTES = 32_768;\n\n/** What the modelled part of the body must fit inside. */\nexport const MAX_INLINE_TURN_BODY_BYTES = MAX_TURN_BODY_BYTES - TURN_BODY_HEADROOM_BYTES;\n\n/**\n * Encode settings for the copy of an image that travels INSIDE the turn.\n *\n * Separate from the upload encode (1280px / q0.72) on purpose: the file that\n * lands in the farmer's file library should not be degraded to fit a transport\n * limit. At 768px / q0.6 a photo is typically 40-90 KB — 53-120 KB of base64 —\n * so one image fits inside `MAX_INLINE_TURN_BODY_BYTES` with room for the\n * prompt, and often two do. Vision models downsample to roughly this size\n * anyway, so the diagnostic detail that matters survives.\n */\nexport const INLINE_IMAGE_MAX_DIM = 768;\nexport const INLINE_IMAGE_QUALITY = 0.6;\n\n/** Reused across calls — the demotion loop measures the body once per image. */\nconst textEncoder = typeof TextEncoder === 'function' ? new TextEncoder() : null;\n\n/** UTF-8 byte length, with a graceful degradation where TextEncoder is absent. */\nfunction utf8ByteLength(value: string): number {\n return textEncoder ? textEncoder.encode(value).length : value.length;\n}\n\n/**\n * Estimate the bytes the prompt + parts will occupy in the POSTed body.\n *\n * Shaped like the JSON fe-libs actually builds (`{ mode, prompt, pageContext,\n * parts }` inside `proxySandboxRequest.body`), so the number tracks the thing\n * being limited rather than a proxy for it. Deliberately an UNDER-estimate of\n * the full request — `TURN_BODY_HEADROOM_BYTES` covers the difference.\n */\nexport function estimateTurnBodyBytes(promptText: string, parts?: AssistantPromptPart[]): number {\n return utf8ByteLength(JSON.stringify({ prompt: promptText, parts: parts ?? [] }));\n}\n\n/**\n * How many attachments COULD have travelled as pixels — i.e. are ready images\n * that have a `data:` URL to inline.\n *\n * Compared against how many actually did, this is what tells the user their\n * photo was demoted to a link. Without it the deterministic budget path is\n * silent, and only the transport-rejection path ever admits to anything.\n */\nexport function countInlineImageCandidates(attachments: AssistantAttachment[]): number {\n return getSendableAttachments(attachments).filter(\n (attachment) => attachment.kind === 'image' && Boolean(attachment.inlineDataUrl ?? attachment.previewUrl)\n ).length;\n}\n\n/** How many parts actually carry image bytes. */\nexport function countInlinedImageParts(parts: AssistantPromptPart[] | undefined): number {\n return (parts ?? []).filter((part) => part.type === 'image' && Boolean(part.data)).length;\n}\n\n/** Split a `data:<mime>;base64,<payload>` URL. Returns null for anything else. */\nexport function parseDataUrl(dataUrl: string): { mimeType: string; base64: string } | null {\n const match = /^data:([a-z0-9.+/-]+);base64,(.*)$/i.exec(dataUrl);\n return match ? { mimeType: match[1], base64: match[2] } : null;\n}\n\n/**\n * The ready images that COULD travel as pixels, in turn order, after the two\n * static budgets (`MAX_INLINE_IMAGE_PARTS`, `MAX_INLINE_IMAGE_BASE64_CHARS`).\n *\n * Factored out so `fitInlineBudget` reserves body space for exactly the set\n * `buildPromptParts` will try to inline, rather than for its own guess at it.\n */\nfunction inlineImageCandidates(usable: AssistantAttachment[]): AssistantAttachment[] {\n const chosen: AssistantAttachment[] = [];\n let inlineChars = 0;\n\n for (const attachment of usable) {\n if (attachment.kind !== 'image') continue;\n // The transport-sized encode when there is one, else the thumbnail.\n const inlineSource = attachment.inlineDataUrl ?? attachment.previewUrl;\n const parsed = inlineSource ? parseDataUrl(inlineSource) : null;\n if (!parsed) continue;\n if (chosen.length >= MAX_INLINE_IMAGE_PARTS) continue;\n if (inlineChars + parsed.base64.length > MAX_INLINE_IMAGE_BASE64_CHARS) continue;\n chosen.push(attachment);\n inlineChars += parsed.base64.length;\n }\n\n return chosen;\n}\n\n/**\n * The media parts for a turn, given which images are allowed to carry bytes.\n *\n * Everything not in `inlinedImageIds` degrades to url-only, exactly as the\n * demotion loop would leave it — so weighing a hypothetical turn and building\n * the real one go through the same code.\n */\nfunction composeMedia(\n usable: AssistantAttachment[],\n inlinedImageIds: ReadonlySet<string>\n): { media: AssistantPromptPart[]; inlinedIndices: number[] } {\n const media: AssistantPromptPart[] = [];\n // Positions in `media` that carry inline bytes, in the order they were added.\n // Demotion pops from the END, so the first photo — the one the farmer's\n // question is usually about — is the last to lose its pixels.\n const inlinedIndices: number[] = [];\n\n for (const attachment of usable) {\n if (attachment.kind === 'image') {\n const inlineSource = attachment.inlineDataUrl ?? attachment.previewUrl;\n const parsed = inlineSource ? parseDataUrl(inlineSource) : null;\n\n if (parsed && inlinedImageIds.has(attachment.id)) {\n inlinedIndices.push(media.length);\n media.push({\n type: 'image',\n mimeType: parsed.mimeType,\n data: parsed.base64,\n // Sent alongside the bytes: a bridge that would rather fetch than\n // carry base64 through its own pipeline can, and the reference\n // outlives this turn.\n ...(attachment.downloadUrl ? { url: attachment.downloadUrl } : {}),\n name: attachment.filename,\n });\n continue;\n }\n\n if (attachment.downloadUrl) {\n media.push({\n type: 'image',\n mimeType: attachment.mimeType,\n url: attachment.downloadUrl,\n name: attachment.filename,\n });\n }\n continue;\n }\n\n // Document BYTES are never inlined: a PDF is not an image, and 10 MB of it\n // would not fit the body anyway. Its TEXT already travels in the prompt\n // block (BOFF-6291 extracts it client-side), so what a part adds here is\n // only the reference — same as for text files, and a missing URL costs\n // nothing because the content is already across.\n if (attachment.downloadUrl) {\n media.push({\n type: 'file',\n mimeType: attachment.mimeType,\n url: attachment.downloadUrl,\n name: attachment.filename,\n });\n }\n }\n\n return { media, inlinedIndices };\n}\n\n/**\n * Build the structured multimodal turn.\n *\n * `promptText` MUST be the exact string also sent as `prompt`, so the two\n * channels are equivalent: a bridge that understands `parts` sees everything a\n * text-only bridge sees, plus the images. Returns `undefined` when there is\n * nothing an image/file part could add, which keeps the wire body byte-identical\n * to a pre-multimodal client for every ordinary text turn.\n */\nexport function buildPromptParts(\n promptText: string,\n attachments: AssistantAttachment[]\n): AssistantPromptPart[] | undefined {\n const usable = getSendableAttachments(attachments);\n if (usable.length === 0) return undefined;\n\n const candidates = new Set(inlineImageCandidates(usable).map((attachment) => attachment.id));\n const { media, inlinedIndices } = composeMedia(usable, candidates);\n\n if (media.length === 0) return undefined;\n\n // ── Fit the body ───────────────────────────────────────────────────────────\n // Everything above decides what we WANT to send; this decides what the\n // gateway will accept. Demote inline images to url-only (dropping the part\n // entirely if it has no URL to fall back to) until the modelled body fits.\n // Doing it here, deterministically, is what keeps the 413 fallback in\n // AssistantChatArea a genuine safety net rather than the normal path.\n while (\n inlinedIndices.length > 0 &&\n estimateTurnBodyBytes(promptText, [{ type: 'text', text: promptText }, ...media]) > MAX_INLINE_TURN_BODY_BYTES\n ) {\n const index = inlinedIndices.pop();\n if (index === undefined) break;\n const part = media[index];\n if (!part || part.type === 'text') continue;\n if (part.url) {\n media[index] = { type: part.type, mimeType: part.mimeType, url: part.url, name: part.name };\n } else {\n // Safe to splice: we always pop the highest remaining index, so no index\n // still in `inlinedIndices` can be shifted by this removal.\n media.splice(index, 1);\n }\n }\n\n if (media.length === 0) return undefined;\n\n // Nothing left to demote and still over the cap. Sending anyway would be a\n // CERTAIN 413, and `parts[0]` duplicates the whole prompt — so a long message\n // with one attachment can exceed the cap on prompt text alone, in a case\n // where the identical message with no attachment would have gone through.\n // Drop the parts entirely: the attachment block and its URLs are still in the\n // prompt, so the model keeps everything except the pixels.\n if (estimateTurnBodyBytes(promptText, [{ type: 'text', text: promptText }, ...media]) > MAX_INLINE_TURN_BODY_BYTES) {\n return undefined;\n }\n\n return [{ type: 'text', text: promptText }, ...media];\n}\n"],"mappings":";;AAuCA,IAAa,IAAiB,KAAK,OAAO,MAG7B,IAA4B,KAG5B,IAAyB,KAgBzB,IAAb,cAA6C,MAAM;CACjD,YAAY,GAAsC;AAEhD,EADA,MAAM,EAAO,EADM,KAAA,SAAA,GAEnB,KAAK,OAAO;;;AAiFhB,SAAgB,EAAoB,GAA6D;AAC/F,QAAO;EACL,IAAI,EAAW;EACf,UAAU,EAAW;EACrB,UAAU,EAAW;EACrB,MAAM,EAAW;EACjB,MAAM,EAAW;EACjB,QAAQ,EAAW;EACpB;;AAOH,IAAM,IAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAEF,SAAgB,EAAa,GAA0B;CACrD,IAAM,IAAM,EAAS,YAAY,IAAI;AACrC,QAAO,KAAO,IAAI,EAAS,MAAM,IAAM,EAAE,CAAC,aAAa,GAAG;;AAG5D,SAAgB,EAAmB,GAAkB,GAA2C;AAW9F,QAVI,EAAS,WAAW,SAAS,GAAS,UAExC,EAAS,WAAW,QAAQ,IAC5B,MAAa,sBACb,MAAa,qBACb,MAAa,wBACb,EAAgB,IAAI,EAAa,EAAS,CAAC,GAEpC,SAEF;;AAWT,IAAM,IAAsD;CAC1D,mBAAmB;C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;GACzB,IAAM,IAAO,EAAM;AACf,IAAC,KAAQ,EAAK,SAAS,WACvB,EAAK,MACP,EAAM,KAAS;IAAE,MAAM,EAAK;IAAM,UAAU,EAAK;IAAU,KAAK,EAAK;IAAK,MAAM,EAAK;IAAM,GAI3F,EAAM,OAAO,GAAO,EAAE;;AAItB,QAAM,WAAW,KAQjB,IAAsB,GAAY,CAAC;GAAE,MAAM;GAAQ,MAAM;GAAY,EAAE,GAAG,EAAM,CAAC,GAAG,GAIxF,QAAO,CAAC;GAAE,MAAM;GAAQ,MAAM;GAAY,EAAE,GAAG,EAAM"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@burdenoff/microfe-healthybowl",
|
|
3
|
-
"version": "2026.813.
|
|
3
|
+
"version": "2026.813.19",
|
|
4
4
|
"description": "Burdenoff HealthyBowl Microfrontend - Comprehensive organic farming and agro-foods management platform",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -48,7 +48,7 @@
|
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
50
|
"@apollo/client": "^4.0.11",
|
|
51
|
-
"@burdenoff/fe-libs": "2026.
|
|
51
|
+
"@burdenoff/fe-libs": "2026.813.3",
|
|
52
52
|
"@burdenoff/planmagnet-fe-sdk": "2026.708.1",
|
|
53
53
|
"@tanstack/react-query": "^5.90.16",
|
|
54
54
|
"clsx": "^2.1.1",
|