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(workbench): unified file-preview kernel (image/svg/html/pdf/office + code/json/csv/md), reused in File Browser, editor & chat (#728)
Call White8f2a052cb257
diff --git a/ui/package-lock.json b/ui/package-lock.jsonindex 5fc375abc..a5cb47286 100644--- a/ui/package-lock.json+++ b/ui/package-lock.json@@ -24,9 +24,11 @@"@xterm/addon-fit": "^0.11.0","@xterm/xterm": "^6.0.0","agentation": "^3.0.2",+ "chart.js": "^4.4.0","class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",+ "docx-preview": "^0.3.7","framer-motion": "^12.26.2","hash-wasm": "^4.12.0","i18next": "^25.7.4",@@ -36,6 +38,7 @@"lucide-react": "^0.562.0","monaco-editor": "^0.55.1","papaparse": "^5.5.3",+ "pptxviewjs": "^1.1.9","qrcode.react": "^4.2.0","react": "^19.2.0","react-dom": "^19.2.0",@@ -47,7 +50,8 @@"remark-gfm": "^4.0.1","shiki": "^4.2.0","tailwind-merge": "^3.4.0",- "tw-animate-css": "^1.4.0"+ "tw-animate-css": "^1.4.0",+ "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"},"devDependencies": {"@eslint/js": "^9.39.1",@@ -117,6 +121,7 @@"integrity": "sha512-H3mcG6ZDLTlYfaSNi0iOKkigqMFvkTKlGUYlD8GW7nNOYRrevuA46iTypPyv+06V3fEmvvazfntkBU34L0azAw==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@babel/code-frame": "^7.28.6","@babel/generator": "^7.28.6",@@ -283,6 +288,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"}@@ -367,7 +373,6 @@"dev": true,"license": "MIT","optional": true,- "peer": true,"dependencies": {"tslib": "^2.4.0"}@@ -717,6 +722,12 @@"@jridgewell/sourcemap-codec": "^1.4.14"}},+ "node_modules/@kurkle/color": {+ "version": "0.3.4",+ "resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.4.tgz",+ "integrity": "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==",+ "license": "MIT"+ },"node_modules/@lexical/clipboard": {"version": "0.45.0","resolved": "https://registry.npmjs.org/@lexical/clipboard/-/clipboard-0.45.0.tgz",@@ -907,6 +918,7 @@"resolved": "https://registry.npmjs.org/@lexical/react/-/react-0.45.0.tgz","integrity": "sha512-LAaceAtcQpVMDvldhkrQC1MSawpj7aAm1CfGg6RbyQgTDDp2fKnP1gDhjQIef3lH8W2fYeXRe66EdzaFkoGHKA==","license": "MIT",+ "peer": true,"dependencies": {"@floating-ui/react": "^0.27.19","@lexical/devtools-core": "0.45.0",@@ -994,6 +1006,7 @@"resolved": "https://registry.npmjs.org/@lexical/utils/-/utils-0.45.0.tgz","integrity": "sha512-Fo5MMErqoPlUyTw1qVMZ9kE33ZjJF957KU683tsCrrlaVisVxpboL7BbAnxWTwCcIpAsfc6AUndJJ70M9NDMGg==","license": "MIT",+ "peer": true,"dependencies": {"@lexical/internal": "0.45.0","@lexical/selection": "0.45.0",@@ -2559,6 +2572,7 @@"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.8.tgz","integrity": "sha512-3MbSL37jEchWZz2p2mjntRZtPt837ij10ApxKfgmXCTuHWagYg7iA5bqPw6C8BMPfwidlvfPI/fxOc42HLhcyg==","license": "MIT",+ "peer": true,"dependencies": {"csstype": "^3.2.2"}@@ -2569,6 +2583,7 @@"integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==","devOptional": true,"license": "MIT",+ "peer": true,"peerDependencies": {"@types/react": "^19.2.0"}@@ -2630,6 +2645,7 @@"integrity": "sha512-npiaib8XzbjtzS2N4HlqPvlpxpmZ14FjSJrteZpPxGUaYPlvhzlzUZ4mZyABo0EFrOWnvyd0Xxroq//hKhtAWg==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@typescript-eslint/scope-manager": "8.53.0","@typescript-eslint/types": "8.53.0",@@ -3034,6 +3050,7 @@"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==","dev": true,"license": "MIT",+ "peer": true,"bin": {"acorn": "bin/acorn"},@@ -3226,6 +3243,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"baseline-browser-mapping": "^2.9.0","caniuse-lite": "^1.0.30001759",@@ -3348,6 +3366,19 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/chart.js": {+ "version": "4.5.1",+ "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz",+ "integrity": "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw==",+ "license": "MIT",+ "peer": true,+ "dependencies": {+ "@kurkle/color": "^0.3.0"+ },+ "engines": {+ "pnpm": ">=8"+ }+ },"node_modules/class-variance-authority": {"version": "0.7.1","resolved": "https://registry.npmjs.org/class-variance-authority/-/class-variance-authority-0.7.1.tgz",@@ -3442,6 +3473,12 @@"url": "https://opencollective.com/express"}},+ "node_modules/core-util-is": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",+ "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",+ "license": "MIT"+ },"node_modules/cross-spawn": {"version": "7.0.6","resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",@@ -3538,6 +3575,15 @@"url": "https://github.com/sponsors/wooorm"}},+ "node_modules/docx-preview": {+ "version": "0.3.7",+ "resolved": "https://registry.npmjs.org/docx-preview/-/docx-preview-0.3.7.tgz",+ "integrity": "sha512-Lav69CTA/IYZPJTsKH7oYeoZjyg96N0wEJMNslGJnZJ+dMUZK85Lt5ASC79yUlD48ecWjuv+rkcmFt6EVPV0Xg==",+ "license": "Apache-2.0",+ "dependencies": {+ "jszip": ">=3.0.0"+ }+ },"node_modules/dompurify": {"version": "3.2.7","resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.2.7.tgz",@@ -3604,6 +3650,7 @@"integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"@eslint-community/eslint-utils": "^4.8.0","@eslint-community/regexpp": "^4.12.1",@@ -4160,6 +4207,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"@babel/runtime": "^7.28.4"},@@ -4191,6 +4239,12 @@"node": ">= 4"}},+ "node_modules/immediate": {+ "version": "3.0.6",+ "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",+ "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==",+ "license": "MIT"+ },"node_modules/import-fresh": {"version": "3.3.1","resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",@@ -4218,6 +4272,12 @@"node": ">=0.8.19"}},+ "node_modules/inherits": {+ "version": "2.0.4",+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",+ "license": "ISC"+ },"node_modules/inline-style-parser": {"version": "0.2.7","resolved": "https://registry.npmjs.org/inline-style-parser/-/inline-style-parser-0.2.7.tgz",@@ -4303,6 +4363,12 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/isarray": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",+ "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",+ "license": "MIT"+ },"node_modules/isexe": {"version": "2.0.0","resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",@@ -4315,7 +4381,6 @@"resolved": "https://registry.npmjs.org/isomorphic.js/-/isomorphic.js-0.2.5.tgz","integrity": "sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==","license": "MIT",- "peer": true,"funding": {"type": "GitHub Sponsors ❤","url": "https://github.com/sponsors/dmonad"@@ -4398,6 +4463,18 @@"node": ">=6"}},+ "node_modules/jszip": {+ "version": "3.10.1",+ "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz",+ "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==",+ "license": "(MIT OR GPL-3.0-or-later)",+ "dependencies": {+ "lie": "~3.3.0",+ "pako": "~1.0.2",+ "readable-stream": "~2.3.6",+ "setimmediate": "^1.0.5"+ }+ },"node_modules/keyv": {"version": "4.5.4","resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",@@ -4427,6 +4504,7 @@"resolved": "https://registry.npmjs.org/lexical/-/lexical-0.45.0.tgz","integrity": "sha512-z2M9C2ILPW7SopQE1aKbOFdZJbe3HvsrgWnJKveMDrSEvVjU9Hce4UpKVsAdkwY7TgY9RDuCV3+sfrGu0WkL+w==","license": "MIT",+ "peer": true,"dependencies": {"@lexical/internal": "0.45.0"}@@ -4449,7 +4527,6 @@"resolved": "https://registry.npmjs.org/lib0/-/lib0-0.2.117.tgz","integrity": "sha512-DeXj9X5xDCjgKLU/7RR+/HQEVzuuEUiwldwOGsHK/sfAfELGWEyTcf0x+uOvCvK3O2zPmZePXWL85vtia6GyZw==","license": "MIT",- "peer": true,"dependencies": {"isomorphic.js": "^0.2.4"},@@ -4466,6 +4543,15 @@"url": "https://github.com/sponsors/dmonad"}},+ "node_modules/lie": {+ "version": "3.3.0",+ "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz",+ "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==",+ "license": "MIT",+ "dependencies": {+ "immediate": "~3.0.5"+ }+ },"node_modules/lightningcss": {"version": "1.30.2","resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.30.2.tgz",@@ -5688,6 +5774,7 @@"resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.55.1.tgz","integrity": "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==","license": "MIT",+ "peer": true,"dependencies": {"dompurify": "3.2.7","marked": "14.0.0"@@ -5828,6 +5915,12 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/pako": {+ "version": "1.0.11",+ "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",+ "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",+ "license": "(MIT AND Zlib)"+ },"node_modules/papaparse": {"version": "5.5.3","resolved": "https://registry.npmjs.org/papaparse/-/papaparse-5.5.3.tgz",@@ -5912,6 +6005,7 @@"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==","dev": true,"license": "MIT",+ "peer": true,"engines": {"node": ">=12"},@@ -5939,6 +6033,7 @@}],"license": "MIT",+ "peer": true,"dependencies": {"nanoid": "^3.3.12","picocolors": "^1.1.1",@@ -5955,6 +6050,27 @@"dev": true,"license": "MIT"},+ "node_modules/pptxviewjs": {+ "version": "1.1.9",+ "resolved": "https://registry.npmjs.org/pptxviewjs/-/pptxviewjs-1.1.9.tgz",+ "integrity": "sha512-mHkSfwFOjExQpMPT9aNdahANwA5ONvsUpvneZXlBaQh3Lo/cq9g8K9qWAHlmJ66vqDRclWckZrQb7rw1jzjjqQ==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ },+ "peerDependencies": {+ "chart.js": ">=4.4.1",+ "jszip": ">=3.10.1"+ },+ "peerDependenciesMeta": {+ "chart.js": {+ "optional": true+ },+ "jszip": {+ "optional": true+ }+ }+ },"node_modules/prelude-ls": {"version": "1.2.1","resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",@@ -5965,6 +6081,12 @@"node": ">= 0.8.0"}},+ "node_modules/process-nextick-args": {+ "version": "2.0.1",+ "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",+ "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",+ "license": "MIT"+ },"node_modules/property-information": {"version": "7.1.0","resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz",@@ -5999,6 +6121,7 @@"resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz","integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==","license": "MIT",+ "peer": true,"engines": {"node": ">=0.10.0"}@@ -6008,6 +6131,7 @@"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz","integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==","license": "MIT",+ "peer": true,"dependencies": {"scheduler": "^0.27.0"},@@ -6199,6 +6323,21 @@"react-dom": "*"}},+ "node_modules/readable-stream": {+ "version": "2.3.8",+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",+ "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",+ "license": "MIT",+ "dependencies": {+ "core-util-is": "~1.0.0",+ "inherits": "~2.0.3",+ "isarray": "~1.0.0",+ "process-nextick-args": "~2.0.0",+ "safe-buffer": "~5.1.1",+ "string_decoder": "~1.1.1",+ "util-deprecate": "~1.0.1"+ }+ },"node_modules/regex": {"version": "6.1.0","resolved": "https://registry.npmjs.org/regex/-/regex-6.1.0.tgz",@@ -6348,6 +6487,12 @@"@rolldown/binding-win32-x64-msvc": "1.0.3"}},+ "node_modules/safe-buffer": {+ "version": "5.1.2",+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",+ "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",+ "license": "MIT"+ },"node_modules/scheduler": {"version": "0.27.0","resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz",@@ -6370,6 +6515,12 @@"integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==","license": "MIT"},+ "node_modules/setimmediate": {+ "version": "1.0.5",+ "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz",+ "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==",+ "license": "MIT"+ },"node_modules/shebang-command": {"version": "2.0.0","resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",@@ -6459,6 +6610,15 @@"dev": true,"license": "MIT"},+ "node_modules/string_decoder": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz",+ "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==",+ "license": "MIT",+ "dependencies": {+ "safe-buffer": "~5.1.0"+ }+ },"node_modules/stringify-entities": {"version": "4.0.4","resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz",@@ -6665,6 +6825,7 @@"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==","devOptional": true,"license": "Apache-2.0",+ "peer": true,"bin": {"tsc": "bin/tsc","tsserver": "bin/tsserver"@@ -6884,6 +7045,12 @@"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"}},+ "node_modules/util-deprecate": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",+ "license": "MIT"+ },"node_modules/vfile": {"version": "6.0.3","resolved": "https://registry.npmjs.org/vfile/-/vfile-6.0.3.tgz",@@ -6918,6 +7085,7 @@"integrity": "sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==","dev": true,"license": "MIT",+ "peer": true,"dependencies": {"lightningcss": "^1.32.0","picomatch": "^4.0.4",@@ -7393,6 +7561,18 @@"node": ">=0.10.0"}},+ "node_modules/xlsx": {+ "version": "0.20.3",+ "resolved": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",+ "integrity": "sha512-oLDq3jw7AcLqKWH2AhCpVTZl8mf6X2YReP+Neh0SJUzV/BdZYjth94tG5toiMB1PPrYtxOCfaoUCkvtuH+3AJA==",+ "license": "Apache-2.0",+ "bin": {+ "xlsx": "bin/xlsx.njs"+ },+ "engines": {+ "node": ">=0.8"+ }+ },"node_modules/yallist": {"version": "3.1.1","resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",@@ -7437,6 +7617,7 @@"integrity": "sha512-k7Nwx6vuWx1IJ9Bjuf4Zt1PEllcwe7cls3VNzm4CQ1/hgtFUK2bRNG3rvnpPUhFjmqJKAKtjV576KnUkHocg/g==","dev": true,"license": "MIT",+ "peer": true,"funding": {"url": "https://github.com/sponsors/colinhacks"}diff --git a/ui/package.json b/ui/package.jsonindex 701ecda4c..aa6857df8 100644--- a/ui/package.json+++ b/ui/package.json@@ -31,9 +31,11 @@"@xterm/addon-fit": "^0.11.0","@xterm/xterm": "^6.0.0","agentation": "^3.0.2",+ "chart.js": "^4.4.0","class-variance-authority": "^0.7.1","clsx": "^2.1.1","cmdk": "^1.1.1",+ "docx-preview": "^0.3.7","framer-motion": "^12.26.2","hash-wasm": "^4.12.0","i18next": "^25.7.4",@@ -43,6 +45,7 @@"lucide-react": "^0.562.0","monaco-editor": "^0.55.1","papaparse": "^5.5.3",+ "pptxviewjs": "^1.1.9","qrcode.react": "^4.2.0","react": "^19.2.0","react-dom": "^19.2.0",@@ -54,7 +57,8 @@"remark-gfm": "^4.0.1","shiki": "^4.2.0","tailwind-merge": "^3.4.0",- "tw-animate-css": "^1.4.0"+ "tw-animate-css": "^1.4.0",+ "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"},"devDependencies": {"@eslint/js": "^9.39.1",diff --git a/ui/src/components/ui/file-card.tsx b/ui/src/components/ui/file-card.tsxindex 717cd73fb..5468aa1ab 100644--- a/ui/src/components/ui/file-card.tsx+++ b/ui/src/components/ui/file-card.tsx@@ -8,7 +8,7 @@ import { apiFetch } from '@/lib/apiFetch';import { isProxyMediaUrl } from '@/lib/mediaProxy';import { handleMediaDownloadClick, mediaDownloadHref } from '@/lib/downloadMedia';import { useFileViewer } from '@/components/ui/file-viewer';-import { previewKind, formatBytes } from '@/lib/filePreview';+import { previewRenderKind, formatBytes } from '@/lib/filePreview';import { cn } from '@/lib/utils';// Download card for an agent-reply file that was rewritten to the same-origin@@ -74,7 +74,9 @@ export const FileCard: React.FC<{ href: string; children?: React.ReactNode }> =// 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;+ // Gate the preview eye with the shared render classifier (not just the text-only previewKind) so the+ // chat offers in-app preview for every kind the kernel can render — PDF / Office / image included.+ const previewable = previewRenderKind(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">diff --git a/ui/src/components/ui/file-preview.tsx b/ui/src/components/ui/file-preview.tsxnew file mode 100644index 000000000..72aa71c58--- /dev/null+++ b/ui/src/components/ui/file-preview.tsx@@ -0,0 +1,667 @@+import * as React from 'react';+import { useTranslation } from 'react-i18next';+import { ChevronLeft, ChevronRight, Loader2 } from 'lucide-react';+import clsx from 'clsx';++import { Markdown } from '@/components/ui/markdown';+import { useTheme } from '@/context/ThemeContext';+import { apiFetch } from '@/lib/apiFetch';+import {+ CODE_HIGHLIGHT_MAX_BYTES,+ CSV_MAX_COLS,+ CSV_MAX_ROWS,+ DOC_PREVIEW_MAX_BYTES,+ JSON_TREE_MAX_BYTES,+ JSON_TREE_MAX_NODES,+ PREVIEW_MAX_BYTES,+ codeLanguage,+ previewRenderKind,+} from '@/lib/filePreview';++// ── Shared file-preview kernel ("Quick Look") ───────────────────────────────+// One read-only renderer for every previewable file, reused by the File Browser overlay, the editor's+// Source ⇄ Preview toggle, and the chat file viewer. A `source` is either a same-origin content `url`+// (fetched with apiFetch) or in-memory `text` (the editor's live, possibly-unsaved buffer). The kind+// is resolved from the name/mime (``previewRenderKind``), and every heavy engine — Shiki, the JSON+// tree, papaparse, and the Office parsers (docx-preview / SheetJS / PptxViewJS) — is dynamic-imported+// inside its own renderer, so none of them reach the apps/main bundle until that file type is opened.++export type PreviewSource = {+ name: string;+ mime?: string | null;+ /** Server-supplied extension (e.g. chat /meta `ext`) — used to classify when the name is just a+ * descriptive label whose suffix doesn't match the real file type. */+ ext?: string | null;+ /** Same-origin, apiFetch-able content URL. Required for image / pdf / office; default fetch for text. */+ url?: string;+ /** In-memory text (the editor's live buffer). Used for text-derived kinds instead of fetching `url`. */+ text?: string;+ /** Known byte size, so an oversized text file is refused before being pulled into the page. */+ size?: number | null;+};++// JSON tree is the one renderer whose dep can't be dynamic-imported inline (it's a component), so it+// lives in its own module and loads lazily here.+const PreviewJson = React.lazy(() => import('@/components/ui/preview-json'));++export const FilePreview: React.FC<{ source: PreviewSource; className?: string; onText?: (text: string) => void }> = ({+ source,+ className,+ onText,+}) => {+ const { t } = useTranslation();+ const kind = previewRenderKind(source.name, source.mime, source.ext);++ if (!kind) return <Centered className={className}>{t('preview.unsupported')}</Centered>;+ if (kind === 'image')+ return source.url ? <ImageBody src={source.url} name={source.name} className={className} /> : <Centered className={className}>{t('preview.failed')}</Centered>;+ if (kind === 'pdf')+ return source.url ? <PdfView url={source.url} className={className} /> : <Centered className={className}>{t('preview.failed')}</Centered>;+ if (kind === 'docx' || kind === 'xlsx' || kind === 'pptx') {+ if (!source.url) return <Centered className={className}>{t('preview.failed')}</Centered>;+ // Office parsers pull the whole file into memory. The File Browser gates by `previewOverlayKind`'s+ // 25 MB cap, but the chat media proxy enforces no such limit — so refuse an oversized doc here+ // (when /meta gave a size) before fetching, rather than freezing the tab.+ if (source.size != null && source.size > DOC_PREVIEW_MAX_BYTES) return <Centered className={className}>{t('preview.tooLarge')}</Centered>;+ if (kind === 'docx') return <DocxView url={source.url} className={className} />;+ if (kind === 'xlsx') return <XlsxView url={source.url} className={className} />;+ return <PptxView url={source.url} className={className} />;+ }+ // svg / html / markdown / json / csv / code — all derived from the file's text.+ return <TextPreview source={source} kind={kind} onText={onText} className={className} />;+};++// Shared loading / message chrome.+const Centered: React.FC<{ className?: string; children: React.ReactNode }> = ({ className, children }) => (+ <div className={clsx('grid h-full min-h-0 place-items-center bg-surface p-6 text-center text-[12.5px] text-muted', className)}>{children}</div>+);++const Spinner: React.FC<{ className?: string }> = ({ className }) => (+ <Centered className={className}>+ <Loader2 className="size-5 animate-spin" />+ </Centered>+);++// ── Image / SVG ──────────────────────────────────────────────────────────────+// Fit-to-container by default; click toggles 1:1 actual size. `src` is a content URL (raster) or a+// data: URL (SVG rendered from its text) — an <img> neutralizes any script in an SVG, so it's safe.+const ImageBody: React.FC<{ src: string; name?: string; className?: string }> = ({ src, name, className }) => {+ const { t } = useTranslation();+ const [status, setStatus] = React.useState<'loading' | 'ready' | 'error'>('loading');+ const [actual, setActual] = React.useState(false);+ React.useEffect(() => {+ setStatus('loading');+ setActual(false);+ }, [src]);++ if (status === 'error') return <Centered className={clsx('!bg-[#0c0c0f]', className)}>{t('preview.failed')}</Centered>;+ return (+ <div className={clsx('grid h-full min-h-0 place-items-center overflow-auto bg-[#0c0c0f] p-4', className)}>+ {status === 'loading' && <div className="col-start-1 row-start-1 text-[12px] text-muted">{t('common.loading')}</div>}+ <img+ src={src}+ alt={name || ''}+ onLoad={() => setStatus('ready')}+ onError={() => setStatus('error')}+ onClick={() => setActual((a) => !a)}+ draggable={false}+ className={clsx(+ 'col-start-1 row-start-1 select-none',+ actual ? 'max-w-none cursor-zoom-out' : 'max-h-full max-w-full cursor-zoom-in object-contain',+ status !== 'ready' && 'opacity-0',+ )}+ />+ </div>+ );+};++// ── PDF ───────────────────────────────────────────────────────────────────────+// The browser's built-in viewer via an <iframe>. The backend serves PDF inline (same-origin), so no+// JS engine is shipped and it frames without CSP trouble.+const PdfView: React.FC<{ url: string; className?: string }> = ({ url, className }) => {+ const { t } = useTranslation();+ return <iframe title={t('preview.title')} src={url} className={clsx('h-full w-full border-0 bg-white', className)} />;+};++// ── HTML ──────────────────────────────────────────────────────────────────────+// Render the markup in a fully sandboxed iframe: `sandbox=""` disables scripts, same-origin access,+// forms, and popups. But sandbox does NOT stop subresource fetches — a `<img src="https://…">` or CSS+// import in an untrusted file would still hit the network and leak the viewer's IP on preview. So we+// prepend a restrictive CSP <meta> (parsed before any subresource): network pinned to nothing, only+// inline styles + data: URIs allowed. Relative/remote asset references won't resolve — acceptable for+// a static, no-network preview (mirrors the no-auto-fetch policy of chat Markdown previews).+const HTML_PREVIEW_CSP =+ "default-src 'none'; img-src data:; media-src data:; font-src data:; style-src 'unsafe-inline' data:; base-uri 'none'; form-action 'none'";++// Build the srcDoc for an HTML preview. Parse via a <template>, NOT DOMParser: a template's contents+// live in a browsing-context-less "template contents owner" document, so they're truly inert — no+// <img>/<iframe> subresource is fetched while we inspect them (MDN warns a DOMParser document *can*+// download those). Parsing (vs. a regex) still decodes entities, so an obfuscated+// `http-equiv="refresh"` normalizes to `refresh` and is dropped. We then prepend our restrictive+// CSP (parsed before any subresource in the eventual iframe) — so the actual rendering frame fetches+// nothing and can't auto-navigate.+function buildHtmlPreviewDoc(html: string): string {+ const tpl = document.createElement('template');+ tpl.innerHTML = html; // inert: template contents never load resources+ tpl.content.querySelectorAll('meta[http-equiv]').forEach((m) => {+ if ((m.getAttribute('http-equiv') || '').trim().toLowerCase() === 'refresh') m.remove();+ });+ // The <template> innerHTML getter serializes the (now meta-refresh-free) contents.+ return `<!DOCTYPE html><meta http-equiv="Content-Security-Policy" content="${HTML_PREVIEW_CSP}">\n${tpl.innerHTML}`;+}++const HtmlView: React.FC<{ html: string; className?: string }> = ({ html, className }) => {+ const { t } = useTranslation();+ const safeHtml = React.useMemo(() => buildHtmlPreviewDoc(html), [html]);+ return (+ <iframe+ title={t('preview.title')}+ sandbox=""+ referrerPolicy="no-referrer"+ srcDoc={safeHtml}+ className={clsx('h-full w-full border-0 bg-white', className)}+ />+ );+};++// ── Office (docx / xlsx / pptx) ────────────────────────────────────────────────+// Neutralize hyperlinks in rendered-into-the-DOM content (docx-preview copies a DOCX relationship+// target straight into <a href>, so a crafted `javascript:` link would run in the app origin on+// click). Anything that isn't a plain web/mail link has its href stripped (inert text); safe links+// open in a new tab so a click can't navigate the workbench away.+const SAFE_LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:']);+function sanitizeRenderedLinks(root: HTMLElement) {+ root.querySelectorAll('a[href]').forEach((a) => {+ let safe = false;+ try {+ // new URL() normalizes obfuscated schemes (e.g. `java\tscript:`), so the check can't be fooled.+ safe = SAFE_LINK_PROTOCOLS.has(new URL(a.getAttribute('href') || '', window.location.href).protocol);+ } catch {+ safe = false;+ }+ if (safe) {+ a.setAttribute('target', '_blank');+ a.setAttribute('rel', 'noopener noreferrer');+ } else {+ a.removeAttribute('href');+ }+ });+}++// Fetch the file bytes once per URL. Shared by the Office views; their parsers want an ArrayBuffer.+function useFileBytes(url: string) {+ const [state, setState] = React.useState<{ status: 'loading' | 'ready' | 'error' | 'toolarge'; bytes: ArrayBuffer | null }>({ status: 'loading', bytes: null });+ React.useEffect(() => {+ let alive = true;+ setState({ status: 'loading', bytes: null });+ (async () => {+ try {+ const res = await apiFetch(url, { headers: { Accept: '*/*' } });+ if (!res.ok) throw new Error(`http ${res.status}`);+ // The dispatch checks the /meta size, but that can be stale (the media token serves a mutable+ // path). Re-check the actual response: refuse by Content-Length before reading, then guard the+ // final byte length too — mirroring the text preview's size checks.+ const len = Number(res.headers.get('content-length'));+ if (Number.isFinite(len) && len > DOC_PREVIEW_MAX_BYTES) {+ if (alive) setState({ status: 'toolarge', bytes: null });+ return;+ }+ const bytes = await res.arrayBuffer();+ if (bytes.byteLength > DOC_PREVIEW_MAX_BYTES) {+ if (alive) setState({ status: 'toolarge', bytes: null });+ return;+ }+ if (alive) setState({ status: 'ready', bytes });+ } catch {+ if (alive) setState({ status: 'error', bytes: null });+ }+ })();+ return () => {+ alive = false;+ };+ }, [url]);+ return state;+}++// DOCX → docx-preview renders the document into a scrollable container (white pages on a neutral mat).+const DocxView: React.FC<{ url: string; className?: string }> = ({ url, className }) => {+ const { t } = useTranslation();+ const ref = React.useRef<HTMLDivElement>(null);+ const { status, bytes } = useFileBytes(url);+ const [render, setRender] = React.useState<'idle' | 'done' | 'error'>('idle');++ React.useEffect(() => {+ if (status !== 'ready' || !bytes || !ref.current) return;+ let alive = true;+ const container = ref.current;+ setRender('idle');+ (async () => {+ try {+ const { renderAsync } = await import('docx-preview');+ if (!alive) return;+ container.innerHTML = '';+ // renderAltChunks: false — a DOCX can embed an HTML "altChunk" part, which docx-preview would+ // otherwise render straight into our DOM (with remote subresources / active attributes),+ // bypassing the sandbox+CSP path used for .html previews. Disable it for untrusted files.+ await renderAsync(bytes, container, undefined, { className: 'docx-rendered', inWrapper: true, ignoreLastRenderedPageBreak: true, renderAltChunks: false });+ if (alive) {+ sanitizeRenderedLinks(container); // strip javascript:/unsafe DOCX hyperlinks before the user can click+ setRender('done');+ }+ } catch {+ if (alive) setRender('error');+ }+ })();+ return () => {+ alive = false;+ };+ }, [status, bytes]);++ if (status === 'toolarge') return <Centered className={className}>{t('preview.tooLarge')}</Centered>;+ if (status === 'error' || render === 'error') return <Centered className={className}>{t('preview.failed')}</Centered>;+ return (+ <div className={clsx('relative h-full min-h-0 overflow-auto bg-neutral-200 p-4', className)}>+ {(status === 'loading' || render === 'idle') && (+ <div className="absolute inset-0 grid place-items-center text-[12px] text-muted">+ <Loader2 className="size-5 animate-spin" />+ </div>+ )}+ <div ref={ref} className="mx-auto" />+ </div>+ );+};++// XLSX → SheetJS parses to plain values, then each VISIBLE sheet renders as a React <table> — NOT+// dangerouslySetInnerHTML. sheet_to_html injects a cell's `.h` (rich-text HTML) raw, so a crafted+// workbook could smuggle active markup (e.g. a javascript: link) into the app DOM; rendering parsed+// values through React escapes everything and removes that XSS surface. Hidden / very-hidden sheets+// are dropped (Excel keeps them out of view too). The range is clamped (rows × cols) so a huge sheet+// can't freeze the tab by mounting hundreds of thousands of cells.+type XlsxSheet = { name: string; rows: string[][]; cols: number; truncated: boolean };+const XlsxView: React.FC<{ url: string; className?: string }> = ({ url, className }) => {+ const { t } = useTranslation();+ const { status, bytes } = useFileBytes(url);+ const [sheets, setSheets] = React.useState<XlsxSheet[] | null>(null);+ const [active, setActive] = React.useState(0);+ const [failed, setFailed] = React.useState(false);++ React.useEffect(() => {+ if (status !== 'ready' || !bytes) return;+ let alive = true;+ setSheets(null);+ setActive(0);+ setFailed(false);+ (async () => {+ try {+ const XLSX = await import('xlsx');+ if (!alive) return;+ const wb = XLSX.read(bytes, { type: 'array' });+ const MAX_ROWS = 1000;+ const MAX_COLS = 60;+ const out: XlsxSheet[] = [];+ wb.SheetNames.forEach((name, i) => {+ if (wb.Workbook?.Sheets?.[i]?.Hidden) return; // 1 = hidden, 2 = very hidden → skip+ const ws = wb.Sheets[name];+ // Clamp the declared range BEFORE converting: sheet_to_json materializes the whole `!ref`+ // grid, and with blankrows/defval a small workbook with a huge sparse `!ref` would allocate+ // hundreds of thousands of empty rows and freeze the tab. Trim `!ref` so the cap applies+ // before allocation.+ let truncated = false;+ if (ws['!ref']) {+ const r = XLSX.utils.decode_range(ws['!ref']);+ if (r.e.r - r.s.r > MAX_ROWS) {+ r.e.r = r.s.r + MAX_ROWS;+ truncated = true;+ }+ if (r.e.c - r.s.c > MAX_COLS) {+ r.e.c = r.s.c + MAX_COLS;+ truncated = true;+ }+ ws['!ref'] = XLSX.utils.encode_range(r);+ }+ const rows = XLSX.utils.sheet_to_json(ws, { header: 1, raw: false, defval: '', blankrows: true }) as unknown as string[][];+ const cols = rows.reduce((m, r) => Math.max(m, r.length), 0);+ out.push({ name, rows, cols, truncated });+ });+ if (alive) setSheets(out);+ } catch {+ if (alive) setFailed(true);+ }+ })();+ return () => {+ alive = false;+ };+ }, [status, bytes]);++ if (status === 'toolarge') return <Centered className={className}>{t('preview.tooLarge')}</Centered>;+ if (status === 'error' || failed) return <Centered className={className}>{t('preview.failed')}</Centered>;+ if (!sheets) return <Spinner className={className} />;+ if (sheets.length === 0) return <Centered className={className}>{t('preview.empty')}</Centered>;+ const sheet = sheets[active];+ const colIdx = Array.from({ length: sheet?.cols ?? 0 }, (_, i) => i);++ return (+ <div className={clsx('flex h-full min-h-0 flex-col bg-surface', className)}>+ {sheet?.truncated && (+ <div className="shrink-0 border-b border-amber-300 bg-amber-50 px-3 py-1 text-[11.5px] text-amber-800">{t('preview.truncated')}</div>+ )}+ <div className="vr-fileview-csv min-h-0 flex-1 overflow-auto p-2">+ <table className="vr-fileview-table">+ <tbody>+ {(sheet?.rows ?? []).map((r, ri) => (+ <tr key={ri}>{colIdx.map((ci) => <td key={ci}>{r[ci] ?? ''}</td>)}</tr>+ ))}+ </tbody>+ </table>+ </div>+ {sheets.length > 1 && (+ <div className="flex shrink-0 items-center gap-1 overflow-x-auto border-t border-border bg-surface-2 px-2 py-1">+ {sheets.map((s, i) => (+ <button+ key={s.name + i}+ type="button"+ onClick={() => setActive(i)}+ className={clsx(+ 'shrink-0 rounded px-2 py-0.5 text-[11.5px] transition',+ i === active ? 'bg-cyan-soft text-foreground' : 'text-muted hover:bg-foreground/[0.06] hover:text-foreground',+ )}+ >+ {s.name}+ </button>+ ))}+ </div>+ )}+ </div>+ );+};++// PPTX → PptxViewJS renders one slide to a canvas; a control bar pages through. Canvas (not HTML), so+// text isn't selectable, but it's read-only browsing.+const PptxView: React.FC<{ url: string; className?: string }> = ({ url, className }) => {+ const { t } = useTranslation();+ const canvasRef = React.useRef<HTMLCanvasElement>(null);+ const viewerRef = React.useRef<{ goToSlide: (i: number, c?: HTMLCanvasElement | null) => Promise<unknown>; destroy: () => void } | null>(null);+ const { status, bytes } = useFileBytes(url);+ const [count, setCount] = React.useState(0);+ const [index, setIndex] = React.useState(0);+ const [failed, setFailed] = React.useState(false);++ React.useEffect(() => {+ if (status !== 'ready' || !bytes || !canvasRef.current) return;+ let alive = true;+ setFailed(false);+ setCount(0);+ setIndex(0);+ (async () => {+ try {+ const { PPTXViewer } = await import('pptxviewjs');+ if (!alive || !canvasRef.current) return;+ const viewer = new PPTXViewer({ canvas: canvasRef.current, slideSizeMode: 'fit' });+ await viewer.loadFile(bytes);+ if (!alive) {+ viewer.destroy();+ return;+ }+ viewerRef.current = viewer;+ setCount(viewer.getSlideCount());+ await viewer.render(canvasRef.current); // canonical first paint (renders the current slide, 0)+ } catch {+ if (alive) setFailed(true);+ }+ })();+ return () => {+ alive = false;+ viewerRef.current?.destroy();+ viewerRef.current = null;+ };+ }, [status, bytes]);++ const go = (next: number) => {+ if (!viewerRef.current || next < 0 || next >= count) return;+ setIndex(next);+ void viewerRef.current.goToSlide(next, canvasRef.current);+ };++ if (status === 'toolarge') return <Centered className={className}>{t('preview.tooLarge')}</Centered>;+ if (status === 'error' || failed) return <Centered className={className}>{t('preview.failed')}</Centered>;+ return (+ <div className={clsx('flex h-full min-h-0 flex-col bg-[#0c0c0f]', className)}>+ <div className="grid min-h-0 flex-1 place-items-center overflow-auto p-4">+ {status === 'loading' && (+ <div className="col-start-1 row-start-1 text-[12px] text-muted">+ <Loader2 className="size-5 animate-spin" />+ </div>+ )}+ <canvas ref={canvasRef} className="col-start-1 row-start-1 max-h-full max-w-full" />+ </div>+ {count > 1 && (+ <div className="flex shrink-0 items-center justify-center gap-3 border-t border-border bg-surface-2 px-2 py-1.5 text-[12px] text-muted">+ <button type="button" disabled={index <= 0} onClick={() => go(index - 1)} className="grid size-6 place-items-center rounded transition hover:bg-foreground/10 hover:text-foreground disabled:opacity-30">+ <ChevronLeft className="size-4" />+ </button>+ <span className="tabular-nums">+ {index + 1} / {count}+ </span>+ <button type="button" disabled={index >= count - 1} onClick={() => go(index + 1)} className="grid size-6 place-items-center rounded transition hover:bg-foreground/10 hover:text-foreground disabled:opacity-30">+ <ChevronRight className="size-4" />+ </button>+ </div>+ )}+ </div>+ );+};++// ── Text-derived kinds (svg / html / markdown / json / csv / code) ─────────────+type TextKind = 'svg' | 'html' | 'markdown' | 'json' | 'csv' | 'code';++const TextPreview: React.FC<{ source: PreviewSource; kind: TextKind; onText?: (text: string) => void; className?: string }> = ({ source, kind, onText, className }) => {+ const { t } = useTranslation();+ const onTextRef = React.useRef(onText);+ onTextRef.current = onText;+ const [state, setState] = React.useState<{ phase: 'loading' | 'ready' | 'error' | 'toolarge'; text: string }>(() =>+ source.text != null ? { phase: 'ready', text: source.text } : { phase: 'loading', text: '' },+ );++ React.useEffect(() => {+ if (source.text != null) {+ setState({ phase: 'ready', text: source.text });+ onTextRef.current?.(source.text);+ return;+ }+ const url = source.url;+ if (!url) {+ setState({ phase: 'error', text: '' });+ return;+ }+ let alive = true;+ setState({ phase: 'loading', text: '' });+ (async () => {+ try {+ if (source.size != null && source.size > PREVIEW_MAX_BYTES) {+ if (alive) setState({ phase: 'toolarge', text: '' });+ return;+ }+ const res = await apiFetch(url, { headers: { Accept: '*/*' } });+ if (!alive) return;+ if (!res.ok) {+ setState({ phase: 'error', text: '' });+ return;+ }+ // Refuse a huge body by Content-Length before reading it in, then a final guard for the+ // (rare) chunked / no-Content-Length case.+ const len = Number(res.headers.get('content-length'));+ if (Number.isFinite(len) && len > PREVIEW_MAX_BYTES) {+ setState({ phase: 'toolarge', text: '' });+ return;+ }+ const text = await res.text();+ if (!alive) return;+ if (text.length > PREVIEW_MAX_BYTES) {+ setState({ phase: 'toolarge', text: '' });+ return;+ }+ setState({ phase: 'ready', text });+ onTextRef.current?.(text);+ } catch {+ if (alive) setState({ phase: 'error', text: '' });+ }+ })();+ return () => {+ alive = false;+ };+ }, [source.url, source.text, source.size]);++ if (state.phase === 'loading') return <Spinner className={className} />;+ if (state.phase === 'toolarge') return <Centered className={className}>{t('preview.tooLarge')}</Centered>;+ if (state.phase === 'error') return <Centered className={className}>{t('preview.failed')}</Centered>;++ const text = state.text;+ if (kind === 'markdown')+ return (+ <div className={clsx('h-full min-h-0 overflow-auto bg-surface', className)}>+ <Markdown content={text} interactive={false} className="vr-fileview-md mx-auto max-w-3xl px-6 py-5" />+ </div>+ );+ if (kind === 'svg') return <ImageBody src={`data:image/svg+xml;charset=utf-8,${encodeURIComponent(text)}`} name={source.name} className={className} />;+ if (kind === 'html') return <HtmlView html={text} className={className} />;+ if (kind === 'json') return <JsonBlock text={text} className={className} />;+ if (kind === 'csv') return <CsvTable text={text} className={className} />;+ return <CodeBlock code={text} lang={codeLanguage(source.name, source.ext)} className={className} />;+};++// Scroll container shared by the text renderers (their inner markup owns its own padding via the+// .vr-fileview-* rules, so this only provides the sized, scrollable box).+const TextScroll: React.FC<{ className?: string; children: React.ReactNode }> = ({ className, children }) => (+ <div className={clsx('vr-fileview-body h-full min-h-0 overflow-auto bg-surface', className)}>{children}</div>+);++// Code / source: highlight asynchronously (Shiki + grammar, both dynamic-imported), falling back to+// plain escaped text while pending, when the file is too big to tokenize, or if highlighting fails.+const CodeBlock: React.FC<{ code: string; lang: string; className?: string }> = ({ code, lang, className }) => {+ const { resolvedTheme } = useTheme();+ const [html, setHtml] = React.useState<string | null>(null);+ React.useEffect(() => {+ if (code.length > CODE_HIGHLIGHT_MAX_BYTES) return; // too big — keep the plain <pre> fallback+ let alive = true;+ setHtml(null);+ import('@/lib/highlighter')+ .then(({ highlightCode }) => 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 <TextScroll className={className}><div className="vr-fileview-code" dangerouslySetInnerHTML={{ __html: html }} /></TextScroll>;+ return (+ <TextScroll className={className}>+ <pre className="vr-fileview-pre">{code}</pre>+ </TextScroll>+ );+};++const CsvTable: React.FC<{ text: string; className?: string }> = ({ text, className }) => {+ const { t } = useTranslation();+ const [parsed, setParsed] = React.useState<{ rows: string[][]; more: boolean; cols: number } | null>(null);+ React.useEffect(() => {+ let alive = true;+ setParsed(null);+ (async () => {+ try {+ const Papa = (await import('papaparse')).default;+ if (!alive) return;+ // Don't trim: leading whitespace / an empty first cell is data. ``preview`` stops Papa after+ // the rows we show (+1 to detect "there's more"), so a giant file isn't fully materialized.+ const out = Papa.parse<string[]>(text, { skipEmptyLines: true, preview: CSV_MAX_ROWS + 1 });+ const all = (out.data || []) as string[][];+ const shown = all.slice(0, CSV_MAX_ROWS);+ const cols = shown.reduce((max, r) => Math.max(max, r.length), 0); // widest row, not the first+ if (alive) setParsed({ rows: shown, more: all.length > CSV_MAX_ROWS, cols });+ } catch {+ if (alive) setParsed({ rows: [], more: false, cols: 0 });+ }+ })();+ return () => {+ alive = false;+ };+ }, [text]);++ if (!parsed) return <Spinner className={className} />;+ const { rows, more, cols } = parsed;+ if (rows.length === 0 || cols === 0)+ return (+ <TextScroll className={className}>+ <pre className="vr-fileview-pre">{text}</pre>+ </TextScroll>+ );+ const [head, ...bodyRows] = rows;+ const shownCols = Math.min(cols, CSV_MAX_COLS); // cap a pathologically wide row too+ const colIdx = Array.from({ length: shownCols }, (_, i) => i);+ const colsTruncated = cols > shownCols;+ return (+ <TextScroll className={className}>+ <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>+ </div>+ {(more || colsTruncated) && (+ <div className="vr-fileview-note">+ {[more ? t('preview.csvTruncated', { count: rows.length }) : null, colsTruncated ? t('preview.csvColsTruncated', { shown: shownCols, total: cols }) : null]+ .filter(Boolean)+ .join(' · ')}+ </div>+ )}+ </TextScroll>+ );+};++// Count nodes in a parsed JSON value, short-circuiting past the limit. 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; className?: string }> = ({ text, className }) => {+ 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. 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" className={className} />;+ return (+ <TextScroll className={className}>+ <React.Suspense fallback={<div className="p-4 text-[12px] text-muted">…</div>}>+ <PreviewJson value={parsed.value as object} />+ </React.Suspense>+ </TextScroll>+ );+};diff --git a/ui/src/components/ui/file-viewer-modal.tsx b/ui/src/components/ui/file-viewer-modal.tsxindex c783a12cc..51135b284 100644--- a/ui/src/components/ui/file-viewer-modal.tsx+++ b/ui/src/components/ui/file-viewer-modal.tsx@@ -1,272 +1,79 @@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 { FilePreview } from '@/components/ui/file-preview';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 { formatBytes } from '@/lib/filePreview';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.+// The chat file viewer: a Dialog shell (header + copy/download) around the shared <FilePreview>+// kernel, which owns every renderer (Shiki, the JSON tree, papaparse, the Office parsers, images, PDF,+// HTML) and lazy-loads each. Default export so ``React.lazy`` can split it out of the main bundle.+//+// A lightweight /meta fetch resolves the real name / size / content-type before rendering, so the+// kernel can pick the right renderer for a proxy URL whose path is just a token. In-app preview is+// restricted to our own same-origin media proxy — a non-proxy URL is never auto-fetched (it would+// leak the viewer's network to a third-party host).-type Status =- | { phase: 'loading' }- | { phase: 'error' }- | { phase: 'toolarge' }- | { phase: 'ready'; kind: PreviewKind; text: string };+type Meta = { name: string; size: number | null; mime: string | null; ext: string | null };-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;-}) {+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 proxy = isProxyMediaUrl(target.url);+ const [meta, setMeta] = React.useState<Meta>(() => ({ name: target.name || '', size: null, mime: null, ext: null }));+ const [metaLoaded, setMetaLoaded] = React.useState(false);+ // The kernel reports the file's text when it loads a text kind — enables the copy button (and stays+ // null for image / pdf / office, where copy is meaningless).+ const [text, setText] = React.useState<string | null>(null);const [copied, setCopied] = React.useState(false);React.useEffect(() => {- if (!isProxyMediaUrl(target.url)) return; // non-proxy → never fetch (state is already 'error')+ if (!proxy) return; // non-proxy → never fetch; the body shows an error insteadlet 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: '*/*' } });+ apiFetch(`${target.url}/meta`, { headers: { Accept: 'application/json' } })+ .then((res) => (res.ok ? res.json() : null))+ .then((m: { name?: string; size?: number; content_type?: string; ext?: string } | null) => {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;+ if (m) {+ setMeta({+ name: m.name || target.name || '',+ size: typeof m.size === 'number' ? m.size : null,+ mime: m.content_type || null,+ ext: m.ext || null,+ });}- setStatus({ phase: 'ready', kind, text });- } catch {- if (alive) setStatus({ phase: 'error' });- }- })();+ setMetaLoaded(true);+ })+ .catch(() => {+ if (alive) setMetaLoaded(true);+ });return () => {alive = false;};- }, [target.url, target.name]);+ }, [target.url, target.name, proxy]);const copy = async () => {- if (status.phase !== 'ready') return;- if (await copyTextToClipboard(status.text)) {+ if (text == null) return;+ if (await copyTextToClipboard(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(' · ');+ const name = meta.name || target.name || '';+ const ext = name.includes('.') ? (name.split('.').pop() || '').toUpperCase() : '';+ const metaLine = [ext || null, formatBytes(meta.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>;+ let body: React.ReactNode;+ if (!proxy) body = <div className="vr-fileview-msg">{t('preview.failed')}</div>;+ else if (!metaLoaded) body = <div className="vr-fileview-msg">{t('common.loading')}</div>;+ else body = <FilePreview source={{ url: target.url, name, ext: meta.ext, mime: meta.mime, size: meta.size }} onText={setText} />;return (<Dialog@@ -275,38 +82,30 @@ export default function FileViewerModal({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"- >+ {/* 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. */}+ {/* Definite height (not just max-h): the FilePreview kernel scrolls internally via h-full, which+ needs a resolved parent height — a content-driven box would collapse it. */}+ <DialogContent aria-describedby={undefined} className="flex h-[80vh] w-full max-w-3xl flex-col gap-0 overflow-hidden p-0 max-md:h-[82dvh]"><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>+ <DialogTitle className="truncate text-[13px] font-semibold text-foreground">{name || t('chat.media.preview')}</DialogTitle>{metaLine && <div className="font-mono text-[10px] text-muted">{metaLine}</div>}</div>- {status.phase === 'ready' && (+ {text != null && (<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)}- >+ <a href={`${target.url}?download=1`} download onClick={(e) => handleMediaDownloadClick(e, target.url, name || undefined)}><Download className="size-4" /></a></Button></div>- <div className="vr-fileview-body min-h-0 flex-1 overflow-auto">{bodyNode}</div>+ <div className="vr-fileview-body min-h-0 flex-1 overflow-hidden">{body}</div></DialogContent></Dialog>);diff --git a/ui/src/components/ui/preview-json.tsx b/ui/src/components/ui/preview-json.tsxnew file mode 100644index 000000000..2e6d29034--- /dev/null+++ b/ui/src/components/ui/preview-json.tsx@@ -0,0 +1,23 @@+import JsonView from '@uiw/react-json-view';+import { githubDarkTheme } from '@uiw/react-json-view/githubDark';+import { githubLightTheme } from '@uiw/react-json-view/githubLight';++import { useTheme } from '@/context/ThemeContext';++// The interactive JSON tree, isolated in its own module so the shared preview kernel can+// ``React.lazy`` it — @uiw/react-json-view and its two themes then split into a chunk that loads only+// when a JSON file is actually previewed, never touching the apps/main bundle. The caller (JsonBlock+// in file-preview) has already decided the value is an object/array small enough to mount as a tree.+export default function PreviewJson({ value }: { value: object }) {+ const { resolvedTheme } = useTheme();+ return (+ <JsonView+ value={value}+ style={resolvedTheme === 'light' ? githubLightTheme : githubDarkTheme}+ collapsed={2}+ displayDataTypes={false}+ shortenTextAfterLength={0}+ className="vr-fileview-json"+ />+ );+}diff --git a/ui/src/components/workbench/AppsFileBrowserPage.tsx b/ui/src/components/workbench/AppsFileBrowserPage.tsxindex 1e88f68fa..88b7aafd2 100644--- a/ui/src/components/workbench/AppsFileBrowserPage.tsx+++ b/ui/src/components/workbench/AppsFileBrowserPage.tsx@@ -27,7 +27,7 @@ import clsx from 'clsx';import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';import { useWindowManager } from '../../context/WindowManagerContext';-import { isEditableFile, isEditableMeta, isRenderOnlyImage } from '../../lib/filePreview';+import { isEditableFile, isEditableMeta, previewOverlayKind, type PreviewOverlayKind } from '../../lib/filePreview';import {contentUrl,downloadFile,@@ -45,7 +45,7 @@ import {type FsListing,} from '../../lib/filesApi';import { Button } from '../ui/button';-import { FilePreview } from './FilePreview';+import { FilePreview } from '../ui/file-preview';// A code-file extension → its accent + glyph (mirrors design nknn2's colored type icons).const EXT_ICON: Record<string, { Icon: LucideIcon; color: string }> = {@@ -124,7 +124,7 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri// Quick-look image preview: a raster image opens in an in-window overlay (Finder-style) instead// of downloading. Kept in-window (not a portaled Dialog) so it stays inside the window's dark// data-theme scope and bounds.- const [preview, setPreview] = useState<{ path: string; name: string } | null>(null);+ const [preview, setPreview] = useState<{ path: string; name: string; kind: PreviewOverlayKind } | null>(null);useEffect(() => {if (!preview) return;const onKey = (ev: KeyboardEvent) => {@@ -185,13 +185,16 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: strinavigate(full);return;}- // A raster image has no editable text form (it would otherwise just download) — preview it in an- // overlay instead. Works on mobile too (the overlay is in-window, unlike the desktop-only editor).- if (isRenderOnlyImage(e)) {- setPreview({ path: full, name: e.name });+ // A raster image, PDF, or Office doc (DOCX / XLSX / PPTX) → preview read-only in the in-window+ // overlay instead of downloading. Works on mobile too (the overlay is in-window, unlike the+ // desktop-only editor). Editable text (incl. svg / html / markdown) is excluded here — it opens in+ // the editor, which carries its own Source ⇄ Preview toggle.+ const overlay = previewOverlayKind(e);+ if (overlay) {+ setPreview({ path: full, name: e.name, kind: overlay });return;}- // Mobile has no editor window layer (windows are md+), so a non-image file just downloads.+ // Mobile has no editor window layer (windows are md+), so a non-previewable file just downloads.const desktop = window.matchMedia('(min-width: 768px)').matches;if (!desktop) {downloadFile(full);@@ -470,7 +473,7 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri{preview && (<div className="absolute inset-0 z-20 flex flex-col bg-surface"><div className="flex items-center gap-2 border-b border-border bg-surface-2/60 px-3 py-2">- <ImageIcon className="size-4 shrink-0 text-muted" />+ {preview.kind === 'image' ? <ImageIcon className="size-4 shrink-0 text-muted" /> : <FileText className="size-4 shrink-0 text-muted" />}<span className="min-w-0 flex-1 truncate text-[12.5px] font-medium text-foreground">{preview.name}</span><Buttontype="button"@@ -487,7 +490,7 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri</Button></div><div className="min-h-0 flex-1">- <FilePreview kind="image" src={contentUrl(preview.path)} name={preview.name} />+ <FilePreview source={{ url: contentUrl(preview.path), name: preview.name }} /></div></div>)}diff --git a/ui/src/components/workbench/EditorApp.tsx b/ui/src/components/workbench/EditorApp.tsxindex 83566df58..f34d61d61 100644--- a/ui/src/components/workbench/EditorApp.tsx+++ b/ui/src/components/workbench/EditorApp.tsx@@ -1,13 +1,13 @@import { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react';-import { Blocks, Bug, Clock, CodeXml, FilePlus, Files, FolderOpen, GitBranch, Image as ImageIcon, Search, Settings, X } from 'lucide-react';+import { Blocks, Bug, Clock, CodeXml, FilePlus, Files, FileText, FolderOpen, GitBranch, Image as ImageIcon, Search, Settings, X } from 'lucide-react';import { useTranslation } from 'react-i18next';import clsx from 'clsx';import { useWindowCloseGuard, useWindowManager } from '../../context/WindowManagerContext';import { contentUrl, downloadFile, fileMeta, joinPath, parentDir, writeFile, type FsEntry } from '../../lib/filesApi';-import { imageKind, isEditableFile, isEditableMeta, isRenderOnlyImage } from '../../lib/filePreview';+import { isEditableFile, isEditableMeta, previewOverlayKind, previewRenderKind } from '../../lib/filePreview';import { FileTree } from './FileTree';-import { FilePreview } from './FilePreview';+import { FilePreview } from '../ui/file-preview';import { FilePicker, type FilePickerMode } from './FilePicker';import { EditorSearchView } from './EditorSearchView';@@ -18,9 +18,9 @@ const FileEditorPane = lazy(() => import('./FileEditorPane').then((m) => ({ defa// clobbering newer on-disk content. `path` is null for an unsaved "untitled" buffer (a VS// Code-style new file): it lives only in memory until the first save picks a location. Tabs are// keyed by a synthetic `id` (not the path) so an untitled tab survives becoming a saved file.-// `kind` defaults to 'edit' (a Monaco buffer). An 'image' tab renders a read-only FilePreview-// instead — a raster image has no editable text form, so it's viewed, not edited.-type Tab = { id: string; path: string | null; name: string; mtime: number | null; reload?: number; kind?: 'edit' | 'image' };+// `kind` defaults to 'edit' (a Monaco buffer). A 'preview' tab renders the read-only FilePreview+// kernel instead — for a raster image / PDF / Office doc, which have no editable text form.+type Tab = { id: string; path: string | null; name: string; mtime: number | null; reload?: number; kind?: 'edit' | 'preview' };// A pending file dialog, rendered as the in-window FilePicker overlay.type PickerState = {@@ -134,9 +134,9 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un[],);- // Open (or focus) a raster image as a read-only preview tab (no Monaco). Dedups by path inside the- // updater so a fast double-open can't append two tabs.- const openImage = useCallback((path: string, name: string) => {+ // Open (or focus) a rich file (raster image / PDF / Office doc) as a read-only preview tab (no+ // Monaco). Dedups by path inside the updater so a fast double-open can't append two tabs.+ const openPreview = useCallback((path: string, name: string) => {setRoot((r) => r ?? parentDir(path));setTabs((ts) => {const existing = ts.find((x) => x.path === path);@@ -144,7 +144,7 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, unsetActive(id);setCursor(null);if (existing) return ts;- return [...ts, { id, path, name, mtime: null, kind: 'image' }];+ return [...ts, { id, path, name, mtime: null, kind: 'preview' }];});}, []);@@ -170,10 +170,10 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un// await so the click's user activation survives (Safari/iOS would block the popup otherwise).const onTreeOpen = useCallback(async (path: string, entry: FsEntry) => {- // A raster image previews in an image tab (no Monaco); SVG/Markdown stay editable (with a- // preview toggle inside the pane).- if (isRenderOnlyImage(entry)) {- openImage(path, entry.name);+ // A raster image / PDF / Office doc opens in a read-only preview tab (no Monaco); svg / html /+ // markdown / code / json / csv stay editable (with a preview toggle inside the pane).+ if (previewOverlayKind(entry)) {+ openPreview(path, entry.name);return;}// Fetch fresh metadata (also content-sniffs `text`) and decide by CONTENT, not just the@@ -195,7 +195,7 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un}}},- [openFile, openImage],+ [openFile, openPreview],);// After a cross-file replace/undo rewrites files on disk, reload any open, non-dirty tab for a@@ -265,7 +265,7 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, unconst p = typeof params?.path === 'string' ? params.path : null;if (p) {const name = (typeof params?.filename === 'string' ? params.filename : p.split('/').filter(Boolean).pop()) || p;- if (imageKind(name) === 'raster') openImage(p, name);+ if (previewOverlayKind({ kind: 'file', name, size: null })) openPreview(p, name);else openFile(p, name, typeof params?.mtime === 'number' ? params.mtime : null);return;}@@ -544,7 +544,11 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un}}className="flex items-center gap-1.5">- {tab.kind === 'image' ? <ImageIcon className="size-3.5 text-violet" /> : <CodeXml className="size-3.5 text-cyan" />}+ {tab.kind === 'preview' ? (+ previewRenderKind(tab.name) === 'image' ? <ImageIcon className="size-3.5 text-violet" /> : <FileText className="size-3.5 text-violet" />+ ) : (+ <CodeXml className="size-3.5 text-cyan" />+ )}{tab.name}{dirty[tab.id] && <span className="size-1.5 rounded-full bg-mint" />}</button>@@ -567,8 +571,8 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un) : (tabs.map((tab) => (<div key={tab.id} className={clsx('absolute inset-0', active === tab.id ? 'block' : 'hidden')}>- {tab.kind === 'image' && tab.path ? (- <FilePreview kind="image" src={contentUrl(tab.path)} name={tab.name} />+ {tab.kind === 'preview' && tab.path ? (+ <FilePreview source={{ url: contentUrl(tab.path), name: tab.name }} />) : (<Suspense fallback={<div className="grid h-full place-items-center text-[12px] text-muted">{t('common.loading')}</div>}><FileEditorPane@@ -599,8 +603,8 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, unhardcoded "master · 0 ⚠ 0" would be misleading, so those are omitted until wired. Theright side (cursor / indentation / language) is real. */}<div className="flex items-center gap-3.5 bg-cyan px-3.5 py-1 font-mono text-[10.5px] font-semibold text-[#06222B]">- {active && activeTab?.kind === 'image' ? (- <span className="ml-auto truncate">{t('apps.editor.imagePreview')}</span>+ {active && activeTab?.kind === 'preview' ? (+ <span className="ml-auto truncate">{t('preview.title')}</span>) : active ? (<><span className="ml-auto tabular-nums">{t('apps.editor.lineCol', { line: cursor?.line ?? 1, col: cursor?.col ?? 1 })}</span>diff --git a/ui/src/components/workbench/FileEditorPane.tsx b/ui/src/components/workbench/FileEditorPane.tsxindex 6dedfa37a..8331a964f 100644--- a/ui/src/components/workbench/FileEditorPane.tsx+++ b/ui/src/components/workbench/FileEditorPane.tsx@@ -7,8 +7,8 @@ import { useTheme } from '../../context/ThemeContext';import { useWindowCloseGuard } from '../../context/WindowManagerContext';import { Button } from '../ui/button';import { fileBrowserErrorMessage, readText, writeFile } from '../../lib/filesApi';-import { imageKind, previewKind } from '../../lib/filePreview';-import { FilePreview } from './FilePreview';+import { editorPreviewKind } from '../../lib/filePreview';+import { FilePreview } from '../ui/file-preview';// Monaco (the VS Code kernel) is heavy; lazy-load it so it stays out of the main// bundle and only loads when a file is actually opened for editing.@@ -120,15 +120,11 @@ export const FileEditorPane: React.FC<{const [loading, setLoading] = useState(true);const [saving, setSaving] = useState(false);const [error, setError] = useState<string | null>(null);- // Markdown / SVG can be previewed (rendered) as well as edited, VS-Code-style. `mode` toggles the- // body between the Monaco source and the rendered FilePreview, using the LIVE buffer so the+ // Markdown / SVG / HTML can be previewed (rendered) as well as edited, VS-Code-style. `mode` toggles+ // the body between the Monaco source and the rendered FilePreview, using the LIVE buffer so the// preview reflects unsaved edits.const [mode, setMode] = useState<'source' | 'preview'>('source');- const previewable: 'markdown' | 'svg' | null = useMemo(() => {- if (previewKind(filename) === 'markdown') return 'markdown';- if (imageKind(filename) === 'svg') return 'svg';- return null;- }, [filename]);+ const previewable = useMemo(() => editorPreviewKind(filename), [filename]);// A new file may not be previewable — never strand the body in a preview mode it can't render.useEffect(() => {if (!previewable) setMode('source');@@ -310,10 +306,8 @@ export const FileEditorPane: React.FC<{<div className={clsx('min-h-0 flex-1', loading && 'grid place-items-center')}>{loading ? (<Loader2 className="size-5 animate-spin text-muted" />- ) : text === null ? null : mode === 'preview' && previewable === 'markdown' ? (- <FilePreview kind="markdown" content={text} />- ) : mode === 'preview' && previewable === 'svg' ? (- <FilePreview kind="image" src={`data:image/svg+xml;charset=utf-8,${encodeURIComponent(text)}`} name={filename} />+ ) : text === null ? null : mode === 'preview' && previewable ? (+ <FilePreview source={{ text, name: filename }} />) : (<Suspense fallback={<div className="p-4 text-[12px] text-muted">{t('common.loading')}</div>}><MonacoEditordiff --git a/ui/src/components/workbench/FilePreview.tsx b/ui/src/components/workbench/FilePreview.tsxdeleted file mode 100644index 4e750ef17..000000000--- a/ui/src/components/workbench/FilePreview.tsx+++ /dev/null@@ -1,66 +0,0 @@-import { useEffect, useState } from 'react';-import { useTranslation } from 'react-i18next';-import clsx from 'clsx';--import { Markdown } from '../ui/markdown';--// Reusable RENDERED (non-editor) file preview for the windowed apps. Pure/presentational: the-// caller supplies the image `src` or the markdown `content`, so the same component serves an-// on-disk image (File Browser overlay, editor image tab — src = contentUrl(path)) and a LIVE buffer-// the editor is editing (SVG preview via a data: URL, Markdown via the buffer text). Code/JSON/CSV-// stay in Monaco / the chat FileViewer; this only covers what the editor can't show as text.-type FilePreviewProps =- | { kind: 'image'; src: string; name?: string; className?: string }- | { kind: 'markdown'; content: string; className?: string };--export const FilePreview: React.FC<FilePreviewProps> = (props) => {- if (props.kind === 'markdown') {- return (- <div className={clsx('h-full min-h-0 overflow-auto bg-surface', props.className)}>- <Markdown content={props.content} interactive={false} className="vr-fileview-md mx-auto max-w-3xl px-6 py-5" />- </div>- );- }- return <ImagePreview src={props.src} name={props.name} className={props.className} />;-};--// Fit-to-container by default; click toggles 1:1 actual size (zoom-in / zoom-out cursor), with the-// container scrolling when the image overflows. The dark checker-free backdrop keeps transparent-// PNGs/SVGs legible inside the dark-locked windows.-const ImagePreview: React.FC<{ src: string; name?: string; className?: string }> = ({ src, name, className }) => {- const { t } = useTranslation();- const [status, setStatus] = useState<'loading' | 'ready' | 'error'>('loading');- const [actual, setActual] = useState(false);- // Reset when the source changes — the live SVG preview re-points `src` on every keystroke, so a- // transient error (a momentarily-invalid buffer) must clear once the buffer becomes valid again.- useEffect(() => {- setStatus('loading');- setActual(false);- }, [src]);-- if (status === 'error') {- return (- <div className={clsx('grid h-full min-h-0 place-items-center bg-[#0c0c0f] p-4 text-[12.5px] text-muted', className)}>- {t('apps.fileBrowser.previewFailed')}- </div>- );- }- return (- <div className={clsx('grid h-full min-h-0 place-items-center overflow-auto bg-[#0c0c0f] p-4', className)}>- {status === 'loading' && <div className="col-start-1 row-start-1 text-[12px] text-muted">{t('common.loading')}</div>}- <img- src={src}- alt={name || ''}- onLoad={() => setStatus('ready')}- onError={() => setStatus('error')}- onClick={() => setActual((a) => !a)}- draggable={false}- className={clsx(- 'col-start-1 row-start-1 select-none',- actual ? 'max-w-none cursor-zoom-out' : 'max-h-full max-w-full cursor-zoom-in object-contain',- status !== 'ready' && 'opacity-0',- )}- />- </div>- );-};diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex a666aa9a3..93128d53f 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -13,6 +13,16 @@"retry": "Retry","reload": "Reload page"},+ "preview": {+ "title": "Preview",+ "unsupported": "This file can't be previewed.",+ "failed": "Couldn't load this file for preview.",+ "tooLarge": "File too large to preview — download it instead.",+ "truncated": "Large file — showing only the first part.",+ "empty": "This file is empty.",+ "csvTruncated": "Showing the first {{count}} rows",+ "csvColsTruncated": "Showing {{shown}} of {{total}} columns"+ },"common": {"back": "Back","continue": "Continue",@@ -626,7 +636,6 @@"lineCol": "Ln {{line}}, Col {{col}}","spaces": "Spaces: {{n}}","plainText": "Plain Text",- "imagePreview": "Image preview","source": "Source","preview": "Preview","empty": "No file open",@@ -696,7 +705,6 @@"rename": "Rename","delete": "Delete","confirmDelete": "Delete \"{{name}}\"? This can't be undone.",- "previewFailed": "Couldn't load this image.","searchPlaceholder": "Search","colName": "Name","colSize": "Size",@@ -2146,12 +2154,7 @@"previous": "Previous","next": "Next","zoomIn": "Zoom in",- "zoomOut": "Zoom out",- "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"+ "zoomOut": "Zoom out"},"queue": {"title": "Queued · {{count}}",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 8183700d7..a730595e3 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -13,6 +13,16 @@"retry": "重试","reload": "刷新页面"},+ "preview": {+ "title": "预览",+ "unsupported": "此文件无法预览。",+ "failed": "无法加载此文件预览。",+ "tooLarge": "文件过大,无法预览,请直接下载。",+ "truncated": "文件较大,仅显示开头部分。",+ "empty": "此文件为空。",+ "csvTruncated": "仅显示前 {{count}} 行",+ "csvColsTruncated": "显示前 {{shown}} 列,共 {{total}} 列"+ },"common": {"back": "返回","continue": "继续",@@ -626,7 +636,6 @@"lineCol": "行 {{line}},列 {{col}}","spaces": "空格:{{n}}","plainText": "纯文本",- "imagePreview": "图片预览","source": "源码","preview": "预览","empty": "未打开文件",@@ -696,7 +705,6 @@"rename": "重命名","delete": "删除","confirmDelete": "删除“{{name}}”?此操作无法撤销。",- "previewFailed": "无法加载此图片。","searchPlaceholder": "搜索","colName": "名称","colSize": "大小",@@ -2145,12 +2153,7 @@"previous": "上一张","next": "下一张","zoomIn": "放大",- "zoomOut": "缩小",- "loading": "加载中…",- "error": "无法加载该文件。",- "tooLarge": "文件过大,无法预览,请直接下载。",- "csvTruncated": "仅显示前 {{count}} 行",- "csvColsTruncated": "显示前 {{shown}} 列,共 {{total}} 列"+ "zoomOut": "缩小"},"queue": {"title": "排队中 · {{count}}",diff --git a/ui/src/lib/filePreview.ts b/ui/src/lib/filePreview.tsindex 43f454925..02911d5d3 100644--- a/ui/src/lib/filePreview.ts+++ b/ui/src/lib/filePreview.ts@@ -66,11 +66,17 @@ function extOf(name: string): string {return i > 0 ? b.slice(i + 1).toLowerCase() : '';}+// The extension to classify by. The server-supplied ext wins when present: for chat media the `name`+// can be an arbitrary Markdown label (`[report.pdf](…/report.docx)`) while serverExt/mime are the real+// type — so trusting the label's suffix would route to the wrong renderer. Falls back to the name's+// own extension when no serverExt is given (File Browser / editor, which pass real filenames).+function effectiveExt(name: string, serverExt?: string | null): string {+ return (serverExt || '').replace(/^\.+/, '').toLowerCase() || extOf(name);+}+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 ext = effectiveExt(name, serverExt);const m = (mime || '').split(';')[0].trim().toLowerCase();if (MARKDOWN_EXT.has(ext)) return 'markdown';@@ -116,26 +122,115 @@ export type ImageKind = 'raster' | 'svg';// ``previewKind`` (which classifies EDITABLE text): images have no text kind, and SVG is both an// image (renderable here) and source (editable in Monaco), so ``previewKind('x.svg') === 'source'``// must stay true while this still reports it as an image.-export function imageKind(name: string, mime?: string | null): ImageKind | null {- const ext = extOf(name);+export function imageKind(name: string, mime?: string | null, serverExt?: string | null): ImageKind | null {+ const ext = effectiveExt(name, serverExt);const m = (mime || '').split(';')[0].trim().toLowerCase();if (ext === 'svg' || m === 'image/svg+xml') return 'svg';if (RASTER_IMAGE_EXT.has(ext) || (m.startsWith('image/') && m !== 'image/svg+xml')) return 'raster';return null;}-// Whether a file should preview as RENDERED (not edited) when opened from the File Browser: a raster-// image (no editable text form) within the content cap is the only such case. SVG/Markdown stay-// editable, gaining a preview TOGGLE inside the editor instead. A directory, symlink, or oversized-// image (which `/api/files/content` would reject) is never previewed here — it falls to download.-export function isRenderOnlyImage(entry: { kind: string; name: string; size: number | null }): boolean {- return entry.kind === 'file' && imageKind(entry.name) === 'raster' && (entry.size == null || entry.size <= IMAGE_PREVIEW_MAX_BYTES);+// Rich documents we can preview client-side (read-only): Office files rendered by lazy-loaded libs+// (docx-preview / SheetJS / PptxViewJS) and PDF via the browser's built-in viewer. Kept separate+// from previewKind/imageKind. The parsers pull the whole file into memory, so it's gated by the+// content cap; an oversized doc (which /api/files/content would reject anyway) falls to download.+export type DocPreviewKind = 'docx' | 'xlsx' | 'pptx' | 'pdf';+// NB: csv is intentionally NOT here — it renders as a CSV table (papaparse), lighter than loading+// SheetJS, and matches the chat viewer. ``previewRenderKind`` maps csv → 'csv'.+const DOC_EXT: Record<string, DocPreviewKind> = {+ docx: 'docx',+ xlsx: 'xlsx',+ xlsm: 'xlsx',+ xls: 'xlsx',+ pptx: 'pptx',+ pdf: 'pdf',+};+export const DOC_PREVIEW_MAX_BYTES = IMAGE_PREVIEW_MAX_BYTES; // 25 MB, matches the backend content cap++// Office/PDF content types → kind, so a descriptive-label chat link (whose name carries no real+// suffix) still classifies via the server-supplied content-type. Limited to formats our renderers+// actually read: the OOXML types + PDF, plus legacy .xls (SheetJS reads BIFF). Legacy binary .doc+// (application/msword) and .ppt (application/vnd.ms-powerpoint) are intentionally absent — docx-preview+// and PptxViewJS only load OOXML, so advertising them would open a broken preview instead of download.+const OFFICE_MIME: Record<string, DocPreviewKind> = {+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',+ 'application/vnd.ms-excel': 'xlsx',+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',+ 'application/pdf': 'pdf',+};++export function docPreviewKind(name: string, mime?: string | null, serverExt?: string | null): DocPreviewKind | null {+ const ext = effectiveExt(name, serverExt);+ if (ext in DOC_EXT) return DOC_EXT[ext];+ const m = (mime || '').split(';')[0].trim().toLowerCase();+ return OFFICE_MIME[m] ?? null;+}++// ── Unified preview dispatch ────────────────────────────────────────────────+// HOW a file renders in the shared <FilePreview> kernel (one classifier for the File Browser, the+// editor preview, and the chat viewer). Combines imageKind (raster/svg) + html + docPreviewKind+// (office/pdf) + previewKind (text). 'code' is the catch-all for highlightable text — including+// non-HTML markup (xml/vue/svelte) and plain text (highlights to nothing). Order matters: images and+// HTML are decided before the text classifier so an .svg renders as an image, not edited source.+export type PreviewRenderKind =+ | 'image'+ | 'svg'+ | 'html'+ | 'pdf'+ | 'docx'+ | 'xlsx'+ | 'pptx'+ | 'markdown'+ | 'json'+ | 'csv'+ | 'code';++const HTML_EXT = new Set(['html', 'htm']);++export function previewRenderKind(name: string, mime?: string | null, serverExt?: string | null): PreviewRenderKind | null {+ const img = imageKind(name, mime, serverExt);+ if (img === 'raster') return 'image';+ if (img === 'svg') return 'svg';+ const ext = effectiveExt(name, serverExt);+ const m = (mime || '').split(';')[0].trim().toLowerCase();+ if (HTML_EXT.has(ext) || m === 'text/html') return 'html';+ const doc = docPreviewKind(name, mime, serverExt);+ if (doc) return doc;+ const k = previewKind(name, mime, serverExt);+ if (k === 'markdown') return 'markdown';+ if (k === 'json') return 'json';+ if (k === 'csv') return 'csv';+ if (k === 'code' || k === 'source' || k === 'text') return 'code';+ return null;+}++// The renderable EDITABLE-text kinds the in-editor Source ⇄ Preview toggle offers: Markdown, SVG, and+// HTML all have a meaningful rendered form while staying editable in Monaco. Everything else (code,+// json, csv, plain text) has no distinct render, so the toggle is hidden.+export type EditorPreviewKind = 'markdown' | 'svg' | 'html';+export function editorPreviewKind(name: string): EditorPreviewKind | null {+ if (previewKind(name) === 'markdown') return 'markdown';+ if (imageKind(name) === 'svg') return 'svg';+ if (HTML_EXT.has(extOf(name))) return 'html';+ return null;+}++// What opens in the File Browser's read-only PREVIEW overlay (vs. the editor): a non-editable rich+// file — raster image, PDF, or Office doc — within the content cap. Editable text (incl. svg / html /+// markdown / code / json / csv) opens in the editor instead, which carries its own preview toggle.+export type PreviewOverlayKind = 'image' | 'pdf' | 'docx' | 'xlsx' | 'pptx';+export function previewOverlayKind(entry: { kind: string; name: string; size: number | null }): PreviewOverlayKind | null {+ if (entry.kind !== 'file') return null;+ if (entry.size != null && entry.size > DOC_PREVIEW_MAX_BYTES) return null;+ const rk = previewRenderKind(entry.name);+ return rk === 'image' || rk === 'pdf' || rk === 'docx' || rk === 'xlsx' || rk === 'pptx' ? rk : 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();+ const ext = effectiveExt(name, serverExt);return SOURCE_LANG[ext] || CODE_LANG[ext] || NAME_LANG[b] || 'text';}