Skip to content

fix(terminal): defer IME newline dispatch - #11052

Closed
nwparker wants to merge 4 commits into
stablyai:mainfrom
nwparker:nwparker/fix-korean-ime-newline
Closed

nwparker wants to merge 4 commits into
stablyai:mainfrom
nwparker:nwparker/fix-korean-ime-newline

Conversation

@nwparker

Copy link
Copy Markdown
Contributor

Summary

  • defer composing Enter chords until compositionend commits the trailing IME text
  • preserve Shift+Enter and Ctrl+Enter modifiers while deferring the newline
  • absorb the macOS redispatched Enter so each chord reaches the PTY exactly once
  • add unit coverage for composition ordering and the original CDP Korean IME regression

Reproduction

The unchanged CDP scenario reproduced two failures before the fix: Shift+Enter submitted an empty line instead of the completed Korean text, while Ctrl+Enter split the text around duplicate encoded Enter sequences. The terminal now commits the final syllable before emitting one modified newline chord.

Validation

  • 12 focused IME state-machine tests
  • Korean IME Electron E2E: 2/2 passing (Shift+Enter and Ctrl+Enter)
  • pnpm typecheck:web
  • pnpm check:max-lines-ratchet
  • git diff origin/main...HEAD --check

Closes #10842

@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

Failed to post review comments.

We encountered an issue with GitHub. Use @coderabbitai full review to retry the review.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b39b5620-a8bb-49ec-a316-65dfc5cbd78c

📥 Commits

Reviewing files that changed from the base of the PR and between 206b2c81b93c8be8e6610a01993b9419b971a66c and 2d50cdb.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (11)
  • config/patches/@[email protected]
  • src/renderer/src/components/terminal-pane/keyboard-handlers.ts
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-captured-input-dispatch.test.ts
  • src/renderer/src/components/terminal-pane/terminal-captured-input-dispatch.ts
  • 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.test.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/renderer/src/components/terminal-pane/terminal-captured-input-dispatch.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.test.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.ts
  • src/renderer/src/components/terminal-pane/terminal-captured-input-dispatch.test.ts
  • src/renderer/src/components/terminal-pane/keyboard-handlers.ts
⏰ Context from checks skipped due to timeout. (14)
  • GitHub Check: e2e / e2e 8-of-10
  • GitHub Check: e2e / e2e 4-of-10
  • GitHub Check: e2e / e2e 9-of-10
  • GitHub Check: e2e / e2e 6-of-10
  • GitHub Check: e2e / e2e 10-of-10
  • GitHub Check: e2e / e2e 5-of-10
  • GitHub Check: e2e / e2e 7-of-10
  • GitHub Check: e2e / e2e 1-of-10
  • GitHub Check: e2e / e2e 3-of-10
  • GitHub Check: e2e / e2e 2-of-10
  • GitHub Check: e2e / ssh docker watcher isolation
  • GitHub Check: Greptile Review
  • GitHub Check: Windows terminal restart regressions
  • GitHub Check: crash-survival (packaged build)
🧰 Additional context used
📓 Path-based instructions (5)
**/*

📄 CodeRabbit inference engine (AGENTS.md)

Do not use vague names such as helpers, utils, common, misc, or shared-stuff for files, folders, or modules; use concrete domain names and split responsibilities when necessary.

Files:

  • config/patches/@[email protected]
  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • 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/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.ts
src/renderer/src/**/*.{css,scss,tsx,ts}

📄 CodeRabbit inference engine (AGENTS.md)

All UI work—including layout, color, typography, spacing, component selection, and UX behavior—must follow docs/STYLEGUIDE.md, use tokens from src/renderer/src/assets/main.css, and use shadcn primitives from src/renderer/src/components/ui/; do not invent documented design values.

Files:

  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • 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/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx,js,jsx}: Comments must be concise, limited to non-obvious information, and preferably one line; do not explain obvious code or walk through implementation details.
Keep platform-dependent behavior behind runtime checks for macOS, Linux, and Windows. Use platform-aware keyboard shortcuts, CmdOrCtrl for Electron accelerators, platform-specific shortcut labels, and path utilities such as path.join instead of hardcoded separators.
Git commands must remain compatible with Git 2.25 across native, WSL, and SSH hosts. Check subcommand and option introduction versions, provide safe fallbacks, use host-scoped GitCapabilityCache with narrow unsupported-error handling, test caching/concurrency/host isolation, maintain real-binary compatibility CI, and preserve global options such as -c before subcommands.
Source-control and review changes must support GitLab and other supported providers; keep provider-specific behavior behind explicit checks and avoid GitHub-only names for generic review concepts.

