perf(web): terminal snapshots reuse WASM memory views #26717
main fromrefs/pull/26717/head·merged by maria-rcks View on GitHubProblem#
Every Ghostty terminal frame reads its dirty rows cell by cell out of WASM memory. Each scratch read or write built a fresh Uint8Array or DataView (runtime.bytes() / runtime.view()), several per cell, and each one went through the WebAssembly.Memory.buffer getter, which is slow in V8. A CPU profile of a full 200×60 frame put about 40% of the time in that getter and those view allocations, and only about 10% in the wasm itself.
Fix#
runtime.tskeeps oneDataViewand oneUint8Arrayover WASM memory. It rebuilds them only whenmemory.growhas detached the old buffer, which it detects when the cached view'sbyteLengthreads 0.bytes()andview()reuse that buffer. A newfn(name)returns an export without calling it, andcall()now goes through it.core.ts: the snapshot /readRowhot path and the scalar getters read and write through the cached views at absolute offsets. Views are still fetched again after every WASM call, because any call may grow memory.readRowlooks up the two per-cell exports once per row.ghosttyCellTexttakes an optionalbyteOffset, so it reads graphemes straight from the shared view.
No behaviour change. Snapshots are identical.
Measurements#
Harness: a standalone Node 24 script that imports the real core.ts / runtime.ts (a small loader maps ?url wasm imports to file URLs) and compares the original files with the changed ones. The terminal is 200×60 and holds 2,000 lines of SGR-coloured output. Each frame scrolls one row and calls snapshot(), so every row is dirty. Each run takes the median of 9 × 60-frame batches after a 200-frame warmup. Allocation is the heapUsed delta of a single frame after gc(), kept only when no GC ran during the frame. Streaming means writing the same output as 126 × 4 KB chunks with write() + snapshot() after each chunk. Before and after ran interleaved, 5 runs each, on an Apple Silicon Mac.
| before (median of 5) | after (median of 5) | change | |
|---|---|---|---|
| full frame (200×60, all rows dirty) | 3.73 ms | 1.81 ms | 2.06× faster |
| allocated per frame | 5.89 MB | 2.34 MB | −60% |
| stream 126 × 4 KB chunks, write + snapshot | 478 ms | 237 ms | 2.02× faster |
What limits the new number: the remaining cost is mostly the JS→wasm calls per cell (row_cells_next, get_multi, the grapheme read) plus building one GhosttyCell object and its two colour objects per cell. Those objects are most of the 2.3 MB left. I tried sharing colour objects between cells: it cut allocation another 22% but made frames slightly slower and needed an unbounded cache, so I left it out.
Harness (term.mjs, register.mjs, hooks.mjs)
// term.mjs — REPO=<repo> node --expose-gc --import ./register.mjs term.mjs <path to core.ts>
import { PerformanceObserver } from "node:perf_hooks";
const { GhosttyTerminalCore } = await import(process.argv[2]);
const COLS = +(process.env.COLS ?? 200), ROWS = +(process.env.ROWS ?? 60);
const core = await GhosttyTerminalCore.create(COLS, ROWS, 8, 16, { foreground: { r: 255, g: 255, b: 255 }, background: { r: 0, g: 0, b: 0 }, cursor: { r: 255, g: 255, b: 255 } }, () => {});
let seed = 1;
const rand = () => ((seed = (seed * 1103515245 + 12345) & 0x7fffffff) / 0x7fffffff);
let out = "";
for (let line = 0; line < 2000; line++) {
let l = "", visible = 0;
while (visible < COLS - 30) {
const c = 31 + Math.floor(rand() * 7);
const w = `src/components/file${Math.floor(rand() * 999)}.tsx`;
l += `\x1b[${rand() < 0.3 ? "1;" : ""}${c}m${w}\x1b[0m `; visible += w.length + 1;
}
out += l + "\r\n";
}
core.write(out); core.snapshot();
let gcs = 0;
new PerformanceObserver((l) => (gcs += l.getEntries().length)).observe({ entryTypes: ["gc"] });
const frame = (i) => { core.scroll(i % 2 === 0 ? -1 : 1); return core.snapshot().dirtyRows.size; };
for (let i = 0; i < 200; i++) frame(i);
const FRAMES = 60, times = [];
for (let run = 0; run < 9; run++) {
const t0 = performance.now(); let sink = 0;
for (let i = 0; i < FRAMES; i++) sink += frame(i);
times.push((performance.now() - t0) / FRAMES);
if (sink !== FRAMES * ROWS) throw new Error(`dirty ${sink}`);
}
const frameAllocs = [];
for (let i = 0; i < 30; i++) {
globalThis.gc(); await new Promise((r) => setTimeout(r, 5));
const g0 = gcs, h0 = process.memoryUsage().heapUsed; frame(i); const h1 = process.memoryUsage().heapUsed;
await new Promise((r) => setTimeout(r, 5));
if (gcs === g0) frameAllocs.push((h1 - h0) / 1e6);
}
const chunks = out.match(/[\s\S]{1,4096}/g), wtimes = [];
for (let run = 0; run < 7; run++) { const t0 = performance.now(); for (const c of chunks) { core.write(c); core.snapshot(); } wtimes.push(performance.now() - t0); }
const med = (a) => [...a].sort((x, y) => x - y)[a.length >> 1];
console.log(JSON.stringify({ fullFrameMs: med(times).toFixed(3), allocMBPerFrame: med(frameAllocs)?.toFixed(3), allocSamples: frameAllocs.length, stream126ChunksMs: med(wtimes).toFixed(1) }));
// register.mjs
import { register } from "node:module";
import fs from "node:fs";
register("./hooks.mjs", import.meta.url);
const realFetch = globalThis.fetch;
globalThis.fetch = async (url) => {
const s = String(url);
if (s.startsWith("file:")) { const b = fs.readFileSync(new URL(s)); return { ok: true, status: 200, arrayBuffer: async () => b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength) }; }
return realFetch(url);
};
// hooks.mjs
import { pathToFileURL } from "node:url";
import fs from "node:fs";
export async function resolve(spec, ctx, next) {
if (spec.includes(".wasm?")) {
const file = new URL(spec.split("?")[0], ctx.parentURL);
return { url: "data:text/javascript," + encodeURIComponent(`export default ${JSON.stringify(file.href)};`), shortCircuit: true };
}
if (spec.startsWith("@t3tools/shared/")) {
const root = process.env.REPO;
return { url: pathToFileURL(`${root}/packages/shared/src/${spec.slice(16)}.ts`).href, shortCircuit: true };
}
if ((spec.startsWith("./") || spec.startsWith("../")) && !/\.[mc]?[jt]sx?$/.test(spec)) {
const u = new URL(spec, ctx.parentURL);
if (fs.existsSync(u.pathname + ".ts")) return { url: u.href + ".ts", shortCircuit: true };
}
return next(spec, ctx);
}
Validation#
vp run check:changedpasses (format, lint, knip, typecheck, tests).vp test run src/terminal/ghostty/and theThreadTerminalDrawertests pass (57). That includes the existing "preserves styles, wide cells, and selection after shared memory grows" test, which covers the detach path.- A differential fuzz harness outside the repo ran the original and new
GhosttyTerminalCoreside by side. Inputs were random ANSI streams: truecolor/256/16-colour SGR, bold/faint/inverse/invisible/strike/overline, wide CJK and emoji, graphemes with up to 200 combining marks, cursor moves, erase, alt screen, OSC 8 links and cursor style. It also mixed in random scroll, selection, resize and clear-selection steps. Across 4 seeds, 9,600snapshot()/selectionText()/scrollbarState()comparisons were identical.
Not checked: browser frame timing in a real client. Subagents in this run do not launch dev servers. The change is in pure JS ↔ WASM glue and renders nothing differently.
Authored with Claude Opus 5.5 via the Claude Code harness in T3 Code.
🤖 Generated with Claude Code
- 1
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:M
Approvability#
Verdict: Approved at
8a93dd2Macroscope's review found this PR approvable — Terminal snapshots reuse WASM memory views and exported functions to reduce allocation and lookup overhead. The change preserves existing terminal behavior and refreshes cached views after memory growth, with no obvious material risk requiring human review.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).No actionable comments were generated in the recent review.
Recent review info-
Run configuration-
- Source mode: Auto
- Repository: pingdotgg/t3code
- Branch: main
- File: .coderabbit.config.ts
- Commit: d464631
- Layers: Repository TS config
- Review profile: CHILL
- Plan: Advanced
- Run ID:
508817dc-c5e2-4be1-885c-12292d59d620
Commits-
Reviewing files that changed from the base of the PR and between d46463140776d3d45f0ce705a36e6b411f1d4b5d and 8a93dd27f1d7b832a97796305d1d9853f19dfe2b.
Files selected for processing: 2-
apps/web/src/terminal/ghostty/core.tsapps/web/src/terminal/ghostty/runtime.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.
-
Walkthrough
-
GhosttyRuntime now refreshes cached WebAssembly memory views after memory growth and exposes validated function lookup. GhosttyTerminalCore uses the current views for memory access and passes an optional byte offset to grapheme decoding.
Changes: Ghostty WASM memory access
Priority:Layer / File(s) Summary Runtime memory views and export lookup
apps/web/src/terminal/ghostty/runtime.tsGhosttyRuntimecaches aUint8Arrayview and refreshes it and theDataViewwhen the cached byte view has zero length.fn()validates and returns an exported function, andcall()invokes it.Terminal core memory access
apps/web/src/terminal/ghostty/core.tsGhosttyTerminalCoreuses the runtime’s current byte and data views for snapshot, row, and cell memory access.ghosttyCellTextaccepts an optional byte offset and uses it when reading code points. LowEstimated code review effort: 3 (Moderate) | ~20 minutes
Change: Refactor
Suggested reviewers:
maria-rcks
Merge Risk:
Minimal · up to8a93d-
The changed snapshot path has no established correctness or availability risk and is mergeable.
Pre-merge checks:
3 · 1-
Failed checks: 1 warningCheck name Status Explanation Resolution Description check The description clearly explains the problem, fix, measurements, validation, limitations, and tooling. It does not include the required Scope and approval section, and it does not provide a linked iss… Add a Scope and approval section. Link the triaged issue or maintainer approval with the approval comment, or explain why this focused optimization qualifies for an exemption. Rename Fix to Change if the repository requires the template hea… Passed checks: 3 passed-
Check name Status Explanation Title check The title clearly and concisely describes the primary change: reusing WASM memory views for terminal snapshots. Linked Issues check Check skipped because no linked issues were found for this pull request. Out of Scope Changes check Check skipped because no linked issues were found for this pull request.
Full details: Description check
-
Explanation
The description clearly explains the problem, fix, measurements, validation, limitations, and tooling. It does not include the required Scope and approval section, and it does not provide a linked issue, maintainer approval, or a small-fix exemption rationale. The Fix section also does not use the template's Change heading.
Resolution
Add a Scope and approval section. Link the triaged issue or maintainer approval with the approval comment, or explain why this focused optimization qualifies for an exemption. Rename Fix to Change if the repository requires the template headings exactly.
-
Finishing Touches
-
🧪 Generate unit tests (beta)
-
- Create a new PR
-
- Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
-
@juliusmarminge ready for review. Terminal
snapshot()reused one WASM memory view per kind instead of building several per cell: full 200x60 frame 3.73 ms to 1.81 ms (about 2.1x), 5.89 MB to 2.34 MB allocated per frame (-60%); streaming 126 x 4 KB chunks 478 ms to 237 ms. Old-vs-new core fuzz matched on 9,600 snapshot, selection and scrollbar comparisons. I also drove the terminal in a browser on a merge of this and #26720: it rendered and colored output correctly (I could not capture a screenshot, so that check was by canvas pixels). CI workflows on this fork PR showaction_required, so they are waiting on a maintainer to approve the run. CodeRabbit and Macroscope have no open findings.Note
Written by
gpt-6.1-solon behalf of MariaVerified in a real dev environment#
verified as-is at
8a93dd27f1d7b832a97796305d1d9853f19dfe2b, after reproducing the hot-path overhead ongithub/main(5fe18d79ac). no source changes were needed.- installed and ran both checkouts with isolated state, one background dev server at a time. drove the real web client with repository playwright and
/usr/bin/google-chromeon linux. - created the project through the app against a real git checkout. selected codex
gpt-6.1-soland completed real provider turns on both versions, including shell commands and the visibleTERMINAL_PROVIDER_OKresponse. - opened the integrated terminal and typed a real shell command streaming 2,000 colored lines with bold text, cjk, emoji, and combining marks. output completed, scrolling returned to the same rows, and the prompt remained usable.
- four warmed batches of 80 actual wheel frames at 150 columns × 15 rows measured snapshot medians of 0.60-0.70 ms on main and 0.40 ms on the pr. p95 was 0.90-1.00 ms versus 0.50-0.60 ms. a separate getter-counting run observed 1,046,912 versus 240 wasm buffer reads over 80 dirty snapshots. timing excluded getter instrumentation and recording.
- selection returned
ROW 01987; resizing changed 150 columns to 107 and back. an explicit diagnosticmemory.grow(1)on the active terminal detached the old cached view; the replacement view and subsequent real pty output preserved bold truecolor, wide cells, and graphemes. two split terminals sharing the runtime rendered independently, and closing the second preserved the first. - blacksmith ran the existing ghostty core, abi, and surface suites: 47 tests passed. ci reports 30 successful checks on this head.
before, main:

after, exact pr head:

command and runtime transcript. captures were inspected; uploaded video playback and seeking were exercised in chrome.
Not verified#
native electron, ios/android, macos/windows, relay/tunnel connections, and providers other than codex were not exercised on this linux vm. the original 200×60 mac benchmark, allocation-volume claims, and end-to-end frame timing were not reproduced; the numbers above measure snapshots in the running client. git.cafe renders these external uploads as links; their direct image rendering, video playback, and seeking were verified in chrome. t3's separate inline media player was not exercised.
- installed and ran both checkouts with isolated state, one background dev server at a time. drove the real web client with repository playwright and
maria-rcks merged thisd1049c4
maria-rcks closed this
Sign in to join this conversation.
macroscopeapp[bot](GitHub profile, opens in a new tab) approved these changes