Skip to content

fix(terminal): send a committed IME string without waiting for the next composition - #12043

Closed
kunsanglee wants to merge 2 commits into
stablyai:mainfrom
kunsanglee:fix/terminal-hangul-continuous-run-lag
Closed

kunsanglee wants to merge 2 commits into
stablyai:mainfrom
kunsanglee:fix/terminal-hangul-continuous-run-lag

Conversation

@kunsanglee

@kunsanglee kunsanglee commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A committed IME composition reaches the pty one session late whenever the commit did not propagate as an input event and the next compositionstart arrives in the same task. The shell then has nothing to echo, the cursor never advances, and the overlay for the string being composed paints over the cell the previous one should own.

Korean makes this constant. One jamo key commits the previous syllable and opens the next, so every syllable boundary meets both conditions and a continuous run is unreadable — 그리고 shows as 그고. The bytes are fine; pressing Enter sends 그리고 intact. Measured against the real patched CompositionHelper:

그 composition ends   → sent: (nothing)
리 composition starts → (nothing)
리 composition ends   → 그        ← 그 only leaves now
고 composition starts → 그
고 composition ends   → 그리       ← 리 only leaves now
next macrotask        → 그리고

A devtools trace of .composition-view confirms the cursor never moves: left stays at 17px for the whole word.

This is not Korean-specific. There is no language or character-range branch in compositionstart, _finalizeComposition, _sendPendingComposition, _endPendingCompositionSession or _getPendingTextareaInput. Replaying the same event shape with pinyin (你好 / 世界), kana-kanji (日本 / 語) and Vietnamese Telex (tiến / Việt) reproduces it identically, and this change corrects all of them. Those IMEs commit on a dedicated key and open the next composition on the following keypress, so they usually land one task apart and escape it; Korean cannot.

Cause

CompositionHelper.compositionstart cancelled the pending composition's finalizer before closing its session:

if (this._pendingComposition) {
  this._cancelPendingFinalizer(this._pendingComposition);
  this._endPendingCompositionSession(this._pendingComposition);
  this._settlePendingComposition(this._pendingComposition);
}

_endPendingCompositionSession only dispatches a session-end carrying dataPendingReconciliation: true; it sends nothing to the pty. With the finalizer cancelled nothing else was scheduled, so the committed text sat there until the next composition's _finalizeComposition flushed it on its way past.

Any non-composition key in between hides the bug — CompositionHelper.keydown calls _finalizeComposition(false) and flushes first. So does a commit that propagates as insertText.

Fix

Drop the _cancelPendingFinalizer call and leave the timer armed. compositionstart assigns pending.nextCompositionStart a few lines further down, so by the time the timer runs the exact boundary between the committed text and the new composition is known and _getPendingTextareaInput returns the right slice. The string leaves one macrotask after compositionstart instead of one composition later.

This restores the timing xterm had before the pending-composition machinery landed: the original code committed on a setTimeout(…, 0) for the reason its comment still gives, that composition events fire before the textarea settles. What changed is only that the wait is bounded again.

Sending directly inside compositionstart was tried first and breaks IBus. In preserves a Korean final-consonant transfer across compositions the textarea still reads 앙 when the next compositionstart fires; the transfer to 아 + ㅇ only shows up on the following compositionupdate. That path emitted 앙아 instead of 아아. The reconciliation window is what dataPendingReconciliation is named for, so this shortens the wait to one task rather than removing it.

Source maps

The patch edits shipped minified bundles, so mappings has to move with them. config/scripts/shift-sourcemap-after-bundle-edit.mjs does it and is included here, because otherwise the next @xterm/xterm bump has to redo the surgery by hand with nothing to check it against.

For the 55 characters removed from one generated line in each bundle: segments past the deletion move back by 55, segments that named the removed statement are dropped because their code is gone, and no other generated line changes — asserted by the script, which refuses to write if the running source-position state at the end of the line would shift.

