Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(ui): in-app file preview for agent-reply attachments (#429)
Call White3905f48b69ae
diff --git a/docs/plans/file-preview-component.md b/docs/plans/file-preview-component.mdnew file mode 100644index 000000000..42cb78e3b--- /dev/null+++ b/docs/plans/file-preview-component.md@@ -0,0 +1,62 @@+# In-app file preview for agent-reply attachments++## Background++A file card's "eye" button currently opens the media proxy URL with+`target="_blank"`, kicking the user out to a browser/OS preview. We want a+generic, in-app file viewer for readable text-based files, and to hide the eye+for formats we can't render.++## Goal++- One reusable viewer that renders previewable files in a modal.+- Supported kinds: Markdown, plain text/log, CSV (table), JSON+ (collapsible + highlighted), code (syntax-highlighted), markup source+ (HTML/XML/SVG shown as highlighted source, never executed).+- Copy button for text-based content.+- The eye icon only shows when the file is previewable.+- No bundle-size regression on the main app.++## Solution++- `ui/src/lib/filePreview.ts` — `previewKind(name, mime)` allowlist (single+ source of truth for eye-gating) + `codeLanguage(name)` (ext → Shiki lang id)+ + `formatBytes` (shared with FileCard) + size/row caps.+- `ui/src/lib/highlighter.ts` — lean Shiki: `shiki/core` + JS RegExp engine (no+ WASM), grammars/themes dynamically imported per language. Only imported by the+ lazy modal, so nothing reaches the main bundle.+- `ui/src/components/ui/file-viewer.tsx` — light `FileViewerProvider` + context+ (`useFileViewer().open({url,name})`) + `React.lazy` modal. Mirrors the+ existing `ImageViewerProvider`.+- `ui/src/components/ui/file-viewer-modal.tsx` — heavy, lazy: fetch via+ `apiFetch` (≤1MB cap, 401 recovery), header (name/type/size · copy · download ·+ close), renders by kind. Markdown reuses `<Markdown interactive={false}>`;+ JSON uses `@uiw/react-json-view`; CSV uses `papaparse` (first+ `CSV_MAX_ROWS=500` rows); code/source/yaml use the Shiki helper.+- `FileCard` — show the eye only when `previewKind(meta) !== null`; the eye opens+ the viewer (falls back to `target="_blank"` if no provider mounted).+- Mount `FileViewerProvider` alongside `ImageViewerProvider` in `ChatPage`.++## Decisions (confirmed)++- Code highlighter: **Shiki**, lazy-loaded, JS engine.+- JSON viewer: **@uiw/react-json-view**.+- CSV: **papaparse**. Markdown: reuse existing renderer.+- Unsupported formats (incl. PDF): hide the eye. PDF preview is a possible+ later phase (pdf.js).+- Caps: preview ≤ 1 MB; CSV first 500 rows.++## Security++- HTML/XML/SVG render as highlighted **source only**, never executed.+- Markdown reuses the existing renderer's same-origin-only `<img>` handling.+- Shiki output escapes the code text; JSON/CSV/text are inert.++## Todo++- [ ] filePreview.ts + highlighter.ts+- [ ] FileViewer provider + lazy modal + renderers+- [ ] index.css: shiki / table / viewer styles+- [ ] Gate FileCard eye; mount provider in ChatPage+- [ ] i18n keys (en/zh)+- [ ] `npm run build` + lint; reviewer; PRdiff --git a/ui/package-lock.json b/ui/package-lock.jsonindex 32ac630d6..d23b6300b 100644--- a/ui/package-lock.json+++ b/ui/package-lock.json@@ -13,6 +13,9 @@"@radix-ui/react-popover": "^1.1.15","@radix-ui/react-separator": "^1.1.8","@radix-ui/react-slot": "^1.2.4",+ "@shikijs/langs": "^4.2.0",+ "@shikijs/themes": "^4.2.0",+ "@uiw/react-json-view": "^2.0.0-alpha.43","agentation": "^3.0.2","class-variance-authority": "^0.7.1","clsx": "^2.1.1",@@ -21,6 +24,7 @@"i18next": "^25.7.4","i18next-browser-languagedetector": "^8.2.0","lucide-react": "^0.562.0",+ "papaparse": "^5.5.3","qrcode.react": "^4.2.0","react": "^19.2.0","react-dom": "^19.2.0",@@ -28,6 +32,7 @@"react-markdown": "^10.1.0","react-router-dom": "^7.12.0","remark-gfm": "^4.0.1",+ "shiki": "^4.2.0","tailwind-merge": "^3.4.0","tw-animate-css": "^1.4.0"},@@ -35,6 +40,7 @@"@eslint/js": "^9.39.1","@tailwindcss/postcss": "^4.1.18","@types/node": "^24.10.1",+ "@types/papaparse": "^5.5.2","@types/react": "^19.2.5","@types/react-dom": "^19.2.3","@vitejs/plugin-react": "^5.1.1",@@ -303,6 +309,7 @@"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.6.tgz","integrity": "sha512-05WQkdpL9COIMz4LjTxGpPNCdlpyimKppYNoJ5Di5EUObifl8t4tuLuUBBZEpoLYOmfvIWrsp9fCl0HoPRVTdA==","license": "MIT",+ "peer": true,"engines": {"node": ">=6.9.0"}@@ -2062,6 +2069,106 @@"win32"]},+ "node_modules/@shikijs/core": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/@shikijs/core/-/core-4.2.0.tgz",+ "integrity": "sha512-Hc87Ab1Ld/vEbZRCbwx344I5v+4RU8CVToUTRkqXL1+TjbuOp9U5Xa0M23V4GEWHxVn+yO5otb+HkQVm3ptWQQ==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/primitive": "4.2.0",+ "@shikijs/types": "4.2.0",+ "@shikijs/vscode-textmate": "^10.0.2",+ "@types/hast": "^3.0.4",+ "hast-util-to-html": "^9.0.5"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/@shikijs/engine-javascript": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/@shikijs/engine-javascript/-/engine-javascript-4.2.0.tgz",+ "integrity": "sha512-fjETeq1k5ffyXqRgS6+3hpvqseLalp1kjNfRbXpUgWR8FpZ1CmQfiNHovc5lncYjt/Vg5JK/WJEmLahjwMa0og==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "4.2.0",+ "@shikijs/vscode-textmate": "^10.0.2",+ "oniguruma-to-es": "^4.3.6"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/@shikijs/engine-oniguruma": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/@shikijs/engine-oniguruma/-/engine-oniguruma-4.2.0.tgz",+ "integrity": "sha512-hTorK1dffPkpbMUk6Z+828PgRo7d07HbnizoP0hNPFjhxMHctj0Px/qoHeGMYafc6ju+u9iMldN4JbVzNQM++g==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "4.2.0",+ "@shikijs/vscode-textmate": "^10.0.2"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/@shikijs/langs": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/@shikijs/langs/-/langs-4.2.0.tgz",+ "integrity": "sha512-bwrVRlJ0wUhZxAbVdvBbv2TTC9yLsh4C/IO5Ofz0T8MQntgDvyVnkbjw9vi50r1kx7RCIJdnJnjZAwmAsXFLZQ==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "4.2.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/@shikijs/primitive": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/@shikijs/primitive/-/primitive-4.2.0.tgz",+ "integrity": "sha512-NOq+DtUkVBJtZMVXL5A0vI0Xk8nvDYaXetFHSJFlOqjDZIVhIPRYFdGkSoElDqNuegikcc3A76SNUa8dTqtAYA==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "4.2.0",+ "@shikijs/vscode-textmate": "^10.0.2",+ "@types/hast": "^3.0.4"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/@shikijs/themes": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/@shikijs/themes/-/themes-4.2.0.tgz",+ "integrity": "sha512-RX8IHYeLv8Cu2W6ruc3RxUqWn0IYCqSrMBzi/uRGAmfyDNOnNO5BF/Px7o97n4XTpmFTo5GbRaazuOWj+2ak2w==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/types": "4.2.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/@shikijs/types": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/@shikijs/types/-/types-4.2.0.tgz",+ "integrity": "sha512-VT/MKtlpOhEPZloSH3Pb9WCZEBDoQVMa9jedp5UAwmJOar1DVc9DRODAxmYPW9M93IK4ryuqRejFfmlvlVDemw==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/vscode-textmate": "^10.0.2",+ "@types/hast": "^3.0.4"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/@shikijs/vscode-textmate": {+ "version": "10.0.2",+ "resolved": "https://registry.npmjs.org/@shikijs/vscode-textmate/-/vscode-textmate-10.0.2.tgz",+ "integrity": "sha512-83yeghZ2xxin3Nj8z1NMd/NCuca+gsYXswywDy5bHvwlWL8tpTQmzGeUuHd9FC3E/SBEMvzJRwWEOz5gGes9Qg==",+ "license": "MIT"+ },"node_modules/@tailwindcss/node": {"version": "4.1.18","resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.1.18.tgz",@@ -2444,6 +2551,16 @@"undici-types": "~7.16.0"}},+ "node_modules/@types/papaparse": {+ "version": "5.5.2",+ "resolved": "https://registry.npmjs.org/@types/papaparse/-/papaparse-5.5.2.tgz",+ "integrity": "sha512-gFnFp/JMzLHCwRf7tQHrNnfhN4eYBVYYI897CGX4MY1tzY9l2aLkVyx2IlKZ/SAqDbB3I1AOZW5gTMGGsqWliA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@types/react": {"version": "19.2.8","resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.8.tgz",@@ -2741,6 +2858,20 @@"url": "https://opencollective.com/typescript-eslint"}},+ "node_modules/@uiw/react-json-view": {+ "version": "2.0.0-alpha.43",+ "resolved": "https://registry.npmjs.org/@uiw/react-json-view/-/react-json-view-2.0.0-alpha.43.tgz",+ "integrity": "sha512-PMj+6xRDCPbVGccfLUDhx7yGrmVBSeFx3py6bqDds4QIYScXo9GEgtTbWXn3gXpoehsmOu//6dveYTf872wu3Q==",+ "license": "MIT",+ "funding": {+ "url": "https://jaywcjlove.github.io/#/sponsor"+ },+ "peerDependencies": {+ "@babel/runtime": ">=7.10.0",+ "react": ">=18.0.0",+ "react-dom": ">=18.0.0"+ }+ },"node_modules/@ungap/structured-clone": {"version": "1.3.1","resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.1.tgz",@@ -3755,6 +3886,29 @@"node": ">=8"}},+ "node_modules/hast-util-to-html": {+ "version": "9.0.5",+ "resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz",+ "integrity": "sha512-OguPdidb+fbHQSU4Q4ZiLKnzWo8Wwsf5bZfbvu7//a9oTYoqD/fWpe96NuHkoS9h0ccGOTe0C4NGXdtS0iObOw==",+ "license": "MIT",+ "dependencies": {+ "@types/hast": "^3.0.0",+ "@types/unist": "^3.0.0",+ "ccount": "^2.0.0",+ "comma-separated-tokens": "^2.0.0",+ "hast-util-whitespace": "^3.0.0",+ "html-void-elements": "^3.0.0",+ "mdast-util-to-hast": "^13.0.0",+ "property-information": "^7.0.0",+ "space-separated-tokens": "^2.0.0",+ "stringify-entities": "^4.0.0",+ "zwitch": "^2.0.4"+ },+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/unified"+ }+ },"node_modules/hast-util-to-jsx-runtime": {"version": "2.3.6","resolved": "https://registry.npmjs.org/hast-util-to-jsx-runtime/-/hast-util-to-jsx-runtime-2.3.6.tgz",@@ -3831,6 +3985,16 @@"url": "https://opencollective.com/unified"}},+ "node_modules/html-void-elements": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/html-void-elements/-/html-void-elements-3.0.0.tgz",+ "integrity": "sha512-bEqo66MRXsUGxWHV5IP0PUiAWwoEjba4VCzg0LjFJBpchPaTfyfCKTG6bc5F8ucKec3q5y6qOdGyYTSBEvhCrg==",+ "license": "MIT",+ "funding": {+ "type": "github",+ "url": "https://github.com/sponsors/wooorm"+ }+ },"node_modules/i18next": {"version": "25.7.4","resolved": "https://registry.npmjs.org/i18next/-/i18next-25.7.4.tgz",@@ -5347,6 +5511,23 @@"dev": true,"license": "MIT"},+ "node_modules/oniguruma-parser": {+ "version": "0.12.2",+ "resolved": "https://registry.npmjs.org/oniguruma-parser/-/oniguruma-parser-0.12.2.tgz",+ "integrity": "sha512-6HVa5oIrgMC6aA6WF6XyyqbhRPJrKR02L20+2+zpDtO5QAzGHAUGw5TKQvwi5vctNnRHkJYmjAhRVQF2EKdTQw==",+ "license": "MIT"+ },+ "node_modules/oniguruma-to-es": {+ "version": "4.3.6",+ "resolved": "https://registry.npmjs.org/oniguruma-to-es/-/oniguruma-to-es-4.3.6.tgz",+ "integrity": "sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==",+ "license": "MIT",+ "dependencies": {+ "oniguruma-parser": "^0.12.2",+ "regex": "^6.1.0",+ "regex-recursion": "^6.0.2"+ }+ },"node_modules/optionator": {"version": "0.9.4","resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz",@@ -5397,6 +5578,12 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/papaparse": {+ "version": "5.5.3",+ "resolved": "https://registry.npmjs.org/papaparse/-/papaparse-5.5.3.tgz",+ "integrity": "sha512-5QvjGxYVjxO59MGU2lHVYpRWBBtKHnlIAcSe1uNFCkkptUh63NFRj0FJQm7nR67puEruUci/ZkjmEFrjCAyP4A==",+ "license": "MIT"+ },"node_modules/parent-module": {"version": "1.0.1","resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",@@ -5746,6 +5933,30 @@}}},+ "node_modules/regex": {+ "version": "6.1.0",+ "resolved": "https://registry.npmjs.org/regex/-/regex-6.1.0.tgz",+ "integrity": "sha512-6VwtthbV4o/7+OaAF9I5L5V3llLEsoPyq9P1JVXkedTP33c7MfCG0/5NOPcSJn0TzXcG9YUrR0gQSWioew3LDg==",+ "license": "MIT",+ "dependencies": {+ "regex-utilities": "^2.3.0"+ }+ },+ "node_modules/regex-recursion": {+ "version": "6.0.2",+ "resolved": "https://registry.npmjs.org/regex-recursion/-/regex-recursion-6.0.2.tgz",+ "integrity": "sha512-0YCaSCq2VRIebiaUviZNs0cBz1kg5kVS2UKUfNIx8YVs1cN3AV7NTctO5FOKBA+UT2BPJIWZauYHPqJODG50cg==",+ "license": "MIT",+ "dependencies": {+ "regex-utilities": "^2.3.0"+ }+ },+ "node_modules/regex-utilities": {+ "version": "2.3.0",+ "resolved": "https://registry.npmjs.org/regex-utilities/-/regex-utilities-2.3.0.tgz",+ "integrity": "sha512-8VhliFJAWRaUiVvREIiW2NXXTmHs4vMNnSzuJVhscgmGav3g9VDxLrQndI3dZZVVdp0ZO/5v0xmX516/7M9cng==",+ "license": "MIT"+ },"node_modules/remark-gfm": {"version": "4.0.1","resolved": "https://registry.npmjs.org/remark-gfm/-/remark-gfm-4.0.1.tgz",@@ -5912,6 +6123,25 @@"node": ">=8"}},+ "node_modules/shiki": {+ "version": "4.2.0",+ "resolved": "https://registry.npmjs.org/shiki/-/shiki-4.2.0.tgz",+ "integrity": "sha512-hjNax6o/ylDy9lefQEaSDtzaT3iVNtZ3WmpQnbuQNoG4xvnSKf2kSKbihZVO4JRG1TTMejs7CmNRYlWgAL66pQ==",+ "license": "MIT",+ "dependencies": {+ "@shikijs/core": "4.2.0",+ "@shikijs/engine-javascript": "4.2.0",+ "@shikijs/engine-oniguruma": "4.2.0",+ "@shikijs/langs": "4.2.0",+ "@shikijs/themes": "4.2.0",+ "@shikijs/types": "4.2.0",+ "@shikijs/vscode-textmate": "^10.0.2",+ "@types/hast": "^3.0.4"+ },+ "engines": {+ "node": ">=20"+ }+ },"node_modules/source-map-js": {"version": "1.2.1","resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",diff --git a/ui/package.json b/ui/package.jsonindex 8560b1a5a..936e77424 100644--- a/ui/package.json+++ b/ui/package.json@@ -16,6 +16,9 @@"@radix-ui/react-popover": "^1.1.15","@radix-ui/react-separator": "^1.1.8","@radix-ui/react-slot": "^1.2.4",+ "@shikijs/langs": "^4.2.0",+ "@shikijs/themes": "^4.2.0",+ "@uiw/react-json-view": "^2.0.0-alpha.43","agentation": "^3.0.2","class-variance-authority": "^0.7.1","clsx": "^2.1.1",@@ -24,6 +27,7 @@"i18next": "^25.7.4","i18next-browser-languagedetector": "^8.2.0","lucide-react": "^0.562.0",+ "papaparse": "^5.5.3","qrcode.react": "^4.2.0","react": "^19.2.0","react-dom": "^19.2.0",@@ -31,6 +35,7 @@"react-markdown": "^10.1.0","react-router-dom": "^7.12.0","remark-gfm": "^4.0.1",+ "shiki": "^4.2.0","tailwind-merge": "^3.4.0","tw-animate-css": "^1.4.0"},@@ -38,6 +43,7 @@"@eslint/js": "^9.39.1","@tailwindcss/postcss": "^4.1.18","@types/node": "^24.10.1",+ "@types/papaparse": "^5.5.2","@types/react": "^19.2.5","@types/react-dom": "^19.2.3","@vitejs/plugin-react": "^5.1.1",diff --git a/ui/src/components/ui/file-card.tsx b/ui/src/components/ui/file-card.tsxindex 6c5a62a7c..989c790e0 100644--- a/ui/src/components/ui/file-card.tsx+++ b/ui/src/components/ui/file-card.tsx@@ -7,6 +7,8 @@ import { Button } from '@/components/ui/button';import { apiFetch } from '@/lib/apiFetch';import { isProxyMediaUrl } from '@/lib/mediaProxy';import { handleMediaDownloadClick } from '@/lib/downloadMedia';+import { useFileViewer } from '@/components/ui/file-viewer';+import { previewKind, formatBytes } from '@/lib/filePreview';import { cn } from '@/lib/utils';// Download card for an agent-reply file that was rewritten to the same-origin@@ -30,18 +32,6 @@ function kindOf(ext: string): { Icon: LucideIcon; tile: string } {return { Icon: File, tile: 'bg-mint/15 text-mint' };}-function formatSize(bytes?: number | null): string {- if (!bytes || bytes <= 0) return '';- const units = ['B', 'KB', 'MB', 'GB', 'TB'];- let value = bytes;- let i = 0;- while (value >= 1024 && i < units.length - 1) {- value /= 1024;- i += 1;- }- return `${value >= 10 || i === 0 ? Math.round(value) : value.toFixed(1)} ${units[i]}`;-}-function nodeText(node: React.ReactNode): string {if (node == null || node === false || node === true) return '';if (typeof node === 'string' || typeof node === 'number') return String(node);@@ -50,10 +40,11 @@ function nodeText(node: React.ReactNode): string {return '';}-type Meta = { name?: string; ext?: string; size?: number | null };+type Meta = { name?: string; ext?: string; size?: number | null; content_type?: string };export const FileCard: React.FC<{ href: string; children?: React.ReactNode }> = ({ href, children }) => {const { t } = useTranslation();+ const viewer = useFileViewer();const label = nodeText(children).trim();const [meta, setMeta] = React.useState<Meta | null>(null);@@ -76,7 +67,14 @@ export const FileCard: React.FC<{ href: string; children?: React.ReactNode }> =const ext = (meta?.ext || label.split('.').pop() || '').toLowerCase();const { Icon, tile } = kindOf(ext);const title = label || meta?.name || 'file';- const metaLine = [ext ? ext.toUpperCase() : null, formatSize(meta?.size) || null].filter(Boolean).join(' · ');+ const metaLine = [ext ? ext.toUpperCase() : null, formatBytes(meta?.size) || null].filter(Boolean).join(' · ');+ // Show the preview ("eye") only for kinds we can render (gated on name + the+ // server's content-type). In-app preview is restricted to our own same-origin+ // proxy files — a non-proxy URL must never be auto-fetched (it'd leak the+ // viewer's network to a third-party host), so those keep a plain "open in new+ // tab" eye instead.+ const proxy = isProxyMediaUrl(href);+ const previewable = previewKind(meta?.name || label, meta?.content_type, meta?.ext) !== null;return (<span className="my-1 inline-flex min-w-[240px] max-w-full items-center gap-3 rounded-[10px] border border-border bg-surface-2 px-3 py-2.5 align-middle no-underline">@@ -88,11 +86,24 @@ export const FileCard: React.FC<{ href: string; children?: React.ReactNode }> ={metaLine && <span className="font-mono text-[10px] text-muted">{metaLine}</span>}</span><span className="ml-auto flex shrink-0 items-center gap-1.5">- <Button asChild variant="ghost" size="icon" className="size-8" aria-label={t('chat.media.preview')}>- <a href={href} target="_blank" rel="noopener noreferrer">- <Eye className="size-4" />- </a>- </Button>+ {previewable &&+ (proxy && viewer ? (+ <Button+ variant="ghost"+ size="icon"+ className="size-8"+ aria-label={t('chat.media.preview')}+ onClick={() => viewer.open({ url: href, name: meta?.name || label })}+ >+ <Eye className="size-4" />+ </Button>+ ) : (+ <Button asChild variant="ghost" size="icon" className="size-8" aria-label={t('chat.media.preview')}>+ <a href={href} target="_blank" rel="noopener noreferrer">+ <Eye className="size-4" />+ </a>+ </Button>+ ))}<Button asChild variant="ghost" size="icon" className="size-8 text-mint" aria-label={t('chat.media.download')}><ahref={`${href}?download=1`}diff --git a/ui/src/components/ui/file-viewer-modal.tsx b/ui/src/components/ui/file-viewer-modal.tsxnew file mode 100644index 000000000..c783a12cc--- /dev/null+++ b/ui/src/components/ui/file-viewer-modal.tsx@@ -0,0 +1,313 @@+import * as React from 'react';+import { useTranslation } from 'react-i18next';+import { Check, Copy, Download, FileText } from 'lucide-react';+import JsonView from '@uiw/react-json-view';+import { githubDarkTheme } from '@uiw/react-json-view/githubDark';+import { githubLightTheme } from '@uiw/react-json-view/githubLight';+import Papa from 'papaparse';++import { Button } from '@/components/ui/button';+import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';+import { Markdown } from '@/components/ui/markdown';+import { useTheme } from '@/context/ThemeContext';+import { apiFetch } from '@/lib/apiFetch';+import { handleMediaDownloadClick } from '@/lib/downloadMedia';+import { isProxyMediaUrl } from '@/lib/mediaProxy';+import {+ CODE_HIGHLIGHT_MAX_BYTES,+ CSV_MAX_COLS,+ CSV_MAX_ROWS,+ JSON_TREE_MAX_BYTES,+ JSON_TREE_MAX_NODES,+ PREVIEW_MAX_BYTES,+ codeLanguage,+ formatBytes,+ previewKind,+ type PreviewKind,+} from '@/lib/filePreview';+import { highlightCode } from '@/lib/highlighter';+import { copyTextToClipboard } from '@/lib/utils';+import type { FilePreviewTarget } from '@/components/ui/file-viewer';++// The lazy half of the file viewer: fetches the file text (size-capped) and+// renders it by kind in the shared Dialog. Default export so ``React.lazy`` can+// load it. All the heavy preview deps (Shiki, @uiw/react-json-view, papaparse)+// live here so they stay out of the main bundle.++type Status =+ | { phase: 'loading' }+ | { phase: 'error' }+ | { phase: 'toolarge' }+ | { phase: 'ready'; kind: PreviewKind; text: string };++type Info = { name: string; size: number | null; ext: string };++// Code / source: highlight asynchronously (Shiki + grammar load), falling back+// to plain escaped text while pending or if highlighting fails.+const CodeBlock: React.FC<{ code: string; lang: string }> = ({ code, lang }) => {+ const { resolvedTheme } = useTheme();+ const [html, setHtml] = React.useState<string | null>(null);+ React.useEffect(() => {+ // Large files: skip Shiki — tokenizing hundreds of KB on the main thread+ // would freeze the UI. html stays null, so the plain <pre> fallback renders.+ if (code.length > CODE_HIGHLIGHT_MAX_BYTES) return;+ let alive = true;+ highlightCode(code, lang, resolvedTheme === 'light' ? 'github-light' : 'github-dark')+ .then((out) => alive && setHtml(out))+ .catch(() => alive && setHtml(null));+ return () => {+ alive = false;+ };+ }, [code, lang, resolvedTheme]);+ // Shiki escapes the code text, so the HTML is safe to inject.+ if (html) return <div className="vr-fileview-code" dangerouslySetInnerHTML={{ __html: html }} />;+ return <pre className="vr-fileview-pre">{code}</pre>;+};++const CsvTable: React.FC<{ text: string }> = ({ text }) => {+ const { t } = useTranslation();+ const { rows, more, cols } = React.useMemo(() => {+ // Don't trim: leading whitespace / an empty first cell (e.g. a TSV starting+ // with a tab) is data — shifting it would mis-column the table. ``preview``+ // stops Papa after the rows we show (+1 to detect "there's more"), so a file+ // with hundreds of thousands of rows isn't fully materialized just to slice.+ const parsed = Papa.parse<string[]>(text, { skipEmptyLines: true, preview: CSV_MAX_ROWS + 1 });+ const all = (parsed.data || []) as string[][];+ const shown = all.slice(0, CSV_MAX_ROWS);+ // Width = the widest row, not the first — a later row with more fields (or+ // headerless data) must not have its extra cells truncated to the header.+ const cols = shown.reduce((max, r) => Math.max(max, r.length), 0);+ return { rows: shown, more: all.length > CSV_MAX_ROWS, cols };+ }, [text]);+ if (rows.length === 0 || cols === 0) return <pre className="vr-fileview-pre">{text}</pre>;+ const [head, ...bodyRows] = rows;+ // Cap columns too: a single very wide row would otherwise mount one cell per+ // field and lock the UI.+ const shownCols = Math.min(cols, CSV_MAX_COLS);+ const colIdx = Array.from({ length: shownCols }, (_, i) => i);+ const colsTruncated = cols > shownCols;+ return (+ <div className="vr-fileview-csv">+ <table className="vr-fileview-table">+ <thead>+ <tr>{colIdx.map((ci) => <th key={ci}>{head[ci] ?? ''}</th>)}</tr>+ </thead>+ <tbody>+ {bodyRows.map((r, ri) => (+ <tr key={ri}>{colIdx.map((ci) => <td key={ci}>{r[ci] ?? ''}</td>)}</tr>+ ))}+ </tbody>+ </table>+ {(more || colsTruncated) && (+ <div className="vr-fileview-note">+ {[+ more ? t('chat.viewer.csvTruncated', { count: rows.length }) : null,+ colsTruncated ? t('chat.viewer.csvColsTruncated', { shown: shownCols, total: cols }) : null,+ ]+ .filter(Boolean)+ .join(' · ')}+ </div>+ )}+ </div>+ );+};++// Count nodes in a parsed JSON value, short-circuiting once past the limit (so+// it stays cheap even for huge inputs). Iterative to avoid deep recursion.+function jsonNodeCount(root: unknown, limit: number): number {+ let count = 0;+ const stack: unknown[] = [root];+ while (stack.length > 0) {+ const v = stack.pop();+ count += 1;+ if (count > limit) return count;+ if (v !== null && typeof v === 'object') {+ const children = Array.isArray(v) ? v : Object.values(v as Record<string, unknown>);+ for (let i = 0; i < children.length; i += 1) stack.push(children[i]);+ }+ }+ return count;+}++const JsonBlock: React.FC<{ text: string }> = ({ text }) => {+ const { resolvedTheme } = useTheme();+ const parsed = React.useMemo<{ ok: boolean; value: unknown }>(() => {+ try {+ return { ok: true, value: JSON.parse(text) };+ } catch {+ return { ok: false, value: null };+ }+ }, [text]);+ const isObject = parsed.ok && parsed.value !== null && typeof parsed.value === 'object';+ // The interactive tree mounts every node into the DOM (``collapsed`` only sets+ // the visual state). Fall back to highlighted source for a primitive root+ // (JsonView wants an object/array), invalid JSON, or anything too big — by+ // bytes OR node count, since compact arrays stay under the byte cap but still+ // explode the DOM.+ const tooManyNodes = React.useMemo(+ () => (isObject ? jsonNodeCount(parsed.value, JSON_TREE_MAX_NODES) > JSON_TREE_MAX_NODES : false),+ [isObject, parsed.value],+ );+ if (!isObject || text.length > JSON_TREE_MAX_BYTES || tooManyNodes) {+ return <CodeBlock code={text} lang="json" />;+ }+ return (+ <JsonView+ value={parsed.value as object}+ style={resolvedTheme === 'light' ? githubLightTheme : githubDarkTheme}+ collapsed={2}+ displayDataTypes={false}+ shortenTextAfterLength={0}+ className="vr-fileview-json"+ />+ );+};++export default function FileViewerModal({+ target,+ onClose,+}: {+ target: FilePreviewTarget;+ onClose: () => void;+}) {+ const { t } = useTranslation();+ // Defense in depth alongside FileCard's gate: only ever preview our own+ // same-origin proxy files. A non-proxy URL must never be auto-fetched (it'd+ // leak the viewer's network to a third-party host); start in ``error``.+ const [status, setStatus] = React.useState<Status>(() =>+ isProxyMediaUrl(target.url) ? { phase: 'loading' } : { phase: 'error' },+ );+ const [info, setInfo] = React.useState<Info>({ name: target.name || '', size: null, ext: '' });+ const [copied, setCopied] = React.useState(false);++ React.useEffect(() => {+ if (!isProxyMediaUrl(target.url)) return; // non-proxy → never fetch (state is already 'error')+ let alive = true;+ (async () => {+ try {+ // Cheap /meta first for the size guard + name, so a huge file never gets+ // pulled into the page just to refuse it.+ let size: number | null = null;+ let name = target.name || '';+ let ext = '';+ try {+ const metaRes = await apiFetch(`${target.url}/meta`, { headers: { Accept: 'application/json' } });+ if (metaRes.ok) {+ const m = (await metaRes.json()) as { name?: string; size?: number; ext?: string };+ if (typeof m?.size === 'number') size = m.size;+ if (typeof m?.name === 'string' && m.name) name = m.name;+ if (typeof m?.ext === 'string') ext = m.ext;+ }+ } catch {+ /* meta is best-effort */+ }+ if (!alive) return;+ if (size != null && size > PREVIEW_MAX_BYTES) {+ setInfo({ name, size, ext });+ setStatus({ phase: 'toolarge' });+ return;+ }+ const res = await apiFetch(target.url, { headers: { Accept: '*/*' } });+ if (!alive) return;+ if (!res.ok) {+ setStatus({ phase: 'error' });+ return;+ }+ // Backstop the size cap when /meta gave no size: refuse a huge body by+ // Content-Length before reading it in.+ const len = Number(res.headers.get('content-length'));+ const byteSize = size ?? (Number.isFinite(len) && len > 0 ? len : null);+ if (byteSize != null && byteSize > PREVIEW_MAX_BYTES) {+ setInfo({ name, size: byteSize, ext });+ setStatus({ phase: 'toolarge' });+ return;+ }+ const mime = res.headers.get('content-type') || '';+ const text = await res.text();+ if (!alive) return;+ // Final guard for the (rare) chunked/no-Content-Length case.+ if (text.length > PREVIEW_MAX_BYTES) {+ setInfo({ name, size: byteSize, ext });+ setStatus({ phase: 'toolarge' });+ return;+ }+ const kind = previewKind(name, mime, ext);+ setInfo({ name, size: byteSize, ext });+ if (!kind) {+ setStatus({ phase: 'error' });+ return;+ }+ setStatus({ phase: 'ready', kind, text });+ } catch {+ if (alive) setStatus({ phase: 'error' });+ }+ })();+ return () => {+ alive = false;+ };+ }, [target.url, target.name]);++ const copy = async () => {+ if (status.phase !== 'ready') return;+ if (await copyTextToClipboard(status.text)) {+ setCopied(true);+ window.setTimeout(() => setCopied(false), 1600);+ }+ };++ const ext = info.name.includes('.') ? (info.name.split('.').pop() || '').toUpperCase() : '';+ const metaLine = [ext || null, formatBytes(info.size) || null].filter(Boolean).join(' · ');++ let bodyNode: React.ReactNode;+ if (status.phase === 'loading') bodyNode = <div className="vr-fileview-msg">{t('chat.viewer.loading')}</div>;+ else if (status.phase === 'toolarge') bodyNode = <div className="vr-fileview-msg">{t('chat.viewer.tooLarge')}</div>;+ else if (status.phase === 'error') bodyNode = <div className="vr-fileview-msg">{t('chat.viewer.error')}</div>;+ else if (status.kind === 'markdown') bodyNode = <Markdown content={status.text} interactive={false} className="vr-fileview-md" />;+ else if (status.kind === 'json') bodyNode = <JsonBlock text={status.text} />;+ else if (status.kind === 'csv') bodyNode = <CsvTable text={status.text} />;+ else if (status.kind === 'code' || status.kind === 'source') bodyNode = <CodeBlock code={status.text} lang={codeLanguage(info.name, info.ext)} />;+ else bodyNode = <pre className="vr-fileview-pre">{status.text}</pre>;++ return (+ <Dialog+ open+ onOpenChange={(next) => {+ if (!next) onClose();+ }}+ >+ {/* Reuse the shared Dialog: overlay, focus-trap, scroll-lock, Escape,+ outside-click close, the built-in top-right close X, and the mobile+ bottom-sheet all come for free. ``pr-12`` on the header leaves room for+ that close X. */}+ <DialogContent+ aria-describedby={undefined}+ className="flex max-h-[85vh] w-full max-w-3xl flex-col gap-0 overflow-hidden p-0"+ >+ <div className="flex items-center gap-2 border-b border-border px-4 py-3 pr-12">+ <FileText className="size-4 shrink-0 text-muted" />+ <div className="min-w-0 flex-1">+ <DialogTitle className="truncate text-[13px] font-semibold text-foreground">+ {info.name || t('chat.media.preview')}+ </DialogTitle>+ {metaLine && <div className="font-mono text-[10px] text-muted">{metaLine}</div>}+ </div>+ {status.phase === 'ready' && (+ <Button variant="ghost" size="icon" className="size-8" onClick={copy} aria-label={t('common.copy')}>+ {copied ? <Check className="size-4 text-mint" /> : <Copy className="size-4" />}+ </Button>+ )}+ <Button asChild variant="ghost" size="icon" className="size-8 text-mint" aria-label={t('chat.media.download')}>+ <a+ href={`${target.url}?download=1`}+ download+ onClick={(e) => handleMediaDownloadClick(e, target.url, info.name || undefined)}+ >+ <Download className="size-4" />+ </a>+ </Button>+ </div>+ <div className="vr-fileview-body min-h-0 flex-1 overflow-auto">{bodyNode}</div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/ui/src/components/ui/file-viewer.tsx b/ui/src/components/ui/file-viewer.tsxnew file mode 100644index 000000000..49688a649--- /dev/null+++ b/ui/src/components/ui/file-viewer.tsx@@ -0,0 +1,41 @@+import * as React from 'react';++// Session-scoped in-app file preview. ChatPage mounts the provider; a FileCard+// with a previewable file calls ``open({ url, name })`` to show the modal. The+// heavy modal (Shiki, the JSON viewer, the CSV parser) is ``React.lazy``-loaded,+// so none of it touches the main app bundle — it arrives only when the first+// preview opens. Mirrors ImageViewerProvider so the two media viewers stay+// structurally consistent; FileCard falls back to a plain link where no+// provider is mounted (``useFileViewer()`` returns null).++export type FilePreviewTarget = { url: string; name?: string };++type FileViewerContextValue = { open: (target: FilePreviewTarget) => void };++const FileViewerContext = React.createContext<FileViewerContextValue | null>(null);++export function useFileViewer(): FileViewerContextValue | null {+ return React.useContext(FileViewerContext);+}++const FileViewerModal = React.lazy(() => import('@/components/ui/file-viewer-modal'));++export const FileViewerProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {+ const [target, setTarget] = React.useState<FilePreviewTarget | null>(null);+ const open = React.useCallback((next: FilePreviewTarget) => setTarget(next), []);+ const close = React.useCallback(() => setTarget(null), []);+ const ctx = React.useMemo(() => ({ open }), [open]);++ return (+ <FileViewerContext.Provider value={ctx}>+ {children}+ {target && (+ <React.Suspense fallback={null}>+ {/* key by url so opening a different file remounts the modal: state+ resets to ``loading`` without a setState-in-effect. */}+ <FileViewerModal key={target.url} target={target} onClose={close} />+ </React.Suspense>+ )}+ </FileViewerContext.Provider>+ );+};diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 33a95d0bc..f740ff5f4 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -17,6 +17,7 @@ import { Button } from '../ui/button';import { ChatImage } from '../ui/chat-image';import { FileCard } from '../ui/file-card';import { ImageViewerProvider } from '../ui/image-viewer';+import { FileViewerProvider } from '../ui/file-viewer';import { Input } from '../ui/input';import { Markdown } from '../ui/markdown';import { Composer, type ComposerAttachment } from './Composer';@@ -740,6 +741,7 @@ export const ChatPage: React.FC = () => {// and left a 4rem dead gap below the compose bar. On mobile the sticky// ``h-16`` header occupies 4rem at the top, so subtract that instead.<ImageViewerProvider images={sessionImages}>+ <FileViewerProvider>{/* Mobile: a FIXED full-screen flex column (the AppShell brand header ishidden on chat) so the composer has NO scrollable ancestor — that is whatlet iOS fling it off the top. useIosKeyboardInset then sizes this surface@@ -773,6 +775,7 @@ export const ChatPage: React.FC = () => {onDraftChange={onDraftChange}/></div>+ </FileViewerProvider></ImageViewerProvider>);};diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex b95bd3402..e3306ac30 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1700,7 +1700,12 @@"viewer": {"close": "Close","previous": "Previous",- "next": "Next"+ "next": "Next",+ "loading": "Loading…",+ "error": "Couldn't load this file.",+ "tooLarge": "File too large to preview — download it instead.",+ "csvTruncated": "Showing the first {{count}} rows",+ "csvColsTruncated": "Showing {{shown}} of {{total}} columns"},"queue": {"title": "Queued · {{count}}",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 213df54d8..fbe278c3a 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1699,7 +1699,12 @@"viewer": {"close": "关闭","previous": "上一张",- "next": "下一张"+ "next": "下一张",+ "loading": "加载中…",+ "error": "无法加载该文件。",+ "tooLarge": "文件过大,无法预览,请直接下载。",+ "csvTruncated": "仅显示前 {{count}} 行",+ "csvColsTruncated": "显示前 {{shown}} 列,共 {{total}} 列"},"queue": {"title": "排队中 · {{count}}",diff --git a/ui/src/index.css b/ui/src/index.cssindex d1ed2934a..f5204e442 100644--- a/ui/src/index.css+++ b/ui/src/index.css@@ -524,3 +524,43 @@ pre,.vr-markdown.vr-markdown--preview :is(ul, ol) { padding-left: 1.1em; }.vr-markdown.vr-markdown--preview pre { padding: 4px 8px; border-radius: 6px; }.vr-markdown.vr-markdown--preview blockquote { padding: 0 0 0 0.7em; }++/* File preview viewer (FileViewer modal body). Renderer wrappers own their own+ padding so code / CSV can go edge-to-edge with their own scroll. */+.vr-fileview-body { color: var(--foreground); }+.vr-fileview-msg { padding: 36px 16px; text-align: center; color: var(--muted); font-size: 13px; }+.vr-fileview-md { padding: 16px; }+.vr-fileview-pre {+ margin: 0;+ padding: 16px;+ font-family: var(--font-mono);+ font-size: 12.5px;+ line-height: 1.55;+ white-space: pre-wrap;+ word-break: break-word;+ color: var(--foreground);+}+.vr-fileview-code pre {+ margin: 0;+ padding: 16px;+ overflow-x: auto;+ font-family: var(--font-mono);+ font-size: 12.5px;+ line-height: 1.55;+}+.vr-fileview-json { padding: 14px 16px; font-size: 12.5px; background: transparent; }+.vr-fileview-csv { overflow-x: auto; }+.vr-fileview-table { border-collapse: collapse; font-size: 12.5px; width: max-content; min-width: 100%; }+.vr-fileview-table th,+.vr-fileview-table td {+ border: 1px solid var(--border);+ padding: 5px 10px;+ text-align: left;+ white-space: nowrap;+ max-width: 360px;+ overflow: hidden;+ text-overflow: ellipsis;+}+.vr-fileview-table th { background: var(--surface-2); font-weight: 600; }+.vr-fileview-table tbody tr:nth-child(even) { background: var(--surface-3); }+.vr-fileview-note { padding: 8px 14px; font-size: 11.5px; color: var(--muted); border-top: 1px solid var(--border); }diff --git a/ui/src/lib/filePreview.ts b/ui/src/lib/filePreview.tsnew file mode 100644index 000000000..3a537d610--- /dev/null+++ b/ui/src/lib/filePreview.ts@@ -0,0 +1,104 @@+// Single source of truth for "can we preview this file, and how". Used to gate+// the FileCard preview ("eye") icon and to pick the renderer + syntax-highlight+// language in the FileViewer. Keep the language ids here in sync with the+// grammar loaders in ``highlighter.ts``.++export type PreviewKind = 'markdown' | 'text' | 'json' | 'csv' | 'code' | 'source';++// Refuse to preview files larger than this (fetch the bytes into the page) —+// offer download instead. CSV is additionally capped by row count.+export const PREVIEW_MAX_BYTES = 1024 * 1024;+export const CSV_MAX_ROWS = 500;+// The interactive JSON tree mounts every node into the DOM (collapsed only sets+// the visual state), so above this size we render highlighted JSON source+// instead to avoid freezing the main thread.+export const JSON_TREE_MAX_BYTES = 256 * 1024;+// CSV column cap: a pathologically wide row (e.g. one line with 100k fields)+// would otherwise mount that many cells per row. Extra columns are truncated.+export const CSV_MAX_COLS = 50;+// Above this, skip Shiki and render plain text — tokenizing hundreds of KB on+// the main thread freezes the UI (a large/minified code file or big JSON).+export const CODE_HIGHLIGHT_MAX_BYTES = 200 * 1024;+// Node-count cap for the interactive JSON tree: compact JSON (e.g. a big array+// of numbers) can stay under the byte cap yet hold tens of thousands of nodes,+// which the tree would all mount. Above this we render highlighted source.+export const JSON_TREE_MAX_NODES = 4000;++const MARKDOWN_EXT = new Set(['md', 'markdown', 'mdx', 'mkd', 'mdown']);+const TEXT_EXT = new Set(['txt', 'text', 'log']);+const CSV_EXT = new Set(['csv', 'tsv']);++// Markup rendered as highlighted SOURCE only — never executed (XSS / the server+// already forces these to attachment).+const SOURCE_LANG: Record<string, string> = {+ html: 'html', htm: 'html', xml: 'xml', svg: 'xml', vue: 'vue', svelte: 'svelte',+};++// ext (lowercase, no dot) → Shiki language id.+const CODE_LANG: Record<string, string> = {+ ts: 'typescript', mts: 'typescript', cts: 'typescript', tsx: 'tsx',+ js: 'javascript', mjs: 'javascript', cjs: 'javascript', jsx: 'jsx',+ py: 'python', pyi: 'python', rb: 'ruby', go: 'go', rs: 'rust',+ java: 'java', kt: 'kotlin', kts: 'kotlin', swift: 'swift',+ c: 'c', h: 'c', cpp: 'cpp', cc: 'cpp', cxx: 'cpp', hpp: 'cpp', hh: 'cpp',+ cs: 'csharp', php: 'php',+ sh: 'bash', bash: 'bash', zsh: 'bash',+ sql: 'sql', css: 'css', scss: 'scss', sass: 'scss', less: 'less',+ lua: 'lua', r: 'r', dart: 'dart', scala: 'scala', sc: 'scala', pl: 'perl', pm: 'perl',+ diff: 'diff', patch: 'diff',+ yaml: 'yaml', yml: 'yaml', toml: 'toml',+ ini: 'ini', conf: 'ini', cfg: 'ini', properties: 'ini', env: 'ini',+};++// Files whose meaningful name has no useful extension.+const NAME_LANG: Record<string, string> = {+ dockerfile: 'docker', makefile: 'make', '.gitignore': 'ini', '.gitattributes': 'ini',+ '.env': 'ini', '.bashrc': 'bash', '.zshrc': 'bash', '.profile': 'bash',+};++function baseName(name: string): string {+ return (name || '').split(/[\\/]/).pop() || '';+}++function extOf(name: string): string {+ const b = baseName(name);+ const i = b.lastIndexOf('.');+ return i > 0 ? b.slice(i + 1).toLowerCase() : '';+}++export function previewKind(name: string, mime?: string | null, serverExt?: string | null): PreviewKind | null {+ const b = baseName(name).toLowerCase();+ // Prefer the name's own extension; fall back to the server-supplied ext when+ // the link label is descriptive (e.g. "[view results](…/results.yaml)").+ const ext = extOf(name) || (serverExt || '').replace(/^\.+/, '').toLowerCase();+ const m = (mime || '').split(';')[0].trim().toLowerCase();++ if (MARKDOWN_EXT.has(ext)) return 'markdown';+ if (ext === 'json' || ext === 'jsonc' || ext === 'json5' || m === 'application/json') return 'json';+ if (CSV_EXT.has(ext) || m === 'text/csv' || m === 'text/tab-separated-values') return 'csv';+ if (ext in SOURCE_LANG) return 'source';+ if (ext in CODE_LANG || b in NAME_LANG) return 'code';+ if (TEXT_EXT.has(ext) || m.startsWith('text/')) return 'text';+ return null;+}++// Shiki language id for the 'code'/'source' kinds; 'text' (no highlight) otherwise.+export function codeLanguage(name: string, serverExt?: string | null): string {+ const b = baseName(name).toLowerCase();+ const ext = extOf(name) || (serverExt || '').replace(/^\.+/, '').toLowerCase();+ return SOURCE_LANG[ext] || CODE_LANG[ext] || NAME_LANG[b] || 'text';+}++// Human byte size. Shared with FileCard so the card label and the viewer header+// format sizes identically.+export function formatBytes(bytes?: number | null): string {+ if (!bytes || bytes <= 0) return '';+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];+ let value = bytes;+ let i = 0;+ while (value >= 1024 && i < units.length - 1) {+ value /= 1024;+ i += 1;+ }+ return `${value >= 10 || i === 0 ? Math.round(value) : value.toFixed(1)} ${units[i]}`;+}diff --git a/ui/src/lib/highlighter.ts b/ui/src/lib/highlighter.tsnew file mode 100644index 000000000..506a1d81f--- /dev/null+++ b/ui/src/lib/highlighter.ts@@ -0,0 +1,104 @@+import { createHighlighterCore, type HighlighterCore } from 'shiki/core';+import { createJavaScriptRegexEngine } from 'shiki/engine/javascript';++// Lean, lazy code highlighter for the FileViewer. Only imported by the+// (already lazy) viewer modal, so neither Shiki nor any grammar reaches the main+// app bundle. Uses the JavaScript RegExp engine (no WASM asset to serve) and+// loads each theme + grammar on demand via dynamic import — Vite code-splits+// them per language, so we only ship the languages a user actually opens.+//+// ``forgiving`` lets the JS engine skip the occasional Oniguruma-only regex in a+// grammar instead of throwing, degrading to partial highlight rather than error.++let corePromise: Promise<HighlighterCore> | null = null;+const loadedLangs = new Set<string>();+const loadedThemes = new Set<string>();++type ShikiTheme = 'github-dark' | 'github-light';++// Lang id (matches filePreview's CODE_LANG / SOURCE_LANG / NAME_LANG values) →+// dynamic grammar import.+const LANG_LOADERS: Record<string, () => Promise<unknown>> = {+ typescript: () => import('@shikijs/langs/typescript'),+ tsx: () => import('@shikijs/langs/tsx'),+ javascript: () => import('@shikijs/langs/javascript'),+ jsx: () => import('@shikijs/langs/jsx'),+ python: () => import('@shikijs/langs/python'),+ ruby: () => import('@shikijs/langs/ruby'),+ go: () => import('@shikijs/langs/go'),+ rust: () => import('@shikijs/langs/rust'),+ java: () => import('@shikijs/langs/java'),+ kotlin: () => import('@shikijs/langs/kotlin'),+ swift: () => import('@shikijs/langs/swift'),+ c: () => import('@shikijs/langs/c'),+ cpp: () => import('@shikijs/langs/cpp'),+ csharp: () => import('@shikijs/langs/csharp'),+ php: () => import('@shikijs/langs/php'),+ bash: () => import('@shikijs/langs/bash'),+ sql: () => import('@shikijs/langs/sql'),+ css: () => import('@shikijs/langs/css'),+ scss: () => import('@shikijs/langs/scss'),+ less: () => import('@shikijs/langs/less'),+ lua: () => import('@shikijs/langs/lua'),+ r: () => import('@shikijs/langs/r'),+ dart: () => import('@shikijs/langs/dart'),+ scala: () => import('@shikijs/langs/scala'),+ perl: () => import('@shikijs/langs/perl'),+ diff: () => import('@shikijs/langs/diff'),+ yaml: () => import('@shikijs/langs/yaml'),+ toml: () => import('@shikijs/langs/toml'),+ ini: () => import('@shikijs/langs/ini'),+ html: () => import('@shikijs/langs/html'),+ xml: () => import('@shikijs/langs/xml'),+ vue: () => import('@shikijs/langs/vue'),+ svelte: () => import('@shikijs/langs/svelte'),+ docker: () => import('@shikijs/langs/docker'),+ make: () => import('@shikijs/langs/make'),+ json: () => import('@shikijs/langs/json'),+};++const THEME_LOADERS: Record<ShikiTheme, () => Promise<unknown>> = {+ 'github-dark': () => import('@shikijs/themes/github-dark'),+ 'github-light': () => import('@shikijs/themes/github-light'),+};++async function getCore(): Promise<HighlighterCore> {+ if (!corePromise) {+ // Don't cache a rejected init promise — a one-off failure (e.g. a chunk-load+ // error after a deploy) would otherwise disable highlighting for the whole+ // session. On reject, clear the cache so the next call retries.+ corePromise = createHighlighterCore({ engine: createJavaScriptRegexEngine({ forgiving: true }) }).catch((err) => {+ corePromise = null;+ throw err;+ });+ }+ return corePromise;+}++// Highlight ``code`` for ``langId`` using a single theme picked from the current+// app mode; returns Shiki's HTML (the code text is escaped, so it's safe to+// inject). Falls back to plain (escaped) text for unknown languages.+export async function highlightCode(code: string, langId: string, theme: ShikiTheme): Promise<string> {+ const hl = await getCore();++ if (!loadedThemes.has(theme)) {+ await hl.loadTheme(THEME_LOADERS[theme]() as Parameters<HighlighterCore['loadTheme']>[0]);+ loadedThemes.add(theme);+ }++ let lang = 'text';+ const loader = LANG_LOADERS[langId];+ if (loader) {+ try {+ if (!loadedLangs.has(langId)) {+ await hl.loadLanguage(loader() as Parameters<HighlighterCore['loadLanguage']>[0]);+ loadedLangs.add(langId);+ }+ lang = langId;+ } catch {+ lang = 'text'; // bad/unsupported grammar → render as plain escaped text+ }+ }++ return hl.codeToHtml(code, { lang, theme });+}