Files:

  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • 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/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Never add max-lines disable directives, including eslint-disable max-lines, oxlint-disable max-lines, or line-specific variants.

Files:

  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • 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/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.ts
**/*.{ts,tsx,js,jsx,sh,ps1}

📄 CodeRabbit inference engine (AGENTS.md)

Use the user's gh CLI rate limit carefully by batching requests and avoiding unnecessary calls; code, commands, and scripts must work on macOS, Linux, and Windows.

Files:

  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • 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/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.ts
🧠 Learnings (7)
📚 Learning: 2026-06-16T15:35:16.815Z
Learnt from: gsxdsm
Repo: stablyai/orca PR: 5501
File: src/renderer/src/components/right-sidebar/checks-panel-content.tsx:1504-1504
Timestamp: 2026-06-16T15:35:16.815Z
Learning: In the stablyai/orca renderer codebase, Tailwind classes using the custom variant `can-hover` (e.g., `can-hover:opacity-0`) are intentionally treated as self-documenting, with the hover/pointer-only rationale defined once at `src/renderer/src/assets/main.css` via `custom-variant can-hover (media (hover: hover))`. When reviewing `.ts/.tsx` files, do not flag usage sites for missing inline “why” comments or duplicated rationale—assume the variant name and its central definition provide sufficient context.

Applied to files:

  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • 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/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.ts
📚 Learning: 2026-07-21T20:38:08.166Z
Learnt from: brennanb2025
Repo: stablyai/orca PR: 9765
File: src/renderer/src/popout.tsx:62-64
Timestamp: 2026-07-21T20:38:08.166Z
Learning: When calling the Zustand action `fetchKeybindings()` from `src/renderer/src/store/slices/keybindings.ts`, do not add redundant `.catch(() => undefined)` (or similar error-swallowing wrappers) just to handle keybinding IPC failures. `fetchKeybindings()` already catches and logs failures from `window.api.keybindings.get()` without rethrowing, so callers like `src/renderer/src/popout.tsx` can rely on that behavior unless they intentionally need different error handling/side effects.

Applied to files:

  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • 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/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.ts
📚 Learning: 2026-06-24T11:33:31.894Z
Learnt from: gatsby74
Repo: stablyai/orca PR: 6256
File: src/renderer/src/components/terminal-pane/terminal-agent-session-fork.test.ts:83-84
Timestamp: 2026-06-24T11:33:31.894Z
Learning: When reviewing *.test.ts files, treat hardcoded OS-specific path literals used as mock fixture inputs (e.g., Windows `C:\...`, UNC paths like `\\wsl.localhost\Ubuntu\...`, and POSIX `/repo/...`) as intentional if they exist to simulate real platform path formats for path/launch-platform detection logic. Do not replace these static fixture strings with `path.join` or other runtime path construction utilities—doing so can make assertions OS-dependent and break test determinism. Reserve `path.join` guidance for production/runtime path construction, not for static test fixture strings used to exercise detection/parsing logic.

Applied to files:

  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-composition-route.test.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.ts
📚 Learning: 2026-07-08T00:01:30.534Z
Learnt from: wquintal
Repo: stablyai/orca PR: 7734
File: src/renderer/src/components/right-sidebar/gitlab-check-details-loader.ts:29-41
Timestamp: 2026-07-08T00:01:30.534Z
Learning: In the stablyai/orca Electron renderer, avoid unbounded/bare GitLab IPC calls (e.g., `window.api.gl.jobTrace`, `workItemDetails`, `resolveMRDiscussion`, `updateMR`, and the job-trace call used in GitLab item dialogs/components). Add/use a shared renderer-side timeout wrapper/utility (since there is no shared `withTimeout` currently, create one or reuse the existing implementation pattern from `useCreateProjectDefaults.ts`) and apply it consistently to all such `window.api.gl.*` calls, rather than fixing a single call site in isolation. The goal is to ensure each IPC request has an explicit timeout so hangs can’t block the UI indefinitely.

Applied to files:

  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • 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/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.ts
📚 Learning: 2026-07-22T10:22:46.721Z
Learnt from: kespineira
Repo: stablyai/orca PR: 9900
File: src/renderer/src/components/terminal-pane/TerminalPane.tsx:2056-2060
Timestamp: 2026-07-22T10:22:46.721Z
Learning: In the terminal-pane lifecycle/key handling code, ensure that every terminal pane installs `pane.terminal.attachCustomKeyEventHandler` and that the handler consults `shouldBypassXtermKeyboardEvent` (from `xterm-bypass-policy.ts`). When the policy requests a bypass, the handler must return `false` so the browser/host native paste pipeline runs and the chord never reaches terminal PTY input. The bypass policy should trigger for paste chords: macOS `Mod+V`, and Windows/Linux `Ctrl+V`, `Ctrl+Shift+V`, and `Shift+Insert`.

Applied to files:

  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • 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/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.ts
📚 Learning: 2026-07-22T18:28:59.997Z
Learnt from: OrcaWin
Repo: stablyai/orca PR: 9925
File: src/main/ipc/runtime-environment-shared-control-support.ts:4-7
Timestamp: 2026-07-22T18:28:59.997Z
Learning: In TypeScript, identifiers brought in via `import type` can be referenced inside purely type-level expressions (e.g., `ReturnType<typeof importedIdentifier>` or other `typeof` queries that are used only in a type position). Because the usage occurs entirely in the type space, it should not be treated as requiring a runtime import. In code review, do not require converting that `import type` to a value import when the identifier is only used within type queries/types.

Applied to files:

  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • 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/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.ts
📚 Learning: 2026-07-28T01:28:17.192Z
Learnt from: brennanb2025
Repo: stablyai/orca PR: 10865
File: src/main/skills/skill-plugin-cache-scan.test.ts:0-0
Timestamp: 2026-07-28T01:28:17.192Z
Learning: In test files under src/**/*.test.ts, any test that creates filesystem symlinks (e.g., via fs.symlink/fs.symlinkSync) should be guarded with `it.skipIf(process.platform === 'win32')` (or equivalent `it.skipIf` usage). Ordinary Windows CI environments may not have the elevation or Developer Mode permissions required for symlink creation, and the symlink-dependent test assertions won’t have reliable Windows coverage.

