Skip to content

fix(ime): scope deferred newline to captured sessions - #11983

Closed
yeongjunyoo wants to merge 4 commits into
stablyai:mainfrom
yeongjunyoo:fix-ime-session-snapshot
Closed

yeongjunyoo wants to merge 4 commits into
stablyai:mainfrom
yeongjunyoo:fix-ime-session-snapshot

Conversation

@yeongjunyoo

Copy link
Copy Markdown
Contributor

Summary

#11896 re-arms the deferred-newline deadline while a composition is pending, but its global pending count also includes sessions that start after the newline was deferred. If a new composition overlaps the original session's end, that later session can hold the older newline and reverse the intended syllable -> newline -> next syllable ordering.

This follow-up:

  • snapshots the xterm composition session IDs that are open when the newline is deferred
  • waits only for those captured sessions, excluding sessions started afterward
  • keeps per-session reference counts so overlapping route installations on the same terminal element cannot clear each other's pending state
  • preserves the existing compositionupdate fallback for routes installed mid-composition, where no session start was captured

Related: #11878. Stacked on #11896.

Screenshots

No visual change.

Testing

  • pnpm lint — full repository lint not run; both oxlint configurations passed on all four changed files
  • pnpm typecheck — full three-project check not run; tsc --noEmit -p config/tsconfig.tc.web.json passed
  • pnpm test — full suite not run; 59 focused IME tests passed across keyboard-handlers-ime, terminal-ime-composition-route, and terminal-ime-deferred-newline
  • pnpm build — not run
  • Added regression coverage for post-defer sessions and overlapping route ownership

Additional gates passed: oxfmt --check, check:max-lines-ratchet, and git diff --check.

AI Review Report

Reviewed the change against the IME transaction lifecycle, delayed completion, route replacement, and local/SSH transport paths. The first implementation stored pending IDs in a Set; review found that two overlapping routes can own the same session ID, so disposing one route would incorrectly clear the other's pending state. The implementation now uses per-session reference counts, with a regression test for overlapping route ownership.

Cross-platform review: the change is platform-neutral DOM/xterm composition bookkeeping. It does not alter shortcuts, labels, file paths, shell commands, or Electron platform branches on macOS, Linux, or Windows. Local, SSH, and relay panes continue to use the same terminal-element-scoped state and transport abstraction.

Security Audit

The change only narrows when an already-resolved terminal input write may fire. It does not add or transform input bytes, execute commands, touch paths, add IPC, change authentication, read secrets, or add dependencies. Snapshot state remains in a terminal-element-keyed WeakMap; disposed routes release their reference counts.

Notes

This PR intentionally targets the head branch of #11896 rather than main, so it can be reviewed and folded into that existing non-duplicate IME fix.

@greptile-apps

greptile-apps Bot commented Aug 1, 2026

Copy link
Copy Markdown

Greptile Summary

This PR scopes the deferred-newline release logic to only the composition sessions that were active at the time of the deferral. Previously, any session started after the newline was queued could hold the deferral open, reversing the intended ordering. The fix snapshots open session IDs at deferral time and uses per-session reference counts in a WeakMap so overlapping route installations on the same terminal element cannot clear each other's pending state.

  • terminal-ime-composition-route.ts: Replaces the flat pending-count-per-element with a Map<sessionId, refCount> structure; adds capturePendingTerminalImeCompositionSessions for a point-in-time snapshot and extends hasPendingTerminalImeComposition with an optional snapshot filter.
  • terminal-ime-deferred-newline.ts: Captures the session snapshot at sendTerminalInputAfterComposition call-time and threads it through every decision point — finishAfterPendingComposition, onCompositionUpdate idle-reset guard, and onFallbackDeadline — while preserving the sawRecentUpdate fallback for routes installed mid-composition where no session start was captured.

Confidence Score: 5/5

The change is safe to merge — it only narrows which sessions can hold a deferred newline and cannot introduce data loss or double-writes given the existing done guard.

The snapshot is captured synchronously before any timers or listeners are registered, so there is no window where a session can slip in unobserved. Per-session reference counts correctly handle overlapping routes. All three decision points in the deferred-newline state machine consistently use the same captured snapshot. The sawRecentUpdate fallback for zero-snapshot is preserved.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/renderer/src/components/terminal-pane/terminal-ime-composition-route.ts Refactors global pending count to per-session reference counts; adds snapshot capture and filtered pending check; dispose loop and session-end removal are correctly coordinated to avoid double-decrement.
src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.ts Snapshot captured synchronously before any timers or listeners are registered; all three decision points correctly scope to captured sessions; sawRecentUpdate fallback preserved for zero-snapshot case.
src/renderer/src/components/terminal-pane/terminal-ime-composition-route.test.ts Adds regression coverage for overlapping route ownership with correct reference-count expectations; existing suite continues to pass.
src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.test.ts New test exercises the core fix — a post-defer session must not hold the newline — and verifies the newline fires exactly once after the captured session ends.