Verified with @jridgewell/trace-mapping: the deletion column now resolves to CompositionHelper.ts:146:6, the statement that took its place. Leaving mappings untouched would have overrun the generated line by 44 and 52 columns and mis-attributed roughly 85% of each bundle.

Rebuilding instead of patching is not available: the published tarball omits bin/, webpack.config.js and tsconfig.json, and a rebuilt bundle would differ everywhere the minifier picked other identifiers.

Screenshots

No visual change in the sense of new UI. The user-visible effect is that the terminal composition overlay stops painting over the previous cell during a continuous IME run; there is no new or changed component to screenshot.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test — 4056 files / 43163 pass; 3 pre-existing failures, see below
  • pnpm build
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

The 3 failures are environmental, not from this PR. config/scripts/check-root-directory-entries.test.mjs shells out to .github/scripts/check-root-directory-entries.sh, which uses declare -A. macOS ships bash 3.2, where that is declare: -A: invalid option, so the guard exits 2 against its own throwaway fixture repo before reading anything. It never looks at this branch. CI runs it on bash 5.

New tests in terminal-ime-xterm-continuous-hangul-run.test.ts, using the harness from the existing de-duplication suite. Both fail without the change:

  • a three-syllable run asserting the emitted chunks after every syllable — expected [] to deeply equal [ '그' ]
  • the next syllable's first jamo reaching the textarea before the deferred send runs. This is the only coverage in the repo for the nextCompositionStart bound the fix relies on; deleting that bound yields [ '그ㄹ' ] instead of [ '그' ] and nothing else in the suite notices.

The reproduction hinges on not firing an insertText input event after compositionend; the real Chromium trace has none, and adding one routes through the healthy path and hides the bug.

Also confirmed: config/scripts/package-electron-runtime-contract.test.mjs passes (22), and a fresh pnpm install --frozen-lockfile in an isolated tree reproduces the declared post-image hashes.

AI Review Report

Two rounds of independent reviews, run in parallel and unaware of each other, on simplicity, impact radius, adversarial refutation, patch hygiene, source-map correctness, test coverage, and language generality.

What they flagged and what changed as a result:

  • Source maps were wrong in the first cut. Only sourcesContent had been updated; mappings still described the pre-deletion bundle. A full-column sweep with @jridgewell/trace-mapping measured the overrun. Fixed by shifting the affected generated line, and the transform script is now in the tree.
  • The first shift clamped instead of dropping. Segments landing inside the removed text were pinned to its start, which stacked five segments on one column and made the GLB lookup return the statement that had been deleted. Dropping them takes the full-line sweep to zero mismatches.
  • A test did not earn its place. One of the two original cases passed before the fix as well; the run always totals correctly because the last syllable takes the ordinary path. Merged into one case with per-syllable assertions.
  • The nextCompositionStart bound had no coverage at all. Deleting that line left all 79 IME tests green. Added the case above.
  • Framing was too narrow. The change was titled and written around Hangul. Confirmed IME-general by replaying pinyin, kana-kanji and Telex; retitled and rewritten.
  • Not adopted: merging the two if (this._pendingComposition) branches in compositionstart. It would change the data payload of the dataPendingReconciliation event, which no consumer reads, and widen the divergence from upstream for no behavioural gain.

Adversarial round: 500 differential fuzz runs with macrotask boundaries injected between events at 25%, across macOS, IBus and late-commit shapes plus ASCII/Enter/Escape, checking total equality, prefix-monotonicity of intermediate output, and no-regression against the old bundle. Zero violations; 230/500 runs emitted earlier than before. Fifteen hand-written scenarios and six boundary probes matched the old bundle exactly.

