@burdenoff/microfe-healthybowl 2026.812.21 → 2026.812.22
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/composer/AssistantAttachmentButton.js +19 -19
- package/dist/components/assistant/composer/AssistantAttachmentButton.js.map +1 -1
- package/dist/hooks/useAssistantAttachments.js +82 -63
- package/dist/hooks/useAssistantAttachments.js.map +1 -1
- package/dist/node_modules/fflate/esm/browser.js +326 -0
- package/dist/node_modules/fflate/esm/browser.js.map +1 -0
- package/dist/node_modules/pdfjs-dist/build/pdf.js +16384 -0
- package/dist/node_modules/pdfjs-dist/build/pdf.js.map +1 -0
- package/dist/node_modules/pdfjs-dist/build/pdf.worker.min.js +52129 -0
- package/dist/node_modules/pdfjs-dist/build/pdf.worker.min.js.map +1 -0
- package/dist/utils/assistantAttachments.js +243 -61
- package/dist/utils/assistantAttachments.js.map +1 -1
- package/dist/utils/documentExtract.js +135 -0
- package/dist/utils/documentExtract.js.map +1 -0
- package/dist/utils/documentText.js +237 -0
- package/dist/utils/documentText.js.map +1 -0
- package/package.json +3 -1
|
@@ -1,35 +1,35 @@
|
|
|
1
1
|
import { useTr as e } from "../../../shared/hooks/useTr.js";
|
|
2
|
-
import "../../../utils/assistantAttachments.js";
|
|
3
|
-
import { useCallback as
|
|
4
|
-
import { Plus as
|
|
5
|
-
import { Fragment as
|
|
2
|
+
import { ATTACHMENT_ACCEPT as t } from "../../../utils/assistantAttachments.js";
|
|
3
|
+
import { useCallback as n, useRef as r } from "react";
|
|
4
|
+
import { Plus as i } from "lucide-react";
|
|
5
|
+
import { Fragment as a, jsx as o, jsxs as s } from "react/jsx-runtime";
|
|
6
6
|
//#region src/components/assistant/composer/AssistantAttachmentButton.tsx
|
|
7
|
-
var
|
|
8
|
-
let
|
|
9
|
-
return /* @__PURE__ */
|
|
10
|
-
ref:
|
|
7
|
+
var c = ({ onFiles: c, canAddMore: l, disabled: u = !1 }) => {
|
|
8
|
+
let d = e(), f = r(null), p = l ? d("healthybowl.assistant.composer.attach", "Attach files or photos") : d("healthybowl.assistant.composer.attachFull", "Attachment limit reached ({{max}})", { max: 5 });
|
|
9
|
+
return /* @__PURE__ */ s(a, { children: [/* @__PURE__ */ o("input", {
|
|
10
|
+
ref: f,
|
|
11
11
|
type: "file",
|
|
12
12
|
multiple: !0,
|
|
13
|
-
accept:
|
|
13
|
+
accept: t,
|
|
14
14
|
className: "hidden",
|
|
15
|
-
onChange:
|
|
16
|
-
|
|
17
|
-
}, [
|
|
15
|
+
onChange: n((e) => {
|
|
16
|
+
c(e.target.files), e.target.value = "";
|
|
17
|
+
}, [c]),
|
|
18
18
|
tabIndex: -1,
|
|
19
19
|
"aria-hidden": "true",
|
|
20
20
|
"data-testid": "assistant-attach-input"
|
|
21
|
-
}), /* @__PURE__ */
|
|
21
|
+
}), /* @__PURE__ */ o("button", {
|
|
22
22
|
type: "button",
|
|
23
|
-
onClick: () =>
|
|
24
|
-
disabled:
|
|
25
|
-
title:
|
|
26
|
-
"aria-label":
|
|
23
|
+
onClick: () => f.current?.click(),
|
|
24
|
+
disabled: u || !l,
|
|
25
|
+
title: p,
|
|
26
|
+
"aria-label": p,
|
|
27
27
|
className: "flex size-9 flex-shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-sunken hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-not-allowed disabled:text-text-muted disabled:hover:bg-bg-elevated",
|
|
28
28
|
"data-testid": "assistant-attach",
|
|
29
|
-
children: /* @__PURE__ */
|
|
29
|
+
children: /* @__PURE__ */ o(i, { className: "size-4" })
|
|
30
30
|
})] });
|
|
31
31
|
};
|
|
32
32
|
//#endregion
|
|
33
|
-
export {
|
|
33
|
+
export { c as AssistantAttachmentButton };
|
|
34
34
|
|
|
35
35
|
//# sourceMappingURL=AssistantAttachmentButton.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantAttachmentButton.js","names":[],"sources":["../../../../src/components/assistant/composer/AssistantAttachmentButton.tsx"],"sourcesContent":["import { useCallback, useRef, type ChangeEvent, type FC } from 'react';\nimport { Plus } from 'lucide-react';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { MAX_ATTACHMENTS } from '@/utils/assistantAttachments';\n\ninterface Props {\n onFiles: (files: FileList | null) => void;\n /** False once MAX_ATTACHMENTS is reached — the control explains why. */\n canAddMore: boolean;\n disabled?: boolean;\n}\n\n/**\n * Leading circular \"+\" attach control in the composer (Workstream 3). Opens the\n * native picker over a hidden multi-file input; drag-drop and paste are handled\n * by the composer itself so all three entry points converge on `onFiles`.\n *\n * `accept` is advisory — the picker still allows \"All files\" on most platforms —\n * so validation lives in `validateFile`, not here.\n */\nexport const AssistantAttachmentButton: FC<Props> = ({ onFiles, canAddMore, disabled = false }) => {\n const tr = useTr();\n const inputRef = useRef<HTMLInputElement>(null);\n\n const label = canAddMore\n ? tr('healthybowl.assistant.composer.attach', 'Attach files or photos')\n : tr('healthybowl.assistant.composer.attachFull', 'Attachment limit reached ({{max}})', {\n max: MAX_ATTACHMENTS,\n });\n\n const handleChange = useCallback(\n (event: ChangeEvent<HTMLInputElement>) => {\n onFiles(event.target.files);\n // Reset so picking the SAME file twice in a row still fires a change event.\n event.target.value = '';\n },\n [onFiles]\n );\n\n return (\n <>\n <input\n ref={inputRef}\n type=\"file\"\n multiple\n accept
|
|
1
|
+
{"version":3,"file":"AssistantAttachmentButton.js","names":[],"sources":["../../../../src/components/assistant/composer/AssistantAttachmentButton.tsx"],"sourcesContent":["import { useCallback, useRef, type ChangeEvent, type FC } from 'react';\nimport { Plus } from 'lucide-react';\nimport { useTr } from '../../../shared/hooks/useTr';\nimport { ATTACHMENT_ACCEPT, MAX_ATTACHMENTS } from '@/utils/assistantAttachments';\n\ninterface Props {\n onFiles: (files: FileList | null) => void;\n /** False once MAX_ATTACHMENTS is reached — the control explains why. */\n canAddMore: boolean;\n disabled?: boolean;\n}\n\n/**\n * Leading circular \"+\" attach control in the composer (Workstream 3). Opens the\n * native picker over a hidden multi-file input; drag-drop and paste are handled\n * by the composer itself so all three entry points converge on `onFiles`.\n *\n * `accept` is advisory — the picker still allows \"All files\" on most platforms —\n * so validation lives in `validateFile`, not here. It is nonetheless the app's\n * only PROMISE about what the assistant can read, which is why it is derived\n * from the classifier/extractor tables (`ATTACHMENT_ACCEPT`) rather than typed\n * out: the previous hand-written list advertised .pdf/.docx/.xlsx a year before\n * anything could open them.\n */\nexport const AssistantAttachmentButton: FC<Props> = ({ onFiles, canAddMore, disabled = false }) => {\n const tr = useTr();\n const inputRef = useRef<HTMLInputElement>(null);\n\n const label = canAddMore\n ? tr('healthybowl.assistant.composer.attach', 'Attach files or photos')\n : tr('healthybowl.assistant.composer.attachFull', 'Attachment limit reached ({{max}})', {\n max: MAX_ATTACHMENTS,\n });\n\n const handleChange = useCallback(\n (event: ChangeEvent<HTMLInputElement>) => {\n onFiles(event.target.files);\n // Reset so picking the SAME file twice in a row still fires a change event.\n event.target.value = '';\n },\n [onFiles]\n );\n\n return (\n <>\n <input\n ref={inputRef}\n type=\"file\"\n multiple\n accept={ATTACHMENT_ACCEPT}\n className=\"hidden\"\n onChange={handleChange}\n tabIndex={-1}\n aria-hidden=\"true\"\n data-testid=\"assistant-attach-input\"\n />\n <button\n type=\"button\"\n onClick={() => inputRef.current?.click()}\n disabled={disabled || !canAddMore}\n title={label}\n aria-label={label}\n className=\"flex size-9 flex-shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-elevated text-text-secondary transition-colors hover:bg-bg-sunken hover:text-text-primary focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong disabled:cursor-not-allowed disabled:text-text-muted disabled:hover:bg-bg-elevated\"\n data-testid=\"assistant-attach\"\n >\n <Plus className=\"size-4\" />\n </button>\n </>\n );\n};\n"],"mappings":";;;;;;AAwBA,IAAa,KAAwC,EAAE,YAAS,eAAY,cAAW,SAAY;CACjG,IAAM,IAAK,GAAO,EACZ,IAAW,EAAyB,KAAK,EAEzC,IAAQ,IACV,EAAG,yCAAyC,yBAAyB,GACrE,EAAG,6CAA6C,sCAAsC,EACpF,KAAA,GACD,CAAC;AAWN,QACE,kBAAA,GAAA,EAAA,UAAA,CACE,kBAAC,SAAD;EACE,KAAK;EACL,MAAK;EACL,UAAA;EACA,QAAQ;EACR,WAAU;EACV,UAjBe,GAClB,MAAyC;AAGxC,GAFA,EAAQ,EAAM,OAAO,MAAM,EAE3B,EAAM,OAAO,QAAQ;KAEvB,CAAC,EAAQ,CACV;EAWK,UAAU;EACV,eAAY;EACZ,eAAY;EACZ,CAAA,EACF,kBAAC,UAAD;EACE,MAAK;EACL,eAAe,EAAS,SAAS,OAAO;EACxC,UAAU,KAAY,CAAC;EACvB,OAAO;EACP,cAAY;EACZ,WAAU;EACV,eAAY;YAEZ,kBAAC,GAAD,EAAM,WAAU,UAAW,CAAA;EACpB,CAAA,CACR,EAAA,CAAA"}
|
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
import { getWorkspaceId as e } from "../utils/assistantContext.js";
|
|
2
|
-
import { AttachmentRejectedError as t, INLINE_IMAGE_QUALITY as n, MAX_INLINE_CHARS_PER_FILE as r, classifyAttachment as i,
|
|
3
|
-
import { downscaleImage as
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
2
|
+
import { AttachmentRejectedError as t, INLINE_IMAGE_QUALITY as n, MAX_INLINE_CHARS_PER_FILE as r, classifyAttachment as i, detectDocumentFormat as a, hasAttachmentWorkInFlight as o, truncateForInline as s, validateFile as c } from "../utils/assistantAttachments.js";
|
|
3
|
+
import { downscaleImage as l } from "../healthybowl/utils/imageDownscale.js";
|
|
4
|
+
import { extractDocumentText as u } from "../utils/documentExtract.js";
|
|
5
|
+
import { useCallback as d, useEffect as f, useRef as p, useState as m } from "react";
|
|
6
|
+
import { useSaveToFiles as h } from "@burdenoff/fe-libs/storage";
|
|
7
|
+
import { graphqlFetch as g } from "@burdenoff/fe-libs/shared/graphql";
|
|
7
8
|
//#region src/hooks/useAssistantAttachments.ts
|
|
8
|
-
var
|
|
9
|
-
async function
|
|
9
|
+
var _ = "/HealthyBowl/AI Assistant/Attachments", v = "\n query HealthyBowlAssistantAttachmentUrl($id: ID!) {\n getFileDownloadUrl(id: $id)\n }\n";
|
|
10
|
+
async function y(e, t) {
|
|
10
11
|
if (!e || !t) return null;
|
|
11
12
|
try {
|
|
12
|
-
return (await
|
|
13
|
+
return (await g({
|
|
13
14
|
gateway: "workspace",
|
|
14
|
-
query:
|
|
15
|
+
query: v,
|
|
15
16
|
variables: { id: e },
|
|
16
17
|
workspaceToken: !0,
|
|
17
18
|
workspaceId: t,
|
|
@@ -21,17 +22,17 @@ async function _(e, t) {
|
|
|
21
22
|
return null;
|
|
22
23
|
}
|
|
23
24
|
}
|
|
24
|
-
var
|
|
25
|
-
function
|
|
26
|
-
return
|
|
25
|
+
var b = 0;
|
|
26
|
+
function x() {
|
|
27
|
+
return b += 1, `att-${Date.now()}-${b}`;
|
|
27
28
|
}
|
|
28
|
-
async function
|
|
29
|
-
let
|
|
30
|
-
id:
|
|
29
|
+
async function S(e) {
|
|
30
|
+
let o = i(e.type, e.name), c = {
|
|
31
|
+
id: x(),
|
|
31
32
|
status: "pending"
|
|
32
33
|
};
|
|
33
|
-
if (
|
|
34
|
-
let r = await
|
|
34
|
+
if (o === "image") {
|
|
35
|
+
let r = await l(e, {
|
|
35
36
|
encodeFallback: !1,
|
|
36
37
|
inline: {
|
|
37
38
|
maxDim: 768,
|
|
@@ -41,59 +42,77 @@ async function b(e) {
|
|
|
41
42
|
if (!r.downscaled && r.blob.size > 10485760) throw new t("unsupported-image");
|
|
42
43
|
return {
|
|
43
44
|
attachment: {
|
|
44
|
-
...
|
|
45
|
+
...c,
|
|
45
46
|
filename: r.filename,
|
|
46
47
|
mimeType: r.mimeType,
|
|
47
48
|
size: r.blob.size,
|
|
48
|
-
kind:
|
|
49
|
+
kind: o,
|
|
49
50
|
previewUrl: r.dataUrl || void 0,
|
|
50
51
|
inlineDataUrl: r.inlineDataUrl
|
|
51
52
|
},
|
|
52
53
|
blob: r.blob
|
|
53
54
|
};
|
|
54
55
|
}
|
|
55
|
-
if (
|
|
56
|
-
let { text: t, truncated: n } =
|
|
56
|
+
if (o === "text") {
|
|
57
|
+
let { text: t, truncated: n } = s(await e.text(), r);
|
|
57
58
|
return {
|
|
58
59
|
attachment: {
|
|
59
|
-
...
|
|
60
|
+
...c,
|
|
60
61
|
filename: e.name,
|
|
61
62
|
mimeType: e.type || "text/plain",
|
|
62
63
|
size: e.size,
|
|
63
|
-
kind:
|
|
64
|
+
kind: o,
|
|
64
65
|
textContent: t,
|
|
65
66
|
textTruncated: n
|
|
66
67
|
},
|
|
67
68
|
blob: e
|
|
68
69
|
};
|
|
69
70
|
}
|
|
71
|
+
let d = a(e.type, e.name);
|
|
72
|
+
if (d) {
|
|
73
|
+
let t = await u(e, d);
|
|
74
|
+
return {
|
|
75
|
+
attachment: {
|
|
76
|
+
...c,
|
|
77
|
+
filename: e.name,
|
|
78
|
+
mimeType: e.type || "application/octet-stream",
|
|
79
|
+
size: e.size,
|
|
80
|
+
kind: o,
|
|
81
|
+
extraction: t.extraction,
|
|
82
|
+
textContent: t.textContent,
|
|
83
|
+
textTruncated: t.textTruncated,
|
|
84
|
+
documentPages: t.documentPages
|
|
85
|
+
},
|
|
86
|
+
blob: e
|
|
87
|
+
};
|
|
88
|
+
}
|
|
70
89
|
return {
|
|
71
90
|
attachment: {
|
|
72
|
-
...
|
|
91
|
+
...c,
|
|
73
92
|
filename: e.name,
|
|
74
93
|
mimeType: e.type || "application/octet-stream",
|
|
75
94
|
size: e.size,
|
|
76
|
-
kind:
|
|
95
|
+
kind: o
|
|
77
96
|
},
|
|
78
97
|
blob: e
|
|
79
98
|
};
|
|
80
99
|
}
|
|
81
|
-
function
|
|
82
|
-
let { save: n } =
|
|
83
|
-
|
|
100
|
+
function C() {
|
|
101
|
+
let { save: n } = h(), [r, i] = m([]), [a, s] = m(null), l = p(Promise.resolve()), [u, g] = m(0), v = p(0), b = p(/* @__PURE__ */ new Map()), x = p(/* @__PURE__ */ new Set()), C = p(0), w = p(!0);
|
|
102
|
+
f(() => () => {
|
|
84
103
|
w.current = !1;
|
|
85
104
|
}, []);
|
|
86
|
-
let T =
|
|
87
|
-
|
|
105
|
+
let T = p([]);
|
|
106
|
+
f(() => {
|
|
88
107
|
T.current = r;
|
|
89
108
|
}, [r]);
|
|
90
|
-
let E =
|
|
109
|
+
let E = d((e, t) => {
|
|
91
110
|
w.current && i((n) => n.map((n) => n.id === e ? {
|
|
92
111
|
...n,
|
|
93
112
|
...t
|
|
94
113
|
} : n));
|
|
95
|
-
}, []), D =
|
|
96
|
-
if (!
|
|
114
|
+
}, []), D = d(async ({ attachment: t, blob: r }) => {
|
|
115
|
+
if (!x.current.has(t.id)) {
|
|
97
116
|
E(t.id, { status: "uploading" });
|
|
98
117
|
try {
|
|
99
118
|
let i = await n({
|
|
@@ -107,19 +126,19 @@ function x() {
|
|
|
107
126
|
mimeType: t.mimeType
|
|
108
127
|
})
|
|
109
128
|
},
|
|
110
|
-
folderPath:
|
|
129
|
+
folderPath: _
|
|
111
130
|
});
|
|
112
|
-
if (
|
|
113
|
-
let a = i?.id ? await
|
|
114
|
-
if (
|
|
131
|
+
if (x.current.has(t.id)) return;
|
|
132
|
+
let a = i?.id ? await y(i.id, e()) : null;
|
|
133
|
+
if (x.current.has(t.id)) return;
|
|
115
134
|
E(t.id, {
|
|
116
135
|
status: "ready",
|
|
117
136
|
fileId: i?.id,
|
|
118
137
|
downloadUrl: a ?? void 0
|
|
119
138
|
});
|
|
120
139
|
} catch (e) {
|
|
121
|
-
if (
|
|
122
|
-
if (t.kind === "text") {
|
|
140
|
+
if (x.current.has(t.id)) return;
|
|
141
|
+
if (t.kind === "text" || t.textContent) {
|
|
123
142
|
E(t.id, { status: "ready" });
|
|
124
143
|
return;
|
|
125
144
|
}
|
|
@@ -129,49 +148,49 @@ function x() {
|
|
|
129
148
|
});
|
|
130
149
|
}
|
|
131
150
|
}
|
|
132
|
-
}, [E, n]), O =
|
|
151
|
+
}, [E, n]), O = d((e) => {
|
|
133
152
|
if (!e) return;
|
|
134
153
|
let n = Array.from(e);
|
|
135
154
|
if (n.length === 0) return;
|
|
136
|
-
|
|
155
|
+
s(null);
|
|
137
156
|
let r = [];
|
|
138
157
|
for (let e of n) {
|
|
139
|
-
let t =
|
|
158
|
+
let t = c(e, C.current);
|
|
140
159
|
if (t) {
|
|
141
|
-
|
|
160
|
+
s(t);
|
|
142
161
|
continue;
|
|
143
162
|
}
|
|
144
163
|
r.push(e), C.current += 1;
|
|
145
164
|
}
|
|
146
165
|
if (r.length !== 0) {
|
|
147
|
-
|
|
166
|
+
g((e) => e + r.length);
|
|
148
167
|
for (let e of r) {
|
|
149
|
-
let n =
|
|
150
|
-
|
|
168
|
+
let n = v.current;
|
|
169
|
+
l.current = l.current.then(async () => {
|
|
151
170
|
let r = null;
|
|
152
171
|
try {
|
|
153
|
-
r = await
|
|
172
|
+
r = await S(e);
|
|
154
173
|
} catch (e) {
|
|
155
|
-
C.current = Math.max(0, C.current - 1), w.current &&
|
|
174
|
+
C.current = Math.max(0, C.current - 1), w.current && s(e instanceof t ? e.reason : "unreadable");
|
|
156
175
|
}
|
|
157
|
-
if (!w.current || (
|
|
158
|
-
if (n !==
|
|
176
|
+
if (!w.current || (g((e) => Math.max(0, e - 1)), !r)) return;
|
|
177
|
+
if (n !== v.current) {
|
|
159
178
|
C.current = Math.max(0, C.current - 1);
|
|
160
179
|
return;
|
|
161
180
|
}
|
|
162
181
|
let a = r;
|
|
163
|
-
|
|
182
|
+
b.current.set(a.attachment.id, a.blob), i((e) => [...e, a.attachment]), await D(a);
|
|
164
183
|
});
|
|
165
184
|
}
|
|
166
185
|
}
|
|
167
|
-
}, [D]), k =
|
|
168
|
-
|
|
169
|
-
}, []), A =
|
|
170
|
-
let t = T.current.find((t) => t.id === e), n =
|
|
171
|
-
!t || t.status !== "error" || !n || (
|
|
186
|
+
}, [D]), k = d((e) => {
|
|
187
|
+
x.current.add(e), b.current.delete(e), C.current = Math.max(0, C.current - 1), i((t) => t.filter((t) => t.id !== e));
|
|
188
|
+
}, []), A = d((e) => {
|
|
189
|
+
let t = T.current.find((t) => t.id === e), n = b.current.get(e);
|
|
190
|
+
!t || t.status !== "error" || !n || (x.current.delete(e), E(e, {
|
|
172
191
|
status: "pending",
|
|
173
192
|
error: void 0
|
|
174
|
-
}),
|
|
193
|
+
}), l.current = l.current.then(() => D({
|
|
175
194
|
attachment: {
|
|
176
195
|
...t,
|
|
177
196
|
status: "pending",
|
|
@@ -179,22 +198,22 @@ function x() {
|
|
|
179
198
|
},
|
|
180
199
|
blob: n
|
|
181
200
|
})));
|
|
182
|
-
}, [E, D]), j =
|
|
183
|
-
|
|
201
|
+
}, [E, D]), j = d(() => {
|
|
202
|
+
v.current += 1, C.current = 0, T.current.forEach((e) => x.current.add(e.id)), b.current.clear(), i([]);
|
|
184
203
|
}, []);
|
|
185
204
|
return {
|
|
186
205
|
attachments: r,
|
|
187
|
-
isBusy:
|
|
188
|
-
rejection:
|
|
206
|
+
isBusy: o(u, r),
|
|
207
|
+
rejection: a,
|
|
189
208
|
addFiles: O,
|
|
190
209
|
remove: k,
|
|
191
210
|
retry: A,
|
|
192
211
|
clear: j,
|
|
193
|
-
clearRejection:
|
|
212
|
+
clearRejection: d(() => s(null), []),
|
|
194
213
|
canAddMore: C.current < 5
|
|
195
214
|
};
|
|
196
215
|
}
|
|
197
216
|
//#endregion
|
|
198
|
-
export {
|
|
217
|
+
export { C as useAssistantAttachments };
|
|
199
218
|
|
|
200
219
|
//# 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 → preview → upload to the workspace file\n * library → resolve a presigned URL → ready. Each attachment carries its own\n * status, so one slow or failed upload never blocks 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 * Text-like files degrade gracefully: their content is inlined into the prompt,\n * so a failed upload still leaves a usable attachment (it just has no URL).\n * Images and binaries have nothing to fall back on and are marked failed.\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 hasAttachmentWorkInFlight,\n truncateForInline,\n validateFile,\n type AssistantAttachment,\n type AttachmentRejection,\n} from '@/utils/assistantAttachments';\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 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 /** 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 // A text file's content is already inlined in the prompt, so losing the\n // upload costs only the URL — still worth sending. Anything else is dead\n // weight without its bytes.\n if (attachment.kind === 'text') {\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 isBusy = hasAttachmentWorkInFlight(preparingCount, attachments);\n\n return {\n attachments,\n isBusy,\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":";;;;;;;AAuCA,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,MAA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AAc,QAAQ,IAAI,EAAW,GAAG,CAAC,EACxF,EAAS,QAAQ,OAAO,EACxB,EAAe,EAAE,CAAC;IACjB,EAAE,CAAC;AAIN,QAAO;EACL;EACA,QAJa,EAA0B,GAAgB,EAAY;EAKnE;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 * Text-like files degrade gracefully: their content is inlined into the prompt,\n * so a failed upload still leaves a usable attachment (it just has no URL).\n * Images and binaries have nothing to fall back on and are marked failed.\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 hasAttachmentWorkInFlight,\n truncateForInline,\n validateFile,\n type AssistantAttachment,\n type AttachmentRejection,\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 /** 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 isBusy = hasAttachmentWorkInFlight(preparingCount, attachments);\n\n return {\n attachments,\n isBusy,\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 pr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