Applied to files:

  • src/renderer/src/components/terminal-pane/pty-connection.test.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-composition-route.test.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.ts
🪛 Betterleaks (1.7.0)
config/patches/@[email protected]

[high] 6-6: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


[high] 7-7: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

📝 Walkthrough

Walkthrough

Adds IME-aware deferred newline handling for terminal keyboard shortcuts, including redispatched Enter absorption and lifecycle cleanup. Captured terminal input now verifies pane mounting and PTY ownership before dispatch, with reconfirmation guarded by binding identity. Composition sessions are routed only while captured PTY ownership remains valid and are disposed with the connection. Unit tests and a Playwright suite validate Hangul composition, Enter chord timing, PTY bytes, submitted lines, and stale-state behavior.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers summary and validation, but it omits required Screenshots, AI Review Report, Security Audit, and Notes sections. Add the missing template sections and include the requested testing checklist entries or mark them as not run.
Docstring Coverage ⚠️ Warning Docstring coverage is 4.17% which is insufficient. The required threshold is 80.00%. 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 is concise and accurately describes the main change: deferring IME newline dispatch.
Linked Issues check ✅ Passed The IME newline deferral, macOS Enter absorption, and Korean IME regression tests directly address issue #10842.
Out of Scope Changes check ✅ Passed The new IME helpers, pty wiring, and tests are all aligned with the Korean IME fix and show no clear unrelated changes.

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.

🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/terminal-captured-input-dispatch.test.ts (1)

16-52: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

it.each here runs the same test twice with no route-specific difference.

Both iterations construct an identical mock transport and ignore the parameter, so the titles claim local-IPC vs SSH coverage the assertions don't provide. Either drop the it.each or thread the route into the fixture so it actually varies.

♻️ Collapse to a single test
-  it.each(['local IPC', 'SSH remote runtime'])(
-    'sends on the captured %s route while its PTY still owns the mounted pane',
-    () => {
-      const transport = createTransport('pty-original')
+  it('sends on the captured route while its PTY still owns the mounted pane', () => {
+    const transport = createTransport('pty-original')
 
-      expect(
-        sendCapturedTerminalInput({
-          targetPaneMounted: true,
-          currentTransport: transport,
-          capturedTransport: transport,
-          capturedPtyId: 'pty-original',
-          data: '\r'
-        })
-      ).toBe(true)
-      expect(transport.sendInput).toHaveBeenCalledWith('\r')
-    }
-  )
+    expect(
+      sendCapturedTerminalInput({
+        targetPaneMounted: true,
+        currentTransport: transport,
+        capturedTransport: transport,
+        capturedPtyId: 'pty-original',
+        data: '\r'
+      })
+    ).toBe(true)
+    expect(transport.sendInput).toHaveBeenCalledWith('\r')
+  })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d6a3710c-69fd-491d-b373-70de72253fbb