Cross-platform. Reviewed explicitly for macOS, Linux and Windows. The change is inside vendored renderer code with no platform branch, no shortcut, label, path or shell behaviour, and no Electron main-process surface. Per platform: macOS Hangul is the reported reproduction; Linux IBus is covered by the recorded traces in tests/e2e/terminal-ime-observed-event-sequences.ts, replayed before and after with identical output (한abc글\r, 테a스\r); Windows Process/229 handling is unaffected because CompositionHelper.keydown gates on _isComposing || hasPendingCompositionFinalization and _isComposing stays true through the composition. SSH and remote runtimes see the same onData chunks (["그","리","고"]) with only the arrival time changing, so remote-runtime-pty-batching ordering is untouched.

Security Audit

No new input handling, command execution, path handling, auth, secrets or IPC surface. No Orca source changed.

The dependency angle is the one to look at, since this edits a vendored patch of @xterm/xterm. Reviewed and verified:

  • The patch removes one call and adds one comment; the eight files it touches were hashed against the previous post-images, and the three unrelated to this change are byte-identical.
  • The index blob hashes in the patch match the produced files. pnpm does not verify them — it parses them but never hashes content — so they were checked by hand rather than relied on.
  • pnpm-lock.yaml carries only the patch-hash propagation, which is the sha256 of the patch file; the old hash appears nowhere in the repo, including mobile/pnpm-lock.yaml. CI runs pnpm install --frozen-lockfile, so a patch edited without the lockfile would fail there.
  • The added script reads and writes only the two paths passed to it and shells out to nothing.

Terminal input reaching the pty earlier does not change what is sent, only when. The full run emits the identical byte sequence.

Notes

Known window. If an IME rewrites already-committed text more than one task after compositionend, the old text is already out and cannot be retracted; constructed synthetically that yields 글리 where the previous behaviour yielded 그리. No IME sequence recorded in this repo has that shape: the IBus rewrite completes in the same task as compositionend, and the macOS Hangul final-consonant transfer completes inside the composition. Waiting for the next compositionupdate instead of one task would close the window, but it puts the flush back on the user's next keystroke, so the shell has no time to echo and the overlap returns on the first jamo of each syllable.

Unmeasured. How often real Sogou, Kotoeri or Unikey binaries produce the triggering event shape. The repo has no recorded traces for them, and the mechanism was confirmed by replay rather than on hardware.

Follow-up worth considering. A check next to config/scripts/package-electron-runtime-contract.test.mjs asserting that every patched bundle's maximum mapped column stays inside its generated line would have caught the source-map defect above in CI. tests/e2e/terminal-ime-observed-event-sequences.ts currently records IBus only; a macOS capture would give the shape this fix targets a recorded counterpart.

…xt composition

A committed composition reached the pty one session late whenever the commit
had not propagated as an input event and the next compositionstart arrived in
the same task. The shell then had nothing to echo, the cursor never advanced,
and the overlay for the string being composed painted over the previous cell.

Korean meets both conditions at every syllable boundary, because one jamo key
commits the previous syllable and opens the next one, so a continuous run is
unreadable. Pinyin, kana-kanji and Telex reproduce identically whenever their
event sequence takes that shape.

CompositionHelper.compositionstart cancelled the pending composition's
finalizer before closing its session, and _endPendingCompositionSession sends
nothing to the pty. Nothing else was scheduled, so the text waited for the next
composition's _finalizeComposition to flush it on its way past.

Leave the finalizer armed. It runs after compositionstart records
nextCompositionStart, so the boundary is known and the string leaves one task
later instead of one composition later. Sending inside compositionstart was
tried first and breaks the IBus final-consonant transfer, where the textarea
has not settled yet.

The source maps are realigned for the 55 removed characters, not just their
sourcesContent, by the script this commit adds: segments past the deletion move
back, segments that named the removed statement are dropped, and no other
generated line changes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01HL8CxXZYghUKJEQpYhKeGg
@kunsanglee
kunsanglee force-pushed the fix/terminal-hangul-continuous-run-lag branch from 835cc7c to ff486fd Compare August 2, 2026 05:07
@kunsanglee kunsanglee changed the title fix(terminal): send a committed Hangul syllable without waiting for the next one fix(terminal): send a committed IME string without waiting for the next composition Aug 2, 2026
@kunsanglee
kunsanglee marked this pull request as ready for review August 2, 2026 05:07
@coderabbitai

