Repository navigation
fix(terminal): stop inline-image decoders exhausting the renderer's wasm memory budget - #23499
Conversation
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. Important Review skippedReview was skipped as selected files did not have any reviewable changes. ⛔ Files ignored due to path filters (1)
⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between 5f33bfcdfc5d7c19d655a99a5753fc9ed30ccbc7 and b8e864a. ⛔ Files ignored due to path filters (1)
You can disable this status message by setting the Use the checkbox below for a quick retry:
📝 WalkthroughWalkthroughThe xterm image patch changes IIP and SIXEL decoder lifetimes and adds allocation-failure handling. It adds capacity and input-size checks for Kitty image decoding. It also updates image rendering and bitmap cleanup. Contract tests cover decoder use, palette state, image painting, and terminal writes under allocation failure. The regeneration documentation describes the decoder changes and names the contract test. Estimated code review effort Priority: ➖ Normal Merge Risk: 🟡 Moderate · up to The SIXEL decoder pool can still hold on to WebAssembly memory, and a failed decoder initialization may still throw through the parser. Both undercut the stated goal of the PR. Fix them before merging. Architecture SummaryArchitecture risk: 🔵 Low · up to The change affects 2 systems. Changed systems: Architecture concerns Review detailsSystems and components
Before / after behavior
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 6 functions across 1 files. (2 skipped: 2 unsupported.) ✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
ℹ️ No critical issues — one minor suggestion inline.
Reviewed changes
- Shared SIXEL decoder pool.
SixelHandlerno longer creates a per-terminal decoder at activation; terminals borrow one from a process-global pool while a sequence is open, and color registers move onto the handler so they still survive between images. - IIP decoder release.
KEEP_DATAdrops to0, so the base64 and QOI decoders free their wasm memory after each image;init()and QOIdecode()failures now drop the image instead of escaping the parser. - KITTY init guard. A failed
Base64Decoder.init()aborts the upload and repliesENOMEM(once, and only when ani=id is present) rather than throwing into the parser. - Contract test + docs.
xterm-image-wasm-budget-contract.test.mjspins idle-terminal wasm hold (300 terminals), per-image decoder release, color-register persistence, and non-wedging under stubbed wasm exhaustion.
I confirmed the patch is self-consistent: pnpm install --frozen-lockfile applies the new 5379dd79… hash, regenerate-xterm-patches passes (33/33), and the four image contract suites plus the new wasm-budget test pass locally (25/25). The applied source and bundle agree.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
3123d62 to
5f33bfc
Compare
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟠 Major · Fix the pool release: a decoder can be pooled… · @[email protected]:256-265
config/patches/xterm-src/@[email protected]:256-265
🩺 Stability & Availability | 🟠 Major | ⚡ Quick winFix the pool release: a decoder can be pooled after
release(), and the idle list can overflow.
releaseDecodercallsdec.release()whenmemoryUsageexceedsMEM_PERMA_LIMIT. It then still pushes the decoder into the idle list. The pooled decoder has no memory, which is acceptable only ifinit()reallocates it. The idle list is capped atMAX_IDLE_DECODERS. A decoder that does not fit is dropped withoutrelease(). That decoder keeps its wasm memory until garbage collection. This defeats the purpose of the PR, because V8 caps live wasm memories.Release the decoder when the pool is full.
Proposed fix
function releaseDecoder(dec: Decoder, memoryLimit: number): void { if (dec.memoryUsage > MEM_PERMA_LIMIT) { dec.release(); } const idle = idleDecoders.get(memoryLimit) ?? []; if (idle.length < MAX_IDLE_DECODERS) { idle.push(dec); idleDecoders.set(memoryLimit, idle); + } else { + dec.release(); } }
🟠 Major · Guard this._dec.init() against allocation… · @[email protected]:330
config/patches/xterm-src/@[email protected]:330
🩺 Stability & Availability | 🟠 Major | ⚡ Quick winGuard
this._dec.init()against allocation failure.
acquireDecoderis inside a try/catch.init()on a pooled decoder is not.init()can allocate wasm memory and throw aRangeError. That error escapes through the parser and wedges the write queue. This is the failure the PR tries to prevent. The decoder also stays inthis._decuntil the next_returnDecoder.Wrap
init()in the same try/catch. On failure, set_abortedand return the decoder.Proposed fix
- this._dec.init(fillColor, this._palette, this._opts.sixelPaletteLimit); + try { + this._dec.init(fillColor, this._palette, this._opts.sixelPaletteLimit); + } catch (e) { + console.warn(`SIXEL: could not initialize decoder - ${e}`); + this._aborted = true; + this._returnDecoder(); + }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: f68a1efb-d143-40df-9475-0e64f6eec50c
📥 Commits
Reviewing files that changed from the base of the PR and between 3123d62 and 5f33bfcdfc5d7c19d655a99a5753fc9ed30ccbc7.
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (2)
config/patches/@[email protected]config/patches/xterm-src/@[email protected]
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Added
_qoiDec.release()to the IIP QOI decode failure path, so a throw fromdecode()frees the QOI wasm instance alongside the base64 one — closing the last path that could pin a wasm memory after a failed QOI image. - Regenerated the addon bundle patch and repointed the lockfile patch hash (
5379dd79…→e5254a46…).
The delta is self-consistent: regenerate-xterm-patches.mjs --check reports the source and bundle patches are in sync, and the new lockfile hash equals the sha256 of the regenerated bundle patch. The prior review's QOI-release concern is addressed; its thread is resolved.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
| + const idle = idleDecoders.get(memoryLimit) ?? []; | ||
| + if (idle.length < MAX_IDLE_DECODERS) { | ||
| + idle.push(dec); | ||
| + idleDecoders.set(memoryLimit, idle); | ||
| + } |
There was a problem hiding this comment.
Idle decoder pool can grow If addons use different
pixelLimit values over a renderer’s lifetime, this pool keeps up to two idle SIXEL decoders for each value, even after the terminals are disposed. Each decoder retains a wasm memory, so those memories can accumulate and eventually consume the process-wide budget. Consider a global pool limit or a way to release unused entries.
…asm memory budget V8 reserves an 8 GiB guard region per wasm memory inside its 1 TiB sandbox, so an Electron renderer can hold only ~124 live wasm memories regardless of free RAM. @xterm/addon-image instantiated a SIXEL decoder per terminal at activation (and kept IIP decoders after the first image), so ~120+ terminals exhausted the budget: new panes raised 'WebAssembly.instantiate(): Out of memory' rejections, and the next Kitty/IIP image threw 'WebAssembly.Memory(): could not allocate memory' out of the parser, permanently wedging that terminal's write queue. The addon-image source patch now borrows SIXEL decoders from a shared pool only while a sequence is open (color registers stay on the terminal), drops IIP decoders after each image, and turns a failed decoder allocation into a dropped image instead of a parser throw. Bundles regenerated with regenerate-xterm-patches.mjs --write.
5f33bfc to
b8e864a
Compare
…3745, #23783, #22971, #22565, #22846, #23724, #23721, #23693, #23810) into #23059 #23671 (group chat rows by the turn that produced them) is ported onto #23059's turn-scope model, so there is one grouping mechanism, not two: - A host that states each row's turn scope groups by that scope, as before. #23671's journal-order derivation (rows between one turn record and the next belong to it) moves from the timing selector into src/shared/native-chat-turn-grouping.ts and runs only for a host that states no scope, replacing the positional fallback there. - #23671's anchor rules live in structuredAgentTurnAnchors, which membership, settled timing and the live clock all read: a turn whose opener key nothing resolves yet takes the send still in flight ahead of its record (Codex before its echo), else its own record. - The live turn is one key again. #23671 made row liveness follow the owning turn, so the bar key and the liveness key are always the same; nativeChatTurnMembership now returns only liveTurnKey (barTurnKey, activeTurnOpenedBy and turnKeysByItemId are gone). - A turn with no user bubble draws its bar above its first row (nativeChatTurnBarRows, desktop and mobile), and a turn's diff rollup goes under its last row. - The Codex full-history restore writes each record ahead of its items; that also fixes the derived turn scope on #23059's journal. #23026 (Stop from the moment a message is sent) is ported onto #23059's command turns: the cancel paths ask the translator for a command's provider turn instead of the removed compaction tracker, and a Stop that names no turn still ends a running /compact through its child. performCancel moved to structured-agent-session-turns-cancel.ts to keep the turns module under the line limit. #22090's awaitingInput replaces showTurnStatus/showLiveTurnActivity; the waiting-behind-/compact rows are kept.

