Skip to content

Render Kitty Unicode placeholders in the terminal image addon - #23616

Closed
emmahyde wants to merge 1 commit into
stablyai:mainfrom
emmahyde:feat/kitty-unicode-placeholders
Closed

emmahyde wants to merge 1 commit into
stablyai:mainfrom
emmahyde:feat/kitty-unicode-placeholders

Conversation

@emmahyde

Copy link
Copy Markdown
Contributor

ELI5

Some terminal programs show an image by printing special invisible characters and asking the terminal to paint the picture onto those characters, so the picture scrolls with the text. Orca's terminal didn't understand that request: it drew the picture in the wrong place and showed the special characters as little boxes. Now it paints the picture where those characters are.

What Changed

Before: a Kitty graphics command with U=1 was treated as a normal cursor placement (image painted at the cursor), and the U+10EEEE placeholder cells the client prints afterwards rendered as literal private-use glyphs. Any TUI that uses placeholders (oh-my-pi, timg -pk) showed a stray thumbnail plus rows of coloured boxes.

After: a=p,U=1 / a=T,U=1 records a virtual placement (nothing drawn, cursor unmoved). On every rendered row the addon scans for U+10EEEE cells, decodes the image id from the foreground colour, the placement id from the underline colour and the grid position from the row/column diacritics, merges adjacent cells into runs, and paints the matching slice of the image fitted into the c × r cell box. Placeholder cells are ordinary text so they scroll and reflow; deleting the image (a=d), reset, dispose or byte-budget eviction drops the tiles; an unknown id paints nothing.

Mechanism. All inside the existing @xterm/addon-image source patch (regenerated with regenerate-xterm-patches.mjs --write; --check is in sync):

  • KittyGraphicsTypes.ts — KittyKey.UNICODE_PLACEHOLDER = 'U', cmd.unicodePlaceholder, the 297-entry row/column diacritic table and decodePlaceholderLocation. The table lives here rather than a new file because the derived patch cannot introduce a source file the published tarball lacks.
  • KittyGraphicsHandler.ts — _placeVirtual branch beside _displayImage; the crop / grid maths shared by both are factored into _cropImage / _placementGrid. _cropImage returns the bitmap synchronously when nothing is cropped so the uncropped path keeps its microtask timing (the existing lifecycle contract test depends on it).
  • KittyImageStorage.ts — _virtualPlacements store, addVirtualPlacement, _renderPlaceholderLine (mirrors kitty's screen_render_line_graphics run merging and omitted-diacritic inheritance), _placeholderCell decoder.
  • ImageStorage.ts — onRenderLine hook called once per rendered row, addUnplacedImage / getImageSpec so placeholder payloads never occupy the buffer.
  • ImageRenderer.ts — drawCellImage fits the image into the cell box (aspect preserved, centred) and clips the slice one row shows.

Also: a paragraph in docs/reference/xterm-patch-regeneration.md and a new contract test.

Why

Kitty Unicode placeholders are the only image mode whose output is plain text cells, which is what a TUI needs to put an image inside a border, a table or a scrolling transcript. Without it Orca users of those tools get either broken output or no images at all (oh-my-pi ships Orca as imageProtocol: null because of this). Handling it in the addon patch is the same route the existing Kitty/IIP fixes take; a runtime shim would have to reach into xterm's _core buffer internals from Orca, which upstream renames freely between betas.

Not done here: multiple simultaneous virtual placements per image id (p= selects among them in kitty; this keeps one per image and replaces on re-place), and the SGR 58-without-underline-style quirk in xterm core (a cell with only an underline colour never gets an extended-attr entry, so the placement id is read from the raw extended entry when present — worth an upstream note).

Linked Issue

Fixes #23615

Visual Proof

Before: see the repro in #23615 — partial thumbnail at the cursor plus rows of green U+10EEEE glyphs (my capture was a macOS temp screenshot that was cleaned up before I could attach it; happy to re-capture on request).

After: the contract test drives the built addon through transmit → placeholders → render and asserts the two draw calls land on the placeholder cells ([0,0,20,5 → 0,5,20,5] and [0,5,20,5 → 0,10,20,5] for a 20×10 image letterboxed into a 2×2 box of 10 px cells). I have not yet run a packaged Orca build with this patch; CI's xterm_patch_sync lane rebuilds and byte-compares the bundle.

Testing

  • node config/scripts/regenerate-xterm-patches.mjs --write --work-dir=/tmp/xterm → pnpm install → --check: "xterm patches are in sync with the pinned upstream build."

  • vitest run on config/scripts/xterm-image-kitty-placeholder-contract.test.mjs (new, 4 cases) + xterm-image-{memory,lifecycle,resize}-contract.test.mjs + regenerate-xterm-patches.test.mjs: 58/58 pass.

  • pnpm tc: clean. pnpm run check:code-quality:changed: 0 new findings.

  • Platform: macOS arm64 only. The change is inside the renderer-side xterm addon, so it is not SSH- or platform-specific, but I have not exercised Linux/Windows.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

AI Disclosure

Written with Claude (Opus 4.5 family) via Claude Code: protocol research against kitty's source, the implementation, the contract test, and the regeneration/verification runs. I reviewed the diff and drove the debugging of the test harness and the microtask regression.

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Security: the decoder reads only cell attributes already in the buffer; image bytes go through the same size/pixel limits as direct placements and a virtual placement holds no extra pixel budget beyond the stored image. Performance: the per-row scan exits immediately when no virtual placement exists. Backwards compat: U absent → identical behaviour to before.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred) — typecheck + changed-file quality gate + the image contract tests pass locally; full pnpm lint/test/build left to CI

