Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
perf(tui): shrink standalone builds and target native bindings (#6432)
chengyongruae7fed88e26d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9f8f9e5cd..40e2edb77 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -438,6 +438,15 @@ jobs:working-directory: tuirun: bun run build+ - name: Retain compiled TUI size evidence+ if: always()+ uses: actions/upload-artifact@v4+ with:+ name: tui-size-${{ runner.os }}+ path: tui/dist/*.size.json+ if-no-files-found: ignore+ retention-days: 7+- name: Verify licensed Linux release archiveif: runner.os == 'Linux'working-directory: tuidiff --git a/docs/releasing.md b/docs/releasing.mdindex 04813ca25..64e75c528 100644--- a/docs/releasing.md+++ b/docs/releasing.md@@ -49,7 +49,7 @@ Automate steps within an explicitly requested run, not the decision to build or7. Prepare the documentation PR in `Re-bin/nanobot-web` under its `MAINTAINING.md`: review English and all nine translations, preserve Nightly and previous releases, update latest-version redirects and run the full site quality gate. Pin source links to the candidate and confirm they match the eventual tag. Do not advertise an unpublished version.8. Review pinned Bun/OpenTUI licenses, corresponding source and relinking instructions. Check upstream revision availability and runtime/lockfile/notice agreement. Obtain the maintainer's commitment to the [source offer](../tui/SOURCE_OFFER.md) for its full stated period, at least three years after release; tests cannot grant it.9. Build all five native targets with publication scripts, ad-hoc signing macOS before packaging.- - Verify archive checksums, manifests, architecture, licenses/notices and embedded source. Run supported native smoke tests, record coverage and exact-head CI evidence, and label cross-compiled-only targets.+ - Verify archive checksums, manifests, architecture, licenses/notices and embedded source, including checkout-matching bytes for `tui/scripts/targets.ts` and `tui/scripts/target-bindings.ts`. Run supported native smoke tests, record coverage and exact-head CI evidence, and label cross-compiled-only targets.- Build platform wheels below, check them with `twine check`, validate RECORDs/tags/permissions and test pip selection on all five platforms.- Test first launch with an empty cache and `NANOBOT_TUI_NO_DOWNLOAD=1`; the executable must come from `site-packages/nanobot/tui/bin/`, not checkout or cache.10. Merge release preparation only after current checks/reviews pass. Compare the merged source tree with the tested candidate; rebuild/recheck changes. Reconcile changelog and documentation links, then tag the verified commit, not an unchecked later `main` tip.@@ -68,7 +68,7 @@ Before the third release, remove `provider_api_migration.py`, its import, `Provi### TUI preflight without a release tag-Use Bun 1.3.13 and a clean checkout; no tag or GitHub Release is required. Run targets sequentially because native dependency preparation modifies shared `node_modules`:+Use Bun 1.3.13 and a clean checkout; no tag or GitHub Release is required. Use the same `<target>` for preparation, compilation and notice generation. Run targets sequentially because preparation updates shared `node_modules`:```bashcd tui@@ -82,6 +82,10 @@ python3 scripts/package-release.py <target>Repeat for `darwin-arm64`, `darwin-x64`, `linux-arm64`, `linux-x64` and `win32-x64`. On macOS, run `codesign --force --sign - <binary>` and verify it; the publication workflow uses pinned `rcodesign` on Linux. Keep the ten `.zip`/`.zip.sha256` files with Python intermediates and provenance manifest in a candidate-specific directory, excluding configuration, backups and test environments from upload selections.+Candidate builds bundle minified JavaScript and the standalone Bun runtime with the additional precompiled bytecode cache disabled. Linux targets include both GNU and musl native variants, and x64 retains Bun's baseline CPU variant. Builds enforce a 135 MiB executable budget on Windows/Linux x64; other targets retain the existing 150 MiB ceiling until measured. The `dist/<executable>.size.json` report identifies the compiled, pre-signing executable and expected native packages; final archive manifests identify signed release bytes.++Before release, measure TUI first-screen and Mermaid render latency on each supported target, including first and warm renders. Verify cancellation and worker restart. Retain latency distributions and record executable, ZIP and final platform-wheel sizes separately. Cross-compilation and startup probes do not replace native interactive acceptance.+### Build the PyPI platform wheelsAfter `uv build` and native archive checks, from the exact release checkout:diff --git a/tests/cli/test_tui_release_packaging.py b/tests/cli/test_tui_release_packaging.pyindex d4dafed5d..2517f037b 100644--- a/tests/cli/test_tui_release_packaging.py+++ b/tests/cli/test_tui_release_packaging.py@@ -1,7 +1,9 @@-"""Keep shipped relinking instructions aligned with the pinned TUI runtime."""+"""Keep shipped corresponding source and runtime materials complete and aligned."""import importlib.util+import ioimport json+import tarfilefrom pathlib import Pathimport pytest@@ -13,6 +15,22 @@ packager = importlib.util.module_from_spec(SPEC)SPEC.loader.exec_module(packager)+def test_corresponding_source_contains_build_helpers_byte_for_byte():+ root = ROOT / "tui"+ with tarfile.open(fileobj=io.BytesIO(packager._source_archive(root)), mode="r:gz") as archive:+ for relative in (+ "scripts/build.ts",+ "scripts/targets.ts",+ "scripts/target-bindings.ts",+ "scripts/prepare-target.ts",+ "scripts/release-notices.ts",+ "scripts/package-release.py",+ ):+ source = archive.extractfile(f"nanobot-tui-source/tui/{relative}")+ assert source is not None+ assert source.read() == (root / relative).read_bytes(), relative++def test_current_relinking_matches_pinned_opentui():root = ROOT / "tui"version = json.loads((root / "package.json").read_text())["dependencies"]["@opentui/core"]diff --git a/tui/README.md b/tui/README.mdindex e8a04467b..620731989 100644--- a/tui/README.md+++ b/tui/README.md@@ -21,6 +21,8 @@ Assistant math written with `$...$`, `$$...$$`, `\\(...\\)`, or `\\[...\\]` is pMermaid 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.+On macOS, diagrams use the installed PingFang fonts. The system resolves their location automatically; no font-path configuration is needed. If the font lookup fails, check that PingFang is available in Font Book. Diagram source remains available while fonts are unavailable.+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 titlesdiff --git a/tui/RELINKING.md b/tui/RELINKING.mdindex 67c0fd8d1..bdd79af5f 100644--- a/tui/RELINKING.md+++ b/tui/RELINKING.md@@ -1,6 +1,6 @@# Native TUI corresponding source and relinking-The nanobot TUI release archive contains the executable, its complete JavaScript/TypeScript application source, dependency lockfile, build scripts, and third-party notices. It is built with Bun 1.3.13 and OpenTUI 0.5.11. See `SOURCE_OFFER.md` for the corresponding-source offer that accompanies the executable. The archive also contains the complete LGPL 2.0 and LGPL 2.1 license texts.+The nanobot TUI release archive contains the executable, its complete JavaScript/TypeScript application source, dependency lockfile, build scripts, and third-party notices. The build scripts include the shared target definitions and the resvg binding-loader generator. It is built with Bun 1.3.13 and OpenTUI 0.5.11. See `SOURCE_OFFER.md` for the corresponding-source offer that accompanies the executable. The archive also contains the complete LGPL 2.0 and LGPL 2.1 license texts.Corresponding upstream source:@@ -9,7 +9,7 @@ Corresponding upstream source:- Bun's patched WebKit (`4d5e75ebd84a14edbc7ae264245dcd77fe597c10`): <https://github.com/oven-sh/WebKit/tree/4d5e75ebd84a14edbc7ae264245dcd77fe597c10>- OpenTUI 0.5.11: <https://www.npmjs.com/package/@opentui/core/v/0.5.11> (source: <https://github.com/anomalyco/opentui/tree/6b9863ea7c5fae22bfebb23c242ddcc4c2b0aa0e>)- Pele 1.6.0: <https://www.npmjs.com/package/pele/v/1.6.0>-- resvg-js 2.6.2 (unmodified MPL-2.0 wrapper and native binding): <https://github.com/yisibl/resvg-js/tree/v2.6.2>; its upstream license text is reproduced in the notices.+- resvg-js 2.6.2 (MPL-2.0): <https://github.com/yisibl/resvg-js/tree/v2.6.2>. The public `index.js` wrapper and native bindings are unmodified; `tui/scripts/target-bindings.ts` supplies the build-target-specific internal loader and is included in `nanobot-tui-source.tar.gz`. The upstream license text is reproduced in the notices.- fontkit 2.0.4: <https://www.npmjs.com/package/fontkit/v/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:@@ -17,9 +17,14 @@ To rebuild against a modified JavaScriptCore/WebKit, first build Bun 1.3.13 from```bashcd nanobot-tui-source/tui/path/to/modified/bun install --frozen-lockfile+/path/to/modified/bun scripts/prepare-target.ts <target>/path/to/modified/bun run build -- <target>```Supported targets are `darwin-arm64`, `darwin-x64`, `linux-arm64`, `linux-x64`, and `win32-x64`. The resulting executable is written to `dist/`.+Use the same `<target>` for preparation and compilation. `scripts/targets.ts` defines the native package set and Bun compile target; `scripts/target-bindings.ts` generates the target's internal resvg loader without modifying installed dependency source. Linux targets retain GNU and musl bindings, and x64 targets use Bun's baseline CPU variant.++The included build script bundles minified JavaScript and the standalone Bun runtime without the additional precompiled bytecode cache; this is a build policy, not a runtime option.+Questions about source availability can be reported at <https://github.com/HKUDS/nanobot/issues>.diff --git a/tui/scripts/build.ts b/tui/scripts/build.tsindex 5d4613e59..53212c0e0 100644--- a/tui/scripts/build.ts+++ b/tui/scripts/build.ts@@ -1,36 +1,24 @@import { chmod, mkdir } from "node:fs/promises"import { basename, join } from "node:path"+import { targetBindings } from "./target-bindings"+import { nativePackages, targetPlan } from "./targets"-const target = process.argv[2] || `${process.platform}-${process.arch}`-const [platform, arch] = target.split("-")-const supportedTargets = new Set([- "darwin-arm64",- "darwin-x64",- "linux-arm64",- "linux-x64",- "win32-x64",-])--if (!platform || !arch || !supportedTargets.has(target)) {- throw new Error(`unsupported target: ${target}`)-}--const bunPlatform = platform === "win32" ? "windows" : platform-// Wheels cannot select a CPU feature level: avoid the default AVX2-only x64 runtime.-const cpuVariant = arch === "x64" ? "-baseline" : ""-const extension = platform === "win32" ? ".exe" : ""-const outputDir = join(import.meta.dir, "..", "dist")-const output = join(outputDir, `nanobot-tui-${platform}-${arch}${extension}`)+const plan = targetPlan(process.argv[2] || `${process.platform}-${process.arch}`)+const root = join(import.meta.dir, "..")+const outputDir = join(root, "dist")+const output = join(outputDir, plan.executable)await mkdir(outputDir, { recursive: true })const result = await Bun.build({entrypoints: [join(import.meta.dir, "..", "src", "index.ts")],define: { NANOBOT_COMPILED: "true" },- bytecode: true,+ // Standalone files retain JS; the optional precompiled cache costs another ~22 MiB on x64.+ bytecode: false,format: "esm",+ plugins: [await targetBindings(plan, root)],minify: { whitespace: true, syntax: true, identifiers: true, keepNames: true },compile: {- target: `bun-${bunPlatform}-${arch}${cpuVariant}` as Bun.Build.CompileTarget,+ target: plan.bunTarget,outfile: output,},})@@ -39,9 +27,26 @@ if (!result.success) {for (const log of result.logs) console.error(log)process.exit(1)}-if (platform !== "win32") await chmod(output, 0o755)+if (plan.platform !== "win32") await chmod(output, 0o755)+const bytes = Bun.file(output).sizeconst digest = new Bun.CryptoHasher("sha256").update(await Bun.file(output).arrayBuffer()).digest("hex")await Bun.write(`${output}.sha256`, `${digest} ${basename(output)}\n`)+await Bun.write(`${output}.size.json`, JSON.stringify({+ phase: "compiled", // macOS signing happens later; the archive manifest owns final hashes.+ target: plan.id,+ bunTarget: plan.bunTarget,+ bunVersion: Bun.version,+ bunRevision: Bun.revision,+ bytecode: false,+ executable: basename(output),+ bytes,+ sha256: digest,+ budgetBytes: plan.executableBudgetBytes,+ expectedNativePackages: nativePackages(plan),+}, null, 2) + "\n")+if (bytes > plan.executableBudgetBytes) {+ throw new Error(`${plan.id} executable is ${bytes} bytes; budget is ${plan.executableBudgetBytes}`)+}console.log(output)diff --git a/tui/scripts/package-release.py b/tui/scripts/package-release.pyindex eb95f0dc7..f8fb55c4a 100644--- a/tui/scripts/package-release.py+++ b/tui/scripts/package-release.py@@ -48,6 +48,8 @@ def _source_archive(root: Path) -> bytes:"tsconfig.json","src","scripts/build.ts",+ "scripts/targets.ts",+ "scripts/target-bindings.ts","scripts/prepare-target.ts","scripts/release-notices.ts","scripts/package-release.py",diff --git a/tui/scripts/prepare-target.ts b/tui/scripts/prepare-target.tsindex 9d25eef86..a3b46d640 100644--- a/tui/scripts/prepare-target.ts+++ b/tui/scripts/prepare-target.ts@@ -1,17 +1,9 @@import { join } from "node:path"--const packagesByTarget: Record<string, string[]> = {- "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"],-}+import { nativePackages, targetPlan } from "./targets"const target = process.argv[2]if (!target) throw new Error("target is required")-const packages = packagesByTarget[target]-if (!packages) throw new Error(`unsupported target: ${target}`)+const packages = nativePackages(targetPlan(target))const root = join(import.meta.dir, "..")const manifest = await Bun.file(join(root, "package.json")).json()diff --git a/tui/scripts/release-notices.ts b/tui/scripts/release-notices.tsindex e8f9c4d3d..6b41444d3 100644--- a/tui/scripts/release-notices.ts+++ b/tui/scripts/release-notices.ts@@ -1,28 +1,14 @@import { readdir, readFile, writeFile } from "node:fs/promises"import { basename, join } from "node:path"+import { nativePackages, targetPlan } from "./targets"const target = process.argv[2]if (!target) throw new Error("target is required")-const supportedTargets = new Set([- "darwin-arm64",- "darwin-x64",- "linux-arm64",- "linux-x64",- "win32-x64",-])-if (!supportedTargets.has(target)) throw new Error(`unsupported target: ${target}`)-const nativePackagesByTarget: Record<string, string[]> = {- "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 plan = targetPlan(target)const root = join(import.meta.dir, "..")const projectRoot = join(root, "..")-const extension = target.startsWith("win32-") ? ".exe" : ""-const asset = `nanobot-tui-${target}${extension}`+const asset = plan.executableconst output = join(root, "dist", `${asset}.THIRD_PARTY_NOTICES.txt`)type PackageNotice = {@@ -112,7 +98,7 @@ const notices = await Promise.all((await runtimePackageRoots(root)).map(readPackageNotice),)const packagedNames = new Set(notices.map((notice) => notice.name))-for (const name of nativePackagesByTarget[target] ?? []) {+for (const name of nativePackages(plan)) {if (!packagedNames.has(name)) throw new Error(`target runtime package is missing: ${name}`)}const sections = [@@ -122,7 +108,7 @@ const sections = ["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.",+ "resvg's public wrapper and native binding are unmodified; its internal loader is target-selected. MPL-2.0 source is listed in RELINKING.md.","","===== nanobot project license =====","",diff --git a/tui/scripts/target-bindings.test.ts b/tui/scripts/target-bindings.test.tsnew file mode 100644index 000000000..d6e7bd756--- /dev/null+++ b/tui/scripts/target-bindings.test.ts@@ -0,0 +1,88 @@+import { afterEach, expect, test } from "bun:test"+import { cp, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"+import { tmpdir } from "node:os"+import { join } from "node:path"+import { targetBindings } from "./target-bindings"+import { nativePackages, targetPlan } from "./targets"++const roots: string[] = []+afterEach(async () => {+ await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))+})++async function fixture(): Promise<string> {+ const root = await mkdtemp(join(tmpdir(), "nanobot-target-bindings-"))+ roots.push(root)+ await writeFile(join(root, "package.json"), "{}")+ const wrapper = join(root, "node_modules", "@resvg", "resvg-js")+ await cp(join(import.meta.dir, "..", "node_modules", "@resvg", "resvg-js"), wrapper, { recursive: true })+ for (const name of [+ "resvg-js-win32-x64-msvc", "resvg-js-darwin-arm64", "resvg-js-darwin-x64",+ "resvg-js-linux-x64-gnu", "resvg-js-linux-x64-musl", "resvg-js-linux-arm64-gnu", "resvg-js-linux-arm64-musl",+ ]) {+ const path = join(root, "node_modules", "@resvg", name)+ await mkdir(path, { recursive: true })+ await writeFile(join(path, "package.json"), JSON.stringify({ name: `@resvg/${name}`, version: "2.6.2", main: "index.js" }))+ await writeFile(join(path, "index.js"), `+class Resvg {+ constructor(svg, options) { this.binding = ${JSON.stringify(name)}; this.svg = svg; this.options = JSON.parse(options); }+}+module.exports = { Resvg, renderAsync: async (svg, options) => ({ svg, options: JSON.parse(options) }) };+`)+ }+ return root+}++async function bundle(root: string, target?: string, libc?: "gnu" | "musl") {+ const entry = join(root, "entry.js")+ await writeFile(entry, `+${libc ? `process.report.getReport = () => ({ header: { glibcVersionRuntime: ${libc === "gnu" ? '"2.34"' : "undefined"} } });` : ""}+const { Resvg, renderAsync } = require("@resvg/resvg-js");+const options = { fitTo: { mode: "width", value: 321 } };+console.log(JSON.stringify({ image: new Resvg("<svg/>", options), asyncImage: await renderAsync("<svg/>", options) }));+`)+ const result = await Bun.build({+ entrypoints: [entry],+ outdir: join(root, "out"),+ target: "bun",+ metafile: true,+ plugins: target ? [await targetBindings(targetPlan(target), root)] : [],+ })+ if (!result.success) throw new Error(result.logs.map(String).join("\n"))+ const run = Bun.spawn([process.execPath, join(root, "out", "entry.js")], { stdout: "pipe", stderr: "pipe" })+ const [stdout, stderr, code] = await Promise.all([new Response(run.stdout).text(), new Response(run.stderr).text(), run.exited])+ expect(code, stderr).toBe(0)+ return { value: JSON.parse(stdout), inputs: Object.keys(result.metafile?.inputs ?? {}).map((path) => path.replaceAll("\\", "/")) }+}++test("cross-target binding selection excludes installed host payloads and preserves the public wrapper", async () => {+ const root = await fixture()+ const original = await bundle(root)+ const selected = await bundle(root, "win32-x64")+ // Both host libc variants are installed: the generic loader pulls them into the bundle.+ expect(original.inputs.filter((path) => /resvg-js-linux-x64-.*\/index\.js$/.test(path))).toHaveLength(2)+ expect(selected.inputs.filter((path) => /resvg-js-.*\/index\.js$/.test(path))).toHaveLength(1)+ expect(selected.value).toEqual({+ image: { binding: "resvg-js-win32-x64-msvc", svg: "<svg/>", options: { fitTo: { mode: "width", value: 321 } } },+ asyncImage: { svg: "<svg/>", options: { fitTo: { mode: "width", value: 321 } } },+ })+})++for (const libc of ["gnu", "musl"] as const) {+ test(`Linux target retains both native variants and selects ${libc}`, async () => {+ const root = await fixture()+ const result = await bundle(root, "linux-x64", libc)+ expect(result.value.image.binding).toBe(`resvg-js-linux-x64-${libc}`)+ expect(result.inputs.filter((path) => /resvg-js-linux-x64-.*\/index\.js$/.test(path))).toHaveLength(2)+ expect(nativePackages(targetPlan("linux-x64"))).toEqual([+ "@opentui/core-linux-x64", "@resvg/resvg-js-linux-x64-gnu",+ "@opentui/core-linux-x64-musl", "@resvg/resvg-js-linux-x64-musl",+ ])+ })+}++test("dependency loader changes require an explicit build-adapter review", async () => {+ const root = await fixture()+ await writeFile(join(root, "node_modules", "@resvg", "resvg-js", "js-binding.js"), "module.exports = {}")+ await expect(targetBindings(targetPlan("win32-x64"), root)).rejects.toThrow("js-binding.js changed")+})diff --git a/tui/scripts/target-bindings.ts b/tui/scripts/target-bindings.tsnew file mode 100644index 000000000..bafbba624--- /dev/null+++ b/tui/scripts/target-bindings.ts@@ -0,0 +1,58 @@+// SPDX-License-Identifier: MPL-2.0+// Target-specific replacement for resvg-js 2.6.2's generated binding loader.+import { createRequire } from "node:module"+import { dirname, join, resolve } from "node:path"+import type { BunPlugin } from "bun"+import type { TargetPlan } from "./targets"++// This adapter replaces only the generated loader, not resvg's public options wrapper.+// Review the loader contract and these identities together when updating resvg.+const resvgVersion = "2.6.2"+const resvgSources = {+ "index.js": "b670803d88b380b0610edf743d8b74dcc132d9e2aa6aaa04cfaa06b2fcad397d",+ "js-binding.js": "d5fbe3b7450d1e393ea9856e86e16465d25be8743cae7db03e2f3249aed61e56",+}++export async function targetBindings(plan: TargetPlan, root: string): Promise<BunPlugin> {+ const require = createRequire(join(root, "package.json"))+ const entry = require.resolve("@resvg/resvg-js")+ const packageRoot = dirname(entry)+ const manifest = await Bun.file(join(packageRoot, "package.json")).json()+ if (manifest.version !== resvgVersion) throw new Error(`review resvg target bindings for version ${manifest.version}`)+ for (const [name, expected] of Object.entries(resvgSources)) {+ const digest = new Bun.CryptoHasher("sha256").update(await Bun.file(join(packageRoot, name)).arrayBuffer()).digest("hex")+ if (digest !== expected) throw new Error(`review resvg target bindings: ${name} changed`)+ }++ // Absolute resolutions keep the virtual module independent of the build host's cwd.+ const binding = (name: string) => `require(${JSON.stringify(require.resolve(name))})`+ const load = plan.platform === "linux"+ ? `+function isMusl() {+ if (!process.report || typeof process.report.getReport !== "function") {+ try {+ const lddPath = require("node:child_process").execSync("which ldd").toString().trim();+ return require("node:fs").readFileSync(lddPath, "utf8").includes("musl");+ } catch { return true; }+ }+ return !process.report.getReport().header.glibcVersionRuntime;+}+const nativeBinding = isMusl() ? ${binding(plan.bindings.musl.resvg)} : ${binding(plan.bindings.gnu.resvg)};+`+ : `const nativeBinding = ${binding(plan.bindings.native.resvg)};`+ const contents = `${load}+const { BBox, Resvg, RenderedImage, renderAsync } = nativeBinding;+module.exports = { BBox, Resvg, RenderedImage, renderAsync };+`++ return {+ name: "nanobot-resvg-target",+ setup(builder) {+ builder.onResolve({ filter: /^\.\/js-binding\.js$/ }, (args) => {+ if (resolve(args.importer) === resolve(entry)) return { path: "binding", namespace: "nanobot-resvg" }+ return undefined+ })+ builder.onLoad({ filter: /^binding$/, namespace: "nanobot-resvg" }, () => ({ contents, loader: "js" }))+ },+ }+}diff --git a/tui/scripts/targets.ts b/tui/scripts/targets.tsnew file mode 100644index 000000000..e10cbce5b--- /dev/null+++ b/tui/scripts/targets.ts@@ -0,0 +1,54 @@+type NativePair = Readonly<{ opentui: string; resvg: string }>++type TargetSpec = Readonly<{+ bunTarget: Bun.Build.CompileTarget+ executableBudgetBytes: number+}> & (+ | { platform: "linux"; bindings: { gnu: NativePair; musl: NativePair } }+ | { platform: "darwin" | "win32"; bindings: { native: NativePair } }+)++const MiB = 1024 * 1024+// Wheels cannot select CPU features: every x64 target uses Bun's baseline runtime.+// Unmeasured arm64/macOS targets retain the existing 150 MiB archive limit.+const targets = {+ "darwin-arm64": {+ platform: "darwin", bunTarget: "bun-darwin-arm64", executableBudgetBytes: 150 * MiB,+ bindings: { native: { opentui: "@opentui/core-darwin-arm64", resvg: "@resvg/resvg-js-darwin-arm64" } },+ },+ "darwin-x64": {+ platform: "darwin", bunTarget: "bun-darwin-x64-baseline", executableBudgetBytes: 150 * MiB,+ bindings: { native: { opentui: "@opentui/core-darwin-x64", resvg: "@resvg/resvg-js-darwin-x64" } },+ },+ "linux-arm64": {+ platform: "linux", bunTarget: "bun-linux-arm64", executableBudgetBytes: 150 * MiB,+ bindings: {+ gnu: { opentui: "@opentui/core-linux-arm64", resvg: "@resvg/resvg-js-linux-arm64-gnu" },+ musl: { opentui: "@opentui/core-linux-arm64-musl", resvg: "@resvg/resvg-js-linux-arm64-musl" },+ },+ },+ "linux-x64": {+ platform: "linux", bunTarget: "bun-linux-x64-baseline", executableBudgetBytes: 135 * MiB,+ bindings: {+ gnu: { opentui: "@opentui/core-linux-x64", resvg: "@resvg/resvg-js-linux-x64-gnu" },+ musl: { opentui: "@opentui/core-linux-x64-musl", resvg: "@resvg/resvg-js-linux-x64-musl" },+ },+ },+ "win32-x64": {+ platform: "win32", bunTarget: "bun-windows-x64-baseline", executableBudgetBytes: 135 * MiB,+ bindings: { native: { opentui: "@opentui/core-win32-x64", resvg: "@resvg/resvg-js-win32-x64-msvc" } },+ },+} as const satisfies Record<string, TargetSpec>++export type TargetPlan = TargetSpec & { id: keyof typeof targets; executable: string }++export function targetPlan(raw: string): TargetPlan {+ if (!Object.hasOwn(targets, raw)) throw new Error(`unsupported target: ${raw}`)+ const id = raw as keyof typeof targets+ const spec = targets[id]+ return { ...spec, id, executable: `nanobot-tui-${id}${spec.platform === "win32" ? ".exe" : ""}` }+}++export function nativePackages(plan: TargetPlan): string[] {+ return Object.values(plan.bindings).flatMap((pair: NativePair) => [pair.opentui, pair.resvg])+}diff --git a/tui/src/app/diagrams.test.ts b/tui/src/app/diagrams.test.tsindex a79e8b7d5..4fbf0cfe7 100644--- a/tui/src/app/diagrams.test.ts+++ b/tui/src/app/diagrams.test.ts@@ -15,6 +15,7 @@ function images(root: Renderable): ImageRenderable[] {const source = "graph TD\n A[中文长标签 English] --> B[完成]"const content = `\`\`\`mermaid\n${source}\n\`\`\`\n\nTrailing paragraph`+const nativeFontsAvailable = process.platform === "darwin" || existsSync("C:/Windows/Fonts/msyh.ttc")test("streamed stable Mermaid fences stay source until reply completion, including the viewer", async () => {setup = await createTestRenderer({ width: 80, height: 35 })@@ -35,7 +36,7 @@ test("streamed stable Mermaid fences stay source until reply completion, includiexpect(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 () => {+test.skipIf(!nativeFontsAvailable)("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)@@ -126,7 +127,7 @@ test("diagram command on ordinary Markdown shows an empty viewer and returns toexpect(setup.captureCharFrame()).toContain("draft")})-test.skipIf(!existsSync("C:/Windows/Fonts/msyh.ttc"))("inline image uses real terminal pixels without upscaling small diagrams", async () => {+test.skipIf(!nativeFontsAvailable)("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 } })@@ -144,7 +145,7 @@ test.skipIf(!existsSync("C:/Windows/Fonts/msyh.ttc"))("inline image uses real te}, 10_000)-test.skipIf(!existsSync("C:/Windows/Fonts/msyh.ttc"))("source-only and cancelled viewer release the shared worker; image demand resumes explicitly", async () => {+test.skipIf(!nativeFontsAvailable)("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)@@ -192,7 +193,7 @@ test.skipIf(!existsSync("C:/Windows/Fonts/msyh.ttc"))("source-only and cancelled}, 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 () => {+test.skipIf(!nativeFontsAvailable)("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 }@@ -235,7 +236,7 @@ test.skipIf(!existsSync("C:/Windows/Fonts/msyh.ttc"))("offscreen return and cell}, 20_000)-test.skipIf(!existsSync("C:/Windows/Fonts/msyh.ttc"))("viewer navigation releases old layout pins under the real transcript budget", async () => {+test.skipIf(!nativeFontsAvailable)("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 } })@@ -272,7 +273,7 @@ test.skipIf(!existsSync("C:/Windows/Fonts/msyh.ttc"))("viewer navigation release}, 25_000)-test.skipIf(!existsSync("C:/Windows/Fonts/msyh.ttc"))("source/image retry after a parser failure keeps the original source visible", async () => {+test.skipIf(!nativeFontsAvailable)("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)diff --git a/tui/src/rendering/mermaid/macos-fonts.test.ts b/tui/src/rendering/mermaid/macos-fonts.test.tsnew file mode 100644index 000000000..f16bbd533--- /dev/null+++ b/tui/src/rendering/mermaid/macos-fonts.test.ts@@ -0,0 +1,28 @@+import { expect, spyOn, test } from "bun:test"+import * as childProcess from "node:child_process"+import { macOSFonts } from "./macos-fonts"++test("macOS font lookup preserves system-resolved paths and regular/bold face identity", () => {+ const regular = { path: "/System/Library/AssetsV2/font-version/AssetData/PingFang.ttc", postscriptName: "PingFangSC-Regular" }+ const bold = { ...regular, postscriptName: "PingFangSC-Semibold" }+ const lookup = spyOn(childProcess, "execFileSync").mockReturnValue(JSON.stringify([regular, bold]))+ try {+ expect(macOSFonts()).toEqual({ regular, bold, mono: regular })+ } finally { lookup.mockRestore() }+})++test("an unavailable macOS font URL is a font error, not an undefined file read", () => {+ const lookup = spyOn(childProcess, "execFileSync").mockReturnValue(JSON.stringify([+ { postscriptName: "PingFangSC-Regular" }, { postscriptName: "PingFangSC-Semibold" },+ ]))+ try {+ expect(macOSFonts).toThrow("check PingFang in macOS Font Book")+ } finally { lookup.mockRestore() }+})++test("a failed system lookup stays a recoverable diagram error", () => {+ const lookup = spyOn(childProcess, "execFileSync").mockImplementation(() => { throw new Error("lookup timed out") })+ try {+ expect(macOSFonts).toThrow("check PingFang in macOS Font Book")+ } finally { lookup.mockRestore() }+})diff --git a/tui/src/rendering/mermaid/macos-fonts.ts b/tui/src/rendering/mermaid/macos-fonts.tsnew file mode 100644index 000000000..dcc023375--- /dev/null+++ b/tui/src/rendering/mermaid/macos-fonts.ts@@ -0,0 +1,38 @@+import { execFileSync } from "node:child_process"+import { homedir } from "node:os"+import { isAbsolute } from "node:path"+import type { DiagramFont, DiagramInput } from "./types"++// Ask CoreText for installed font URLs: recent macOS versions manage PingFang+// under versioned Assets directories. No app automation or development toolchain is used.+const query = `+ObjC.import("CoreText");+JSON.stringify(["PingFangSC-Regular", "PingFangSC-Semibold"].map(function(name) {+ const font = $.CTFontCreateWithName($(name), 12, null);+ const actual = ObjC.unwrap(ObjC.castRefToObject($.CTFontCopyPostScriptName(font)));+ if (actual !== name) throw new Error("PingFang font unavailable");+ const url = $.CTFontCopyAttribute(font, $.kCTFontURLAttribute);+ return { path: ObjC.unwrap(url.path), postscriptName: actual };+}));+`++function isFont(value: unknown): value is DiagramFont {+ return value !== null && typeof value === "object"+ && "path" in value && typeof value.path === "string" && isAbsolute(value.path)+ && "postscriptName" in value && typeof value.postscriptName === "string" && value.postscriptName.length > 0+}++/** Called only in the diagram worker; getFonts caches the resolved faces. */+export function macOSFonts(): NonNullable<DiagramInput["fonts"]> {+ try {+ const fonts: unknown = JSON.parse(execFileSync("/usr/bin/osascript", ["-l", "JavaScript", "-e", query], {+ encoding: "utf8", timeout: 5000, maxBuffer: 4096, stdio: ["ignore", "pipe", "pipe"],+ env: { HOME: homedir(), PATH: "/usr/bin:/bin" },+ }))+ if (!Array.isArray(fonts) || fonts.length !== 2 || !fonts.every(isFont)) throw new Error("Invalid font lookup result")+ const regular = fonts[0]!, bold = fonts[1]!+ return { regular, bold, mono: regular }+ } catch (cause) {+ throw new Error("Diagram font unavailable (check PingFang in macOS Font Book)", { cause })+ }+}diff --git a/tui/src/rendering/mermaid/render.test.ts b/tui/src/rendering/mermaid/render.test.tsindex 443d07260..3edc6c4a0 100644--- a/tui/src/rendering/mermaid/render.test.ts+++ b/tui/src/rendering/mermaid/render.test.ts@@ -12,7 +12,8 @@ import { SOURCE_LIMIT, type DiagramInput } from "./types"const input: DiagramInput = {source: "graph TD\n A[中文:开始处理长标签] --> B{检查数据}\n B -->|通过| C[完成]",width: 800, scale: 2,- fonts: {+ // macOS must discover its system-managed font location, not use a test override.+ fonts: process.platform === "darwin" ? undefined : {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" },@@ -47,7 +48,7 @@ test("worker records preserve split UTF-8 and multiple replies across pipe readsexpect(records).toEqual([{ label: "中文" }, { width: 9 }])})-describe.skipIf(!existsSync(input.fonts!.regular.path))("Windows raster integration", () => {+describe.skipIf(process.platform !== "darwin" && !existsSync(input.fonts!.regular.path))("Native raster integration", () => {test("Pele renders Chinese flowchart and sequence diagram to bounded PNGs", async () => {for (const source of [input.source, "sequenceDiagram\n participant A as 用户\n participant B as 服务\n A->>B: 长标签消息\n B-->>A: 完成"]) {const image = await renderDiagram({ ...input, source })diff --git a/tui/src/rendering/mermaid/render.ts b/tui/src/rendering/mermaid/render.tsindex 7c8ff4fe0..a262f9d21 100644--- a/tui/src/rendering/mermaid/render.ts+++ b/tui/src/rendering/mermaid/render.ts@@ -6,17 +6,17 @@ import { diagramFrame } from "./geometry"import { resolveDiagramSvg } from "./svg"import { rasterDiagram } from "./raster"import { outlineDiagramText, shapeDiagramText } from "./text"+import { macOSFonts } from "./macos-fonts"import { DIAGRAM_FONT_SIZE, MAX_DIMENSION, MAX_PIXELS, OUTPUT_LIMIT, SOURCE_LIMIT, type DiagramAsset, type DiagramFont, type DiagramInput, type DiagramLayout } from "./types"type FontFile = ReturnType<typeof create>function systemFonts(file: (path: string) => FontFile): NonNullable<DiagramInput["fonts"]> {+ if (process.platform === "darwin") return macOSFonts()const windows = join(process.env.SystemRoot || "C:/Windows", "Fonts")const candidates = process.platform === "win32"? [[join(windows, "msyh.ttc"), join(windows, "msyhbd.ttc")]]- : process.platform === "darwin"- ? [["/System/Library/Fonts/PingFang.ttc", "/System/Library/Fonts/PingFang.ttc"]]- : [["/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", "/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc"],- ["/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"]]+ : [["/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", "/usr/share/fonts/opentype/noto/NotoSansCJK-Bold.ttc"],+ ["/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"]]for (const [regularPath, boldPath] of candidates) {if (!regularPath || !boldPath || !existsSync(regularPath) || !existsSync(boldPath)) continueconst select = (path: string, bold: boolean): DiagramFont => {diff --git a/webui/browser/prompt-rail.spec.ts b/webui/browser/prompt-rail.spec.tsindex f32fcb648..0227aeb12 100644--- a/webui/browser/prompt-rail.spec.ts+++ b/webui/browser/prompt-rail.spec.ts@@ -55,6 +55,8 @@ test("complete rail scrolls independently, jumps to unloaded history and returnsawait expect(body.getByText("Question 0", { exact: true })).toBeInViewport();expect(reads).toEqual(["?limit=24&after=0"]);await expect(body.getByText("Question 1999", { exact: true })).toHaveCount(0);+ // Force input-before-scroll ordering instead of relying on compositor timing.+ await body.evaluate((node) => node.addEventListener("wheel", () => undefined, { passive: false }));for (const after of [10, 20, 30, 40]) {await body.hover();await page.mouse.wheel(0, 10000);diff --git a/webui/src/components/thread/ThreadViewport.tsx b/webui/src/components/thread/ThreadViewport.tsxindex 49249c080..1fdd921ac 100644--- a/webui/src/components/thread/ThreadViewport.tsx+++ b/webui/src/components/thread/ThreadViewport.tsx@@ -903,7 +903,8 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProif (el.scrollTop > 1) historySpringRef.current?.leaveBoundary();const distance = el.scrollHeight - el.scrollTop - el.clientHeight;const near = distance < NEAR_BOTTOM_PX;- const owner = threadMotionRef.current?.observeScroll(near) ?? "automatic";+ // A detached history page's bottom is not the live tail.+ const owner = threadMotionRef.current?.observeScroll(near && !historyWindow) ?? "automatic";const logicallyAtBottom = !historyWindow && (owner === "automatic" || (owner === "navigation" && near));setAtBottom((current) =>current === logicallyAtBottom ? current : logicallyAtBottom,@@ -942,7 +943,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportPro}threadMotionRef.current?.handleUserScrollIntent(canScrollInDirection(el, direction),- direction === "forward",+ direction === "forward" && !historyWindow,);};const prepareHistoryPull = () => {@@ -1026,11 +1027,7 @@ export const ThreadViewport = forwardRef<ThreadViewportHandle, ThreadViewportProsetAtHistoryTop(true);return;}- // Locally windowed messages need no network gesture or loading feedback.- if (hiddenMessageCount > 0) handleDirectionalInput(directionFromDelta(delta));- else threadMotionRef.current?.handleUserScrollIntent(- canScrollInDirection(el, directionFromDelta(delta)), delta > 0,- );+ handleDirectionalInput(directionFromDelta(delta));};const handleTouchEnd = () => {const pulling = historyTouchRef.current?.pulling;diff --git a/webui/src/components/thread/thread-motion.ts b/webui/src/components/thread/thread-motion.tsindex 42780b701..3a99fc119 100644--- a/webui/src/components/thread/thread-motion.ts+++ b/webui/src/components/thread/thread-motion.ts@@ -342,13 +342,14 @@ export class ThreadMotionCoordinator {* A scroll event reports geometry; it does not prove user intent. Explicit* input handlers call takeUserControl() before the browser scrolls. Layout,* sticky positioning, and camera writes therefore remain automatic even- * when the browser emits an intermediate scroll event for them.+ * when the browser emits an intermediate scroll event for them. Proximity+ * to a detached history page's bottom must not count as near the live tail.*/- observeScroll(nearBottom: boolean): ThreadScrollOwner {+ observeScroll(nearLiveTail: boolean): ThreadScrollOwner {switch (this.mode) {case "navigating-latest":if (!this.camera.isFollowing()) {- if (nearBottom) {+ if (nearLiveTail) {this.settleLatestNavigation();} else {this.invalidateGeometry();@@ -358,7 +359,7 @@ export class ThreadMotionCoordinator {case "navigating-history":if (!this.camera.isFollowing()) {this.transition("navigation-settled");- if (nearBottom) {+ if (nearLiveTail) {this.resumeAutoFollow();} else {this.resumeFollowArmed = true;@@ -366,7 +367,7 @@ export class ThreadMotionCoordinator {}return "navigation";case "browsing-history":- if (!nearBottom) {+ if (!nearLiveTail) {this.resumeFollowArmed = true;return "user";}@@ -374,7 +375,7 @@ export class ThreadMotionCoordinator {this.resumeAutoFollow();return "automatic";default:- if (!nearBottom) this.invalidateGeometry();+ if (!nearLiveTail) this.invalidateGeometry();return "automatic";}}diff --git a/webui/src/tests/thread-viewport.test.tsx b/webui/src/tests/thread-viewport.test.tsxindex 90cd71208..55a5b98db 100644--- a/webui/src/tests/thread-viewport.test.tsx+++ b/webui/src/tests/thread-viewport.test.tsx@@ -12,6 +12,7 @@ import {} from "@/components/thread/ThreadViewport";import { ThreadCameraController } from "@/components/thread/thread-camera";import { ThreadMotionCoordinator } from "@/components/thread/thread-motion";+import type { PromptHistoryNavigation } from "@/hooks/usePromptHistory";import type { UIMessage } from "@/lib/types";const messages: UIMessage[] = [@@ -2028,6 +2029,56 @@ describe("ThreadViewport", () => {await waitFor(() => expect(screen.getByText("hello")).toBeInTheDocument());});+ it.each(["wheel", "touch", "keyboard"] as const)("loads newer history after one %s input reaches the page bottom", async (input) => {+ const history = makePromptExchangeMessages(5);+ const newer = vi.fn();+ const navigation: PromptHistoryNavigation = {+ prompts: [], window: { messages: history, userMessageOffset: 0,+ hasMoreBefore: false, hasMoreAfter: true, forkBoundaryMessageCount: null },+ target: null, operation: null, loading: false, error: null,+ jump: vi.fn(), older: vi.fn(), newer, cancel: vi.fn(), latest: vi.fn(), retry: vi.fn(), updateMessages: vi.fn(),+ };+ const view = render(<ThreadViewport messages={messages} isStreaming={false} composer={<div />} navigation={navigation} />);+ await flushAnimationFrame();+ const scroller = view.getByTestId("thread-message-region");+ mockScrollGeometry(scroller, 2000, 500, 100);++ const forward = () => {+ if (input === "wheel") fireEvent.wheel(scroller, { deltaY: 10000 });+ if (input === "keyboard") fireEvent.keyDown(scroller, { key: "End" });+ if (input === "touch") {+ fireEvent.touchStart(scroller, { touches: [{ clientX: 100, clientY: 400 }] });+ fireEvent.touchMove(scroller, { touches: [{ clientX: 100, clientY: 200 }] });+ fireEvent.touchEnd(scroller);+ }+ };+ // A large input can cross the entire prefetch range in one native scroll.+ forward();+ expect(newer).not.toHaveBeenCalled();+ act(() => {+ scroller.scrollTop = 1500;+ fireEvent.scroll(scroller);+ });+ expect(newer).toHaveBeenCalledOnce();++ // Appending a page must preserve the reader's position, not follow its tail.+ mockScrollGeometry(scroller, 2800, 500, 1500);+ view.rerender(<ThreadViewport messages={messages} isStreaming={false} composer={<div />}+ navigation={{ ...navigation, window: { ...navigation.window!, messages: makePromptExchangeMessages(10) } }} />);+ await flushAnimationFrame();+ expect(scroller.scrollTop).toBe(1500);++ // At the existing page boundary, forward input cannot produce a scroll event.+ mockScrollGeometry(scroller, 2800, 500, 2300);+ forward();+ expect(newer).toHaveBeenCalledTimes(2);+ mockScrollGeometry(scroller, 3600, 500, 2300);+ view.rerender(<ThreadViewport messages={messages} isStreaming={false} composer={<div />}+ navigation={{ ...navigation, window: { ...navigation.window!, messages: makePromptExchangeMessages(15) } }} />);+ await flushAnimationFrame();+ expect(scroller.scrollTop).toBe(2300);+ });+it("includes the selected prompt when one server turn exceeds the local render window", async () => {const history: UIMessage[] = [{ id: "old-user", role: "user", content: "Large old turn", createdAt: 1 },...Array.from({ length: INITIAL_HISTORY_WINDOW + 10 }, (_, index): UIMessage => ({