@burdenoff/microfe-healthybowl 2026.903.21 → 2026.904.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/assistant/AIAssistantPanel.js +25 -21
- package/dist/components/assistant/AIAssistantPanel.js.map +1 -1
- package/dist/components/assistant/AssistantApiCallsConsentDialog.js +8 -8
- package/dist/components/assistant/AssistantApiCallsConsentDialog.js.map +1 -1
- package/dist/components/assistant/AssistantAutoSpeakToggle.js +1 -1
- package/dist/components/assistant/AssistantChatArea.js +248 -249
- package/dist/components/assistant/AssistantChatArea.js.map +1 -1
- package/dist/components/assistant/AssistantConversationList.js +31 -31
- package/dist/components/assistant/AssistantConversationList.js.map +1 -1
- package/dist/components/assistant/AssistantEmptyState.js +9 -9
- package/dist/components/assistant/AssistantEmptyState.js.map +1 -1
- package/dist/components/assistant/AssistantHeader.js +17 -17
- package/dist/components/assistant/AssistantHeader.js.map +1 -1
- package/dist/components/assistant/AssistantMarkdownImage.js +14 -14
- package/dist/components/assistant/AssistantMarkdownImage.js.map +1 -1
- package/dist/components/assistant/AssistantMarkdownRenderer.js +25 -25
- package/dist/components/assistant/AssistantMarkdownRenderer.js.map +1 -1
- package/dist/components/assistant/AssistantMessageAttachments.js +29 -29
- package/dist/components/assistant/AssistantMessageAttachments.js.map +1 -1
- package/dist/components/assistant/AssistantMessageItem.js +28 -28
- package/dist/components/assistant/AssistantMessageItem.js.map +1 -1
- package/dist/components/assistant/AssistantMessageList.js +14 -14
- package/dist/components/assistant/AssistantMessageList.js.map +1 -1
- package/dist/components/assistant/AssistantMoreMenu.js +25 -25
- package/dist/components/assistant/AssistantMoreMenu.js.map +1 -1
- package/dist/components/assistant/AssistantPendingWriteCard.js +8 -8
- package/dist/components/assistant/AssistantPendingWriteCard.js.map +1 -1
- package/dist/components/assistant/AssistantReplyLanguageSelector.js +11 -11
- package/dist/components/assistant/AssistantReplyLanguageSelector.js.map +1 -1
- package/dist/components/assistant/AssistantSpeakButton.js +4 -4
- package/dist/components/assistant/AssistantSpeakButton.js.map +1 -1
- package/dist/components/assistant/AssistantSpeechProvider.js +188 -188
- package/dist/components/assistant/AssistantSpeechProvider.js.map +1 -1
- package/dist/components/assistant/AssistantSpokenTurnsNotice.js +5 -5
- package/dist/components/assistant/AssistantSpokenTurnsNotice.js.map +1 -1
- package/dist/components/assistant/AssistantToolActivity.js +16 -16
- package/dist/components/assistant/AssistantToolActivity.js.map +1 -1
- package/dist/components/assistant/composer/AssistantAttachmentButton.js +20 -20
- package/dist/components/assistant/composer/AssistantAttachmentButton.js.map +1 -1
- package/dist/components/assistant/composer/AssistantAttachmentChips.js +23 -23
- package/dist/components/assistant/composer/AssistantAttachmentChips.js.map +1 -1
- package/dist/components/assistant/composer/AssistantComposer.js +44 -44
- package/dist/components/assistant/composer/AssistantComposer.js.map +1 -1
- package/dist/components/assistant/composer/AssistantLanguageSelector.js +7 -7
- package/dist/components/assistant/composer/AssistantLanguageSelector.js.map +1 -1
- package/dist/components/assistant/composer/AssistantModeSelector.js +28 -28
- package/dist/components/assistant/composer/AssistantModeSelector.js.map +1 -1
- package/dist/components/assistant/composer/AssistantVoiceButton.js +6 -6
- package/dist/components/assistant/composer/AssistantVoiceButton.js.map +1 -1
- package/dist/components/assistant/composer/AssistantVoiceSelector.js +7 -7
- package/dist/components/assistant/composer/AssistantVoiceSelector.js.map +1 -1
- package/dist/components/assistant/voice/AssistantVoiceSession.js +77 -77
- package/dist/components/assistant/voice/AssistantVoiceSession.js.map +1 -1
- package/dist/components/assistant/voice/AssistantVoiceSessionButton.js +6 -6
- package/dist/components/assistant/voice/AssistantVoiceSessionButton.js.map +1 -1
- package/dist/components/assistant/voice/VoiceConversationView.js +11 -11
- package/dist/components/assistant/voice/VoiceConversationView.js.map +1 -1
- package/dist/components/assistant/voice/VoiceTranscriptDrawer.js +13 -13
- package/dist/components/assistant/voice/VoiceTranscriptDrawer.js.map +1 -1
- package/dist/hooks/useAssistantAttachments.js +94 -94
- package/dist/hooks/useAssistantAttachments.js.map +1 -1
- package/dist/services/assistantApi.js +1 -1
- package/dist/services/assistantApi.js.map +1 -1
- package/dist/utils/attachmentSources.js +4 -4
- package/dist/utils/attachmentSources.js.map +1 -1
- package/package.json +2 -2
|
@@ -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 { 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,CAAC,GAAI,MAAM;CACvD;AACF,GAgBM,IAAi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,kBAAC,MAAD;EAAI,WAAU;EAA2C;CAAa,CAAA;CAE5F,KAAK,EAAE,kBACL,kBAAC,MAAD;EAAI,OAAM;EAAM,WAAU;EACvB;CACC,CAAA;CAGN,KAAK,EAAE,kBAAe,kBAAC,MAAD;EAAI,WAAU;EAAiC;CAAa,CAAA;CAElF,KAAK,EAAE,cAAW,kBAChB,kBAAC,MAAD;EACE,WAEE,EAAS,GAAW,oBAAoB,IACpC,wCACA;EAGL;CACC,CAAA;AAER,GAEa,KAAwC,EAAE,iBACrD,kBAAC,OAAD;CAIE,WAAU;CACV,eAAY;WAEZ,kBAAC,GAAD;EACE,eAAe;EACf,eAAe;EACf,cAAc;EACd,YAAY;YAEX;CACO,CAAA;AACP,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 { useAssistantTr } from '@burdenoff/fe-libs/shared/assistant';\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 = useAssistantTr();\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('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('markdown.copied', 'Copied')}</span>\n </>\n ) : (\n <>\n <Copy className=\"size-3\" />\n <span>{tr('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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;GAAK,WAAU;GACZ;EACE,CAAA;CAET;CAEA,SAAS,EAAE,kBAAe,kBAAC,UAAD;EAAQ,WAAU;EAAmC;CAAiB,CAAA;CAIhG,QAAQ,EAAE,kBACR,kBAAC,OAAD;EAAK,WAAU;EAAuB,eAAY;YAChD,kBAAC,SAAD;GAAO,WAAU;GAAuC;EAAgB,CAAA;CACrE,CAAA;CAGP,KAAK,EAAE,kBAAe,kBAAC,MAAD;EAAI,WAAU;EAA2C;CAAa,CAAA;CAE5F,KAAK,EAAE,kBACL,kBAAC,MAAD;EAAI,OAAM;EAAM,WAAU;EACvB;CACC,CAAA;CAGN,KAAK,EAAE,kBAAe,kBAAC,MAAD;EAAI,WAAU;EAAiC;CAAa,CAAA;CAElF,KAAK,EAAE,cAAW,kBAChB,kBAAC,MAAD;EACE,WAEE,EAAS,GAAW,oBAAoB,IACpC,wCACA;EAGL;CACC,CAAA;AAER,GAEa,KAAwC,EAAE,iBACrD,kBAAC,OAAD;CAIE,WAAU;CACV,eAAY;WAEZ,kBAAC,GAAD;EACE,eAAe;EACf,eAAe;EACf,cAAc;EACd,YAAY;YAEX;CACO,CAAA;AACP,CAAA"}
|
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
1
|
+
import { getWorkspaceId as e } from "../../utils/assistantContext.js";
|
|
2
|
+
import { formatBytes as t } from "../../utils/assistantAttachments.js";
|
|
3
|
+
import { useEffect as n, useState as r } from "react";
|
|
4
|
+
import { FileText as i, Paperclip as a } from "lucide-react";
|
|
5
|
+
import { useAssistantTr as o } from "@burdenoff/fe-libs/shared/assistant";
|
|
6
6
|
import { jsx as s, jsxs as c } from "react/jsx-runtime";
|
|
7
7
|
import { graphqlFetch as l } from "@burdenoff/fe-libs/shared/graphql";
|
|
8
8
|
//#region src/components/assistant/AssistantMessageAttachments.tsx
|
|
9
9
|
var u = "\n query HealthyBowlAssistantMessageAttachmentUrl($id: ID!) {\n getFileDownloadUrl(id: $id)\n }\n";
|
|
10
|
-
function d(
|
|
11
|
-
let [
|
|
12
|
-
return
|
|
13
|
-
let n = !0, r =
|
|
14
|
-
if (!(!
|
|
10
|
+
function d(t) {
|
|
11
|
+
let [i, a] = r(null);
|
|
12
|
+
return n(() => {
|
|
13
|
+
let n = !0, r = e();
|
|
14
|
+
if (!(!t || !r)) return l({
|
|
15
15
|
gateway: "workspace",
|
|
16
16
|
query: u,
|
|
17
|
-
variables: { id:
|
|
17
|
+
variables: { id: t },
|
|
18
18
|
workspaceToken: !0,
|
|
19
19
|
workspaceId: r,
|
|
20
20
|
suppressGlobalErrorEvent: !0
|
|
@@ -23,56 +23,56 @@ function d(e) {
|
|
|
23
23
|
}).catch(() => void 0), () => {
|
|
24
24
|
n = !1;
|
|
25
25
|
};
|
|
26
|
-
}, [
|
|
26
|
+
}, [t]), i;
|
|
27
27
|
}
|
|
28
|
-
var f = ({ attachment:
|
|
29
|
-
let
|
|
28
|
+
var f = ({ attachment: e }) => {
|
|
29
|
+
let n = o(), r = d(e.fileId), l = e.kind === "image", u = l ? /* @__PURE__ */ s("span", {
|
|
30
30
|
className: "block size-full overflow-hidden rounded-lg bg-bg-sunken",
|
|
31
|
-
children:
|
|
32
|
-
src:
|
|
33
|
-
alt:
|
|
31
|
+
children: r ? /* @__PURE__ */ s("img", {
|
|
32
|
+
src: r,
|
|
33
|
+
alt: e.filename,
|
|
34
34
|
className: "size-full object-cover",
|
|
35
35
|
loading: "lazy",
|
|
36
36
|
referrerPolicy: "no-referrer",
|
|
37
37
|
"data-testid": "assistant-message-attachment-image"
|
|
38
38
|
}) : /* @__PURE__ */ s("span", {
|
|
39
39
|
className: "flex size-full items-center justify-center text-text-muted",
|
|
40
|
-
children: /* @__PURE__ */ s(
|
|
40
|
+
children: /* @__PURE__ */ s(a, { className: "size-4" })
|
|
41
41
|
})
|
|
42
42
|
}) : /* @__PURE__ */ c("span", {
|
|
43
43
|
className: "flex items-center gap-1.5 rounded-lg border border-border-subtle bg-bg-surface px-2 py-1.5",
|
|
44
44
|
children: [/* @__PURE__ */ s("span", {
|
|
45
45
|
className: "flex size-6 flex-shrink-0 items-center justify-center rounded-md bg-bg-sunken text-text-muted",
|
|
46
|
-
children:
|
|
46
|
+
children: e.kind === "text" ? /* @__PURE__ */ s(i, { className: "size-3.5" }) : /* @__PURE__ */ s(a, { className: "size-3.5" })
|
|
47
47
|
}), /* @__PURE__ */ c("span", {
|
|
48
48
|
className: "min-w-0",
|
|
49
49
|
children: [/* @__PURE__ */ s("span", {
|
|
50
50
|
className: "block truncate text-[11px] font-medium leading-tight text-text-primary",
|
|
51
|
-
children:
|
|
51
|
+
children: e.filename
|
|
52
52
|
}), /* @__PURE__ */ s("span", {
|
|
53
53
|
className: "block text-[10px] leading-tight text-text-muted",
|
|
54
|
-
children:
|
|
54
|
+
children: t(e.size)
|
|
55
55
|
})]
|
|
56
56
|
})]
|
|
57
57
|
}), f = l ? "block size-16 overflow-hidden rounded-lg" : "block max-w-[200px]";
|
|
58
|
-
return
|
|
59
|
-
href:
|
|
58
|
+
return r ? /* @__PURE__ */ s("a", {
|
|
59
|
+
href: r,
|
|
60
60
|
target: "_blank",
|
|
61
61
|
rel: "noopener noreferrer",
|
|
62
62
|
className: `${f} focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`,
|
|
63
|
-
title:
|
|
63
|
+
title: n("attachments.open", "Open {{name}}", { name: e.filename }),
|
|
64
64
|
children: u
|
|
65
65
|
}) : /* @__PURE__ */ s("span", {
|
|
66
66
|
className: f,
|
|
67
67
|
children: u
|
|
68
68
|
});
|
|
69
|
-
}, p = ({ attachments:
|
|
70
|
-
let
|
|
71
|
-
return
|
|
69
|
+
}, p = ({ attachments: e }) => {
|
|
70
|
+
let t = o();
|
|
71
|
+
return e.length === 0 ? null : /* @__PURE__ */ s("ul", {
|
|
72
72
|
className: "mt-1.5 flex flex-wrap justify-end gap-1.5",
|
|
73
|
-
"aria-label":
|
|
73
|
+
"aria-label": t("attachments.messageLabel", "Files sent with this message"),
|
|
74
74
|
"data-testid": "assistant-message-attachments",
|
|
75
|
-
children:
|
|
75
|
+
children: e.map((e) => /* @__PURE__ */ s("li", { children: /* @__PURE__ */ s(f, { attachment: e }) }, e.id))
|
|
76
76
|
});
|
|
77
77
|
};
|
|
78
78
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantMessageAttachments.js","names":[],"sources":["../../../src/components/assistant/AssistantMessageAttachments.tsx"],"sourcesContent":["import { useEffect, useState, type FC } from 'react';\nimport { FileText, Paperclip } from 'lucide-react';\nimport { graphqlFetch } from '@burdenoff/fe-libs/shared/graphql';\nimport {
|
|
1
|
+
{"version":3,"file":"AssistantMessageAttachments.js","names":[],"sources":["../../../src/components/assistant/AssistantMessageAttachments.tsx"],"sourcesContent":["import { useEffect, useState, type FC } from 'react';\nimport { FileText, Paperclip } from 'lucide-react';\nimport { graphqlFetch } from '@burdenoff/fe-libs/shared/graphql';\nimport { useAssistantTr } from '@burdenoff/fe-libs/shared/assistant';\nimport { getWorkspaceId } from '@/utils/assistantContext';\nimport { formatBytes, type AssistantMessageAttachment } from '@/utils/assistantAttachments';\n\nconst DOWNLOAD_URL_QUERY = `\n query HealthyBowlAssistantMessageAttachmentUrl($id: ID!) {\n getFileDownloadUrl(id: $id)\n }\n`;\n\n/**\n * Resolve an opaque files-svc id to a short-lived presigned URL.\n *\n * The sent message only stores the file id (persisted conversations must stay\n * small), and presigned URLs expire — so the URL is re-fetched per render of a\n * visible attachment rather than being kept on the message.\n */\nfunction useAttachmentUrl(fileId: string | undefined): string | null {\n const [url, setUrl] = useState<string | null>(null);\n\n useEffect(() => {\n let active = true;\n const workspaceId = getWorkspaceId();\n if (!fileId || !workspaceId) return;\n\n void graphqlFetch<{ getFileDownloadUrl?: string | null }>({\n gateway: 'workspace',\n query: DOWNLOAD_URL_QUERY,\n variables: { id: fileId },\n workspaceToken: true,\n workspaceId,\n suppressGlobalErrorEvent: true,\n })\n .then((res) => {\n if (active) setUrl(res.data?.getFileDownloadUrl ?? null);\n })\n .catch(() => undefined);\n\n return () => {\n active = false;\n };\n }, [fileId]);\n\n return url;\n}\n\nconst AttachmentTile: FC<{ attachment: AssistantMessageAttachment }> = ({ attachment }) => {\n const tr = useAssistantTr();\n const url = useAttachmentUrl(attachment.fileId);\n const isImage = attachment.kind === 'image';\n\n const body = isImage ? (\n <span className=\"block size-full overflow-hidden rounded-lg bg-bg-sunken\">\n {url ? (\n <img\n src={url}\n alt={attachment.filename}\n className=\"size-full object-cover\"\n loading=\"lazy\"\n referrerPolicy=\"no-referrer\"\n data-testid=\"assistant-message-attachment-image\"\n />\n ) : (\n <span className=\"flex size-full items-center justify-center text-text-muted\">\n <Paperclip className=\"size-4\" />\n </span>\n )}\n </span>\n ) : (\n <span className=\"flex items-center gap-1.5 rounded-lg border border-border-subtle bg-bg-surface px-2 py-1.5\">\n <span className=\"flex size-6 flex-shrink-0 items-center justify-center rounded-md bg-bg-sunken text-text-muted\">\n {attachment.kind === 'text' ? <FileText className=\"size-3.5\" /> : <Paperclip className=\"size-3.5\" />}\n </span>\n <span className=\"min-w-0\">\n <span className=\"block truncate text-[11px] font-medium leading-tight text-text-primary\">\n {attachment.filename}\n </span>\n <span className=\"block text-[10px] leading-tight text-text-muted\">{formatBytes(attachment.size)}</span>\n </span>\n </span>\n );\n\n const className = isImage ? 'block size-16 overflow-hidden rounded-lg' : 'block max-w-[200px]';\n\n // Only linkable once the presigned URL resolves; without it the tile is still\n // a faithful record of what was sent, just not clickable.\n return url ? (\n <a\n href={url}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className={`${className} focus:outline-none focus-visible:ring-2 focus-visible:ring-border-strong`}\n title={tr('attachments.open', 'Open {{name}}', { name: attachment.filename })}\n >\n {body}\n </a>\n ) : (\n <span className={className}>{body}</span>\n );\n};\n\n/**\n * Attachments rendered under a user message bubble — a durable record of what\n * the farmer actually sent with the question, thumbnails included.\n */\nexport const AssistantMessageAttachments: FC<{ attachments: AssistantMessageAttachment[] }> = ({ attachments }) => {\n const tr = useAssistantTr();\n if (attachments.length === 0) return null;\n\n return (\n <ul\n className=\"mt-1.5 flex flex-wrap justify-end gap-1.5\"\n aria-label={tr('attachments.messageLabel', 'Files sent with this message')}\n data-testid=\"assistant-message-attachments\"\n >\n {attachments.map((attachment) => (\n <li key={attachment.id}>\n <AttachmentTile attachment={attachment} />\n </li>\n ))}\n </ul>\n );\n};\n"],"mappings":";;;;;;;;AAOA,IAAM,IAAqB;AAa3B,SAAS,EAAiB,GAA2C;CACnE,IAAM,CAAC,GAAK,KAAU,EAAwB,IAAI;CAyBlD,OAvBA,QAAgB;EACd,IAAI,IAAS,IACP,IAAc,EAAe;EAC/B,OAAC,KAAU,CAAC,IAehB,OAbA,EAA0D;GACxD,SAAS;GACT,OAAO;GACP,WAAW,EAAE,IAAI,EAAO;GACxB,gBAAgB;GAChB;GACA,0BAA0B;EAC5B,CAAC,EACE,MAAM,MAAQ;GACb,AAAI,KAAQ,EAAO,EAAI,MAAM,sBAAsB,IAAI;EACzD,CAAC,EACA,YAAY,KAAA,CAAS,SAEX;GACX,IAAS;EACX;CACF,GAAG,CAAC,CAAM,CAAC,GAEJ;AACT;AAEA,IAAM,KAAkE,EAAE,oBAAiB;CACzF,IAAM,IAAK,EAAe,GACpB,IAAM,EAAiB,EAAW,MAAM,GACxC,IAAU,EAAW,SAAS,SAE9B,IAAO,IACX,kBAAC,QAAD;EAAM,WAAU;YACb,IACC,kBAAC,OAAD;GACE,KAAK;GACL,KAAK,EAAW;GAChB,WAAU;GACV,SAAQ;GACR,gBAAe;GACf,eAAY;EACb,CAAA,IAED,kBAAC,QAAD;GAAM,WAAU;aACd,kBAAC,GAAD,EAAW,WAAU,SAAU,CAAA;EAC3B,CAAA;CAEJ,CAAA,IAEN,kBAAC,QAAD;EAAM,WAAU;YAAhB,CACE,kBAAC,QAAD;GAAM,WAAU;aACb,EAAW,SAAS,SAAS,kBAAC,GAAD,EAAU,WAAU,WAAY,CAAA,IAAI,kBAAC,GAAD,EAAW,WAAU,WAAY,CAAA;EAC/F,CAAA,GACN,kBAAC,QAAD;GAAM,WAAU;aAAhB,CACE,kBAAC,QAAD;IAAM,WAAU;cACb,EAAW;GACR,CAAA,GACN,kBAAC,QAAD;IAAM,WAAU;cAAmD,EAAY,EAAW,IAAI;GAAQ,CAAA,CAClG;IACF;KAGF,IAAY,IAAU,6CAA6C;CAIzE,OAAO,IACL,kBAAC,KAAD;EACE,MAAM;EACN,QAAO;EACP,KAAI;EACJ,WAAW,GAAG,EAAU;EACxB,OAAO,EAAG,oBAAoB,iBAAiB,EAAE,MAAM,EAAW,SAAS,CAAC;YAE3E;CACA,CAAA,IAEH,kBAAC,QAAD;EAAiB;YAAY;CAAW,CAAA;AAE5C,GAMa,KAAkF,EAAE,qBAAkB;CACjH,IAAM,IAAK,EAAe;CAG1B,OAFI,EAAY,WAAW,IAAU,OAGnC,kBAAC,MAAD;EACE,WAAU;EACV,cAAY,EAAG,4BAA4B,8BAA8B;EACzE,eAAY;YAEX,EAAY,KAAK,MAChB,kBAAC,MAAD,EAAA,UACE,kBAAC,GAAD,EAA4B,cAAa,CAAA,EACvC,GAFK,EAAW,EAEhB,CACL;CACC,CAAA;AAER"}
|
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
1
|
+
import { downloadAssistantArtifact as e } from "../../services/assistantApi.js";
|
|
2
|
+
import { AssistantToolActivity as t, parseToolActivity as n } from "./AssistantToolActivity.js";
|
|
3
|
+
import { useAssistantSpeech as r } from "./AssistantSpeechProvider.js";
|
|
4
|
+
import { copyToClipboard as i } from "../../utils/clipboard.js";
|
|
5
|
+
import { AssistantMarkdownRenderer as a } from "./AssistantMarkdownRenderer.js";
|
|
6
|
+
import { AssistantPendingWriteCard as o } from "./AssistantPendingWriteCard.js";
|
|
7
|
+
import { AssistantMessageAttachments as s } from "./AssistantMessageAttachments.js";
|
|
8
|
+
import { AssistantSpeakButton as c } from "./AssistantSpeakButton.js";
|
|
9
|
+
import { useMemo as l, useState as u } from "react";
|
|
10
|
+
import { Check as d, Copy as f, RotateCcw as p, Sparkles as m } from "lucide-react";
|
|
11
|
+
import { useAssistantTr as h } from "@burdenoff/fe-libs/shared/assistant";
|
|
12
12
|
import { Fragment as g, jsx as _, jsxs as v } from "react/jsx-runtime";
|
|
13
13
|
import { SaveToFilesButton as y } from "@burdenoff/fe-libs/storage";
|
|
14
14
|
import { useGatewayClient as b } from "@burdenoff/fe-libs/shared/graphql";
|
|
@@ -30,20 +30,20 @@ function T(e, t, n) {
|
|
|
30
30
|
s.href = o, s.download = t, document.body.appendChild(s), s.click(), document.body.removeChild(s), URL.revokeObjectURL(o);
|
|
31
31
|
}
|
|
32
32
|
var E = ({ message: w, isStreaming: E, isFailed: D, isLastAssistant: O, onRetry: k }) => {
|
|
33
|
-
let A =
|
|
33
|
+
let A = h(), j = b("workspace"), { getAccessToken: M, getWorkspaceToken: N } = x(), P = r(), [F, I] = u(null), [L, R] = u(!1), z = w.role === "user", B = l(() => S(w), [w]), V = l(() => C(B), [B]), { steps: H, text: U } = l(() => z ? {
|
|
34
34
|
steps: [],
|
|
35
35
|
text: w.content
|
|
36
|
-
} :
|
|
37
|
-
|
|
36
|
+
} : n(w.content), [z, w.content]), W = () => {
|
|
37
|
+
i(U || w.content).then((e) => {
|
|
38
38
|
e && (R(!0), setTimeout(() => R(!1), 2e3));
|
|
39
39
|
});
|
|
40
|
-
}, G = async (
|
|
40
|
+
}, G = async (t) => {
|
|
41
41
|
if (!B?.sandboxId || !B.sessionId) return;
|
|
42
42
|
let n = new URLSearchParams(window.location.search).get("workspace") ?? "";
|
|
43
43
|
if (n) {
|
|
44
|
-
I(
|
|
44
|
+
I(t.path);
|
|
45
45
|
try {
|
|
46
|
-
let r = await
|
|
46
|
+
let r = await e(j, B.sandboxId, n, B.sessionId, t.path, {
|
|
47
47
|
accessToken: M(),
|
|
48
48
|
workspaceToken: N()
|
|
49
49
|
});
|
|
@@ -79,7 +79,7 @@ var E = ({ message: w, isStreaming: E, isFailed: D, isLastAssistant: O, onRetry:
|
|
|
79
79
|
children: w.content
|
|
80
80
|
})
|
|
81
81
|
}),
|
|
82
|
-
/* @__PURE__ */ _(
|
|
82
|
+
/* @__PURE__ */ _(s, { attachments: e }),
|
|
83
83
|
/* @__PURE__ */ _("div", {
|
|
84
84
|
className: "mt-1 pr-1 text-right text-[10px] text-text-muted",
|
|
85
85
|
children: K
|
|
@@ -93,15 +93,15 @@ var E = ({ message: w, isStreaming: E, isFailed: D, isLastAssistant: O, onRetry:
|
|
|
93
93
|
"data-testid": "assistant-message-assistant",
|
|
94
94
|
children: [/* @__PURE__ */ _("div", {
|
|
95
95
|
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",
|
|
96
|
-
children: /* @__PURE__ */ _(
|
|
96
|
+
children: /* @__PURE__ */ _(m, { className: "size-3.5" })
|
|
97
97
|
}), /* @__PURE__ */ v("div", {
|
|
98
98
|
className: "min-w-0 flex-1",
|
|
99
99
|
children: [
|
|
100
|
-
H.length > 0 && /* @__PURE__ */ _(
|
|
101
|
-
B?.pendingWrite ? /* @__PURE__ */ _(
|
|
100
|
+
H.length > 0 && /* @__PURE__ */ _(t, { steps: H }),
|
|
101
|
+
B?.pendingWrite ? /* @__PURE__ */ _(o, { pendingWrite: B.pendingWrite }) : null,
|
|
102
102
|
U && /* @__PURE__ */ _("div", {
|
|
103
103
|
className: "text-[15px] leading-relaxed text-text-primary",
|
|
104
|
-
children: /* @__PURE__ */ _(
|
|
104
|
+
children: /* @__PURE__ */ _(a, { content: U })
|
|
105
105
|
}),
|
|
106
106
|
E && /* @__PURE__ */ _("span", {
|
|
107
107
|
"aria-hidden": "true",
|
|
@@ -111,7 +111,7 @@ var E = ({ message: w, isStreaming: E, isFailed: D, isLastAssistant: O, onRetry:
|
|
|
111
111
|
className: "mt-3 space-y-2 border-t border-border-subtle pt-2",
|
|
112
112
|
children: [/* @__PURE__ */ _("p", {
|
|
113
113
|
className: "text-[10px] font-medium uppercase tracking-wide text-text-muted",
|
|
114
|
-
children: A("
|
|
114
|
+
children: A("message.downloads", "Downloads")
|
|
115
115
|
}), /* @__PURE__ */ _("div", {
|
|
116
116
|
className: "flex flex-wrap gap-2",
|
|
117
117
|
children: V.map((e) => {
|
|
@@ -140,13 +140,13 @@ var E = ({ message: w, isStreaming: E, isFailed: D, isLastAssistant: O, onRetry:
|
|
|
140
140
|
type: "button",
|
|
141
141
|
onClick: W,
|
|
142
142
|
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",
|
|
143
|
-
"aria-label": A("
|
|
143
|
+
"aria-label": A("message.copy", "Copy message"),
|
|
144
144
|
"data-testid": "assistant-message-copy",
|
|
145
|
-
children: L ? /* @__PURE__ */ v(g, { children: [/* @__PURE__ */ _(
|
|
145
|
+
children: L ? /* @__PURE__ */ v(g, { children: [/* @__PURE__ */ _(d, { className: "size-3 text-status-success-text" }), /* @__PURE__ */ _("span", { children: A("message.copied", "Copied") })] }) : /* @__PURE__ */ v(g, { children: [/* @__PURE__ */ _(f, { className: "size-3" }), /* @__PURE__ */ _("span", { children: A("message.copy", "Copy") })] })
|
|
146
146
|
}),
|
|
147
147
|
U && P.isSupported && (() => {
|
|
148
148
|
let e = P.blockedFor(w.id) ?? P.disabledReason, t = !!e && !!O, n = t ? `speak-reason-${w.id}` : void 0;
|
|
149
|
-
return /* @__PURE__ */ v(g, { children: [/* @__PURE__ */ _(
|
|
149
|
+
return /* @__PURE__ */ v(g, { children: [/* @__PURE__ */ _(c, {
|
|
150
150
|
isSpeaking: P.isSpeaking(w.id),
|
|
151
151
|
disabled: e !== null,
|
|
152
152
|
disabledReason: e,
|
|
@@ -163,9 +163,9 @@ var E = ({ message: w, isStreaming: E, isFailed: D, isLastAssistant: O, onRetry:
|
|
|
163
163
|
type: "button",
|
|
164
164
|
onClick: k,
|
|
165
165
|
className: `flex items-center gap-1 rounded-md px-1.5 py-1 text-[11px] transition-colors hover:bg-bg-elevated ${D ? "text-status-error-text" : "text-text-muted hover:text-text-secondary"}`,
|
|
166
|
-
"aria-label": A("
|
|
166
|
+
"aria-label": A("message.retry", "Retry"),
|
|
167
167
|
"data-testid": "assistant-message-retry",
|
|
168
|
-
children: [/* @__PURE__ */ _(
|
|
168
|
+
children: [/* @__PURE__ */ _(p, { className: "size-3" }), /* @__PURE__ */ _("span", { children: A("message.retry", "Retry") })]
|
|
169
169
|
})
|
|
170
170
|
]
|
|
171
171
|
}),
|
|
@@ -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 { AssistantPendingWriteCard } from './AssistantPendingWriteCard';\nimport { AssistantMessageAttachments } from './AssistantMessageAttachments';\nimport { AssistantSpeakButton } from './AssistantSpeakButton';\nimport { useAssistantSpeech } from './AssistantSpeechProvider';\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 /**\n * The most recent assistant turn. Retry is offered here too — a turn can\n * \"complete\" with an apology (e.g. a gateway 403 the model reports as text)\n * without ever tripping `isFailed`, and the user still needs a way to re-run.\n */\n isLastAssistant?: 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, isLastAssistant, onRetry }) => {\n const tr = useTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken } = useAuthToken();\n const speech = useAssistantSpeech();\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 // ── System note: neither side of the conversation ────────────────────\n //\n // ★ Everything that is not `role: 'user'` used to fall through to the\n // assistant branch, so a note the app wrote about itself would have rendered\n // as an assistant bubble — complete with Copy and Listen — claiming the model\n // had said something it never said. The only writer today is \"Continue in\n // chat\", and its whole purpose is to be an honest record.\n //\n // Centred, muted and quiet: it is chronology, not conversation.\n if (message.role === 'system') {\n return (\n <div className=\"flex justify-center px-2 py-1\" data-testid=\"assistant-message-system\">\n <p className=\"max-w-[90%] whitespace-pre-wrap break-words rounded-lg border border-border-subtle bg-bg-sunken/60 px-3 py-2 text-center text-xs leading-relaxed text-text-muted\">\n {message.content}\n </p>\n </div>\n );\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 {/* ★ ABOVE the prose, deliberately. The prose is the model asking for\n approval; this is what it actually tried to send. Reading the request\n after the pitch invites skimming past it, and the whole point is that\n the two can disagree. */}\n {metadata?.pendingWrite ? <AssistantPendingWriteCard pendingWrite={metadata.pendingWrite} /> : null}\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 + Read aloud (any settled assistant text) + Retry (failed OR latest turn) */}\n {!isStreaming && (text || isFailed || isLastAssistant) && (\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 {/* Playback is always user-initiated — nothing here autoplays. The\n control is absent (not disabled) where the browser has no speech\n output, matching how the composer treats the microphone. */}\n {text &&\n speech.isSupported &&\n (() => {\n // Two independent reasons this cannot speak: the app language\n // has no voice at all (known up front), or THIS reply came back\n // in another language that has none (only knowable after trying).\n // `isBlocked` is now only the device-has-no-voices-at-all case.\n // Anything language-specific is resolved per reply, so an\n // app-language gap must not pre-emptively disable a reply this\n // device CAN speak.\n const speechBlockedReason = speech.blockedFor(message.id) ?? speech.disabledReason;\n // The reason element is rendered only on the newest reply, so\n // only that button may reference it. A describedby pointing at a\n // missing id is worse than none — assistive tech follows the\n // reference and finds nothing.\n const showsReason = Boolean(speechBlockedReason) && Boolean(isLastAssistant);\n const reasonId = showsReason ? `speak-reason-${message.id}` : undefined;\n return (\n <>\n <AssistantSpeakButton\n isSpeaking={speech.isSpeaking(message.id)}\n disabled={speechBlockedReason !== null}\n disabledReason={speechBlockedReason}\n describedById={reasonId}\n onClick={() => speech.toggle(message.id, text, metadata?.lang)}\n />\n {showsReason && (\n <span id={reasonId} className=\"text-[11px] text-text-muted\" data-testid=\"assistant-speak-reason\">\n {speechBlockedReason}\n </span>\n )}\n </>\n );\n })()}\n {(isFailed || isLastAssistant) && 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] transition-colors hover:bg-bg-elevated ${\n isFailed ? 'text-status-error-text' : 'text-text-muted hover:text-text-secondary'\n }`}\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":";;;;;;;;;;;;;;;;AA+BA,SAAS,EAAqB,GAAwD;CACpF,OAAO,EAAQ,SAAS,cAAc,EAAQ,WAAW,KAAA;AAC3D;AAEA,SAAS,EAAa,GAAqE;CACzF,OAAO,GAAU,aAAa,CAAC;AACjC;AAEA,SAAS,EAAa,GAAwB;CAC5C,OAAO,OAAO,KAAK,CAAM;AAC3B;AAEA,SAAS,EAAmB,GAAgB,GAAkB,GAAwB;CACpF,IAAM,IAAS,EAAa,CAAM,GAC5B,IAAQ,IAAI,WAAW,EAAO,MAAM;CAE1C,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAO,QAAQ,KAAS,GAClD,EAAM,KAAS,EAAO,WAAW,CAAK;CAGxC,IAAM,IAAO,IAAI,KAAK,CAAC,CAAK,GAAG,EAAE,MAAM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;QACxC,UAAU,MAAwB;QAClC,gBAAgB;QAChB,eAAe;QACf,eAAe,EAAO,OAAO,EAAQ,IAAI,GAAM,GAAU,IAAI;OAC9D,CAAA,GACA,KACC,kBAAC,QAAD;QAAM,IAAI;QAAU,WAAU;QAA8B,eAAY;kBACrE;OACG,CAAA,CAER,EAAA,CAAA;MAEN,GAAG;OACH,KAAY,MAAoB,KAChC,kBAAC,UAAD;OACE,MAAK;OACL,SAAS;OACT,WAAW,qGACT,IAAW,2BAA2B;OAExC,cAAY,EAAG,uCAAuC,OAAO;OAC7D,eAAY;iBAPd,CASE,kBAAC,GAAD,EAAW,WAAU,SAAU,CAAA,GAC/B,kBAAC,QAAD,EAAA,UAAO,EAAG,uCAAuC,OAAO,EAAQ,CAAA,CAC1D;;KAEP;;IAGP,kBAAC,OAAD;KAAK,WAAU;eAAf,CACG,GACA,EAAQ,UAAU,kBAAC,QAAD;MAAM,WAAU;gBAAhB,CAAwB,EAAQ,OAAO,QAAQ,EAAQ,OAAO,QAAO,SAAa;OAClG;;GACF;IACF;;AAET"}
|
|
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 { AssistantPendingWriteCard } from './AssistantPendingWriteCard';\nimport { AssistantMessageAttachments } from './AssistantMessageAttachments';\nimport { AssistantSpeakButton } from './AssistantSpeakButton';\nimport { useAssistantSpeech } from './AssistantSpeechProvider';\nimport { AssistantToolActivity, parseToolActivity } from './AssistantToolActivity';\nimport { downloadAssistantArtifact } from '@/services/assistantApi';\nimport type { AssistantArtifact, AssistantMessageMetadata, Message } from '@/types/assistant';\nimport { useAssistantTr } from '@burdenoff/fe-libs/shared/assistant';\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 /**\n * The most recent assistant turn. Retry is offered here too — a turn can\n * \"complete\" with an apology (e.g. a gateway 403 the model reports as text)\n * without ever tripping `isFailed`, and the user still needs a way to re-run.\n */\n isLastAssistant?: 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, isLastAssistant, onRetry }) => {\n const tr = useAssistantTr();\n const apollo = useGatewayClient('workspace');\n const { getAccessToken, getWorkspaceToken } = useAuthToken();\n const speech = useAssistantSpeech();\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 // ── System note: neither side of the conversation ────────────────────\n //\n // ★ Everything that is not `role: 'user'` used to fall through to the\n // assistant branch, so a note the app wrote about itself would have rendered\n // as an assistant bubble — complete with Copy and Listen — claiming the model\n // had said something it never said. The only writer today is \"Continue in\n // chat\", and its whole purpose is to be an honest record.\n //\n // Centred, muted and quiet: it is chronology, not conversation.\n if (message.role === 'system') {\n return (\n <div className=\"flex justify-center px-2 py-1\" data-testid=\"assistant-message-system\">\n <p className=\"max-w-[90%] whitespace-pre-wrap break-words rounded-lg border border-border-subtle bg-bg-sunken/60 px-3 py-2 text-center text-xs leading-relaxed text-text-muted\">\n {message.content}\n </p>\n </div>\n );\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 {/* ★ ABOVE the prose, deliberately. The prose is the model asking for\n approval; this is what it actually tried to send. Reading the request\n after the pitch invites skimming past it, and the whole point is that\n the two can disagree. */}\n {metadata?.pendingWrite ? <AssistantPendingWriteCard pendingWrite={metadata.pendingWrite} /> : null}\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('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 + Read aloud (any settled assistant text) + Retry (failed OR latest turn) */}\n {!isStreaming && (text || isFailed || isLastAssistant) && (\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('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('message.copied', 'Copied')}</span>\n </>\n ) : (\n <>\n <Copy className=\"size-3\" />\n <span>{tr('message.copy', 'Copy')}</span>\n </>\n )}\n </button>\n )}\n {/* Playback is always user-initiated — nothing here autoplays. The\n control is absent (not disabled) where the browser has no speech\n output, matching how the composer treats the microphone. */}\n {text &&\n speech.isSupported &&\n (() => {\n // Two independent reasons this cannot speak: the app language\n // has no voice at all (known up front), or THIS reply came back\n // in another language that has none (only knowable after trying).\n // `isBlocked` is now only the device-has-no-voices-at-all case.\n // Anything language-specific is resolved per reply, so an\n // app-language gap must not pre-emptively disable a reply this\n // device CAN speak.\n const speechBlockedReason = speech.blockedFor(message.id) ?? speech.disabledReason;\n // The reason element is rendered only on the newest reply, so\n // only that button may reference it. A describedby pointing at a\n // missing id is worse than none — assistive tech follows the\n // reference and finds nothing.\n const showsReason = Boolean(speechBlockedReason) && Boolean(isLastAssistant);\n const reasonId = showsReason ? `speak-reason-${message.id}` : undefined;\n return (\n <>\n <AssistantSpeakButton\n isSpeaking={speech.isSpeaking(message.id)}\n disabled={speechBlockedReason !== null}\n disabledReason={speechBlockedReason}\n describedById={reasonId}\n onClick={() => speech.toggle(message.id, text, metadata?.lang)}\n />\n {showsReason && (\n <span id={reasonId} className=\"text-[11px] text-text-muted\" data-testid=\"assistant-speak-reason\">\n {speechBlockedReason}\n </span>\n )}\n </>\n );\n })()}\n {(isFailed || isLastAssistant) && 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] transition-colors hover:bg-bg-elevated ${\n isFailed ? 'text-status-error-text' : 'text-text-muted hover:text-text-secondary'\n }`}\n aria-label={tr('message.retry', 'Retry')}\n data-testid=\"assistant-message-retry\"\n >\n <RotateCcw className=\"size-3\" />\n <span>{tr('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":";;;;;;;;;;;;;;;;AA+BA,SAAS,EAAqB,GAAwD;CACpF,OAAO,EAAQ,SAAS,cAAc,EAAQ,WAAW,KAAA;AAC3D;AAEA,SAAS,EAAa,GAAqE;CACzF,OAAO,GAAU,aAAa,CAAC;AACjC;AAEA,SAAS,EAAa,GAAwB;CAC5C,OAAO,OAAO,KAAK,CAAM;AAC3B;AAEA,SAAS,EAAmB,GAAgB,GAAkB,GAAwB;CACpF,IAAM,IAAS,EAAa,CAAM,GAC5B,IAAQ,IAAI,WAAW,EAAO,MAAM;CAE1C,KAAK,IAAI,IAAQ,GAAG,IAAQ,EAAO,QAAQ,KAAS,GAClD,EAAM,KAAS,EAAO,WAAW,CAAK;CAGxC,IAAM,IAAO,IAAI,KAAK,CAAC,CAAK,GAAG,EAAE,MAA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AAE;QACxC,UAAU,MAAwB;QAClC,gBAAgB;QAChB,eAAe;QACf,eAAe,EAAO,OAAO,EAAQ,IAAI,GAAM,GAAU,IAAI;OAC9D,CAAA,GACA,KACC,kBAAC,QAAD;QAAM,IAAI;QAAU,WAAU;QAA8B,eAAY;kBACrE;OACG,CAAA,CAER,EAAA,CAAA;MAEN,GAAG;OACH,KAAY,MAAoB,KAChC,kBAAC,UAAD;OACE,MAAK;OACL,SAAS;OACT,WAAW,qGACT,IAAW,2BAA2B;OAExC,cAAY,EAAG,iBAAiB,OAAO;OACvC,eAAY;iBAPd,CASE,kBAAC,GAAD,EAAW,WAAU,SAAU,CAAA,GAC/B,kBAAC,QAAD,EAAA,UAAO,EAAG,iBAAiB,OAAO,EAAQ,CAAA,CACpC;;KAEP;;IAGP,kBAAC,OAAD;KAAK,WAAU;eAAf,CACG,GACA,EAAQ,UAAU,kBAAC,QAAD;MAAM,WAAU;gBAAhB,CAAwB,EAAQ,OAAO,QAAQ,EAAQ,OAAO,QAAO,SAAa;OAClG;;GACF;IACF;;AAET"}
|
|
@@ -1,20 +1,20 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { AssistantMessageItem as e } from "./AssistantMessageItem.js";
|
|
2
|
+
import { useEffect as t, useRef as n } from "react";
|
|
3
|
+
import { useAssistantTr as r } from "@burdenoff/fe-libs/shared/assistant";
|
|
4
4
|
import { jsx as i, jsxs as a } from "react/jsx-runtime";
|
|
5
5
|
//#region src/components/assistant/AssistantMessageList.tsx
|
|
6
6
|
var o = ({ messages: o, streamingMessageId: s, failedMessageId: c, onRetry: l }) => {
|
|
7
|
-
let u =
|
|
7
|
+
let u = r(), d = (() => {
|
|
8
8
|
for (let e = o.length - 1; e >= 0; --e) if (o[e].role === "assistant") return o[e].id;
|
|
9
9
|
return null;
|
|
10
|
-
})(), f =
|
|
11
|
-
return
|
|
10
|
+
})(), f = n(null), p = n(null);
|
|
11
|
+
return t(() => {
|
|
12
12
|
let e = p.current;
|
|
13
13
|
if (e && e.scrollHeight - e.scrollTop - e.clientHeight < 100) {
|
|
14
14
|
let e = typeof window < "u" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;
|
|
15
15
|
f.current?.scrollIntoView({ behavior: e ? "auto" : "smooth" });
|
|
16
16
|
}
|
|
17
|
-
}, [o, s]),
|
|
17
|
+
}, [o, s]), t(() => {
|
|
18
18
|
f.current?.scrollIntoView({ behavior: "instant" });
|
|
19
19
|
}, []), /* @__PURE__ */ a("div", {
|
|
20
20
|
ref: p,
|
|
@@ -23,14 +23,14 @@ var o = ({ messages: o, streamingMessageId: s, failedMessageId: c, onRetry: l })
|
|
|
23
23
|
"aria-live": "polite",
|
|
24
24
|
"aria-relevant": "additions",
|
|
25
25
|
"aria-busy": s !== null,
|
|
26
|
-
"aria-label": u("
|
|
27
|
-
children: [o.map((
|
|
28
|
-
message:
|
|
29
|
-
isStreaming:
|
|
30
|
-
isFailed:
|
|
31
|
-
isLastAssistant:
|
|
26
|
+
"aria-label": u("messageList.ariaLabel", "Conversation messages"),
|
|
27
|
+
children: [o.map((t) => /* @__PURE__ */ i(e, {
|
|
28
|
+
message: t,
|
|
29
|
+
isStreaming: t.id === s,
|
|
30
|
+
isFailed: t.id === c,
|
|
31
|
+
isLastAssistant: t.id === d,
|
|
32
32
|
onRetry: l
|
|
33
|
-
},
|
|
33
|
+
}, t.id)), /* @__PURE__ */ i("div", { ref: f })]
|
|
34
34
|
});
|
|
35
35
|
};
|
|
36
36
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantMessageList.js","names":[],"sources":["../../../src/components/assistant/AssistantMessageList.tsx"],"sourcesContent":["import { useEffect, useRef, type FC } from 'react';\nimport { AssistantMessageItem } from './AssistantMessageItem';\nimport type { Message } from '@/types/assistant';\nimport {
|
|
1
|
+
{"version":3,"file":"AssistantMessageList.js","names":[],"sources":["../../../src/components/assistant/AssistantMessageList.tsx"],"sourcesContent":["import { useEffect, useRef, type FC } from 'react';\nimport { AssistantMessageItem } from './AssistantMessageItem';\nimport type { Message } from '@/types/assistant';\nimport { useAssistantTr } from '@burdenoff/fe-libs/shared/assistant';\n\ninterface Props {\n messages: Message[];\n streamingMessageId: string | null;\n /** The assistant message (if any) whose turn ended in an error. */\n failedMessageId?: string | null;\n /** Re-send the last user prompt — shown on the failed message. */\n onRetry?: () => void;\n}\n\nexport const AssistantMessageList: FC<Props> = ({ messages, streamingMessageId, failedMessageId, onRetry }) => {\n const tr = useAssistantTr();\n\n // The newest assistant turn also gets a Retry control: a turn can settle with\n // an apology (e.g. the model reporting a gateway 403 as text) without ever\n // setting `failedMessageId`, and the user still needs a one-click re-run.\n const lastAssistantId = (() => {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n if (messages[index].role === 'assistant') return messages[index].id;\n }\n return null;\n })();\n const bottomRef = useRef<HTMLDivElement>(null);\n const containerRef = useRef<HTMLDivElement>(null);\n\n // Auto-scroll to bottom on new messages or streaming updates\n useEffect(() => {\n const container = containerRef.current;\n if (!container) return;\n\n // Only auto-scroll if user is near the bottom (within 100px)\n const isNearBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 100;\n\n if (isNearBottom) {\n // A reply streaming in scrolls on nearly every poll; smooth-scrolling that\n // is exactly the repeated involuntary motion WCAG 2.3.3 asks us to avoid.\n const prefersReducedMotion =\n typeof window !== 'undefined' && window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;\n bottomRef.current?.scrollIntoView({ behavior: prefersReducedMotion ? 'auto' : 'smooth' });\n }\n }, [messages, streamingMessageId]);\n\n // Always scroll on first render\n useEffect(() => {\n bottomRef.current?.scrollIntoView({ behavior: 'instant' });\n }, []);\n\n return (\n <div\n ref={containerRef}\n className=\"flex-1 space-y-4 overflow-y-auto p-3\"\n role=\"log\"\n aria-live=\"polite\"\n // A streaming reply rewrites its bubble on every poll. Without these, a\n // screen reader re-reads the whole growing answer each time; announcing\n // only ADDITIONS, and marking the in-flight turn busy, means the user\n // hears the finished reply once instead of a dozen partial ones.\n aria-relevant=\"additions\"\n aria-busy={streamingMessageId !== null}\n aria-label={tr('messageList.ariaLabel', 'Conversation messages')}\n >\n {messages.map((message) => (\n <AssistantMessageItem\n key={message.id}\n message={message}\n isStreaming={message.id === streamingMessageId}\n isFailed={message.id === failedMessageId}\n isLastAssistant={message.id === lastAssistantId}\n onRetry={onRetry}\n />\n ))}\n <div ref={bottomRef} />\n </div>\n );\n};\n"],"mappings":";;;;;AAcA,IAAa,KAAmC,EAAE,aAAU,uBAAoB,oBAAiB,iBAAc;CAC7G,IAAM,IAAK,EAAe,GAKpB,WAAyB;EAC7B,KAAK,IAAI,IAAQ,EAAS,SAAS,GAAG,KAAS,GAAG,KAChD,IAAI,EAAS,GAAO,SAAS,aAAa,OAAO,EAAS,GAAO;EAEnE,OAAO;CACT,GAAG,GACG,IAAY,EAAuB,IAAI,GACvC,IAAe,EAAuB,IAAI;CAwBhD,OArBA,QAAgB;EACd,IAAM,IAAY,EAAa;EAC1B,SAGgB,EAAU,eAAe,EAAU,YAAY,EAAU,eAAe,KAE3E;GAGhB,IAAM,IACJ,OAAO,SAAW,OAAe,OAAO,aAAa,kCAAkC,EAAE;GAC3F,EAAU,SAAS,eAAe,EAAE,UAAU,IAAuB,SAAS,SAAS,CAAC;EAC1F;CACF,GAAG,CAAC,GAAU,CAAkB,CAAC,GAGjC,QAAgB;EACd,EAAU,SAAS,eAAe,EAAE,UAAU,UAAU,CAAC;CAC3D,GAAG,CAAC,CAAC,GAGH,kBAAC,OAAD;EACE,KAAK;EACL,WAAU;EACV,MAAK;EACL,aAAU;EAKV,iBAAc;EACd,aAAW,MAAuB;EAClC,cAAY,EAAG,yBAAyB,uBAAuB;YAXjE,CAaG,EAAS,KAAK,MACb,kBAAC,GAAD;GAEW;GACT,aAAa,EAAQ,OAAO;GAC5B,UAAU,EAAQ,OAAO;GACzB,iBAAiB,EAAQ,OAAO;GACvB;EACV,GANM,EAAQ,EAMd,CACF,GACD,kBAAC,OAAD,EAAK,KAAK,EAAY,CAAA,CACnB;;AAET"}
|