Skip to content

perf(terminal): stop the IME candidate anchor forcing layout on every compositionupdate - #12442

Merged
brennanb2025 merged 3 commits into
mainfrom
brennanb2025/perf-ime-anchor-layout
Aug 5, 2026
Merged

brennanb2025 merged 3 commits into
mainfrom
brennanb2025/perf-ime-anchor-layout

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Typing Korean/Japanese/Chinese in a terminal pane was laggy while ASCII typing was fine. installTerminalImeCandidateAnchor() registers one handler on both compositionstart and compositionupdate, and every event did a getBoundingClientRect() on .xterm-screen (forced sync layout) followed by two textarea.style writes (layout invalidation) — a read→write→read cycle repeated 3–4× per Hangul syllable, interleaved with xterm's own composition layout reads.

This keeps the anchor exactly as correct as before and removes the per-event forced layout:

  • Cell metrics (cellWidth/cellHeight) are measured once per composition and reused by every compositionupdate, with a cols/rows staleness guard so a mid-composition refit still re-measures.
  • Anchor style writes are skipped when the inline value already matches. Reading textarea.style.top is a CSSOM read, not a layout read, so this costs nothing and avoids re-invalidating layout.
  • The deferred Cursor Agent correction keeps one pending setTimeout and re-queues it after xterm's latest composition timer, so xterm cannot clobber the final anchor. When it fires, it revalidates cell metrics and resolves the live anchor.

Latin input is untouched: it fires no composition events, so the handler never runs (covered by a test).

Fixes #12211

Why the update listener was kept