Kitty's graphics protocol lets a client place an image without moving the
cursor (`a=p,U=1`) and then paint it through ordinary text cells: U+10EEEE
with row/column diacritics, the image id in the foreground colour and the
placement id in the underline colour. TUIs that need images to scroll and
reflow with text (oh-my-pi, timg -pk) rely on it. The addon's Kitty parser
had no `U` key, so those commands drew at the cursor and the placeholder
cells rendered as literal private-use glyphs.

The addon now records a virtual placement for `U=1` and, per rendered row,
decodes placeholder cells into runs and paints the matching slice of the
image fitted into the c x r cell box. Virtual placements are dropped with
the image on delete, reset, dispose and byte-budget eviction; an unknown id
paints nothing. The diacritic table sits at the end of
KittyGraphicsTypes.ts because the derived patch cannot introduce a file the
published tarball lacks.

The crop helper stays synchronous when nothing is cropped so the uncropped
placement path keeps its microtask timing, which the lifecycle contract test
depends on.

Patch trio regenerated with regenerate-xterm-patches.mjs --write; --check is
in sync with the pinned upstream build.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The placeholder feature works end to end, but the new unplaced-image path is not wired into the shared-storage lifecycle. One issue silently breaks placeholder rendering whenever a normal Kitty image is transmitted afterwards; the other retains the placement's pixels after deletion. Both reproduced against the freshly installed bundle; details inline.

Reviewed changes

  • Kitty Unicode placeholder rendering — a=p,U=1 / a=T,U=1 now records a virtual placement (nothing drawn at the cursor); each rendered row scans U+10EEEE cells, decodes image id / placement id / grid position from fg colour, underline colour and the row-column diacritics, merges cells into runs, and paints the fitted image slice per row.
  • Shared-storage hooks — ImageStorage gains onRenderLine, addUnplacedImage and getImageSpec; KittyImageStorage gains the _virtualPlacements store and the run-merging renderer, and now takes the ImageRenderer; ImageRenderer.drawCellImage does the aspect-fit and one-row clipping.
  • Protocol plumbing — KittyKey.UNICODE_PLACEHOLDER, cmd.unicodePlaceholder, the 297-entry diacritic table and decodePlaceholderLocation; the crop / grid maths shared with the display path are factored into _cropImage / _placementGrid.
  • Tests + docs — new xterm-image-kitty-placeholder-contract.test.mjs (4 cases), a paragraph in xterm-patch-regeneration.md, and the lockfile patch-hash bump.

I checked the diacritic table against kitty's published gen/rowcolumn-diacritics.txt (exact match) and the run-merging against screen.c's screen_render_line_graphics, including the (highByte - 1) << 24 image-id reconstruction and the omitted-diacritic inheritance — those are faithful.

ℹ️ Nitpicks

  • The contract test covers transmit → placeholders → render, deletion and an unknown id, but not a normal image transmitted after a virtual placement, nor that deletion reclaims the shared-storage entry — both gaps sit exactly where the two issues above live.
  • The per-row scan runs for every rendered row once any virtual placement exists (early-return only when none do). Worth a glance if a TUI holds a placement on screen while repainting heavily, though it is not a correctness problem.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

