Skip to content

fix(terminal): let unselected Cmd+C reach keyboard encoding - #22950

Closed
Jinwoo-H wants to merge 4 commits into
mainfrom
fix/terminal-copy-fallthrough
Closed

Jinwoo-H wants to merge 4 commits into
mainfrom
fix/terminal-copy-fallthrough

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​276 $\color{#cf222e}{\Huge{\mathbf{−}}}$​43 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​233
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​18 $\color{#cf222e}{\Huge{\mathbf{−}}}$​37 $\color{#cf222e}{\Huge{\mathbf{−}}}$​19

ELI5

Cmd+C can now reach a terminal application that owns its highlighted text. Copying a terminal selection still works as before, and pressing Cmd+C in an ordinary shell sends no extra input.

What Changed

Previously, macOS Cmd+C always skipped xterm's keyboard encoder, even when the terminal had nothing to copy. Now it falls through when the pane has no selection and the application has enabled the Kitty keyboard protocol. The existing encoder and input transport deliver the chord.

Ctrl+C also preserves the running application's negotiated keyboard mode. Previously it unconditionally reset the encoder, so an application that handled Ctrl+C without exiting lost subsequent Cmd+C input. The unused immediate-reset helper is removed; existing cleanup after a confirmed program exit remains responsible for restoring shell modes.

Selection copying also uses the existing shortcut tracker to suppress the matching key release. Held copy shortcuts remain claimed while a selection exists, including custom bindings.

Why

An application-owned highlight is not an xterm selection. Letting the existing encoder handle the chord preserves negotiated modifiers and event reporting without introducing application detection, hardcoded input bytes, or another transport path. Requiring active protocol flags keeps ordinary shells protected. A keypress alone cannot establish that a program exited, so the fix reuses existing exit recovery instead of adding a timer or another process check.

Linked Issue

Related to #9727: addresses the macOS Cmd+C path for applications that negotiate keyboard reporting. This does not change every shortcut or application described in that issue.

Visual Proof

Same hidden Electron test against the original and updated implementations. Before: the test stops at COPY_MODE_1 because Cmd+C produces no input. After: the application prints received key bytes through all modes, and selection-copy checks pass. These demonstrate terminal input delivery with a deterministic application, not a live third-party CLI session. The expanded test also verifies Cmd+C after Ctrl+C and normal shell input after the application dies without restoring its modes.

Before After
Before After

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

macOS validation, with all apps hidden and ORCA_BACKGROUND_LAUNCH=1:

  • 154 focused tests passed, including interrupt handling, terminal lifecycle, confirmed-exit recovery, and existing Windows keyboard-reset coverage.
  • The Electron regression test fails before the interrupt fix because Cmd+C produces no bytes after Ctrl+C. Both focused Electron tests pass after rebuilding. It covers protocol flags 0, 1, 3, and 31; both shortcut policies; clipboard copying; custom copy bindings; repeats; and release after the selection disappears.
  • Attached playwright-cli over CDP to a separate hidden test app from this workspace and inspected the full rendered screenshot, including the received input and successful shell command.
  • pnpm tc, pnpm run check:code-quality:changed, and pnpm run audit:anti-slop passed. The latter reproduces the previously failing CI check; the test now uses a typed xterm core lookup.
  • The optional full typecheck:e2e still reports errors outside this change; the new copy regression spec has no remaining diagnostics.
  • The Electron app built successfully in e2e mode. Full lint/test and other-platform builds are left to CI.

Reproduce: ORCA_BACKGROUND_LAUNCH=1 pnpm exec playwright test tests/e2e/terminal-copy-fallback.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1.

Not exercised: physical keyboard events, live third-party CLI sessions, SSH sessions, folder workspaces, Linux, or Windows. The change uses pane-local selection/protocol state and the existing transport; it adds no host, repository, or wire assumptions. Unclean-exit recovery was verified with shell integration active. Without shell lifecycle signals or host proof of exit, this change does not introduce a new crash-recovery mechanism.

Review

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

No new clipboard permissions, remote messages, or per-keystroke process lookups. The non-macOS bypass rules and paste path are unchanged.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The changes update macOS terminal copy bypass behavior for Kitty keyboard modes and allow repeated copy-selection shortcuts to resolve. Clipboard copying and native-only shortcut tracking occur only for non-repeated events when a selection exists. The changes also remove the keyboard-protocol reset after interrupt input. Tests cover event handling, Kitty modes, PTY writes, and default and remapped shortcuts.

Priority: ➖ Normal

Merge Risk: 🔵 Low · up to 4cf86

The terminal copy tests may miss a broken remapped shortcut or delayed terminal input. The change is mergeable with owner awareness, though strengthening these assertions would give better regression protection.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 4cf86

The changed shortcut can reach the application in the active terminal pane, but selection copying remains protected and no broader permission or service boundary change was identified. Recovery in less common terminal sessions is not fully established.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — Application-controlled terminal output can influence whether an unselected Cmd+C reaches input encoding, but the decision uses the active pane's flags and routes input to that pane's terminal; no cross-pane destination is shown.

Trust Boundaries and Controls

  • observed — A selected copy chord remains owned by the renderer: its event is prevented, only the initial press initiates a clipboard write, and the companion release is tracked. With no selection, clipboard copying is not initiated by this dispatcher.

Resilience and Maintainability Implications

  • inferred — Resetting flags on PTY exit and replacement limits stale-mode inheritance by a new PTY. The supplied recovery test does not independently prove that every child-process exit or remote reattach clears the pane-local routing flag.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 4 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: allowing unselected macOS Cmd+C events to reach keyboard encoding.
Description check ✅ Passed The description is complete and focused. It explains the user impact, implementation, rationale, linked issue, visual proof, testing, limitations, and checklist status. The linked issue is referenced …
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🛠️ Fix failing CI checks 💡
  • Commit to this branch
  • Create a new PR

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

🧹 Nitpick comments (1)
tests/e2e/terminal-copy-fallback.spec.ts (1)

94-94: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Reset the clipboard before each copy attempt.

Both iterations select the same text. After the first iteration, the clipboard already contains the expected value. If the remapped shortcut fails in the second iteration, its clipboard assertion can still pass. The PTY write assertion does not detect this because a failed copy produces no PTY write.

🐛 Suggested fix
       })
       expect(selectedText).toBe('Terminal copy selection')