📥 Commits

Reviewing files that changed from the base of the PR and between badf911 and 206b2c81b93c8be8e6610a01993b9419b971a66c.

📒 Files selected for processing (6)
  • src/renderer/src/components/terminal-pane/keyboard-handlers.ts
  • src/renderer/src/components/terminal-pane/terminal-captured-input-dispatch.test.ts
  • src/renderer/src/components/terminal-pane/terminal-captured-input-dispatch.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.test.ts
  • src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.ts
  • tests/e2e/korean-ime-terminal-shift-enter-commit.spec.ts

@Jinwoo-H
Jinwoo-H force-pushed the nwparker/fix-korean-ime-newline branch from 206b2c8 to 2d50cdb Compare July 28, 2026 22:39
Comment on lines +62 to +93
const onSessionEnd = (event: Event): void => {
const detail = getCompositionDetail(event)
if (!detail) {
return
}
event.preventDefault()
const captured =
session?.id === detail.id
? session
: previousSession?.id === detail.id
? previousSession
: null
if (!captured) {
return
}
if (session === captured) {
session = null
}
if (previousSession === captured) {
previousSession = null
}
if (
disposed ||
!detail.data ||
captured.ptyId === null ||
args.getCurrentTransport() !== args.capturedTransport ||
args.capturedTransport.getPtyId() !== captured.ptyId
) {
return
}
args.terminal.input(detail.data)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 preventDefault called before captured is resolved

event.preventDefault() fires at line 67 regardless of whether captured resolves to a non-null session. When getCompositionDetail returns a valid detail but the session ID does not match either tracked slot (e.g., a duplicate end event or a session that was already cleared), the event is cancelled unconditionally. If the xterm patch ever checks defaultPrevented on the dispatched event to skip its own fallback, an orphaned end event would silently suppress that path. Moving the preventDefault() call to after the if (!captured) { return } guard would make the contract explicit — the event is only consumed when this route is actually handling it.

Comment on lines +91 to +99
absorbRedispatchedEnter: (enter) => {
const state = statesByEnterCode.get(enter.code)?.get(enter.timeStamp)
if (!state || state.absorbCredits <= 0) {
clearCreditsForCode(enter.code)
return false
}
state.absorbCredits -= 1
cleanUpIfSettled(enter, state)
return true

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 clearCreditsForCode invalidates credits for all concurrent Enter cycles

When absorbRedispatchedEnter is called with a timestamp that has no credit (either !state or state.absorbCredits <= 0), it calls clearCreditsForCode which zeroes credits for every timestamp tracked under the same key code. In the unlikely-but-possible case of two overlapping IME compositions (e.g., fast Korean chord entry on a slow host), the second arrival of a spent credit for timestamp A would also clear the unspent credit for a still-in-flight timestamp B, causing B's subsequent macOS re-dispatch to pass through un-absorbed and produce a duplicate newline. The existing tests cover the intended semantics, but this cross-timestamp side-effect of the "stale credit" retirement path is not covered by an explicit multi-cycle overlap + spent-credit test.

@greptile-apps

greptile-apps Bot commented Jul 28, 2026

Copy link
Copy Markdown

Greptile Summary

This PR fixes a Korean IME race on macOS where pressing Shift+Enter or Ctrl+Enter during an active composition would either submit an empty line or produce duplicate encoded Enter sequences. The root cause was that macOS delivers the committing Enter chord twice — first as an IME Process keydown (isComposing=true, keyCode 229), then as a re-dispatched plain keydown (isComposing=false, keyCode 13) roughly 2 ms after compositionend — and the PTY received both.

  • Adds terminal-ime-deferred-newline.ts: a state machine that defers composing-Enter sends until compositionend fires (with a 200 ms fallback), issues one "absorb credit" per deferred send, and absorbs the macOS re-dispatched Enter by timestamp match so each chord reaches the PTY exactly once.
  • Adds terminal-ime-composition-route.ts: routes xterm's custom xterm-composition-session-end events directly to the PTY transport, with PTY-identity staleness guards, replacing the previous path that could double-emit committed glyphs through xterm's keypress pipeline.
  • Extends the xterm patch and validates it with a new terminal-ime-xterm-composition-deduplication test suite and a CDP-level E2E spec that replays the exact macOS Hangul commit sequence in both redispatch-before-keyup and keyup-before-redispatch orderings.

Confidence Score: 4/5

Safe to merge; the core IME race is correctly fixed and well-tested across unit, integration, and E2E layers

The deferred-newline state machine and composition-route logic are sound and backed by thorough tests. Two minor defensive concerns exist: event.preventDefault() fires before the !captured null-guard in terminal-ime-composition-route.ts, which could silently cancel a custom event the route does not intend to handle; and clearCreditsForCode in absorbRedispatchedEnter wipes credits for all concurrent Enter timestamps when any one of them is already spent, which could cause a duplicate newline in overlapping IME cycles — a practically rare edge case not covered by the existing tests.

Files Needing Attention: terminal-ime-deferred-newline.ts (cross-timestamp credit invalidation) and terminal-ime-composition-route.ts (early preventDefault before null-guard)

Important Files Changed

Filename Overview
src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.ts New module implementing the deferred-newline state machine; logic is sound and thoroughly tested, but clearCreditsForCode in absorbRedispatchedEnter has a cross-timestamp side-effect in overlapping Enter cycles
src/renderer/src/components/terminal-pane/terminal-ime-composition-route.ts New module routing xterm custom composition events to the PTY transport; event.preventDefault() is called before the !captured null-guard, which could silently cancel events the route does not intend to handle
src/renderer/src/components/terminal-pane/keyboard-handlers.ts Integrates deferred-newline sender and absorb-redispatch logic cleanly; absorb check correctly positioned after scope guard and before shortcut resolution; e.keyCode === 13 guard reliably distinguishes real from Process-key Enter
src/renderer/src/components/terminal-pane/pty-connection.ts Minimal surgical addition of installTerminalImeCompositionRoute with proper disposal on pane teardown
src/renderer/src/components/terminal-pane/terminal-captured-input-dispatch.ts Extracted staleness guard for deferred input delivery; straightforward and correctly tested
tests/e2e/korean-ime-terminal-shift-enter-commit.spec.ts Comprehensive E2E harness using CDP to replay the exact macOS Hangul commit sequence; covers both redispatch orderings and a modifier-lost variant; proper cleanup in finally
src/renderer/src/components/terminal-pane/terminal-ime-deferred-newline.test.ts 12 unit tests covering fallback timer, double-send guards, cross-cycle credit isolation, blur cleanup, and null-element path
src/renderer/src/components/terminal-pane/terminal-ime-xterm-composition-deduplication.test.ts Validates xterm patch behavior with real Terminal instances including IBus Hangul de-duplication, blur/focus ordering, and Escape cancellation
src/renderer/src/components/terminal-pane/pty-connection.test.ts Single test assertion update — filters by event type rather than counting all addEventListener calls, correctly accommodating the new composition route listeners

Sequence Diagram

sequenceDiagram
    participant OS as macOS IME
    participant KB as keyboard-handlers
    participant DNS as DeferredNewlineSender
    participant SATC as sendAfterComposition
    participant xterm as xterm element
    participant PTY as PTY Transport

    OS->>KB: "keydown isComposing=true keyCode=229 Enter t=100"
    KB->>DNS: "defer enter t=100 element sendResolvedInput"
    DNS->>SATC: register compositionend listener and 200ms fallback
    KB->>KB: preventDefault stopImmediatePropagation

    OS->>xterm: compositionend glyph committed
    xterm->>SATC: compositionend fires
    SATC->>SATC: clearTimeout fallback then setTimeout send 0

    OS->>KB: "keydown isComposing=false keyCode=13 Enter t=100 re-dispatch"
    KB->>DNS: "absorbRedispatchedEnter enter t=100"
    DNS-->>KB: true credit consumed
    KB->>KB: preventDefault stopImmediatePropagation re-dispatch absorbed

    Note over SATC: macrotask fires
    SATC->>PTY: sendResolvedInput one newline after glyph flush
    DNS->>DNS: cleanUpIfSettled state deleted
Loading

Reviews (1): Last reviewed commit: "fix(terminal): complete IME composition ..." | Re-trigger Greptile

@Jinwoo-H

Copy link
Copy Markdown
Contributor

Closing as superseded by #11293, which incorporated this PRs IME Enter/newline ordering work while preserving contributor authorship and reconciling it with the broader xterm composition fixes. The merged implementation passes the complete #11052 regression matrix (50/50), combined IME coverage, native Linux IBus coverage, and platform CI. Thank you @nwparker for the original fix.

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] Issue when typing in Korean

3 participants