From 1df8aa56051cbe1ca08c3c0133abdd3b503cbd8e Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 28 Jul 2026 21:57:41 -0700 Subject: [PATCH] fix(dashboard): give the agent preview terminal a real pane's keyboard (#11015) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(dashboard): give the agent preview terminal a real pane's keyboard The dashboard's preview terminal is a bare xterm, not a pane, so it never ran `resolveTerminalShortcutAction` — its only custom key handler covered copy/paste and IME. Ctrl+Backspace therefore fell through to xterm's default `\x08`, which readline binds to backward-delete-char: one character instead of a word. Route the preview's keys through the pane's own shortcut policy, so word and line kills, Option chords, modified Enter, and scrollback chords encode identically. Pane-scoped verdicts (splits, search, focus) are swallowed rather than passed to xterm, which would send e.g. Ctrl+Shift+D as a bare Ctrl+D. The policy needs three things the preview could not see: - kitty-protocol flags — mirrored locally from the same PTY output stream - the PTY's execution host — bytes follow the host, not the client OS, so a new `DashboardCard.terminalInput` profile is derived in the main renderer (the only one holding the store) and relayed to the pop-out - host terminal options — the ConPTY backend and the kitty withhold now apply Also brings the emulator itself up to a pane's: Orca's Unicode 11 width shim (replayed CJK/emoji/ZWJ laid out wrong without it), Windows Ctrl+Alt chord repair, user font/cursor/line-height/word-separator/sensitivity settings, ligatures, the TUI wheel multiplier, lazy Arabic shaping, clickable links, and the IME candidate anchor — extracted from pane-lifecycle so both surfaces share one implementation. The in-window drawer built its snapshot from a slice subset, which would have degraded the new profile to client-OS defaults there; it now reads the full store non-reactively. * fix(dashboard): enumerate pane-scoped chords instead of a default case The switch-exhaustiveness gate rejects a `default` over the shortcut-action union — it would let a newly added action be swallowed silently instead of forcing a decision at the preview's boundary. * fix(dashboard): preserve native shortcuts and PTY host routing * chore: keep merge scope limited to dashboard * perf(dashboard): avoid full-store copies for terminal profiles * fix(dashboard): validate terminal input profiles at IPC boundary * fix(dashboard): sync preview terminal refs on commit, not during render react-compiler rejects ref writes in the render pass; every reader is an event handler or a post-await continuation, so a commit-phase sync is equivalent. * test(dashboard): cover the three seams that relay the host-input profile Reverting any of them left every suite green: the dialog's terminalInput prop (the only reader of DashboardCard.terminalInput), the drawer's hand-threaded store slices, and the pop-out's republish triggers. Each new assertion was mutation-checked against its source line. * fix(dashboard): follow the WSL host for a preview terminal's byte routing The card resolver handed resolveTerminalInputHostPlatform a transport with no getLocalSessionMetadata, so a WSL pty on a Windows client resolved to win32 while its own pane resolves linux — Shift+Enter would then encode CSI-u where the pane sends alt-enter. Mirror the pane transport's own gate. * fix(dashboard): republish on every slice the host-input profile resolves from The compare set covered 4 of the ~11 slices that decide a card's execution host, so a change to the rest (folder workspaces, project groups, the runtime catalog, detected worktrees) never triggered a publish. On a quiet board there is no later publish to heal from, and the pop-out — which cannot re-derive the profile — keeps encoding bytes for the host the pty used to run on. * fix(dashboard): sync preview terminal refs on layout, not on a passive effect xterm's keydown is a native listener, so React never flushes a passive effect before it. A just-relayed host profile could therefore miss the next keystroke. * test(dashboard): pin the preview's replay-vs-live kitty scan The existing A/B passed either way: a lone CSI > u sets the same flags through scan and scanReplay. Redeliver the push across a snapshot and its replay so stack semantics would leave the TUI's single pop on a stale frame. * fix(dashboard): rebuild the drawer's snapshot on every host-input slice The in-window drawer read ~12 host slices through getState() while subscribing to none of them, on the premise that agent activity drives the next rebuild. A quiet board has no such rebuild: an SSH handshake completing with every agent idle leaves the preview terminal encoding bytes for the pre-connect host, and agentStatusEpoch only ticks on live status changes so it never heals. Watch the same set useDashboardPopoutBridge republishes on — each writer bails out when nothing changed, so the added deps are far quieter than agentStatusByPaneKey, which already rebuilds this memo on every status ping. The existing coverage mounted a second hook, which always recomputes; the new test re-renders the same hook after changing only sshConnectionStates. * fix(dashboard): key the preview by the user's terminal shortcut policy The preview passed 11 of the 12 inputs the pane's policy takes and let the 12th default to orca-first. Under terminal-first a remapped tab.close chord is meant to yield to the shell — Ctrl+W is a word-kill there — but the preview kept claiming it as a pane close and swallowed the bytes. * test(dashboard): pin the host-input profile to card snapshots only The count path main added in #11042 renders no cards, so it must not pay a per-pty host resolution on every agent-status tick. Both assertions run against a card that does have a live pty, so only the gate keeps the profile off. * refactor(dashboard): extract the board's client-host read The merge of main's label bounding pushed build-dashboard-snapshot.ts to 302 lines. The client's own platform facts are a distinct concept from the pty host each card keys against, so they move out rather than earn a max-lines bypass. --- .../ipc/dashboard-payload-validation.test.ts | 51 ++++ src/main/ipc/dashboard-payload-validation.ts | 36 ++- .../AgentTerminalDialog.test.tsx | 88 +++++++ .../dashboard-popout/AgentTerminalDialog.tsx | 2 +- .../AgentTerminalPreview.test.tsx | 189 +++++++++++++- .../dashboard-popout/AgentTerminalPreview.tsx | 245 ++++++++++-------- .../preview-clipboard-shortcuts.ts | 70 ----- .../preview-terminal-compatibility.ts | 51 ++++ .../preview-terminal-ime-bridge.ts | 40 +++ .../preview-terminal-key-handler.ts | 182 +++++++++++++ .../preview-terminal-ligatures.ts | 43 +++ .../preview-terminal-links.ts | 26 ++ .../preview-terminal-options.test.ts | 92 +++++++ .../preview-terminal-options.ts | 83 ++++++ .../preview-terminal-paste.ts | 63 +++++ .../preview-terminal-shortcuts.test.ts | 148 +++++++++++ .../preview-terminal-shortcuts.ts | 58 +++++ .../build-dashboard-snapshot.test.ts | 14 + .../dashboard/build-dashboard-snapshot.ts | 29 ++- .../dashboard-card-terminal-input.test.ts | 144 ++++++++++ .../dashboard-card-terminal-input.ts | 132 ++++++++++ .../dashboard/dashboard-client-host.ts | 32 +++ .../useDashboardPopoutBridge.test.tsx | 41 ++- .../dashboard/useDashboardPopoutBridge.ts | 22 +- .../useLiveDashboardSnapshot.test.ts | 38 +++ .../dashboard/useLiveDashboardSnapshot.ts | 51 +++- .../src/lib/pane-manager/pane-lifecycle.ts | 59 +---- .../terminal-ime-candidate-anchor.ts | 67 +++++ .../pane-manager/windows-pty-compatibility.ts | 13 +- src/shared/dashboard-snapshot.ts | 23 ++ 30 files changed, 1883 insertions(+), 249 deletions(-) create mode 100644 src/renderer/src/components/dashboard-popout/AgentTerminalDialog.test.tsx delete mode 100644 src/renderer/src/components/dashboard-popout/preview-clipboard-shortcuts.ts create mode 100644 src/renderer/src/components/dashboard-popout/preview-terminal-compatibility.ts create mode 100644 src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge.ts create mode 100644 src/renderer/src/components/dashboard-popout/preview-terminal-key-handler.ts create mode 100644 src/renderer/src/components/dashboard-popout/preview-terminal-ligatures.ts create mode 100644 src/renderer/src/components/dashboard-popout/preview-terminal-links.ts create mode 100644 src/renderer/src/components/dashboard-popout/preview-terminal-options.test.ts create mode 100644 src/renderer/src/components/dashboard-popout/preview-terminal-options.ts create mode 100644 src/renderer/src/components/dashboard-popout/preview-terminal-paste.ts create mode 100644 src/renderer/src/components/dashboard-popout/preview-terminal-shortcuts.test.ts create mode 100644 src/renderer/src/components/dashboard-popout/preview-terminal-shortcuts.ts create mode 100644 src/renderer/src/components/dashboard/dashboard-card-terminal-input.test.ts create mode 100644 src/renderer/src/components/dashboard/dashboard-card-terminal-input.ts create mode 100644 src/renderer/src/components/dashboard/dashboard-client-host.ts create mode 100644 src/renderer/src/lib/pane-manager/terminal-ime-candidate-anchor.ts diff --git a/src/main/ipc/dashboard-payload-validation.test.ts b/src/main/ipc/dashboard-payload-validation.test.ts index 7baed3adb..954723a61 100644 --- a/src/main/ipc/dashboard-payload-validation.test.ts +++ b/src/main/ipc/dashboard-payload-validation.test.ts @@ -177,6 +177,57 @@ describe('dashboard payload validation', () => { ).toBe(false) }) + it('validates the preview terminal input profile', () => { + const terminalInput = { + hostPlatform: 'win32', + localWindowsConpty: true, + osRelease: '10.0.22631', + windowsShiftEnterEncoding: 'alt-enter', + kittyKeyboardAdvertised: false + } + expect( + isDashboardSnapshot({ + ...SNAPSHOT, + cards: [{ ...SNAPSHOT.cards[0], terminalInput }] + }) + ).toBe(true) + for (const invalid of [ + { ...terminalInput, hostPlatform: 'windows' }, + { ...terminalInput, localWindowsConpty: 'true' }, + { ...terminalInput, osRelease: 'x'.repeat(1_025) }, + { ...terminalInput, windowsShiftEnterEncoding: 'enter' }, + { ...terminalInput, kittyKeyboardAdvertised: 1 } + ]) { + expect( + isDashboardSnapshot({ + ...SNAPSHOT, + cards: [{ ...SNAPSHOT.cards[0], terminalInput: invalid }] + }) + ).toBe(false) + } + }) + + // Why: terminalInput is per-card, so a host profile this validator does not + // know must cost that preview its card, never the whole board. + it('drops only the card whose terminal input profile is unusable', () => { + const good = SNAPSHOT.cards[0] + const bad = { + ...good, + paneKey: 'tab-2:leaf-2', + terminalInput: { + hostPlatform: 'plan9', + localWindowsConpty: false, + windowsShiftEnterEncoding: 'csi-u', + kittyKeyboardAdvertised: true + } + } + + const admitted = admitDashboardSnapshot({ ...SNAPSHOT, cards: [good, bad] }) + + expect(admitted?.droppedCardCount).toBe(1) + expect(admitted?.snapshot.cards.map((card) => card.paneKey)).toEqual(['tab-1:leaf-1']) + }) + // Why: the pop-out replays the last accepted snapshot, so rejecting the whole // board over one card froze every other agent's status until it was renamed. describe('admitDashboardSnapshot', () => { diff --git a/src/main/ipc/dashboard-payload-validation.ts b/src/main/ipc/dashboard-payload-validation.ts index 00c62b105..0dfb80648 100644 --- a/src/main/ipc/dashboard-payload-validation.ts +++ b/src/main/ipc/dashboard-payload-validation.ts @@ -29,6 +29,20 @@ const MAX_LABEL_LENGTH = DASHBOARD_MAX_LABEL_LENGTH const DASHBOARD_BUCKETS = new Set(['attention', 'working', 'done', 'idle']) const DASHBOARD_DOT_STATES = new Set(['working', 'blocked', 'waiting', 'done', 'idle']) const DASHBOARD_REVIEW_STATES = new Set(['open', 'closed', 'merged', 'draft']) +const DASHBOARD_HOST_PLATFORMS = new Set([ + 'aix', + 'android', + 'cygwin', + 'darwin', + 'freebsd', + 'haiku', + 'linux', + 'netbsd', + 'openbsd', + 'sunos', + 'win32' +]) +const WINDOWS_SHIFT_ENTER_ENCODINGS = new Set(['alt-enter', 'csi-u']) function isBoundedString(value: unknown, maxLength: number, allowEmpty = false): value is string { return typeof value === 'string' && value.length <= maxLength && (allowEmpty || value.length > 0) @@ -263,6 +277,26 @@ function isDashboardCard(value: unknown): boolean { isFiniteNumber(card.stateChangedAt) && typeof card.unseen === 'boolean' && isOptionalBoundedString(card.askSummary, AGENT_STATUS_INTERACTIVE_PROMPT_MAX_LENGTH) && - isOptionalBoundedString(card.conversationName, MAX_LABEL_LENGTH) + isOptionalBoundedString(card.conversationName, MAX_LABEL_LENGTH) && + isDashboardTerminalInput(card.terminalInput) + ) +} + +function isDashboardTerminalInput(value: unknown): boolean { + if (value === undefined) { + return true + } + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return false + } + const input = value as Record + return ( + typeof input.hostPlatform === 'string' && + DASHBOARD_HOST_PLATFORMS.has(input.hostPlatform) && + typeof input.localWindowsConpty === 'boolean' && + isOptionalBoundedString(input.osRelease, MAX_LABEL_LENGTH) && + typeof input.windowsShiftEnterEncoding === 'string' && + WINDOWS_SHIFT_ENTER_ENCODINGS.has(input.windowsShiftEnterEncoding) && + typeof input.kittyKeyboardAdvertised === 'boolean' ) } diff --git a/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.test.tsx b/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.test.tsx new file mode 100644 index 000000000..6610efe26 --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.test.tsx @@ -0,0 +1,88 @@ +// @vitest-environment happy-dom + +import '@testing-library/jest-dom/vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cleanup, render, screen } from '@testing-library/react' +import type { + DashboardCard, + DashboardCardTerminalInput +} from '../../../../shared/dashboard-snapshot' +import { AgentTerminalDialog } from './AgentTerminalDialog' + +// Stub the preview so the assertion is on the props the dialog hands it, with +// no xterm / IPC machinery in the way. +vi.mock('./AgentTerminalPreview', () => ({ + AgentTerminalPreview: ({ + ptyId, + terminalInput + }: { + ptyId: string + terminalInput?: DashboardCardTerminalInput | null + }) => ( +
+ ) +})) + +const TERMINAL_INPUT: DashboardCardTerminalInput = { + hostPlatform: 'win32', + localWindowsConpty: true, + osRelease: '10.0.22631', + windowsShiftEnterEncoding: 'csi-u', + kittyKeyboardAdvertised: false +} + +function card(overrides: Partial = {}): DashboardCard { + return { + paneKey: 'tab1:leaf1', + ptyId: 'pty-1', + agentType: 'claude', + bucket: 'working', + dotState: 'working', + task: 'task', + repoId: 'r1', + worktreeId: 'w1', + tabId: 'tab1', + leafId: 'leaf1', + repoName: 'Repo', + worktreeName: 'wt', + startedAt: 0, + finishedAt: null, + stateChangedAt: 0, + unseen: false, + ...overrides + } +} + +afterEach(() => { + cleanup() +}) + +// Why: this is the only seam carrying the relayed host profile into the +// emulator. Dropping the prop degrades every preview to client-OS byte routing +// silently — nothing else in the app reads DashboardCard.terminalInput. +describe('AgentTerminalDialog', () => { + it("hands the card's relayed host-input profile to the preview terminal", () => { + render( + {}} + onReveal={() => {}} + /> + ) + + expect(screen.getByTestId('preview')).toHaveAttribute( + 'data-terminal-input', + JSON.stringify(TERMINAL_INPUT) + ) + }) + + it('passes null when the card carries no profile, so the preview routes by client OS', () => { + render( {}} onReveal={() => {}} />) + + expect(screen.getByTestId('preview')).toHaveAttribute('data-terminal-input', 'null') + }) +}) diff --git a/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.tsx b/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.tsx index 23a5e5b1d..ead430908 100644 --- a/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.tsx +++ b/src/renderer/src/components/dashboard-popout/AgentTerminalDialog.tsx @@ -96,7 +96,7 @@ export function AgentTerminalDialog({
{card.ptyId ? ( - + ) : (
{translate( diff --git a/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx b/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx index 575e906df..01ac36f41 100644 --- a/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx +++ b/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.test.tsx @@ -22,6 +22,8 @@ const terminalHarness = vi.hoisted(() => ({ reset: ReturnType paste: ReturnType input: ReturnType + scrollToTop: ReturnType + scrollToBottom: ReturnType modes: { bracketedPasteMode: boolean } selectionText: string customKeyHandler: ((event: KeyboardEvent) => boolean) | null @@ -31,6 +33,10 @@ const terminalHarness = vi.hoisted(() => ({ })) const platformState = vi.hoisted(() => ({ value: 'linux' })) +const storeState = vi.hoisted(() => ({ + settings: null, + keybindings: {} as Record +})) const imeHarness = vi.hoisted(() => ({ forwarders: [] as { @@ -72,6 +78,11 @@ vi.mock('@xterm/xterm', () => ({ this.onDataListener?.(data) }) element = document.createElement('div') + unicode = { activeVersion: '6', versions: ['6', '11'], register: vi.fn() } + loadAddon = vi.fn() + attachCustomWheelEventHandler = vi.fn() + scrollToTop = vi.fn() + scrollToBottom = vi.fn() getSelection = vi.fn(() => this.selectionText) attachCustomKeyEventHandler = vi.fn((handler: (event: KeyboardEvent) => boolean) => { this.customKeyHandler = handler @@ -86,7 +97,8 @@ vi.mock('@xterm/xterm', () => ({ } } })) -vi.mock('@/lib/pane-manager/pane-terminal-options', () => ({ +vi.mock(import('@/lib/pane-manager/pane-terminal-options'), async (importOriginal) => ({ + ...(await importOriginal()), buildDefaultTerminalOptions: () => ({}) })) vi.mock('@/components/terminal-pane/terminal-user-input-signal', () => ({ @@ -126,9 +138,8 @@ vi.mock('@/components/terminal-pane/terminal-ime-input-source', () => ({ } })) vi.mock('@/store', () => { - const state = { settings: null, keybindings: {} } - const useAppStore = (selector: (s: typeof state) => unknown): unknown => selector(state) - useAppStore.getState = (): typeof state => state + const useAppStore = (selector: (s: typeof storeState) => unknown): unknown => selector(storeState) + useAppStore.getState = (): typeof storeState => storeState return { useAppStore } }) @@ -149,6 +160,7 @@ describe('AgentTerminalPreview', () => { terminalHarness.instances.length = 0 terminalHarness.userInputListener = null platformState.value = 'linux' + storeState.keybindings = {} imeHarness.forwarders.length = 0 imeHarness.trackers.length = 0 imeHarness.claimResult = false @@ -346,6 +358,175 @@ describe('AgentTerminalPreview', () => { expect(terminalHarness.instances[0]!.paste).not.toHaveBeenCalled() }) + it('sends the word-kill byte on Ctrl+Backspace and blocks xterm handling', async () => { + render() + await waitFor(() => expect(terminalHarness.instances).toHaveLength(1)) + const terminal = terminalHarness.instances[0]! + await waitFor(() => expect(terminal.customKeyHandler).not.toBeNull()) + + const keydown = new KeyboardEvent('keydown', { + key: 'Backspace', + code: 'Backspace', + ctrlKey: true, + cancelable: true + }) + const handled = terminal.customKeyHandler!(keydown) + + expect(handled).toBe(false) + expect(keydown.defaultPrevented).toBe(true) + expect(terminal.input).toHaveBeenCalledWith('\x17') + await waitFor(() => expect(input).toHaveBeenCalledWith('pty-1', '\x17')) + }) + + it('swallows a pane-scoped chord instead of leaking its control byte to the agent', async () => { + render() + await waitFor(() => expect(terminalHarness.instances).toHaveLength(1)) + const terminal = terminalHarness.instances[0]! + await waitFor(() => expect(terminal.customKeyHandler).not.toBeNull()) + + // Ctrl+Shift+D splits a pane on Linux; xterm would otherwise send Ctrl+D. + const keydown = new KeyboardEvent('keydown', { + key: 'D', + code: 'KeyD', + ctrlKey: true, + shiftKey: true, + cancelable: true + }) + const handled = terminal.customKeyHandler!(keydown) + + expect(handled).toBe(false) + expect(keydown.defaultPrevented).toBe(true) + expect(terminal.input).not.toHaveBeenCalled() + expect(input).not.toHaveBeenCalled() + }) + + it('keeps a native input-source chord from inserting text into the preview', async () => { + storeState.keybindings = { 'terminal.switchInputSource': ['Shift+Space'] } + const view = render() + await waitFor(() => expect(terminalHarness.instances).toHaveLength(1)) + const terminal = terminalHarness.instances[0]! + await waitFor(() => expect(terminal.customKeyHandler).not.toBeNull()) + + const keydown = new KeyboardEvent('keydown', { + key: ' ', + code: 'Space', + shiftKey: true, + bubbles: true, + cancelable: true + }) + expect(terminal.customKeyHandler!(keydown)).toBe(false) + expect(keydown.defaultPrevented).toBe(false) + + const keypress = new KeyboardEvent('keypress', { + key: ' ', + bubbles: true, + cancelable: true + }) + window.dispatchEvent(keypress) + expect(keypress.defaultPrevented).toBe(true) + + const beforeInput = new InputEvent('beforeinput', { + data: ' ', + inputType: 'insertText', + bubbles: true, + cancelable: true + }) + window.dispatchEvent(beforeInput) + expect(beforeInput.defaultPrevented).toBe(true) + + window.dispatchEvent(new KeyboardEvent('keyup', { key: ' ', code: 'Space', bubbles: true })) + const unarmedBeforeInput = new InputEvent('beforeinput', { + data: ' ', + inputType: 'insertText', + bubbles: true, + cancelable: true + }) + window.dispatchEvent(unarmedBeforeInput) + expect(unarmedBeforeInput.defaultPrevented).toBe(false) + expect(terminal.input).not.toHaveBeenCalled() + expect(input).not.toHaveBeenCalled() + + view.unmount() + }) + + it('defers Option chords to xterm once the TUI negotiates kitty keyboard mode', async () => { + render() + await waitFor(() => expect(terminalHarness.instances).toHaveLength(1)) + const terminal = terminalHarness.instances[0]! + await waitFor(() => expect(terminal.customKeyHandler).not.toBeNull()) + + const altBackspace = (): KeyboardEvent => + new KeyboardEvent('keydown', { key: 'Backspace', code: 'Backspace', altKey: true }) + expect(terminal.customKeyHandler!(altBackspace())).toBe(false) + expect(terminal.input).toHaveBeenCalledWith('\x1b\x7f') + + // The agent's TUI pushes kitty flags (CSI > 1 u) on the live stream. + act(() => { + emitData?.({ type: 'data', ptyId: 'pty-1', data: '\x1b[>1u', bytes: 5 }) + }) + terminal.input.mockClear() + + expect(terminal.customKeyHandler!(altBackspace())).toBe(true) + expect(terminal.input).not.toHaveBeenCalled() + }) + + // Why: a snapshot carries the TUI's one-time kitty push and the post-snapshot + // replay redelivers it. Applying replays with stack semantics would leave the + // TUI's single pop on a stale frame, so a plain shell keeps getting + // kitty-encoded Option chords. + it('does not let a redelivered kitty push outlive the TUI pop', async () => { + connect.mockResolvedValueOnce({ + snapshot: { data: '\x1b[>1u', cols: 80, rows: 24, seq: 1 }, + replay: ['\x1b[>1u'] + }) + render() + await waitFor(() => expect(terminalHarness.instances).toHaveLength(1)) + const terminal = terminalHarness.instances[0]! + await waitFor(() => expect(terminal.customKeyHandler).not.toBeNull()) + + const altBackspace = (): KeyboardEvent => + new KeyboardEvent('keydown', { key: 'Backspace', code: 'Backspace', altKey: true }) + expect(terminal.customKeyHandler!(altBackspace())).toBe(true) + + // The TUI exits and pops once on the live stream. + act(() => { + emitData?.({ type: 'data', ptyId: 'pty-1', data: '\x1b[ { + platformState.value = 'darwin' + render() + await waitFor(() => expect(terminalHarness.instances).toHaveLength(1)) + const terminal = terminalHarness.instances[0]! + await waitFor(() => expect(terminal.customKeyHandler).not.toBeNull()) + + const handled = terminal.customKeyHandler!( + new KeyboardEvent('keydown', { key: 'ArrowUp', code: 'ArrowUp', metaKey: true }) + ) + + expect(handled).toBe(false) + expect(terminal.scrollToTop).toHaveBeenCalled() + expect(terminal.input).not.toHaveBeenCalled() + }) + + it('leaves an unmodified Backspace to xterm', async () => { + render() + await waitFor(() => expect(terminalHarness.instances).toHaveLength(1)) + const terminal = terminalHarness.instances[0]! + await waitFor(() => expect(terminal.customKeyHandler).not.toBeNull()) + + const handled = terminal.customKeyHandler!( + new KeyboardEvent('keydown', { key: 'Backspace', code: 'Backspace', cancelable: true }) + ) + + expect(handled).toBe(true) + expect(terminal.input).not.toHaveBeenCalled() + }) + it('leaves plain Ctrl+V to the Edit-menu accelerator but handles the shifted paste chord', async () => { const view = render() await waitFor(() => expect(terminalHarness.instances).toHaveLength(1)) diff --git a/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx b/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx index 4d01ce480..8da354166 100644 --- a/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx +++ b/src/renderer/src/components/dashboard-popout/AgentTerminalPreview.tsx @@ -1,36 +1,33 @@ -import { useEffect, useMemo, useRef, useState } from 'react' +import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react' import { Terminal } from '@xterm/xterm' import '@xterm/xterm/css/xterm.css' -import { buildDefaultTerminalOptions } from '@/lib/pane-manager/pane-terminal-options' import { getShortcutPlatform } from '@/lib/shortcut-platform' import { subscribeToTerminalUserInput } from '@/components/terminal-pane/terminal-user-input-signal' -import { - executeTerminalPastePlan, - planTerminalPasteWithYield -} from '@/components/terminal-pane/terminal-paste-coordinator' -import { resolveTerminalPasteRuntime } from '@/components/terminal-pane/terminal-paste-runtime' -import { TERMINAL_PASTE_MAX_BYTES } from '@/components/terminal-pane/terminal-paste-limits' -import { - installTerminalImeCompositionTracker, - type TerminalImeCompositionTracker -} from '@/components/terminal-pane/terminal-ime-composition-tracker' -import { - installTerminalImeNativeTextForwarder, - type TerminalImeNativeTextForwarder -} from '@/components/terminal-pane/terminal-ime-native-text-forwarder' -import { getMacNativeTextInputSourceTracker } from '@/components/terminal-pane/terminal-ime-input-source' import { composeActiveTerminalTheme } from '@/components/terminal-pane/terminal-appearance' -import { resolveTerminalMinimumContrastRatio } from '@/lib/terminal-contrast-correction' import { useSystemPrefersDark } from '@/components/terminal-pane/use-system-prefers-dark' +import { TerminalKittyKeyboardModeTracker } from '../../../../shared/terminal-kitty-keyboard-mode-tracker' +import { useEffectiveMacOptionAsAlt } from '@/lib/keyboard-layout/use-effective-mac-option-as-alt' +import { + buildPreviewAppearanceOptions, + buildPreviewTerminalOptions +} from './preview-terminal-options' +import { syncPreviewTerminalLigatures } from './preview-terminal-ligatures' +import { installPreviewTerminalCompatibility } from './preview-terminal-compatibility' +import { createPreviewClipboardPaster } from './preview-terminal-paste' +import { installPreviewImeBridge, type PreviewImeBridge } from './preview-terminal-ime-bridge' +import type { DashboardCardTerminalInput } from '../../../../shared/dashboard-snapshot' import { translate } from '@/i18n/i18n' import { getBuiltinTheme, resolveEffectiveTerminalAppearance } from '@/lib/terminal-theme' import { cn } from '@/lib/utils' import { useAppStore } from '@/store' -import { installPreviewClipboardShortcuts } from './preview-clipboard-shortcuts' +import { installPreviewTerminalKeyHandler } from './preview-terminal-key-handler' import { createPreviewGridClaim } from './preview-grid-claim' import type { TerminalPreviewDataPayload } from '../../../../shared/terminal-preview' const PREVIEW_SCROLLBACK_ROWS = 24 +// Why: main only ever serializes PREVIEW_SCROLLBACK_ROWS of history into this +// terminal, so the pane's user-configured scrollback would only cost memory. +const PREVIEW_SCROLLBACK_BUFFER_ROWS = 1000 const FALLBACK_COLS = 80 const FALLBACK_ROWS = 24 const RESYNC_RETRY_DELAY_MS = 150 @@ -50,10 +47,24 @@ function clamp(value: number, min: number, max: number): number { * anchored so the cursor stays visible. Keystrokes pass through to the PTY; * DOM renderer so it never grabs a WebGL context. */ -export function AgentTerminalPreview({ ptyId }: { ptyId: string }): React.JSX.Element { +export function AgentTerminalPreview({ + ptyId, + terminalInput = null +}: { + ptyId: string + /** Host-input facts relayed with the card; null routes bytes by client OS. */ + terminalInput?: DashboardCardTerminalInput | null +}): React.JSX.Element { const containerRef = useRef(null) + const terminalRef = useRef(null) const settings = useAppStore((state) => state.settings) const systemPrefersDark = useSystemPrefersDark() + const macOptionAsAlt = useEffectiveMacOptionAsAlt(settings?.terminalMacOptionAsAlt) + // Why: keys and appearance must read live values without remounting the + // terminal (a remount reconnects the pty and repaints from a new snapshot). + const settingsRef = useRef(settings) + const macOptionAsAltRef = useRef(macOptionAsAlt) + const terminalInputRef = useRef(terminalInput) const { terminalTheme, terminalMode } = useMemo(() => { if (!settings) { return { terminalTheme: null, terminalMode: 'dark' as const } @@ -69,6 +80,16 @@ export function AgentTerminalPreview({ ptyId }: { ptyId: string }): React.JSX.El // spawned this session) — say so instead of painting a silent blank terminal. const [ptyGone, setPtyGone] = useState(false) + // Why: refs are seeded at first render and refreshed on commit — assigning + // during render trips react-compiler. Layout, not passive: xterm's keydown is + // a native listener, so React would not flush a passive effect before the + // next keystroke and a just-relayed profile could miss it. + useLayoutEffect(() => { + settingsRef.current = settings + macOptionAsAltRef.current = macOptionAsAlt + terminalInputRef.current = terminalInput + }, [settings, macOptionAsAlt, terminalInput]) + useEffect(() => { setPtyGone(false) const container = containerRef.current @@ -79,8 +100,12 @@ export function AgentTerminalPreview({ ptyId }: { ptyId: string }): React.JSX.El let terminal: Terminal | null = null let offData: (() => void) | null = null let userInputDisposable: { dispose: () => void } | null = null - let imeCompositionTracker: TerminalImeCompositionTracker | null = null - let imeNativeTextForwarder: TerminalImeNativeTextForwarder | null = null + let imeBridge: PreviewImeBridge | null = null + let disposeKeyHandler: (() => void) | null = null + let disposeTerminalCompatibility: (() => void) | null = null + // Why: mirrors the pane's tracker — the policy needs the flags the TUI + // negotiated, and this preview parses the same output stream the pane does. + const kittyKeyboardModes = new TerminalKittyKeyboardModeTracker() let refreshInFlight = false let refreshAgain = false let retryTimer: ReturnType | null = null @@ -136,7 +161,14 @@ export function AgentTerminalPreview({ ptyId }: { ptyId: string }): React.JSX.El boxResizeObserver?.observe(container) let replayDepth = 0 - const writeReplayed = (chunk: string, onDone?: () => void): void => { + const writeReplayed = (chunk: string, onDone?: () => void, live = false): void => { + // Why: a redelivered snapshot repeats the TUI's one-time kitty push, so + // replayed bytes must apply as idempotent sets (see the tracker's docs). + if (live) { + kittyKeyboardModes.scan(chunk) + } else { + kittyKeyboardModes.scanReplay(chunk) + } replayDepth++ terminal?.write(chunk, () => { replayDepth-- @@ -150,93 +182,63 @@ export function AgentTerminalPreview({ ptyId }: { ptyId: string }): React.JSX.El pendingLivePayloads.push(payload) return } - writeReplayed(payload.data, () => { - if (!disposed) { - void window.api.terminalPreview.ack(ptyId, payload.bytes) - } - }) + writeReplayed( + payload.data, + () => { + if (!disposed) { + void window.api.terminalPreview.ack(ptyId, payload.bytes) + } + }, + true + ) } - const pasteClipboardText = async ( - activeElementAtDispatch: Element | null, - source: 'keyboard' | 'app-menu' - ): Promise => { - let text: string - try { - text = await window.api.ui.readClipboardText({ maxBytes: TERMINAL_PASTE_MAX_BYTES }) - } catch { - return - } - const pasteTerminal = terminal - if (!pasteTerminal || !text) { - return - } - const targetIsCurrent = (): boolean => - !disposed && - terminal === pasteTerminal && - activeElementAtDispatch !== null && - document.activeElement === activeElementAtDispatch && - container.contains(activeElementAtDispatch) - if (!targetIsCurrent()) { - return - } - const platform = getShortcutPlatform() - const plan = await planTerminalPasteWithYield({ - text, - source, - target: { - kind: 'terminal', - paneId: 0, - leafId: ptyId, - ptyId, - runtime: resolveTerminalPasteRuntime({ platform, ptyId }) - }, - terminalBracketedPasteMode: pasteTerminal.modes.bracketedPasteMode - }) - await executeTerminalPastePlan(plan, { - // Why: stream large pastes so the renderer never emits one huge IPC payload. - pasteText: (pasteText) => pasteTerminal.paste(pasteText), - writePty: (data) => window.api.terminalPreview.input(ptyId, data), - isTargetCurrent: targetIsCurrent, - // Why: if focus changes mid-bracketed paste, the closing marker must still reach the live PTY. - canContinue: () => true - }) - } + const pasteClipboardText = createPreviewClipboardPaster({ + ptyId, + container, + getTerminal: () => terminal, + isDisposed: () => disposed + }) const disposeImeNativeTextBridge = (): void => { - imeNativeTextForwarder?.dispose() - imeNativeTextForwarder = null - imeCompositionTracker?.dispose() - imeCompositionTracker = null + imeBridge?.dispose() + imeBridge = null } - // Why: xterm's kitty encoder can encode+cancel a printable keydown before - // Chromium commits IME/native text, silently dropping the glyph (mirrors - // TerminalPane's forwarder; macOS-only like the pane's install). const installImeNativeTextBridge = (): void => { - if (!terminal || getShortcutPlatform() !== 'darwin') { - return + if (terminal) { + imeBridge = installPreviewImeBridge(terminal) } - // Why: prewarm the async input-source lookup before the first native-text key needs classification. - const inputSourceTracker = getMacNativeTextInputSourceTracker() - imeCompositionTracker = installTerminalImeCompositionTracker(terminal.element) - imeNativeTextForwarder = installTerminalImeNativeTextForwarder({ - terminalElement: terminal.element, - isComposing: () => imeCompositionTracker?.isActive() ?? false, - sendInput: (data) => terminal?.input(data), - getInputSourceFeatures: () => inputSourceTracker.getFeatures() - }) } - const installClipboardShortcuts = (): void => { + const installKeyHandler = (): void => { if (!terminal) { return } - installPreviewClipboardShortcuts({ + disposeKeyHandler = installPreviewTerminalKeyHandler({ terminal, - claimImeKeyEvent: (event) => imeNativeTextForwarder?.claimKeyEvent(event) ?? false, + claimImeKeyEvent: (event) => imeBridge?.claimKeyEvent(event) ?? false, pasteClipboardText: (activeElement, source) => - void pasteClipboardText(activeElement, source) + void pasteClipboardText(activeElement, source), + // Why: route through terminal.input so the chord's bytes carry core's user-input signal, like typed keys. + sendInput: (data) => terminal?.input(data), + getShortcutContext: () => ({ + clientPlatform: getShortcutPlatform(), + macOptionAsAlt: macOptionAsAltRef.current, + keybindings: useAppStore.getState().keybindings, + terminalInput: terminalInputRef.current, + kittyKeyboardActive: () => kittyKeyboardModes.flags > 0, + terminalShortcutPolicy: settingsRef.current?.terminalShortcutPolicy + }) + }) + } + + const installTerminalCompatibility = (): void => { + if (!terminal) { + return + } + disposeTerminalCompatibility = installPreviewTerminalCompatibility(terminal, { + getSettings: () => settingsRef.current }) } @@ -268,17 +270,18 @@ export function AgentTerminalPreview({ ptyId }: { ptyId: string }): React.JSX.El ): void => { const snap = connection.snapshot! if (!terminal) { - terminal = new Terminal({ - ...buildDefaultTerminalOptions(), - cols: clamp(snap.cols ?? FALLBACK_COLS, 2, 500), - rows: clamp(snap.rows ?? FALLBACK_ROWS, 2, 200), - theme: terminalTheme ?? undefined, - minimumContrastRatio: resolveTerminalMinimumContrastRatio( - terminalTheme?.background, - terminalMode - ), - scrollback: 1000 - }) + terminal = new Terminal( + buildPreviewTerminalOptions({ + settings: settingsRef.current, + terminalInput: terminalInputRef.current, + macOptionIsMeta: macOptionAsAltRef.current === 'true', + theme: terminalTheme, + themeMode: terminalMode, + cols: clamp(snap.cols ?? FALLBACK_COLS, 2, 500), + rows: clamp(snap.rows ?? FALLBACK_ROWS, 2, 200), + scrollback: PREVIEW_SCROLLBACK_BUFFER_ROWS + }) + ) try { terminal.open(container) } catch { @@ -286,9 +289,11 @@ export function AgentTerminalPreview({ ptyId }: { ptyId: string }): React.JSX.El terminal = null return } + terminalRef.current = terminal + installTerminalCompatibility() installInputRouting() installImeNativeTextBridge() - installClipboardShortcuts() + installKeyHandler() } else if (replaceExisting) { // Why: keep the old frame visible during capture, then atomically replace it once the authoritative snapshot arrives. terminal.resize( @@ -296,6 +301,9 @@ export function AgentTerminalPreview({ ptyId }: { ptyId: string }): React.JSX.El clamp(snap.rows ?? FALLBACK_ROWS, 2, 200) ) terminal.reset() + // Why: the reset drops xterm's kitty flags, so the mirror must restart + // from the incoming snapshot instead of the dead session's state. + kittyKeyboardModes.reset() } if (snap.scrollbackAnsi) { writeReplayed(snap.scrollbackAnsi) @@ -355,8 +363,13 @@ export function AgentTerminalPreview({ ptyId }: { ptyId: string }): React.JSX.El userInputDisposable?.dispose() userInputDisposable = null disposeImeNativeTextBridge() + disposeTerminalCompatibility?.() + disposeTerminalCompatibility = null + disposeKeyHandler?.() + disposeKeyHandler = null terminal?.dispose() terminal = null + terminalRef.current = null void window.api.terminalPreview.unsubscribe(ptyId) return } @@ -402,11 +415,29 @@ export function AgentTerminalPreview({ ptyId }: { ptyId: string }): React.JSX.El offData?.() userInputDisposable?.dispose() disposeImeNativeTextBridge() + disposeTerminalCompatibility?.() + disposeKeyHandler?.() void window.api.terminalPreview.unsubscribe(ptyId) terminal?.dispose() + terminalRef.current = null } }, [ptyId, terminalTheme, terminalMode]) + // Why: appearance settings must land on the open terminal, and the OS input + // source can flip Option-as-Alt with no settings change at all. A remount + // would reconnect the pty and repaint the agent's screen from a new snapshot. + useEffect(() => { + const terminal = terminalRef.current + if (!terminal) { + return + } + Object.assign( + terminal.options, + buildPreviewAppearanceOptions(settings, macOptionAsAlt === 'true') + ) + syncPreviewTerminalLigatures(terminal, settings) + }, [settings, macOptionAsAlt]) + return ( // Why: a size FIXED by the viewport (not shrink-to-fit) + overflow-hidden // keeps the dialog stable no matter how wide/tall the pane's serialized diff --git a/src/renderer/src/components/dashboard-popout/preview-clipboard-shortcuts.ts b/src/renderer/src/components/dashboard-popout/preview-clipboard-shortcuts.ts deleted file mode 100644 index d23873e90..000000000 --- a/src/renderer/src/components/dashboard-popout/preview-clipboard-shortcuts.ts +++ /dev/null @@ -1,70 +0,0 @@ -import type { Terminal } from '@xterm/xterm' -import { getShortcutPlatform } from '@/lib/shortcut-platform' -import { keybindingMatchesAction } from '../../../../shared/keybindings' -import { useAppStore } from '@/store' - -/** - * Installs the popout preview terminal's ONE custom key handler (xterm allows - * a single attachCustomKeyEventHandler) covering copy/paste chords and the - * IME native-text bypass. Plain Mod+V is left to the Edit-menu accelerator, - * which reaches this window as ui:appMenuPaste — matching it here too would - * paste twice. - */ -export function installPreviewClipboardShortcuts(args: { - terminal: Terminal - claimImeKeyEvent: (event: KeyboardEvent) => boolean - pasteClipboardText: (activeElement: Element | null, source: 'keyboard') => void -}): void { - const { terminal } = args - const platform = getShortcutPlatform() - const consumedClipboardKeys = new Set() - const consumeEvent = (event: KeyboardEvent): false => { - event.preventDefault() - event.stopPropagation() - return false - } - terminal.attachCustomKeyEventHandler((event) => { - if (args.claimImeKeyEvent(event)) { - // Why: bypass xterm's kitty encoder for native-text keydowns so the committed glyph survives via the input event. - return false - } - if (event.type !== 'keydown') { - const keyIdentity = event.code || event.key - if (consumedClipboardKeys.has(keyIdentity)) { - if (event.type === 'keyup') { - consumedClipboardKeys.delete(keyIdentity) - } - return consumeEvent(event) - } - return true - } - const keybindings = useAppStore.getState().keybindings - if (keybindingMatchesAction('terminal.copySelection', event, platform, keybindings)) { - const keyIdentity = event.code || event.key - const firstKeydown = !consumedClipboardKeys.has(keyIdentity) - consumedClipboardKeys.add(keyIdentity) - const selection = terminal.getSelection() - if (firstKeydown && selection) { - void window.api.ui.writeClipboardText(selection).catch(() => undefined) - } - return consumeEvent(event) - } - const isMenuPasteChord = - (platform === 'darwin' ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey) && - !event.altKey && - !event.shiftKey && - event.key.toLowerCase() === 'v' - if ( - !isMenuPasteChord && - keybindingMatchesAction('terminal.paste', event, platform, keybindings) - ) { - const keyIdentity = event.code || event.key - if (!consumedClipboardKeys.has(keyIdentity)) { - consumedClipboardKeys.add(keyIdentity) - args.pasteClipboardText(document.activeElement, 'keyboard') - } - return consumeEvent(event) - } - return true - }) -} diff --git a/src/renderer/src/components/dashboard-popout/preview-terminal-compatibility.ts b/src/renderer/src/components/dashboard-popout/preview-terminal-compatibility.ts new file mode 100644 index 000000000..0693bdff8 --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/preview-terminal-compatibility.ts @@ -0,0 +1,51 @@ +import type { Terminal } from '@xterm/xterm' +import { Unicode11Addon } from '@xterm/addon-unicode11' +import type { GlobalSettings } from '../../../../shared/types' +import { activateOrcaTerminalUnicodeProvider } from '../../../../shared/terminal-unicode-provider' +import { installWindowsCtrlAltChordRepair } from '@/lib/pane-manager/terminal-windows-ctrl-alt-chord-classification' +import { attachTerminalMouseWheelMultiplier } from '@/lib/pane-manager/pane-terminal-mouse-wheel' +import { configureLazyArabicShapingJoiner } from '@/lib/pane-manager/terminal-arabic-shaping-joiner' +import { installTerminalImeCandidateAnchor } from '@/lib/pane-manager/terminal-ime-candidate-anchor' +import { normalizeTerminalTuiMouseWheelMultiplier } from '@/lib/pane-manager/pane-terminal-tui-wheel-reports' +import { installPreviewTerminalLinks } from './preview-terminal-links' +import { syncPreviewTerminalLigatures } from './preview-terminal-ligatures' + +/** + * Brings the preview's emulator up to a pane's: Orca's Unicode 11 width shim, + * Windows Ctrl+Alt chord classification, clickable links, ligatures, the TUI + * wheel multiplier, lazy Arabic shaping, and the IME candidate anchor. + * + * Returns a disposer for everything bound to the terminal's DOM element, which + * must run before that terminal is disposed or replaced. + */ +export function installPreviewTerminalCompatibility( + terminal: Terminal, + deps: { getSettings: () => GlobalSettings | null } +): () => void { + // Why: the width shim wraps xterm's v11 provider, so the addon that registers + // it has to load first — and both must precede any replay write, or wide + // chars bake into the buffer at xterm's default v6 tables (same order as + // the pane's openTerminal). + terminal.loadAddon(new Unicode11Addon()) + activateOrcaTerminalUnicodeProvider(terminal) + installWindowsCtrlAltChordRepair(terminal) + installPreviewTerminalLinks(terminal) + syncPreviewTerminalLigatures(terminal, deps.getSettings()) + attachTerminalMouseWheelMultiplier(terminal, { + getTuiMouseWheelMultiplier: () => + normalizeTerminalTuiMouseWheelMultiplier(deps.getSettings()?.terminalTuiScrollSensitivity) + }) + // Why: joiners cost a full-grid scan per repaint, so registration stays lazy + // until RTL text arrives. Never shaping-active: the preview is DOM-rendered + // and has no WebGL glyph atlas to compensate for. + const disposeArabicShapingJoiner = configureLazyArabicShapingJoiner(terminal, () => false) + const imeAnchorHandler = installTerminalImeCandidateAnchor(terminal) + + return () => { + if (imeAnchorHandler && terminal.element) { + terminal.element.removeEventListener('compositionstart', imeAnchorHandler) + terminal.element.removeEventListener('compositionupdate', imeAnchorHandler) + } + disposeArabicShapingJoiner() + } +} diff --git a/src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge.ts b/src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge.ts new file mode 100644 index 000000000..f61a93ab0 --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/preview-terminal-ime-bridge.ts @@ -0,0 +1,40 @@ +import type { Terminal } from '@xterm/xterm' +import { getShortcutPlatform } from '@/lib/shortcut-platform' +import { installTerminalImeCompositionTracker } from '@/components/terminal-pane/terminal-ime-composition-tracker' +import { installTerminalImeNativeTextForwarder } from '@/components/terminal-pane/terminal-ime-native-text-forwarder' +import { getMacNativeTextInputSourceTracker } from '@/components/terminal-pane/terminal-ime-input-source' + +export type PreviewImeBridge = { + /** True when the forwarder owns this keydown, so xterm must not encode it. */ + claimKeyEvent: (event: KeyboardEvent) => boolean + dispose: () => void +} + +/** + * Native-text bridge for the preview terminal. + * + * Why: xterm's kitty encoder can encode+cancel a printable keydown before + * Chromium commits IME/native text, silently dropping the glyph. Mirrors + * TerminalPane's forwarder, macOS-only like the pane's install. + */ +export function installPreviewImeBridge(terminal: Terminal): PreviewImeBridge | null { + if (getShortcutPlatform() !== 'darwin') { + return null + } + // Why: prewarm the async input-source lookup before the first native-text key needs classification. + const inputSourceTracker = getMacNativeTextInputSourceTracker() + const compositionTracker = installTerminalImeCompositionTracker(terminal.element) + const forwarder = installTerminalImeNativeTextForwarder({ + terminalElement: terminal.element, + isComposing: () => compositionTracker?.isActive() ?? false, + sendInput: (data) => terminal.input(data), + getInputSourceFeatures: () => inputSourceTracker.getFeatures() + }) + return { + claimKeyEvent: (event) => forwarder?.claimKeyEvent(event) ?? false, + dispose: () => { + forwarder?.dispose() + compositionTracker?.dispose() + } + } +} diff --git a/src/renderer/src/components/dashboard-popout/preview-terminal-key-handler.ts b/src/renderer/src/components/dashboard-popout/preview-terminal-key-handler.ts new file mode 100644 index 000000000..4eb7157e4 --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/preview-terminal-key-handler.ts @@ -0,0 +1,182 @@ +import type { Terminal } from '@xterm/xterm' +import { getShortcutPlatform } from '@/lib/shortcut-platform' +import { keybindingMatchesAction } from '../../../../shared/keybindings' +import { useAppStore } from '@/store' +import { prefetchLayoutBaseCharacters } from '@/lib/keyboard-layout/layout-base-character' +import { createTerminalNativeOnlyShortcutTracker } from '@/components/terminal-pane/terminal-native-only-shortcut' +import { + resolvePreviewShortcutAction, + type PreviewShortcutContext +} from './preview-terminal-shortcuts' + +/** + * Installs the preview terminal's ONE custom key handler (xterm allows a single + * attachCustomKeyEventHandler) covering copy/paste chords, the IME native-text + * bypass, and the full pane shortcut policy. Plain Mod+V is left to the + * Edit-menu accelerator, which reaches this window as ui:appMenuPaste — matching + * it here too would paste twice. + * + * Returns a disposer for the Option-key location listeners the policy needs to + * tell left Option from right. + */ +export function installPreviewTerminalKeyHandler(args: { + terminal: Terminal + claimImeKeyEvent: (event: KeyboardEvent) => boolean + pasteClipboardText: (activeElement: Element | null, source: 'keyboard') => void + sendInput: (data: string) => void + /** Everything but optionKeyLocation, which this installer tracks itself. */ + getShortcutContext: () => Omit +}): () => void { + const { terminal } = args + const platform = getShortcutPlatform() + const consumedClipboardKeys = new Set() + const nativeOnlyShortcutTracker = createTerminalNativeOnlyShortcutTracker() + const consumeEvent = (event: KeyboardEvent): false => { + event.preventDefault() + event.stopPropagation() + return false + } + + // Why: a character key's KeyboardEvent.location reports its own position, so + // left-vs-right Option must be recorded from the modifier's own keydown. + let optionKeyLocation = 0 + const onModifierDown = (event: KeyboardEvent): void => { + if (event.key === 'Alt') { + optionKeyLocation = event.location + } + } + const onModifierUp = (event: KeyboardEvent): void => { + if (event.key === 'Alt') { + optionKeyLocation = 0 + } + } + const onWindowBlur = (): void => { + optionKeyLocation = 0 + nativeOnlyShortcutTracker.clear() + } + const onNativeOnlyShortcutCompanion = (event: KeyboardEvent): void => { + if (!nativeOnlyShortcutTracker.consumeCompanion(event)) { + return + } + if (event.type === 'keypress') { + event.preventDefault() + } + event.stopImmediatePropagation() + } + const onNativeOnlyBeforeInput = (event: Event): void => { + if ( + !(event instanceof InputEvent) || + !nativeOnlyShortcutTracker.shouldSuppressBeforeInput(event) + ) { + return + } + event.preventDefault() + event.stopImmediatePropagation() + } + if (platform === 'darwin') { + // Why: kitty Option-chord encoding resolves base keys through the async + // KeyboardLayoutMap; prefetch so the map is cached before the first chord. + prefetchLayoutBaseCharacters() + } + window.addEventListener('keydown', onModifierDown, true) + window.addEventListener('keyup', onModifierUp, true) + window.addEventListener('keypress', onNativeOnlyShortcutCompanion, true) + window.addEventListener('keyup', onNativeOnlyShortcutCompanion, true) + window.addEventListener('beforeinput', onNativeOnlyBeforeInput, true) + window.addEventListener('blur', onWindowBlur) + + terminal.attachCustomKeyEventHandler((event) => { + if (args.claimImeKeyEvent(event)) { + // Why: bypass xterm's kitty encoder for native-text keydowns so the committed glyph survives via the input event. + return false + } + if (event.type !== 'keydown') { + const keyIdentity = event.code || event.key + if (consumedClipboardKeys.has(keyIdentity)) { + if (event.type === 'keyup') { + consumedClipboardKeys.delete(keyIdentity) + } + return consumeEvent(event) + } + return true + } + nativeOnlyShortcutTracker.prepareKeyDown(event) + const keybindings = useAppStore.getState().keybindings + if (keybindingMatchesAction('terminal.copySelection', event, platform, keybindings)) { + const keyIdentity = event.code || event.key + const firstKeydown = !consumedClipboardKeys.has(keyIdentity) + consumedClipboardKeys.add(keyIdentity) + const selection = terminal.getSelection() + if (firstKeydown && selection) { + void window.api.ui.writeClipboardText(selection).catch(() => undefined) + } + return consumeEvent(event) + } + const isMenuPasteChord = + (platform === 'darwin' ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey) && + !event.altKey && + !event.shiftKey && + event.key.toLowerCase() === 'v' + if ( + !isMenuPasteChord && + keybindingMatchesAction('terminal.paste', event, platform, keybindings) + ) { + const keyIdentity = event.code || event.key + if (!consumedClipboardKeys.has(keyIdentity)) { + consumedClipboardKeys.add(keyIdentity) + args.pasteClipboardText(document.activeElement, 'keyboard') + } + return consumeEvent(event) + } + + const action = resolvePreviewShortcutAction(event, { + ...args.getShortcutContext(), + optionKeyLocation + }) + if (!action) { + return true + } + switch (action.type) { + case 'sendInput': + args.sendInput(action.data) + return consumeEvent(event) + case 'scrollViewport': + if (action.position === 'top') { + terminal.scrollToTop() + } else { + terminal.scrollToBottom() + } + return consumeEvent(event) + case 'switchInputSource': + // Why: the OS owns this chord — block xterm without preventing the default. + nativeOnlyShortcutTracker.armKeyDown(event) + event.stopImmediatePropagation() + return false + // Why: pane-scoped chords have no target in a preview dialog. Swallow them + // — a pane never sends these bytes to the shell, and xterm would encode + // e.g. Ctrl+Shift+D as a bare Ctrl+D. Listed one by one rather than under a + // `default` so a newly added action has to be classified here, not + // silently swallowed. + case 'clearActivePane': + case 'clearPaneTitle': + case 'closeActivePane': + case 'copySelection': + case 'equalizePaneSizes': + case 'focusPane': + case 'setTitle': + case 'splitActivePane': + case 'toggleExpandActivePane': + case 'toggleSearch': + return consumeEvent(event) + } + }) + + return () => { + window.removeEventListener('keydown', onModifierDown, true) + window.removeEventListener('keyup', onModifierUp, true) + window.removeEventListener('keypress', onNativeOnlyShortcutCompanion, true) + window.removeEventListener('keyup', onNativeOnlyShortcutCompanion, true) + window.removeEventListener('beforeinput', onNativeOnlyBeforeInput, true) + window.removeEventListener('blur', onWindowBlur) + } +} diff --git a/src/renderer/src/components/dashboard-popout/preview-terminal-ligatures.ts b/src/renderer/src/components/dashboard-popout/preview-terminal-ligatures.ts new file mode 100644 index 000000000..cc0cb2036 --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/preview-terminal-ligatures.ts @@ -0,0 +1,43 @@ +import type { Terminal } from '@xterm/xterm' +import type { GlobalSettings } from '../../../../shared/types' +import { resolveTerminalLigaturesEnabled } from '../../../../shared/terminal-ligatures' +import { TerminalLigaturesAddon } from '@/lib/pane-manager/terminal-ligatures-addon' + +const ligatureAddonsByTerminal = new WeakMap() + +/** + * Match the pane's ligature state on the preview terminal, attaching and + * detaching as the setting (or a font that can't ligate) changes. The pane's + * WebGL atlas rebuild has no counterpart here — the preview is DOM-rendered. + */ +export function syncPreviewTerminalLigatures( + terminal: Terminal, + settings: GlobalSettings | null +): void { + const enabled = resolveTerminalLigaturesEnabled( + settings?.terminalLigatures, + settings?.terminalFontFamily + ) + const attached = ligatureAddonsByTerminal.get(terminal) + if (enabled === Boolean(attached)) { + return + } + if (!enabled) { + try { + attached?.dispose() + } catch { + /* ignore */ + } + ligatureAddonsByTerminal.delete(terminal) + return + } + try { + const addon = new TerminalLigaturesAddon() + terminal.loadAddon(addon) + ligatureAddonsByTerminal.set(terminal, addon) + // Why: ligatures can turn on after rows rendered; force a glyph-run recompute. + terminal.refresh(0, terminal.rows - 1) + } catch { + /* ignore: ligatures are cosmetic, never fail the preview over them */ + } +} diff --git a/src/renderer/src/components/dashboard-popout/preview-terminal-links.ts b/src/renderer/src/components/dashboard-popout/preview-terminal-links.ts new file mode 100644 index 000000000..bbc521a52 --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/preview-terminal-links.ts @@ -0,0 +1,26 @@ +import type { Terminal } from '@xterm/xterm' +import { WebLinksAddon } from '@xterm/addon-web-links' +import { installGuardedLinkProviderRegistration } from '@/lib/pane-manager/terminal-link-provider-guard' +import { isTerminalHttpLinkActivation } from '@/components/terminal-pane/terminal-http-link-activation' + +/** + * Makes URLs in the preview clickable under the same Mod+click gesture a pane + * uses. Links always open in the system browser: Orca's in-app browser routing + * is workspace-scoped, and the pop-out window hosts no browser pane. + */ +export function installPreviewTerminalLinks(terminal: Terminal): void { + // Why: a link provider throwing inside provideLinks (xterm's LinkComputer + // raises RangeError on pathological wrapped lines) escapes to window.onerror + // and kills the renderer — guard before any provider registers. + installGuardedLinkProviderRegistration(terminal) + terminal.loadAddon( + new WebLinksAddon((event, uri) => { + if (!isTerminalHttpLinkActivation(event)) { + return + } + event.preventDefault() + void window.api.shell.openUrl(uri).catch(() => undefined) + terminal.clearSelection() + }) + ) +} diff --git a/src/renderer/src/components/dashboard-popout/preview-terminal-options.test.ts b/src/renderer/src/components/dashboard-popout/preview-terminal-options.test.ts new file mode 100644 index 000000000..790334ace --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/preview-terminal-options.test.ts @@ -0,0 +1,92 @@ +// @vitest-environment happy-dom + +import { describe, expect, it } from 'vitest' +import type { GlobalSettings } from '../../../../shared/types' +import { + buildPreviewAppearanceOptions, + buildPreviewTerminalOptions +} from './preview-terminal-options' + +const SETTINGS = { + terminalFontSize: 17, + terminalFontFamily: 'Fira Code', + terminalCursorStyle: 'bar', + terminalCursorBlink: false, + terminalLineHeight: 1.4, + terminalWordSeparator: ' ()[]', + terminalScrollSensitivity: 3 +} as unknown as GlobalSettings + +describe('buildPreviewAppearanceOptions', () => { + it('carries the user terminal appearance a pane would apply', () => { + const options = buildPreviewAppearanceOptions(SETTINGS, false) + expect(options.fontSize).toBe(17) + expect(options.fontFamily).toContain('Fira Code') + expect(options.cursorStyle).toBe('bar') + expect(options.cursorBlink).toBe(false) + expect(options.lineHeight).toBe(1.4) + expect(options.wordSeparator).toBe(' ()[]') + expect(options.scrollSensitivity).toBe(3) + // Why: a bar cursor's inactive style must not become xterm's block outline. + expect(options.cursorInactiveStyle).toBe('bar') + }) + + it('enables macOptionIsMeta only for the resolved full Option-as-Alt', () => { + expect(buildPreviewAppearanceOptions(SETTINGS, true).macOptionIsMeta).toBe(true) + expect(buildPreviewAppearanceOptions(SETTINGS, false).macOptionIsMeta).toBe(false) + }) + + it('falls back to pane defaults with no settings hydrated', () => { + const options = buildPreviewAppearanceOptions(null, false) + expect(options.fontSize).toBe(14) + expect(options.cursorBlink).toBe(true) + }) +}) + +describe('buildPreviewTerminalOptions', () => { + const base = { + settings: SETTINGS, + macOptionIsMeta: false, + theme: null, + themeMode: 'dark' as const, + cols: 100, + rows: 30, + scrollback: 1000 + } + + it('keeps the kitty advertisement and skips ConPTY options off Windows', () => { + const options = buildPreviewTerminalOptions({ + ...base, + terminalInput: { + hostPlatform: 'darwin', + localWindowsConpty: false, + windowsShiftEnterEncoding: 'alt-enter', + kittyKeyboardAdvertised: true + } + }) + expect(options.vtExtensions?.kittyKeyboard).toBe(true) + expect(options.windowsPty).toBeUndefined() + expect(options.cols).toBe(100) + }) + + it('mirrors the ConPTY backend and kitty withhold a local Windows pane resolves', () => { + const options = buildPreviewTerminalOptions({ + ...base, + terminalInput: { + hostPlatform: 'win32', + localWindowsConpty: true, + osRelease: '10.0.22631', + windowsShiftEnterEncoding: 'alt-enter', + kittyKeyboardAdvertised: false + } + }) + expect(options.windowsPty).toEqual({ backend: 'conpty', buildNumber: 22631 }) + expect(options.vtExtensions?.kittyKeyboard).toBe(false) + }) + + it('keeps the advertised default when the card carries no host profile', () => { + const options = buildPreviewTerminalOptions({ ...base, terminalInput: null }) + expect(options.vtExtensions?.kittyKeyboard).toBe(true) + expect(options.windowsPty).toBeUndefined() + }) +}) diff --git a/src/renderer/src/components/dashboard-popout/preview-terminal-options.ts b/src/renderer/src/components/dashboard-popout/preview-terminal-options.ts new file mode 100644 index 000000000..bfbaae299 --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/preview-terminal-options.ts @@ -0,0 +1,83 @@ +import type { ITerminalInitOnlyOptions, ITerminalOptions, ITheme } from '@xterm/xterm' +import type { GlobalSettings } from '../../../../shared/types' +import type { DashboardCardTerminalInput } from '../../../../shared/dashboard-snapshot' +import { resolveTerminalFontWeights } from '../../../../shared/terminal-fonts' +import { normalizeTerminalLineHeight } from '../../../../shared/terminal-line-height-settings' +import { + buildDefaultTerminalOptions, + normalizeTerminalFastScrollSensitivity, + normalizeTerminalScrollSensitivity, + resolveTerminalCursorInactiveStyle +} from '@/lib/pane-manager/pane-terminal-options' +import { buildLocalConptyTerminalOptions } from '@/lib/pane-manager/windows-pty-compatibility' +import { buildFontFamily } from '@/components/terminal-pane/layout-serialization' +import { resolveTerminalMinimumContrastRatio } from '@/lib/terminal-contrast-correction' + +/** Options a live settings change can write onto an open preview terminal. */ +export function buildPreviewAppearanceOptions( + settings: GlobalSettings | null, + macOptionIsMeta: boolean +): Partial { + const cursorStyle = settings?.terminalCursorStyle ?? 'block' + const fontWeights = resolveTerminalFontWeights(settings?.terminalFontWeight) + return { + fontSize: settings?.terminalFontSize ?? 14, + fontFamily: buildFontFamily(settings?.terminalFontFamily ?? ''), + fontWeight: fontWeights.fontWeight, + fontWeightBold: fontWeights.fontWeightBold, + cursorStyle, + cursorInactiveStyle: resolveTerminalCursorInactiveStyle(cursorStyle), + cursorBlink: settings?.terminalCursorBlink ?? true, + scrollSensitivity: normalizeTerminalScrollSensitivity(settings?.terminalScrollSensitivity), + fastScrollSensitivity: normalizeTerminalFastScrollSensitivity( + settings?.terminalFastScrollSensitivity + ), + lineHeight: normalizeTerminalLineHeight(settings?.terminalLineHeight), + wordSeparator: settings?.terminalWordSeparator, + // Why only 'true': 'left'/'right' are handled by the keydown policy, which needs Option composable at the xterm level. + macOptionIsMeta, + // Why: xterm renders an alpha background opaque unless transparency is on (matches applyTerminalAppearance). + allowTransparency: + settings?.terminalBackgroundOpacity !== undefined && settings.terminalBackgroundOpacity < 1 + } +} + +/** + * Full option set for the preview's xterm: the same defaults, user appearance, + * and host compatibility flags a pane resolves, so the agent's TUI negotiates + * with an identically-configured emulator. Scrollback stays preview-sized — + * main only ever serializes a short history window into this terminal. + */ +export function buildPreviewTerminalOptions(args: { + settings: GlobalSettings | null + terminalInput: DashboardCardTerminalInput | null + macOptionIsMeta: boolean + theme: ITheme | null + themeMode: 'dark' | 'light' + cols: number + rows: number + scrollback: number +}): ITerminalOptions & ITerminalInitOnlyOptions { + const hostCompatibility: Partial = { + ...(args.terminalInput?.localWindowsConpty + ? buildLocalConptyTerminalOptions(args.terminalInput.osRelease) + : {}), + // Why: local ConPTY CLIs read the advertisement but can't decode CSI-u (#2434); mirror the pane's withhold. + ...(args.terminalInput && !args.terminalInput.kittyKeyboardAdvertised + ? { vtExtensions: { kittyKeyboard: false } } + : {}) + } + return { + ...buildDefaultTerminalOptions(), + ...buildPreviewAppearanceOptions(args.settings, args.macOptionIsMeta), + ...hostCompatibility, + cols: args.cols, + rows: args.rows, + scrollback: args.scrollback, + theme: args.theme ?? undefined, + minimumContrastRatio: resolveTerminalMinimumContrastRatio( + args.theme?.background, + args.themeMode + ) + } +} diff --git a/src/renderer/src/components/dashboard-popout/preview-terminal-paste.ts b/src/renderer/src/components/dashboard-popout/preview-terminal-paste.ts new file mode 100644 index 000000000..6738502d6 --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/preview-terminal-paste.ts @@ -0,0 +1,63 @@ +import type { Terminal } from '@xterm/xterm' +import { getShortcutPlatform } from '@/lib/shortcut-platform' +import { + executeTerminalPastePlan, + planTerminalPasteWithYield +} from '@/components/terminal-pane/terminal-paste-coordinator' +import { resolveTerminalPasteRuntime } from '@/components/terminal-pane/terminal-paste-runtime' +import { TERMINAL_PASTE_MAX_BYTES } from '@/components/terminal-pane/terminal-paste-limits' + +/** + * Clipboard paste for the preview terminal, on the pane's coordinator: large + * pastes stream as bounded IPC payloads, and the plan re-checks that the same + * terminal still owns focus between chunks. + */ +export function createPreviewClipboardPaster(deps: { + ptyId: string + container: HTMLElement + getTerminal: () => Terminal | null + isDisposed: () => boolean +}): (activeElementAtDispatch: Element | null, source: 'keyboard' | 'app-menu') => Promise { + return async (activeElementAtDispatch, source) => { + let text: string + try { + text = await window.api.ui.readClipboardText({ maxBytes: TERMINAL_PASTE_MAX_BYTES }) + } catch { + return + } + const pasteTerminal = deps.getTerminal() + if (!pasteTerminal || !text) { + return + } + const targetIsCurrent = (): boolean => + !deps.isDisposed() && + deps.getTerminal() === pasteTerminal && + activeElementAtDispatch !== null && + document.activeElement === activeElementAtDispatch && + deps.container.contains(activeElementAtDispatch) + if (!targetIsCurrent()) { + return + } + const platform = getShortcutPlatform() + const plan = await planTerminalPasteWithYield({ + text, + source, + target: { + kind: 'terminal', + paneId: 0, + leafId: deps.ptyId, + ptyId: deps.ptyId, + runtime: resolveTerminalPasteRuntime({ platform, ptyId: deps.ptyId }) + }, + terminalBracketedPasteMode: pasteTerminal.modes.bracketedPasteMode + }) + await executeTerminalPastePlan(plan, { + // Why: stream large pastes so the renderer never emits one huge IPC payload. + pasteText: (pasteText) => pasteTerminal.paste(pasteText), + writePty: (data) => window.api.terminalPreview.input(deps.ptyId, data), + isTargetCurrent: targetIsCurrent, + // Why: if focus changes mid-bracketed paste, the closing marker must still reach the live PTY. + canContinue: () => true + }) + } +} diff --git a/src/renderer/src/components/dashboard-popout/preview-terminal-shortcuts.test.ts b/src/renderer/src/components/dashboard-popout/preview-terminal-shortcuts.test.ts new file mode 100644 index 000000000..b76c7c146 --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/preview-terminal-shortcuts.test.ts @@ -0,0 +1,148 @@ +// @vitest-environment happy-dom + +import { describe, expect, it } from 'vitest' +import type { DashboardCardTerminalInput } from '../../../../shared/dashboard-snapshot' +import { + resolvePreviewShortcutAction, + type PreviewShortcutContext +} from './preview-terminal-shortcuts' + +const LOCAL_MAC: DashboardCardTerminalInput = { + hostPlatform: 'darwin', + localWindowsConpty: false, + windowsShiftEnterEncoding: 'alt-enter', + kittyKeyboardAdvertised: true +} + +function contextFor( + overrides: Partial & { kitty?: boolean } = {} +): PreviewShortcutContext { + return { + clientPlatform: 'darwin', + macOptionAsAlt: 'false', + optionKeyLocation: 0, + keybindings: undefined, + terminalInput: LOCAL_MAC, + kittyKeyboardActive: () => overrides.kitty === true, + terminalShortcutPolicy: 'orca-first', + ...overrides + } +} + +function keydown(init: KeyboardEventInit): KeyboardEvent { + return new KeyboardEvent('keydown', init) +} + +describe('resolvePreviewShortcutAction', () => { + it('kills the previous word on Ctrl+Backspace instead of deleting one character', () => { + expect( + resolvePreviewShortcutAction(keydown({ key: 'Backspace', ctrlKey: true }), contextFor()) + ).toEqual({ type: 'sendInput', data: '\x17' }) + }) + + it('maps the macOS line-kill and word-navigation chords', () => { + const context = contextFor() + expect( + resolvePreviewShortcutAction(keydown({ key: 'Backspace', metaKey: true }), context) + ).toEqual({ type: 'sendInput', data: '\x15' }) + expect( + resolvePreviewShortcutAction(keydown({ key: 'Delete', metaKey: true }), context) + ).toEqual({ type: 'sendInput', data: '\x0b' }) + expect( + resolvePreviewShortcutAction(keydown({ key: 'ArrowLeft', altKey: true }), context) + ).toEqual({ type: 'sendInput', data: '\x1bb' }) + expect( + resolvePreviewShortcutAction(keydown({ key: 'ArrowUp', metaKey: true }), context) + ).toEqual({ type: 'scrollViewport', position: 'top' }) + }) + + it('leaves Option chords to xterm while the TUI has kitty mode negotiated', () => { + const kittyContext = contextFor({ kitty: true }) + expect( + resolvePreviewShortcutAction(keydown({ key: 'Backspace', altKey: true }), kittyContext) + ).toBeNull() + expect( + resolvePreviewShortcutAction(keydown({ key: 'Backspace', altKey: true }), contextFor()) + ).toEqual({ type: 'sendInput', data: '\x1b\x7f' }) + }) + + it('withholds the Ctrl+arrow translation on a local ConPTY pty, where PSReadLine binds it', () => { + const conpty = contextFor({ + clientPlatform: 'win32', + terminalInput: { + hostPlatform: 'win32', + localWindowsConpty: true, + windowsShiftEnterEncoding: 'alt-enter', + kittyKeyboardAdvertised: false + } + }) + expect( + resolvePreviewShortcutAction(keydown({ key: 'ArrowLeft', ctrlKey: true }), conpty) + ).toBeNull() + expect( + resolvePreviewShortcutAction( + keydown({ key: 'ArrowLeft', ctrlKey: true }), + contextFor({ clientPlatform: 'linux', terminalInput: null }) + ) + ).toEqual({ type: 'sendInput', data: '\x1bb' }) + }) + + it('routes Shift+Enter by the PTY host, not the client OS', () => { + // A macOS client driving a Windows runtime that negotiated CSI-u. + const windowsHost = contextFor({ + terminalInput: { + hostPlatform: 'win32', + localWindowsConpty: false, + windowsShiftEnterEncoding: 'csi-u', + kittyKeyboardAdvertised: true + } + }) + expect( + resolvePreviewShortcutAction(keydown({ key: 'Enter', shiftKey: true }), windowsHost) + ).toEqual({ type: 'sendInput', data: '\x1b[13;2u' }) + expect( + resolvePreviewShortcutAction(keydown({ key: 'Enter', shiftKey: true }), contextFor()) + ).toEqual({ type: 'sendInput', data: '\x1b\r' }) + }) + + it('reports pane-scoped chords so the caller can swallow them', () => { + expect( + resolvePreviewShortcutAction(keydown({ key: 'd', code: 'KeyD', metaKey: true }), contextFor()) + ).toEqual({ type: 'splitActivePane', direction: 'vertical' }) + }) + + // Why: a terminal-first user remapped terminal.closePane away, so only the + // tab.close alias still matches Ctrl+W — which the shell owns as a word-kill. + // The pane yields it; the preview must not swallow it. + it('follows the terminal shortcut policy for the tab.close pane-close alias', () => { + const keybindings = { + 'terminal.closePane': ['Mod+Shift+W'], + 'tab.close': ['Ctrl+W'] + } as unknown as PreviewShortcutContext['keybindings'] + const chord = (): KeyboardEvent => keydown({ key: 'w', code: 'KeyW', ctrlKey: true }) + expect( + resolvePreviewShortcutAction( + chord(), + contextFor({ clientPlatform: 'linux', terminalInput: null, keybindings }) + ) + ).toEqual({ type: 'closeActivePane' }) + expect( + resolvePreviewShortcutAction( + chord(), + contextFor({ + clientPlatform: 'linux', + terminalInput: null, + keybindings, + terminalShortcutPolicy: 'terminal-first' + }) + ) + ).toBeNull() + }) + + it('leaves ordinary typing to xterm', () => { + expect( + resolvePreviewShortcutAction(keydown({ key: 'a', code: 'KeyA' }), contextFor()) + ).toBeNull() + expect(resolvePreviewShortcutAction(keydown({ key: 'Backspace' }), contextFor())).toBeNull() + }) +}) diff --git a/src/renderer/src/components/dashboard-popout/preview-terminal-shortcuts.ts b/src/renderer/src/components/dashboard-popout/preview-terminal-shortcuts.ts new file mode 100644 index 000000000..e235c8d49 --- /dev/null +++ b/src/renderer/src/components/dashboard-popout/preview-terminal-shortcuts.ts @@ -0,0 +1,58 @@ +import { + resolveTerminalShortcutAction, + type MacOptionAsAlt, + type TerminalShortcutAction +} from '@/components/terminal-pane/terminal-shortcut-policy' +import { getLayoutBaseCharacterForCode } from '@/lib/keyboard-layout/layout-base-character' +import type { DashboardCardTerminalInput } from '../../../../shared/dashboard-snapshot' +import { + normalizeTerminalShortcutPolicy, + type KeybindingOverrides, + type TerminalShortcutPolicy +} from '../../../../shared/keybindings' + +export type PreviewShortcutContext = { + clientPlatform: NodeJS.Platform + macOptionAsAlt: MacOptionAsAlt + /** Location of the physically held Option key (character keys report their own). */ + optionKeyLocation: number + keybindings: KeybindingOverrides | undefined + /** Host-input facts relayed with the card; null falls back to client-OS routing. */ + terminalInput: DashboardCardTerminalInput | null + /** Live kitty-protocol flags mirrored from this pty's output. */ + kittyKeyboardActive: () => boolean + /** The user's setting; terminal-first yields the tab.close alias to the shell. */ + terminalShortcutPolicy: TerminalShortcutPolicy | null | undefined +} + +/** + * Runs the preview terminal's keys through the same policy a pane uses, so the + * dashboard encodes word-kills, Option chords, and modified Enter identically. + * Every pane-scoped verdict (splits, search, focus) still comes back — the + * caller swallows those rather than leaking raw bytes to the agent. + */ +export function resolvePreviewShortcutAction( + event: KeyboardEvent, + context: PreviewShortcutContext +): TerminalShortcutAction | null { + const isMac = context.clientPlatform === 'darwin' + const hostPlatform = context.terminalInput?.hostPlatform ?? context.clientPlatform + return resolveTerminalShortcutAction( + event, + isMac, + context.macOptionAsAlt, + context.optionKeyLocation, + context.clientPlatform === 'win32', + context.keybindings, + // Why: PSReadLine on a local ConPTY binds Ctrl+←/→ itself; \eb/\ef would print stray b/f. + () => context.terminalInput?.localWindowsConpty === true, + context.kittyKeyboardActive, + getLayoutBaseCharacterForCode, + () => context.terminalInput?.windowsShiftEnterEncoding ?? 'alt-enter', + // Why: byte protocols follow the pty's host, which differs from the client OS on remote runtimes. + () => hostPlatform === 'win32', + // Why: without it a terminal-first user's remapped tab.close chord — Ctrl+W + // is a shell word-kill — reaches the shell in the pane but is swallowed here. + normalizeTerminalShortcutPolicy(context.terminalShortcutPolicy) + ) +} diff --git a/src/renderer/src/components/dashboard/build-dashboard-snapshot.test.ts b/src/renderer/src/components/dashboard/build-dashboard-snapshot.test.ts index a2821b094..aa3534eac 100644 --- a/src/renderer/src/components/dashboard/build-dashboard-snapshot.test.ts +++ b/src/renderer/src/components/dashboard/build-dashboard-snapshot.test.ts @@ -394,9 +394,23 @@ describe('buildDashboardSnapshot', () => { expect(snapshot.cards[0].workspaceStatusId).toBeUndefined() expect(snapshot.cards[0].subagents).toBeUndefined() + // Why: the card has a live pty, so only the count-path gate keeps the + // host-input resolution off the sidebar's per-status-tick rebuild. + expect(snapshot.cards[0].ptyId).toBe('pty1') + expect(snapshot.cards[0].terminalInput).toBeUndefined() expect(linkedReviewReads).toBe(0) }) + it("resolves a live pty's host-input profile for card snapshots", () => { + const snapshot = buildDashboardSnapshot( + baseState({ agentStatusByPaneKey: { [PANE_KEY]: entry({}) } }), + NOW + ) + + expect(snapshot.cards[0].terminalInput?.windowsShiftEnterEncoding).toBe('alt-enter') + expect(snapshot.cards[0].terminalInput?.kittyKeyboardAdvertised).toBe(true) + }) + it('relays the idle-column setting in the serialized snapshot', () => { const snapshot = buildDashboardSnapshot( baseState({ diff --git a/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts b/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts index e51313ad1..c7c3c9711 100644 --- a/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts +++ b/src/renderer/src/components/dashboard/build-dashboard-snapshot.ts @@ -10,6 +10,11 @@ import { import type { RepoIcon } from '../../../../shared/repo-icon' import { DEFAULT_WORKSPACE_STATUSES } from '../../../../shared/workspace-statuses' import { parsePaneKey } from '../../../../shared/stable-pane-id' +import { + resolveDashboardCardTerminalInput, + type DashboardCardTerminalInputState +} from './dashboard-card-terminal-input' +import { readDashboardClientHost } from './dashboard-client-host' import { getAgentRowConversationName } from '../../../../shared/agent-row-conversation-name' import { migrationUnsupportedToAgentStatusEntry } from '@/lib/migration-unsupported-agent-entry' import { applyAgentRowLineage } from './agent-row-lineage' @@ -54,7 +59,8 @@ export type DashboardSnapshotState = Pick< | 'acknowledgedAgentsByPaneKey' | 'settings' > & - DashboardCardContextState + DashboardCardContextState & + Partial function bucketForState(state: DashboardAgentRow['state']): DashboardBucket { switch (state) { @@ -123,6 +129,7 @@ export function buildDashboardSnapshot( options: { includeCardDetails?: boolean; includeFilterOptions?: boolean } = {} ): DashboardSnapshot { const cards: DashboardCard[] = [] + const clientHost = readDashboardClientHost() const repoIconsByRepoId: Record = {} const includeCardDetails = options.includeCardDetails !== false const generatedTitlesEnabled = state.settings?.tabAutoGenerateTitle === true @@ -262,6 +269,23 @@ export function buildDashboardSnapshot( : null const dotState = row.state as DashboardCardDotState const bucket = bucketForState(row.state) + // Why: only a live pty can open a preview terminal, and only a + // card-rendering caller can open one — the sidebar's bucket counts must + // not pay host resolution on every agent-status tick. + const terminalInput = + ptyId && includeCardDetails + ? resolveDashboardCardTerminalInput(state, { + ptyId, + worktreeId, + paneKey: routingPaneKey, + cwd: row.tab.startupCwd ?? worktree.path, + shellOverride: row.tab.shellOverride, + launchAgent: row.tab.launchAgent, + clientPlatform: clientHost.platform, + userAgent: clientHost.userAgent, + osRelease: clientHost.osRelease + }) + : null // Only repos that actually contribute a card ship their icon. repoIconsByRepoId[repo.id] = repo.repoIcon ?? null @@ -295,7 +319,8 @@ export function buildDashboardSnapshot( !isTitleDerived && (state.acknowledgedAgentsByPaneKey?.[row.paneKey] ?? 0) < row.entry.stateStartedAt, askSummary: bucket === 'attention' ? (row.entry.interactivePrompt ?? undefined) : undefined, - conversationName: boundedLabelOrUndefined(rowConversationName(row, generatedTitlesEnabled)) + conversationName: boundedLabelOrUndefined(rowConversationName(row, generatedTitlesEnabled)), + ...(terminalInput ? { terminalInput } : {}) }) } } diff --git a/src/renderer/src/components/dashboard/dashboard-card-terminal-input.test.ts b/src/renderer/src/components/dashboard/dashboard-card-terminal-input.test.ts new file mode 100644 index 000000000..d7aad2ce5 --- /dev/null +++ b/src/renderer/src/components/dashboard/dashboard-card-terminal-input.test.ts @@ -0,0 +1,144 @@ +// @vitest-environment happy-dom + +import { describe, expect, it } from 'vitest' +import { + resolveDashboardCardTerminalInput, + type DashboardCardTerminalInputState +} from './dashboard-card-terminal-input' + +const MAC_ARGS = { + ptyId: 'pty-1', + worktreeId: 'wt-1', + paneKey: 'tab-1:00000000-0000-4000-8000-000000000001', + cwd: '/Users/dev/repo', + shellOverride: undefined, + launchAgent: undefined, + clientPlatform: 'darwin' as NodeJS.Platform, + userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)', + osRelease: undefined +} + +const WINDOWS_ARGS = { + ...MAC_ARGS, + cwd: 'C:\\repo', + clientPlatform: 'win32' as NodeJS.Platform, + userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0.0.0', + osRelease: '10.0.22631' +} + +function stateWith( + overrides: Partial = {} +): Partial { + return { + repos: [{ id: 'repo-1', connectionId: null, executionHostId: 'local' }], + worktreesByRepo: { 'repo-1': [{ id: 'wt-1', repoId: 'repo-1' }] }, + ...overrides + } as Partial +} + +describe('resolveDashboardCardTerminalInput', () => { + it('resolves a local macOS pane to client-host routing with kitty advertised', () => { + expect(resolveDashboardCardTerminalInput(stateWith(), MAC_ARGS)).toEqual({ + hostPlatform: 'darwin', + localWindowsConpty: false, + windowsShiftEnterEncoding: 'alt-enter', + kittyKeyboardAdvertised: true + }) + }) + + it('marks a local native Windows pane as ConPTY and withholds the kitty advertisement', () => { + const profile = resolveDashboardCardTerminalInput(stateWith(), WINDOWS_ARGS) + expect(profile.localWindowsConpty).toBe(true) + expect(profile.kittyKeyboardAdvertised).toBe(false) + expect(profile.osRelease).toBe('10.0.22631') + }) + + it('keeps the kitty advertisement on ConPTY for an agent that needs CSI-u', () => { + const profile = resolveDashboardCardTerminalInput(stateWith(), { + ...WINDOWS_ARGS, + launchAgent: 'grok' + }) + expect(profile.localWindowsConpty).toBe(true) + expect(profile.kittyKeyboardAdvertised).toBe(true) + }) + + // Why: the pty runs Linux inside WSL, so byte protocols must follow it and + // not the Windows client — the pane resolves this from its own session cwd. + it('treats a WSL shell override as a non-ConPTY Linux-hosted pty', () => { + const profile = resolveDashboardCardTerminalInput(stateWith(), { + ...WINDOWS_ARGS, + shellOverride: 'wsl.exe' + }) + expect(profile.localWindowsConpty).toBe(false) + expect(profile.kittyKeyboardAdvertised).toBe(true) + expect(profile.hostPlatform).toBe('linux') + }) + + it('follows the WSL host for a UNC session path with no shell override', () => { + const profile = resolveDashboardCardTerminalInput(stateWith(), { + ...WINDOWS_ARGS, + cwd: '\\\\wsl$\\Ubuntu\\home\\dev\\repo' + }) + expect(profile.hostPlatform).toBe('linux') + expect(profile.localWindowsConpty).toBe(false) + }) + + it('keeps a native Windows pane on the client host', () => { + expect(resolveDashboardCardTerminalInput(stateWith(), WINDOWS_ARGS).hostPlatform).toBe('win32') + }) + + it('follows the SSH host platform rather than the client OS', () => { + const state = stateWith({ + repos: [{ id: 'repo-1', connectionId: 'conn-1', executionHostId: 'ssh:conn-1' }], + sshConnectionStates: new Map([['conn-1', { remotePlatform: 'win32' }]]) + } as unknown as Partial) + expect(resolveDashboardCardTerminalInput(state, MAC_ARGS).hostPlatform).toBe('win32') + }) + + it("keeps the live SSH PTY's host after the worktree owner changes", () => { + const state = stateWith({ + sshConnectionStates: new Map([['conn-live', { remotePlatform: 'win32' }]]) + } as unknown as Partial) + const profile = resolveDashboardCardTerminalInput(state, { + ...MAC_ARGS, + ptyId: 'ssh:conn-live@@pty-1' + }) + expect(profile.hostPlatform).toBe('win32') + expect(profile.localWindowsConpty).toBe(false) + }) + + it("keeps the live runtime PTY's host after the worktree owner changes", () => { + const state = stateWith({ + runtimeStatusByEnvironmentId: new Map([['env-live', { status: { hostPlatform: 'linux' } }]]) + } as unknown as Partial) + const profile = resolveDashboardCardTerminalInput(state, { + ...WINDOWS_ARGS, + ptyId: 'remote:env-live@@pty-1' + }) + expect(profile.hostPlatform).toBe('linux') + expect(profile.localWindowsConpty).toBe(false) + expect(profile.kittyKeyboardAdvertised).toBe(true) + }) + + it('degrades to client-OS routing when the store has not hydrated', () => { + expect(resolveDashboardCardTerminalInput({}, MAC_ARGS)).toEqual({ + hostPlatform: 'darwin', + localWindowsConpty: false, + windowsShiftEnterEncoding: 'alt-enter', + kittyKeyboardAdvertised: true + }) + }) + + it('does not enumerate unrelated store slices per card', () => { + const state = stateWith() as Partial & { + unrelatedSlice?: unknown + } + Object.defineProperty(state, 'unrelatedSlice', { + enumerable: true, + get: () => { + throw new Error('unrelated store slice was read') + } + }) + expect(() => resolveDashboardCardTerminalInput(state, MAC_ARGS)).not.toThrow() + }) +}) diff --git a/src/renderer/src/components/dashboard/dashboard-card-terminal-input.ts b/src/renderer/src/components/dashboard/dashboard-card-terminal-input.ts new file mode 100644 index 000000000..ab7fc611c --- /dev/null +++ b/src/renderer/src/components/dashboard/dashboard-card-terminal-input.ts @@ -0,0 +1,132 @@ +import type { AppState } from '@/store/types' +import type { DashboardCardTerminalInput } from '../../../../shared/dashboard-snapshot' +import type { TuiAgent } from '../../../../shared/types' +import { toRuntimeExecutionHostId, toSshExecutionHostId } from '../../../../shared/execution-host' +import { parseAppSshPtyId } from '../../../../shared/ssh-pty-id' +import { getConnectionIdFromState } from '@/lib/connection-context' +import { getExecutionHostIdForWorktree } from '@/lib/worktree-runtime-owner' +import { shouldDisableKittyKeyboardForTerminal } from '@/lib/pane-manager/terminal-keyboard-protocol' +import { isLocalNativeWindowsConpty } from '@/lib/pane-manager/windows-pty-compatibility' +import { resolveTerminalInputHostPlatform } from '@/components/terminal-pane/terminal-input-host-platform' +import { resolveWindowsShiftEnterEncodingForPane } from '@/components/terminal-pane/terminal-windows-shift-enter' +import { getRemoteRuntimePtyEnvironmentId } from '@/runtime/runtime-terminal-stream' + +/** Store slices the pane's own input helpers read. */ +export type DashboardCardTerminalInputState = Pick< + AppState, + | 'repos' + | 'worktreesByRepo' + | 'detectedWorktreesByRepo' + | 'folderWorkspaces' + | 'projectGroups' + | 'settings' + | 'sshConnectionStates' + | 'sshStateByEnvironment' + | 'runtimeStatusByEnvironmentId' + | 'restoredRuntimeHostIdByWorkspaceSessionKey' + | 'runtimeEnvironments' + | 'runtimeEnvironmentCatalogHydrated' + | 'removedRuntimeEnvironmentIds' + | 'paneForegroundAgentByPaneKey' + | 'agentLaunchConfigByPaneKey' +> + +const EMPTY_RECORD = {} as Record + +/** Why: the snapshot builder must never throw on a partially hydrated store — + * a missing slice degrades one card to client-OS defaults, not a blank board. */ +function withHydratedSlices( + state: Partial +): DashboardCardTerminalInputState { + return { + repos: state.repos ?? [], + worktreesByRepo: state.worktreesByRepo ?? EMPTY_RECORD, + detectedWorktreesByRepo: state.detectedWorktreesByRepo ?? EMPTY_RECORD, + folderWorkspaces: state.folderWorkspaces ?? [], + projectGroups: state.projectGroups ?? [], + settings: state.settings ?? null, + sshConnectionStates: state.sshConnectionStates ?? new Map(), + sshStateByEnvironment: state.sshStateByEnvironment ?? new Map(), + runtimeStatusByEnvironmentId: state.runtimeStatusByEnvironmentId ?? new Map(), + restoredRuntimeHostIdByWorkspaceSessionKey: + state.restoredRuntimeHostIdByWorkspaceSessionKey ?? EMPTY_RECORD, + runtimeEnvironments: state.runtimeEnvironments ?? [], + runtimeEnvironmentCatalogHydrated: state.runtimeEnvironmentCatalogHydrated ?? false, + removedRuntimeEnvironmentIds: state.removedRuntimeEnvironmentIds ?? new Set(), + paneForegroundAgentByPaneKey: state.paneForegroundAgentByPaneKey ?? EMPTY_RECORD, + agentLaunchConfigByPaneKey: state.agentLaunchConfigByPaneKey ?? EMPTY_RECORD + } +} + +/** + * Resolve the host-dependent input facts a card's preview terminal needs to + * encode keys like the agent's own pane. Store-derived only — the board holds no + * live PtyTransport, so the shared pane helpers run their fallback path, the + * same one a pane itself uses before its transport attaches. + */ +export function resolveDashboardCardTerminalInput( + partialState: Partial, + args: { + ptyId: string + worktreeId: string + paneKey: string + /** Worktree path — decides WSL vs native Windows for a local pty. */ + cwd: string + shellOverride: string | null | undefined + launchAgent: TuiAgent | null | undefined + clientPlatform: NodeJS.Platform + userAgent: string + osRelease: string | undefined + } +): DashboardCardTerminalInput { + const state = withHydratedSlices(partialState) + const sshPty = parseAppSshPtyId(args.ptyId) + const runtimeEnvironmentId = getRemoteRuntimePtyEnvironmentId(args.ptyId) + const connectionId = + sshPty?.connectionId ?? + (runtimeEnvironmentId ? null : getConnectionIdFromState(state, args.worktreeId)) + const executionHostId = sshPty + ? toSshExecutionHostId(sshPty.connectionId) + : runtimeEnvironmentId + ? toRuntimeExecutionHostId(runtimeEnvironmentId) + : getExecutionHostIdForWorktree(state, args.worktreeId) + const windowsPtyContext = { + userAgent: args.userAgent, + osRelease: args.osRelease, + connectionId, + cwd: args.cwd, + shellOverride: args.shellOverride, + executionHostId + } + return { + hostPlatform: resolveTerminalInputHostPlatform({ + clientPlatform: args.clientPlatform, + state, + worktreeId: args.worktreeId, + transport: { + getConnectionId: () => connectionId, + getPtyId: () => args.ptyId, + getExecutionHostId: () => executionHostId, + // Why: gated exactly like the pane transport's own accessor — without + // it a WSL pty on a Windows client resolves to win32 and Shift+Enter + // would encode CSI-u where the pane sends alt-enter. + getLocalSessionMetadata: () => + connectionId + ? null + : { + ...(args.cwd ? { cwd: args.cwd } : {}), + ...(args.shellOverride ? { shellOverride: args.shellOverride } : {}) + } + } + }), + localWindowsConpty: isLocalNativeWindowsConpty(windowsPtyContext), + ...(args.osRelease === undefined ? {} : { osRelease: args.osRelease }), + windowsShiftEnterEncoding: resolveWindowsShiftEnterEncodingForPane(state, args.paneKey), + kittyKeyboardAdvertised: !shouldDisableKittyKeyboardForTerminal({ + ...windowsPtyContext, + // Why: launch identity is the only agent signal the board holds; it opts + // Grok out of the ConPTY kitty withhold exactly as its pane does. + tuiAgent: args.launchAgent ?? null + }) + } +} diff --git a/src/renderer/src/components/dashboard/dashboard-client-host.ts b/src/renderer/src/components/dashboard/dashboard-client-host.ts new file mode 100644 index 000000000..adb507b60 --- /dev/null +++ b/src/renderer/src/components/dashboard/dashboard-client-host.ts @@ -0,0 +1,32 @@ +/** + * The facts about the machine *rendering* the board, as opposed to the machine + * executing a pty. A card's preview terminal needs both: byte encodings follow + * the pty's host, while xterm's own ConPTY wrap-marker compat follows the client. + */ +export type DashboardClientHost = { + platform: NodeJS.Platform + userAgent: string + osRelease: string | undefined +} + +export function readDashboardClientHost(): DashboardClientHost { + const userAgent = typeof navigator === 'undefined' ? '' : navigator.userAgent + return { + platform: userAgent.includes('Mac') + ? 'darwin' + : userAgent.includes('Windows') + ? 'win32' + : 'linux', + userAgent, + // Why: absent in the pop-out renderer and in tests, where no preload rides along. + osRelease: readClientOsRelease() + } +} + +function readClientOsRelease(): string | undefined { + try { + return window.api?.platform?.get?.()?.osRelease + } catch { + return undefined + } +} diff --git a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.test.tsx b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.test.tsx index 1bc03a6b4..e4d853d6e 100644 --- a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.test.tsx +++ b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.test.tsx @@ -67,8 +67,21 @@ function makeSnapshotWatchState(): DashboardSnapshotWatchState { runtimePaneTitlesByTabId: {}, acknowledgedAgentsByPaneKey: {}, settings: null, - agentStatusEpoch: 0 - } + agentStatusEpoch: 0, + // Why: seeded with real identities so the profile assertions below compare + // two distinct values — omitting them would pass against `undefined`. + sshConnectionStates: new Map(), + sshStateByEnvironment: new Map(), + runtimeStatusByEnvironmentId: new Map(), + paneForegroundAgentByPaneKey: {}, + detectedWorktreesByRepo: {}, + folderWorkspaces: [], + projectGroups: [], + restoredRuntimeHostIdByWorkspaceSessionKey: {}, + runtimeEnvironments: [], + runtimeEnvironmentCatalogHydrated: false, + removedRuntimeEnvironmentIds: new Set() + } as DashboardSnapshotWatchState } function Harness({ enabled }: { enabled: boolean }): null { @@ -167,6 +180,30 @@ describe('useDashboardPopoutBridge', () => { expect( dashboardSnapshotInputsChanged({ ...previousState, agentStatusEpoch: 1 }, previousState) ).toBe(true) + + // Why: each card's preview terminal keys against a host-input profile + // derived from these. Not republishing leaves the pop-out encoding bytes + // for the host the pty used to run on. + const profileInputs: Partial[] = [ + { sshConnectionStates: new Map() }, + { sshStateByEnvironment: new Map() }, + { runtimeStatusByEnvironmentId: new Map() }, + { paneForegroundAgentByPaneKey: {} }, + { detectedWorktreesByRepo: {} }, + // A folder workspace is not a git worktree; its host resolves through these. + { folderWorkspaces: [] }, + { projectGroups: [] }, + { restoredRuntimeHostIdByWorkspaceSessionKey: {} }, + { runtimeEnvironments: [] }, + { runtimeEnvironmentCatalogHydrated: true }, + { removedRuntimeEnvironmentIds: new Set() } + ] + const republished = profileInputs + .filter((next) => + dashboardSnapshotInputsChanged({ ...previousState, ...next }, previousState) + ) + .map((next) => Object.keys(next)[0]) + expect(republished).toEqual(profileInputs.map((next) => Object.keys(next)[0])) }) it('releases every dashboard listener when the experiment is disabled', async () => { diff --git a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts index abde79789..0c0d26909 100644 --- a/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts +++ b/src/renderer/src/components/dashboard/useDashboardPopoutBridge.ts @@ -58,7 +58,27 @@ export function dashboardSnapshotInputsChanged( state.settings !== previousState.settings || state.workspaceStatuses !== previousState.workspaceStatuses || // Why: freshness can change a bucket without replacing any backing map. - state.agentStatusEpoch !== previousState.agentStatusEpoch + state.agentStatusEpoch !== previousState.agentStatusEpoch || + // Why: each card carries the host-input profile its preview terminal keys + // against, and the pop-out cannot re-derive it. Every slice that resolves + // an execution host must republish or the preview keeps encoding bytes for + // the host the pty used to run on — a quiet board has no later publish to + // heal from. All are low-frequency except the foreground agent, whose churn + // the publish throttle already absorbs. + state.sshConnectionStates !== previousState.sshConnectionStates || + state.sshStateByEnvironment !== previousState.sshStateByEnvironment || + state.runtimeStatusByEnvironmentId !== previousState.runtimeStatusByEnvironmentId || + state.paneForegroundAgentByPaneKey !== previousState.paneForegroundAgentByPaneKey || + state.detectedWorktreesByRepo !== previousState.detectedWorktreesByRepo || + // Why: a folder workspace is not a git worktree — its host resolves through + // these two instead of worktreesByRepo. + state.folderWorkspaces !== previousState.folderWorkspaces || + state.projectGroups !== previousState.projectGroups || + state.restoredRuntimeHostIdByWorkspaceSessionKey !== + previousState.restoredRuntimeHostIdByWorkspaceSessionKey || + state.runtimeEnvironments !== previousState.runtimeEnvironments || + state.runtimeEnvironmentCatalogHydrated !== previousState.runtimeEnvironmentCatalogHydrated || + state.removedRuntimeEnvironmentIds !== previousState.removedRuntimeEnvironmentIds ) } diff --git a/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.test.ts b/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.test.ts index 9ebaa72fb..2b6c35db8 100644 --- a/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.test.ts +++ b/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.test.ts @@ -123,4 +123,42 @@ describe('useLiveDashboardSnapshot', () => { 'repo-1': { type: 'lucide', name: 'Rocket' } }) }) + + // Why: the profile resolves from connection/runtime slices this hook does not + // subscribe to. Dropping one degrades the drawer's preview terminal to + // client-OS byte routing while the pop-out keeps encoding correctly. + it("resolves each card's host-input profile from the slices it does not subscribe to", () => { + seed({ tabAutoGenerateTitle: false }) + const { result: localResult } = renderHook(() => useLiveDashboardSnapshot()) + expect(localResult.current.cards[0].terminalInput?.hostPlatform).toBe('linux') + + useAppStore.setState({ + repos: [{ ...repo(), connectionId: 'conn-1', executionHostId: 'ssh:conn-1' }], + sshConnectionStates: new Map([ + ['conn-1', { remotePlatform: 'win32' }] + ]) as unknown as ReturnType['sshConnectionStates'] + }) + const { result: sshResult } = renderHook(() => useLiveDashboardSnapshot()) + expect(sshResult.current.cards[0].terminalInput?.hostPlatform).toBe('win32') + }) + + // Why: a fresh renderHook always recomputes, so only re-rendering the SAME + // hook proves the memo watches the slice. An idle board publishes nothing + // else, so a missed subscription never heals. + it('re-derives the host-input profile when only a host slice changes', () => { + seed({ tabAutoGenerateTitle: false }) + useAppStore.setState({ + repos: [{ ...repo(), connectionId: 'conn-1', executionHostId: 'ssh:conn-1' }] + }) + const { result, rerender } = renderHook(() => useLiveDashboardSnapshot()) + expect(result.current.cards[0].terminalInput?.hostPlatform).toBe('linux') + + useAppStore.setState({ + sshConnectionStates: new Map([ + ['conn-1', { remotePlatform: 'win32' }] + ]) as unknown as ReturnType['sshConnectionStates'] + }) + rerender() + expect(result.current.cards[0].terminalInput?.hostPlatform).toBe('win32') + }) }) diff --git a/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts b/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts index fe8e99dd8..43933bfae 100644 --- a/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts +++ b/src/renderer/src/components/dashboard/useLiveDashboardSnapshot.ts @@ -28,6 +28,29 @@ export function useLiveDashboardSnapshot(): DashboardSnapshot { // Why: controls idle visibility and gates generated conversation names. const settings = useAppStore((s) => s.settings) const workspaceStatuses = useAppStore((s) => s.workspaceStatuses) + // Why: each card carries the host-input profile its preview terminal keys + // against, so the drawer must watch every slice that resolves an execution + // host — exactly the set useDashboardPopoutBridge republishes on. Agent + // activity alone cannot heal these: a board whose agents are idle never + // rebuilds, so an SSH handshake or host swap would leave the preview encoding + // bytes for the host the pty used to run on. All are low-frequency (each + // writer bails out when nothing changed) next to agentStatusByPaneKey, which + // already rebuilds this memo on every status ping. + const detectedWorktreesByRepo = useAppStore((s) => s.detectedWorktreesByRepo) + // Why: a folder workspace is not a git worktree — its host resolves through + // these two instead of worktreesByRepo. + const folderWorkspaces = useAppStore((s) => s.folderWorkspaces) + const projectGroups = useAppStore((s) => s.projectGroups) + const sshConnectionStates = useAppStore((s) => s.sshConnectionStates) + const sshStateByEnvironment = useAppStore((s) => s.sshStateByEnvironment) + const runtimeStatusByEnvironmentId = useAppStore((s) => s.runtimeStatusByEnvironmentId) + const restoredRuntimeHostIdByWorkspaceSessionKey = useAppStore( + (s) => s.restoredRuntimeHostIdByWorkspaceSessionKey + ) + const runtimeEnvironments = useAppStore((s) => s.runtimeEnvironments) + const runtimeEnvironmentCatalogHydrated = useAppStore((s) => s.runtimeEnvironmentCatalogHydrated) + const removedRuntimeEnvironmentIds = useAppStore((s) => s.removedRuntimeEnvironmentIds) + const paneForegroundAgentByPaneKey = useAppStore((s) => s.paneForegroundAgentByPaneKey) // Why: freshness can flip a bucket without any backing map changing; the epoch // ticks on the freshness boundary so the memo re-derives stale-decayed cards. const agentStatusEpoch = useAppStore((s) => s.agentStatusEpoch) @@ -52,7 +75,22 @@ export function useLiveDashboardSnapshot(): DashboardSnapshot { hostedReviewCache, prCache, settings, - workspaceStatuses + workspaceStatuses, + detectedWorktreesByRepo, + folderWorkspaces, + projectGroups, + sshConnectionStates, + sshStateByEnvironment, + runtimeStatusByEnvironmentId, + restoredRuntimeHostIdByWorkspaceSessionKey, + runtimeEnvironments, + runtimeEnvironmentCatalogHydrated, + removedRuntimeEnvironmentIds, + paneForegroundAgentByPaneKey, + // Why: read non-reactively — resolveWindowsShiftEnterEncoding takes + // launch identity but never routes on it, so subscribing would only + // rebuild the board. Matches the bridge's republish gate. + agentLaunchConfigByPaneKey: useAppStore.getState().agentLaunchConfigByPaneKey }, Date.now() ), @@ -73,6 +111,17 @@ export function useLiveDashboardSnapshot(): DashboardSnapshot { prCache, settings, workspaceStatuses, + detectedWorktreesByRepo, + folderWorkspaces, + projectGroups, + sshConnectionStates, + sshStateByEnvironment, + runtimeStatusByEnvironmentId, + restoredRuntimeHostIdByWorkspaceSessionKey, + runtimeEnvironments, + runtimeEnvironmentCatalogHydrated, + removedRuntimeEnvironmentIds, + paneForegroundAgentByPaneKey, agentStatusEpoch ] ) diff --git a/src/renderer/src/lib/pane-manager/pane-lifecycle.ts b/src/renderer/src/lib/pane-manager/pane-lifecycle.ts index 91cffb1e6..dd6f41e43 100644 --- a/src/renderer/src/lib/pane-manager/pane-lifecycle.ts +++ b/src/renderer/src/lib/pane-manager/pane-lifecycle.ts @@ -15,7 +15,7 @@ import { attachDomRendererFocusClassSync } from './pane-dom-focus-class-sync' import { attachWebgl, cancelPendingWebglRefresh, disposeWebgl } from './pane-webgl-renderer' import { configureLazyArabicShapingJoiner } from './terminal-arabic-shaping-joiner' import { TerminalLigaturesAddon } from './terminal-ligatures-addon' -import { resolveCursorAgentImeAnchor } from './terminal-ime-anchor' +import { installTerminalImeCandidateAnchor } from './terminal-ime-candidate-anchor' // --------------------------------------------------------------------------- // Pane creation, terminal open/close, addon management @@ -84,61 +84,8 @@ export function openTerminal(pane: ManagedPaneInternal): void { () => pane.webglAddon != null ) - // Why: the OS reads the focused textarea's screen rect at compositionstart to - // decide where to display the IME candidate window. xterm positions that - // textarea from its own cursor, which can be stale or intentionally hidden by - // TUIs. We force-sync after xterm's own composition handlers so the OS sees - // the corrected location before it opens the candidate window. - // - // Cell dimensions are derived from the public .xterm-screen element's bounds - // (xterm sizes that element to cols*cellWidth × rows*cellHeight) rather than - // poking `_core._renderService.dimensions` — keeps us on the public API - // surface so upgrades don't silently regress the fix. - if (terminal.element && terminal.textarea) { - const screenElement = terminal.element.querySelector('.xterm-screen') - const textarea = terminal.textarea - const handler = (): void => { - if (!screenElement) { - return - } - const rect = screenElement.getBoundingClientRect() - const cellWidth = rect.width / terminal.cols - const cellHeight = rect.height / terminal.rows - if (!(cellWidth > 0) || !(cellHeight > 0)) { - return - } - const buf = terminal.buffer.active - // Why: Cursor Agent draws its prompt UI while leaving xterm's public cursor - // on a blank row, so the OS IME anchor needs the rendered prompt row instead. - const cursorAgentAnchor = resolveCursorAgentImeAnchor({ - buffer: buf, - rows: terminal.rows, - cols: terminal.cols, - cursorX: buf.cursorX, - cursorY: buf.cursorY - }) - const anchor = cursorAgentAnchor ?? { - row: buf.cursorY, - column: Math.min(buf.cursorX, terminal.cols - 1) - } - const applyAnchor = (): void => { - textarea.style.top = `${anchor.row * cellHeight}px` - textarea.style.left = `${anchor.column * cellWidth}px` - } - applyAnchor() - if (cursorAgentAnchor) { - window.setTimeout(() => { - if (textarea.isConnected) { - applyAnchor() - } - }, 0) - } - } - terminal.element.addEventListener('compositionstart', handler) - terminal.element.addEventListener('compositionupdate', handler) - // Store so disposePane() can remove it and avoid a memory leak. - pane.compositionHandler = handler - } + // Store so disposePane() can remove it and avoid a memory leak. + pane.compositionHandler = installTerminalImeCandidateAnchor(terminal) pane.focusClassSyncCleanup = attachDomRendererFocusClassSync(terminal.element) diff --git a/src/renderer/src/lib/pane-manager/terminal-ime-candidate-anchor.ts b/src/renderer/src/lib/pane-manager/terminal-ime-candidate-anchor.ts new file mode 100644 index 000000000..c8979c6f3 --- /dev/null +++ b/src/renderer/src/lib/pane-manager/terminal-ime-candidate-anchor.ts @@ -0,0 +1,67 @@ +import type { Terminal } from '@xterm/xterm' +import { resolveCursorAgentImeAnchor } from './terminal-ime-anchor' + +/** + * Keep the OS IME candidate window anchored to the cell the user is typing in. + * + * Why: the OS reads the focused textarea's screen rect at compositionstart to + * decide where to display the candidate window. xterm positions that textarea + * from its own cursor, which can be stale or intentionally hidden by TUIs. We + * force-sync after xterm's own composition handlers so the OS sees the corrected + * location before it opens the candidate window. + * + * Cell dimensions are derived from the public .xterm-screen element's bounds + * (xterm sizes that element to cols*cellWidth × rows*cellHeight) rather than + * poking `_core._renderService.dimensions` — keeps us on the public API surface + * so upgrades don't silently regress the fix. + * + * Returns the installed handler so the caller can remove it on dispose, or null + * when the terminal has not opened its DOM yet. + */ +export function installTerminalImeCandidateAnchor(terminal: Terminal): (() => void) | null { + if (!terminal.element || !terminal.textarea) { + return null + } + const screenElement = terminal.element.querySelector('.xterm-screen') + const textarea = terminal.textarea + const handler = (): void => { + if (!screenElement) { + return + } + const rect = screenElement.getBoundingClientRect() + const cellWidth = rect.width / terminal.cols + const cellHeight = rect.height / terminal.rows + if (!(cellWidth > 0) || !(cellHeight > 0)) { + return + } + const buf = terminal.buffer.active + // Why: Cursor Agent draws its prompt UI while leaving xterm's public cursor + // on a blank row, so the OS IME anchor needs the rendered prompt row instead. + const cursorAgentAnchor = resolveCursorAgentImeAnchor({ + buffer: buf, + rows: terminal.rows, + cols: terminal.cols, + cursorX: buf.cursorX, + cursorY: buf.cursorY + }) + const anchor = cursorAgentAnchor ?? { + row: buf.cursorY, + column: Math.min(buf.cursorX, terminal.cols - 1) + } + const applyAnchor = (): void => { + textarea.style.top = `${anchor.row * cellHeight}px` + textarea.style.left = `${anchor.column * cellWidth}px` + } + applyAnchor() + if (cursorAgentAnchor) { + window.setTimeout(() => { + if (textarea.isConnected) { + applyAnchor() + } + }, 0) + } + } + terminal.element.addEventListener('compositionstart', handler) + terminal.element.addEventListener('compositionupdate', handler) + return handler +} diff --git a/src/renderer/src/lib/pane-manager/windows-pty-compatibility.ts b/src/renderer/src/lib/pane-manager/windows-pty-compatibility.ts index 549defbb3..5dd034950 100644 --- a/src/renderer/src/lib/pane-manager/windows-pty-compatibility.ts +++ b/src/renderer/src/lib/pane-manager/windows-pty-compatibility.ts @@ -56,10 +56,15 @@ export function buildWindowsPtyCompatibilityOptions( if (!isLocalNativeWindowsConpty(context)) { return {} } - const buildNumber = parseWindowsBuildNumber(context.osRelease) - return { - windowsPty: buildXtermWindowsPtyOptions(buildNumber) - } + return buildLocalConptyTerminalOptions(context.osRelease) +} + +/** ConPTY backend options for a pane already known to be local native Windows — + * the dashboard preview resolves that verdict upstream and reuses this. */ +export function buildLocalConptyTerminalOptions( + osRelease: string | null | undefined +): Partial { + return { windowsPty: buildXtermWindowsPtyOptions(parseWindowsBuildNumber(osRelease)) } } /** Mirror of main's effectiveShellOverride fold (pty.ts spawn handlers): a diff --git a/src/shared/dashboard-snapshot.ts b/src/shared/dashboard-snapshot.ts index 5b70bf358..043786e57 100644 --- a/src/shared/dashboard-snapshot.ts +++ b/src/shared/dashboard-snapshot.ts @@ -85,6 +85,29 @@ export type DashboardCard = { /** The tab's conversation name, resolved exactly as the sidebar's agent rows * resolve it. Undefined when no usable name exists (status-only titles). */ conversationName?: string + /** Host-dependent input facts the preview terminal needs to encode keys the + * way this agent's real pane does. Null when the card has no live pty. Only + * the main renderer owns the store these derive from, so they ride the + * snapshot to reach the pop-out. */ + terminalInput?: DashboardCardTerminalInput +} + +/** + * Per-pty input contract shared by a pane and its dashboard preview. Byte + * protocols follow the PTY's execution host, not the client OS — they differ + * for a macOS client driving a Windows runtime. + */ +export type DashboardCardTerminalInput = { + /** Platform executing the pty; picks the host-side byte encodings. */ + hostPlatform: NodeJS.Platform + /** Local native Windows ConPTY, where PSReadLine binds Ctrl+←/→ itself. */ + localWindowsConpty: boolean + /** OS release of a local Windows client, for xterm's ConPTY wrap-marker compat. */ + osRelease?: string + /** Shift+Enter encoding resolved from this pane's agent evidence. */ + windowsShiftEnterEncoding: 'alt-enter' | 'csi-u' + /** False withholds the kitty (CSI-u) advertisement, as ConPTY panes do. */ + kittyKeyboardAdvertised: boolean } export type DashboardFilterOption = {