+      await electronApp.evaluate(
+        ({ clipboard }, text) => clipboard.writeText(text),
+        `copy-sentinel-${remapped}`
+      )
       await clearTerminalPtyWriteLog(electronApp)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 5a39be11-dcb1-4641-9b6a-f569fb04ca5a

📥 Commits

Reviewing files that changed from the base of the PR and between 2796a3a and 510e53c.

📒 Files selected for processing (6)
  • src/renderer/src/components/terminal-pane/terminal-copy-shortcut.test.ts
  • src/renderer/src/components/terminal-pane/terminal-keyboard-action-dispatch.ts
  • src/renderer/src/components/terminal-pane/terminal-shortcut-policy.ts
  • src/renderer/src/components/terminal-pane/xterm-bypass-policy.test.ts
  • src/renderer/src/components/terminal-pane/xterm-bypass-policy.ts
  • tests/e2e/terminal-copy-fallback.spec.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

await orcaPage.keyboard.press('Meta+c')
const press = flags === 31 ? '\x1b[99;9;99u' : '\x1b[99;9u'
const expected = flags === 0 ? [] : flags === 1 ? [press] : [press, '\x1b[99;9:3u']
await expect.poll(() => readTerminalPtyWrites(electronApp)).toEqual(expected)

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

Wait for PTY writes before asserting that none occurred.

When expected is [], the poll on Line 73 can pass on its first read. The empty-log assertion on Line 114 has the same problem. Playwright dispatches keyboard events, while this spy records PTY writes later in Electron’s main process. A delayed write can therefore escape either assertion. Add a write-processing barrier or a bounded observation period before checking that the log remains empty. (playwright.dev)

Also applies to: 114-114

@pullfrog pullfrog 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.

ℹ️ No critical issues — one scope question and a couple of doc/test nits. The mechanism itself reads correctly and the focused suites pass.

Reviewed changes

Reviewed the macOS Cmd+C fallthrough end to end: the bypass policy, shortcut resolution and dispatch, and the new unit + Electron tests.

  • Kitty-gated macOS Cmd+C fallthrough — shouldBypassXtermKeyboardEvent now bubbles Mod+C on macOS only when the pane has an xterm selection or the app has not negotiated Kitty flags (xterm-bypass-policy.ts:354), so unselected Cmd+C reaches xterm's encoder. Mod+V and the Windows/Linux branch are unchanged.
  • Copy claims repeats and its key release — copySelection now resolves on repeat (terminal-shortcut-policy.ts:109) and dispatch claims repeats without re-copying while arming the native-only shortcut tracker (terminal-keyboard-action-dispatch.ts:82), so the matching keyup stays suppressed even if the selection disappears first.
  • New coverage — a happy-dom unit test for dispatch ownership and remapped-binding repeats, five Kitty-flag cases in the bypass policy test, and a macOS-only Electron spec asserting exact encoded PTY bytes per flag set.

ℹ️ The fix is gated on Kitty negotiation, which the linked repro may not do

