Skip to content

fix(terminal): stop IME newline defer holding Shift+Enter with no composition (#10203) - #11778

Closed
itisvincent wants to merge 1 commit into
stablyai:mainfrom
itisvincent:fix/terminal-shift-enter-ime-defer-freeze
Closed

itisvincent wants to merge 1 commit into
stablyai:mainfrom
itisvincent:fix/terminal-shift-enter-ime-defer-freeze

Conversation

@itisvincent

Copy link
Copy Markdown
Contributor

Summary

Fixes the "Pi input freezes briefly on Shift+Enter" symptom from #10203 — and more precisely, the freeze anyone sees on Windows when comparing Shift+Enter (freezes ~200ms before the newline lands) vs Alt+J (smooth).

Root cause

On Windows, Shift+Enter is a modified-Enter chord. keyboard-handlers.ts routes modified Enter through the IME deferred-newline path:

```ts
if ((e.isComposing || hasPendingImeComposition) && (e.key === 'Enter' || imeProcessEnter)) {
...
deferredNewlineSender.defer(e, pane.terminal.element, sendResolvedInput)
return
}
```

defer() calls `sendTerminalInputAfterComposition`, which always armed a 200ms fallback timer and waited for `compositionend` / a captured xterm transaction end — even when no IME composition was actually pending:

```ts
const fallbackTimer = window.setTimeout(finish, fallbackMs) // 200ms
```

When no compositionend arrives (the common case: IME idle, or no IME), the newline is held for the full `TERMINAL_IME_DEFERRED_NEWLINE_FALLBACK_MS = 200` — the visible "brief freeze before the newline is accepted."

Alt+J is not an Enter chord (`e.key !== 'Enter'`), so it never enters this defer and is sent immediately — which is exactly why Alt+J is smooth and Shift+Enter is not.

Fix

Only hold the newline while a composition is genuinely pending (`hasPendingTerminalImeComposition`). If nothing is pending, send on the next macrotask (matching the existing no-terminal-element path). Genuine pending compositions still wait for `compositionend` / the captured xterm transaction to settle, so IME correctness is preserved.

```ts
if (!hasPendingTerminalImeComposition(terminalElement)) {
window.setTimeout(send, 0)
return
}
```

Test

New regression case in `terminal-ime-deferred-newline.test.ts`: with no pending composition, `sendTerminalInputAfterComposition` sends on the next macrotask instead of waiting for the 200ms fallback. This test fails on main (`expected 1, got 0` after `advanceTimersByTime(1)`) and passes with the fix.

All 33 existing `terminal-ime-deferred-newline` tests still pass, including the overlapping-transaction and compositionend-flush cases.

Verification

  • `pnpm typecheck` — clean.
  • `pnpm exec vitest run terminal-ime-deferred-newline.test.ts` — 33/33 pass (incl. new regression test, which fails on `main`).
  • `pnpm exec oxlint` + `pnpm exec oxfmt --check` on changed files — clean.
  • (`keyboard-handlers-ime.test.tsx` fails to load on this host due to a pre-existing `@/lib/...` alias resolution issue that also fails on `main`; unrelated to this change.)

Cross-platform / compatibility notes

  • Windows-only in effect (the defer is gated `isWindows` in `keyboard-handlers.ts`); macOS/Linux paths untouched.
  • Agent-agnostic: applies to any agent whose Shift+Enter enters the defer (Pi, and any other modified-Enter user). This is the likely root cause of the Pi-specific freeze reported in [Bug]: Pi agent input freezes briefly on Shift+Enter newline (other CLI agents unaffected) #10203; the "only Pi" framing there is most likely because Pi is where multiline Shift+Enter input is most used.
  • No UI/visual change. No perf risk — it removes a 200ms wait, and the pending-composition check is a `WeakMap` lookup.
  • IME correctness preserved: real pending compositions still defer until `compositionend`/transaction end.

Reviewer checklist

  • Cross-platform: Windows fix; macOS/Linux untouched
  • SSH/remote/local: input path is renderer-local; unaffected by transport
  • Agent/integration: agent-agnostic; no per-agent config changed
  • Performance: removes a 200ms hold; check is O(1)
  • Security: no new surface

Closes #10203

X handle: @itisvincent

… composition (stablyai#10203)

sendTerminalInputAfterComposition armed a 200ms fallback timer and waited
for compositionend even when no IME composition was actually pending. On
Windows, Shift+Enter is a modified-Enter chord routed through this defer
(keyboard-handlers.ts), while non-Enter chords like Alt+J bypass it, so
every Shift+Enter newline was held up to the full 200ms fallback - seen
as a brief input/cursor freeze before the newline was accepted.

Only hold the newline while a composition is genuinely pending
(hasPendingTerminalImeComposition); otherwise send on the next
macrotask, matching the no-terminal-element path. Genuine pending
compositions still wait for compositionend / the captured xterm
transaction to settle, preserving IME correctness.
@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

sendTerminalInputAfterComposition now checks for pending IME composition before registering deferred listeners and the fallback timer. When no composition is pending, it schedules send on the next macrotask. A regression test verifies that the callback runs within one millisecond.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the terminal IME deferral fix for the Shift+Enter delay when no composition is pending.
Description check ✅ Passed The description explains the user-visible issue, root cause, fix, testing, compatibility, security, and absence of visual changes.
Linked Issues check ✅ Passed The implementation addresses issue #10203 by removing the Windows Shift+Enter delay without an active IME composition and adds regression coverage.
Out of Scope Changes check ✅ Passed The changes are limited to terminal IME newline handling and its regression test, which directly support issue #10203.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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: 69d72b9f-8858-46a0-b3cc-be5d509b1a33

📥 Commits

Reviewing files that changed from the base of the PR and between 79251d7 and 2b163ba.

📒 Files selected for processing (2)
  • 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 +50 to +58
it('sends on the next macrotask when no composition is pending instead of waiting for the fallback (#10203)', () => {
const el = document.createElement('div')
const send = vi.fn()

sendTerminalInputAfterComposition(el, send)
// Why: with no pending composition the newline must not be held for the 200ms fallback.
vi.advanceTimersByTime(1)
expect(send).toHaveBeenCalledTimes(1)
})

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

Assert that delivery is asynchronous.

The test only checks that send runs after advancing timers. A synchronous send() implementation would also pass. Assert that send has not been called before advancing the timer.

Proposed test fix
     sendTerminalInputAfterComposition(el, send)
+    expect(send).not.toHaveBeenCalled()
     // Why: with no pending composition the newline must not be held for the 200ms fallback.
     vi.advanceTimersByTime(1)
📝 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
it('sends on the next macrotask when no composition is pending instead of waiting for the fallback (#10203)', () => {
const el = document.createElement('div')
const send = vi.fn()
sendTerminalInputAfterComposition(el, send)
// Why: with no pending composition the newline must not be held for the 200ms fallback.
vi.advanceTimersByTime(1)
expect(send).toHaveBeenCalledTimes(1)
})
it('sends on the next macrotask when no composition is pending instead of waiting for the fallback (`#10203`)', () => {
const el = document.createElement('div')
const send = vi.fn()
sendTerminalInputAfterComposition(el, send)
expect(send).not.toHaveBeenCalled()
// Why: with no pending composition the newline must not be held for the 200ms fallback.
vi.advanceTimersByTime(1)
expect(send).toHaveBeenCalledTimes(1)
})

@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes a ~200ms input freeze on Windows when pressing Shift+Enter by short-circuiting the IME deferred-newline path when no composition is actually pending. Previously sendTerminalInputAfterComposition always armed a 200ms fallback timer; now it immediately schedules setTimeout(send, 0) if hasPendingTerminalImeComposition returns false, matching the existing null-element path.

  • Production fix (terminal-ime-deferred-newline.ts): adds an early-return guard that uses the WeakMap-backed hasPendingTerminalImeComposition check; genuine pending compositions continue to wait for compositionend / XTERM_COMPOSITION_SESSION_END_EVENT as before.
  • Regression test (terminal-ime-deferred-newline.test.ts): new case verifies that with no pending composition the send fires within 1 ms (advanceTimersByTime(1)) rather than waiting for the 200 ms fallback.

Confidence Score: 4/5

The production fix is safe to merge — it removes a guaranteed 200ms hold on every non-IME modified-Enter (Shift+Enter) on Windows, and genuine pending compositions continue through the original deferred path unchanged.

The two-line guard in terminal-ime-deferred-newline.ts is straightforward and correct. The only concern is in the test file: several existing tests that were designed to exercise the compositionend listener and the 200ms fallback now silently take the new fast path (because they use bare div elements with no pending composition primed in the WeakMap). Those code paths remain untested. The production behavior for IME users is preserved, so this is a test-coverage gap rather than a functional regression.

Files Needing Attention: src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.test.ts — tests that dispatch compositionend now exercise the fast path, leaving the compositionend listener and the 200ms fallback for genuine compositions without coverage.

Important Files Changed

Filename Overview
src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.ts Adds an early-return fast path when no IME composition is pending, removing the 200ms delay for modified-Enter keys like Shift+Enter; the deferred path for genuine compositions is unchanged.
src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.test.ts Adds one new regression test verifying the 0ms fast path; however, existing tests that dispatch compositionend now silently exercise the fast path (no pending composition) rather than the compositionend listener in the deferred path, leaving that listener and the 200ms fallback for genuine compositions untested.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["sendTerminalInputAfterComposition"] --> B{"terminalElement null?"}
    B -- yes --> C["setTimeout(send,0) — existing null path"]
    B -- no --> D{"hasPendingImeComposition?"}
    D -- "false — NEW fast path" --> E["setTimeout(send,0) — skip 200ms wait"]
    D -- "true — existing deferred path" --> F["Register compositionend + SESSION_END listeners\nArm 200ms fallback timer"]
    F --> G{"compositionend or SESSION_END fires"}
    G -- "pending == false" --> H["finish: clear listeners/timer\nsetTimeout(send,0)"]
    G -- "still pending" --> G
    F --> I["200ms fallback fires — finish()"]
    H --> J["send called"]
    I --> J
    C --> J
    E --> J
Loading

Comments Outside Diff (1)

  1. src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.test.ts, line 25-38 (link)

    P2 Test now exercises the fast path, not the compositionend listener

    After the fix, sendTerminalInputAfterComposition checks hasPendingTerminalImeComposition before registering any listeners. Because this test uses a plain document.createElement('div') with no prior XTERM_COMPOSITION_SESSION_START_EVENT, the element is absent from the WeakMap, so the function exits early via setTimeout(send, 0) and never attaches onCompositionEnd. The el.dispatchEvent(new Event('compositionend')) call on line 32 lands on an element with no listener, and vi.runAllTimers() fires only the 0ms macro-task timeout — not the compositionend-triggered path the test was designed to cover.

    This means a regression in the compositionend event listener (e.g. accidental removal, wrong guard) or in the 200ms fallback for genuinely pending compositions would not be caught by any test in this file. To restore coverage, the test would need to install a composition route on el, dispatch a XTERM_COMPOSITION_SESSION_START_EVENT to prime the WeakMap, and then exercise the compositionend / SESSION_END paths through the deferred branch.

    Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Reviews (1): Last reviewed commit: "fix(terminal): stop the IME newline defe..." | Re-trigger Greptile

@itisvincent

Copy link
Copy Markdown
Contributor Author

Closing — the IME deferred-newline path is NOT the cause

Runtime diagnostic on Windows (v1.4.167 + a console.warn in the Shift+Enter policy) confirmed:

  • No [S+Enter DEFER] appeared in the DevTools console — the IME deferred-newline path (sendTerminalInputAfterComposition) was NOT firing.
  • The freeze was CSI-u decode cost (\x1b[13;2u is slow for Pi to parse), not a 200ms IME delay.
  • The encoding flickered between csi-u (newline with freeze) and alt-enter (submit) — a routingTrusted gate issue, not an IME issue.

The correct fix is in #12299 (LF encoding + launch-agent fallback), which:

  • Sends \n (1 byte, Pi binds as Ctrl+J newline) instead of CSI-u — no decode freeze.
  • Uses the launch agent as fallback when routingTrusted flickers — no submit.

This (#11778) targeted the wrong layer. Closing.

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]: Pi agent input freezes briefly on Shift+Enter newline (other CLI agents unaffected)

3 participants