Reviews (1): Last reviewed commit: "fix(ime): scope deferred newline to capt..." | Re-trigger Greptile

nwparker and others added 4 commits August 4, 2026 07:13
…inal

Two ways a committed composition was lost or corrupted.

The composition route called preventDefault() before checking whether it owned
the session. A route installed mid-composition never saw the matching session
start, so it suppressed xterm's own insertion and then returned without
delivering anything — the commit vanished. Ownership is now decided first;
preventDefault stays for sessions the route does own, including the ones it
deliberately drops after a transport swap, since that drop is its decision to
make.

The deferred-newline fallback fired `finish` directly, bypassing the
pending-composition re-check that the event path uses. A composition still open
at 200 ms got a newline sent into the middle of its preedit. The deadline now
re-arms while a composition is pending, and its 2 s ceiling is measured from the
last compositionupdate rather than from the start. A slow candidate window no
longer splits the preedit, and neither does multi-segment bunsetsu conversion,
which stays legitimately pending well past any fixed total-elapsed ceiling. A
composition that stops progressing still cannot strand the keystroke.

Co-authored-by: Orca <[email protected]>

The re-arm also treats a live compositionupdate as evidence in its own right, not
just a session the route recorded. A route installed while a composition was
already in flight never saw that session start, so it has nothing to report as
pending and the deadline would otherwise split that composition too.
@Jinwoo-H
Jinwoo-H force-pushed the fix-ime-session-snapshot branch from 9fc0803 to 2450397 Compare August 4, 2026 12:30
@Jinwoo-H
Jinwoo-H requested a review from brennanb2025 as a code owner August 4, 2026 12:30
@greptile-apps

greptile-apps Bot commented Aug 4, 2026

Copy link
Copy Markdown

Too many files changed for review. (1422 files found, 100 file limit)

@Jinwoo-H
Jinwoo-H changed the base branch from nwparker/ime-commit-delivery to main August 4, 2026 12:33
@Jinwoo-H
Jinwoo-H marked this pull request as draft August 4, 2026 12:34
@Jinwoo-H
Jinwoo-H marked this pull request as ready for review August 4, 2026 12:34
@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This change updates terminal IME composition handling. The composition route now tracks pending sessions per session ID within a per-element map, instead of a single aggregate count, and adds a snapshot API for checking pending status against a captured set of sessions. Session-end handling only prevents events for sessions owned by the route. The deferred-newline sender now captures pending sessions, listens for composition updates and later session starts, tracks idle time, and enforces a configurable maximum idle duration (maxIdleMs) alongside the existing fallback timeout. Tests cover session sharing across routes, capture/suppression behavior, and deferred-newline timing, including an xterm integration test.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states that deferred newline handling is scoped to captured IME sessions.
Description check ✅ Passed The description covers the summary, visual impact, testing results, AI review, security audit, and platform-specific notes.
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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 11b43cee-5557-4627-85ef-b1b153d70ae9

📥 Commits

Reviewing files that changed from the base of the PR and between 4734428 and 2450397.

📒 Files selected for processing (5)
  • src/renderer/src/components/terminal-pane/terminal-ime-composition-route.test.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-composition-route.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline-xterm.test.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.test.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.ts

Comment on lines +32 to +36
let idleMs = 0
let laterSessionStarted = false
const pendingCompositionSessions = capturePendingTerminalImeCompositionSessions(terminalElement)
const hasCapturedPendingComposition = (): boolean =>
hasPendingTerminalImeComposition(terminalElement, pendingCompositionSessions)

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 | 🟠 Major | ⚡ Quick win

Measure idle duration from the last relevant update.

idleMs adds a full fallbackMs at each deadline, and sawRecentUpdate is cleared after one deadline. With { fallbackMs: 50, maxIdleMs: 200 }, an untracked update at 30 ms can finish at 100 ms, and a tracked update at 49 ms can finish at 200 ms after only 151 ms idle. This can send the deferred newline during an active composition. Track the last relevant update time, use actual elapsed idle time, and re-arm for the remaining window. Add a regression with an update gap between fallbackMs and maxIdleMs.

Also applies to: 68-100

@nwparker

Copy link
Copy Markdown
Contributor

Thanks for this, @yeongjunyoo — the captured-session IME route was the right design.

This already landed on main in #15056, which ported your change onto current main with Co-authored-by credit. I'm closing this PR as no longer needed.

This note is from an automated scan of open PRs whose issue already shipped in a later merge. If that's wrong, please reopen and say so.

@nwparker nwparker closed this Aug 26, 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.

4 participants