The linked issue's primary repro is Claude Code, but the new fallthrough only fires when kittyKeyboardFlags > 0. Claude Code historically enables the Kitty protocol from a terminal-name allow-list rather than answering a CSI ? u capability query, and Orca advertises TERM_PROGRAM=Orca, so it may never negotiate in Orca — leaving the reported Cmd+C no-op in place. The PR's testing notes confirm live third-party CLI sessions were not exercised.

Technical details
# Confirm the target TUI actually negotiates Kitty in Orca

## Affected sites
- `src/renderer/src/components/terminal-pane/xterm-bypass-policy.ts:354-355` — fallthrough requires `(options.kittyKeyboardFlags ?? 0) !== 0`.
- `src/main/providers/local-pty-spawn-environment.ts:29` — Orca sets `TERM_PROGRAM=Orca`.
- `docs/...`/PR body — "Not exercised: ... live third-party CLI sessions".

## Required outcome
- Either confirm the reported app (Claude Code) reaches `kittyKeyboardFlags > 0` inside Orca, or state the narrower supported set in the PR so the linked issue isn't closed on a fix that can't reach it.

## Suggested approach (optional)
- Run the reported repro (`claude` + drag-select + `Cmd+C`) against this build and check the pane's live Kitty flags; if Claude Code stays at `0`, the issue's suggested condition (mouse-tracking ownership, not just Kitty) is what actually needs a gate.

## Open questions for the human
- Is Claude Code expected to negotiate Kitty here, or is this PR deliberately scoped to the subset of TUIs that do (Neovim, etc.)?

## Reference
- Claude Code Kitty enablement gated on terminal-name allow-list: https://claudeissues.com/issue/71700-bug-kitty-keyboard-protocol-gated-on-terminal-name-allow-list-instead-of-csi-u-c

ℹ️ Nitpicks

  • xterm-bypass-policy.test.ts:22 — the title "bubbles Cmd+C even with no selection (no-op copy is harmless on macOS)" only holds when Kitty flags are 0 now; it reads as if the no-selection bypass were unconditional. Worth renaming to note the flags-0 condition.
  • xterm-bypass-policy.ts:28-31 — the hasSelection JSDoc still frames the field as only the Windows/Linux Ctrl+C SIGINT split, but it now also gates the macOS Cmd+C fallthrough. A one-line update keeps the contract discoverable.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

Important

Deleting the Ctrl+C Kitty wipe removes WSL panes' only live recovery after a TUI dies on SIGINT — see the inline note. The interrupt-mode preservation and the reworked tests otherwise read correctly.

Reviewed changes

Reviewed the two commits pushed since the prior review (af37508b, 80f688b), which drop the interrupt-time Kitty reset and rework the interrupt/copy coverage.

  • Interrupt no longer resets Kitty flags — resetTerminalKeyboardProtocolAfterInterrupt and its call in installTerminalPaneInputHandling are deleted, so an application that handles Ctrl+C and keeps running keeps its negotiated mode; a dead TUI is now expected to be recovered by the existing shell-lifecycle barrier.
  • Recovery coverage moved to the barrier — tests/e2e/terminal-copy-fallback.spec.ts now dispatches Ctrl+C while its receiver stays alive (asserting flags persist), then kills it with SIGINT and asserts flags return to 0 and plain shell input works; tests/e2e/terminal-shortcuts.spec.ts asserts flags survive Ctrl+C and resets them explicitly.
  • Regression-test hardening — the copy spec now throws when terminal settings are not loaded instead of spreading undefined, and reads xterm's core flags through a typed lookup.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

}
// Leave keyboard reporting armed and die without running application cleanup.
await sendToTerminal(orcaPage, ptyId, '\x04')
await expect.poll(readKeyboardFlags).toBe(0)

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.

