diff --git a/tui/README.md b/tui/README.md index cc2b947be..e8a04467b 100644 --- a/tui/README.md +++ b/tui/README.md @@ -19,6 +19,8 @@ The TUI uses OpenTUI's retained full-screen layout: the transcript reflows with Assistant math written with `$...$`, `$$...$$`, `\\(...\\)`, or `\\[...\\]` is presented as Unicode plain text so formulas remain readable in terminals without a math renderer. Currency and LaTeX inside inline or fenced code remain literal. +Mermaid diagrams appear after a reply finishes. Press `Ctrl+G` or run `/diagrams` to open the viewer, where you can zoom, pan, switch diagrams, and view or copy the source. Keyboard shortcuts are shown at the bottom. Press `q` or `Esc` to return without losing your draft or reading position. If a diagram cannot be displayed, its source remains available. + Automatic theme selection follows the terminal's OSC 10/11 responses. Until a response arrives, the TUI uses the terminal's default foreground and background without semantic colors or color animations. Terminals that do not answer keep this readable fallback. Use `nanobot --theme light` or `nanobot --theme dark` to select a color palette explicitly. ## Herdr pane titles diff --git a/tui/RELINKING.md b/tui/RELINKING.md index f962a7744..67c0fd8d1 100644 --- a/tui/RELINKING.md +++ b/tui/RELINKING.md @@ -8,6 +8,9 @@ Corresponding upstream source: - Bun 1.3.13 (`bf2e2cecf27e800962b1e7f03d66278f9d5d2e79`): - Bun's patched WebKit (`4d5e75ebd84a14edbc7ae264245dcd77fe597c10`): - OpenTUI 0.5.11: (source: ) +- Pele 1.6.0: +- resvg-js 2.6.2 (unmodified MPL-2.0 wrapper and native binding): ; its upstream license text is reproduced in the notices. +- fontkit 2.0.4: ; fontkit, dfa 1.2.0, and brotli 1.3.3 declare MIT in their upstream README files, which are reproduced in the notices because these npm releases have no standalone license file. Exact dependency versions and tarball integrity are pinned in `bun.lock`. To rebuild against a modified JavaScriptCore/WebKit, first build Bun 1.3.13 from its complete source checkout together with the WebKit revision above by following Bun's pinned license and build instructions. Then unpack `nanobot-tui-source.tar.gz` from the release archive and run the resulting Bun executable: diff --git a/tui/bun.lock b/tui/bun.lock index b7bbd0676..08331772a 100644 --- a/tui/bun.lock +++ b/tui/bun.lock @@ -6,9 +6,16 @@ "name": "@nanobot/tui", "dependencies": { "@opentui/core": "0.5.11", + "@resvg/resvg-js": "2.6.2", + "@xmldom/xmldom": "0.8.11", + "css-tree": "3.2.1", + "fontkit": "2.0.4", + "pele": "1.6.0", }, "devDependencies": { "@types/bun": "^1.3.13", + "@types/css-tree": "^3.2.0", + "@types/fontkit": "^2.0.9", "typescript": "^5.9.3", }, }, @@ -32,32 +39,98 @@ "@opentui/core-win32-x64": ["@opentui/core-win32-x64@0.5.11", "", { "os": "win32", "cpu": "x64" }, "sha512-sMEGX9rhiPd1gBa190jzj5uIdzKCMImxHmr22hJLxIRWqejxWvqGnRBkW68wT8NfMViDiMtZWavgWL7GgmYCAQ=="], + "@resvg/resvg-js": ["@resvg/resvg-js@2.6.2", "", { "optionalDependencies": { "@resvg/resvg-js-android-arm-eabi": "2.6.2", "@resvg/resvg-js-android-arm64": "2.6.2", "@resvg/resvg-js-darwin-arm64": "2.6.2", "@resvg/resvg-js-darwin-x64": "2.6.2", "@resvg/resvg-js-linux-arm-gnueabihf": "2.6.2", "@resvg/resvg-js-linux-arm64-gnu": "2.6.2", "@resvg/resvg-js-linux-arm64-musl": "2.6.2", "@resvg/resvg-js-linux-x64-gnu": "2.6.2", "@resvg/resvg-js-linux-x64-musl": "2.6.2", "@resvg/resvg-js-win32-arm64-msvc": "2.6.2", "@resvg/resvg-js-win32-ia32-msvc": "2.6.2", "@resvg/resvg-js-win32-x64-msvc": "2.6.2" } }, "sha512-xBaJish5OeGmniDj9cW5PRa/PtmuVU3ziqrbr5xJj901ZDN4TosrVaNZpEiLZAxdfnhAe7uQ7QFWfjPe9d9K2Q=="], + + "@resvg/resvg-js-android-arm-eabi": ["@resvg/resvg-js-android-arm-eabi@2.6.2", "", { "os": "android", "cpu": "arm" }, "sha512-FrJibrAk6v29eabIPgcTUMPXiEz8ssrAk7TXxsiZzww9UTQ1Z5KAbFJs+Z0Ez+VZTYgnE5IQJqBcoSiMebtPHA=="], + + "@resvg/resvg-js-android-arm64": ["@resvg/resvg-js-android-arm64@2.6.2", "", { "os": "android", "cpu": "arm64" }, "sha512-VcOKezEhm2VqzXpcIJoITuvUS/fcjIw5NA/w3tjzWyzmvoCdd+QXIqy3FBGulWdClvp4g+IfUemigrkLThSjAQ=="], + + "@resvg/resvg-js-darwin-arm64": ["@resvg/resvg-js-darwin-arm64@2.6.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-nmok2LnAd6nLUKI16aEB9ydMC6Lidiiq2m1nEBDR1LaaP7FGs4AJ90qDraxX+CWlVuRlvNjyYJTNv8qFjtL9+A=="], + + "@resvg/resvg-js-darwin-x64": ["@resvg/resvg-js-darwin-x64@2.6.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-GInyZLjgWDfsVT6+SHxQVRwNzV0AuA1uqGsOAW+0th56J7Nh6bHHKXHBWzUrihxMetcFDmQMAX1tZ1fZDYSRsw=="], + + "@resvg/resvg-js-linux-arm-gnueabihf": ["@resvg/resvg-js-linux-arm-gnueabihf@2.6.2", "", { "os": "linux", "cpu": "arm" }, "sha512-YIV3u/R9zJbpqTTNwTZM5/ocWetDKGsro0SWp70eGEM9eV2MerWyBRZnQIgzU3YBnSBQ1RcxRZvY/UxwESfZIw=="], + + "@resvg/resvg-js-linux-arm64-gnu": ["@resvg/resvg-js-linux-arm64-gnu@2.6.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-zc2BlJSim7YR4FZDQ8OUoJg5holYzdiYMeobb9pJuGDidGL9KZUv7SbiD4E8oZogtYY42UZEap7dqkkYuA91pg=="], + + "@resvg/resvg-js-linux-arm64-musl": ["@resvg/resvg-js-linux-arm64-musl@2.6.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-3h3dLPWNgSsD4lQBJPb4f+kvdOSJHa5PjTYVsWHxLUzH4IFTJUAnmuWpw4KqyQ3NA5QCyhw4TWgxk3jRkQxEKg=="], + + "@resvg/resvg-js-linux-x64-gnu": ["@resvg/resvg-js-linux-x64-gnu@2.6.2", "", { "os": "linux", "cpu": "x64" }, "sha512-IVUe+ckIerA7xMZ50duAZzwf1U7khQe2E0QpUxu5MBJNao5RqC0zwV/Zm965vw6D3gGFUl7j4m+oJjubBVoftw=="], + + "@resvg/resvg-js-linux-x64-musl": ["@resvg/resvg-js-linux-x64-musl@2.6.2", "", { "os": "linux", "cpu": "x64" }, "sha512-UOf83vqTzoYQO9SZ0fPl2ZIFtNIz/Rr/y+7X8XRX1ZnBYsQ/tTb+cj9TE+KHOdmlTFBxhYzVkP2lRByCzqi4jQ=="], + + "@resvg/resvg-js-win32-arm64-msvc": ["@resvg/resvg-js-win32-arm64-msvc@2.6.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-7C/RSgCa+7vqZ7qAbItfiaAWhyRSoD4l4BQAbVDqRRsRgY+S+hgS3in0Rxr7IorKUpGE69X48q6/nOAuTJQxeQ=="], + + "@resvg/resvg-js-win32-ia32-msvc": ["@resvg/resvg-js-win32-ia32-msvc@2.6.2", "", { "os": "win32", "cpu": "ia32" }, "sha512-har4aPAlvjnLcil40AC77YDIk6loMawuJwFINEM7n0pZviwMkMvjb2W5ZirsNOZY4aDbo5tLx0wNMREp5Brk+w=="], + + "@resvg/resvg-js-win32-x64-msvc": ["@resvg/resvg-js-win32-x64-msvc@2.6.2", "", { "os": "win32", "cpu": "x64" }, "sha512-ZXtYhtUr5SSaBrUDq7DiyjOFJqBVL/dOBN7N/qmi/pO0IgiWW/f/ue3nbvu9joWE5aAKDoIzy/CxsY0suwGosQ=="], + + "@swc/helpers": ["@swc/helpers@0.5.23", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw=="], + "@types/bun": ["@types/bun@1.3.14", "", { "dependencies": { "bun-types": "1.3.14" } }, "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw=="], + "@types/css-tree": ["@types/css-tree@3.2.0", "", {}, "sha512-J5KXmk6BFIepOT7280FdFyNs4c5fh0Uee0otjKEvzchrRs38Ii9qminqc4ds0L19X8Zd/rT+brR9jkBthygjWw=="], + + "@types/fontkit": ["@types/fontkit@2.0.9", "", { "dependencies": { "@types/node": "*" } }, "sha512-qNYerFky3muCmZPq+R+B3cUDRA5OONw/oh6aGGFxx2LOBz6yu8eamKusrhkHnC6rc2fm76+G9z9QoWSB2SaQaw=="], + "@types/node": ["@types/node@26.2.0", "", { "dependencies": { "undici-types": "~8.3.0" } }, "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg=="], + "@xmldom/xmldom": ["@xmldom/xmldom@0.8.11", "", {}, "sha512-cQzWCtO6C8TQiYl1ruKNn2U6Ao4o4WBBcbL61yJl84x+j5sOWWFU9X7DpND8XZG3daDppSsigMdfAIl2upQBRw=="], + "ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], + "base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="], + + "brotli": ["brotli@1.3.3", "", { "dependencies": { "base64-js": "^1.1.2" } }, "sha512-oTKjJdShmDuGW94SyyaoQvAjf30dZaHnjJ8uAF+u2/vGJkJbJPJAT1gDiOJP5v1Zb6f9KEyW/1HpuaWIXtGHPg=="], + "bun-ffi-structs": ["bun-ffi-structs@0.3.1", "", { "peerDependencies": { "typescript": "^5" } }, "sha512-3gM7PpVWLyrwxWjcilSiGuhWanhZivvo6l0u573NziPH6f/gwk6McbaYgn7oJWov6pKGRTDbrg94W5DcJsKTtQ=="], "bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="], + "clone": ["clone@2.1.2", "", {}, "sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w=="], + + "css-tree": ["css-tree@3.2.1", "", { "dependencies": { "mdn-data": "2.27.1", "source-map-js": "^1.2.1" } }, "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA=="], + + "dfa": ["dfa@1.2.0", "", {}, "sha512-ED3jP8saaweFTjeGX8HQPjeC1YYyZs98jGNZx6IiBvxW7JG5v492kamAQB3m2wop07CvU/RQmzcKr6bgcC5D/Q=="], + "diff": ["diff@9.0.0", "", {}, "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw=="], "emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="], + "fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="], + + "fontkit": ["fontkit@2.0.4", "", { "dependencies": { "@swc/helpers": "^0.5.12", "brotli": "^1.3.2", "clone": "^2.1.2", "dfa": "^1.2.0", "fast-deep-equal": "^3.1.3", "restructure": "^3.0.0", "tiny-inflate": "^1.0.3", "unicode-properties": "^1.4.0", "unicode-trie": "^2.0.0" } }, "sha512-syetQadaUEDNdxdugga9CpEYVaQIxOwk7GlwZWWZ19//qW4zE5bknOKeMBDYAASwnpaSHKJITRLMF9m1fp3s6g=="], + "get-east-asian-width": ["get-east-asian-width@1.6.0", "", {}, "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA=="], "marked": ["marked@17.0.1", "", { "bin": { "marked": "bin/marked.js" } }, "sha512-boeBdiS0ghpWcSwoNm/jJBwdpFaMnZWRzjA6SkUMYb40SVaN1x7mmfGKp0jvexGcx+7y2La5zRZsYFZI6Qpypg=="], + "mdn-data": ["mdn-data@2.27.1", "", {}, "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ=="], + + "pako": ["pako@0.2.9", "", {}, "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA=="], + + "pele": ["pele@1.6.0", "", {}, "sha512-VfAiVItsOGlGhvnBfphdT28VCG7mXMZxQNOwAGsCtxI2ztbUsT39MraEOYjsapLxVETkdUZscm0DdotYDQMLdw=="], + + "restructure": ["restructure@3.0.2", "", {}, "sha512-gSfoiOEA0VPE6Tukkrr7I0RBdE0s7H1eFCDBk05l1KIQT1UIKNc5JZy6jdyW6eYH3aR3g5b3PuL77rq0hvwtAw=="], + + "source-map-js": ["source-map-js@1.2.2", "", {}, "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw=="], + "string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], "strip-ansi": ["strip-ansi@7.1.2", "", { "dependencies": { "ansi-regex": "^6.0.1" } }, "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA=="], + "tiny-inflate": ["tiny-inflate@1.0.3", "", {}, "sha512-pkY1fj1cKHb2seWDy0B16HeWyczlJA9/WW3u3c4z/NiWDsO3DOU5D7nhTLE9CF0yXv/QZFY7sEJmj24dK+Rrqw=="], + + "tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], "undici-types": ["undici-types@8.3.0", "", {}, "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ=="], + "unicode-properties": ["unicode-properties@1.4.1", "", { "dependencies": { "base64-js": "^1.3.0", "unicode-trie": "^2.0.0" } }, "sha512-CLjCCLQ6UuMxWnbIylkisbRj31qxHPAurvena/0iwSVbQ2G1VY5/HjV0IRabOEbDHlzZlRdCrD4NhB0JtU40Pg=="], + + "unicode-trie": ["unicode-trie@2.0.0", "", { "dependencies": { "pako": "^0.2.5", "tiny-inflate": "^1.0.0" } }, "sha512-x7bc76x0bm4prf1VLg79uhAzKw8DVboClSN5VxJuQ+LKDOVEW9CdH+VY7SP+vX7xCYQqzzgQpFqz15zeLvAtZQ=="], + "web-tree-sitter": ["web-tree-sitter@0.25.10", "", { "peerDependencies": { "@types/emscripten": "^1.40.0" }, "optionalPeers": ["@types/emscripten"] }, "sha512-Y09sF44/13XvgVKgO2cNDw5rGk6s26MgoZPXLESvMXeefBf7i6/73eFurre0IsTW6E14Y0ArIzhUMmjoc7xyzA=="], } } diff --git a/tui/package.json b/tui/package.json index 00709264e..e81a3cea9 100644 --- a/tui/package.json +++ b/tui/package.json @@ -12,10 +12,17 @@ "test": "bun test" }, "dependencies": { - "@opentui/core": "0.5.11" + "@opentui/core": "0.5.11", + "@resvg/resvg-js": "2.6.2", + "@xmldom/xmldom": "0.8.11", + "css-tree": "3.2.1", + "fontkit": "2.0.4", + "pele": "1.6.0" }, "devDependencies": { "@types/bun": "^1.3.13", + "@types/css-tree": "^3.2.0", + "@types/fontkit": "^2.0.9", "typescript": "^5.9.3" } } diff --git a/tui/scripts/build.ts b/tui/scripts/build.ts index 3e1152876..5d4613e59 100644 --- a/tui/scripts/build.ts +++ b/tui/scripts/build.ts @@ -25,6 +25,10 @@ const output = join(outputDir, `nanobot-tui-${platform}-${arch}${extension}`) await mkdir(outputDir, { recursive: true }) const result = await Bun.build({ entrypoints: [join(import.meta.dir, "..", "src", "index.ts")], + define: { NANOBOT_COMPILED: "true" }, + bytecode: true, + format: "esm", + minify: { whitespace: true, syntax: true, identifiers: true, keepNames: true }, compile: { target: `bun-${bunPlatform}-${arch}${cpuVariant}` as Bun.Build.CompileTarget, outfile: output, diff --git a/tui/scripts/prepare-target.ts b/tui/scripts/prepare-target.ts index 7cb57b9fa..9d25eef86 100644 --- a/tui/scripts/prepare-target.ts +++ b/tui/scripts/prepare-target.ts @@ -1,11 +1,11 @@ import { join } from "node:path" const packagesByTarget: Record = { - "darwin-arm64": ["@opentui/core-darwin-arm64"], - "darwin-x64": ["@opentui/core-darwin-x64"], - "linux-arm64": ["@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl"], - "linux-x64": ["@opentui/core-linux-x64", "@opentui/core-linux-x64-musl"], - "win32-x64": ["@opentui/core-win32-x64"], + "darwin-arm64": ["@opentui/core-darwin-arm64", "@resvg/resvg-js-darwin-arm64"], + "darwin-x64": ["@opentui/core-darwin-x64", "@resvg/resvg-js-darwin-x64"], + "linux-arm64": ["@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@resvg/resvg-js-linux-arm64-gnu", "@resvg/resvg-js-linux-arm64-musl"], + "linux-x64": ["@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@resvg/resvg-js-linux-x64-gnu", "@resvg/resvg-js-linux-x64-musl"], + "win32-x64": ["@opentui/core-win32-x64", "@resvg/resvg-js-win32-x64-msvc"], } const target = process.argv[2] @@ -15,9 +15,11 @@ if (!packages) throw new Error(`unsupported target: ${target}`) const root = join(import.meta.dir, "..") const manifest = await Bun.file(join(root, "package.json")).json() -const version = manifest.dependencies?.["@opentui/core"] -if (typeof version !== "string" || !/^\d+\.\d+\.\d+$/.test(version)) { - throw new Error("@opentui/core must use an exact version") +const versions: Record = {} +for (const name of ["@opentui/core", "@resvg/resvg-js"]) { + const version = manifest.dependencies?.[name] + if (typeof version !== "string" || !/^\d+\.\d+\.\d+$/.test(version)) throw new Error(`${name} must use an exact version`) + versions[name] = version } const npm = process.platform === "win32" ? "npm.cmd" : "npm" @@ -29,7 +31,7 @@ const result = Bun.spawnSync( "--ignore-scripts", "--force", "--package-lock=false", - ...packages.map((name) => `${name}@${version}`), + ...packages.map((name) => `${name}@${versions[name.startsWith("@opentui/") ? "@opentui/core" : "@resvg/resvg-js"]}`), ], { cwd: root, diff --git a/tui/scripts/release-notices.ts b/tui/scripts/release-notices.ts index ce2029a43..e8f9c4d3d 100644 --- a/tui/scripts/release-notices.ts +++ b/tui/scripts/release-notices.ts @@ -12,11 +12,11 @@ const supportedTargets = new Set([ ]) if (!supportedTargets.has(target)) throw new Error(`unsupported target: ${target}`) const nativePackagesByTarget: Record = { - "darwin-arm64": ["@opentui/core-darwin-arm64"], - "darwin-x64": ["@opentui/core-darwin-x64"], - "linux-arm64": ["@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl"], - "linux-x64": ["@opentui/core-linux-x64", "@opentui/core-linux-x64-musl"], - "win32-x64": ["@opentui/core-win32-x64"], + "darwin-arm64": ["@opentui/core-darwin-arm64", "@resvg/resvg-js-darwin-arm64"], + "darwin-x64": ["@opentui/core-darwin-x64", "@resvg/resvg-js-darwin-x64"], + "linux-arm64": ["@opentui/core-linux-arm64", "@opentui/core-linux-arm64-musl", "@resvg/resvg-js-linux-arm64-gnu", "@resvg/resvg-js-linux-arm64-musl"], + "linux-x64": ["@opentui/core-linux-x64", "@opentui/core-linux-x64-musl", "@resvg/resvg-js-linux-x64-gnu", "@resvg/resvg-js-linux-x64-musl"], + "win32-x64": ["@opentui/core-win32-x64", "@resvg/resvg-js-win32-x64-msvc"], } const root = join(import.meta.dir, "..") @@ -86,7 +86,18 @@ async function readPackageNotice(path: string): Promise { .filter((entry) => entry.isFile() && /^(licen[cs]e|copying|notice)([._-].*)?$/i.test(entry.name)) .map((entry) => entry.name) .sort() - if (!licenseNames.length) throw new Error(`${manifest.name ?? basename(path)} has no license file`) + if (!licenseNames.length) { + // These exact npm releases put their MIT declaration in the README only. + const readme = new Map([ + ["fontkit@2.0.4", "README.md"], ["dfa@1.2.0", "README.md"], ["brotli@1.3.3", "readme.md"], + ]).get(`${manifest.name}@${manifest.version}`) + if (readme && manifest.license === "MIT") licenseNames.push(readme) + else if (typeof manifest.name === "string" && manifest.name.startsWith("@resvg/resvg-js-") && manifest.version === "2.6.2") { + const wrapper = JSON.parse(await readFile(join(path, "..", "resvg-js", "package.json"), "utf8")) as PackageManifest + if (wrapper.version !== manifest.version || wrapper.license !== manifest.license) throw new Error("resvg native license version mismatch") + licenseNames.push("../resvg-js/LICENSE") + } else throw new Error(`${manifest.name ?? basename(path)} has no license file`) + } return { name: String(manifest.name ?? basename(path)), version: String(manifest.version ?? "unknown"), @@ -110,6 +121,8 @@ const sections = [ `Target: ${target}`, "Runtime: Bun 1.3.13", "The release archive also contains SOURCE_OFFER.md, RELINKING.md, and the complete TUI application source.", + "fontkit 2.0.4, dfa 1.2.0 and brotli 1.3.3 declare MIT in their included README notices.", + "resvg's unmodified native binding includes its upstream MPL-2.0 text; source is listed in RELINKING.md.", "", "===== nanobot project license =====", "", diff --git a/tui/src/app/app.ts b/tui/src/app/app.ts index 38781bab4..093eacfd2 100644 --- a/tui/src/app/app.ts +++ b/tui/src/app/app.ts @@ -376,7 +376,7 @@ export class NanobotTui { }, { onPrimaryMouseDown: () => { - const restoreComposerFocus = !this.diffViewer.visible + const restoreComposerFocus = !this.diffViewer.visible && !this.transcript.diagrams.viewer.visible if (restoreComposerFocus) this.composer.focus() // Runtime pickers are transient popovers. A primary click anywhere // outside their trigger or body dismisses them; hide() restores the @@ -405,6 +405,16 @@ export class NanobotTui { this.status = layout.status this.meta = layout.meta this.renderer.root.add(this.shell) + this.renderer.root.add(this.transcript.diagrams.viewer.root) + this.transcript.diagrams.onOpen = () => { + this.composer.blur() + } + this.transcript.diagrams.viewer.onClose = () => { + this.composer.focus() + if (this.activeTurn) this.renderActiveStatus() + else this.status.content = this.readyStatus() + this.updateMeta() + } this.shell.renderBefore = () => { const selection = this.renderer.getSelection() if (selection) applySelectionColors(selection, this.palette.selection) @@ -562,6 +572,7 @@ export class NanobotTui { else if (command.command.action === "context") void this.openContext() else if (command.command.action === "usage") this.openUsage() else if (command.command.action === "diff") this.openDiff() + else if (command.command.action === "diagrams") { this.clearComposer(); this.transcript.diagrams.open() } else if (command.command.action === "branch") void this.openBranch() else if (command.command.action === "detach") this.quit(true) else if (command.command.action === "exit") this.quit() @@ -1313,6 +1324,17 @@ export class NanobotTui { return } } + if (this.transcript.diagrams.viewer.visible) { + this.transcript.diagrams.viewer.handleKey(key) + key.preventDefault() + return + } + if (key.ctrl && key.name === "g") { + this.commandMenu.hide() + this.transcript.diagrams.open() + key.preventDefault() + return + } if (this.diffViewer.visible) { if (key.ctrl && key.name === "c") { const selected = this.renderer.getSelection()?.getSelectedText() diff --git a/tui/src/app/commands.ts b/tui/src/app/commands.ts index e2f7961b9..90e88ded3 100644 --- a/tui/src/app/commands.ts +++ b/tui/src/app/commands.ts @@ -25,6 +25,12 @@ export const LOCAL_COMMANDS: TuiCommand[] = [ description: "Show context occupancy and recent model-call input tokens", action: "usage", }, + { + command: "/diagrams", + title: "Mermaid diagrams", + description: "View, zoom and copy diagrams in this conversation (Ctrl+G)", + action: "diagrams", + }, { command: "/diff", title: "Last turn diff", diff --git a/tui/src/app/diagrams.test.ts b/tui/src/app/diagrams.test.ts new file mode 100644 index 000000000..a79e8b7d5 --- /dev/null +++ b/tui/src/app/diagrams.test.ts @@ -0,0 +1,292 @@ +import { afterEach, expect, spyOn, test } from "bun:test" +import { existsSync } from "node:fs" +import { ImageRenderable, TextareaRenderable, TextRenderable, type Renderable } from "@opentui/core" +import { createTestRenderer, type TestRendererSetup } from "@opentui/core/testing" +import type { Transcript } from "../rendering/transcript" +import { mount, waitUntil } from "./test-support" + +let setup: TestRendererSetup | undefined + +afterEach(() => { if (setup && !setup.renderer.isDestroyed) setup.renderer.destroy(); setup = undefined }) + +function images(root: Renderable): ImageRenderable[] { + return root.getChildren().flatMap(child => [ ...(child instanceof ImageRenderable ? [child] : []), ...images(child) ]) +} + +const source = "graph TD\n A[中文长标签 English] --> B[完成]" +const content = `\`\`\`mermaid\n${source}\n\`\`\`\n\nTrailing paragraph` + +test("streamed stable Mermaid fences stay source until reply completion, including the viewer", async () => { + setup = await createTestRenderer({ width: 80, height: 35 }) + const app = mount(setup) + const transcript = (app as unknown as { transcript: Transcript }).transcript + app.accept({ event: "delta", chat_id: "chat", text: content }) + await setup.flush() + expect(setup.captureCharFrame()).toContain("source while replying") + setup.mockInput.pressKey("\x07") + await setup.flush() + expect(setup.captureCharFrame()).toContain("Replying · original source") + expect(images(transcript.diagrams.viewer.root)).toHaveLength(0) + setup.mockInput.pressKey("q") + app.accept({ event: "stream_end", chat_id: "chat", text: content }) + await setup.flush() + expect(setup.captureCharFrame()).toContain("no image protocol") + expect(setup.captureCharFrame()).toContain("A[中文长标签 English]") + expect(images(transcript.root)).toHaveLength(0) +}) + +test.skipIf(!existsSync("C:/Windows/Fonts/msyh.ttc"))("viewer preserves preview footprint, transcript position and draft; session reset releases images", async () => { + setup = await createTestRenderer({ width: 100, height: 42 }) + Object.defineProperty(setup.renderer, "capabilities", { value: { kitty_graphics: true, multiplexer: "none", image_protocol: "auto" } }) + const app = mount(setup) + const transcript = (app as unknown as { transcript: Transcript }).transcript + app.accept({ event: "delta", chat_id: "chat", text: content }) + app.accept({ event: "stream_end", chat_id: "chat", text: content }) + await setup.flush() + await waitUntil(() => images(transcript.root).some(image => image.image !== null), 5000) + await setup.flush() + const preview = images(transcript.root)[0]! + const render = spyOn(transcript.diagrams.jobs, "render") + const raster = spyOn(transcript.diagrams.jobs, "raster") + const height = transcript.root.scrollHeight + const top = transcript.root.scrollTop + const composer = setup.renderer.root.findDescendantById("nanobot-tui-composer") as TextareaRenderable + composer.setText("keep draft 中文") + setup.mockInput.pressKey("\x07") + await setup.flush() + await setup.flush() + expect(transcript.root.scrollHeight).toBe(height) + expect(images(transcript.root)[0]).toBe(preview) + expect(preview.visible).toBe(false) + await waitUntil(() => images(transcript.diagrams.viewer.root).some(image => image.image !== null), 5000) + await setup.flush() + const dialogImage = images(transcript.diagrams.viewer.root)[0] + const rasters = raster.mock.calls.length + expect(raster).not.toHaveBeenCalled() + setup.renderer.copyToClipboardOSC52 = () => true + setup.mockInput.pressKey("c") + await setup.flush() + expect(setup.captureCharFrame()).toContain("Source copied") + setup.mockInput.pressKey("q") + await setup.flush() + expect(images(transcript.root)[0]).toBe(preview) + expect(preview.visible).toBe(true) + setup.mockInput.pressKey("\x07") + await setup.flush() + expect(images(transcript.diagrams.viewer.root)[0]).toBe(dialogImage) + expect(setup.captureCharFrame()).toContain("100% fit") + expect(render).not.toHaveBeenCalled() + expect(raster.mock.calls.length).toBe(rasters) + setup.mockInput.pressKey("q") + await setup.flush() + render.mockRestore() + raster.mockRestore() + expect(composer.plainText).toBe("keep draft 中文") + expect(transcript.root.scrollTop).toBe(top) + expect(transcript.root.scrollHeight).toBe(height) + transcript.reset({ workspace: "next session", version: "test" }) + await setup.flush() + expect(images(transcript.root)).toHaveLength(0) + expect(transcript.diagrams.viewer.visible).toBe(false) +}, 15_000) + +test("diagram source copy uses the original fence text and cancelled viewer work stays source", async () => { + setup = await createTestRenderer({ width: 90, height: 30 }) + const app = mount(setup) + let copied = "" + setup.renderer.copyToClipboardOSC52 = text => { copied = text; return true } + app.accept({ event: "delta", chat_id: "chat", text: content }) + app.accept({ event: "stream_end", chat_id: "chat", text: content }) + await setup.flush() + setup.mockInput.pressKey("\x07") + await setup.flush() + setup.mockInput.pressKey("c") + await setup.flush() + expect(copied).toBe(source) + setup.mockInput.pressKey("x") + await setup.flush() + expect(setup.captureCharFrame()).toContain("Rendering cancelled") + expect(setup.captureCharFrame()).toContain("A[中文长标签 English]") +}) + +test("diagram command on ordinary Markdown shows an empty viewer and returns to the draft", async () => { + setup = await createTestRenderer({ width: 80, height: 35 }) + const app = mount(setup) + app.accept({ event: "stream_end", chat_id: "chat", text: "Ordinary **Markdown**" }) + const composer = setup.renderer.root.findDescendantById("nanobot-tui-composer") as TextareaRenderable + composer.setText("draft") + setup.mockInput.pressKey("\x07") + await setup.flush() + const header = setup.renderer.root.findDescendantById("diagrams-header") as TextRenderable + expect(header.content.chunks.map(chunk => chunk.text).join("")).toBe("Mermaid") + expect(setup.captureCharFrame()).toContain("No Mermaid diagrams in this conversation.") + expect(setup.captureCharFrame()).toContain("q/esc back") + setup.mockInput.pressKey("q") + await setup.flush() + expect(setup.captureCharFrame()).toContain("draft") +}) + +test.skipIf(!existsSync("C:/Windows/Fonts/msyh.ttc"))("inline image uses real terminal pixels without upscaling small diagrams", async () => { + setup = await createTestRenderer({ width: 100, height: 42 }) + Object.defineProperty(setup.renderer, "capabilities", { value: { kitty_graphics: true, multiplexer: "none", image_protocol: "auto" } }) + Object.defineProperty(setup.renderer, "resolution", { value: { width: 1300, height: 1008 } }) + const app = mount(setup) + const transcript = (app as unknown as { transcript: Transcript }).transcript + app.accept({ event: "stream_end", chat_id: "chat", text: content }) + await setup.flush() + await waitUntil(() => images(transcript.root).some(image => image.image !== null), 5000) + await setup.flush() + const image = images(transcript.root)[0]! + expect(image.width).toBeLessThan(80) + expect(image.image!.width).toBe(image.width * 13) + expect(image.image!.height).toBe(image.height * 24) + expect(image.height).toBeLessThanOrEqual(24) +}, 10_000) + + +test.skipIf(!existsSync("C:/Windows/Fonts/msyh.ttc"))("source-only and cancelled viewer release the shared worker; image demand resumes explicitly", async () => { + setup = await createTestRenderer({ width: 100, height: 42 }) + Object.defineProperty(setup.renderer, "capabilities", { value: { kitty_graphics: true, multiplexer: "none", image_protocol: "auto" } }) + const app = mount(setup) + const transcript = (app as unknown as { transcript: Transcript }).transcript + const spawn = spyOn(Bun, "spawn") + try { + app.accept({ event: "stream_end", chat_id: "chat", text: content }) + await setup.flush() + await waitUntil(() => images(transcript.root).some(image => image.image !== null), 5000) + const first = spawn.mock.results[0]!.value as Bun.Subprocess + setup.mockInput.pressKey("\x07") + await setup.flush() + await waitUntil(() => images(transcript.diagrams.viewer.root).some(image => image.image !== null), 5000) + expect(spawn).toHaveBeenCalledTimes(1) + expect(first.killed).toBe(false) + setup.mockInput.pressKey("s") + await setup.flush() + await first.exited + expect(first.killed).toBe(true) + setup.mockInput.pressKey("+") + await setup.flush() + expect(spawn).toHaveBeenCalledTimes(1) + setup.mockInput.pressKey("s") + await setup.flush() + setup.mockInput.pressKey("+") + await setup.flush() + await waitUntil(() => spawn.mock.calls.length === 2 && transcript.diagrams.jobs.idle, 5000) + const second = spawn.mock.results[1]!.value as Bun.Subprocess + expect(second.killed).toBe(false) + setup.mockInput.pressKey("x") + await setup.flush() + await second.exited + expect(second.killed).toBe(true) + expect(setup.captureCharFrame()).toContain("Rendering cancelled") + expect(setup.captureCharFrame()).toContain("A[中文长标签 English]") + setup.mockInput.pressKey("s") + await setup.flush() + await waitUntil(() => images(transcript.diagrams.viewer.root).some(image => image.image !== null), 5000) + await setup.flush() + expect(setup.captureCharFrame()).toContain("150% fit") + expect(spawn).toHaveBeenCalledTimes(3) + transcript.reset({ workspace: "next session", version: "test" }) + expect(transcript.diagrams.layouts.retainedBytes).toBe(0) + } finally { transcript.diagrams.jobs.dispose(); spawn.mockRestore() } +}, 20_000) + + +test.skipIf(!existsSync("C:/Windows/Fonts/msyh.ttc"))("offscreen return and cell-height changes reuse SVG; theme and session changes invalidate it", async () => { + setup = await createTestRenderer({ width: 100, height: 42 }) + Object.defineProperty(setup.renderer, "capabilities", { value: { kitty_graphics: true, multiplexer: "none", image_protocol: "auto" } }) + const resolution = { width: 1000, height: 840 } + Object.defineProperty(setup.renderer, "resolution", { value: resolution }) + const app = mount(setup) + const transcript = (app as unknown as { transcript: Transcript }).transcript + app.accept({ event: "stream_end", chat_id: "chat", text: content }) + await setup.flush() + await waitUntil(() => images(transcript.root).some(image => image.image !== null), 5000) + await setup.flush() + const render = spyOn(transcript.diagrams.jobs, "render") + const raster = spyOn(transcript.diagrams.jobs, "raster") + try { + const bytes = transcript.diagrams.layouts.retainedBytes + app.accept({ event: "stream_end", chat_id: "chat", text: Array.from({ length: 60 }, (_, i) => `Paragraph ${i}\n`).join("\n") }) + await setup.flush() + expect(images(transcript.root)).toHaveLength(0) + expect(transcript.diagrams.layouts.retainedBytes).toBe(bytes) + transcript.root.scrollTo(0) + await setup.flush() + await waitUntil(() => images(transcript.root).some(image => image.image !== null), 5000) + await setup.flush() + expect(render).not.toHaveBeenCalled() + expect(raster).toHaveBeenCalledTimes(1) + resolution.height = 1008 + setup.renderer.requestRender() + await setup.flush() + await waitUntil(() => images(transcript.root).some(image => image.image !== null), 5000) + expect(render).not.toHaveBeenCalled() + expect(raster).toHaveBeenCalledTimes(2) + expect(transcript.diagrams.layouts.retainedBytes).toBe(bytes) + transcript.diagrams.setTheme({ ...transcript.diagrams.colors(), accent: "#dd8800" }) + expect(transcript.diagrams.layouts.retainedBytes).toBe(0) + await setup.flush() + await waitUntil(() => images(transcript.root).some(image => image.image !== null), 5000) + expect(render).toHaveBeenCalledTimes(1) + transcript.reset({ workspace: "next session", version: "test" }) + expect(transcript.diagrams.layouts.retainedBytes).toBe(0) + } finally { render.mockRestore(); raster.mockRestore() } +}, 20_000) + + +test.skipIf(!existsSync("C:/Windows/Fonts/msyh.ttc"))("viewer navigation releases old layout pins under the real transcript budget", async () => { + setup = await createTestRenderer({ width: 100, height: 42 }) + Object.defineProperty(setup.renderer, "capabilities", { value: { kitty_graphics: true, multiplexer: "none", image_protocol: "auto" } }) + Object.defineProperty(setup.renderer, "resolution", { value: { width: 1000, height: 840 } }) + const app = mount(setup) + const transcript = (app as unknown as { transcript: Transcript }).transcript + for (let index = 0; index < 8; index++) { + const source = `flowchart TD\n${Array.from({ length: 40 }, (_, i) => `A${i}["数据库请求处理权限验证任务执行记录完成 ${index}-${i}"]`).join("\n")}\n${Array.from({ length: 39 }, (_, i) => `A${i} --> A${i + 1}`).join("\n")}` + app.accept({ event: "stream_end", chat_id: "chat", text: `Graph ${index + 1}\n\n\`\`\`mermaid\n${source}\n\`\`\`\n\nEnd of graph ${index + 1}` }) + } + await setup.flush() + await waitUntil(() => images(transcript.root).some(image => image.image !== null), 5000) + const preview = images(transcript.root)[0]! + setup.mockInput.pressKey("\x07") + await setup.flush() + const note = setup.renderer.root.findDescendantById("diagrams-note") as TextRenderable + const ready = () => images(transcript.diagrams.viewer.root).some(image => image.image !== null) + || note.content.chunks.some(chunk => chunk.text.includes("original source")) + await waitUntil(ready, 5000) + expect(images(transcript.diagrams.viewer.root)).toHaveLength(1) + for (const direction of ["[", "]"]) { + for (let index = 0; index < 7; index++) { + setup.mockInput.pressKey(direction) + await setup.flush() + await waitUntil(ready, 5000) + expect(images(transcript.diagrams.viewer.root)).toHaveLength(1) + expect(transcript.diagrams.layouts.retainedBytes).toBeLessThanOrEqual(4_000_000) + } + } + expect(preview.visible).toBe(false) + setup.mockInput.pressKey("q") + await setup.flush() + expect(images(transcript.root)[0]).toBe(preview) + expect(preview.visible).toBe(true) +}, 25_000) + + +test.skipIf(!existsSync("C:/Windows/Fonts/msyh.ttc"))("source/image retry after a parser failure keeps the original source visible", async () => { + setup = await createTestRenderer({ width: 100, height: 42 }) + Object.defineProperty(setup.renderer, "capabilities", { value: { kitty_graphics: true, multiplexer: "none", image_protocol: "auto" } }) + const app = mount(setup) + const transcript = (app as unknown as { transcript: Transcript }).transcript + app.accept({ event: "stream_end", chat_id: "chat", text: "```mermaid\ngraph TD\n A -->\n```" }) + await setup.flush() + setup.mockInput.pressKey("\x07") + await setup.flush() + const sourceScroll = setup.renderer.root.findDescendantById("diagrams-source-scroll")! + await waitUntil(() => sourceScroll.visible && transcript.diagrams.jobs.idle, 5000) + setup.mockInput.pressKey("s") + await setup.flush() + await waitUntil(() => sourceScroll.visible && transcript.diagrams.jobs.idle, 5000) + await setup.flush() + expect(setup.captureCharFrame()).toContain("original source") + expect(setup.captureCharFrame()).toContain("A -->") +}, 15_000) diff --git a/tui/src/app/host-lifecycle.test.ts b/tui/src/app/host-lifecycle.test.ts index 7eefb1c34..f7dc2283e 100644 --- a/tui/src/app/host-lifecycle.test.ts +++ b/tui/src/app/host-lifecycle.test.ts @@ -48,9 +48,11 @@ describe("NanobotTui with a Herdr pane title reporter", () => { await setup.mockInput.typeText("/") await setup.flush() const commandFrame = setup.captureCharFrame() - expect(commandFrame).toContain("/sessions") expect(commandFrame).toContain("/new-chat") expect(commandFrame).toContain("/branch") + await setup.mockInput.typeText("sessions") + await setup.flush() + expect(setup.captureCharFrame()).toContain("/sessions") setup.mockInput.pressEscape() ui.composer.setText("") diff --git a/tui/src/app/theme.ts b/tui/src/app/theme.ts index ed0281713..c16e9f7d1 100644 --- a/tui/src/app/theme.ts +++ b/tui/src/app/theme.ts @@ -4,6 +4,7 @@ import { SyntaxStyle, TextAttributes, parseColor, + rgbToHex, type ColorInput, type TextChunk, } from "@opentui/core" @@ -142,6 +143,13 @@ export function transcriptTheme(palette: Palette, backgroundKnown: boolean): Tra userBackground: backgroundKnown ? palette.userBackground : null, border: palette.border, syntax: syntaxStyle(palette), + diagramColors: { + foreground: rgbToHex(parseColor(palette.text)), + muted: rgbToHex(parseColor(palette.muted)), + surface: rgbToHex(parseColor(palette.userBackground)), + border: rgbToHex(parseColor(palette.border)), + accent: rgbToHex(parseColor(palette.accent)), + }, } } diff --git a/tui/src/index.ts b/tui/src/index.ts index 4b6865c67..a17f3c78b 100644 --- a/tui/src/index.ts +++ b/tui/src/index.ts @@ -1,10 +1,19 @@ -import { NanobotTui, sessionExitMessage, type AppOptions } from "./app" +import type { NanobotTui as App, AppOptions } from "./app" import { desktopConnectionSource } from "./platform/desktop" +if (process.argv.slice(2).join(" ") === "--render-mermaid") { + const { runDiagramWorker } = await import("./rendering/mermaid/worker") + await runDiagramWorker() + process.exit(0) +} if (process.argv.slice(2).join(" ") === "--desktop-protocol") { process.stdout.write("1\n") process.exit(0) } +// Initialize OpenTUI before the UI graph: compiled async cycles otherwise expose an +// uninitialized CliRenderer binding. Raster children never enter this graph. +await import("@opentui/core") +const { NanobotTui, sessionExitMessage } = await import("./app") const desktop = desktopConnectionSource() // Keep in sync with _TUI_DETACH_EXIT_CODE in nanobot/cli/tui_launcher.py. @@ -53,7 +62,7 @@ const options: AppOptions = { }, } -let app: NanobotTui | undefined +let app: App | undefined let shuttingDown = false const shutdown = (code = 0) => { diff --git a/tui/src/menus/command-menu.ts b/tui/src/menus/command-menu.ts index a60f071dd..c92c1fc4d 100644 --- a/tui/src/menus/command-menu.ts +++ b/tui/src/menus/command-menu.ts @@ -11,6 +11,7 @@ type TuiCommandAction = | "context" | "usage" | "diff" + | "diagrams" | "branch" | "detach" | "exit" diff --git a/tui/src/rendering/mermaid/block.ts b/tui/src/rendering/mermaid/block.ts new file mode 100644 index 000000000..101b6c1bb --- /dev/null +++ b/tui/src/rendering/mermaid/block.ts @@ -0,0 +1,238 @@ +import { + BoxRenderable, CodeRenderable, ImageRenderable, NativeImage, TextRenderable, + resolveImageRenderProtocol, type CliRenderer, +} from "@opentui/core" +import type { DiagramJobs } from "./jobs" +import { diagramLayoutKey, type DiagramLayoutLease, type DiagramLayouts } from "./cache" +import { diagramFrame } from "./geometry" +import type { DiagramFrame, DiagramInput, DiagramLayout } from "./types" + +export interface DiagramOwner { + jobs: DiagramJobs + layouts: DiagramLayouts + colors(): DiagramInput["colors"] + inViewport(block: MermaidBlock): boolean + readonly viewerOpen: boolean + restorePreviews(): void + reserve(pixels: number): boolean + release(pixels: number): void + open(block: MermaidBlock): void + released(block: MermaidBlock): void + removed(block: MermaidBlock): void +} + +export function diagramProtocol(renderer: CliRenderer): "kitty" | "sixel" | null { + const protocol = resolveImageRenderProtocol("auto", renderer.capabilities, renderer.resolution !== null) + return protocol === "blocks" ? null : protocol +} + +export function diagramCellSize(renderer: CliRenderer): { width: number; height: number } { + return renderer.resolution + ? { width: renderer.resolution.width / renderer.width, height: renderer.resolution.height / renderer.height } + : { width: 10, height: 20 } +} + +/** Source remains authoritative; the native image exists only while this block is on screen. */ +export class MermaidBlock extends BoxRenderable { + private readonly label: TextRenderable + private readonly sourceCode: CodeRenderable + private picture: ImageRenderable | null = null + private native: NativeImage | null = null + private request: AbortController | null = null + private releaseWorker: (() => void) | null = null + private pixels = 0 + private layoutLease: DiagramLayoutLease | null = null + private frame: DiagramFrame | null = null + private failure = "" + private renderedGeometry = "" + private previewHeight = 0 + private wanted = false + + constructor( + private readonly renderer: CliRenderer, + private readonly owner: DiagramOwner, + readonly source: string, + code: CodeRenderable, + private readonly state: { settled: boolean }, + id: string, + ) { + super(renderer, { id, width: "100%", minWidth: 0, flexDirection: "column", flexShrink: 0 }) + this.sourceCode = code + this.label = new TextRenderable(renderer, { + id: `${id}-label`, content: "Mermaid · source while replying", fg: owner.colors().muted, + width: "100%", minHeight: 1, flexShrink: 0, + onMouseDown: () => owner.open(this), + }) + this.add(this.label) + this.add(code) + this.onLifecyclePass = () => this.sync() + } + + get settled(): boolean { return this.state.settled } + get renderedLayout(): DiagramLayout | null { return this.layoutLease?.layout ?? null } + + borrowImage(frame: DiagramFrame): NativeImage | null { + return this.native && this.frame && Object.entries(this.frame).every(([key, value]) => frame[key as keyof DiagramFrame] === value) + ? this.native.retain() : null + } + + borrowLayout(): DiagramLayoutLease | null { + return this.layoutLease ? this.owner.layouts.acquire(this.layoutLease.key) : null + } + + private layoutFor(width: number): DiagramLayout | null { + const key = diagramLayoutKey({ source: this.source, width, colors: this.owner.colors() }) + if (this.layoutLease?.key !== key) { + this.layoutLease?.release() + this.layoutLease = this.owner.layouts.acquire(key) + } + return this.renderedLayout + } + + private keepLayout(layout: DiagramLayout, width: number): DiagramLayout { + if (this.renderedLayout === layout) return layout + this.layoutLease?.release() + this.layoutLease = null + this.layoutLease = this.owner.layouts.store(diagramLayoutKey({ source: this.source, width, colors: this.owner.colors() }), layout) + return this.layoutLease.layout + } + + suspend(): void { this.releaseImage() } + + hidePreview(): void { + this.request?.abort() + this.request = null + this.setWorkerDemand(false) + if (!this.picture?.visible) return + this.previewHeight = this.height + this.minHeight = this.previewHeight + this.picture.visible = false + } + + restorePreview(): void { + if (!this.picture) return + this.picture.visible = true + this.minHeight = 0 + this.setWorkerDemand(this.owner.inViewport(this)) + } + + private setWorkerDemand(wanted: boolean): void { + if (wanted) this.releaseWorker ??= this.owner.jobs.retainWorker() + else { this.releaseWorker?.(); this.releaseWorker = null } + } + + invalidate(): void { + this.failure = "" + this.releaseImage() + this.label.fg = this.owner.colors().muted + this.sourceCode.visible = true + this.requestRender() + } + + private sync(): void { + if (!this.state.settled) return + if (this.owner.viewerOpen) { this.hidePreview(); return } + if (this.picture && !this.picture.visible) { + this.picture.visible = true + this.minHeight = 0 + } + const wanted = this.owner.inViewport(this) + const protocol = diagramProtocol(this.renderer) + const cells = diagramCellSize(this.renderer) + const width = Math.max(1, Math.floor(this.width)) * cells.width + const geometry = `${width}:${cells.width}:${cells.height}` + if (this.renderedGeometry && this.renderedGeometry !== geometry) { + this.failure = "" + this.releaseFrame() + } + this.wanted = wanted + if (!protocol) { + this.releaseImage() + this.sourceCode.visible = true + this.label.content = "Mermaid · no image protocol · Ctrl+G source" + return + } + if (!wanted) { this.releaseImage(); return } + if (this.native || this.request || this.failure) return + this.renderedGeometry = geometry + const request = new AbortController() + this.request = request + this.setWorkerDemand(true) + this.label.content = "Mermaid · rendering… · Ctrl+G view / cancel" + const viewport = { width, height: 24 * cells.height, cellWidth: cells.width, cellHeight: cells.height } + const layout = this.layoutFor(width) + const work = layout + ? this.owner.jobs.raster(layout, diagramFrame(layout, viewport), request.signal).then(image => ({ ...image, layout })) + : this.owner.jobs.render({ source: this.source, width, scale: 1, viewport, colors: this.owner.colors() }, request.signal) + void work.then(image => { + if (this.isDestroyed || this.request !== request || !this.wanted) return + this.keepLayout(image.layout, width) + const pixels = image.width * image.height + if (!this.owner.reserve(pixels)) throw new Error("Visible image memory limit") + this.pixels = pixels + try { this.native = NativeImage.decode(image.png) } + catch (error) { this.owner.release(this.pixels); this.pixels = 0; throw error } + this.frame = diagramFrame(image.layout, viewport) + this.picture = new ImageRenderable(this.renderer, { + id: `${this.id}-image`, source: this.native, + width: Math.round(image.width / cells.width), height: Math.round(image.height / cells.height), + alignSelf: "center", fit: "fill", protocol, + onError: () => this.fail("Terminal image load failed"), + }) + this.add(this.picture) + this.sourceCode.visible = false + this.minHeight = 0 + this.label.content = "Mermaid · Ctrl+G view / source / copy" + }) + .catch(error => { + if (this.isDestroyed || this.request !== request || request.signal.aborted) return + this.fail(error instanceof Error ? error.message : "Rendering failed") + }) + .finally(() => { + if (this.request === request) this.request = null + if (!this.isDestroyed) this.requestRender() + }) + } + + private fail(message: string): void { + this.failure = message + this.releaseImage() + this.sourceCode.visible = true + // Only controlled renderer errors, not untrusted Mermaid source, enter the status line. + this.label.content = `Mermaid · ${message.replace(/[\r\n\x00-\x1f]/g, " ").slice(0, 120)} · Ctrl+G source` + } + + private releaseImage(): void { + this.setWorkerDemand(false) + this.releaseFrame() + this.layoutLease?.release() + this.layoutLease = null + } + + private releaseFrame(): void { + this.request?.abort() + this.request = null + if (this.picture) this.previewHeight = Math.max(this.height, this.picture.height + this.label.height) + if (this.picture) { + this.remove(this.picture) + this.picture.destroyRecursively() + this.picture = null + } + this.native?.dispose() + this.native = null + this.frame = null + if (this.pixels) this.owner.release(this.pixels) + this.pixels = 0 + // Keep the known preview footprint while culled; scrolling back does not jump. + if (this.previewHeight && !this.sourceCode.visible) { + this.minHeight = this.previewHeight + } + this.owner.released(this) + } + + protected override destroySelf(): void { + this.releaseImage() + this.owner.removed(this) + super.destroySelf() + } +} diff --git a/tui/src/rendering/mermaid/cache.test.ts b/tui/src/rendering/mermaid/cache.test.ts new file mode 100644 index 000000000..c032a7a8f --- /dev/null +++ b/tui/src/rendering/mermaid/cache.test.ts @@ -0,0 +1,57 @@ +import { expect, test } from "bun:test" +import { DiagramLayouts, diagramLayoutKey } from "./cache" +import type { DiagramInput, DiagramLayout } from "./types" + +const input: DiagramInput = { + source: "graph TD\n A[中文] --> B", width: 800, scale: 1, + colors: { foreground: "#111", muted: "#666", surface: "#eee", border: "#888", accent: "#36c" }, +} +const layout = (text: string): DiagramLayout => ({ svg: `${text}`, width: 100, height: 50 }) + +test("layout identity includes source, physical width, fonts and palette, not raster geometry", () => { + const key = diagramLayoutKey(input) + const zoomed: DiagramInput = { ...input, scale: 4, viewport: { height: 720, cellWidth: 9, cellHeight: 24 } } + expect(diagramLayoutKey(zoomed)).toBe(key) + expect(diagramLayoutKey({ ...input, source: "graph TD\n B --> C" })).not.toBe(key) + expect(diagramLayoutKey({ ...input, width: 799 })).not.toBe(key) + expect(diagramLayoutKey({ ...input, colors: { ...input.colors, foreground: "#eee" } })).not.toBe(key) + const font = { path: "font.ttf", postscriptName: "Font" } + const withFonts = { ...input, fonts: { regular: font, bold: font, mono: font } } + expect(diagramLayoutKey(withFonts)).not.toBe(key) + expect(diagramLayoutKey({ ...withFonts, fonts: { ...withFonts.fonts, bold: { ...font, postscriptName: "Bold" } } })).not.toBe(diagramLayoutKey(withFonts)) +}) + +test("offscreen layouts reuse one bounded LRU while visible pins cannot be evicted", () => { + const first = layout("first"), second = layout("second"), third = layout("third") + const cache = new DiagramLayouts(Buffer.byteLength(first.svg) + Buffer.byteLength(second.svg)) + const a = cache.store("a", first), b = cache.store("b", second) + expect(() => cache.store("c", third)).toThrow("Visible diagram layout limit") + a.release() + b.release() + const returned = cache.acquire("a")! + expect(returned.layout).toBe(first) + returned.release() + const c = cache.store("c", third) + expect(cache.acquire("b")).toBeNull() + const pinned = cache.acquire("a")! + expect(pinned.layout).toBe(first) + expect(cache.retainedBytes).toBe(Buffer.byteLength(first.svg) + Buffer.byteLength(third.svg)) + pinned.release() + pinned.release() + c.release() +}) + +test("reset removes old layouts and releases cannot resurrect the previous cache", () => { + const cache = new DiagramLayouts() + const old = cache.store("diagram", layout("old")) + old.release() + cache.clear() + const current = cache.store("diagram", layout("new")) + old.release() + expect(cache.acquire("diagram")!.layout).toBe(current.layout) + expect(cache.retainedBytes).toBe(Buffer.byteLength(current.layout.svg)) + current.release() + cache.clear() + expect(cache.retainedBytes).toBe(0) + expect(cache.acquire("diagram")).toBeNull() +}) diff --git a/tui/src/rendering/mermaid/cache.ts b/tui/src/rendering/mermaid/cache.ts new file mode 100644 index 000000000..e60c9d071 --- /dev/null +++ b/tui/src/rendering/mermaid/cache.ts @@ -0,0 +1,66 @@ +import { createHash } from "node:crypto" +import { DIAGRAM_FONT_SIZE, type DiagramInput, type DiagramLayout } from "./types" + +export function diagramLayoutKey(input: Pick): string { + const { source, width, fonts, colors } = input + return createHash("sha256").update(JSON.stringify([ + source, width, DIAGRAM_FONT_SIZE, + fonts ? [fonts.regular.path, fonts.regular.postscriptName, fonts.bold.path, fonts.bold.postscriptName, fonts.mono.path, fonts.mono.postscriptName] : null, + colors.foreground, colors.muted, colors.surface, colors.border, colors.accent, + ])).digest("hex") +} + +export interface DiagramLayoutLease { + key: string + layout: DiagramLayout + release(): void +} + +type Entry = { layout: DiagramLayout; bytes: number; users: number } + +/** Visible pins and offscreen LRU entries share one transcript's vector budget. */ +export class DiagramLayouts { + private readonly entries = new Map() + private bytes = 0 + + constructor(private readonly limit = 4_000_000) {} + + get retainedBytes(): number { return this.bytes } + + acquire(key: string): DiagramLayoutLease | null { + const entry = this.entries.get(key) + return entry ? this.pin(key, entry) : null + } + + store(key: string, layout: DiagramLayout): DiagramLayoutLease { + const existing = this.acquire(key) + if (existing) return existing + const bytes = Buffer.byteLength(layout.svg) + if (bytes > this.limit) throw new Error("Visible diagram layout limit") + for (const [oldKey, entry] of this.entries) { + if (this.bytes + bytes <= this.limit) break + if (entry.users) continue + this.entries.delete(oldKey) + this.bytes -= entry.bytes + } + if (this.bytes + bytes > this.limit) throw new Error("Visible diagram layout limit") + const entry = { layout, bytes, users: 0 } + this.entries.set(key, entry) + this.bytes += bytes + return this.pin(key, entry) + } + + clear(): void { this.entries.clear(); this.bytes = 0 } + + private pin(key: string, entry: Entry): DiagramLayoutLease { + this.entries.delete(key) + this.entries.set(key, entry) + entry.users++ + let released = false + return { key, layout: entry.layout, release: () => { + if (released) return + released = true + entry.users-- + } } + } +} diff --git a/tui/src/rendering/mermaid/controller.ts b/tui/src/rendering/mermaid/controller.ts new file mode 100644 index 000000000..113075617 --- /dev/null +++ b/tui/src/rendering/mermaid/controller.ts @@ -0,0 +1,87 @@ +import { CodeRenderable, type CliRenderer, type ScrollBoxRenderable } from "@opentui/core" +import { MermaidBlock, type DiagramOwner } from "./block" +import { DiagramJobs } from "./jobs" +import { DiagramLayouts } from "./cache" +import type { DiagramInput } from "./types" +import { DiagramViewer } from "./viewer" + +const RETAINED_PIXEL_LIMIT = 16_000_000 + +/** One transcript owns all render jobs and native images, including its overlay. */ +export class TranscriptDiagrams implements DiagramOwner { + readonly jobs = new DiagramJobs() + readonly layouts = new DiagramLayouts() + readonly viewer: DiagramViewer + onOpen?: () => void + private readonly blocks = new Set() + private retainedPixels = 0 + + constructor( + private readonly renderer: CliRenderer, + private readonly viewport: ScrollBoxRenderable, + private palette: DiagramInput["colors"], + ) { + this.viewer = new DiagramViewer(renderer, this) + } + + colors(): DiagramInput["colors"] { return this.palette } + + create(source: string, code: CodeRenderable, state: { settled: boolean }, id: string): MermaidBlock { + const block = new MermaidBlock(this.renderer, this, source, code, state, id) + this.blocks.add(block) + return block + } + + inViewport(block: MermaidBlock): boolean { + const view = this.viewport.viewport + return !this.viewer.visible && block.width > 0 && view.height > 0 + && block.screenY < view.screenY + view.height && block.screenY + block.height > view.screenY + } + + get viewerOpen(): boolean { return this.viewer.visible } + + reserve(pixels: number): boolean { + if (pixels + this.retainedPixels > RETAINED_PIXEL_LIMIT) return false + this.retainedPixels += pixels + return true + } + + release(pixels: number): void { this.retainedPixels -= pixels } + released(block: MermaidBlock): void { this.viewer.evict(block) } + removed(block: MermaidBlock): void { this.blocks.delete(block) } + + open(block?: MermaidBlock): void { + const blocks = [...this.blocks].filter(item => !item.isDestroyed).sort((a, b) => a.screenY - b.screenY) + const selected = block ? blocks.indexOf(block) : blocks.indexOf(blocks.filter(item => this.inViewport(item)).at(-1)!) + const index = selected >= 0 ? selected : Math.max(0, blocks.length - 1) + // Transfer worker ownership before culling previews; the dialog shares the selected image. + this.viewer.show(blocks, index) + for (const item of blocks) { + if (item === blocks[index]) item.hidePreview() + else item.suspend() + } + this.onOpen?.() + } + + restorePreviews(): void { for (const block of this.blocks) block.restorePreview() } + + setTheme(colors: DiagramInput["colors"]): void { + this.palette = colors + for (const block of this.blocks) block.invalidate() + this.layouts.clear() + this.viewer.setTheme() + } + + reset(): void { + this.viewer.clear() + for (const block of this.blocks) block.suspend() + this.layouts.clear() + this.jobs.reset() + } + + destroy(): void { + this.reset() + this.jobs.dispose() + if (!this.viewer.root.isDestroyed) this.viewer.root.destroyRecursively() + } +} diff --git a/tui/src/rendering/mermaid/frame.ts b/tui/src/rendering/mermaid/frame.ts new file mode 100644 index 000000000..20f954098 --- /dev/null +++ b/tui/src/rendering/mermaid/frame.ts @@ -0,0 +1,12 @@ +import { DOMParser, XMLSerializer } from "@xmldom/xmldom" +import type { DiagramFrame } from "./types" + +/** Transform only the already validated image document; frame jobs need no CSS resolver. */ +export function frameDiagramSvg(svg: string, frame: DiagramFrame): string { + const document = new DOMParser().parseFromString(svg, "image/svg+xml") + const root = document.documentElement + root.setAttribute("width", String(frame.width)) + root.setAttribute("height", String(frame.height)) + root.setAttribute("viewBox", `${frame.x} ${frame.y} ${frame.viewWidth} ${frame.viewHeight}`) + return new XMLSerializer().serializeToString(document) +} diff --git a/tui/src/rendering/mermaid/geometry.ts b/tui/src/rendering/mermaid/geometry.ts new file mode 100644 index 000000000..5faf41f95 --- /dev/null +++ b/tui/src/rendering/mermaid/geometry.ts @@ -0,0 +1,26 @@ +import { MAX_DIMENSION, MAX_PIXELS, OUTPUT_LIMIT, type DiagramFrame, type DiagramLayout } from "./types" + +export function validateDiagramFrame(layout: DiagramLayout, frame: DiagramFrame): void { + if (![frame.width, frame.height].every(value => Number.isSafeInteger(value) && value > 0 && value <= MAX_DIMENSION) + || frame.width * frame.height > MAX_PIXELS || ![frame.x, frame.y, frame.viewWidth, frame.viewHeight].every(Number.isFinite) + || frame.viewWidth <= 0 || frame.viewHeight <= 0 || Buffer.byteLength(layout.svg) > OUTPUT_LIMIT) throw new Error("Diagram pixel limit") +} + +/** Rasterize the final cell footprint; padding never stretches the diagram itself. */ +export function diagramFrame( + natural: { width: number; height: number }, + viewport: { width: number; height: number; cellWidth: number; cellHeight: number }, + zoom = 1, panX = 0, panY = 0, +): DiagramFrame { + const { width, height, cellWidth, cellHeight } = viewport + if (![width, height, cellWidth, cellHeight, zoom].every(value => Number.isFinite(value) && value > 0)) throw new Error("Diagram viewport limit") + const scale = Math.min(1, width / natural.width, height / natural.height) * zoom + const pixelsWide = Math.round(Math.min(Math.round(width / cellWidth), Math.ceil(natural.width * scale / cellWidth)) * cellWidth) + const pixelsHigh = Math.round(Math.min(Math.round(height / cellHeight), Math.ceil(natural.height * scale / cellHeight)) * cellHeight) + const viewWidth = pixelsWide / scale, viewHeight = pixelsHigh / scale + return { + width: pixelsWide, height: pixelsHigh, viewWidth, viewHeight, + x: viewWidth >= natural.width ? -(viewWidth - natural.width) / 2 : (natural.width - viewWidth) * panX, + y: viewHeight >= natural.height ? -(viewHeight - natural.height) / 2 : (natural.height - viewHeight) * panY, + } +} diff --git a/tui/src/rendering/mermaid/jobs.ts b/tui/src/rendering/mermaid/jobs.ts new file mode 100644 index 000000000..b8164c715 --- /dev/null +++ b/tui/src/rendering/mermaid/jobs.ts @@ -0,0 +1,182 @@ +import { fileURLToPath } from "node:url" +import { jsonLines, REPLY_LIMIT, REQUEST_LIMIT } from "./protocol" +import { MAX_DIMENSION, MAX_PIXELS, OUTPUT_LIMIT, SOURCE_LIMIT, type DiagramAsset, type DiagramFrame, type DiagramImage, type DiagramInput, type DiagramLayout, type DiagramWork } from "./types" + +declare const NANOBOT_COMPILED: boolean + +function launch() { + const args = typeof NANOBOT_COMPILED !== "undefined" && NANOBOT_COMPILED + ? [process.execPath, "--render-mermaid"] + : [process.execPath, fileURLToPath(new URL("../../index.ts", import.meta.url)), "--render-mermaid"] + return Bun.spawn(args, { stdin: "pipe", stdout: "pipe", stderr: "pipe", windowsHide: true }) +} + +type RasterProcess = ReturnType +interface Job { + work: DiagramWork + signal: AbortSignal + resolve: (image: DiagramImage | DiagramAsset) => void + reject: (error: Error) => void + cancel: () => void +} + +async function readBounded(stream: ReadableStream, limit: number): Promise { + const reader = stream.getReader() + const chunks: Uint8Array[] = [] + let size = 0 + try { + while (true) { + const { done, value } = await reader.read() + if (done) break + size += value.length + if (size > limit) throw new Error("Diagram worker output limit") + chunks.push(value) + } + return Buffer.concat(chunks).toString("utf8") + } finally { reader.releaseLock() } +} + +/** One terminable child, retained only by visible diagrams or their viewer. */ +export class DiagramJobs { + private queue: Job[] = [] + private active: { job: Job; timer: ReturnType } | null = null + private process: { child: RasterProcess; closing: boolean; error?: Error } | null = null + private retainers = new Set() + private disposed = false + + get idle(): boolean { return !this.active && !this.queue.length } + + render(input: DiagramInput, signal: AbortSignal): Promise { + if (Buffer.byteLength(input.source) > SOURCE_LIMIT) return Promise.reject(new Error("Diagram source limit")) + return this.enqueue({ kind: "render", input }, signal) + } + + raster(layout: DiagramLayout, frame: DiagramFrame, signal: AbortSignal): Promise { + return this.enqueue({ kind: "raster", layout, frame }, signal) + } + + reset(): void { + for (const job of [...this.queue]) job.cancel() + this.stop(new Error("Diagram cancelled")) + } + + dispose(): void { this.disposed = true; this.reset() } + + retainWorker(): () => void { + const owner = {} + this.retainers.add(owner) + return () => { this.retainers.delete(owner); this.start() } + } + + private enqueue(work: DiagramWork, signal: AbortSignal): Promise { + if (this.disposed || signal.aborted) return Promise.reject(new Error("Diagram cancelled")) + if (this.queue.length >= 8) return Promise.reject(new Error("Diagram render queue full")) + return new Promise((resolve, reject) => { + const job: Job = { work, signal, resolve: image => resolve(image as T), reject, cancel: () => { + if (this.active?.job === job) this.stop(new Error("Diagram cancelled")) + else { + this.queue = this.queue.filter(queued => queued !== job) + signal.removeEventListener("abort", job.cancel) + reject(new Error("Diagram cancelled")) + } + } } + signal.addEventListener("abort", job.cancel, { once: true }) + this.queue.push(job) + this.start() + }) + } + + private start(): void { + if (this.disposed || this.active || this.process?.error || this.process?.closing) return + const job = this.queue[0] + if (!job) { + if (this.process && !this.retainers.size) this.finishProcess() + return + } + this.queue.shift() + try { + const input = JSON.stringify(job.work) + if (Buffer.byteLength(input) > REQUEST_LIMIT) throw new Error("Diagram input limit") + if (!this.process) { + const process = { child: launch(), closing: false, error: undefined as Error | undefined } + this.process = process + void this.observe(process) + } + const process = this.process + this.active = { job, timer: setTimeout(() => { + if (this.active?.job === job) this.stop(new Error("Diagram render timed out")) + }, 10_000) } + process.child.stdin.write(input + "\n") + void Promise.resolve(process.child.stdin.flush()).catch(() => { + if (this.process === process) this.stop(new Error("Diagram worker pipe failed")) + }) + } catch (error) { + if (this.active?.job === job) this.stop(error instanceof Error ? error : new Error("Diagram worker unavailable")) + else { + job.signal.removeEventListener("abort", job.cancel) + job.reject(error instanceof Error ? error : new Error("Diagram worker unavailable")) + this.start() + } + } + } + + private async observe(process: NonNullable): Promise { + const { child } = process + const stderr = readBounded(child.stderr, 8192) + const stdout = (async () => { + for await (const record of jsonLines(child.stdout, REPLY_LIMIT)) { + if (process.error) break + const active = this.active + if (!active) throw new Error("Unexpected diagram worker reply") + const reply = record as { error?: string; image?: { png: string; width: number; height: number; layout?: DiagramLayout } } + let failure: Error | undefined, image: DiagramImage | DiagramAsset | undefined + if (typeof reply.error === "string") failure = new Error(reply.error) + else { + const result = reply.image + if (!result || typeof result.png !== "string" || !Number.isSafeInteger(result.width) || !Number.isSafeInteger(result.height)) throw new Error("Invalid diagram worker result") + if (result.width < 1 || result.height < 1 || result.width > MAX_DIMENSION || result.height > MAX_DIMENSION || result.width * result.height > MAX_PIXELS) throw new Error("Diagram pixel limit") + const png = new Uint8Array(Buffer.from(result.png, "base64")) + if (png.byteLength > OUTPUT_LIMIT) throw new Error("Diagram image limit") + if (active.job.work.kind === "render" && (!result.layout || Buffer.byteLength(result.layout.svg) > OUTPUT_LIMIT)) throw new Error("Invalid diagram layout") + image = { ...result, png } + } + clearTimeout(active.timer) + active.job.signal.removeEventListener("abort", active.job.cancel) + this.active = null + if (failure) active.job.reject(failure) + else active.job.resolve(image!) + this.start() + } + })() + try { await Promise.all([stdout, stderr, child.exited]) } + catch (error) { this.stop(error instanceof Error ? error : new Error("Diagram worker failed")) } + finally { + child.stdin.end() + // Replacement admission includes exit plus both pipe collectors, even on failure. + await Promise.allSettled([stdout, stderr, child.exited]) + if (this.process === process) { + if (this.active) { + clearTimeout(this.active.timer) + this.active.job.signal.removeEventListener("abort", this.active.job.cancel) + this.active.job.reject(process.error ?? new Error("Diagram worker exited")) + this.active = null + } + this.process = null + this.start() + } + } + } + + private finishProcess(): void { + const process = this.process! + process.closing = true + process.child.kill() + } + + private stop(error: Error): void { + const process = this.process + if (!process || process.error) return + process.error = error + process.child.kill() + } +} diff --git a/tui/src/rendering/mermaid/protocol.ts b/tui/src/rendering/mermaid/protocol.ts new file mode 100644 index 000000000..437cc3098 --- /dev/null +++ b/tui/src/rendering/mermaid/protocol.ts @@ -0,0 +1,29 @@ +import { OUTPUT_LIMIT, SOURCE_LIMIT } from "./types" + +export const REQUEST_LIMIT = OUTPUT_LIMIT * 6 + SOURCE_LIMIT * 6 + 8192 +export const REPLY_LIMIT = OUTPUT_LIMIT * 6 + Math.ceil(OUTPUT_LIMIT * 4 / 3) + 8192 + +/** Bounded records, including incomplete records and UTF-8 split across pipe reads. */ +export async function* jsonLines(stream: ReadableStream, limit: number): AsyncGenerator { + const reader = stream.getReader() + let parts: Uint8Array[] = [], size = 0 + try { + while (true) { + const { done, value } = await reader.read() + if (done) break + let start = 0 + while (start < value.length) { + const end = value.indexOf(10, start) + const part = value.subarray(start, end < 0 ? value.length : end) + size += part.length + if (size > limit) throw new Error("Diagram worker pipe limit") + parts.push(part) + if (end < 0) break + yield JSON.parse(Buffer.concat(parts).toString("utf8")) + parts = []; size = 0 + start = end + 1 + } + } + if (size) throw new Error("Incomplete diagram worker reply") + } finally { reader.releaseLock() } +} diff --git a/tui/src/rendering/mermaid/raster.ts b/tui/src/rendering/mermaid/raster.ts new file mode 100644 index 000000000..c53326717 --- /dev/null +++ b/tui/src/rendering/mermaid/raster.ts @@ -0,0 +1,13 @@ +import { Resvg } from "@resvg/resvg-js" +import { validateDiagramFrame } from "./geometry" +import { frameDiagramSvg } from "./frame" +import { OUTPUT_LIMIT, type DiagramFrame, type DiagramImage, type DiagramLayout } from "./types" + +/** Initial and interactive frames rasterize the same measured glyph outlines, without font loading. */ +export function rasterDiagram(layout: DiagramLayout, frame: DiagramFrame): DiagramImage { + validateDiagramFrame(layout, frame) + const raster = new Resvg(frameDiagramSvg(layout.svg, frame), { font: { loadSystemFonts: false } }).render() + const png = raster.asPng() + if (png.byteLength > OUTPUT_LIMIT) throw new Error("Diagram image limit") + return { png, width: raster.width, height: raster.height } +} diff --git a/tui/src/rendering/mermaid/render.test.ts b/tui/src/rendering/mermaid/render.test.ts new file mode 100644 index 000000000..443d07260 --- /dev/null +++ b/tui/src/rendering/mermaid/render.test.ts @@ -0,0 +1,155 @@ +import { describe, expect, spyOn, test } from "bun:test" +import { NativeImage } from "@opentui/core" +import { existsSync } from "node:fs" +import { renderDiagram } from "./render" +import { rasterDiagram } from "./raster" +import { diagramFrame } from "./geometry" +import { resolveDiagramSvg } from "./svg" +import { DiagramJobs } from "./jobs" +import { jsonLines } from "./protocol" +import { SOURCE_LIMIT, type DiagramInput } from "./types" + +const input: DiagramInput = { + source: "graph TD\n A[中文:开始处理长标签] --> B{检查数据}\n B -->|通过| C[完成]", + width: 800, scale: 2, + fonts: { + regular: { path: "C:/Windows/Fonts/msyh.ttc", postscriptName: "MicrosoftYaHei" }, + bold: { path: "C:/Windows/Fonts/msyhbd.ttc", postscriptName: "MicrosoftYaHei-Bold" }, + mono: { path: "C:/Windows/Fonts/consola.ttf", postscriptName: "Consolas" }, + }, + colors: { foreground: "#202020", muted: "#666666", surface: "#eeeeee", border: "#888888", accent: "#3366cc" }, +} + +const svg = (body: string) => `${body}` + +test("SVG image policy rejects external resources and executable elements", () => { + for (const body of ['', '