+ actual: img,
+ actualCellSize: { ...cellSize },
+ marker: undefined,
+ tileCount: 0,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Storing the unplaced image with tileCount: 0 collides with the zero-tile garbage sweep in ImageStorage.addImage, which deletes every stored spec with tileCount < 1 on each call. So any ordinary Kitty image transmitted after a virtual placement silently deletes the placement's pixels, and because the unplaced storage id is never registered in _storageIdToKittyId, the _virtualPlacements entry is left dangling and the placeholders then render nothing. I reproduced this against the installed bundle: after a=T,f=100,i=7,U=1 + placeholder cells + render (2 draws), adding a plain a=T,f=100,i=8,c=1,r=1 dropped the next render to 1 draw.

Technical details
# Unplaced images are collected as zero-tile garbage

## Affected sites
- `config/patches/xterm-src/@[email protected]:284` — `addUnplacedImage` writes `tileCount: 0`
- patched `src/ImageStorage.ts` `addImage` — unconditionally sweeps `this._images` for `spec.tileCount < 1` and calls `_delImg`
- patched `src/kitty/KittyImageStorage.ts` `_handleStorageImageDeleted` — can only map a deleted storage id back through `_storageIdToKittyId`, which `addVirtualPlacement` never populates, so the sweep cannot clear the stale `_virtualPlacements` entry even when it fires

## Required outcome
- A later `addImage` must not evict a live virtual placement's pixels, and if the underlying storage entry does disappear the matching `_virtualPlacements` entry must be removed in the same step.

## Suggested approach
- Give the unplaced spec a positive tile count / a dedicated flag the sweep skips, and register the storage id in the kitty maps so the existing eviction handler can map back and drop `_virtualPlacements`.

## Open questions for the human
- Should unplaced entries participate in the `tileCount`-based cleanup invariant at all, or be excluded from it entirely?

+ }
+ // Kitty draws cell images behind the text, but the placeholder code point is
+ // ordinary text to xterm, so the image has to cover its glyph.
+ const storageId = this._storage.addUnplacedImage(image, { scrolling: false, layer: 'top', zIndex: 0, cursorPos: 'iip' });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

addVirtualPlacement parks the bitmap via addUnplacedImage but never records the returned storage id in _kittyIdToStorageId / _storageIdToKittyId, and deleteById frees storage only through _kittyIdToStorageId. So a=d removes the placement (painting stops, which is what the new test asserts) but leaves the unplaced image in ImageStorage._images, still counted against the pixel budget until some unrelated eviction happens to reap it. Reproduced: the shared-storage image count stayed at 1 after a=d,d=i,i=7,q=2. deleteAll and _evictUndisplayedImages have the same gap.

Technical details
# Deleted virtual placements leak their shared-storage entry

## Affected sites
- `config/patches/xterm-src/@[email protected]:886` — `addVirtualPlacement` calls `_storage.addUnplacedImage(...)` and stores only `_virtualPlacements`, leaving the kitty↔storage maps untouched
- `...src.patch:898` — `deleteById` deletes `_virtualPlacements` then frees storage only via `_kittyIdToStorageId`, which has no entry for a virtual placement
- `...src.patch` `deleteAll` and `_evictUndisplayedImages` — clear/evict `_virtualPlacements` without calling `this._storage.deleteImage(placement.storageId)`

## Required outcome
- Every path that drops a virtual placement frees its `storageId`, so the pixels and their share of the pixel budget are reclaimed immediately rather than on a later unrelated eviction.

## Suggested approach
- Call `this._storage.deleteImage(placement.storageId)` wherever a virtual placement is removed (`deleteById`, `deleteAll`, `_evictUndisplayedImages`).

@coderabbitai

coderabbitai Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The addon-image patch adds Kitty Unicode placeholder support. Commands can create virtual placements, and matching placeholder cells identify image tiles and their grid positions for rendering. The patch also updates image scaling, decoding, storage limits, and teardown handling. Contract tests cover placeholder rendering, regular cursor placement, image deletion, and unknown image IDs. The scope documentation describes the placeholder format and rendering behavior.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to ee90f

Some Kitty placeholders can disappear after another upload or fail to render, while deleted placements can continue consuming image storage. Resolve these defects before merging.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to ee90f

Virtual images can remain allocated after a terminal command deletes them. Subsequent image activity can also discard images that are still meant to be visible. The exposure is within a terminal session and is limited by the configured image-storage budget, but the new lifecycle needs correction.