This recovery assertion covers only daemon-backed panes. WSL panes are structurally excluded from the barrier and from the renderer foreground tracker, and this PR removed their only live Kitty reset, so a TUI that dies on SIGINT without restoring its flags can leave a WSL pane encoding subsequent input as CSI-u (the #3941 symptom). Please keep a WSL-safe reset or extend the barrier's shell proof to wsl.exe.

Technical details
# WSL panes lose their only live Kitty recovery

## Affected sites
- `src/renderer/src/components/terminal-pane/terminal-pane-pane-input.ts:144` — the deleted `resetTerminalKeyboardProtocolAfterInterrupt(pane.terminal)` was transport-agnostic and covered every host, WSL included.
- `src/main/providers/agent-foreground-process-wsl-shell-proof.test.ts:4-7` — pins that the recovery barrier "never grounds WSL panes" because the spawned shell is `wsl.exe`.
- `src/renderer/src/components/terminal-pane/pty-connection/pane-agent-identity.ts:133-156` — `isForegroundTrackingAllowed` returns `isLocalNativeWindowsConpty(...)` on Windows, which is false for a WSL cwd/shell, so `onConfirmedShellForeground` (the `POST_REPLAY_REATTACH_RESET` write) never runs.
- `src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts:120` — the non-ConPTY idle reset is `RESET_TERMINAL_CURSOR_STYLE` only; the Kitty reset is appended only for native Windows ConPTY (`direct-ssh-retry-status.ts:89-93`).
- `src/renderer/src/lib/pane-manager/terminal-keyboard-protocol.test.ts:102-113` — Kitty stays enabled for WSL panes, so they can genuinely be left armed.

## Required outcome
- After a TUI dies on SIGINT without restoring its Kitty flags, a WSL pane must return to flags `0` before the shell consumes further input — either by extending the shell-foreground proof to `wsl.exe` so the barrier grounds it, or by keeping a WSL-scoped renderer reset.

## Open questions for the human
- The same dependency applies to SSH/remote panes whose relay does not emit `foregroundProcessEvidence` (which normalizes to `unverifiable`); was mixed-version relay coverage considered?

The Shift+Enter spec armed Kitty flags from a finished command, which the
host now grounds at command exit; let the command disarm its own flags.
The Ctrl+C spec interrupted a fresh tab's shell mid-startup, killing it;
wait for a ready prompt first.

@pullfrog pullfrog 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.

✅ No new issues found in the commit pushed since the prior review.

Reviewed changes

Reviewed 4cf866e — the only commit since the prior pullfrog review — across its three files.

  • Simplified the macOS copy ownership check — shouldBypassXtermKeyboardEvent now extracts appOwnsCopy = !hasSelection && (kittyKeyboardFlags ?? 0) !== 0. The new Mod+C bypass is logically identical to the prior hasSelection || (kittyKeyboardFlags ?? 0) === 0 (checked against 80f688b), so this is a pure refactor with no behavior change.
  • Consolidated the copy unit test — terminal-copy-shortcut.test.ts folds the per-case setup into a dispatchCopy(selection, repeat) helper and asserts claimed / copied / release as one object; the repeat case is now covered explicitly.
  • Stabilized the terminal shortcut e2e — the Shift+Enter spec has its printf command disarm its own Kitty flags before exit (a command left armed at exit is grounded by the host), and the Ctrl+C spec now waits for a ready prompt before interrupting instead of killing a shell mid-startup. Both reflect the interrupt no longer resetting flags.

Approval is withheld only because the earlier [!IMPORTANT] thread on the removed interrupt Kitty wipe (WSL recovery) is still open and unaddressed by this commit — it is untouched here, so I have not re-raised it.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@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-copy-shortcut.test.ts (1)

65-65: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Use one tracker for the held copy sequence.

dispatchCopy creates and consumes a tracker within each call. The repeat assertion therefore does not share state with the initial press. Dispatch the initial press and repeat through one tracker, then consume the companion release. Assert one copy, no repeat copy, and a claimed release. The E2E sequence sends the held keys but does not assert release ownership.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: b62fcf51-a1e9-4018-8474-0592d39028aa

📥 Commits

Reviewing files that changed from the base of the PR and between 80f688b and 4cf866e.

📒 Files selected for processing (3)
  • src/renderer/src/components/terminal-pane/terminal-copy-shortcut.test.ts
  • src/renderer/src/components/terminal-pane/xterm-bypass-policy.ts
  • tests/e2e/terminal-shortcuts.spec.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@Jinwoo-H
Jinwoo-H marked this pull request as draft September 27, 2026 21:31
@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Parking this until the underlying keyboard-mode work lands.

Removing the Ctrl+C Kitty reset loses recovery on terminals whose host does not yet clean up after a dead program: SSH, terminals still on a pre-update daemon, older paired runtimes, shells without lifecycle hooks, and nested shells. The reconnect reset also wipes an agent's Kitty flags, so unselected Cmd+C would still stop working after a window reload.

Planned order:

  1. Fix a recovery gap in the host cleanup from fix(terminal): ground a program that dies with input modes armed on the normal screen #22739, where a refuted foreground proof drops the command's armed modes.
  2. Reset the renderer's Kitty tracker together with xterm in the fix(terminal): disarm stale TUI modes when a pane confirms return to shell #9608 confirmed-shell reset.
  3. Add host cleanup to the SSH relay.
  4. Add a per-terminal host capability, so the renderer stops its own resets only where the host cleans up.
  5. Revisit this Cmd+C change on top of that.

The e2e stability fixes from this branch will go in a separate PR.

@Jinwoo-H

Copy link
Copy Markdown
Contributor Author

Superseded by #23597, which re-lands this Cmd+C rule on top of #23584 (the Ctrl+C keyboard-mode wipe it depended on removing). Both are merged.

@Jinwoo-H Jinwoo-H closed this Sep 28, 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.

1 participant