coderabbitai Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0c102eb7-4e2d-45d2-8202-b177f9074f7a

📥 Commits

Reviewing files that changed from the base of the PR and between ff486fd and 6e892fb.

📒 Files selected for processing (2)
  • config/scripts/shift-sourcemap-after-bundle-edit.mjs
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-continuous-hangul-run.test.ts

📝 Walkthrough

Walkthrough

The pull request adds a CLI script that adjusts source-map mappings after deleting text from a generated bundle. It locates the deletion with a unique marker, updates affected mappings, preserves unaffected lines, and validates the result before writing the map. It also adds happy-dom/Vitest regression tests for continuous macOS Hangul IME composition in xterm, including consecutive syllable commits and deferred input handling.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the terminal IME fix and the corrected delayed delivery behavior.
Description check ✅ Passed The description includes all required sections and documents testing, review findings, cross-platform checks, security risks, and follow-up work.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ffdc7662-afbd-41e1-9ac1-cb397e90c1b4

📥 Commits

Reviewing files that changed from the base of the PR and between 6e2a88c and ff486fd.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (3)
  • config/patches/@[email protected]
  • config/scripts/shift-sourcemap-after-bundle-edit.mjs
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-continuous-hangul-run.test.ts

@greptile-apps

greptile-apps Bot commented Aug 2, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a timing bug in the vendored @xterm/xterm CompositionHelper where a committed IME syllable was delayed by one composition whenever compositionstart fired in the same synchronous task as compositionend — a pattern that is constant in Korean (Hangul) and possible in other IMEs. The fix drops a single _cancelPendingFinalizer call from compositionstart, allowing the deferred finalizer timer to fire naturally with the nextCompositionStart position bound already set, so only the committed text is emitted.

  • Core patch (@[email protected]): Removes _cancelPendingFinalizer from compositionstart and adds pending.nextCompositionStart = this._compositionPosition.start so the armed timer knows the exact boundary when it fires one macrotask later.
  • Sourcemap utility (shift-sourcemap-after-bundle-edit.mjs): New dev-time script that realigns VLQ-encoded mappings in .js.map files after a hand-deletion from a minified bundle, keeping segment columns consistent with the edited line.
  • Tests (terminal-ime-xterm-continuous-hangul-run.test.ts): Two new cases — per-syllable emission assertions for a three-syllable run, and a nextCompositionStart-bound proof that the deferred send stops at the correct column even when the next syllable's first jamo has already arrived in the textarea.

Confidence Score: 5/5

Safe to merge. The change is a one-call removal in a well-tested vendored module, the deferred timer path it re-enables has been in xterm before, and the existing guard on the timer body prevents double-emission.

The fix is minimal and its invariant is airtight: the timer checks this._pendingComposition === pending before sending, so a second composition's _finalizeComposition flushing the same pending object cannot race with the timer. Both the new per-syllable assertions and the nextCompositionStart-bound proof case fail without the change and pass with it. Source maps were verified with @jridgewell/trace-mapping and the shift script refuses to write if any mapped column overruns the generated line.

Files Needing Attention: No files require special attention. The patch to the minified bundles was already verified against the TypeScript source, the sourcemap delta was measured and validated, and the new test cases are independent and deterministic.

Important Files Changed

Filename Overview
config/patches/@[email protected] Drops _cancelPendingFinalizer from compositionstart and sets nextCompositionStart so the armed timer correctly slices the committed syllable; both lib/xterm.js and lib/xterm.mjs patched with matching sourcemap updates.
config/scripts/shift-sourcemap-after-bundle-edit.mjs New dev-time utility that decodes VLQ source-map segments, drops those inside a deletion range, shifts the rest back, validates no other generated line changes, and refuses to write if any mapped column would overrun the line length.
src/renderer/src/components/terminal-pane/terminal-ime-xterm-continuous-hangul-run.test.ts Two focused integration tests using the xterm Terminal directly; per-syllable emission assertions and a nextCompositionStart-bound proof that together fail without the fix and pass with it.
pnpm-lock.yaml Patch SHA-256 hash updated to reflect the new patch content; no other dependency changes.