Retained concerns

  • Medium · security · observed: Virtual placements are not consistently owned by shared-image cleanup: explicit deletion and Kitty eviction retain decoded entries, while ordinary tile cleanup can remove a live virtual entry and leave its placement reference stale. Terminal-controlled image traffic can therefore retain resources after deletion or disrupt other image rendering within the storage budget.
Security review details

Security Blast Radius

  • inferred — A producer of terminal output that can send Kitty image commands can exercise the new placement lifecycle in that terminal session. The inspected paths do not establish cross-tenant access, added privileges, or infrastructure changes.

Security Findings and Attack Paths

  • inferred — Repeated virtual placement and deletion can leave decoded images occupying shared storage after their Kitty IDs cease to be usable. Later image insertions may need to evict entries to stay within the pixel budget; regular-image cleanup can also remove a live virtual entry because it has no buffer tiles.

Trust Boundaries and Controls

  • observed — Terminal command data is converted into decoded images and, for U=1, into a placement looked up during text rendering. Generation checks reject interrupted decodes, invalid or unknown image references do not draw, and image storage applies a pixel budget.

Resilience and Maintainability Implications

  • observed — The deletion contract test checks that drawing stops, but does not establish that the associated shared bitmap is deleted or closed.

Hardening Proposals

  • proposed — Give each virtual shared-storage ID a reversible Kitty ownership mapping, and make explicit deletion, byte-budget eviction, shared-storage sweeps, reset, and disposal converge on one bitmap-release path. Exercise those transitions with image-closure and stale-reference assertions.
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR also changes general image-decoder and bitmap behavior that is not required by [#23615]. The summary lists stale-result rejection after reset, decoder allocation and transmission limits, PNG di… Limit this PR to placeholder rendering and the lifecycle cleanup required for virtual placements. Move the general decoder limits, stale-result handling, and unrelated bitmap lifecycle changes to a separate issue and pull request, or provid…
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 1 files. (2 skipped: 2… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: rendering Kitty Unicode placeholders in the terminal image addon.
Description check ✅ Passed The description is detailed and covers the user impact, implementation, rationale, linked issue, testing, platform scope, security, performance, and compatibility. The visual proof does not include an…
Linked Issues check ✅ Passed The PR implements the coding requirements in [#23615]. U=1 commands create virtual placements instead of drawing at the cursor. Rendered U+10EEEE cells are decoded into image, placement, and grid co…
Full details: Out of Scope Changes check

Explanation

The PR also changes general image-decoder and bitmap behavior that is not required by [#23615]. The summary lists stale-result rejection after reset, decoder allocation and transmission limits, PNG dimension and decompressed-output limits, and broader bitmap disposal changes. These changes are separate from Kitty placeholder rendering and are not established as required support for the linked issue.

Resolution

Limit this PR to placeholder rendering and the lifecycle cleanup required for virtual placements. Move the general decoder limits, stale-result handling, and unrelated bitmap lifecycle changes to a separate issue and pull request, or provide a direct requirement that connects each change to [#23615].

Full details: Docstring Coverage

Explanation

Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 1 files. (2 skipped: 2 unsupported.)

  • Fix all pre-merge checks with AI

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: fc5a807c-74ce-41f2-9430-fb70b15fb443

📥 Commits

Reviewing files that changed from the base of the PR and between 8b410b4 and ee90f53.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (4)
  • config/patches/@[email protected]
  • config/patches/xterm-src/@[email protected]
  • config/scripts/xterm-image-kitty-placeholder-contract.test.mjs
  • docs/reference/xterm-patch-regeneration.md

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment on lines +268 to +291
+ public addUnplacedImage(img: HTMLCanvasElement | ImageBitmap, opts: IAddImageOpts): number {
+ // never allow storage to exceed memory limit
+ this._evictOldest(img.width * img.height);
+
+ let cellSize = this._renderer.cellSize;
+ if (cellSize.width === -1 || cellSize.height === -1) {
+ cellSize = CELL_SIZE_DEFAULT;
+ }
+
+ const imageId = ++this._lastId;
+ this._images.set(imageId, {
+ orig: img,
+ origCellSize: cellSize,
+ actual: img,
+ actualCellSize: { ...cellSize },
+ marker: undefined,
+ tileCount: 0,
+ bufferType: this._terminal.buffer.active.type,
+ layer: opts.layer,
+ zIndex: opts.zIndex
+ });
+ this.onImageAdded?.();
+ return imageId;
+ }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
fd -t f 'ImageStorage.ts' | xargs -r rg -n -C6 '_evictOnAlternate|tileCount|marker!|\.marker\.'

Repository: stablyai/orca

Length of output: 151


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- candidate files ---'
fd -t f | rg '(^|/)(ImageStorage|KittyImageStorage|ImageRenderer|KittyGraphicsTypes)\.(ts|patch)$|xterm.*image.*patch'
printf '%s\n' '--- changed paths ---'
git diff --name-only 08300512eb9a63c43ec7f4ae7ef4226a852335b6 ee90f53619799b34b28c499f9b427e07afeef61f -- 'src/*' 'config/patches/*'
printf '%s\n' '--- ImageStorage symbols in checkout ---'
rg -n -C8 'addUnplacedImage|_evictOnAlternate|addImage\(|tileCount|onImageDeleted|onImageAdded|getImageSpec' . -g 'ImageStorage.ts' -g 'KittyImageStorage.ts' -g '*.patch'
printf '%s\n' '--- relevant diff ---'
git diff --unified=25 08300512eb9a63c43ec7f4ae7ef4226a852335b6 ee90f53619799b34b28c499f9b427e07afeef61f -- \
  src/ImageStorage.ts src/kitty/KittyImageStorage.ts \
  config/patches/xterm-src/@[email protected]

Repository: stablyai/orca

Length of output: 45656


🏁 Script executed:

set -eu
fd -t f | rg '(^|/)(ImageStorage|KittyImageStorage|ImageRenderer|KittyGraphicsTypes)\.(ts|patch)$|xterm.*image.*patch'
git diff --name-only 08300512eb9a63c43ec7f4ae7ef4226a852335b6 ee90f53619799b34b28c499f9b427e07afeef61f -- 'src/*' 'config/patches/*'
rg -n -C8 'addUnplacedImage|_evictOnAlternate|addImage\(|tileCount|onImageDeleted|onImageAdded|getImageSpec' . -g 'ImageStorage.ts' -g 'KittyImageStorage.ts' -g '*.patch'
git diff --unified=25 08300512eb9a63c43ec7f4ae7ef4226a852335b6 ee90f53619799b34b28c499f9b427e07afeef61f -- src/ImageStorage.ts src/kitty/KittyImageStorage.ts 'config/patches/xterm-src/@[email protected]'

Repository: stablyai/orca

Length of output: 45656


🏁 Script executed:

#!/bin/sh
set -eu
p='config/patches/xterm-src/@[email protected]'
printf '%s\n' '--- patch locations ---'
rg -n '_evictOnAlternate|addUnplacedImage|addImage\(|tileCount|onImageDeleted|onImageAdded|getImageSpec|virtual|placeholder|delete' "$p"
printf '%s\n' '--- patch context ---'
python3 - "$p" <<'PY'
from pathlib import Path
p = Path(__import__('sys').argv[1])
lines = p.read_text().splitlines()
need = ('_evictOnAlternate','addUnplacedImage','addImage(', 'onImageDeleted','getImageSpec')
ranges = []
for i, line in enumerate(lines):
    if any(x in line for x in need):
        ranges.append((max(0,i-12), min(len(lines),i+35)))
seen = set()
for a,b in ranges:
    for i in range(a,b):
        if i not in seen:
            print(f'{i+1}: {lines[i]}')
            seen.add(i)
    print('---')
PY
printf '%s\n' '--- reviewed patch diff summary ---'
git diff --stat 08300512eb9a63c43ec7f4ae7ef4226a852335b6 ee90f53619799b34b28c499f9b427e07afeef61f -- "$p"

Repository: stablyai/orca

Length of output: 21092


🏁 Script executed:

grep -n -E -C12 '_evictOnAlternate|addUnplacedImage|tileCount|onImageDeleted|_deleteImage' 'config/patches/xterm-src/@[email protected]'

Repository: stablyai/orca

Length of output: 5990


🏁 Script executed:

set -eu
p='config/patches/xterm-src/@[email protected]'
printf '%s\n' '--- ImageStorage patch hunk ---'
sed -n '300,430p' "$p"
printf '%s\n' '--- all cleanup-name matches in source patch ---'
rg -n -i -C5 'evict|tileCount|bufferType|deleteImage' "$p" | sed -n '1,260p'
printf '%s\n' '--- bundled cleanup-name matches ---'
rg -n -i -o '.{0,100}(evict|tilecount|buffertype).{0,180}' 'config/patches/@[email protected]' | sed -n '1,120p'

Repository: stablyai/orca

Length of output: 45100


🏁 Script executed:

set -eu
p='config/patches/xterm-src/@[email protected]'
sed -n '300,430p' "$p"
rg -n -i -C5 'evict|tileCount|bufferType|deleteImage' "$p" | sed -n '1,260p'
rg -n -i -o '.{0,100}(evict|tilecount|buffertype).{0,180}' 'config/patches/@[email protected]' | sed -n '1,120p'

Repository: stablyai/orca

Length of output: 44982


🌐 Web query:

xterm addon-image 0.10.0-beta.300 ImageStorage _evictOnAlternate

💡 Result:

`_evictOnAlternate()` is an internal `ImageStorage` cleanup routine in `@xterm/addon-image` **0.10.0-beta.300**. When an image is added on the alternate screen, it resets the tile counts for previously stored alternate-screen images, then scans the active buffer to recount the tiles still present. Images left with no tiles can then be removed, preventing stale alternate-buffer images from lingering in storage. ([app.unpkg.com](https://app.unpkg.com/%40daiyam/xterm-tab-addon-image%400.10.0-beta.169.0/files/lib/addon-image.mjs.map?utm_source=openai))

It’s called because marker-based cleanup doesn’t work reliably on the alternate buffer. ([app.unpkg.com](https://app.unpkg.com/%40daiyam/xterm-tab-addon-image%400.10.0-beta.169.0/files/lib/addon-image.mjs.map?utm_source=openai))

Citations:

- 1: https://app.unpkg.com/%40daiyam/xterm-tab-addon-image%400.10.0-beta.169.0/files/lib/addon-image.mjs.map?utm_source=openai
- 2: https://app.unpkg.com/%40daiyam/xterm-tab-addon-image%400.10.0-beta.169.0/files/lib/addon-image.mjs.map?utm_source=openai

🏁 Script executed:

set -eu
log=/tmp/coderabbit-shell-logs/shell-output-nx2mgC
printf '%s\n' '--- omitted shell output matches ---'
rg -n -C15 '_evictOnAlternate|_deleteImage|tileCount|bufferType' "$log" | sed -n '1,260p'
printf '%s\n' '--- focused patch source hunk ---'
sed -n '300,430p' config/patches/xterm-src/@[email protected]

Repository: stablyai/orca

Length of output: 45668


Keep unplaced images out of alternate-buffer cleanup.

ImageStorage.addImage calls _evictOnAlternate() on the alternate buffer. That method recounts only extended-attribute image tiles and deletes alternate-buffer entries with tileCount === 0. addUnplacedImage creates such an entry, so a later regular upload can remove the virtual placement. _drawPlaceholderRun then gets no spec and draws nothing.

Mark unplaced specs and exclude them from _evictOnAlternate.

The stale-mapping consequence does not apply here because _delImg invokes onImageDeleted, and KittyImageStorage removes the virtual placement in that callback.

Comment on lines +896 to +899
public deleteById(kittyId: number): void {
this._images.delete(kittyId);
+ this._virtualPlacements.delete(kittyId);
const storageId = this._kittyIdToStorageId.get(kittyId);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚀 Performance & Scalability | 🟠 Major | ⚡ Quick win

Delete the shared-storage entry when you drop a virtual placement.

deleteById removes the _virtualPlacements entry. It does not call this._storage.deleteImage(placement.storageId). deleteAll (Line 906) and _evictUndisplayedImages (Line 914) have the same gap. _handleStorageImageDeleted (Line 803) also has it: evicting the displayed entry drops the virtual placement but keeps its unplaced bitmap.

The addUnplacedImage entry stays in ImageStorage._images, and its bitmap is not closed. The mapping is gone, so the entry is never used again. It still counts against the pixel budget until _evictOldest removes it. Until then it can push out visible images early.

The unknown-ID and deletion tests still pass because the render path finds no mapping and draws nothing. Only the leak is hidden.

Re-entrancy is safe. deleteImage triggers onImageDeleted. That callback finds no _storageIdToKittyId entry for an unplaced storage ID, so it does nothing.

🐛 Proposed fix
+  private _deleteVirtualPlacement(kittyId: number): void {
+    const placement = this._virtualPlacements.get(kittyId);
+    if (placement) {
+      this._virtualPlacements.delete(kittyId);
+      this._storage.deleteImage(placement.storageId);
+    }
+  }
+
   public deleteById(kittyId: number): void {
     this._images.delete(kittyId);
-    this._virtualPlacements.delete(kittyId);
+    this._deleteVirtualPlacement(kittyId);

In deleteAll, call this._storage.deleteImage(p.storageId) for each value before this._virtualPlacements.clear(). At Line 803 and Line 914, replace the delete calls with this._deleteVirtualPlacement(kittyId).

Comment on lines +992 to +999
+ let placementId = 0;
+ const underlineColor = line._extendedAttrs?.[col]?.underlineColor ?? 0;
+ if (underlineColor > 0) {
+ const underlineMode = underlineColor & Attributes.CM_MASK;
+ placementId = underlineMode === Attributes.CM_RGB
+ ? underlineColor & Attributes.RGB_MASK
+ : underlineMode === 0 ? 0 : underlineColor & Attributes.PCOLOR_MASK;
+ }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '960,1015p' config/patches/xterm-src/@[email protected]
rg -n -C 6 'isEmpty\(\)|updateExtended|setCellFromCodepoint' node_modules/@xterm/xterm/src/common/buffer/AttributeData.ts node_modules/@xterm/xterm/src/common/buffer/BufferLine.ts

Repository: stablyai/orca

Length of output: 14569


Read underlineColor only when HAS_EXTENDED is set.

BufferLine.setCellFromCodepoint can leave a previous _extendedAttrs[col] entry after HAS_EXTENDED is cleared. This can expose a stale underlineColor to _placeholderCell, produce a nonzero placementId, and cause _virtualPlacementFor to reject the placeholder.

Gate the read with the cell's HAS_EXTENDED flag. Do not change xterm's AttributeData.isEmpty() semantics or retain HAS_EXTENDED for underlineColor; xterm intentionally excludes that field from the extended-attribute presence test.

+ }
+
+ private _drawPlaceholderRun(cell: IPlaceholderCell, startCol: number, count: number, row: number): void {
+ const imageId = cell.imageId | ((cell.location.highByte - 1) << 24);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

rg -n -C 8 'highByte|imageId =|PLACEHOLDER_DIACRITICS|KittyKey.IMAGE_ID|imageId:' config/patches/xterm-src/@[email protected] | tail -180

Repository: stablyai/orca

Length of output: 8152


🏁 Script executed:

set -eu
patch='config/patches/xterm-src/@[email protected]'
printf '%s\n' '--- Kitty ID parsing and placeholder references ---'
rg -n -C 12 'parseKittyCommand|IMAGE_ID|imageId|highByte|PLACEHOLDER_DIACRITICS|rowcolumn|virtualPlacementFor|addVirtualPlacement' "$patch" | sed -n '1,420p'
printf '%s\n' '--- array declaration and length ---'
python3 - <<'PY'
from pathlib import Path
p = Path('config/patches/xterm-src/@[email protected]')
s = p.read_text()
start = s.index('+export const PLACEHOLDER_DIACRITICS')
end = s.index('+];', start) + 3
block = s[start:end]
entries = []
for line in block.splitlines():
    if ':' not in line:
        continue
    rhs = line.split(':', 1)[1]
    for token in rhs.split(','):
        token = token.strip().lstrip('+')
        if token.startswith('0x'):
            entries.append(token)
print('diacritic_entries=', len(entries))
print('last_entries=', entries[-8:])
PY
printf '%s\n' '--- relevant source context ---'
sed -n '900,1045p' "$patch"

Repository: stablyai/orca

Length of output: 23021


🏁 Script executed:

set -eu
patch='config/patches/xterm-src/@[email protected]'
rg -n -C 12 'parseKittyCommand|IMAGE_ID|imageId|highByte|PLACEHOLDER_DIACRITICS|rowcolumn|virtualPlacementFor|addVirtualPlacement' "$patch" | sed -n '1,420p'
python3 - <<'PY'
from pathlib import Path
p = Path('config/patches/xterm-src/@[email protected]')
s = p.read_text()
start = s.index('+export const PLACEHOLDER_DIACRITICS')
end = s.index('+];', start) + 3
block = s[start:end]
entries = []
for line in block.splitlines():
    if ':' not in line:
        continue
    rhs = line.split(':', 1)[1]
    for token in rhs.split(','):
        token = token.strip().lstrip('+')
        if token.startswith('0x'):
            entries.append(token)
print('diacritic_entries=', len(entries))
print('last_entries=', entries[-8:])
PY
sed -n '900,1045p' "$patch"

Repository: stablyai/orca

Length of output: 22900


🏁 Script executed:

set -eu
patch='config/patches/xterm-src/@[email protected]'
printf '%s\n' '--- parser body and Kitty key definitions ---'
sed -n '80,225p' "$patch"
printf '%s\n' '--- image/color masks and surrounding declarations ---'
rg -n -C 8 'RGB_MASK|PCOLOR_MASK|CM_MASK|enum KittyKey|interface IKittyCommand|image.id|storeImage\(' "$patch" | sed -n '1,300p'
printf '%s\n' '--- exact diacritic count and indexed range ---'
python3 - <<'PY'
from pathlib import Path
import re
p = Path('config/patches/xterm-src/@[email protected]')
s = p.read_text()
start = s.index('+export const PLACEHOLDER_DIACRITICS')
end = s.index('+];', start) + 3
block = s[start:end]
entries = re.findall(r'\+\\s*(0x[0-9A-Fa-f]+)', block)
print('diacritic_entries=', len(entries))
print('accepted_nonzero_highByte_range=1..%d' % len(entries))
print('last_entries=', entries[-8:])
PY

Repository: stablyai/orca

Length of output: 17367


🏁 Script executed:

set -eu
patch='config/patches/xterm-src/@[email protected]'
printf '%s\n' '--- repository files containing the parser ---'
rg -n -C 10 'function parseKittyCommand|parseKittyCommand\s*\(|case KittyKey\.IMAGE_ID|IMAGE_ID\s*=' --glob '!config/patches/xterm-src/@[email protected]' . | sed -n '1,260p'
printf '%s\n' '--- patch hunk headers near the parser ---'
rg -n '^@@|parseKittyCommand|case KittyKey' "$patch" | sed -n '1,160p'
printf '%s\n' '--- robust diacritic count ---'
python3 - <<'PY'
from pathlib import Path
p = Path('config/patches/xterm-src/@[email protected]')
s = p.read_text()
start = s.index('+export const PLACEHOLDER_DIACRITICS')
end = s.index('+];', start)
block = s[start:end]
tokens = []
for token in block.replace('\\n', ' ').replace(',', ' ').split():
    token = token.lstrip('+')
    if token.lower().startswith('0x'):
        tokens.append(token)
print('diacritic_entries=', len(tokens))
print('first=', tokens[:3])
print('last=', tokens[-8:])
PY

Repository: stablyai/orca

Length of output: 45668


🏁 Script executed:

set -eu
for f in config/patches/@[email protected] config/patches/@[email protected] config/patches/@[email protected]; do
  if [ -f "$f" ]; then
    echo "--- $f ---"
    python3 - "$f" <<'PY'
from pathlib import Path
import sys
s = Path(sys.argv[1]).read_text(errors='replace')
for needle in ('function parseKittyCommand', 'parseKittyCommand =', 'numValue =', 'parseInt(value'):
    pos = s.find(needle)
    if pos >= 0:
        print('needle:', needle, 'offset:', pos)
        print(s[max(0, pos-700):pos+1400])
PY
  fi
done

Repository: stablyai/orca

Length of output: 6641


Use arithmetic when recombining the image ID, and reject high-byte values above 256.

parseKittyCommand parses the Kitty image ID with parseInt and does not clamp valid positive 32-bit values. The current shift produces a signed value when highByte - 1 >= 128, so _virtualPlacementFor cannot find IDs from 0x80000000 through 0xFFFFFFFF.

The diacritic decoder accepts values through 297 because its table has 297 entries. Values above 256 exceed the 8-bit high-byte field and are not valid 32-bit image IDs.

🐛 Suggested fix
-    const imageId = cell.imageId | ((cell.location.highByte - 1) << 24);
+    if (cell.location.highByte > 256) return;
+    const imageId = cell.imageId + (cell.location.highByte - 1) * 0x1000000;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
+ const imageId = cell.imageId | ((cell.location.highByte - 1) << 24);
if (cell.location.highByte > 256) return;
const imageId = cell.imageId + (cell.location.highByte - 1) * 0x1000000;

@nwparker

nwparker commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Closing as superseded — the linked issue (#23615) has been resolved on main by #26031 (26278b32ce), #27935 (125007b680), #28200 (90849ed0c6). Thanks for the contribution!

@nwparker nwparker closed this Nov 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Kitty Unicode placeholders (a=p,U=1 + U+10EEEE cells) render as literal glyphs instead of the image

2 participants