@burdenoff/microfe-healthybowl 2026.725.5 → 2026.725.6
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/AssistantMarkdownRenderer.js +60 -57
- package/dist/components/assistant/AssistantMarkdownRenderer.js.map +1 -1
- package/dist/components/assistant/AssistantMessageItem.js +72 -69
- package/dist/components/assistant/AssistantMessageItem.js.map +1 -1
- package/dist/utils/assistantAttachments.js +1 -1
- package/dist/utils/assistantAttachments.js.map +1 -1
- package/dist/utils/clipboard.js +12 -0
- package/dist/utils/clipboard.js.map +1 -0
- package/package.json +1 -1
|
@@ -3,47 +3,50 @@ import { Markdown as t, defaultUrlTransform as n } from "../../node_modules/reac
|
|
|
3
3
|
import r from "../../node_modules/remark-gfm/lib/index.js";
|
|
4
4
|
import { defaultSchema as i } from "../../node_modules/hast-util-sanitize/lib/schema.js";
|
|
5
5
|
import a from "../../node_modules/rehype-sanitize/lib/index.js";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
6
|
+
import { copyToClipboard as o } from "../../utils/clipboard.js";
|
|
7
|
+
import { AssistantMarkdownImage as s } from "./AssistantMarkdownImage.js";
|
|
8
|
+
import { useState as c } from "react";
|
|
9
|
+
import { Check as l, Copy as u } from "lucide-react";
|
|
10
|
+
import { Fragment as d, jsx as f, jsxs as p } from "react/jsx-runtime";
|
|
10
11
|
//#region src/components/assistant/AssistantMarkdownRenderer.tsx
|
|
11
|
-
var
|
|
12
|
+
var m = {
|
|
12
13
|
...i,
|
|
13
14
|
protocols: {
|
|
14
15
|
...i.protocols,
|
|
15
16
|
src: [...i.protocols?.src ?? [], "data"]
|
|
16
17
|
}
|
|
17
|
-
},
|
|
18
|
-
function
|
|
19
|
-
let r = e(), [i, a] =
|
|
20
|
-
return /* @__PURE__ */
|
|
18
|
+
}, h = /^data:image\/(?:png|jpe?g|gif|webp|avif|bmp);base64,[A-Za-z0-9+/=\s]+$/, g = (e, t, r) => t === "src" && r.tagName === "img" && h.test(e) ? e : n(e), _ = [r], v = [[a, m]];
|
|
19
|
+
function y({ language: t, code: n }) {
|
|
20
|
+
let r = e(), [i, a] = c(!1);
|
|
21
|
+
return /* @__PURE__ */ p("div", {
|
|
21
22
|
className: "group relative my-2 overflow-hidden rounded-md border border-border-default bg-bg-sunken",
|
|
22
|
-
children: [/* @__PURE__ */
|
|
23
|
+
children: [/* @__PURE__ */ p("div", {
|
|
23
24
|
className: "flex items-center justify-between border-b border-border-default bg-bg-elevated px-3 py-1.5",
|
|
24
|
-
children: [/* @__PURE__ */
|
|
25
|
+
children: [/* @__PURE__ */ f("span", {
|
|
25
26
|
className: "font-mono text-[10px] uppercase tracking-wider text-text-muted",
|
|
26
27
|
children: t || "code"
|
|
27
|
-
}), /* @__PURE__ */
|
|
28
|
+
}), /* @__PURE__ */ f("button", {
|
|
28
29
|
type: "button",
|
|
29
30
|
onClick: () => {
|
|
30
|
-
|
|
31
|
+
o(n).then((e) => {
|
|
32
|
+
e && (a(!0), setTimeout(() => a(!1), 2e3));
|
|
33
|
+
});
|
|
31
34
|
},
|
|
32
35
|
className: "flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] text-text-secondary transition-colors hover:bg-bg-sunken hover:text-text-primary",
|
|
33
36
|
"aria-label": r("healthybowl.assistant.markdown.copyCode", "Copy code"),
|
|
34
37
|
"data-testid": "assistant-markdown-copy-code",
|
|
35
|
-
children: i ? /* @__PURE__ */
|
|
38
|
+
children: i ? /* @__PURE__ */ p(d, { children: [/* @__PURE__ */ f(l, { className: "size-3 text-status-success-text" }), /* @__PURE__ */ f("span", { children: r("healthybowl.assistant.markdown.copied", "Copied") })] }) : /* @__PURE__ */ p(d, { children: [/* @__PURE__ */ f(u, { className: "size-3" }), /* @__PURE__ */ f("span", { children: r("healthybowl.assistant.markdown.copy", "Copy") })] })
|
|
36
39
|
})]
|
|
37
|
-
}), /* @__PURE__ */
|
|
40
|
+
}), /* @__PURE__ */ f("pre", {
|
|
38
41
|
className: "overflow-x-auto p-3 text-xs leading-relaxed",
|
|
39
|
-
children: /* @__PURE__ */
|
|
42
|
+
children: /* @__PURE__ */ f("code", {
|
|
40
43
|
className: "font-mono text-text-primary",
|
|
41
44
|
children: n
|
|
42
45
|
})
|
|
43
46
|
})]
|
|
44
47
|
});
|
|
45
48
|
}
|
|
46
|
-
function
|
|
49
|
+
function b(e) {
|
|
47
50
|
let t = e?.children?.[0];
|
|
48
51
|
if (!t || t.type !== "element" || t.tagName !== "code") return null;
|
|
49
52
|
let n = t.children.map((e) => e.type === "text" ? e.value : "").join(""), r = t.properties?.className, i = (Array.isArray(r) ? r.map(String) : String(r ?? "").split(" ")).find((e) => e.startsWith("language-"));
|
|
@@ -52,10 +55,10 @@ function y(e) {
|
|
|
52
55
|
language: i ? i.slice(9) : ""
|
|
53
56
|
};
|
|
54
57
|
}
|
|
55
|
-
function
|
|
58
|
+
function x(e, t) {
|
|
56
59
|
return typeof e == "string" && e.split(" ").includes(t);
|
|
57
60
|
}
|
|
58
|
-
function
|
|
61
|
+
function S({ level: e, children: t }) {
|
|
59
62
|
let n = `h${e}`, r = {
|
|
60
63
|
2: "text-[1.15em]",
|
|
61
64
|
3: "text-[1.08em]",
|
|
@@ -63,13 +66,13 @@ function x({ level: e, children: t }) {
|
|
|
63
66
|
5: "text-[0.95em]",
|
|
64
67
|
6: "text-[0.9em]"
|
|
65
68
|
}[e];
|
|
66
|
-
return /* @__PURE__ */
|
|
69
|
+
return /* @__PURE__ */ f(n, {
|
|
67
70
|
className: `mb-1 mt-3 font-semibold text-text-primary ${r}`,
|
|
68
71
|
children: t
|
|
69
72
|
});
|
|
70
73
|
}
|
|
71
|
-
var
|
|
72
|
-
a: ({ href: e, children: t }) => /* @__PURE__ */
|
|
74
|
+
var C = {
|
|
75
|
+
a: ({ href: e, children: t }) => /* @__PURE__ */ f("a", {
|
|
73
76
|
href: e,
|
|
74
77
|
target: "_blank",
|
|
75
78
|
rel: "noopener noreferrer",
|
|
@@ -77,121 +80,121 @@ var S = {
|
|
|
77
80
|
"data-testid": "assistant-markdown-link",
|
|
78
81
|
children: t
|
|
79
82
|
}),
|
|
80
|
-
blockquote: ({ children: e }) => /* @__PURE__ */
|
|
83
|
+
blockquote: ({ children: e }) => /* @__PURE__ */ f("blockquote", {
|
|
81
84
|
className: "my-2 border-l-2 border-action-primary-bg pl-3 italic text-text-secondary",
|
|
82
85
|
children: e
|
|
83
86
|
}),
|
|
84
|
-
code: ({ children: e }) => /* @__PURE__ */
|
|
87
|
+
code: ({ children: e }) => /* @__PURE__ */ f("code", {
|
|
85
88
|
className: "rounded bg-bg-sunken px-1 py-0.5 font-mono text-[0.85em] text-text-primary",
|
|
86
89
|
children: e
|
|
87
90
|
}),
|
|
88
|
-
del: ({ children: e }) => /* @__PURE__ */
|
|
91
|
+
del: ({ children: e }) => /* @__PURE__ */ f("del", {
|
|
89
92
|
className: "text-text-muted line-through",
|
|
90
93
|
children: e
|
|
91
94
|
}),
|
|
92
|
-
em: ({ children: e }) => /* @__PURE__ */
|
|
95
|
+
em: ({ children: e }) => /* @__PURE__ */ f("em", {
|
|
93
96
|
className: "italic",
|
|
94
97
|
children: e
|
|
95
98
|
}),
|
|
96
|
-
h1: ({ children: e }) => /* @__PURE__ */
|
|
99
|
+
h1: ({ children: e }) => /* @__PURE__ */ f(S, {
|
|
97
100
|
level: 2,
|
|
98
101
|
children: e
|
|
99
102
|
}),
|
|
100
|
-
h2: ({ children: e }) => /* @__PURE__ */
|
|
103
|
+
h2: ({ children: e }) => /* @__PURE__ */ f(S, {
|
|
101
104
|
level: 3,
|
|
102
105
|
children: e
|
|
103
106
|
}),
|
|
104
|
-
h3: ({ children: e }) => /* @__PURE__ */
|
|
107
|
+
h3: ({ children: e }) => /* @__PURE__ */ f(S, {
|
|
105
108
|
level: 4,
|
|
106
109
|
children: e
|
|
107
110
|
}),
|
|
108
|
-
h4: ({ children: e }) => /* @__PURE__ */
|
|
111
|
+
h4: ({ children: e }) => /* @__PURE__ */ f(S, {
|
|
109
112
|
level: 5,
|
|
110
113
|
children: e
|
|
111
114
|
}),
|
|
112
|
-
h5: ({ children: e }) => /* @__PURE__ */
|
|
115
|
+
h5: ({ children: e }) => /* @__PURE__ */ f(S, {
|
|
113
116
|
level: 6,
|
|
114
117
|
children: e
|
|
115
118
|
}),
|
|
116
|
-
h6: ({ children: e }) => /* @__PURE__ */
|
|
119
|
+
h6: ({ children: e }) => /* @__PURE__ */ f(S, {
|
|
117
120
|
level: 6,
|
|
118
121
|
children: e
|
|
119
122
|
}),
|
|
120
|
-
hr: () => /* @__PURE__ */
|
|
121
|
-
img: ({ src: e, alt: t, title: n }) => /* @__PURE__ */
|
|
123
|
+
hr: () => /* @__PURE__ */ f("hr", { className: "my-3 border-border-default" }),
|
|
124
|
+
img: ({ src: e, alt: t, title: n }) => /* @__PURE__ */ f(s, {
|
|
122
125
|
src: typeof e == "string" ? e : void 0,
|
|
123
126
|
alt: t,
|
|
124
127
|
title: n
|
|
125
128
|
}),
|
|
126
|
-
input: ({ checked: e, type: t }) => t === "checkbox" ? /* @__PURE__ */
|
|
129
|
+
input: ({ checked: e, type: t }) => t === "checkbox" ? /* @__PURE__ */ f("input", {
|
|
127
130
|
type: "checkbox",
|
|
128
131
|
checked: !!e,
|
|
129
132
|
disabled: !0,
|
|
130
133
|
className: "mr-1.5 size-3 flex-shrink-0 align-[-0.1em] accent-[var(--color-action-primary-bg)]"
|
|
131
134
|
}) : null,
|
|
132
|
-
li: ({ className: e, children: t }) => /* @__PURE__ */
|
|
133
|
-
className:
|
|
135
|
+
li: ({ className: e, children: t }) => /* @__PURE__ */ f("li", {
|
|
136
|
+
className: x(e, "task-list-item") ? "list-none text-text-primary" : "text-text-primary",
|
|
134
137
|
children: t
|
|
135
138
|
}),
|
|
136
|
-
ol: ({ children: e }) => /* @__PURE__ */
|
|
139
|
+
ol: ({ children: e }) => /* @__PURE__ */ f("ol", {
|
|
137
140
|
className: "my-1.5 ml-5 list-decimal space-y-0.5",
|
|
138
141
|
children: e
|
|
139
142
|
}),
|
|
140
|
-
p: ({ children: e }) => /* @__PURE__ */
|
|
143
|
+
p: ({ children: e }) => /* @__PURE__ */ f("p", {
|
|
141
144
|
className: "my-1.5 leading-relaxed text-text-primary",
|
|
142
145
|
children: e
|
|
143
146
|
}),
|
|
144
147
|
pre: ({ children: e, node: t }) => {
|
|
145
|
-
let n =
|
|
146
|
-
return n ? /* @__PURE__ */
|
|
148
|
+
let n = b(t);
|
|
149
|
+
return n ? /* @__PURE__ */ f(y, {
|
|
147
150
|
language: n.language,
|
|
148
151
|
code: n.code
|
|
149
|
-
}) : /* @__PURE__ */
|
|
152
|
+
}) : /* @__PURE__ */ f("pre", {
|
|
150
153
|
className: "my-2 overflow-x-auto rounded-md border border-border-default bg-bg-sunken p-3 text-xs leading-relaxed",
|
|
151
154
|
children: e
|
|
152
155
|
});
|
|
153
156
|
},
|
|
154
|
-
strong: ({ children: e }) => /* @__PURE__ */
|
|
157
|
+
strong: ({ children: e }) => /* @__PURE__ */ f("strong", {
|
|
155
158
|
className: "font-semibold text-text-primary",
|
|
156
159
|
children: e
|
|
157
160
|
}),
|
|
158
|
-
table: ({ children: e }) => /* @__PURE__ */
|
|
161
|
+
table: ({ children: e }) => /* @__PURE__ */ f("div", {
|
|
159
162
|
className: "my-2 overflow-x-auto",
|
|
160
163
|
"data-testid": "assistant-markdown-table",
|
|
161
|
-
children: /* @__PURE__ */
|
|
164
|
+
children: /* @__PURE__ */ f("table", {
|
|
162
165
|
className: "w-full border-collapse text-[0.9em]",
|
|
163
166
|
children: e
|
|
164
167
|
})
|
|
165
168
|
}),
|
|
166
|
-
td: ({ children: e }) => /* @__PURE__ */
|
|
169
|
+
td: ({ children: e }) => /* @__PURE__ */ f("td", {
|
|
167
170
|
className: "px-2 py-1.5 align-top text-text-primary",
|
|
168
171
|
children: e
|
|
169
172
|
}),
|
|
170
|
-
th: ({ children: e }) => /* @__PURE__ */
|
|
173
|
+
th: ({ children: e }) => /* @__PURE__ */ f("th", {
|
|
171
174
|
scope: "col",
|
|
172
175
|
className: "px-2 py-1.5 text-left font-semibold text-text-primary",
|
|
173
176
|
children: e
|
|
174
177
|
}),
|
|
175
|
-
tr: ({ children: e }) => /* @__PURE__ */
|
|
178
|
+
tr: ({ children: e }) => /* @__PURE__ */ f("tr", {
|
|
176
179
|
className: "border-b border-border-subtle",
|
|
177
180
|
children: e
|
|
178
181
|
}),
|
|
179
|
-
ul: ({ className: e, children: t }) => /* @__PURE__ */
|
|
180
|
-
className:
|
|
182
|
+
ul: ({ className: e, children: t }) => /* @__PURE__ */ f("ul", {
|
|
183
|
+
className: x(e, "contains-task-list") ? "my-1.5 ml-0.5 list-none space-y-0.5" : "my-1.5 ml-5 list-disc space-y-0.5",
|
|
181
184
|
children: t
|
|
182
185
|
})
|
|
183
|
-
},
|
|
186
|
+
}, w = ({ content: e }) => /* @__PURE__ */ f("div", {
|
|
184
187
|
className: "break-words [&>*:first-child]:mt-0 [&>*:last-child]:mb-0",
|
|
185
188
|
"data-testid": "assistant-markdown",
|
|
186
|
-
children: /* @__PURE__ */
|
|
187
|
-
remarkPlugins:
|
|
188
|
-
rehypePlugins:
|
|
189
|
-
urlTransform:
|
|
190
|
-
components:
|
|
189
|
+
children: /* @__PURE__ */ f(t, {
|
|
190
|
+
remarkPlugins: _,
|
|
191
|
+
rehypePlugins: v,
|
|
192
|
+
urlTransform: g,
|
|
193
|
+
components: C,
|
|
191
194
|
children: e
|
|
192
195
|
})
|
|
193
196
|
});
|
|
194
197
|
//#endregion
|
|
195
|
-
export {
|
|
198
|
+
export { w as AssistantMarkdownRenderer };
|
|
196
199
|
|
|
197
200
|
//# sourceMappingURL=AssistantMarkdownRenderer.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantMarkdownRenderer.js","names":[],"sources":["../../../src/components/assistant/AssistantMarkdownRenderer.tsx"],"sourcesContent":["/**\n * Markdown renderer for assistant messages (Workstream 5).\n *\n * Replaces the previous hand-rolled regex renderer with react-markdown +\n * remark-gfm + rehype-sanitize, per the AI Assistant V2 spec. The regex version\n * had defects that only a real parser fixes: it emitted one `<p>` per SOURCE\n * line (shredding every soft-wrapped paragraph), emitted `<li>` elements with no\n * `<ul>`/`<ol>` parent at all (invalid markup that assistive tech does not\n * announce as a list), dropped empty table cells (shifting every later column),\n * and used a lookbehind assertion that throws at PARSE time on Safari < 16.4.\n * GFM also brings strikethrough, task lists and autolinks for free.\n *\n * ## Safety\n *\n * The assistant's output is attacker-reachable (prompt injection through a\n * scanned document, a shared field note, a marketplace listing), so it is\n * treated as untrusted HTML:\n *\n * - Raw HTML is NOT enabled (`rehype-raw` is deliberately absent), so markup\n * inside a reply is escaped rather than rendered.\n * - `rehype-sanitize` is the belt to that braces, running GitHub's default\n * schema with one deliberate widening — see `SANITIZE_SCHEMA`.\n * - `assistantUrlTransform` is a second, independent gate on every URL.\n *\n * `@/utils/sanitizeUrl` is intentionally no longer used here: link protocols are\n * now enforced twice over, by the sanitizer schema and by react-markdown's\n * `defaultUrlTransform`, both of which allow strictly less than it did.\n *\n * ## Type scale\n *\n * The V2 redesign sets assistant prose at 15px in AssistantMessageItem. The old\n * renderer hard-set `text-xs` on its root, which silently overrode that back to\n * 12px for every reply; the root now inherits, and the few size tweaks below are\n * `em`-relative so they scale with whatever the parent sets.\n */\n\nimport { useState, type FC, type ReactNode } from 'react';\nimport Markdown, { defaultUrlTransform, type Components, type ExtraProps, type Options } from 'react-markdown';\nimport remarkGfm from 'remark-gfm';\nimport rehypeSanitize, { defaultSchema } from 'rehype-sanitize';\nimport { Copy, Check } from 'lucide-react';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { AssistantMarkdownImage } from './AssistantMarkdownImage';\n\ninterface Props {\n content: string;\n}\n\n/** The hast element react-markdown hands to a custom component. */\ntype MarkdownNode = NonNullable<ExtraProps['node']>;\n\n/**\n * Sanitizer schema: GitHub's default, widened in exactly one place.\n *\n * `defaultSchema.protocols.src` is `['http', 'https']`. We add `data` so an\n * inline `` — how the sandbox returns a\n * generated image, with no upload round-trip — survives sanitisation.\n *\n * Why a `data:` **image** is safe but a `data:` **link** is not:\n *\n * - `<img src=\"data:...\">` is a *passive* fetch. The bytes are handed to the\n * image decoder, never to the HTML parser, so they cannot execute script or\n * touch this origin's DOM, cookies or tokens. Worst case is a picture the\n * farmer did not ask for.\n * - `<a href=\"data:text/html,...\">` is *active navigation*. One click and the\n * browser renders attacker-authored HTML as a real document — historically\n * in the opener's origin, and still a first-class phishing surface (a\n * pixel-perfect fake login page on a URL the user cannot inspect). So\n * `protocols.href` is left exactly as GitHub ships it.\n *\n * `protocols.cite` / `longDesc` are likewise untouched, and no tag or attribute\n * is added to the allow-lists (`language-*` on `code`, which gives the fenced\n * block its language label, is already permitted by the default schema).\n */\nconst SANITIZE_SCHEMA = {\n ...defaultSchema,\n protocols: {\n ...defaultSchema.protocols,\n src: [...(defaultSchema.protocols?.src ?? []), 'data'],\n },\n};\n\n/**\n * The sanitizer's protocol check is scheme-only — it would pass\n * `data:text/html` on an `<img>` just as happily as `data:image/png`. That is\n * inert in an image element, but \"inert today\" is a weak thing to rely on, so\n * the media type is pinned here as well.\n *\n * `svg+xml` is excluded on purpose: SVG is an active document format, and\n * keeping it out means no later change of ours can route one into an\n * `<object>`/`<embed>`/CSS `url()` context where its script would run.\n *\n * Scheme and media type are matched case-sensitively so this agrees with the\n * sanitizer, whose protocol comparison is also case-sensitive: a `DATA:` URL\n * loses its `src` there, and must not look allowed here.\n */\nconst DATA_IMAGE_URL = /^data:image\\/(?:png|jpe?g|gif|webp|avif|bmp);base64,[A-Za-z0-9+/=\\s]+$/;\n\n/** @internal Exported for unit tests; not part of the module's public surface. */\nexport const assistantUrlTransform: Options['urlTransform'] = (url, key, node) => {\n if (key === 'src' && node.tagName === 'img' && DATA_IMAGE_URL.test(url)) return url;\n // Everything else — every `href`, every remote `src` — falls back to\n // react-markdown's allow-list (http, https, irc, ircs, mailto, xmpp, and\n // relative URLs). Nothing is broadened.\n return defaultUrlTransform(url);\n};\n\nconst REMARK_PLUGINS: Options['remarkPlugins'] = [remarkGfm];\nconst REHYPE_PLUGINS: Options['rehypePlugins'] = [[rehypeSanitize, SANITIZE_SCHEMA]];\n\nfunction CodeBlock({ language, code }: { language: string; code: string }) {\n const tr = useTr();\n const [copied, setCopied] = useState(false);\n\n const handleCopy = () => {\n void navigator.clipboard?.writeText(code);\n setCopied(true);\n setTimeout(() => setCopied(false), 2000);\n };\n\n return (\n <div className=\"group relative my-2 overflow-hidden rounded-md border border-border-default bg-bg-sunken\">\n <div className=\"flex items-center justify-between border-b border-border-default bg-bg-elevated px-3 py-1.5\">\n <span className=\"font-mono text-[10px] uppercase tracking-wider text-text-muted\">{language || 'code'}</span>\n <button\n type=\"button\"\n onClick={handleCopy}\n className=\"flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] text-text-secondary transition-colors hover:bg-bg-sunken hover:text-text-primary\"\n aria-label={tr('healthybowl.assistant.markdown.copyCode', 'Copy code')}\n data-testid=\"assistant-markdown-copy-code\"\n >\n {copied ? (\n <>\n <Check className=\"size-3 text-status-success-text\" />\n <span>{tr('healthybowl.assistant.markdown.copied', 'Copied')}</span>\n </>\n ) : (\n <>\n <Copy className=\"size-3\" />\n <span>{tr('healthybowl.assistant.markdown.copy', 'Copy')}</span>\n </>\n )}\n </button>\n </div>\n <pre className=\"overflow-x-auto p-3 text-xs leading-relaxed\">\n <code className=\"font-mono text-text-primary\">{code}</code>\n </pre>\n </div>\n );\n}\n\n/**\n * Pull the text and language out of a fenced block.\n *\n * react-markdown no longer flags inline vs block code, so `pre` is overridden\n * instead and its `code` child read straight off the hast node — which is both\n * the reliable signal for \"this is a fence\" and the only place the raw,\n * unescaped source is available to hand to the copy button (walking the\n * rendered React children back to a string is lossy).\n */\nfunction readFencedCode(node: MarkdownNode | undefined): { code: string; language: string } | null {\n const child = node?.children?.[0];\n if (!child || child.type !== 'element' || child.tagName !== 'code') return null;\n\n const code = child.children.map((leaf) => (leaf.type === 'text' ? leaf.value : '')).join('');\n const className = child.properties?.className;\n const classes = Array.isArray(className) ? className.map(String) : String(className ?? '').split(' ');\n const languageClass = classes.find((entry) => entry.startsWith('language-'));\n\n return { code: code.replace(/\\n$/, ''), language: languageClass ? languageClass.slice('language-'.length) : '' };\n}\n\nfunction hasClass(className: string | undefined, name: string): boolean {\n return typeof className === 'string' && className.split(' ').includes(name);\n}\n\n/**\n * Markdown headings are demoted one level: this renderer draws inside a panel on\n * a page that already owns the document's `h1`, so an assistant `#` becomes an\n * `h2` and the heading outline stays sane for screen readers.\n */\nfunction Heading({ level, children }: { level: 2 | 3 | 4 | 5 | 6; children: ReactNode }) {\n const Tag = `h${level}` as const;\n const size = { 2: 'text-[1.15em]', 3: 'text-[1.08em]', 4: 'text-[1em]', 5: 'text-[0.95em]', 6: 'text-[0.9em]' }[\n level\n ];\n return <Tag className={`mb-1 mt-3 font-semibold text-text-primary ${size}`}>{children}</Tag>;\n}\n\nconst COMPONENTS: Components = {\n a: ({ href, children }) => (\n <a\n href={href}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"text-action-primary-bg underline-offset-2 hover:underline\"\n data-testid=\"assistant-markdown-link\"\n >\n {children}\n </a>\n ),\n\n blockquote: ({ children }) => (\n <blockquote className=\"my-2 border-l-2 border-action-primary-bg pl-3 italic text-text-secondary\">\n {children}\n </blockquote>\n ),\n\n // Only inline code reaches this: fenced blocks are consumed whole by `pre`.\n code: ({ children }) => (\n <code className=\"rounded bg-bg-sunken px-1 py-0.5 font-mono text-[0.85em] text-text-primary\">{children}</code>\n ),\n\n del: ({ children }) => <del className=\"text-text-muted line-through\">{children}</del>,\n\n em: ({ children }) => <em className=\"italic\">{children}</em>,\n\n h1: ({ children }) => <Heading level={2}>{children}</Heading>,\n h2: ({ children }) => <Heading level={3}>{children}</Heading>,\n h3: ({ children }) => <Heading level={4}>{children}</Heading>,\n h4: ({ children }) => <Heading level={5}>{children}</Heading>,\n h5: ({ children }) => <Heading level={6}>{children}</Heading>,\n h6: ({ children }) => <Heading level={6}>{children}</Heading>,\n\n hr: () => <hr className=\"my-3 border-border-default\" />,\n\n img: ({ src, alt, title }) => (\n <AssistantMarkdownImage src={typeof src === 'string' ? src : undefined} alt={alt} title={title} />\n ),\n\n // GFM task lists. The transcript is a record of what the assistant wrote, so\n // the boxes are `disabled` (never user-editable) but NOT `aria-hidden` —\n // done/not-done is the point of the line, and a screen reader needs it.\n input: ({ checked, type }) =>\n type === 'checkbox' ? (\n <input\n type=\"checkbox\"\n checked={Boolean(checked)}\n // `disabled` (which the sanitizer schema forces on every input anyway)\n // is what makes this a legitimate uncontrolled-looking checkbox to\n // React — no onChange needed, and no console warning.\n disabled\n className=\"mr-1.5 size-3 flex-shrink-0 align-[-0.1em] accent-[var(--color-action-primary-bg)]\"\n />\n ) : null,\n\n li: ({ className, children }) => (\n <li className={hasClass(className, 'task-list-item') ? 'list-none text-text-primary' : 'text-text-primary'}>\n {children}\n </li>\n ),\n\n ol: ({ children }) => <ol className=\"my-1.5 ml-5 list-decimal space-y-0.5\">{children}</ol>,\n\n p: ({ children }) => <p className=\"my-1.5 leading-relaxed text-text-primary\">{children}</p>,\n\n pre: ({ children, node }) => {\n const fenced = readFencedCode(node);\n if (fenced) return <CodeBlock language={fenced.language} code={fenced.code} />;\n // Defensive: a `pre` that is not a fence still must not overflow the panel.\n return (\n <pre className=\"my-2 overflow-x-auto rounded-md border border-border-default bg-bg-sunken p-3 text-xs leading-relaxed\">\n {children}\n </pre>\n );\n },\n\n strong: ({ children }) => <strong className=\"font-semibold text-text-primary\">{children}</strong>,\n\n // The panel is ~440-480px wide, so a wide table scrolls inside its own box\n // rather than making the whole conversation scroll sideways.\n table: ({ children }) => (\n <div className=\"my-2 overflow-x-auto\" data-testid=\"assistant-markdown-table\">\n <table className=\"w-full border-collapse text-[0.9em]\">{children}</table>\n </div>\n ),\n\n td: ({ children }) => <td className=\"px-2 py-1.5 align-top text-text-primary\">{children}</td>,\n\n th: ({ children }) => (\n <th scope=\"col\" className=\"px-2 py-1.5 text-left font-semibold text-text-primary\">\n {children}\n </th>\n ),\n\n tr: ({ children }) => <tr className=\"border-b border-border-subtle\">{children}</tr>,\n\n ul: ({ className, children }) => (\n <ul\n className={\n // A task list carries its own checkbox glyph; a bullet would double up.\n hasClass(className, 'contains-task-list')\n ? 'my-1.5 ml-0.5 list-none space-y-0.5'\n : 'my-1.5 ml-5 list-disc space-y-0.5'\n }\n >\n {children}\n </ul>\n ),\n};\n\nexport const AssistantMarkdownRenderer: FC<Props> = ({ content }) => (\n <div\n // No font size here on purpose — the reply inherits the 15px body scale set\n // by AssistantMessageItem. `break-words` keeps a long URL or hash from\n // widening the panel; the first/last margin reset keeps the block flush.\n className=\"break-words [&>*:first-child]:mt-0 [&>*:last-child]:mb-0\"\n data-testid=\"assistant-markdown\"\n >\n <Markdown\n remarkPlugins={REMARK_PLUGINS}\n rehypePlugins={REHYPE_PLUGINS}\n urlTransform={assistantUrlTransform}\n components={COMPONENTS}\n >\n {content}\n </Markdown>\n </div>\n);\n"],"mappings":";;;;;;;;;;AA0EA,IAAM,IAAkB;CACtB,GAAG;CACH,WAAW;EACT,GAAG,EAAc;EACjB,KAAK,CAAC,GAAI,EAAc,WAAW,OAAO,EAAE,EAAG,OAAO;EACvD;CACF,EAgBK,IAAiB,0EAGV,KAAkD,GAAK,GAAK,MACnE,MAAQ,SAAS,EAAK,YAAY,SAAS,EAAe,KAAK,EAAI,GAAS,IAIzE,EAAoB,EAAI,EAG3B,IAA2C,CAAC,EAAU,EACtD,IAA2C,CAAC,CAAC,GAAgB,EAAgB,CAAC;AAEpF,SAAS,EAAU,EAAE,aAAU,WAA4C;CACzE,IAAM,IAAK,GAAO,EACZ,CAAC,GAAQ,KAAa,EAAS,GAAM;AAQ3C,QACE,kBAAC,OAAD;EAAK,WAAU;YAAf,CACE,kBAAC,OAAD;GAAK,WAAU;aAAf,CACE,kBAAC,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EACf,cAAc;EACd,YAAY;YAEX;EACQ,CAAA;CACP,CAAA"}
|
|
1
|
+
{"version":3,"file":"AssistantMarkdownRenderer.js","names":[],"sources":["../../../src/components/assistant/AssistantMarkdownRenderer.tsx"],"sourcesContent":["/**\n * Markdown renderer for assistant messages (Workstream 5).\n *\n * Replaces the previous hand-rolled regex renderer with react-markdown +\n * remark-gfm + rehype-sanitize, per the AI Assistant V2 spec. The regex version\n * had defects that only a real parser fixes: it emitted one `<p>` per SOURCE\n * line (shredding every soft-wrapped paragraph), emitted `<li>` elements with no\n * `<ul>`/`<ol>` parent at all (invalid markup that assistive tech does not\n * announce as a list), dropped empty table cells (shifting every later column),\n * and used a lookbehind assertion that throws at PARSE time on Safari < 16.4.\n * GFM also brings strikethrough, task lists and autolinks for free.\n *\n * ## Safety\n *\n * The assistant's output is attacker-reachable (prompt injection through a\n * scanned document, a shared field note, a marketplace listing), so it is\n * treated as untrusted HTML:\n *\n * - Raw HTML is NOT enabled (`rehype-raw` is deliberately absent), so markup\n * inside a reply is escaped rather than rendered.\n * - `rehype-sanitize` is the belt to that braces, running GitHub's default\n * schema with one deliberate widening — see `SANITIZE_SCHEMA`.\n * - `assistantUrlTransform` is a second, independent gate on every URL.\n *\n * `@/utils/sanitizeUrl` is intentionally no longer used here: link protocols are\n * now enforced twice over, by the sanitizer schema and by react-markdown's\n * `defaultUrlTransform`, both of which allow strictly less than it did.\n *\n * ## Type scale\n *\n * The V2 redesign sets assistant prose at 15px in AssistantMessageItem. The old\n * renderer hard-set `text-xs` on its root, which silently overrode that back to\n * 12px for every reply; the root now inherits, and the few size tweaks below are\n * `em`-relative so they scale with whatever the parent sets.\n */\n\nimport { useState, type FC, type ReactNode } from 'react';\nimport Markdown, { defaultUrlTransform, type Components, type ExtraProps, type Options } from 'react-markdown';\nimport remarkGfm from 'remark-gfm';\nimport rehypeSanitize, { defaultSchema } from 'rehype-sanitize';\nimport { Copy, Check } from 'lucide-react';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { copyToClipboard } from '../../utils/clipboard';\nimport { AssistantMarkdownImage } from './AssistantMarkdownImage';\n\ninterface Props {\n content: string;\n}\n\n/** The hast element react-markdown hands to a custom component. */\ntype MarkdownNode = NonNullable<ExtraProps['node']>;\n\n/**\n * Sanitizer schema: GitHub's default, widened in exactly one place.\n *\n * `defaultSchema.protocols.src` is `['http', 'https']`. We add `data` so an\n * inline `` — how the sandbox returns a\n * generated image, with no upload round-trip — survives sanitisation.\n *\n * Why a `data:` **image** is safe but a `data:` **link** is not:\n *\n * - `<img src=\"data:...\">` is a *passive* fetch. The bytes are handed to the\n * image decoder, never to the HTML parser, so they cannot execute script or\n * touch this origin's DOM, cookies or tokens. Worst case is a picture the\n * farmer did not ask for.\n * - `<a href=\"data:text/html,...\">` is *active navigation*. One click and the\n * browser renders attacker-authored HTML as a real document — historically\n * in the opener's origin, and still a first-class phishing surface (a\n * pixel-perfect fake login page on a URL the user cannot inspect). So\n * `protocols.href` is left exactly as GitHub ships it.\n *\n * `protocols.cite` / `longDesc` are likewise untouched, and no tag or attribute\n * is added to the allow-lists (`language-*` on `code`, which gives the fenced\n * block its language label, is already permitted by the default schema).\n */\nconst SANITIZE_SCHEMA = {\n ...defaultSchema,\n protocols: {\n ...defaultSchema.protocols,\n src: [...(defaultSchema.protocols?.src ?? []), 'data'],\n },\n};\n\n/**\n * The sanitizer's protocol check is scheme-only — it would pass\n * `data:text/html` on an `<img>` just as happily as `data:image/png`. That is\n * inert in an image element, but \"inert today\" is a weak thing to rely on, so\n * the media type is pinned here as well.\n *\n * `svg+xml` is excluded on purpose: SVG is an active document format, and\n * keeping it out means no later change of ours can route one into an\n * `<object>`/`<embed>`/CSS `url()` context where its script would run.\n *\n * Scheme and media type are matched case-sensitively so this agrees with the\n * sanitizer, whose protocol comparison is also case-sensitive: a `DATA:` URL\n * loses its `src` there, and must not look allowed here.\n */\nconst DATA_IMAGE_URL = /^data:image\\/(?:png|jpe?g|gif|webp|avif|bmp);base64,[A-Za-z0-9+/=\\s]+$/;\n\n/** @internal Exported for unit tests; not part of the module's public surface. */\nexport const assistantUrlTransform: Options['urlTransform'] = (url, key, node) => {\n if (key === 'src' && node.tagName === 'img' && DATA_IMAGE_URL.test(url)) return url;\n // Everything else — every `href`, every remote `src` — falls back to\n // react-markdown's allow-list (http, https, irc, ircs, mailto, xmpp, and\n // relative URLs). Nothing is broadened.\n return defaultUrlTransform(url);\n};\n\nconst REMARK_PLUGINS: Options['remarkPlugins'] = [remarkGfm];\nconst REHYPE_PLUGINS: Options['rehypePlugins'] = [[rehypeSanitize, SANITIZE_SCHEMA]];\n\nfunction CodeBlock({ language, code }: { language: string; code: string }) {\n const tr = useTr();\n const [copied, setCopied] = useState(false);\n\n const handleCopy = () => {\n // Confirm only on a real copy — see copyToClipboard.\n void copyToClipboard(code).then((ok) => {\n if (!ok) return;\n setCopied(true);\n setTimeout(() => setCopied(false), 2000);\n });\n };\n\n return (\n <div className=\"group relative my-2 overflow-hidden rounded-md border border-border-default bg-bg-sunken\">\n <div className=\"flex items-center justify-between border-b border-border-default bg-bg-elevated px-3 py-1.5\">\n <span className=\"font-mono text-[10px] uppercase tracking-wider text-text-muted\">{language || 'code'}</span>\n <button\n type=\"button\"\n onClick={handleCopy}\n className=\"flex items-center gap-1 rounded px-1.5 py-0.5 text-[10px] text-text-secondary transition-colors hover:bg-bg-sunken hover:text-text-primary\"\n aria-label={tr('healthybowl.assistant.markdown.copyCode', 'Copy code')}\n data-testid=\"assistant-markdown-copy-code\"\n >\n {copied ? (\n <>\n <Check className=\"size-3 text-status-success-text\" />\n <span>{tr('healthybowl.assistant.markdown.copied', 'Copied')}</span>\n </>\n ) : (\n <>\n <Copy className=\"size-3\" />\n <span>{tr('healthybowl.assistant.markdown.copy', 'Copy')}</span>\n </>\n )}\n </button>\n </div>\n <pre className=\"overflow-x-auto p-3 text-xs leading-relaxed\">\n <code className=\"font-mono text-text-primary\">{code}</code>\n </pre>\n </div>\n );\n}\n\n/**\n * Pull the text and language out of a fenced block.\n *\n * react-markdown no longer flags inline vs block code, so `pre` is overridden\n * instead and its `code` child read straight off the hast node — which is both\n * the reliable signal for \"this is a fence\" and the only place the raw,\n * unescaped source is available to hand to the copy button (walking the\n * rendered React children back to a string is lossy).\n */\nfunction readFencedCode(node: MarkdownNode | undefined): { code: string; language: string } | null {\n const child = node?.children?.[0];\n if (!child || child.type !== 'element' || child.tagName !== 'code') return null;\n\n const code = child.children.map((leaf) => (leaf.type === 'text' ? leaf.value : '')).join('');\n const className = child.properties?.className;\n const classes = Array.isArray(className) ? className.map(String) : String(className ?? '').split(' ');\n const languageClass = classes.find((entry) => entry.startsWith('language-'));\n\n return { code: code.replace(/\\n$/, ''), language: languageClass ? languageClass.slice('language-'.length) : '' };\n}\n\nfunction hasClass(className: string | undefined, name: string): boolean {\n return typeof className === 'string' && className.split(' ').includes(name);\n}\n\n/**\n * Markdown headings are demoted one level: this renderer draws inside a panel on\n * a page that already owns the document's `h1`, so an assistant `#` becomes an\n * `h2` and the heading outline stays sane for screen readers.\n */\nfunction Heading({ level, children }: { level: 2 | 3 | 4 | 5 | 6; children: ReactNode }) {\n const Tag = `h${level}` as const;\n const size = { 2: 'text-[1.15em]', 3: 'text-[1.08em]', 4: 'text-[1em]', 5: 'text-[0.95em]', 6: 'text-[0.9em]' }[\n level\n ];\n return <Tag className={`mb-1 mt-3 font-semibold text-text-primary ${size}`}>{children}</Tag>;\n}\n\nconst COMPONENTS: Components = {\n a: ({ href, children }) => (\n <a\n href={href}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"text-action-primary-bg underline-offset-2 hover:underline\"\n data-testid=\"assistant-markdown-link\"\n >\n {children}\n </a>\n ),\n\n blockquote: ({ children }) => (\n <blockquote className=\"my-2 border-l-2 border-action-primary-bg pl-3 italic text-text-secondary\">\n {children}\n </blockquote>\n ),\n\n // Only inline code reaches this: fenced blocks are consumed whole by `pre`.\n code: ({ children }) => (\n <code className=\"rounded bg-bg-sunken px-1 py-0.5 font-mono text-[0.85em] text-text-primary\">{children}</code>\n ),\n\n del: ({ children }) => <del className=\"text-text-muted line-through\">{children}</del>,\n\n em: ({ children }) => <em className=\"italic\">{children}</em>,\n\n h1: ({ children }) => <Heading level={2}>{children}</Heading>,\n h2: ({ children }) => <Heading level={3}>{children}</Heading>,\n h3: ({ children }) => <Heading level={4}>{children}</Heading>,\n h4: ({ children }) => <Heading level={5}>{children}</Heading>,\n h5: ({ children }) => <Heading level={6}>{children}</Heading>,\n h6: ({ children }) => <Heading level={6}>{children}</Heading>,\n\n hr: () => <hr className=\"my-3 border-border-default\" />,\n\n img: ({ src, alt, title }) => (\n <AssistantMarkdownImage src={typeof src === 'string' ? src : undefined} alt={alt} title={title} />\n ),\n\n // GFM task lists. The transcript is a record of what the assistant wrote, so\n // the boxes are `disabled` (never user-editable) but NOT `aria-hidden` —\n // done/not-done is the point of the line, and a screen reader needs it.\n input: ({ checked, type }) =>\n type === 'checkbox' ? (\n <input\n type=\"checkbox\"\n checked={Boolean(checked)}\n // `disabled` (which the sanitizer schema forces on every input anyway)\n // is what makes this a legitimate uncontrolled-looking checkbox to\n // React — no onChange needed, and no console warning.\n disabled\n className=\"mr-1.5 size-3 flex-shrink-0 align-[-0.1em] accent-[var(--color-action-primary-bg)]\"\n />\n ) : null,\n\n li: ({ className, children }) => (\n <li className={hasClass(className, 'task-list-item') ? 'list-none text-text-primary' : 'text-text-primary'}>\n {children}\n </li>\n ),\n\n ol: ({ children }) => <ol className=\"my-1.5 ml-5 list-decimal space-y-0.5\">{children}</ol>,\n\n p: ({ children }) => <p className=\"my-1.5 leading-relaxed text-text-primary\">{children}</p>,\n\n pre: ({ children, node }) => {\n const fenced = readFencedCode(node);\n if (fenced) return <CodeBlock language={fenced.language} code={fenced.code} />;\n // Defensive: a `pre` that is not a fence still must not overflow the panel.\n return (\n <pre className=\"my-2 overflow-x-auto rounded-md border border-border-default bg-bg-sunken p-3 text-xs leading-relaxed\">\n {children}\n </pre>\n );\n },\n\n strong: ({ children }) => <strong className=\"font-semibold text-text-primary\">{children}</strong>,\n\n // The panel is ~440-480px wide, so a wide table scrolls inside its own box\n // rather than making the whole conversation scroll sideways.\n table: ({ children }) => (\n <div className=\"my-2 overflow-x-auto\" data-testid=\"assistant-markdown-table\">\n <table className=\"w-full border-collapse text-[0.9em]\">{children}</table>\n </div>\n ),\n\n td: ({ children }) => <td className=\"px-2 py-1.5 align-top text-text-primary\">{children}</td>,\n\n th: ({ children }) => (\n <th scope=\"col\" className=\"px-2 py-1.5 text-left font-semibold text-text-primary\">\n {children}\n </th>\n ),\n\n tr: ({ children }) => <tr className=\"border-b border-border-subtle\">{children}</tr>,\n\n ul: ({ className, children }) => (\n <ul\n className={\n // A task list carries its own checkbox glyph; a bullet would double up.\n hasClass(className, 'contains-task-list')\n ? 'my-1.5 ml-0.5 list-none space-y-0.5'\n : 'my-1.5 ml-5 list-disc space-y-0.5'\n }\n >\n {children}\n </ul>\n ),\n};\n\nexport const AssistantMarkdownRenderer: FC<Props> = ({ content }) => (\n <div\n // No font size here on purpose — the reply inherits the 15px body scale set\n // by AssistantMessageItem. `break-words` keeps a long URL or hash from\n // widening the panel; the first/last margin reset keeps the block flush.\n className=\"break-words [&>*:first-child]:mt-0 [&>*:last-child]:mb-0\"\n data-testid=\"assistant-markdown\"\n >\n <Markdown\n remarkPlugins={REMARK_PLUGINS}\n rehypePlugins={REHYPE_PLUGINS}\n urlTransform={assistantUrlTransform}\n components={COMPONENTS}\n >\n {content}\n </Markdown>\n </div>\n);\n"],"mappings":";;;;;;;;;;;AA2EA,IAAM,IAAkB;CACtB,GAAG;CACH,WAAW;EACT,GAAG,EAAc;EACjB,KAAK,CAAC,GAAI,EAAc,WAAW,OAAO,EAAE,EAAG,OAAO;EACvD;CACF,EAgBK,IAAiB,0EAGV,KAAkD,GAAK,GAAK,MACnE,MAAQ,SAAS,EAAK,YAAY,SAAS,EAAe,KAAK,EAAI,GAAS,IAIzE,EAAoB,EAAI,EAG3B,IAA2C,CAAC,E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AAD;EAAI,WAAU;EAAiC;EAAc,CAAA;CAEnF,KAAK,EAAE,cAAW,kBAChB,kBAAC,MAAD;EACE,WAEE,EAAS,GAAW,qBAAqB,GACrC,wCACA;EAGL;EACE,CAAA;CAER,EAEY,KAAwC,EAAE,iBACrD,kBAAC,OAAD;CAIE,WAAU;CACV,eAAY;WAEZ,kBAAC,GAAD;EACE,eAAe;EACf,eAAe;EACf,cAAc;EACd,YAAY;YAEX;EACQ,CAAA;CACP,CAAA"}
|
|
@@ -1,146 +1,149 @@
|
|
|
1
1
|
import { useTr as e } from "../../shared/hooks/useTr.js";
|
|
2
2
|
import { downloadAssistantArtifact as t } from "../../services/assistantApi.js";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
3
|
+
import { copyToClipboard as n } from "../../utils/clipboard.js";
|
|
4
|
+
import { AssistantMarkdownRenderer as r } from "./AssistantMarkdownRenderer.js";
|
|
5
|
+
import { AssistantMessageAttachments as i } from "./AssistantMessageAttachments.js";
|
|
6
|
+
import { AssistantToolActivity as a, parseToolActivity as o } from "./AssistantToolActivity.js";
|
|
7
|
+
import { useMemo as s, useState as c } from "react";
|
|
8
|
+
import { Check as l, Copy as u, RotateCcw as d, Sparkles as f } from "lucide-react";
|
|
9
|
+
import { Fragment as p, jsx as m, jsxs as h } from "react/jsx-runtime";
|
|
10
|
+
import { SaveToFilesButton as g } from "@burdenoff/fe-libs/storage";
|
|
11
|
+
import { useGatewayClient as _ } from "@burdenoff/fe-libs/shared/graphql";
|
|
12
|
+
import { useAuthToken as v } from "@burdenoff/fe-libs/shared/providers/shell";
|
|
12
13
|
//#region src/components/assistant/AssistantMessageItem.tsx
|
|
13
|
-
function
|
|
14
|
+
function y(e) {
|
|
14
15
|
return e.role === "assistant" ? e.metadata : void 0;
|
|
15
16
|
}
|
|
16
|
-
function
|
|
17
|
+
function b(e) {
|
|
17
18
|
return e?.artifacts ?? [];
|
|
18
19
|
}
|
|
19
|
-
function
|
|
20
|
+
function x(e) {
|
|
20
21
|
return window.atob(e);
|
|
21
22
|
}
|
|
22
|
-
function
|
|
23
|
-
let r =
|
|
23
|
+
function S(e, t, n) {
|
|
24
|
+
let r = x(e), i = new Uint8Array(r.length);
|
|
24
25
|
for (let e = 0; e < r.length; e += 1) i[e] = r.charCodeAt(e);
|
|
25
26
|
let a = new Blob([i], { type: n }), o = URL.createObjectURL(a), s = document.createElement("a");
|
|
26
27
|
s.href = o, s.download = t, document.body.appendChild(s), s.click(), document.body.removeChild(s), URL.revokeObjectURL(o);
|
|
27
28
|
}
|
|
28
|
-
var
|
|
29
|
-
let
|
|
29
|
+
var C = ({ message: x, isStreaming: C, isFailed: w, onRetry: T }) => {
|
|
30
|
+
let E = e(), D = _("workspace"), { getAccessToken: O, getWorkspaceToken: k } = v(), [A, j] = c(null), [M, N] = c(!1), P = x.role === "user", F = s(() => y(x), [x]), I = s(() => b(F), [F]), { steps: L, text: R } = s(() => P ? {
|
|
30
31
|
steps: [],
|
|
31
|
-
text:
|
|
32
|
-
} :
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
32
|
+
text: x.content
|
|
33
|
+
} : o(x.content), [P, x.content]), z = () => {
|
|
34
|
+
n(R || x.content).then((e) => {
|
|
35
|
+
e && (N(!0), setTimeout(() => N(!1), 2e3));
|
|
36
|
+
});
|
|
37
|
+
}, B = async (e) => {
|
|
38
|
+
if (!F?.sandboxId || !F.sessionId) return;
|
|
36
39
|
let n = new URLSearchParams(window.location.search).get("workspace") ?? "";
|
|
37
40
|
if (n) {
|
|
38
|
-
|
|
41
|
+
j(e.path);
|
|
39
42
|
try {
|
|
40
|
-
let r = await t(
|
|
41
|
-
accessToken:
|
|
42
|
-
workspaceToken:
|
|
43
|
+
let r = await t(D, F.sandboxId, n, F.sessionId, e.path, {
|
|
44
|
+
accessToken: O(),
|
|
45
|
+
workspaceToken: k()
|
|
43
46
|
});
|
|
44
|
-
|
|
47
|
+
S(r.contentBase64, r.filename, r.mimeType);
|
|
45
48
|
} finally {
|
|
46
|
-
|
|
49
|
+
j(null);
|
|
47
50
|
}
|
|
48
51
|
}
|
|
49
|
-
},
|
|
52
|
+
}, V = new Date(x.timestamp).toLocaleTimeString([], {
|
|
50
53
|
hour: "2-digit",
|
|
51
54
|
minute: "2-digit"
|
|
52
55
|
});
|
|
53
|
-
if (
|
|
54
|
-
let e =
|
|
55
|
-
return /* @__PURE__ */
|
|
56
|
+
if (P) {
|
|
57
|
+
let e = x.metadata?.attachments ?? [];
|
|
58
|
+
return /* @__PURE__ */ m("div", {
|
|
56
59
|
className: "flex justify-end",
|
|
57
60
|
"data-testid": "assistant-message-user",
|
|
58
|
-
children: /* @__PURE__ */
|
|
61
|
+
children: /* @__PURE__ */ h("div", {
|
|
59
62
|
className: "max-w-[85%]",
|
|
60
63
|
children: [
|
|
61
|
-
|
|
64
|
+
x.content && /* @__PURE__ */ m("div", {
|
|
62
65
|
className: "rounded-2xl rounded-br-md bg-action-primary-bg/12 px-3.5 py-2.5 text-[15px] leading-relaxed text-text-primary",
|
|
63
|
-
children: /* @__PURE__ */
|
|
66
|
+
children: /* @__PURE__ */ m("p", {
|
|
64
67
|
className: "whitespace-pre-wrap",
|
|
65
|
-
children:
|
|
68
|
+
children: x.content
|
|
66
69
|
})
|
|
67
70
|
}),
|
|
68
|
-
/* @__PURE__ */
|
|
69
|
-
/* @__PURE__ */
|
|
71
|
+
/* @__PURE__ */ m(i, { attachments: e }),
|
|
72
|
+
/* @__PURE__ */ m("div", {
|
|
70
73
|
className: "mt-1 pr-1 text-right text-[10px] text-text-muted",
|
|
71
|
-
children:
|
|
74
|
+
children: V
|
|
72
75
|
})
|
|
73
76
|
]
|
|
74
77
|
})
|
|
75
78
|
});
|
|
76
79
|
}
|
|
77
|
-
return /* @__PURE__ */
|
|
80
|
+
return /* @__PURE__ */ h("div", {
|
|
78
81
|
className: "flex gap-2.5",
|
|
79
82
|
"data-testid": "assistant-message-assistant",
|
|
80
|
-
children: [/* @__PURE__ */
|
|
83
|
+
children: [/* @__PURE__ */ m("div", {
|
|
81
84
|
className: "mt-0.5 flex size-6 flex-shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-action-primary-bg/25 to-action-primary-bg/5 text-action-primary-bg",
|
|
82
|
-
children: /* @__PURE__ */
|
|
83
|
-
}), /* @__PURE__ */
|
|
85
|
+
children: /* @__PURE__ */ m(f, { className: "size-3.5" })
|
|
86
|
+
}), /* @__PURE__ */ h("div", {
|
|
84
87
|
className: "min-w-0 flex-1",
|
|
85
88
|
children: [
|
|
86
|
-
|
|
87
|
-
|
|
89
|
+
L.length > 0 && /* @__PURE__ */ m(a, { steps: L }),
|
|
90
|
+
R && /* @__PURE__ */ m("div", {
|
|
88
91
|
className: "text-[15px] leading-relaxed text-text-primary",
|
|
89
|
-
children: /* @__PURE__ */
|
|
92
|
+
children: /* @__PURE__ */ m(r, { content: R })
|
|
90
93
|
}),
|
|
91
|
-
|
|
94
|
+
C && /* @__PURE__ */ m("span", {
|
|
92
95
|
"aria-hidden": "true",
|
|
93
96
|
className: "ml-0.5 inline-block h-4 w-1.5 rounded-sm bg-text-secondary align-middle motion-safe:animate-pulse"
|
|
94
97
|
}),
|
|
95
|
-
|
|
98
|
+
I.length > 0 && F?.sandboxId && F.sessionId && /* @__PURE__ */ h("div", {
|
|
96
99
|
className: "mt-3 space-y-2 border-t border-border-subtle pt-2",
|
|
97
|
-
children: [/* @__PURE__ */
|
|
100
|
+
children: [/* @__PURE__ */ m("p", {
|
|
98
101
|
className: "text-[10px] font-medium uppercase tracking-wide text-text-muted",
|
|
99
|
-
children:
|
|
100
|
-
}), /* @__PURE__ */
|
|
102
|
+
children: E("healthybowl.assistant.message.downloads", "Downloads")
|
|
103
|
+
}), /* @__PURE__ */ m("div", {
|
|
101
104
|
className: "flex flex-wrap gap-2",
|
|
102
|
-
children:
|
|
105
|
+
children: I.map((e) => {
|
|
103
106
|
let t = `${e.name}${e.type === "directory" ? ".tar.gz" : ""}`;
|
|
104
|
-
return /* @__PURE__ */
|
|
107
|
+
return /* @__PURE__ */ m(g, {
|
|
105
108
|
label: t,
|
|
106
|
-
disabled:
|
|
109
|
+
disabled: A === e.path,
|
|
107
110
|
testId: `assistant-artifact-${e.name}`,
|
|
108
111
|
source: {
|
|
109
112
|
kind: "sandbox-artifact",
|
|
110
|
-
sandboxId:
|
|
111
|
-
sessionId:
|
|
113
|
+
sandboxId: F.sandboxId,
|
|
114
|
+
sessionId: F.sessionId,
|
|
112
115
|
path: e.path,
|
|
113
116
|
filename: t
|
|
114
117
|
},
|
|
115
118
|
defaultFolderPath: "/HealthyBowl/AI Assistant/Artifacts",
|
|
116
|
-
onDownload: () =>
|
|
119
|
+
onDownload: () => B(e)
|
|
117
120
|
}, e.path);
|
|
118
121
|
})
|
|
119
122
|
})]
|
|
120
123
|
}),
|
|
121
|
-
!
|
|
124
|
+
!C && (R || w) && /* @__PURE__ */ h("div", {
|
|
122
125
|
className: "mt-1.5 flex items-center gap-1",
|
|
123
|
-
children: [
|
|
126
|
+
children: [R && /* @__PURE__ */ m("button", {
|
|
124
127
|
type: "button",
|
|
125
|
-
onClick:
|
|
128
|
+
onClick: z,
|
|
126
129
|
className: "flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] text-text-muted transition-colors hover:bg-bg-elevated hover:text-text-secondary",
|
|
127
|
-
"aria-label":
|
|
130
|
+
"aria-label": E("healthybowl.assistant.message.copy", "Copy message"),
|
|
128
131
|
"data-testid": "assistant-message-copy",
|
|
129
|
-
children:
|
|
130
|
-
}),
|
|
132
|
+
children: M ? /* @__PURE__ */ h(p, { children: [/* @__PURE__ */ m(l, { className: "size-3 text-status-success-text" }), /* @__PURE__ */ m("span", { children: E("healthybowl.assistant.message.copied", "Copied") })] }) : /* @__PURE__ */ h(p, { children: [/* @__PURE__ */ m(u, { className: "size-3" }), /* @__PURE__ */ m("span", { children: E("healthybowl.assistant.message.copy", "Copy") })] })
|
|
133
|
+
}), w && T && /* @__PURE__ */ h("button", {
|
|
131
134
|
type: "button",
|
|
132
|
-
onClick:
|
|
135
|
+
onClick: T,
|
|
133
136
|
className: "flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] text-status-error-text transition-colors hover:bg-bg-elevated",
|
|
134
|
-
"aria-label":
|
|
137
|
+
"aria-label": E("healthybowl.assistant.message.retry", "Retry"),
|
|
135
138
|
"data-testid": "assistant-message-retry",
|
|
136
|
-
children: [/* @__PURE__ */
|
|
139
|
+
children: [/* @__PURE__ */ m(d, { className: "size-3" }), /* @__PURE__ */ m("span", { children: E("healthybowl.assistant.message.retry", "Retry") })]
|
|
137
140
|
})]
|
|
138
141
|
}),
|
|
139
|
-
/* @__PURE__ */
|
|
142
|
+
/* @__PURE__ */ h("div", {
|
|
140
143
|
className: "mt-1 text-[10px] text-text-muted",
|
|
141
|
-
children: [
|
|
144
|
+
children: [V, x.tokens && /* @__PURE__ */ h("span", {
|
|
142
145
|
className: "ml-2",
|
|
143
|
-
children: [
|
|
146
|
+
children: [x.tokens.input + x.tokens.output, " tokens"]
|
|
144
147
|
})]
|
|
145
148
|
})
|
|
146
149
|
]
|
|
@@ -148,6 +151,6 @@ var S = ({ message: b, isStreaming: S, isFailed: C, onRetry: w }) => {
|
|
|
148
151
|
});
|
|
149
152
|
};
|
|
150
153
|
//#endregion
|
|
151
|
-
export {
|
|
154
|
+
export { C as AssistantMessageItem };
|
|
152
155
|
|
|
153
156
|
//# sourceMappingURL=AssistantMessageItem.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantMessageItem.js","names":[],"sources":["../../../src/components/assistant/AssistantMessageItem.tsx"],"sourcesContent":["import { useMemo, useState, type FC } from 'react';\nimport { Sparkles, Copy, Check, RotateCcw } from 'lucide-react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { SaveToFilesButton } from '@burdenoff/fe-libs/storage';\nimport { AssistantMarkdownRenderer } from './AssistantMarkdownRenderer';\nimport { AssistantMessageAttachments } from './AssistantMessageAttachments';\nimport { AssistantToolActivity, parseToolActivity } from './AssistantToolActivity';\nimport { downloadAssistantArtifact } from '@/services/assistantApi';\nimport type { AssistantArtifact, AssistantMessageMetadata, Message } from '@/types/assistant';\nimport { useTr } from '../../shared/hooks/useTr';\n\ninterface Props {\n message: Message;\n isStreaming?: boolean;\n /** This assistant message ended in an error — show the Retry affordance. */\n isFailed?: boolean;\n /** Re-send the last user prompt (wired by AssistantChatArea). */\n onRetry?: () => void;\n}\n\nfunction getAssistantMetadata(message: Message): AssistantMessageMetadata | undefined {\n return message.role === 'assistant' ? message.metadata : undefined;\n}\n\nfunction getArtifacts(metadata: AssistantMessageMetadata | undefined): AssistantArtifact[] {\n return metadata?.artifacts ?? [];\n}\n\nfunction decodeBase64(base64: string): string {\n return window.atob(base64);\n}\n\nfunction downloadBase64File(base64: string, filename: string, mimeType: string): void {\n const binary = decodeBase64(base64);\n const bytes = new Uint8Array(binary.length);\n\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n\n const blob = new Blob([bytes], { type: mimeType });\n const url = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = url;\n link.download = filename;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n\nexport const AssistantMessageItem: FC<Props> = ({ message, isStreaming, isFailed, onRetry }) => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken } = useAuthToken();\n const [downloadingArtifactPath, setDownloadingArtifactPath] = useState<string | null>(null);\n const [copied, setCopied] = useState(false);\n const isUser = message.role === 'user';\n const metadata = useMemo(() => getAssistantMetadata(message), [message]);\n const artifacts = useMemo(() => getArtifacts(metadata), [metadata]);\n // Separate the streamed tool-progress lines from the assistant's prose so the\n // former renders as a structured activity card (see AssistantToolActivity).\n const { steps, text } = useMemo(\n () => (isUser ? { steps: [], text: message.content } : parseToolActivity(message.content)),\n [isUser, message.content]\n );\n\n const handleCopy = () => {\n void navigator.clipboard?.writeText(text || message.content);\n setCopied(true);\n setTimeout(() => setCopied(false), 2000);\n };\n\n const handleArtifactDownload = async (artifact: AssistantArtifact) => {\n if (!metadata?.sandboxId || !metadata.sessionId) return;\n\n const workspaceId = new URLSearchParams(window.location.search).get('workspace') ?? '';\n if (!workspaceId) return;\n\n setDownloadingArtifactPath(artifact.path);\n\n try {\n const result = await downloadAssistantArtifact(\n apollo,\n metadata.sandboxId,\n workspaceId,\n metadata.sessionId,\n artifact.path,\n {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n }\n );\n\n downloadBase64File(result.contentBase64, result.filename, result.mimeType);\n } finally {\n setDownloadingArtifactPath(null);\n }\n };\n\n const timeLabel = new Date(message.timestamp).toLocaleTimeString([], {\n hour: '2-digit',\n minute: '2-digit',\n });\n\n // ── User message: soft filled bubble, right-aligned ──────────────────\n if (isUser) {\n const attachments = message.metadata?.attachments ?? [];\n return (\n <div className=\"flex justify-end\" data-testid=\"assistant-message-user\">\n <div className=\"max-w-[85%]\">\n {/* An attachments-only turn (a photo with no words) has no bubble to\n draw — skip it rather than rendering an empty green pill. */}\n {message.content && (\n <div className=\"rounded-2xl rounded-br-md bg-action-primary-bg/12 px-3.5 py-2.5 text-[15px] leading-relaxed text-text-primary\">\n <p className=\"whitespace-pre-wrap\">{message.content}</p>\n </div>\n )}\n <AssistantMessageAttachments attachments={attachments} />\n <div className=\"mt-1 pr-1 text-right text-[10px] text-text-muted\">{timeLabel}</div>\n </div>\n </div>\n );\n }\n\n // ── Assistant message: open editorial style with a brand avatar ──────\n return (\n <div className=\"flex gap-2.5\" data-testid=\"assistant-message-assistant\">\n <div className=\"mt-0.5 flex size-6 flex-shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-action-primary-bg/25 to-action-primary-bg/5 text-action-primary-bg\">\n <Sparkles className=\"size-3.5\" />\n </div>\n\n <div className=\"min-w-0 flex-1\">\n {steps.length > 0 && <AssistantToolActivity steps={steps} />}\n\n {text && (\n <div className=\"text-[15px] leading-relaxed text-text-primary\">\n <AssistantMarkdownRenderer content={text} />\n </div>\n )}\n\n {isStreaming && (\n // Purely decorative \"still typing\" caret: hidden from assistive tech\n // (the list's aria-busy already conveys the state) and motion-safe so\n // it does not pulse for a reduced-motion user.\n <span\n aria-hidden=\"true\"\n className=\"ml-0.5 inline-block h-4 w-1.5 rounded-sm bg-text-secondary align-middle motion-safe:animate-pulse\"\n />\n )}\n\n {artifacts.length > 0 && metadata?.sandboxId && metadata.sessionId && (\n <div className=\"mt-3 space-y-2 border-t border-border-subtle pt-2\">\n <p className=\"text-[10px] font-medium uppercase tracking-wide text-text-muted\">\n {tr('healthybowl.assistant.message.downloads', 'Downloads')}\n </p>\n <div className=\"flex flex-wrap gap-2\">\n {artifacts.map((artifact) => {\n const displayName = `${artifact.name}${artifact.type === 'directory' ? '.tar.gz' : ''}`;\n const isDownloading = downloadingArtifactPath === artifact.path;\n return (\n <SaveToFilesButton\n key={artifact.path}\n label={displayName}\n disabled={isDownloading}\n testId={`assistant-artifact-${artifact.name}`}\n source={{\n kind: 'sandbox-artifact',\n sandboxId: metadata.sandboxId!,\n sessionId: metadata.sessionId!,\n path: artifact.path,\n filename: displayName,\n }}\n defaultFolderPath=\"/HealthyBowl/AI Assistant/Artifacts\"\n onDownload={() => handleArtifactDownload(artifact)}\n />\n );\n })}\n </div>\n </div>\n )}\n\n {/* Action row: Copy (any settled assistant text) + Retry (failed turns) */}\n {!isStreaming && (text || isFailed) && (\n <div className=\"mt-1.5 flex items-center gap-1\">\n {text && (\n <button\n type=\"button\"\n onClick={handleCopy}\n className=\"flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] text-text-muted transition-colors hover:bg-bg-elevated hover:text-text-secondary\"\n aria-label={tr('healthybowl.assistant.message.copy', 'Copy message')}\n data-testid=\"assistant-message-copy\"\n >\n {copied ? (\n <>\n <Check className=\"size-3 text-status-success-text\" />\n <span>{tr('healthybowl.assistant.message.copied', 'Copied')}</span>\n </>\n ) : (\n <>\n <Copy className=\"size-3\" />\n <span>{tr('healthybowl.assistant.message.copy', 'Copy')}</span>\n </>\n )}\n </button>\n )}\n {isFailed && onRetry && (\n <button\n type=\"button\"\n onClick={onRetry}\n className=\"flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] text-status-error-text transition-colors hover:bg-bg-elevated\"\n aria-label={tr('healthybowl.assistant.message.retry', 'Retry')}\n data-testid=\"assistant-message-retry\"\n >\n <RotateCcw className=\"size-3\" />\n <span>{tr('healthybowl.assistant.message.retry', 'Retry')}</span>\n </button>\n )}\n </div>\n )}\n\n <div className=\"mt-1 text-[10px] text-text-muted\">\n {timeLabel}\n {message.tokens && <span className=\"ml-2\">{message.tokens.input + message.tokens.output} tokens</span>}\n </div>\n </div>\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;AAqBA,SAAS,EAAqB,GAAwD;AACpF,QAAO,EAAQ,SAAS,cAAc,EAAQ,WAAW,KAAA;;AAG3D,SAAS,EAAa,GAAqE;AACzF,QAAO,GAAU,aAAa,EAAE;;AAGlC,SAAS,EAAa,GAAwB;AAC5C,QAAO,OAAO,KAAK,EAAO;;AAG5B,SAAS,EAAmB,GAAgB,GAAkB,GAAwB;CACpF,IAAM,IAAS,EAAa,EAAO,EAC7B,IAAQ,IAAI,WAAW,EAAO,OAAO;AAE3C,MAAK,IAAI,IAAQ,GAAG,IAAQ,EAAO,QAAQ,KAAS,EAClD,GAAM,KAAS,EAAO,WAAW,EAAM;CAGzC,IAAM,IAAO,IAAI,KAAK,CAAC,EAAM,EAAE,EAAE,MAAM,GAAU,CAAC,EAC5C,IAAM,IAAI,gBAAgB,EAAK,EAC/B,IAAO,SAAS,cAAc,IAAI;AAMxC,CALA,EAAK,OAAO,GACZ,EAAK,WAAW,GAChB,SA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EAAS;QAClD,EAbK,EAAS,KAad;QAEJ;MACE,CAAA,CACF;;IAIP,CAAC,MAAgB,KAAQ,MACxB,kBAAC,OAAD;KAAK,WAAU;eAAf,CACG,KACC,kBAAC,UAAD;MACE,MAAK;MACL,SAAS;MACT,WAAU;MACV,cAAY,EAAG,sCAAsC,eAAe;MACpE,eAAY;gBAEX,IACC,kBAAA,GAAA,EAAA,UAAA,CACE,kBAAC,GAAD,EAAO,WAAU,mCAAoC,CAAA,EACrD,kBAAC,QAAD,EAAA,UAAO,EAAG,wCAAwC,SAAS,EAAQ,CAAA,CAClE,EAAA,CAAA,GAEH,kBAAA,GAAA,EAAA,UAAA,CACE,kBAAC,GAAD,EAAM,WAAU,UAAW,CAAA,EAC3B,kBAAC,QAAD,EAAA,UAAO,EAAG,sCAAsC,OAAO,EAAQ,CAAA,CAC9D,EAAA,CAAA;MAEE,CAAA,EAEV,KAAY,KACX,kBAAC,UAAD;MACE,MAAK;MACL,SAAS;MACT,WAAU;MACV,cAAY,EAAG,uCAAuC,QAAQ;MAC9D,eAAY;gBALd,CAOE,kBAAC,GAAD,EAAW,WAAU,UAAW,CAAA,EAChC,kBAAC,QAAD,EAAA,UAAO,EAAG,uCAAuC,QAAQ,EAAQ,CAAA,CAC1D;QAEP;;IAGR,kBAAC,OAAD;KAAK,WAAU;eAAf,CACG,GACA,EAAQ,UAAU,kBAAC,QAAD;MAAM,WAAU;gBAAhB,CAAwB,EAAQ,OAAO,QAAQ,EAAQ,OAAO,QAAO,UAAc;QAClG;;IACF;KACF"}
|
|
1
|
+
{"version":3,"file":"AssistantMessageItem.js","names":[],"sources":["../../../src/components/assistant/AssistantMessageItem.tsx"],"sourcesContent":["import { useMemo, useState, type FC } from 'react';\nimport { Sparkles, Copy, Check, RotateCcw } from 'lucide-react';\nimport { useGatewayClient } from '@burdenoff/fe-libs/shared/graphql';\nimport { useAuthToken } from '@burdenoff/fe-libs/shared/providers/shell';\nimport { SaveToFilesButton } from '@burdenoff/fe-libs/storage';\nimport { AssistantMarkdownRenderer } from './AssistantMarkdownRenderer';\nimport { AssistantMessageAttachments } from './AssistantMessageAttachments';\nimport { AssistantToolActivity, parseToolActivity } from './AssistantToolActivity';\nimport { downloadAssistantArtifact } from '@/services/assistantApi';\nimport type { AssistantArtifact, AssistantMessageMetadata, Message } from '@/types/assistant';\nimport { useTr } from '../../shared/hooks/useTr';\nimport { copyToClipboard } from '../../utils/clipboard';\n\ninterface Props {\n message: Message;\n isStreaming?: boolean;\n /** This assistant message ended in an error — show the Retry affordance. */\n isFailed?: boolean;\n /** Re-send the last user prompt (wired by AssistantChatArea). */\n onRetry?: () => void;\n}\n\nfunction getAssistantMetadata(message: Message): AssistantMessageMetadata | undefined {\n return message.role === 'assistant' ? message.metadata : undefined;\n}\n\nfunction getArtifacts(metadata: AssistantMessageMetadata | undefined): AssistantArtifact[] {\n return metadata?.artifacts ?? [];\n}\n\nfunction decodeBase64(base64: string): string {\n return window.atob(base64);\n}\n\nfunction downloadBase64File(base64: string, filename: string, mimeType: string): void {\n const binary = decodeBase64(base64);\n const bytes = new Uint8Array(binary.length);\n\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index);\n }\n\n const blob = new Blob([bytes], { type: mimeType });\n const url = URL.createObjectURL(blob);\n const link = document.createElement('a');\n link.href = url;\n link.download = filename;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n\nexport const AssistantMessageItem: FC<Props> = ({ message, isStreaming, isFailed, onRetry }) => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken } = useAuthToken();\n const [downloadingArtifactPath, setDownloadingArtifactPath] = useState<string | null>(null);\n const [copied, setCopied] = useState(false);\n const isUser = message.role === 'user';\n const metadata = useMemo(() => getAssistantMetadata(message), [message]);\n const artifacts = useMemo(() => getArtifacts(metadata), [metadata]);\n // Separate the streamed tool-progress lines from the assistant's prose so the\n // former renders as a structured activity card (see AssistantToolActivity).\n const { steps, text } = useMemo(\n () => (isUser ? { steps: [], text: message.content } : parseToolActivity(message.content)),\n [isUser, message.content]\n );\n\n const handleCopy = () => {\n // Confirm only on a real copy — see copyToClipboard.\n void copyToClipboard(text || message.content).then((ok) => {\n if (!ok) return;\n setCopied(true);\n setTimeout(() => setCopied(false), 2000);\n });\n };\n\n const handleArtifactDownload = async (artifact: AssistantArtifact) => {\n if (!metadata?.sandboxId || !metadata.sessionId) return;\n\n const workspaceId = new URLSearchParams(window.location.search).get('workspace') ?? '';\n if (!workspaceId) return;\n\n setDownloadingArtifactPath(artifact.path);\n\n try {\n const result = await downloadAssistantArtifact(\n apollo,\n metadata.sandboxId,\n workspaceId,\n metadata.sessionId,\n artifact.path,\n {\n accessToken: getAccessToken(),\n workspaceToken: getWorkspaceToken(),\n }\n );\n\n downloadBase64File(result.contentBase64, result.filename, result.mimeType);\n } finally {\n setDownloadingArtifactPath(null);\n }\n };\n\n const timeLabel = new Date(message.timestamp).toLocaleTimeString([], {\n hour: '2-digit',\n minute: '2-digit',\n });\n\n // ── User message: soft filled bubble, right-aligned ──────────────────\n if (isUser) {\n const attachments = message.metadata?.attachments ?? [];\n return (\n <div className=\"flex justify-end\" data-testid=\"assistant-message-user\">\n <div className=\"max-w-[85%]\">\n {/* An attachments-only turn (a photo with no words) has no bubble to\n draw — skip it rather than rendering an empty green pill. */}\n {message.content && (\n <div className=\"rounded-2xl rounded-br-md bg-action-primary-bg/12 px-3.5 py-2.5 text-[15px] leading-relaxed text-text-primary\">\n <p className=\"whitespace-pre-wrap\">{message.content}</p>\n </div>\n )}\n <AssistantMessageAttachments attachments={attachments} />\n <div className=\"mt-1 pr-1 text-right text-[10px] text-text-muted\">{timeLabel}</div>\n </div>\n </div>\n );\n }\n\n // ── Assistant message: open editorial style with a brand avatar ──────\n return (\n <div className=\"flex gap-2.5\" data-testid=\"assistant-message-assistant\">\n <div className=\"mt-0.5 flex size-6 flex-shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-action-primary-bg/25 to-action-primary-bg/5 text-action-primary-bg\">\n <Sparkles className=\"size-3.5\" />\n </div>\n\n <div className=\"min-w-0 flex-1\">\n {steps.length > 0 && <AssistantToolActivity steps={steps} />}\n\n {text && (\n <div className=\"text-[15px] leading-relaxed text-text-primary\">\n <AssistantMarkdownRenderer content={text} />\n </div>\n )}\n\n {isStreaming && (\n // Purely decorative \"still typing\" caret: hidden from assistive tech\n // (the list's aria-busy already conveys the state) and motion-safe so\n // it does not pulse for a reduced-motion user.\n <span\n aria-hidden=\"true\"\n className=\"ml-0.5 inline-block h-4 w-1.5 rounded-sm bg-text-secondary align-middle motion-safe:animate-pulse\"\n />\n )}\n\n {artifacts.length > 0 && metadata?.sandboxId && metadata.sessionId && (\n <div className=\"mt-3 space-y-2 border-t border-border-subtle pt-2\">\n <p className=\"text-[10px] font-medium uppercase tracking-wide text-text-muted\">\n {tr('healthybowl.assistant.message.downloads', 'Downloads')}\n </p>\n <div className=\"flex flex-wrap gap-2\">\n {artifacts.map((artifact) => {\n const displayName = `${artifact.name}${artifact.type === 'directory' ? '.tar.gz' : ''}`;\n const isDownloading = downloadingArtifactPath === artifact.path;\n return (\n <SaveToFilesButton\n key={artifact.path}\n label={displayName}\n disabled={isDownloading}\n testId={`assistant-artifact-${artifact.name}`}\n source={{\n kind: 'sandbox-artifact',\n sandboxId: metadata.sandboxId!,\n sessionId: metadata.sessionId!,\n path: artifact.path,\n filename: displayName,\n }}\n defaultFolderPath=\"/HealthyBowl/AI Assistant/Artifacts\"\n onDownload={() => handleArtifactDownload(artifact)}\n />\n );\n })}\n </div>\n </div>\n )}\n\n {/* Action row: Copy (any settled assistant text) + Retry (failed turns) */}\n {!isStreaming && (text || isFailed) && (\n <div className=\"mt-1.5 flex items-center gap-1\">\n {text && (\n <button\n type=\"button\"\n onClick={handleCopy}\n className=\"flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] text-text-muted transition-colors hover:bg-bg-elevated hover:text-text-secondary\"\n aria-label={tr('healthybowl.assistant.message.copy', 'Copy message')}\n data-testid=\"assistant-message-copy\"\n >\n {copied ? (\n <>\n <Check className=\"size-3 text-status-success-text\" />\n <span>{tr('healthybowl.assistant.message.copied', 'Copied')}</span>\n </>\n ) : (\n <>\n <Copy className=\"size-3\" />\n <span>{tr('healthybowl.assistant.message.copy', 'Copy')}</span>\n </>\n )}\n </button>\n )}\n {isFailed && onRetry && (\n <button\n type=\"button\"\n onClick={onRetry}\n className=\"flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] text-status-error-text transition-colors hover:bg-bg-elevated\"\n aria-label={tr('healthybowl.assistant.message.retry', 'Retry')}\n data-testid=\"assistant-message-retry\"\n >\n <RotateCcw className=\"size-3\" />\n <span>{tr('healthybowl.assistant.message.retry', 'Retry')}</span>\n </button>\n )}\n </div>\n )}\n\n <div className=\"mt-1 text-[10px] text-text-muted\">\n {timeLabel}\n {message.tokens && <span className=\"ml-2\">{message.tokens.input + message.tokens.output} tokens</span>}\n </div>\n </div>\n </div>\n );\n};\n"],"mappings":";;;;;;;;;;;;;AAsBA,SAAS,EAAqB,GAAwD;AACpF,QAAO,EAAQ,SAAS,cAAc,EAAQ,WAAW,KAAA;;AAG3D,SAAS,EAAa,GAAqE;AACzF,QAAO,GAAU,aAAa,EAAE;;AAGlC,SAAS,EAAa,GAAwB;AAC5C,QAAO,OAAO,KAAK,EAAO;;AAG5B,SAAS,EAAmB,GAAgB,GAAkB,GAAwB;CACpF,IAAM,IAAS,EAAa,EAAO,EAC7B,IAAQ,IAAI,WAAW,EAAO,OAAO;AAE3C,MAAK,IAAI,IAAQ,GAAG,IAAQ,EAAO,QAAQ,KAAS,EAClD,GAAM,KAAS,EAAO,WAAW,EAAM;CAGzC,IAAM,IAAO,IAAI,KAAK,CAAC,EAAM,EAAE,EAAE,MAAM,GAAU,CAAC,EAC5C,IAAM,IAAI,gBAAgB,EAAK,EAC/B,IAAO,SAAS,cAAc,IAAI;AAMxC,CALA,EAAK,OAAO,GAC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D,mBAAkB;QAClB,kBAAkB,EAAuB,EAAS;QAClD,EAbK,EAAS,KAad;QAEJ;MACE,CAAA,CACF;;IAIP,CAAC,MAAgB,KAAQ,MACxB,kBAAC,OAAD;KAAK,WAAU;eAAf,CACG,KACC,kBAAC,UAAD;MACE,MAAK;MACL,SAAS;MACT,WAAU;MACV,cAAY,EAAG,sCAAsC,eAAe;MACpE,eAAY;gBAEX,IACC,kBAAA,GAAA,EAAA,UAAA,CACE,kBAAC,GAAD,EAAO,WAAU,mCAAoC,CAAA,EACrD,kBAAC,QAAD,EAAA,UAAO,EAAG,wCAAwC,SAAS,EAAQ,CAAA,CAClE,EAAA,CAAA,GAEH,kBAAA,GAAA,EAAA,UAAA,CACE,kBAAC,GAAD,EAAM,WAAU,UAAW,CAAA,EAC3B,kBAAC,QAAD,EAAA,UAAO,EAAG,sCAAsC,OAAO,EAAQ,CAAA,CAC9D,EAAA,CAAA;MAEE,CAAA,EAEV,KAAY,KACX,kBAAC,UAAD;MACE,MAAK;MACL,SAAS;MACT,WAAU;MACV,cAAY,EAAG,uCAAuC,QAAQ;MAC9D,eAAY;gBALd,CAOE,kBAAC,GAAD,EAAW,WAAU,UAAW,CAAA,EAChC,kBAAC,QAAD,EAAA,UAAO,EAAG,uCAAuC,QAAQ,EAAQ,CAAA,CAC1D;QAEP;;IAGR,kBAAC,OAAD;KAAK,WAAU;eAAf,CACG,GACA,EAAQ,UAAU,kBAAC,QAAD;MAAM,WAAU;gBAAhB,CAAwB,EAAQ,OAAO,QAAQ,EAAQ,OAAO,QAAO,UAAc;QAClG;;IACF;KACF"}
|
|
@@ -59,7 +59,7 @@ function c(e, t) {
|
|
|
59
59
|
}
|
|
60
60
|
function l(e, t) {
|
|
61
61
|
let n = [`[${t + 1}] ${e.filename} — ${e.mimeType}, ${o(e.size)}`];
|
|
62
|
-
return e.downloadUrl && n.push(` URL: ${e.downloadUrl}`), e.kind === "text" && e.textContent ? n.push(e.textTruncated ? ` Contents (first ${e.textContent.length} characters of ${o(e.size)}; truncated):` : " Contents:", " ```", ...e.textContent.split("\n").map((e) => ` ${e}`), " ```") : e.kind === "image" ? n.push(" If this image is attached to the message as an image you can view, answer from what you see in it.", " If you cannot view attached images, say so plainly and ask the user to describe it — never guess.") : n.push(" Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user", " to paste the relevant section as text."), n.join("\n");
|
|
62
|
+
return e.downloadUrl && n.push(` URL: ${e.downloadUrl}`), e.kind === "text" && e.textContent ? n.push(e.textTruncated ? ` Contents (first ${e.textContent.length} characters of ${o(e.size)}; truncated):` : " Contents:", " ```", ...e.textContent.split("\n").map((e) => ` ${e}`), " ```") : e.kind === "image" ? n.push(" If this image is attached to the message as an image you can view, answer from what you see in it.", " If you cannot view attached images, say so plainly and ask the user to describe it — never guess.") : e.kind === "text" ? n.push(" Text file — contents omitted because this turn ran out of inline budget, not because they are", " unavailable. Fetch the URL above if you can; otherwise ask the user which part matters so they", " can re-send just that section.") : n.push(" Binary file — contents not inlined. Fetch the URL above if you can; otherwise ask the user", " to paste the relevant section as text."), n.join("\n");
|
|
63
63
|
}
|
|
64
64
|
function u(e) {
|
|
65
65
|
let n = e.filter((e) => e.status === "ready");
|
|
@@ -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. */\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 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 /** wspace-files-svc id, once the upload lands. */\n fileId?: string;\n /** Short-lived presigned URL, resolved at send time. */\n downloadUrl?: string;\n /** Extracted UTF-8 content for text-like files (already truncated). */\n textContent?: string;\n /** True when `textContent` is a prefix of a longer file. */\n textTruncated?: boolean;\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\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\nexport type AttachmentRejection = 'too-many' | 'too-large' | 'empty' | 'unreadable';\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 */\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\nfunction describeAttachment(attachment: AssistantAttachment, index: number): 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 ' ```',\n ...attachment.textContent.split('\\n').map((line) => ` ${line}`),\n ' ```'\n );\n } else if (attachment.kind === 'image') {\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 } 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\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 * 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[]): string {\n const usable = attachments.filter((attachment) => attachment.status === 'ready');\n if (usable.length === 0) return '';\n\n // Apply the shared inline budget in order, so the first files keep their\n // content and later ones degrade to metadata-only rather than every file\n // being trimmed to uselessness.\n let remaining = MAX_INLINE_CHARS_TOTAL;\n const budgeted = usable.map((attachment) => {\n if (attachment.kind !== 'text' || !attachment.textContent) return attachment;\n if (remaining <= 0) {\n return { ...attachment, textContent: undefined, textTruncated: true };\n }\n const { text, truncated } = truncateForInline(attachment.textContent, remaining);\n remaining -= text.length;\n return { ...attachment, textContent: text, textTruncated: attachment.textTruncated || truncated };\n });\n\n return [\n '',\n `--- Attachments (${usable.length}) ---`,\n 'The user attached the following file(s) to this message.',\n ...budgeted.map(describeAttachment),\n '--- End attachments ---',\n ].join('\\n');\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);\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, and the total base64 budget.\n *\n * Inline bytes are what make vision work without the sandbox needing egress to\n * our storage, but they ride inside a GraphQL variable through the public\n * gateway — so the turn has to stay a sane size. A 1280px JPEG at q0.72 is\n * typically 150-400 KB, i.e. 200-530 KB of base64; three of them sit\n * comfortably under the cap. Images beyond the budget still travel, by URL\n * only, and the prompt block still describes them.\n */\nexport const MAX_INLINE_IMAGE_PARTS = 3;\nexport const MAX_INLINE_IMAGE_BASE64_CHARS = 1_500_000;\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 * 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 = attachments.filter((attachment) => attachment.status === 'ready');\n if (usable.length === 0) return undefined;\n\n const media: AssistantPromptPart[] = [];\n let inlined = 0;\n let inlineChars = 0;\n\n for (const attachment of usable) {\n if (attachment.kind === 'image') {\n const parsed = attachment.previewUrl ? parseDataUrl(attachment.previewUrl) : null;\n const withinBudget =\n parsed !== null &&\n inlined < MAX_INLINE_IMAGE_PARTS &&\n inlineChars + parsed.base64.length <= MAX_INLINE_IMAGE_BASE64_CHARS;\n\n if (withinBudget && parsed) {\n inlined += 1;\n inlineChars += parsed.base64.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 // Documents are never inlined: a PDF is not an image, and making it useful\n // needs an extraction/retrieval step on the agent side. A reference is the\n // honest maximum from here. Text-like files already have their content in\n // the prompt block, so a missing URL costs nothing.\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 if (media.length === 0) return undefined;\n return [{ type: 'text', text: promptText }, ...media];\n}\n"],"mappings":"AAiCA,IAAa,IAA4B,KAG5B,IAAyB;AAgDtC,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;;AAGT,SAAgB,EAAY,GAAuB;AAGjD,QAFI,IAAQ,OAAa,GAAG,EAAM,MAC9B,IAAQ,OAAO,OAAa,IAAI,IAAQ,MAAM,QAAQ,EAAE,CAAC,OACtD,IAAI,KAAS,OAAO,OAAO,QAAQ,EAAE,CAAC;;AAU/C,SAAgB,EAAa,GAAY,GAAkD;AAIzF,QAHI,KAAA,IAAwC,aACxC,EAAK,SAAS,IAAU,UACxB,EAAK,OAAA,YAAyB,CAAC,EAAK,KAAK,WAA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AC;EAAE,MAAM;EAAQ,MAAM;EAAY,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. */\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 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 /** wspace-files-svc id, once the upload lands. */\n fileId?: string;\n /** Short-lived presigned URL, resolved at send time. */\n downloadUrl?: string;\n /** Extracted UTF-8 content for text-like files (already truncated). */\n textContent?: string;\n /** True when `textContent` is a prefix of a longer file. */\n textTruncated?: boolean;\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\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\nexport type AttachmentRejection = 'too-many' | 'too-large' | 'empty' | 'unreadable';\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 */\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\nfunction describeAttachment(attachment: AssistantAttachment, index: number): 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 ' ```',\n ...attachment.textContent.split('\\n').map((line) => ` ${line}`),\n ' ```'\n );\n } else if (attachment.kind === 'image') {\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 } 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\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 * 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[]): string {\n const usable = attachments.filter((attachment) => attachment.status === 'ready');\n if (usable.length === 0) return '';\n\n // Apply the shared inline budget in order, so the first files keep their\n // content and later ones degrade to metadata-only rather than every file\n // being trimmed to uselessness.\n let remaining = MAX_INLINE_CHARS_TOTAL;\n const budgeted = usable.map((attachment) => {\n if (attachment.kind !== 'text' || !attachment.textContent) return attachment;\n if (remaining <= 0) {\n return { ...attachment, textContent: undefined, textTruncated: true };\n }\n const { text, truncated } = truncateForInline(attachment.textContent, remaining);\n remaining -= text.length;\n return { ...attachment, textContent: text, textTruncated: attachment.textTruncated || truncated };\n });\n\n return [\n '',\n `--- Attachments (${usable.length}) ---`,\n 'The user attached the following file(s) to this message.',\n ...budgeted.map(describeAttachment),\n '--- End attachments ---',\n ].join('\\n');\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);\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, and the total base64 budget.\n *\n * Inline bytes are what make vision work without the sandbox needing egress to\n * our storage, but they ride inside a GraphQL variable through the public\n * gateway — so the turn has to stay a sane size. A 1280px JPEG at q0.72 is\n * typically 150-400 KB, i.e. 200-530 KB of base64; three of them sit\n * comfortably under the cap. Images beyond the budget still travel, by URL\n * only, and the prompt block still describes them.\n */\nexport const MAX_INLINE_IMAGE_PARTS = 3;\nexport const MAX_INLINE_IMAGE_BASE64_CHARS = 1_500_000;\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 * 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 = attachments.filter((attachment) => attachment.status === 'ready');\n if (usable.length === 0) return undefined;\n\n const media: AssistantPromptPart[] = [];\n let inlined = 0;\n let inlineChars = 0;\n\n for (const attachment of usable) {\n if (attachment.kind === 'image') {\n const parsed = attachment.previewUrl ? parseDataUrl(attachment.previewUrl) : null;\n const withinBudget =\n parsed !== null &&\n inlined < MAX_INLINE_IMAGE_PARTS &&\n inlineChars + parsed.base64.length <= MAX_INLINE_IMAGE_BASE64_CHARS;\n\n if (withinBudget && parsed) {\n inlined += 1;\n inlineChars += parsed.base64.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 // Documents are never inlined: a PDF is not an image, and making it useful\n // needs an extraction/retrieval step on the agent side. A reference is the\n // honest maximum from here. Text-like files already have their content in\n // the prompt block, so a missing URL costs nothing.\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 if (media.length === 0) return undefined;\n return [{ type: 'text', text: promptText }, ...media];\n}\n"],"mappings":"AAiCA,IAAa,IAA4B,KAG5B,IAAyB;AAgDtC,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;CAC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,GACmC;CACnC,IAAM,IAAS,EAAY,QAAQ,MAAe,EAAW,WAAW,QAAQ;AAChF,KAAI,EAAO,WAAW,EAAG;CAEzB,IAAM,IAA+B,EAAE,EACnC,IAAU,GACV,IAAc;AAElB,MAAK,IAAM,KAAc,GAAQ;AAC/B,MAAI,EAAW,SAAS,SAAS;GAC/B,IAAM,IAAS,EAAW,aAAa,EAAa,EAAW,WAAW,GAAG;AAM7E,OAJE,MAAW,QACX,IAAA,KACA,IAAc,EAAO,OAAO,UAAA,QAEV,GAAQ;AAG1B,IAFA,KAAW,GACX,KAAe,EAAO,OAAO,QAC7B,EAAM,KAAK;KACT,MAAM;KACN,UAAU,EAAO;KACjB,MAAM,EAAO;KAIb,GAAI,EAAW,cAAc,EAAE,KAAK,EAAW,aAAa,GAAG,EAAE;KACjE,MAAM,EAAW;KAClB,CAAC;AACF;;AAGF,GAAI,EAAW,eACb,EAAM,KAAK;IACT,MAAM;IACN,UAAU,EAAW;IACrB,KAAK,EAAW;IAChB,MAAM,EAAW;IAClB,CAAC;AAEJ;;AAOF,EAAI,EAAW,eACb,EAAM,KAAK;GACT,MAAM;GACN,UAAU,EAAW;GACrB,KAAK,EAAW;GAChB,MAAM,EAAW;GAClB,CAAC;;AAIF,OAAM,WAAW,EACrB,QAAO,CAAC;EAAE,MAAM;EAAQ,MAAM;EAAY,EAAE,GAAG,EAAM"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
//#region src/utils/clipboard.ts
|
|
2
|
+
async function e(e) {
|
|
3
|
+
try {
|
|
4
|
+
return navigator.clipboard?.writeText ? (await navigator.clipboard.writeText(e), !0) : !1;
|
|
5
|
+
} catch {
|
|
6
|
+
return !1;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
//#endregion
|
|
10
|
+
export { e as copyToClipboard };
|
|
11
|
+
|
|
12
|
+
//# sourceMappingURL=clipboard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"clipboard.js","names":[],"sources":["../../src/utils/clipboard.ts"],"sourcesContent":["/**\n * Copy text to the clipboard, reporting whether it actually happened.\n *\n * `navigator.clipboard` is undefined outside a secure context (plain http on a\n * LAN address — how an on-farm tablet often reaches an internal host), and\n * `writeText` can also reject when the document is not focused or permission is\n * denied. Fire-and-forgetting it means the UI claims \"Copied\" while the\n * clipboard still holds whatever was there before, which is worse than no\n * feedback: the user pastes stale content and does not know why.\n */\nexport async function copyToClipboard(text: string): Promise<boolean> {\n try {\n if (!navigator.clipboard?.writeText) return false;\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n return false;\n }\n}\n"],"mappings":";AAUA,eAAsB,EAAgB,GAAgC;AACpE,KAAI;AAGF,SAFK,UAAU,WAAW,aAC1B,MAAM,UAAU,UAAU,UAAU,EAAK,EAClC,MAFqC;SAGtC;AACN,SAAO"}
|
package/package.json
CHANGED