Found by Orca crash scan 28 on the released v1.4.215. User identities are left out.
Description
A user with about 220–230 open terminals saw many
RangeError: WebAssembly.instantiate(): Out of memory: Cannot allocate Wasm memory for new instanceandRangeError: WebAssembly.Memory(): could not allocate memoryerrors. After those errors, terminals stopped showing output, Orca's stall detector kept rebuilding them (terminal_pane_recovery_remount reason=write-stalled, repeatedterminal_replay_guard_wedged_release), and the rebuilt terminals failed the same way.Root cause. Electron renderers run V8 with its memory sandbox turned on. Inside that sandbox, every live WebAssembly memory reserves a large guard region, so a process can hold only about 124 live wasm memories, however much RAM is free. The terminal picture add-on (
@xterm/addon-image) used up that budget:KEEP_DATA(4 MB) is larger than the starting buffer (1 MB).With inline images on (the default), about 124 terminals used up the budget. After that:
WebAssembly.Memory(): could not allocate memorysynchronously out of xterm's parser. xterm's write buffer then never fired the callback for that write or any later one, so the terminal stayed frozen until something rebuilt it.A React #185 error also appeared right after a burst of these failures. The rebuild storm is a plausible trigger, but that link is not proven: the attribution for that error is marked unreliable, and I did not reproduce #185 itself.
ELI5
Electron gives each window about 124 "parking spaces" for a kind of fast decoding engine (WebAssembly), no matter how much RAM the computer has. The picture-in-terminal add-on parked one engine for every terminal, even terminals that never showed a picture. With about 230 terminals the spaces ran out. After that, the next picture a terminal received broke that terminal's text pipeline, so it stopped showing output until Orca rebuilt it, and the rebuilt terminal hit the same problem. Now all terminals share a couple of engines and only borrow one while a picture is arriving. If there's still no space, that one picture is skipped and the text keeps flowing.
What Changed
Before (as the user experiences it): past about 120 terminals in one window, terminals go blank or freeze as soon as a program prints an image or sends a Kitty graphics query. Orca then rebuilds those terminals over and over.
After: terminals hold no image decoders while idle, so the number of terminals no longer uses up the budget. The whole renderer holds about 1 decoder at rest. If the budget really is exhausted (for example, by some other wasm user), that one image is dropped and the text keeps flowing.
Mechanism. This PR changes the addon-image source patch (
config/patches/xterm-src/@[email protected]). The bundle patch and the lockfile hash were regenerated withregenerate-xterm-patches.mjs --write, and--checkconfirms they are in sync.memoryLimit, with at most 2 idle. The pool is primed once per process with an async compile. A terminal borrows a decoder when an image starts (hook) and returns it when the image ends or the terminal resets (unhook/reset, with atry/finally). Each terminal keeps its own color registers in aUint32Arraypalette, so registers still carry over between images until RIS/DECSTR, as before. If no decoder can be allocated, the image is dropped with aconsole.warn.KEEP_DATAis now 0, so the base64 and QOI decoders free their wasm memory after each image. Ifinit()or a QOIdecode()fails, the image is dropped (single-part and multipart) instead of the error escaping from the parser, and both the base64 and QOI decoders are released so a faileddecode()cannot pin a wasm memory.Base64Decoder.init()fails, the upload is aborted. When the upload has an id, Kitty gets anENOMEMreply. No error is thrown.config/scripts/xterm-image-wasm-budget-contract.test.mjs. There is also a short section indocs/reference/xterm-patch-regeneration.md.No Orca TypeScript changed.
pane-inline-images.tsalready catches synchronous attach errors, and activation no longer has a wasm step that can fail.Why
The limit is on how many wasm memories are alive at once, not on RAM. So the fix has to make sure idle terminals don't hold any. Alternatives I considered:
A shared, borrowed pool keeps the cost constant no matter how many terminals are open. Dropping an image on allocation failure turns a permanent freeze into one missing picture.
Fix evidence
All runs used Electron 43.7.0, the same Electron the user runs, with
ORCA_BACKGROUND_LAUNCH=1and hidden BrowserWindows. The "before" bundle is the released addon, whose patch is identical between v1.4.215 andmain.1) Per-process cap (raw
new WebAssembly.Memoryheld alive):2) Each real xterm
Terminal+ImageAddonholds 1 wasm memory (BEFORE):3) Functional probe: write kitty / sixel / IIP images, then plain text:
4) New contract test run against both bundles:
Commands:
Trade-offs
ENOMEMreply. Before, the terminal froze instead. Under exhaustion, a chunked Kitty upload can also decode only part of its data.Adversarial review
1 loop, clean on the first pass (3 non-blocking notes).
init().dispose→resetreturns the decoder to the pool.unhookreturns the decoder on every path (try/finally)._abortedand sends only oneENOMEMreply.oxfmtandcheck:code-quality:changedare clean. The new tests fail on the old code.Linked Issue
None. Found by the internal crash scan.
Visual Proof
N/A. The fix is in the terminal parser, and the only visible change is that terminals no longer freeze. The before/after probe output above stands in for screenshots.
Testing
I manually tested these changes locally (Electron 43.7.0 before/after probes at N=20 with EXHAUST=1, 50, 250 and 400)
Automated tests added/updated
config/scripts/xterm-image-wasm-budget-contract.test.mjs: 4/4 after the fix, 3/4 fail on the released bundle.xterm-image, regenerate-xterm-patches and pane-manager suites: 85 files, 940 passed, 1 skipped.
terminal-capability-replies, terminal-inline-image-da1, terminal-appearance and terminal-ime-xterm-transaction-events: 71/71 passed.
regenerate-xterm-patches.mjs --check: in sync. oxlint and oxfmt clean.After rebasing on the latest
main: the contract test and regenerate test pass (37/37), and the patches are in sync.Platforms: the change is pure renderer JavaScript, so it behaves the same on macOS, Linux and Windows, and for local, SSH, WSL and folder workspaces. Probes ran on macOS.
Review
Agent skill upstream boundary
docs/reference/agent-skill-sharing-upstream-boundary.mdand copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.Notes
Security: no new inputs are trusted, and an allocation failure now fails closed by dropping the image. Cross-platform: renderer JS only. SSH: the parser runs in the renderer, so remote terminals get the same fix. Mobile: not affected. Backwards compatibility: SIXEL color-register behavior is kept. Performance: covered in Trade-offs.
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)