The issue's cheapest suggestion — drop the compositionupdate listener and keep only compositionstart — is not safe, and verifying that was the first step here. xterm's own CompositionHelper.compositionupdate() calls updateCompositionElements(), which writes _textarea.style.left/top from its uncorrected cursor on every update, and then schedules a setTimeout(0) recursion that writes them again (node_modules/@xterm/xterm/src/browser/input/CompositionHelper.ts:179-199, 726-765). Removing our update listener would hand the textarea back to xterm mid-composition and regress the Cursor Agent anchor (where xterm's public cursor deliberately sits on a blank row). That matters most for exactly the IMEs the issue says are affected: Hangul is one composition per syllable, but Japanese romaji→kana→kanji and Chinese pinyin phrases compose long sequences, so a wrong anchor would persist for the whole conversion. A regression test asserts we re-correct the anchor after a simulated xterm clobber.

For the same reason the deferred re-apply stays on setTimeout(0) rather than moving to requestAnimationFrame as the issue suggests: it has to land after xterm's own deferred updateCompositionElements(true) timer, and a rAF callback can run before a pending timer task when the frame deadline arrives first. The remaining sync write is a pure style write with no read after it, so there is no read-write-read cycle left.

Measured

Deterministic harness (terminal-ime-candidate-anchor.test.ts, happy-dom) drives a realistic Hangul burst — 30 syllables × (1 compositionstart + 3 compositionupdate) = 120 events — with a counting getBoundingClientRect and a Proxy over textarea.style:

forced-layout reads style writes pending timers (Cursor Agent burst)
before (e8d4818b5a) 120 240 6
after 30 31 1

Reads drop from O(events) to O(compositions); writes drop to one per anchor change (2 for the first syllable, 1 per syllable after, since only left moves). Verified red-on-parent: reverting only the source file and re-running the harness fails with expected 120 to be 30 and expected 6 to be 1.

Screenshots

No intended visual change — only the cost and ordering of the anchor correction changed.

Active Korean composition at the terminal cursor:

Active Korean IME composition

Committed Korean, Japanese, and Chinese output in the surrounding terminal UI:

CJK terminal output

Electron QA on the final head drove 30 Hangul syllables × 4 composition events in the live renderer: 120 events, 30 .xterm-screen layout reads.

Testing

  • pnpm lint — oxlint, audit:code-quality:native, audit:code-quality:type-aware, check:max-lines-ratchet all clean
  • pnpm typecheck
  • pnpm test — new file 9/9; src/renderer/src/lib/pane-manager 628 passed, 1 skipped; dashboard-popout + terminal-pane 3086 passed
  • React Doctor changed-lines gate — 0 issues (check:react-doctor:changed, lint:react-doctor:changed)
  • Added or updated high-quality tests that would catch regressions

New tests: the counting harness above, plus coverage for no-work-on-Latin-input, mid-composition re-correction after an xterm clobber, mid-composition refit re-measurement, post-refit anchor refresh, xterm timer ordering, one pending correction, and no write after the textarea detaches.

AI Review Report

Reviewed against the issue's claims rather than taking them at face value; the reported code shape was confirmed accurate against src/ (not app.asar), including the shared handler, the per-event rect read, and the setTimeout(0) second write.

Risks checked:

  • Correctness of the invariant. Read xterm's CompositionHelper source to confirm whether mid-composition repositioning is load-bearing. It is (see above), so the proposed listener removal was rejected in favour of making the update path free of layout.
  • Stale metrics. Guarded by re-measuring at every compositionstart plus a cols/rows comparison in both the event and deferred paths, so a refit mid-composition re-measures before either write. A sub-cell resize that changes neither cols nor rows can leave metrics off by well under one cell until the next composition — deliberate, and strictly better than the previous behaviour's cost.
  • Skipped writes. The skip compares against the live inline value, so an xterm clobber always causes a rewrite; it can only skip when the DOM already holds the value we want. Blink itself already no-ops an identical setProperty, so this is purely avoiding CSSOM churn.
  • Deferred correctness. Each Cursor Agent event clears and re-queues the single pending correction after xterm's newest timer. The callback revalidates dimensions and resolves the live buffer anchor, so neither a refit nor xterm's deferred write can restore stale positioning.
  • Listener lifecycle (STA-3291 / fix(terminal): stop keyboard effect re-registering on every pane render #12348). Install is once per pane in openTerminal (pane-lifecycle.ts) and once per preview in installPreviewTerminalCompatibility; neither is per-render. The exported signature is unchanged ((() => void) | null), so both existing dispose paths keep working untouched.
  • Cross-platform. Renderer-only, no keyboard shortcuts, no path handling, no platform branches added or touched. IME composition events are Chromium-level and identical on macOS, Linux, and Windows; the Windows report in the issue thread ("first syllable one behind") exercises the same handler. No Electron main-process or IPC surface involved, so SSH and folder-workspace panes behave identically.

Not changed, and called out deliberately: resolveCursorAgentImeAnchor's buffer scan still runs per event. It is pure JS with no layout involvement and early-returns unless the cursor is at column 0 on a blank row, so it is off the hot path for normal shells and TUIs. Caching it would need a render-driven invalidation to avoid a stale anchor when async agent output moves the prompt row mid-composition — out of scope for this PR.

Security Audit

No new input handling, command execution, path handling, auth, secrets, dependency, or IPC surface. The change is confined to one renderer module that reads xterm's public buffer/geometry API and writes two inline CSS offsets on xterm's own textarea; all values written are numbers derived from cell geometry, never user text. No new dependencies. No follow-up needed.

Notes

  • The issue also asks for a setting to disable the anchor. Not added — with the per-event forced layout gone there is nothing left to opt out of, and a toggle would be a separate concern.
  • The second comment on the issue (Windows, "first composed syllable appears one syllable late" in the agent prompt) describes a rendering-order symptom in a different surface and is not addressed here.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Updated terminal IME candidate anchoring to cache cell metrics, reuse measurements during composition, remeasure after terminal dimension changes, and skip redundant style writes. Cursor Agent corrections now use a coalesced deferred timer. Added tests for composition handling, repositioning, refits, deferred updates, null elements, and detached textareas.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The changes address issue #12211 by reducing layout reads and writes while preserving correct IME anchor positioning.
Out of Scope Changes check ✅ Passed The source changes and regression tests are limited to the linked issue's IME anchoring performance and correctness objectives.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Title check ✅ Passed The title clearly and concisely describes the main performance change to terminal IME candidate anchoring.
Description check ✅ Passed The description covers the required summary, screenshots, testing, AI review, security audit, and notes with detailed implementation and validation results.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c1215384-1cb9-4d8c-8df7-7b43aa72dce0

📥 Commits

Reviewing files that changed from the base of the PR and between e8d4818 and 6ebb2bb.

📒 Files selected for processing (2)
  • src/renderer/src/lib/pane-manager/terminal-ime-candidate-anchor.test.ts
  • src/renderer/src/lib/pane-manager/terminal-ime-candidate-anchor.ts

@brennanb2025

brennanb2025 commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor Author

Attachments

pr12442-windows-ime.png
pr12442-windows-ime.png

pr12442-windows-cjk-ime.png
pr12442-windows-cjk-ime.png

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Windows low-spec remote QA at HEAD 037a5d20947e415365177e5678f0a05b327a50a8:

  • Created an isolated Windows worktree and launched this checkout as an Electron dev app through CDP.
  • Focused IME anchor suite: 9/9 passed.
  • Exercised a real Chromium composition sequence: ㅎ → 하 → 한, then committed 한글 입력 테스트.
  • Observed compositionstart, incremental compositionupdate events, and compositionend; the committed text rendered cleanly in the Windows terminal.
  • Performance evidence: exactly one .xterm-screen.getBoundingClientRect() read across the full composition burst. The textarea anchor advanced from left: 224px to 352px after the committed phrase.
  • Screenshot: perf(terminal): stop the IME candidate anchor forcing layout on every compositionupdate #12442 (comment)

Remaining limitation: CDP drives Chromium composition events but cannot show the native Windows IME candidate popup, so native-popup placement itself was not directly observed. The renderer composition, anchor-update, and performance paths were verified.

@brennanb2025
brennanb2025 merged commit ac9b83d into main Aug 5, 2026
42 checks passed
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Expanded Asian-language IME regression pass at HEAD 037a5d20947e415365177e5678f0a05b327a50a8:

  • Historical IME suite: 35 files, 481 tests passed.
  • Independent scoped review: CLEAN; an additional 9 files / 131 focused tests passed.
  • Windows Electron live scenarios: Korean 2-set (ㅎ → 하 → 한 → 한글), Japanese conversion (ni → に → 日本語), Chinese Pinyin (zhong → 中 → 中文), Pinyin cancellation, immediate Japanese restart, and a 30-update CJK candidate burst.
  • Cancellation removed the uncommitted 拼; the immediate 再開 composition started and committed cleanly.
  • Chromium observed 6 compositionstart and 6 compositionend events.
  • Performance invariant held: exactly one screen layout read per composition, including the 30-update burst (6 total reads). Final anchor was 560px within the 1080px terminal screen.
  • Multilingual Windows screenshot: perf(terminal): stop the IME candidate anchor forcing layout on every compositionupdate #12442 (comment)

The native Windows candidate popup itself remains outside CDP visibility; composition events, cancellation/restart, committed text, anchor movement, and layout cost were verified.

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… compositionupdate (stablyai#12442)

* perf(terminal): stop the IME candidate anchor forcing layout per compositionupdate

* fix(terminal): refresh deferred IME anchor after refit

* fix(terminal): preserve deferred IME anchor ordering
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.

Korean/CJK IME input lag in terminal panes — installTerminalImeCandidateAnchor forces layout on every compositionupdate

1 participant