Sequence Diagram

sequenceDiagram
    participant KB as Keyboard / IME
    participant CH as CompositionHelper
    participant PT as pty (onData)

    note over KB,PT: Korean syllable boundary — compositionstart in the same task as compositionend

    KB->>CH: compositionend("그")
    CH->>CH: "_finalizeComposition(true)<br/>creates pending1, arms finalizerTimer"
    note right of CH: OLD CODE: compositionstart<br/>calls _cancelPendingFinalizer(pending1)<br/>timer silently dropped → 그 is never sent

    KB->>CH: compositionstart (리 begins)
    note right of CH: NEW CODE: timer stays armed<br/>sets pending1.nextCompositionStart = cursor(1)

    note over CH: --- next macrotask ---
    CH->>CH: "finalizerTimer fires<br/>_getPendingTextareaInput(pending1)<br/>= value[0..nextCompositionStart=1] = "그""
    CH->>PT: triggerDataEvent("그") ✓

    KB->>CH: compositionend("리")
    CH->>CH: "_finalizeComposition(true)<br/>creates pending2, arms finalizerTimer"

    KB->>CH: compositionstart (고 begins)
    note right of CH: timer stays armed<br/>sets pending2.nextCompositionStart = cursor(2)

    note over CH: --- next macrotask ---
    CH->>CH: finalizerTimer fires → "리"
    CH->>PT: triggerDataEvent("리") ✓

    KB->>CH: compositionend("고")
    CH->>CH: "_finalizeComposition(true)<br/>no new compositionstart — ordinary path"
    note over CH: --- next macrotask ---
    CH->>PT: triggerDataEvent("고") ✓
Loading

Reviews (2): Last reviewed commit: "fix(terminal): harden the source-map shi..." | Re-trigger Greptile

Review feedback on the PR:

- reject a deletion containing a line terminator, since the shift only
  realigns one generated line and later lines would move unadjusted
- fail with the intended message rather than a TypeError when a generated
  line has no segment left to carry running state, which also keeps
  Math.max off an empty spread
- dispose terminals from afterEach so a throwing assertion cannot leak one

Verified the script still reproduces the committed patch byte for byte.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01HL8CxXZYghUKJEQpYhKeGg
@kunsanglee

Copy link
Copy Markdown
Contributor Author

Addressed the review feedback in 6e892fb6a.

  • Reject deletions containing line terminators — applied. The shift realigns one generated line, so a multi-line deletion would move later lines with their mappings left behind. It now throws before doing anything.
  • .at(-1) on a possibly-empty array / Math.max(...[]) — applied as one guard. If the filtered line has no segment left to carry the running source-position state, the script throws with that message; the Math.max spread is downstream of it and can no longer see an empty array.
  • Terminal disposal on a throwing assertion — applied. Terminals are tracked at module scope and disposed in afterEach before the DOM is cleared, and the success-only dispose() calls are gone.

Re-verified after the change that the script still reproduces the committed patch byte for byte: reset to the parent commit's patch, reinstalled, re-ran the bundle edit, the shift and the comment substitution, and all five post-image blob hashes match. terminal-pane is 219 files / 2888 tests green, pnpm lint and pnpm typecheck exit 0.

@OrcaWin

OrcaWin commented Aug 3, 2026

Copy link
Copy Markdown
Collaborator

Superseded by #12278 and #12280. The finalizer mechanism identified here was landed with reproducibly rebuilt xterm artifacts, and #12280 then verified physical macOS 2-Set input end to end. Thank you @kunsanglee for independently isolating the one-session-late commit and the IBus constraint.

@OrcaWin OrcaWin closed this Aug 3, 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.

2 participants