diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 309404761034..6dc255162069 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -1,6 +1,6 @@ { "schemaVersion": 1, - "updatedAt": "2026-07-09", + "updatedAt": "2026-07-10", "policy": { "maturityLevels": [ "experimental", @@ -1791,6 +1791,258 @@ ], "demotionRule": "Cannot promote if standard-key behavior is inferred without PTY byte evidence." }, + { + "id": "terminal-input.windows-modified-enter-routing", + "title": "Windows modified Enter routes agent-compatible bytes to the active pane", + "maturity": "experimental", + "protection": "partial", + "owner": "terminal-input", + "layer": "main-provider-renderer-unit-and-windows-electron", + "surfaces": [ + "terminal input", + "Windows modified Enter", + "agent identity", + "split panes", + "SSH", + "WSL", + "remote runtime" + ], + "platforms": [ + "macos", + "linux", + "windows" + ], + "providers": [ + "local", + "daemon", + "ssh", + "wsl", + "remote-runtime" + ], + "coveredPlatforms": [ + "macos" + ], + "coveredProviders": [], + "coverageNotes": "Deterministic main/renderer tests run on macOS and exercise simulated Windows plus POSIX/Linux process-confirmation behavior. They cover exact local-ConPTY membership, detached-child rejection, unchanged SSH/WSL/remote fallback, process-confirmed Droid routing and launch-triggered confirmation, typed-alias and forged-OSC isolation, shells without OSC 133, split/detach ownership with preserved shell classification, stale PTY exit/rebind rejection, command-generation revocation, daemon v21 warm-reattach identity, unavailable inspection, and lazy subprocess/RPC callback counts. The Electron byte test runs only on Windows; live Windows and Linux PTY evidence remains uncollected. Test failures report exact expected bytes; no product telemetry or raw terminal logging is added.", + "motivatingLinks": [ + "https://github.com/stablyai/orca/issues/7620", + "https://github.com/stablyai/orca/pull/7668" + ], + "invariant": "Shift+Enter sends CSI-u only when the active pane is a genuine local Windows ConPTY with allowlisted Droid ownership or fresh routing-trusted Droid process evidence. Every new command and PTY replacement revokes stale routing until current evidence settles. All other Windows panes preserve Esc+CR; non-Windows panes remain CSI-u; SSH/WSL/remote behavior is unchanged; split or reused panes cannot inherit sibling or prior-PTY authority; unrelated keys perform no agent or ConPTY lookup.", + "oracle": "Main/renderer tests assert exact bytes for local and non-local Windows plus non-Windows policy cells. Fresh Windows process evidence authorizes bytes only after a recognized global candidate is intersected with the exact ConPTY console process list; detached descendants, helper failure/timeout/root-only fallback, stale PTY exit/rebind results, typed text, and hook/OSC output fail closed. A new OSC 133;C immediately publishes a routing-neutral generation, including during D-to-C races. In cmd.exe/Git Bash/custom shells without OSC 133, accepted inferred commands start the same fresh generation; accepted submit/interrupt, title exit, focus, and visibility revoke trusted Droid bytes while one bounded confirmation runs. Detach preserves the live PTY's source shell override so WSL/native classification cannot change with the current default. Ordinary fast shell commands use cached/no-scan paths; routing-relevant confirmation bypasses cached process snapshots and keeps the bounded three-read ladder. Daemon protocol v21 persists only an allowlisted launchAgent; warm reattach uses it as a display/confirmation hint and restores routing only after current process proof. The Windows Electron test focuses the real xterm textarea and records exact renderer-to-main PTY writes.", + "commands": [ + "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/daemon-foreground-confirmation-protocol.test.ts src/main/daemon/daemon-pty-adapter.test.ts src/main/daemon/daemon-pty-router.test.ts src/main/daemon/daemon-server.test.ts src/main/daemon/degraded-daemon-pty-provider.test.ts src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts src/main/daemon/pty-subprocess.test.ts src/main/ipc/pty.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider.test.ts src/main/providers/windows-conpty-process-membership.test.ts src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts src/renderer/src/components/terminal-pane/pty-transport.test.ts src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts src/renderer/src/store/slices/store-cascades.test.ts src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts src/shared/agent-process-recognition.test.ts src/shared/process-table-snapshot.test.ts tests/e2e/terminal-foreground-confirmation.unit.test.ts", + "pnpm run test:e2e -- tests/e2e/terminal-shortcuts.spec.ts" + ], + "testFiles": [ + "src/main/daemon/daemon-foreground-confirmation-protocol.test.ts", + "src/main/daemon/daemon-pty-adapter.test.ts", + "src/main/daemon/daemon-pty-router.test.ts", + "src/main/daemon/daemon-server.test.ts", + "src/main/daemon/degraded-daemon-pty-provider.test.ts", + "src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts", + "src/main/daemon/pty-subprocess.test.ts", + "src/main/ipc/pty.test.ts", + "src/main/providers/agent-foreground-process.test.ts", + "src/main/providers/local-pty-provider.test.ts", + "src/main/providers/windows-conpty-process-membership.test.ts", + "src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts", + "src/renderer/src/components/terminal-pane/pty-connection.test.ts", + "src/renderer/src/components/terminal-pane/pty-transport.test.ts", + "src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts", + "src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts", + "src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts", + "src/renderer/src/store/slices/store-cascades.test.ts", + "src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts", + "src/shared/agent-process-recognition.test.ts", + "src/shared/process-table-snapshot.test.ts", + "tests/e2e/terminal-foreground-confirmation.unit.test.ts", + "tests/e2e/terminal-shortcuts.spec.ts" + ], + "assertionRefs": [ + { + "file": "src/shared/process-table-snapshot.test.ts", + "assertions": [ + "a fresh request bypasses a same-tick TTL cache and any scan already in flight before the request", + "same-turn fresh requests and ordinary cache misses share one later scan while requests arriving after it starts queue behind it" + ] + }, + { + "file": "src/main/providers/agent-foreground-process.test.ts", + "assertions": [ + "successful root-present Windows enumeration and failed, blank, malformed, or root-missing enumeration remain distinct evidence states", + "an observed shell root with no children is authoritative while a snapshot omitting that root is unavailable", + "an attached Droid candidate is authorized only when exact ConPTY membership contains it, while a detached Start-Process descendant is rejected", + "a Windows process-table scan with no recognized agent performs zero ConPTY membership helper forks", + "fresh POSIX scan failure or a snapshot missing the PTY root is unavailable rather than shell proof", + "the compatibility process-name API still preserves its existing fallback contract for other consumers" + ] + }, + { + "file": "src/main/providers/windows-conpty-process-membership.test.ts", + "assertions": [ + "the fixed node-pty helper returns validated integer console membership containing the PTY root", + "root-only fallback, malformed/missing-root messages, spawn errors, and a silent helper timeout all fail closed", + "the bounded timeout kills the child helper exactly once" + ] + }, + { + "file": "src/main/providers/local-pty-provider.test.ts", + "assertions": [ + "a delayed foreground confirmation is discarded after the owning PTY exits" + ] + }, + { + "file": "src/main/daemon/daemon-pty-adapter.test.ts", + "assertions": [ + "new daemon sessions and warm reattach results carry the same minimal allowlisted launchAgent" + ] + }, + { + "file": "src/main/daemon/daemon-server.test.ts", + "assertions": [ + "daemon protocol v21 persists allowlisted launchAgent across reattach and drops unknown identity strings" + ] + }, + { + "file": "src/main/daemon/pty-subprocess.test.ts", + "assertions": [ + "Windows daemon foreground lookup can return PowerShell synchronously before async process-tree enrichment resolves the agent", + "the enriched agent result is served by a later foreground read", + "fresh confirmation awaits a post-request scan instead of serving cached PowerShell and returns null when inspection is unavailable" + ] + }, + { + "file": "tests/e2e/terminal-foreground-confirmation.unit.test.ts", + "assertions": [ + "the real daemon handle and pane tracker keep restored Droid identity when confirmation resolves after the old cache window", + "one fresh command-finish scan confirms real shell exit, while unavailable inspection performs exactly three bounded reads and never claims shell" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts", + "assertions": [ + "Windows defaults and non-Droid agents preserve Esc+CR while explicit Droid capability selects CSI-u", + "SSH, WSL, and remote Windows-client panes preserve Esc+CR without consulting the Droid capability", + "non-Windows Shift+Enter remains CSI-u and unrelated keys invoke neither agent nor ConPTY callbacks" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts", + "assertions": [ + "only routing-trusted current process identity overrides launch evidence and confirmed shell foreground clears stale identity", + "a newer untrusted or neutral command generation blocks stale launch ownership until confirmation", + "only allowlisted fresh process or pane-scoped launch ownership selects Droid's CSI-u capability", + "forged hook or OSC-derived Droid status cannot change the Windows byte encoding", + "after split and original-pane close, a sole surviving sibling cannot inherit the original pane's Droid launch identity" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts", + "assertions": [ + "manual and restored local agent identity is published from bounded foreground-process reads", + "a delayed read cannot publish after the pane rebinds to a replacement PTY id", + "every new command publishes a routing-neutral generation before confirmation", + "typed agent text only widens the confirmation window and never becomes published or routable identity", + "unavailable typed-command confirmation stays on legacy routing through the three-read ladder and then fails closed", + "ordinary fast OSC 133;C-to-D command pairs publish shell without a fresh confirmation scan", + "command-start and visible launch recovery use at most three reads across the bounded 350 ms, 1.2 s, and 6 s ladder", + "null and rejected reads participate in the same bounded known-identity ladder", + "command-finished accepts one fresh recognized shell scan when agent evidence exists, while unavailable final evidence retires routing without claiming shell" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/pty-connection.test.ts", + "assertions": [ + "after detach remount, pane-key launch/process identity forces a leaked nested OSC 133;D through foreground confirmation", + "a still-running Droid process republishes Droid instead of being overwritten with shell-foreground evidence", + "typing droid does not route CSI-u until fresh process evidence confirms Droid", + "null and rejected command-start reads never promote typed Droid text to process evidence", + "typed Droid input cannot replace live Antigravity process or pane-scoped launch identity inside another TUI", + "typed Droid input on SSH or remote-runtime panes never writes local process evidence", + "Droid routing survives a fresh command-finish scan that still sees Droid and retires after one fresh shell result", + "a D-to-C transition immediately routes legacy bytes while the new command generation is pending", + "an identityless visible-read versus OSC 133;D race cancels stale sampling and fails closed to shell", + "a manually typed Droid in a shell without OSC 133 gains routing only after accepted-input fresh confirmation", + "accepted no-OSC exit or interrupt input immediately revokes trusted Droid bytes and confirms the returned shell", + "unavailable command-finish evidence resolves deferred cleanup, returns legacy routing, and does not assert shell foreground", + "daemon-returned allowlisted launchAgent requests warm-reattach confirmation without restoring stale byte authority or the original args/env payload, while missing identity fails closed", + "an unknown persisted wrapper cannot spoof launch identity and confirmed shell state prevents repeat focus scans" + ] + }, + { + "file": "src/renderer/src/components/terminal-pane/pty-transport.test.ts", + "assertions": [ + "allowlisted daemon launchAgent reaches PtyConnectResult on reattach", + "unknown launch identity is dropped at the renderer transport boundary" + ] + }, + { + "file": "src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts", + "assertions": [ + "pane-to-tab detach moves only the detached leaf's launch and process identity to its new pane key", + "pane-to-tab detach preserves the source PTY shell override across native PowerShell and WSL classifications", + "the source hook snapshot is retired rather than copied to a key the running PTY cannot emit", + "the detached Droid keeps CSI-u while the source sibling keeps its own legacy encoding" + ] + }, + { + "file": "src/shared/agent-process-recognition.test.ts", + "assertions": [ + "Droid's process name resolves to the allowlisted Droid agent identity without substring matching" + ] + }, + { + "file": "tests/e2e/terminal-shortcuts.spec.ts", + "assertions": [ + "on Windows the focused terminal sends CSI-u bytes for a Droid pane and Esc+CR bytes after switching that same pane to Antigravity identity", + "the byte oracle observes the real renderer-to-main PTY write path rather than terminal DOM state" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-07-10", + "runner": "local", + "platform": "macos", + "command": "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/daemon-foreground-confirmation-protocol.test.ts src/main/daemon/daemon-pty-adapter.test.ts src/main/daemon/daemon-pty-router.test.ts src/main/daemon/daemon-server.test.ts src/main/daemon/degraded-daemon-pty-provider.test.ts src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts src/main/daemon/pty-subprocess.test.ts src/main/ipc/pty.test.ts src/main/providers/agent-foreground-process.test.ts src/main/providers/local-pty-provider.test.ts src/main/providers/windows-conpty-process-membership.test.ts src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts src/renderer/src/components/terminal-pane/pty-transport.test.ts src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts src/renderer/src/store/slices/store-cascades.test.ts src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts src/shared/agent-process-recognition.test.ts src/shared/process-table-snapshot.test.ts tests/e2e/terminal-foreground-confirmation.unit.test.ts", + "result": "passed", + "durationSeconds": 8.71, + "summary": "Twenty-two focused test files passed (1206 tests) on current main, covering fresh-scan ordering/deduplication, exact ConPTY membership and detached-child rejection, stale PTY guards, daemon v21 launch ownership with current-process confirmation, no-OSC command/exit recovery, preserved detach shell classification, unavailable evidence, routing-neutral command generations, exact shortcut bytes, and the composed daemon-plus-tracker contract; the Windows Electron byte test remains platform-gated and is not counted as local macOS evidence." + } + ], + "runtimeBudget": { + "p95Seconds": 90, + "scope": "focused renderer units plus the Windows Electron terminal-shortcut spec" + }, + "flakeHistory": { + "status": "unknown", + "evidence": "The deterministic units are stable locally; the Windows-only Electron byte path needs CI or nightly soak history before promotion." + }, + "redGreenEvidence": { + "status": "partial", + "evidence": "Reverting to the previous unconditional Windows Esc+CR branch fails the Droid byte assertion, while resolving launch metadata from any key other than the active pane fails the split-survivor isolation assertion. Saved intentional-break artifacts and live Windows history are still missing." + }, + "performanceBudget": { + "required": true, + "evidence": "Callback-count tests prove unrelated ordinary keys invoke neither ConPTY nor agent resolution. Windows Shift+Enter performs two store reads: one local-ConPTY classification with an O(tabs-in-worktree) tab lookup, then two pane-keyed O(1) ownership lookups. Typed text performs no routing write. Ordinary fast OSC 133;C-to-D shell commands perform no fresh confirmation RPC or process scan. An accepted submit/interrupt while trusted Droid is current, a typed allowlisted agent command, title exit, focus, visibility transition, or an idle burst after trusted Droid Shift+Enter can schedule the bounded confirmation ladder; each event cancels/deduplicates prior work and no timer recurs after settling. Windows confirmation performs one fresh process-table scan and forks exact ConPTY membership only after a recognized agent candidate appears; no recognized candidate makes zero helper calls. Same-turn fresh requests share one scan and later arrivals queue at most one successor. Recovery remains three bounded one-shot reads (350 ms, 1.2 s, 6 s). No polling loop, provider fanout, persistent listener, hidden-pane wake loop, or per-printable-key work is added." + }, + "promotionCriteria": [ + "Run the exact PTY-byte Electron oracle on Windows without silent platform skips.", + "Collect stable runtime and flake history for local and daemon Windows ConPTY while retaining deterministic unchanged-provider assertions for SSH, WSL, and remote runtime.", + "Attach saved intentional-break evidence for Droid capability removal and split-sibling identity leakage." + ], + "knownGaps": [ + "No Windows runner or live Linux PTY evidence is attached; the Electron byte test skips on macOS and Linux, while Linux behavior is covered only by deterministic POSIX unit paths.", + "Droid inside SSH, WSL, or remote-runtime intentionally keeps the pre-existing Windows-client Esc+CR behavior because local foreground confirmation is unavailable; this PR narrows the exception to issue #7620's local ConPTY surface.", + "The Electron test injects allowlisted pane identity rather than launching the real Droid and Antigravity binaries.", + "If both Windows process-enumeration backends remain unavailable through the bounded ladder, routing fails closed to the legacy Esc+CR path; no live Droid artifact covers that degraded host configuration.", + "Protocol v21 restarts older daemons because the minimal persisted launchAgent is a new contract; sessions preserved by pre-v21 daemons cannot supply warm-reattach launch ownership and fail closed until current process confirmation or restart.", + "No live daemon, SSH, WSL, remote-runtime, paired-web, or restore/replay byte artifact has been collected.", + "A running PTY keeps its spawn-time ORCA_PANE_KEY after pane-to-tab detach. This change transfers launch/process routing evidence and retires the stale hook snapshot, but does not redesign future hook reattribution across tab IDs." + ], + "demotionRule": "Keep non-blocking or demote to protection none if the Windows byte test silently skips, flakes without an actionable artifact, routes bytes using tab/title/terminal-output heuristics, or adds any ordinary-key lookup, IPC, polling, scan, or lifecycle leak." + }, { "id": "terminal-input.agent-prompt-injection", "title": "Orchestration agent prompts arrive as bracketed paste before submit", diff --git a/src/main/daemon/daemon-errors.ts b/src/main/daemon/daemon-errors.ts index 99d19818a3cf..8077add319af 100644 --- a/src/main/daemon/daemon-errors.ts +++ b/src/main/daemon/daemon-errors.ts @@ -1,6 +1,5 @@ // Error classes shared across the daemon protocol boundary (client, server, // host). Split from types.ts, which is capped for wire-shape declarations. - export class TerminalAttachCanceledError extends Error { constructor(sessionId: string) { super(`Attach canceled for session ${sessionId}`) diff --git a/src/main/daemon/daemon-foreground-confirmation-protocol.test.ts b/src/main/daemon/daemon-foreground-confirmation-protocol.test.ts new file mode 100644 index 000000000000..4fbb3047d6ab --- /dev/null +++ b/src/main/daemon/daemon-foreground-confirmation-protocol.test.ts @@ -0,0 +1,9 @@ +import { describe, expect, it } from 'vitest' +import { PREVIOUS_DAEMON_PROTOCOL_VERSIONS, PROTOCOL_VERSION } from './types' + +describe('foreground-confirmation daemon protocol', () => { + it('rejects daemons from before the fresh-confirmation RPC', () => { + expect(PROTOCOL_VERSION).toBeGreaterThan(19) + expect(PREVIOUS_DAEMON_PROTOCOL_VERSIONS).toContain(19) + }) +}) diff --git a/src/main/daemon/daemon-foreground-process-protocol.ts b/src/main/daemon/daemon-foreground-process-protocol.ts new file mode 100644 index 000000000000..01b050c58d32 --- /dev/null +++ b/src/main/daemon/daemon-foreground-process-protocol.ts @@ -0,0 +1,11 @@ +export type GetForegroundProcessRequest = { + id: string + type: 'getForegroundProcess' + payload: { + sessionId: string + } +} + +export type ConfirmForegroundProcessRequest = Omit & { + type: 'confirmForegroundProcess' +} diff --git a/src/main/daemon/daemon-pty-adapter.test.ts b/src/main/daemon/daemon-pty-adapter.test.ts index 310ea2aa9550..06a77789f4b3 100644 --- a/src/main/daemon/daemon-pty-adapter.test.ts +++ b/src/main/daemon/daemon-pty-adapter.test.ts @@ -489,9 +489,10 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { describe('spawn with sessionId (reattach)', () => { it('returns full snapshot and isReattach when reattaching', async () => { const sessionId = 'reattach-test-session' - const first = await adapter.spawn({ cols: 80, rows: 24, sessionId }) + const first = await adapter.spawn({ cols: 80, rows: 24, sessionId, launchAgent: 'droid' }) expect(first.id).toBe(sessionId) expect(first.isReattach).toBeUndefined() + expect(first.launchAgent).toBe('droid') // Write data so the headless emulator captures it lastSubprocess._simulateData('hello from shell\r\n') @@ -501,6 +502,7 @@ describe('DaemonPtyAdapter (IPtyProvider)', () => { const second = await adapter.spawn({ cols: 80, rows: 24, sessionId }) expect(second.id).toBe(sessionId) expect(second.isReattach).toBe(true) + expect(second.launchAgent).toBe('droid') expect(second.snapshot).toBeDefined() expect(second.snapshot).toContain('hello from shell') }) diff --git a/src/main/daemon/daemon-pty-adapter.ts b/src/main/daemon/daemon-pty-adapter.ts index 3535b4104045..e0d5ec598ca5 100644 --- a/src/main/daemon/daemon-pty-adapter.ts +++ b/src/main/daemon/daemon-pty-adapter.ts @@ -237,6 +237,7 @@ export class DaemonPtyAdapter implements IPtyProvider { envToDelete: opts.envToDelete, command: opts.command, startupCommandDelivery: opts.startupCommandDelivery, + launchAgent: opts.launchAgent, // Why: without this, the daemon always spawns cmd.exe (COMSPEC) or // PowerShell as a fallback — regardless of which shell the renderer // asked for in the "+" menu or persisted as the default. Forwarding @@ -252,6 +253,8 @@ export class DaemonPtyAdapter implements IPtyProvider { let scrollback = restoreInfo ? getRecoveredHistorySeed(restoreInfo) : null let result = await createOrAttach(scrollback) + const launchIdentity = (): { launchAgent?: NonNullable } => + result.launchAgent ? { launchAgent: result.launchAgent } : {} if (effectiveCwd) { this.initialCwds.set(sessionId, effectiveCwd) @@ -278,6 +281,7 @@ export class DaemonPtyAdapter implements IPtyProvider { return { id: sessionId, pid, + ...launchIdentity(), coldRestore: cachedRestore, ...(!result.isNew ? { isReattach: true } : {}) } @@ -342,11 +346,12 @@ export class DaemonPtyAdapter implements IPtyProvider { return { id: sessionId, pid, + ...launchIdentity(), coldRestore, ...(!result.isNew ? { isReattach: true } : {}) } } - return { id: sessionId, pid } + return { id: sessionId, pid, ...launchIdentity() } } if (this.historyManager && result.isNew) { @@ -380,7 +385,12 @@ export class DaemonPtyAdapter implements IPtyProvider { const isReattach = !result.isNew if (!isReattach || !result.snapshot) { - return { id: sessionId, pid, ...(isReattach ? { isReattach: true } : {}) } + return { + id: sessionId, + pid, + ...launchIdentity(), + ...(isReattach ? { isReattach: true } : {}) + } } const isAltScreen = result.snapshot.modes.alternateScreen @@ -396,6 +406,7 @@ export class DaemonPtyAdapter implements IPtyProvider { return { id: sessionId, pid, + ...launchIdentity(), snapshot: snapshotPayload, snapshotCols: result.snapshot.cols, snapshotRows: result.snapshot.rows, @@ -658,6 +669,18 @@ export class DaemonPtyAdapter implements IPtyProvider { } } + async confirmForegroundProcess(id: string): Promise { + try { + const result = await this.client.request<{ foregroundProcess: string | null }>( + 'confirmForegroundProcess', + { sessionId: id } + ) + return result.foregroundProcess + } catch { + return null + } + } + async serialize(ids: string[]): Promise { const sessions: Record = {} for (const id of ids) { diff --git a/src/main/daemon/daemon-pty-router.test.ts b/src/main/daemon/daemon-pty-router.test.ts index a8c2b2232d8f..eb8acb86488f 100644 --- a/src/main/daemon/daemon-pty-router.test.ts +++ b/src/main/daemon/daemon-pty-router.test.ts @@ -63,6 +63,7 @@ function createAdapter( acknowledgeDataEvent: vi.fn(), hasChildProcesses: vi.fn(async () => false), getForegroundProcess: vi.fn(async () => null), + confirmForegroundProcess: vi.fn(async () => `${label}-confirmed`), serialize: vi.fn(async () => '{}'), revive: vi.fn(async () => {}), getDefaultShell: vi.fn(async () => '/bin/zsh'), @@ -121,6 +122,22 @@ function createAdapter( } describe('DaemonPtyRouter', () => { + it('routes fresh foreground confirmation to the session-owning daemon', async () => { + const current = createAdapter('current', ['current-session']) + const legacy = createAdapter('legacy', ['legacy-session']) + const router = new DaemonPtyRouter({ current, legacy: [legacy] }) + await router.discoverLegacySessions() + + await expect(router.confirmForegroundProcess('legacy-session')).resolves.toBe( + 'legacy-confirmed' + ) + await expect(router.confirmForegroundProcess('current-session')).resolves.toBe( + 'current-confirmed' + ) + expect(legacy.confirmForegroundProcess).toHaveBeenCalledWith('legacy-session') + expect(current.confirmForegroundProcess).toHaveBeenCalledWith('current-session') + }) + it('routes existing legacy sessions to their old daemon and new sessions to current daemon', async () => { const current = createAdapter('current') const legacy = createAdapter('legacy', ['legacy-session']) diff --git a/src/main/daemon/daemon-pty-router.ts b/src/main/daemon/daemon-pty-router.ts index ed43c6633257..18bf0f926b59 100644 --- a/src/main/daemon/daemon-pty-router.ts +++ b/src/main/daemon/daemon-pty-router.ts @@ -146,6 +146,10 @@ export class DaemonPtyRouter implements IPtyProvider { return this.adapterFor(id).getForegroundProcess(id) } + async confirmForegroundProcess(id: string): Promise { + return this.adapterFor(id).confirmForegroundProcess(id) + } + async serialize(ids: string[]): Promise { return this.current.serialize(ids) } diff --git a/src/main/daemon/daemon-server.test.ts b/src/main/daemon/daemon-server.test.ts index 7de928d75434..3760ee89de29 100644 --- a/src/main/daemon/daemon-server.test.ts +++ b/src/main/daemon/daemon-server.test.ts @@ -10,6 +10,8 @@ import { PROTOCOL_VERSION, type DaemonRequest } from './types' import type { SubprocessHandle } from './session' import { getDaemonSocketPath } from './daemon-spawner' +const confirmForegroundProcessMock = vi.fn(async () => 'droid') + function createTestDir(): string { return mkdtempSync(join(tmpdir(), 'daemon-server-test-')) } @@ -23,6 +25,7 @@ function createMockSubprocess(): SubprocessHandle & { return { pid: 55555, getForegroundProcess: vi.fn(() => null), + confirmForegroundProcess: confirmForegroundProcessMock, write: vi.fn(), resize: vi.fn(), kill: vi.fn(() => setTimeout(() => onExitCb?.(0), 5)), @@ -65,6 +68,7 @@ describe('DaemonServer', () => { let client: DaemonClient beforeEach(() => { + confirmForegroundProcessMock.mockClear() dir = createTestDir() socketPath = getDaemonSocketPath(dir) tokenPath = join(dir, 'test.token') @@ -174,6 +178,34 @@ describe('DaemonServer', () => { }) }) + it('persists only an allowlisted launch identity across reattach', async () => { + await startServer() + const c = await connectClient() + + const first = await c.request('createOrAttach', { + sessionId: 'agent-session', + cols: 80, + rows: 24, + launchAgent: 'droid' + }) + expect(first).toMatchObject({ isNew: true, launchAgent: 'droid' }) + + const second = await c.request('createOrAttach', { + sessionId: 'agent-session', + cols: 80, + rows: 24 + }) + expect(second).toMatchObject({ isNew: false, launchAgent: 'droid' }) + + const unknown = await c.request('createOrAttach', { + sessionId: 'unknown-agent-session', + cols: 80, + rows: 24, + launchAgent: 'not-an-agent' + } as never) + expect(unknown).not.toHaveProperty('launchAgent') + }) + it('handles listSessions', async () => { await startServer() const c = await connectClient() @@ -279,6 +311,19 @@ describe('DaemonServer', () => { expect(result.cwd === null || typeof result.cwd === 'string').toBe(true) }) + it('awaits fresh foreground confirmation', async () => { + await startServer() + const c = await connectClient() + await c.request('createOrAttach', { sessionId: 'test-session', cols: 80, rows: 24 }) + + await expect( + c.request<{ foregroundProcess: string | null }>('confirmForegroundProcess', { + sessionId: 'test-session' + }) + ).resolves.toEqual({ foregroundProcess: 'droid' }) + expect(confirmForegroundProcessMock).toHaveBeenCalledTimes(1) + }) + it('returns error for unknown session operations', async () => { await startServer() const c = await connectClient() diff --git a/src/main/daemon/daemon-server.ts b/src/main/daemon/daemon-server.ts index 7c604341c2cf..fe87022e5c51 100644 --- a/src/main/daemon/daemon-server.ts +++ b/src/main/daemon/daemon-server.ts @@ -22,6 +22,7 @@ import { readCurrentProcessMacSystemResolverHealth } from '../network/macos-syst import type { SubprocessHandle } from './session' import { checkPtySpawnHealth } from './pty-subprocess' import { createNoopDaemonFileLog, type DaemonFileLog } from './daemon-file-log' +import { isTuiAgent } from '../../shared/tui-agent-config' import { PROTOCOL_VERSION, NOTIFY_PREFIX, @@ -341,6 +342,9 @@ export class DaemonServer { envToDelete: p.envToDelete, command: p.command, startupCommandDelivery: p.startupCommandDelivery, + // Why: daemon RPC payloads are untrusted JSON. Persist only the + // allowlisted enum used for byte routing, never arbitrary identity. + ...(isTuiAgent(p.launchAgent) ? { launchAgent: p.launchAgent } : {}), shellOverride: p.shellOverride, terminalWindowsWslDistro: p.terminalWindowsWslDistro, terminalWindowsPowerShellImplementation: p.terminalWindowsPowerShellImplementation, @@ -406,6 +410,7 @@ export class DaemonServer { snapshot: result.snapshot, pid: result.pid, shellState: result.shellState, + ...(result.launchAgent ? { launchAgent: result.launchAgent } : {}), ...(result.historySeeded !== undefined ? { historySeeded: result.historySeeded } : {}) } } @@ -512,6 +517,11 @@ export class DaemonServer { case 'getForegroundProcess': return { foregroundProcess: this.host.getForegroundProcess(request.payload.sessionId) } + case 'confirmForegroundProcess': + return { + foregroundProcess: await this.host.confirmForegroundProcess(request.payload.sessionId) + } + case 'clearScrollback': this.host.clearScrollback(request.payload.sessionId) return {} diff --git a/src/main/daemon/degraded-daemon-pty-provider.test.ts b/src/main/daemon/degraded-daemon-pty-provider.test.ts index fb0b5087f153..188173816db0 100644 --- a/src/main/daemon/degraded-daemon-pty-provider.test.ts +++ b/src/main/daemon/degraded-daemon-pty-provider.test.ts @@ -37,6 +37,7 @@ function createProvider(label: string, sessions: string[] = []): ProviderMock { acknowledgeDataEvent: vi.fn(), hasChildProcesses: vi.fn(async () => false), getForegroundProcess: vi.fn(async () => null), + confirmForegroundProcess: vi.fn(async () => `${label}-confirmed`), serialize: vi.fn(async () => '{}'), revive: vi.fn(async () => {}), listProcesses: vi.fn(async () => sessions.map((id) => ({ id, cwd: '', title: label }))), @@ -108,6 +109,19 @@ function createDaemonAdapter( } describe('DegradedDaemonPtyProvider', () => { + it('routes fresh foreground confirmation to the session owner', async () => { + const current = createDaemonAdapter('daemon', ['daemon-session']) + const fallback = createProvider('fallback') + const provider = new DegradedDaemonPtyProvider({ current, legacy: [], fallback }) + await provider.discoverDaemonSessions() + const fresh = await provider.spawn({ cols: 80, rows: 24 }) + + await expect(provider.confirmForegroundProcess('daemon-session')).resolves.toBe( + 'daemon-confirmed' + ) + await expect(provider.confirmForegroundProcess(fresh.id)).resolves.toBe('fallback-confirmed') + }) + it('routes discovered daemon sessions to the daemon and fresh PTYs to the fallback', async () => { const current = createDaemonAdapter('daemon', ['daemon-session']) const fallback = createProvider('fallback') diff --git a/src/main/daemon/degraded-daemon-pty-provider.ts b/src/main/daemon/degraded-daemon-pty-provider.ts index 4e818c9b6c0d..572cb0aca37f 100644 --- a/src/main/daemon/degraded-daemon-pty-provider.ts +++ b/src/main/daemon/degraded-daemon-pty-provider.ts @@ -160,6 +160,10 @@ export class DegradedDaemonPtyProvider implements IPtyProvider { return this.providerFor(id).getForegroundProcess(id) } + async confirmForegroundProcess(id: string): Promise { + return this.providerFor(id).confirmForegroundProcess?.(id) ?? null + } + async serialize(ids: string[]): Promise { return this.fallback.serialize(ids) } diff --git a/src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts b/src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts index b198f3e7475a..937dca27bc41 100644 --- a/src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts +++ b/src/main/daemon/pty-subprocess-foreground-scan-cadence.test.ts @@ -40,7 +40,10 @@ vi.mock('../providers/windows-powershell-executable', () => ({ })) vi.mock('../providers/agent-foreground-process', () => ({ - resolveAgentForegroundProcess: resolveAgentForegroundProcessMock + resolveAgentForegroundProcessWithAvailability: async (...args: unknown[]) => ({ + available: true, + processName: await resolveAgentForegroundProcessMock(...args) + }) })) import { createPtySubprocess } from './pty-subprocess' diff --git a/src/main/daemon/pty-subprocess.test.ts b/src/main/daemon/pty-subprocess.test.ts index 9ff69f89ab32..908ef9a68b27 100644 --- a/src/main/daemon/pty-subprocess.test.ts +++ b/src/main/daemon/pty-subprocess.test.ts @@ -56,7 +56,12 @@ vi.mock('../providers/local-pty-utils', async (importOriginal) => { }) vi.mock('../providers/agent-foreground-process', () => ({ - resolveAgentForegroundProcess: resolveAgentForegroundProcessMock + resolveAgentForegroundProcessWithAvailability: async (...args: unknown[]) => { + const value = await resolveAgentForegroundProcessMock(...args) + return value && typeof value === 'object' && 'available' in value + ? value + : { available: true, processName: value } + } })) import { createPtySubprocess, checkPtySpawnHealth } from './pty-subprocess' @@ -514,6 +519,111 @@ describe('createPtySubprocess', () => { } }) + it('preserves the ordinary fallback when Windows process enumeration is unavailable', async () => { + const proc = mockPtyProcess() + proc.process = 'powershell.exe' + spawnMock.mockReturnValue(proc) + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + resolveAgentForegroundProcessMock.mockResolvedValue({ + available: false, + processName: 'powershell.exe' + }) + + try { + const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) + + expect(handle.getForegroundProcess()).toBe('powershell.exe') + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + expect(handle.getForegroundProcess()).toBe('powershell.exe') + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + }) + + it('awaits a fresh delayed Windows scan instead of serving the shell fallback', async () => { + const proc = mockPtyProcess() + proc.process = 'powershell.exe' + spawnMock.mockReturnValue(proc) + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + let resolveFresh!: (processName: string) => void + resolveAgentForegroundProcessMock.mockReturnValue( + new Promise((resolve) => { + resolveFresh = resolve + }) + ) + + try { + const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) + const confirmation = handle.confirmForegroundProcess!() + let settled = false + void confirmation.then(() => { + settled = true + }) + await Promise.resolve() + expect(settled).toBe(false) + + resolveFresh('droid') + await expect(confirmation).resolves.toBe('droid') + expect(resolveAgentForegroundProcessMock).toHaveBeenCalledExactlyOnceWith( + proc.pid, + 'powershell.exe', + expect.objectContaining({ fresh: true, forceProcessScan: true }) + ) + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + }) + + it('returns null when a fresh Windows confirmation scan is unavailable', async () => { + const proc = mockPtyProcess() + proc.process = 'powershell.exe' + spawnMock.mockReturnValue(proc) + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + resolveAgentForegroundProcessMock.mockResolvedValue({ + available: false, + processName: 'powershell.exe' + }) + + try { + const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) + await expect(handle.confirmForegroundProcess!()).resolves.toBeNull() + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + }) + + it('returns null when a recognized Windows fallback disappears during confirmation', async () => { + const proc = mockPtyProcess() + proc.process = 'droid' + spawnMock.mockReturnValue(proc) + const platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + resolveAgentForegroundProcessMock.mockResolvedValue({ + available: true, + processName: null + }) + + try { + const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) + await expect(handle.confirmForegroundProcess!()).resolves.toBeNull() + } finally { + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + } + }) + it('serves Unix agent foreground when node-pty reports an agent child process', async () => { const proc = mockPtyProcess() proc.process = 'uv' diff --git a/src/main/daemon/pty-subprocess.ts b/src/main/daemon/pty-subprocess.ts index 119b3fb9430a..5d36ebe9d693 100644 --- a/src/main/daemon/pty-subprocess.ts +++ b/src/main/daemon/pty-subprocess.ts @@ -41,7 +41,8 @@ import { } from '../pty/powerlevel10k-wizard-env' import { isWindowsGitBashShellPath, resolveWindowsGitBashShellPath } from '../git-bash' import { WINDOWS_GIT_BASH_SHELL } from '../../shared/windows-terminal-shell' -import { resolveAgentForegroundProcess } from '../providers/agent-foreground-process' +import { resolveAgentForegroundProcessWithAvailability } from '../providers/agent-foreground-process' +import { readWindowsConptyProcessIds } from '../providers/windows-conpty-process-membership' import { isAgentForegroundWrapperProcess, recognizeAgentProcess, @@ -940,10 +941,10 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl // Why: daemon foreground reads are sync and run on the IPC hot path. // Refresh derived identities (shell/wrapper/helper -> codex/claude/etc.) // in the background and serve them from a short cache on later reads. - void resolveAgentForegroundProcess(proc.pid, fallbackProcess, { + void resolveAgentForegroundProcessWithAvailability(proc.pid, fallbackProcess, { contextPaths: agentForegroundContextPaths }) - .then((processName) => { + .then(({ processName }) => { if (dead) { return } @@ -1045,6 +1046,56 @@ export function createPtySubprocess(opts: PtySubprocessOptions): SubprocessHandl return null } }, + confirmForegroundProcess: async () => { + if (dead || !proc.pid) { + return null + } + try { + const fallbackProcess = getFallbackForegroundProcess() + if ( + !fallbackProcess || + (recognizeAgentProcess(fallbackProcess) && process.platform !== 'win32') || + (process.platform !== 'win32' && !shouldInspectFallbackForegroundProcess(fallbackProcess)) + ) { + return fallbackProcess + } + // Why: cached/in-flight scans may predate the OSC command boundary. + // Confirmation requires one shared process snapshot started afterward. + const resolution = await resolveAgentForegroundProcessWithAvailability( + proc.pid, + fallbackProcess, + { + contextPaths: agentForegroundContextPaths, + fresh: true, + ...(process.platform === 'win32' + ? { + forceProcessScan: true, + readWindowsConptyProcessIds: () => readWindowsConptyProcessIds(proc.pid) + } + : {}) + } + ) + if (dead || !resolution.available) { + return null + } + const recognized = recognizeAgentProcess(resolution.processName) + if (recognized) { + cachedAgentForeground = { + processName: recognized.processName, + refreshedAt: Date.now() + } + startupAgentForeground = null + return recognized.processName + } + // Why: a successful post-boundary scan that resolves no agent is the + // authority that retires stale cached/startup identity. + cachedAgentForeground = null + startupAgentForeground = null + return resolution.processName + } catch { + return null + } + }, write: (data) => { if (dead) { return diff --git a/src/main/daemon/session.ts b/src/main/daemon/session.ts index 80987b5a1bb1..06404fd92462 100644 --- a/src/main/daemon/session.ts +++ b/src/main/daemon/session.ts @@ -9,6 +9,7 @@ import { type ShellReadyScanState } from '../shell-ready-marker-scanner' import { isPowerShellProcess } from '../../shared/shell-process-detection' +import type { TuiAgent } from '../../shared/types' import type { PendingOutputRecord, SessionState, @@ -42,6 +43,8 @@ export type SubprocessHandle = { /** Live foreground process name of the PTY (node-pty's `.process`), e.g. * 'claude' / 'codex' / 'zsh'. Null once the child has exited. */ getForegroundProcess(): string | null + /** Await process-table evidence captured after this confirmation request. */ + confirmForegroundProcess?(): Promise /** True when shell launch args already delivered the startup command, so the * terminal host must skip its stdin fallback write. */ startupCommandDeliveredInShellArgs?: boolean @@ -72,6 +75,7 @@ export type SessionOptions = { cols: number rows: number terminalHandle?: string + launchAgent?: TuiAgent subprocess: SubprocessHandle shellReadySupported: boolean shellReadyTimeoutMs?: number @@ -94,6 +98,7 @@ type AttachedClient = { export class Session { readonly sessionId: string readonly terminalHandle: string | null + readonly launchAgent: TuiAgent | null private _state: SessionState = 'running' private _shellState: ShellReadyState private _exitCode: number | null = null @@ -120,6 +125,7 @@ export class Session { constructor(opts: SessionOptions) { this.sessionId = opts.sessionId this.terminalHandle = opts.terminalHandle ?? null + this.launchAgent = opts.launchAgent ?? null this.subprocess = opts.subprocess this.onSessionExit = opts.onExit const size = normalizePtySize(opts.cols, opts.rows) @@ -360,6 +366,10 @@ export class Session { return this.subprocess.getForegroundProcess() } + async confirmForegroundProcess(): Promise { + return this.subprocess.confirmForegroundProcess?.() ?? this.subprocess.getForegroundProcess() + } + clearScrollback(): void { if (this._disposed) { return diff --git a/src/main/daemon/terminal-host-create-contract.ts b/src/main/daemon/terminal-host-create-contract.ts new file mode 100644 index 000000000000..a60570ac5fe8 --- /dev/null +++ b/src/main/daemon/terminal-host-create-contract.ts @@ -0,0 +1,33 @@ +import type { StartupCommandDelivery } from '../../shared/codex-startup-delivery' +import type { TuiAgent } from '../../shared/types' +import type { ShellReadyState, TerminalSnapshot } from './types' + +export type CreateOrAttachOptions = { + sessionId: string + cols: number + rows: number + cwd?: string + env?: Record + envToDelete?: string[] + command?: string + startupCommandDelivery?: StartupCommandDelivery + launchAgent?: TuiAgent + /** Explicit shell the renderer asked for, forwarded to the subprocess. */ + shellOverride?: string + terminalWindowsWslDistro?: string | null + terminalWindowsPowerShellImplementation?: 'auto' | 'powershell.exe' | 'pwsh.exe' + shellReadySupported?: boolean + shellReadyTimeoutMs?: number + historySeed?: string + streamClient: { onData: (data: string) => void; onExit: (code: number) => void } +} + +export type CreateOrAttachResult = { + isNew: boolean + snapshot: TerminalSnapshot | null + pid: number | null + shellState: ShellReadyState + historySeeded?: boolean + launchAgent?: TuiAgent + attachToken: symbol +} diff --git a/src/main/daemon/terminal-host.ts b/src/main/daemon/terminal-host.ts index 644356a6c4f3..203719d354e2 100644 --- a/src/main/daemon/terminal-host.ts +++ b/src/main/daemon/terminal-host.ts @@ -3,46 +3,13 @@ import { normalizePtySize } from './daemon-pty-size' import { resolveProcessCwd } from '../providers/process-cwd' import type { StartupCommandDelivery } from '../../shared/codex-startup-delivery' import { buildStartupCommandSubmission } from '../../shared/startup-command-submission' -import type { - SessionInfo, - TakePendingOutputResult, - TerminalSnapshot, - ShellReadyState -} from './types' +import type { SessionInfo, TakePendingOutputResult, TerminalSnapshot } from './types' import { SessionNotFoundError } from './types' +import type { CreateOrAttachOptions, CreateOrAttachResult } from './terminal-host-create-contract' -const DEFAULT_MAX_TOMBSTONES = 1000 - -export type CreateOrAttachOptions = { - sessionId: string - cols: number - rows: number - cwd?: string - env?: Record - envToDelete?: string[] - command?: string - startupCommandDelivery?: StartupCommandDelivery - /** Explicit shell the renderer asked for (e.g. 'wsl.exe' for "New WSL - * terminal" from the "+" menu). Forwarded to the subprocess spawner so the - * daemon path honors per-tab shell selection the same way LocalPtyProvider - * does. */ - shellOverride?: string - terminalWindowsWslDistro?: string | null - terminalWindowsPowerShellImplementation?: 'auto' | 'powershell.exe' | 'pwsh.exe' - shellReadySupported?: boolean - shellReadyTimeoutMs?: number - historySeed?: string - streamClient: { onData: (data: string) => void; onExit: (code: number) => void } -} +export type { CreateOrAttachOptions, CreateOrAttachResult } from './terminal-host-create-contract' -export type CreateOrAttachResult = { - isNew: boolean - snapshot: TerminalSnapshot | null - pid: number | null - shellState: ShellReadyState - historySeeded?: boolean - attachToken: symbol -} +const DEFAULT_MAX_TOMBSTONES = 1000 export type TerminalHostOptions = { spawnSubprocess: (opts: { @@ -107,6 +74,7 @@ export class TerminalHost { snapshot, pid: existing.pid, shellState: existing.shellState, + ...(existing.launchAgent ? { launchAgent: existing.launchAgent } : {}), ...(existing.historySeeded !== undefined ? { historySeeded: existing.historySeeded } : {}), attachToken: token } @@ -141,6 +109,7 @@ export class TerminalHost { cols: size.cols, rows: size.rows, terminalHandle: opts.env?.ORCA_TERMINAL_HANDLE, + launchAgent: opts.launchAgent, subprocess, shellReadySupported: opts.shellReadySupported ?? false, historySeed: opts.historySeed, @@ -184,6 +153,7 @@ export class TerminalHost { snapshot: null, pid: subprocess.pid, shellState: session.shellState, + ...(session.launchAgent ? { launchAgent: session.launchAgent } : {}), ...(session.historySeeded !== undefined ? { historySeeded: session.historySeeded } : {}), attachToken: token } @@ -274,6 +244,14 @@ export class TerminalHost { return session.getForegroundProcess() } + async confirmForegroundProcess(sessionId: string): Promise { + const session = this.sessions.get(sessionId) + if (!session || !session.isAlive) { + return null + } + return session.confirmForegroundProcess() + } + clearScrollback(sessionId: string): void { this.getAliveSession(sessionId).clearScrollback() } diff --git a/src/main/daemon/types.ts b/src/main/daemon/types.ts index 663166e6fca9..550b211aa748 100644 --- a/src/main/daemon/types.ts +++ b/src/main/daemon/types.ts @@ -1,15 +1,24 @@ import type { TerminalOscLinkRange } from '../../shared/terminal-osc-link-ranges' +import type { + ConfirmForegroundProcessRequest, + GetForegroundProcessRequest +} from './daemon-foreground-process-protocol' + +export type { + ConfirmForegroundProcessRequest, + GetForegroundProcessRequest +} from './daemon-foreground-process-protocol' // ─── Protocol Version ──────────────────────────────────────────────── import type { StartupCommandDelivery } from '../../shared/codex-startup-delivery' - +import type { TuiAgent } from '../../shared/types' // Why: daemons can survive app updates. Bump for IPC wire-shape changes, or // when daemon-baked behavior cannot be delivered by on-disk wrapper refresh. // Why: bump when adding daemon wire behavior so same-version old daemons do // not silently accept the handshake and then reject new RPCs. -export const PROTOCOL_VERSION = 20 +export const PROTOCOL_VERSION = 21 export const PREVIOUS_DAEMON_PROTOCOL_VERSIONS = [ - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ] as const // ─── Session State Machine ────────────────────────────────────────── @@ -98,6 +107,7 @@ export type CreateOrAttachRequest = { envToDelete?: string[] command?: string startupCommandDelivery?: StartupCommandDelivery + launchAgent?: TuiAgent /** Explicit Windows shell override selected by the user (e.g. 'wsl.exe'). * The daemon forwards this to its subprocess spawner so each tab honors * the shell picked in the "+" menu or the persisted default-shell setting, @@ -216,14 +226,6 @@ export type GetCwdRequest = { } } -export type GetForegroundProcessRequest = { - id: string - type: 'getForegroundProcess' - payload: { - sessionId: string - } -} - export type ClearScrollbackRequest = { id: string type: 'clearScrollback' @@ -330,6 +332,7 @@ export type DaemonRequest = | DetachRequest | GetCwdRequest | GetForegroundProcessRequest + | ConfirmForegroundProcessRequest | ClearScrollbackRequest | ShutdownRequest | PingRequest @@ -361,8 +364,8 @@ export type CreateOrAttachResult = { pid: number | null shellState: ShellReadyState historySeeded?: boolean + launchAgent?: TuiAgent } - export type GetSnapshotResult = { snapshot: TerminalSnapshot | null } diff --git a/src/main/ipc/pty.test.ts b/src/main/ipc/pty.test.ts index 66a0c1c07507..2b405685c455 100644 --- a/src/main/ipc/pty.test.ts +++ b/src/main/ipc/pty.test.ts @@ -555,6 +555,7 @@ describe('registerPtyHandlers', () => { acknowledgeDataEvent: vi.fn(), hasChildProcesses: vi.fn(), getForegroundProcess: vi.fn(), + confirmForegroundProcess: vi.fn(), serialize: vi.fn(), revive: vi.fn(), onData: vi.fn(() => () => {}), @@ -596,6 +597,7 @@ describe('registerPtyHandlers', () => { acknowledgeDataEvent: vi.fn(), hasChildProcesses: vi.fn(), getForegroundProcess: vi.fn(), + confirmForegroundProcess: vi.fn(), serialize: vi.fn(), revive: vi.fn(), onData: vi.fn((handler: (payload: { id: string; data: string }) => void) => { @@ -3973,6 +3975,7 @@ describe('registerPtyHandlers', () => { listProcesses: vi.fn(), hasChildProcesses: vi.fn(), getForegroundProcess: vi.fn(), + confirmForegroundProcess: vi.fn(), serialize: vi.fn(), revive: vi.fn(), getDefaultShell: vi.fn(), @@ -4034,6 +4037,7 @@ describe('registerPtyHandlers', () => { listProcesses: vi.fn(), hasChildProcesses: vi.fn(), getForegroundProcess: vi.fn(), + confirmForegroundProcess: vi.fn(), serialize: vi.fn(), revive: vi.fn(), getDefaultShell: vi.fn(), @@ -4050,8 +4054,12 @@ describe('registerPtyHandlers', () => { await expect( handlers.get('pty:getForegroundProcess')!(null, { id: 'remote-pty' }) ).resolves.toBeNull() + await expect( + handlers.get('pty:confirmForegroundProcess')!(null, { id: 'remote-pty' }) + ).resolves.toBeNull() expect(provider.hasChildProcesses).not.toHaveBeenCalled() expect(provider.getForegroundProcess).not.toHaveBeenCalled() + expect(provider.confirmForegroundProcess).not.toHaveBeenCalled() }) // Why: regression for the Claude-Code split-pane garbled-render desync. resize diff --git a/src/main/ipc/pty.ts b/src/main/ipc/pty.ts index 0ca456f76072..893a65e4c659 100644 --- a/src/main/ipc/pty.ts +++ b/src/main/ipc/pty.ts @@ -34,6 +34,7 @@ import { redactPtyIdForDiagnostics } from '../../shared/pty-delivery-diagnostics' import { recordCrashBreadcrumb } from '../crash-reporting/crash-breadcrumb-store' +import { isTuiAgent } from '../../shared/tui-agent-config' import type { SleepingAgentLaunchConfig } from '../../shared/agent-session-resume' import type { ProjectExecutionRuntimeResolution } from '../../shared/project-execution-runtime' import { @@ -1480,6 +1481,7 @@ export function registerPtyHandlers( ipcMain.removeHandler('pty:hasPty') ipcMain.removeHandler('pty:hasChildProcesses') ipcMain.removeHandler('pty:getForegroundProcess') + ipcMain.removeHandler('pty:confirmForegroundProcess') ipcMain.removeHandler('pty:getCwd') ipcMain.removeHandler('pty:getSize') ipcMain.removeHandler('pty:declarePendingPaneSerializer') @@ -3916,6 +3918,9 @@ export function registerPtyHandlers( if (args.startupCommandDelivery !== undefined) { spawnOptions.startupCommandDelivery = args.startupCommandDelivery } + if (isTuiAgent(args.launchAgent)) { + spawnOptions.launchAgent = args.launchAgent + } if (args.worktreeId !== undefined) { spawnOptions.worktreeId = args.worktreeId } @@ -4957,6 +4962,19 @@ export function registerPtyHandlers( } ) + ipcMain.handle( + 'pty:confirmForegroundProcess', + async (_event, args: { id: string }): Promise => { + if (!hasPtyProviderForInspection(args.id)) { + return null + } + const provider = getProviderForPty(args.id) + // Why: falling back to the cached foreground API would turn stale + // process identity into shell/agent authority at a command boundary. + return provider.confirmForegroundProcess?.(args.id) ?? null + } + ) + // Why: renderer needs the live shell cwd when the user presses Cmd+D so // the new split pane inherits the source pane's cwd instead of the // worktree root. Routed through getProviderForPty so local and SSH PTYs diff --git a/src/main/providers/agent-foreground-process.test.ts b/src/main/providers/agent-foreground-process.test.ts index c21d501b49ae..a93735a0287e 100644 --- a/src/main/providers/agent-foreground-process.test.ts +++ b/src/main/providers/agent-foreground-process.test.ts @@ -9,7 +9,10 @@ vi.mock('child_process', () => ({ })) import { resetProcessTableSnapshotForTests } from '../../shared/process-table-snapshot' -import { resolveAgentForegroundProcess } from './agent-foreground-process' +import { + resolveAgentForegroundProcess, + resolveAgentForegroundProcessWithAvailability +} from './agent-foreground-process' import { resetWindowsProcessRowsSnapshotForTests } from './windows-foreground-process-rows' // Why: the module wraps execFile with promisify, so the mock must honor the @@ -106,6 +109,28 @@ describe('resolveAgentForegroundProcess', () => { await expect(resolveAgentForegroundProcess(100, 'node')).resolves.toBe('codex') }) + it('treats a fresh POSIX snapshot missing the PTY root as unavailable', async () => { + mockPs('101 999 S+ node /Users/dev/.nvm/versions/node/bin/codex') + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'zsh', { fresh: true }) + ).resolves.toEqual({ available: false, processName: 'zsh' }) + }) + + it('treats a failed fresh POSIX scan as unavailable', async () => { + execFileMock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + callback(new Error('ps unavailable'), { stdout: '', stderr: '' }) + } + ) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'zsh', { fresh: true }) + ).resolves.toEqual({ available: false, processName: 'zsh' }) + await expect(resolveAgentForegroundProcess(100, 'zsh')).resolves.toBe('zsh') + }) + it('does not report Claude print-mode hook descendants as foreground agents', async () => { mockPs( [ @@ -270,6 +295,117 @@ describe('resolveAgentForegroundProcess', () => { ) }) + it('distinguishes unavailable Windows enumeration from a confirmed shell', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + execFileMock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + callback(new Error('enumeration unavailable'), { stdout: '', stderr: '' }) + } + ) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe') + ).resolves.toEqual({ available: false, processName: 'powershell.exe' }) + await expect(resolveAgentForegroundProcess(100, 'powershell.exe')).resolves.toBe( + 'powershell.exe' + ) + }) + + it.each([ + ['blank', ' \r\n'], + ['unparseable', 'wmic returned no structured process values'] + ])('treats successful but %s WMIC output as unavailable', async (_label, wmicOutput) => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + execFileMock.mockImplementation((cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + if (cmd === 'powershell.exe') { + callback(new Error('powershell unavailable'), { stdout: '', stderr: '' }) + return + } + callback(null, { stdout: wmicOutput, stderr: '' }) + }) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe') + ).resolves.toEqual({ available: false, processName: 'powershell.exe' }) + await expect(resolveAgentForegroundProcess(100, 'powershell.exe')).resolves.toBe( + 'powershell.exe' + ) + }) + + it('treats an observed Windows shell with no children as authoritative', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + execFileMock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + callback(null, { + stdout: windowsProcessJsonRows([ + { + CommandLine: 'powershell.exe', + Name: 'powershell.exe', + ParentProcessId: 99, + ProcessId: 100 + } + ]), + stderr: '' + }) + } + ) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe') + ).resolves.toEqual({ available: true, processName: 'powershell.exe' }) + }) + + it('does not restore a recognized fallback that disappeared before confirmation', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + mockPs( + windowsProcessJsonRows([ + { + CommandLine: 'powershell.exe', + Name: 'powershell.exe', + ParentProcessId: 99, + ProcessId: 100 + } + ]) + ) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'droid', { + fresh: true, + forceProcessScan: true + }) + ).resolves.toEqual({ available: true, processName: null }) + }) + + it('treats a Windows snapshot missing the requested shell as unavailable', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + execFileMock.mockImplementation( + (_cmd: string, _args: string[], _opts: unknown, cb: unknown) => { + const callback = cb as (err: unknown, result: { stdout: string; stderr: string }) => void + callback(null, { + stdout: windowsProcessJsonRows([ + { + CommandLine: 'unrelated.exe', + Name: 'unrelated.exe', + ParentProcessId: 99, + ProcessId: 200 + } + ]), + stderr: '' + }) + } + ) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe') + ).resolves.toEqual({ available: false, processName: 'powershell.exe' }) + await expect(resolveAgentForegroundProcess(100, 'powershell.exe')).resolves.toBe( + 'powershell.exe' + ) + }) + it('does not use unrelated Windows agent descendants for wrapper fallbacks', async () => { Object.defineProperty(process, 'platform', { value: 'win32' }) execFileMock.mockImplementation( @@ -334,6 +470,39 @@ describe('resolveAgentForegroundProcess', () => { ) }) + it('filters detached agents before resolving an otherwise ambiguous ConPTY tree', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + mockPs( + windowsProcessJsonRows([ + { + CommandLine: 'powershell.exe', + Name: 'powershell.exe', + ParentProcessId: 99, + ProcessId: 100 + }, + { + CommandLine: 'droid', + Name: 'droid.exe', + ParentProcessId: 100, + ProcessId: 101 + }, + { + CommandLine: 'agy', + Name: 'agy.exe', + ParentProcessId: 100, + ProcessId: 102 + } + ]) + ) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe', { + fresh: true, + readWindowsConptyProcessIds: async () => new Set([100, 101]) + }) + ).resolves.toEqual({ available: true, processName: 'droid' }) + }) + it('recognizes a Windows shell-rooted agent when only one candidate matches the worktree path', async () => { Object.defineProperty(process, 'platform', { value: 'win32' }) execFileMock.mockImplementation( @@ -494,4 +663,83 @@ describe('resolveAgentForegroundProcess', () => { await expect(resolveAgentForegroundProcess(100, 'vim.exe')).resolves.toBe('vim.exe') expect(execFileMock).not.toHaveBeenCalled() }) + + it('authorizes a fresh Windows agent only when it still belongs to the ConPTY', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + mockPs( + windowsProcessJsonRows([ + { + CommandLine: 'powershell.exe', + Name: 'powershell.exe', + ParentProcessId: 99, + ProcessId: 100 + }, + { + CommandLine: 'droid', + Name: 'droid.exe', + ParentProcessId: 100, + ProcessId: 101 + } + ]) + ) + const readWindowsConptyProcessIds = vi.fn(async () => new Set([100, 101, 999])) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe', { + fresh: true, + readWindowsConptyProcessIds + }) + ).resolves.toEqual({ available: true, processName: 'droid' }) + expect(readWindowsConptyProcessIds).toHaveBeenCalledTimes(1) + }) + + it('excludes a detached Windows Droid descendant from byte authority', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + mockPs( + windowsProcessJsonRows([ + { + CommandLine: 'powershell.exe', + Name: 'powershell.exe', + ParentProcessId: 99, + ProcessId: 100 + }, + { + CommandLine: 'droid', + Name: 'droid.exe', + ParentProcessId: 100, + ProcessId: 101 + } + ]) + ) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe', { + fresh: true, + readWindowsConptyProcessIds: async () => new Set([100, 999]) + }) + ).resolves.toEqual({ available: true, processName: 'powershell.exe' }) + }) + + it('does not fork the ConPTY membership helper when no Windows agent is inferred', async () => { + Object.defineProperty(process, 'platform', { value: 'win32' }) + mockPs( + windowsProcessJsonRows([ + { + CommandLine: 'powershell.exe', + Name: 'powershell.exe', + ParentProcessId: 99, + ProcessId: 100 + } + ]) + ) + const readWindowsConptyProcessIds = vi.fn(async () => new Set([100, 999])) + + await expect( + resolveAgentForegroundProcessWithAvailability(100, 'powershell.exe', { + fresh: true, + readWindowsConptyProcessIds + }) + ).resolves.toEqual({ available: true, processName: 'powershell.exe' }) + expect(readWindowsConptyProcessIds).not.toHaveBeenCalled() + }) }) diff --git a/src/main/providers/agent-foreground-process.ts b/src/main/providers/agent-foreground-process.ts index d60582964bd9..6224b8049539 100644 --- a/src/main/providers/agent-foreground-process.ts +++ b/src/main/providers/agent-foreground-process.ts @@ -1,13 +1,22 @@ import { recognizeAgentProcessFromCommandLine } from '../../shared/agent-process-recognition' -import { getProcessTableSnapshot, type ProcessTableRow } from '../../shared/process-table-snapshot' import { - resolveWindowsAgentForegroundProcess, + getFreshProcessTableSnapshot, + getProcessTableSnapshot, + type ProcessTableRow +} from '../../shared/process-table-snapshot' +import { + resolveWindowsAgentForegroundProcessWithAvailability, shouldInspectWindowsAgentForeground, type AgentForegroundResolutionOptions } from './windows-agent-foreground-process' export type { AgentForegroundResolutionOptions } from './windows-agent-foreground-process' +export type AgentForegroundProcessResolution = { + available: boolean + processName: string | null +} + function collectDescendants( rows: Row[], rootPid: number @@ -43,29 +52,57 @@ export async function resolveAgentForegroundProcess( fallbackProcess: string | null, options: AgentForegroundResolutionOptions = {} ): Promise { + return (await resolveAgentForegroundProcessWithAvailability(shellPid, fallbackProcess, options)) + .processName +} + +export async function resolveAgentForegroundProcessWithAvailability( + shellPid: number | null | undefined, + fallbackProcess: string | null, + options: AgentForegroundResolutionOptions = {} +): Promise { if (!shellPid) { - return fallbackProcess + return { available: false, processName: fallbackProcess } } if (process.platform === 'win32') { - if (!fallbackProcess || !shouldInspectWindowsAgentForeground(fallbackProcess)) { - return fallbackProcess + if ( + !fallbackProcess || + (!shouldInspectWindowsAgentForeground(fallbackProcess) && !options.forceProcessScan) + ) { + return { available: true, processName: fallbackProcess } } - return ( - (await resolveWindowsAgentForegroundProcess(shellPid, fallbackProcess, options)) ?? - fallbackProcess + const resolution = await resolveWindowsAgentForegroundProcessWithAvailability( + shellPid, + fallbackProcess, + options ) + return { + available: resolution.available, + // Why: a forced confirmation scan that no longer sees the recognized + // fallback is authoritative evidence that the agent exited meanwhile. + processName: + resolution.processName ?? + (options.forceProcessScan && recognizeAgentProcessFromCommandLine(fallbackProcess) + ? null + : fallbackProcess) + } } try { - const rows = await getProcessTableSnapshot() - return resolveAgentForegroundProcessFromPs(rows, shellPid) ?? fallbackProcess + const rows = options.fresh + ? await getFreshProcessTableSnapshot() + : await getProcessTableSnapshot() + if (options.fresh && !rows.some((row) => row.pid === shellPid)) { + return { available: false, processName: fallbackProcess } + } + return { + available: true, + processName: resolveAgentForegroundProcessFromPs(rows, shellPid) ?? fallbackProcess + } } catch { - // Fall through to node-pty's process name. Foreground process inspection is - // best-effort because terminal identity should never break PTY operation. + return { available: !options.fresh, processName: fallbackProcess } } - - return fallbackProcess } function resolveAgentForegroundProcessFromPs( diff --git a/src/main/providers/local-pty-provider.test.ts b/src/main/providers/local-pty-provider.test.ts index 1448f59d9463..57748417caca 100644 --- a/src/main/providers/local-pty-provider.test.ts +++ b/src/main/providers/local-pty-provider.test.ts @@ -58,7 +58,10 @@ vi.mock('./windows-powershell-executable', () => ({ })) vi.mock('./agent-foreground-process', () => ({ - resolveAgentForegroundProcess: resolveAgentForegroundProcessMock + resolveAgentForegroundProcessWithAvailability: async (...args: unknown[]) => ({ + available: true, + processName: await resolveAgentForegroundProcessMock(...args) + }) })) vi.mock('../wsl', () => ({ @@ -1039,6 +1042,24 @@ describe('LocalPtyProvider', () => { }) }) + describe('confirmForegroundProcess', () => { + it('drops a delayed result after the PTY exits', async () => { + let resolveScan!: (processName: string) => void + resolveAgentForegroundProcessMock.mockReturnValue( + new Promise((resolve) => { + resolveScan = resolve + }) + ) + const { id } = await provider.spawn({ cols: 80, rows: 24 }) + + const confirmation = provider.confirmForegroundProcess(id) + exitCb?.({ exitCode: 0 }) + resolveScan('droid') + + await expect(confirmation).resolves.toBeNull() + }) + }) + describe('event listeners', () => { it('notifies data listeners when PTY produces output', async () => { const dataHandler = vi.fn() diff --git a/src/main/providers/local-pty-provider.ts b/src/main/providers/local-pty-provider.ts index 941fe0629975..806dfdd5d24a 100644 --- a/src/main/providers/local-pty-provider.ts +++ b/src/main/providers/local-pty-provider.ts @@ -51,9 +51,10 @@ import { resolveWindowsGitBashShellPath } from '../git-bash' import { WINDOWS_GIT_BASH_SHELL } from '../../shared/windows-terminal-shell' -import { resolveAgentForegroundProcess } from './agent-foreground-process' +import { resolveAgentForegroundProcessWithAvailability } from './agent-foreground-process' import { getAgentForegroundContextPaths } from './agent-foreground-context-paths' import { recognizeAgentProcessFromCommandLine } from '../../shared/agent-process-recognition' +import { readWindowsConptyProcessIds } from './windows-conpty-process-membership' import { shouldUseShellReadyStartupDelivery } from '../../shared/codex-startup-delivery' import { assertSafeAgentStartupCwd, resolveSafePtyDefaultCwd } from './pty-default-cwd' @@ -971,13 +972,45 @@ export class LocalPtyProvider implements IPtyProvider { return null } try { - return await resolveAgentForegroundProcess( + const resolution = await resolveAgentForegroundProcessWithAvailability( proc.pid, resolveForegroundFallbackProcess(proc.process || null, ptyShellName.get(id)), { contextPaths: ptyAgentForegroundContextPaths.get(id) } ) + return resolution.processName + } catch { + return null + } + } + + async confirmForegroundProcess(id: string): Promise { + const proc = ptyProcesses.get(id) + if (!proc) { + return null + } + try { + const resolution = await resolveAgentForegroundProcessWithAvailability( + proc.pid, + resolveForegroundFallbackProcess(proc.process || null, ptyShellName.get(id)), + { + contextPaths: ptyAgentForegroundContextPaths.get(id), + fresh: true, + ...(process.platform === 'win32' + ? { + forceProcessScan: true, + readWindowsConptyProcessIds: () => readWindowsConptyProcessIds(proc.pid) + } + : {}) + } + ) + // Why: a fresh scan can outlive this PTY id; never publish identity from + // an exited process or a replacement session that reused the same id. + if (ptyProcesses.get(id) !== proc) { + return null + } + return resolution.available ? resolution.processName : null } catch { return null } diff --git a/src/main/providers/types.ts b/src/main/providers/types.ts index 24bd305bfbcc..d5873c948ea7 100644 --- a/src/main/providers/types.ts +++ b/src/main/providers/types.ts @@ -12,6 +12,7 @@ import type { GitStagingArea, GitUpstreamStatus, GitWorktreeInfo, + TuiAgent, RemoveWorktreeResult, SearchOptions, SearchResult @@ -62,6 +63,8 @@ export type PtySpawnOptions = { command?: string commandDelivery?: 'renderer' | 'provider' startupCommandDelivery?: StartupCommandDelivery + /** Minimal allowlisted launch ownership preserved by daemon reattach. */ + launchAgent?: TuiAgent /** Orca worktree identity. When present, the local provider scopes shell * history to this worktree so ArrowUp only surfaces local commands. */ worktreeId?: string @@ -105,6 +108,8 @@ export type PtySpawnResult = { * local providers read it from node-pty. Null when the underlying * provider could not publish a pid (e.g., race during spawn). */ pid?: number | null + /** Minimal allowlisted launch ownership returned by daemon reattach. */ + launchAgent?: TuiAgent /** ANSI snapshot of the terminal screen, present when reattaching to an * existing daemon session. Write this to xterm.js to restore visual state. */ snapshot?: string @@ -204,6 +209,8 @@ export type IPtyProvider = { acknowledgeDataEvent(id: string, charCount: number): void hasChildProcesses(id: string): Promise getForegroundProcess(id: string): Promise + /** Strong process evidence captured after the caller's command boundary. */ + confirmForegroundProcess?: (id: string) => Promise serialize(ids: string[]): Promise revive(state: string): Promise listProcesses(): Promise diff --git a/src/main/providers/windows-agent-foreground-process.ts b/src/main/providers/windows-agent-foreground-process.ts index 39447432a915..556d6763e628 100644 --- a/src/main/providers/windows-agent-foreground-process.ts +++ b/src/main/providers/windows-agent-foreground-process.ts @@ -12,6 +12,17 @@ import { export type AgentForegroundResolutionOptions = { contextPaths?: readonly string[] + /** Require a Windows process-table scan started after this request. */ + fresh?: boolean + /** Force confirmation scans even when node-pty reports a recognized name. */ + forceProcessScan?: boolean + /** Lazily proves which global descendants still belong to this ConPTY. */ + readWindowsConptyProcessIds?: () => Promise | null> +} + +export type WindowsAgentForegroundResolution = { + available: boolean + processName: string | null } export function shouldInspectWindowsAgentForeground(fallbackProcess: string): boolean { @@ -23,21 +34,79 @@ export async function resolveWindowsAgentForegroundProcess( fallbackProcess: string, options: AgentForegroundResolutionOptions ): Promise { - const candidates = await queryWindowsProcessDescendants(shellPid) + return ( + await resolveWindowsAgentForegroundProcessWithAvailability(shellPid, fallbackProcess, options) + ).processName +} + +export async function resolveWindowsAgentForegroundProcessWithAvailability( + shellPid: number, + fallbackProcess: string, + options: AgentForegroundResolutionOptions +): Promise { + const candidates = await queryWindowsProcessDescendants( + shellPid, + options.fresh === true ? { fresh: true } : {} + ) if (!candidates) { - return null + return { available: false, processName: null } + } + // Resolve membership before applying the global ambiguity rule. A detached + // agent can otherwise make an attached Droid look ambiguous and suppress + // the only identity that is actually able to receive this PTY's input. + const hasRecognizedCandidate = windowsCandidatesContainRecognizedAgent( + candidates, + fallbackProcess, + options.contextPaths + ) + let filteredCandidates = candidates + if (hasRecognizedCandidate && options.readWindowsConptyProcessIds) { + const conptyProcessIds = await options.readWindowsConptyProcessIds() + if (!conptyProcessIds) { + return { available: false, processName: null } + } + filteredCandidates = candidates.filter((candidate) => conptyProcessIds.has(candidate.pid)) + } + return { + available: true, + processName: resolveWindowsProcessName( + filteredCandidates, + fallbackProcess, + options.contextPaths + ) } +} + +function windowsCandidatesContainRecognizedAgent( + candidates: readonly WindowsProcessCandidate[], + fallbackProcess: string, + contextPaths: readonly string[] | undefined +): boolean { if (isShellProcess(fallbackProcess)) { - return resolveShellForegroundProcessFromWindowsCandidates(candidates, options.contextPaths) + return createRecognizedWindowsProcessCandidates(candidates, contextPaths).length > 0 + } + return candidates + .filter((candidate) => windowsCandidateMatchesFallbackWrapper(candidate, fallbackProcess)) + .some( + (candidate) => + recognizeAgentProcessFromCommandLine(candidate.command) !== null || + recognizeAgentProcessFromCommandLine(candidate.name) !== null + ) +} + +function resolveWindowsProcessName( + candidates: readonly WindowsProcessCandidate[], + fallbackProcess: string, + contextPaths: readonly string[] | undefined +): string | null { + if (isShellProcess(fallbackProcess)) { + return resolveShellForegroundProcessFromWindowsCandidates(candidates, contextPaths) } const wrapperCandidates = candidates.filter((candidate) => windowsCandidateMatchesFallbackWrapper(candidate, fallbackProcess) ) if (wrapperCandidates.length !== 1) { - return resolveWrapperForegroundProcessFromWindowsCandidates( - wrapperCandidates, - options.contextPaths - ) + return resolveWrapperForegroundProcessFromWindowsCandidates(wrapperCandidates, contextPaths) } const [candidate] = wrapperCandidates const recognized = diff --git a/src/main/providers/windows-conpty-process-membership.test.ts b/src/main/providers/windows-conpty-process-membership.test.ts new file mode 100644 index 000000000000..e9e2ef09fdd0 --- /dev/null +++ b/src/main/providers/windows-conpty-process-membership.test.ts @@ -0,0 +1,64 @@ +import { EventEmitter } from 'node:events' +import { describe, expect, it, vi } from 'vitest' +import { readWindowsConptyProcessIds } from './windows-conpty-process-membership' + +function forkWith(event: 'message' | 'error' | 'none', value?: unknown) { + const child = new EventEmitter() as EventEmitter & { kill: ReturnType } + child.kill = vi.fn() + const forkProcess = vi.fn(() => { + queueMicrotask(() => { + if (event === 'message') { + child.emit('message', { consoleProcessList: value }) + } else if (event === 'error') { + child.emit('error', new Error('spawn failed')) + } + }) + return child + }) + return { child, forkProcess: forkProcess as never } +} + +describe('readWindowsConptyProcessIds', () => { + it('returns exact console membership from the fixed node-pty helper', async () => { + const { forkProcess } = forkWith('message', [101, 202, 303]) + + await expect( + readWindowsConptyProcessIds(101, { + forkProcess, + resolveAgentPath: () => '/fixed/node-pty/conpty_console_list_agent.js' + }) + ).resolves.toEqual(new Set([101, 202, 303])) + expect(forkProcess).toHaveBeenCalledWith( + '/fixed/node-pty/conpty_console_list_agent.js', + ['101'], + { silent: true } + ) + }) + + it.each([ + ['root-only failure fallback', [101]], + ['malformed response', [101, '202']], + ['missing PTY root', [202, 303]] + ])('fails closed for %s', async (_label, processIds) => { + const { forkProcess } = forkWith('message', processIds) + await expect(readWindowsConptyProcessIds(101, { forkProcess })).resolves.toBeNull() + }) + + it('handles helper spawn errors without an unhandled child error', async () => { + const { forkProcess } = forkWith('error') + await expect(readWindowsConptyProcessIds(101, { forkProcess })).resolves.toBeNull() + }) + + it('kills a silent helper at the bounded timeout', async () => { + vi.useFakeTimers() + try { + const { child, forkProcess } = forkWith('none') + const result = readWindowsConptyProcessIds(101, { forkProcess, timeoutMs: 10 }) + await vi.advanceTimersByTimeAsync(10) + await expect(result).resolves.toBeNull() + expect(child.kill).toHaveBeenCalledTimes(1) + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/src/main/providers/windows-conpty-process-membership.ts b/src/main/providers/windows-conpty-process-membership.ts new file mode 100644 index 000000000000..759a234c63fc --- /dev/null +++ b/src/main/providers/windows-conpty-process-membership.ts @@ -0,0 +1,74 @@ +import { fork, type ChildProcess } from 'node:child_process' + +const CONPTY_PROCESS_LIST_TIMEOUT_MS = 3_000 + +type ProcessListMessage = { consoleProcessList?: unknown } + +type WindowsConptyMembershipDeps = { + forkProcess?: typeof fork + resolveAgentPath?: () => string + timeoutMs?: number +} + +function resolveNodePtyConsoleListAgent(): string { + return require.resolve('node-pty/lib/conpty_console_list_agent.js') +} + +/** + * Runs node-pty's fixed native console-list helper with bounded error/exit + * handling. A root-only result is its failure fallback, not shell proof. + */ +export function readWindowsConptyProcessIds( + rootPid: number, + deps: WindowsConptyMembershipDeps = {} +): Promise | null> { + if (!Number.isSafeInteger(rootPid) || rootPid <= 0) { + return Promise.resolve(null) + } + let child: ChildProcess + try { + child = (deps.forkProcess ?? fork)( + (deps.resolveAgentPath ?? resolveNodePtyConsoleListAgent)(), + [String(rootPid)], + { silent: true } + ) + } catch { + return Promise.resolve(null) + } + + return new Promise((resolve) => { + let settled = false + const finish = (value: ReadonlySet | null): void => { + if (settled) { + return + } + settled = true + clearTimeout(timeout) + child.removeListener('message', onMessage) + child.removeListener('error', onFailure) + child.removeListener('exit', onFailure) + resolve(value) + } + const onFailure = (): void => finish(null) + const onMessage = (message: ProcessListMessage): void => { + const value = message?.consoleProcessList + if ( + !Array.isArray(value) || + value.length <= 1 || + !value.includes(rootPid) || + value.some((pid) => !Number.isSafeInteger(pid) || pid <= 0) + ) { + finish(null) + return + } + finish(new Set(value)) + } + const timeout = setTimeout(() => { + child.kill() + finish(null) + }, deps.timeoutMs ?? CONPTY_PROCESS_LIST_TIMEOUT_MS) + child.once('message', onMessage) + child.once('error', onFailure) + child.once('exit', onFailure) + }) +} diff --git a/src/main/providers/windows-foreground-process-rows.ts b/src/main/providers/windows-foreground-process-rows.ts index d26067122a58..6fea54165c8d 100644 --- a/src/main/providers/windows-foreground-process-rows.ts +++ b/src/main/providers/windows-foreground-process-rows.ts @@ -48,14 +48,23 @@ const windowsProcessRowsReader = createProcessTableSnapshotReader { let rows: WindowsProcessRow[] try { - rows = await windowsProcessRowsReader.getSnapshot() + rows = + options.fresh === true + ? await windowsProcessRowsReader.getFreshSnapshot() + : await windowsProcessRowsReader.getSnapshot() } catch { return null } + // Why: a snapshot that omitted the PTY root may be stale or permission- + // filtered; only an observed root can authoritatively have no descendants. + if (!rows.some((row) => row.pid === rootPid)) { + return null + } return collectDescendants(rows, rootPid).sort((a, b) => b.depth - a.depth) } @@ -234,7 +243,8 @@ async function queryWindowsProcessesWithWmic(): Promise 0 ? rows : null } catch { // Best-effort: Windows process enumeration may be disabled, so callers // still fall back to node-pty's process name when both probes fail. diff --git a/src/preload/api-types.ts b/src/preload/api-types.ts index ceb0d6a8d54b..1001d14f9664 100644 --- a/src/preload/api-types.ts +++ b/src/preload/api-types.ts @@ -1231,6 +1231,7 @@ export type PreloadApi = { telemetry?: { agent_kind: AgentKind; launch_source: LaunchSource; request_kind: RequestKind } }) => Promise<{ id: string + launchAgent?: TuiAgent launchConfig?: SleepingAgentLaunchConfig snapshot?: string snapshotCols?: number @@ -1280,6 +1281,7 @@ export type PreloadApi = { publishTerminalViewAttributes: (attributes: TerminalViewAttributes) => void hasChildProcesses: (id: string) => Promise getForegroundProcess: (id: string) => Promise + confirmForegroundProcess: (id: string) => Promise getCwd: (id: string) => Promise getSize: (id: string) => Promise<{ cols: number; rows: number } | null> listSessions: () => Promise<{ id: string; cwd: string; title: string }[]> diff --git a/src/preload/index.ts b/src/preload/index.ts index 2e960b9c461d..c1c8e7fe1545 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -986,6 +986,8 @@ const api = { /** Return the PTY foreground process basename when available (e.g. "codex"). */ getForegroundProcess: (id: string): Promise => ipcRenderer.invoke('pty:getForegroundProcess', { id }), + confirmForegroundProcess: (id: string): Promise => + ipcRenderer.invoke('pty:confirmForegroundProcess', { id }), /** Resolve the live cwd of a PTY via `/proc` (Linux) or `lsof` (macOS). * Returns `''` when the id is unknown or the platform cannot resolve one. */ diff --git a/src/renderer/src/components/terminal-pane/TerminalPane.tsx b/src/renderer/src/components/terminal-pane/TerminalPane.tsx index 297b28da36df..c2ac6928cdf6 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPane.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPane.tsx @@ -1785,6 +1785,7 @@ export default function TerminalPane({ keyboardScopeRef: containerRef, managerRef, paneTransportsRef, + panePtyBindingsRef, paneCwdRef, fallbackCwd: cwd ?? '', expandedPaneIdRef, diff --git a/src/renderer/src/components/terminal-pane/keyboard-handlers.ts b/src/renderer/src/components/terminal-pane/keyboard-handlers.ts index b5bf46b7d0c6..c41a0ea919d3 100644 --- a/src/renderer/src/components/terminal-pane/keyboard-handlers.ts +++ b/src/renderer/src/components/terminal-pane/keyboard-handlers.ts @@ -2,6 +2,7 @@ * precedence in one ordered handler so shell input, pane commands, search, and * split actions do not race across separate window listeners. */ import { useEffect } from 'react' +import type { IDisposable } from '@xterm/xterm' import type { ManagedPane, PaneManager } from '@/lib/pane-manager/pane-manager' import type { PtyTransport } from './pty-transport' import { safeFind } from '../terminal-search-safe-find' @@ -28,6 +29,8 @@ import { splitTerminalPaneWithInheritedCwd } from './terminal-pane-split-with-in import { useAppStore } from '@/store' import { recordTerminalUserInputForLeaf } from './terminal-input-activity' import { isLocalWindowsConptyPaneForCtrlArrow } from './terminal-ctrl-arrow-conpty' +import { makePaneKey } from '../../../../shared/stable-pane-id' +import { resolveWindowsShiftEnterEncodingForPane } from './terminal-windows-shift-enter' import { markTerminalFollowOutput, markTerminalPinnedViewport, @@ -148,6 +151,7 @@ type KeyboardHandlersDeps = { keyboardScopeRef: React.RefObject managerRef: React.RefObject paneTransportsRef: React.RefObject> + panePtyBindingsRef: React.RefObject> paneCwdRef: React.RefObject /** Worktree-root cwd used when OSC 7 and pty.getCwd both fail. */ fallbackCwd: string @@ -183,6 +187,7 @@ export function useTerminalKeyboardShortcuts({ keyboardScopeRef, managerRef, paneTransportsRef, + panePtyBindingsRef, paneCwdRef, fallbackCwd, expandedPaneIdRef, @@ -235,6 +240,19 @@ export function useTerminalKeyboardShortcuts({ } } + // Why: this callback is installed once per active tab and invoked only for + // Windows Shift+Enter, keeping store work and allocations off ordinary keys. + const getActivePaneWindowsShiftEnterEncoding = () => { + const manager = managerRef.current + const activePane = manager?.getActivePane() ?? manager?.getPanes()[0] + if (!activePane) { + return 'alt-enter' as const + } + const state = useAppStore.getState() + const paneKey = makePaneKey(tabId, activePane.leafId) + return resolveWindowsShiftEnterEncodingForPane(state, paneKey) + } + const onKeyDown = (e: KeyboardEvent): void => { const manager = managerRef.current if (!manager) { @@ -326,7 +344,8 @@ export function useTerminalKeyboardShortcuts({ keybindings, isLocalWindowsConptyPane, isKittyKeyboardActivePane, - getLayoutBaseCharacterForCode + getLayoutBaseCharacterForCode, + getActivePaneWindowsShiftEnterEncoding ) if (!action) { return @@ -342,6 +361,14 @@ export function useTerminalKeyboardShortcuts({ const sent = paneTransportsRef.current.get(pane.id)?.sendInput(action.data) === true if (sent) { recordTerminalUserInputForLeaf(tabId, pane.leafId) + if (action.data === '\x1b[13;2u') { + // Why: this direct shortcut write does not pass through PTY onData, + // so no-OSC shells need an explicit post-write confirmation ladder. + const binding = panePtyBindingsRef.current.get(pane.id) as + | (IDisposable & { requestDroidReconfirmation?: () => void }) + | undefined + binding?.requestDroidReconfirmation?.() + } } return } diff --git a/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts b/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts index ab5aaa03b8c9..c5fa06ba8d83 100644 --- a/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts +++ b/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.test.ts @@ -7,21 +7,28 @@ import type { PaneForegroundAgentEntry } from '@/store/slices/pane-foreground-ag const COMMAND_SETTLE_MS = 350 const VISIBLE_PTY_SETTLE_MS = 350 const WRAPPER_RESOLVE_RETRY_MS = 1200 -const SECOND_WRAPPER_RETRY_MS = 3500 +const SECOND_WRAPPER_RETRY_MS = 6000 describe('createPaneForegroundAgentTracker', () => { const readForegroundProcess = vi.fn<(ptyId: string) => Promise>() + const confirmForegroundProcess = vi.fn<(ptyId: string) => Promise>() const publish = vi.fn<(entry: PaneForegroundAgentEntry) => void>() const onConfirmedShellForeground = vi.fn<() => void>() + const onCommandFinishedUnavailable = vi.fn<() => void>() let ptyId: string | null = 'pty-1' - function makeTracker(): ReturnType { + function makeTracker( + hasKnownAgentIdentity?: () => boolean + ): ReturnType { return createPaneForegroundAgentTracker({ getPtyId: () => ptyId, isTrackablePtyId: (id) => !id.startsWith('remote:') && !id.startsWith('ssh:'), readForegroundProcess, + confirmForegroundProcess, publish, - onConfirmedShellForeground + hasKnownAgentIdentity, + onConfirmedShellForeground, + onCommandFinishedUnavailable }) } @@ -32,8 +39,11 @@ describe('createPaneForegroundAgentTracker', () => { beforeEach(() => { vi.useFakeTimers() readForegroundProcess.mockReset() + confirmForegroundProcess.mockReset() + confirmForegroundProcess.mockImplementation((id) => readForegroundProcess(id)) publish.mockReset() onConfirmedShellForeground.mockReset() + onCommandFinishedUnavailable.mockReset() ptyId = 'pty-1' }) @@ -56,12 +66,86 @@ describe('createPaneForegroundAgentTracker', () => { expect(publish).toHaveBeenLastCalledWith({ agent: 'claude', shellForeground: false }) }) + it('drops a delayed foreground result after the pane rebinds to another PTY', async () => { + let resolveRead!: (processName: string) => void + readForegroundProcess.mockReturnValue( + new Promise((resolve) => { + resolveRead = resolve + }) + ) + const tracker = makeTracker() + + tracker.onCommandStarted() + await flushSettleRead(COMMAND_SETTLE_MS) + expect(readForegroundProcess).toHaveBeenCalledExactlyOnceWith('pty-1') + ptyId = 'pty-2' + resolveRead('droid') + await Promise.resolve() + await Promise.resolve() + + expect(publish).not.toHaveBeenCalledWith({ agent: 'droid', shellForeground: false }) + }) + + it('uses typed-agent text only to await process confirmation', async () => { + readForegroundProcess.mockResolvedValueOnce('powershell.exe').mockResolvedValueOnce('droid') + const tracker = makeTracker() + + tracker.onCommandStarted('droid') + expect(publish).toHaveBeenCalledExactlyOnceWith({ agent: null, shellForeground: false }) + + await flushSettleRead(COMMAND_SETTLE_MS) + expect(publish).toHaveBeenCalledTimes(1) + await flushSettleRead(WRAPPER_RESOLVE_RETRY_MS) + expect(publish).toHaveBeenLastCalledWith({ + agent: 'droid', + routingTrusted: true, + shellForeground: false + }) + }) + + it('never publishes typed Droid when command-start reads stay unavailable', async () => { + readForegroundProcess.mockResolvedValue(null) + const tracker = makeTracker() + + tracker.onCommandStarted('droid') + await flushSettleRead(COMMAND_SETTLE_MS) + expect(publish).toHaveBeenLastCalledWith({ agent: null, shellForeground: false }) + + await flushSettleRead(WRAPPER_RESOLVE_RETRY_MS) + expect(publish).toHaveBeenLastCalledWith({ agent: null, shellForeground: false }) + + await flushSettleRead(SECOND_WRAPPER_RETRY_MS - 1) + expect(publish).toHaveBeenLastCalledWith({ agent: null, shellForeground: false }) + await flushSettleRead(1) + + expect(readForegroundProcess).toHaveBeenCalledTimes(3) + expect(publish).toHaveBeenLastCalledWith({ agent: null, shellForeground: false }) + }) + + it('does not replace known foreground identity with typed command inference', () => { + const tracker = makeTracker(() => true) + + tracker.onCommandStarted('droid') + + expect(publish).toHaveBeenCalledExactlyOnceWith({ agent: null, shellForeground: false }) + }) + + it('revokes stale routing immediately while a known pane confirms a new command', () => { + const tracker = makeTracker(() => true) + + tracker.onCommandStarted() + + expect(publish).toHaveBeenCalledExactlyOnceWith({ agent: null, shellForeground: false }) + expect(confirmForegroundProcess).not.toHaveBeenCalled() + }) + it('reads the foreground for a visible PTY so restored running Codex panes regain identity', async () => { readForegroundProcess.mockResolvedValue('codex') const tracker = makeTracker() tracker.onVisiblePtyBound() expect(readForegroundProcess).not.toHaveBeenCalled() + expect(confirmForegroundProcess).not.toHaveBeenCalled() await flushSettleRead(VISIBLE_PTY_SETTLE_MS) @@ -194,10 +278,7 @@ describe('createPaneForegroundAgentTracker', () => { expect(readForegroundProcess).not.toHaveBeenCalled() }) - it('confirms a rapid command start->finish instead of trusting the D', async () => { - // Why: a leaked nested-shell 133;C->133;D pair (or a fast real command) - // cancels the command-start read; confirm the foreground so a still-running - // manual agent with no launchAgent/hook keeps its identity. + it('trusts a rapid ordinary command finish without forcing a fresh scan', async () => { readForegroundProcess.mockResolvedValue('claude') const tracker = makeTracker() @@ -205,15 +286,11 @@ describe('createPaneForegroundAgentTracker', () => { tracker.onCommandFinished() await flushSettleRead(COMMAND_SETTLE_MS) - expect(readForegroundProcess).toHaveBeenCalledExactlyOnceWith('pty-1') - expect(publish).toHaveBeenLastCalledWith({ agent: 'claude', shellForeground: false }) - expect(publish).not.toHaveBeenCalledWith({ agent: null, shellForeground: true }) + expect(readForegroundProcess).not.toHaveBeenCalled() + expect(publish).toHaveBeenLastCalledWith({ agent: null, shellForeground: true }) }) - it('confirms duplicate 133;D pairs instead of fast-pathing past the pending confirmation', async () => { - // Why: user shell integrations (iTerm/VS Code) double up Orca's OSC 133, so - // every D arrives twice ~50ms apart. The second D cancels the first D's - // confirming read; it must reschedule the confirmation, not trust the D. + it('keeps duplicate ordinary 133;D pairs on the no-scan shell path', async () => { readForegroundProcess.mockResolvedValue('grok') const tracker = makeTracker() @@ -224,9 +301,8 @@ describe('createPaneForegroundAgentTracker', () => { tracker.onCommandFinished() await flushSettleRead(COMMAND_SETTLE_MS) - expect(readForegroundProcess).toHaveBeenCalledExactlyOnceWith('pty-1') - expect(publish).toHaveBeenLastCalledWith({ agent: 'grok', shellForeground: false }) - expect(publish).not.toHaveBeenCalledWith({ agent: null, shellForeground: true }) + expect(readForegroundProcess).not.toHaveBeenCalled() + expect(publish).toHaveBeenLastCalledWith({ agent: null, shellForeground: true }) }) it('still marks shell without a read for a duplicate D pair on an idle pane', async () => { @@ -252,7 +328,7 @@ describe('createPaneForegroundAgentTracker', () => { tracker.onCommandFinished() await flushSettleRead(COMMAND_SETTLE_MS) - expect(readForegroundProcess).toHaveBeenCalledExactlyOnceWith('pty-1') + expect(readForegroundProcess).not.toHaveBeenCalled() expect(publish).toHaveBeenLastCalledWith({ agent: null, shellForeground: true }) }) @@ -262,7 +338,10 @@ describe('createPaneForegroundAgentTracker', () => { tracker.onCommandStarted() await flushSettleRead(COMMAND_SETTLE_MS) - expect(publish).toHaveBeenLastCalledWith({ agent: 'codex', shellForeground: false }) + expect(publish).toHaveBeenLastCalledWith({ + agent: 'codex', + shellForeground: false + }) publish.mockClear() readForegroundProcess.mockClear() @@ -272,12 +351,16 @@ describe('createPaneForegroundAgentTracker', () => { await flushSettleRead(COMMAND_SETTLE_MS) expect(readForegroundProcess).toHaveBeenCalledExactlyOnceWith('pty-1') - expect(publish).toHaveBeenLastCalledWith({ agent: 'codex', shellForeground: false }) + expect(publish).toHaveBeenLastCalledWith({ + agent: 'codex', + routingTrusted: true, + shellForeground: false + }) expect(publish).not.toHaveBeenCalledWith({ agent: null, shellForeground: true }) }) it('marks shell foreground when the confirming read shows the agent is gone', async () => { - readForegroundProcess.mockResolvedValueOnce('codex').mockResolvedValueOnce('zsh') + readForegroundProcess.mockResolvedValueOnce('codex').mockResolvedValue('zsh') const tracker = makeTracker() tracker.onCommandStarted() @@ -292,11 +375,12 @@ describe('createPaneForegroundAgentTracker', () => { }) it('signals confirmed shell foreground only when the read proves the agent exited', async () => { - // Reads: command-start=codex, first finish=codex (still running), second finish=zsh (exited). + // Reads: command-start=codex, first finish=codex (still running), then a + // bounded zsh→zsh→zsh confirmation for genuine exit. readForegroundProcess .mockResolvedValueOnce('codex') .mockResolvedValueOnce('codex') - .mockResolvedValueOnce('zsh') + .mockResolvedValue('zsh') const tracker = makeTracker() tracker.onCommandStarted() @@ -314,13 +398,15 @@ describe('createPaneForegroundAgentTracker', () => { }) it('returns to the no-RPC finished path after the agent is confirmed gone', async () => { - readForegroundProcess.mockResolvedValueOnce('codex').mockResolvedValueOnce('zsh') + readForegroundProcess.mockResolvedValueOnce('codex').mockResolvedValue('zsh') const tracker = makeTracker() tracker.onCommandStarted() await flushSettleRead(COMMAND_SETTLE_MS) tracker.onCommandFinished() await flushSettleRead(COMMAND_SETTLE_MS) + await flushSettleRead(WRAPPER_RESOLVE_RETRY_MS) + await flushSettleRead(SECOND_WRAPPER_RETRY_MS) publish.mockClear() readForegroundProcess.mockClear() @@ -336,6 +422,7 @@ describe('createPaneForegroundAgentTracker', () => { getPtyId: () => ptyId, isTrackablePtyId: (id) => !id.startsWith('remote:') && !id.startsWith('ssh:'), readForegroundProcess, + confirmForegroundProcess, publish, hasKnownAgentIdentity: () => true }) @@ -346,7 +433,120 @@ describe('createPaneForegroundAgentTracker', () => { await flushSettleRead(COMMAND_SETTLE_MS) expect(readForegroundProcess).toHaveBeenCalledExactlyOnceWith('pty-1') - expect(publish).toHaveBeenLastCalledWith({ agent: 'codex', shellForeground: false }) + expect(publish).toHaveBeenLastCalledWith({ + agent: 'codex', + routingTrusted: true, + shellForeground: false + }) + }) + + it('accepts a fresh shell result for a launch-known Droid pane', async () => { + readForegroundProcess.mockResolvedValueOnce('powershell.exe').mockResolvedValueOnce('droid') + const tracker = makeTracker(() => true) + + tracker.onCommandFinished() + await flushSettleRead(COMMAND_SETTLE_MS) + expect(readForegroundProcess).toHaveBeenCalledTimes(1) + expect(publish).toHaveBeenCalledExactlyOnceWith({ agent: null, shellForeground: true }) + }) + + it('does not let removed launch identity override fresh shell evidence', async () => { + let knownIdentity = true + readForegroundProcess.mockResolvedValueOnce('powershell.exe').mockResolvedValueOnce('droid') + const tracker = makeTracker(() => knownIdentity) + + tracker.onCommandFinished() + // Why: pty-connection clears launch metadata in the same OSC 133;D + // callback, before this tracker's delayed foreground read starts. + knownIdentity = false + await flushSettleRead(COMMAND_SETTLE_MS) + expect(publish).toHaveBeenCalledExactlyOnceWith({ agent: null, shellForeground: true }) + }) + + it('marks a confirmed shell without repeating a post-boundary scan', async () => { + readForegroundProcess.mockResolvedValue('powershell.exe') + const tracker = makeTracker(() => true) + + tracker.onCommandFinished() + await flushSettleRead(COMMAND_SETTLE_MS) + expect(readForegroundProcess).toHaveBeenCalledTimes(1) + expect(publish).toHaveBeenCalledExactlyOnceWith({ agent: null, shellForeground: true }) + expect(onConfirmedShellForeground).toHaveBeenCalledTimes(1) + expect(onCommandFinishedUnavailable).not.toHaveBeenCalled() + }) + + it('retries a null foreground result once for a known Droid pane', async () => { + readForegroundProcess.mockResolvedValueOnce(null).mockResolvedValueOnce('droid') + const tracker = makeTracker(() => true) + + tracker.onCommandFinished() + await flushSettleRead(COMMAND_SETTLE_MS) + expect(publish).not.toHaveBeenCalled() + + await flushSettleRead(WRAPPER_RESOLVE_RETRY_MS) + expect(readForegroundProcess).toHaveBeenCalledTimes(2) + expect(publish).toHaveBeenCalledExactlyOnceWith({ + agent: 'droid', + routingTrusted: true, + shellForeground: false + }) + }) + + it('retries a rejected foreground read once for a known Droid pane', async () => { + readForegroundProcess.mockRejectedValueOnce(new Error('inspection unavailable')) + readForegroundProcess.mockResolvedValueOnce('droid') + const tracker = makeTracker(() => true) + + tracker.onCommandFinished() + await flushSettleRead(COMMAND_SETTLE_MS) + expect(publish).not.toHaveBeenCalled() + + await flushSettleRead(WRAPPER_RESOLVE_RETRY_MS) + expect(readForegroundProcess).toHaveBeenCalledTimes(2) + expect(publish).toHaveBeenCalledExactlyOnceWith({ + agent: 'droid', + routingTrusted: true, + shellForeground: false + }) + }) + + it('retires known identity when the bounded command-finish ladder remains unavailable', async () => { + readForegroundProcess.mockResolvedValue(null) + const tracker = makeTracker(() => true) + + tracker.onCommandFinished() + await flushSettleRead(COMMAND_SETTLE_MS) + expect(publish).not.toHaveBeenCalled() + + await flushSettleRead(WRAPPER_RESOLVE_RETRY_MS) + expect(readForegroundProcess).toHaveBeenCalledTimes(2) + await flushSettleRead(SECOND_WRAPPER_RETRY_MS) + + expect(readForegroundProcess).toHaveBeenCalledTimes(3) + expect(publish).toHaveBeenCalledExactlyOnceWith({ agent: null, shellForeground: false }) + expect(onConfirmedShellForeground).not.toHaveBeenCalled() + expect(onCommandFinishedUnavailable).toHaveBeenCalledTimes(1) + }) + + it('rebuilds visible launch identity through provisional daemon shell results', async () => { + readForegroundProcess + .mockResolvedValueOnce('powershell.exe') + .mockResolvedValueOnce(null) + .mockResolvedValueOnce('droid') + const tracker = makeTracker(() => false) + + tracker.onVisiblePtyBound(true) + await flushSettleRead(VISIBLE_PTY_SETTLE_MS) + await flushSettleRead(WRAPPER_RESOLVE_RETRY_MS) + expect(publish).not.toHaveBeenCalled() + + await flushSettleRead(SECOND_WRAPPER_RETRY_MS) + expect(readForegroundProcess).toHaveBeenCalledTimes(3) + expect(publish).toHaveBeenCalledExactlyOnceWith({ + agent: 'droid', + routingTrusted: true, + shellForeground: false + }) }) it('never reads or publishes for remote or ssh panes', async () => { diff --git a/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.ts b/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.ts index d3e613f68455..189b91573b61 100644 --- a/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.ts +++ b/src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker.ts @@ -2,15 +2,15 @@ import { isAgentForegroundWrapperProcess, recognizeAgentProcess } from '../../../../shared/agent-process-recognition' +import { isShellProcess } from '../../../../shared/shell-process-detection' +import type { TuiAgent } from '../../../../shared/types' import type { PaneForegroundAgentEntry } from '@/store/slices/pane-foreground-agent' -// Why: the read must land after the shell has exec'd the command; and when it -// still sees a node/python wrapper, the daemon resolves that ancestry -// asynchronously — observed to take >1.5s for real node-wrapped CLIs — so -// give its cache two bounded re-reads, not an open-ended retry loop. +// Why: settle after exec, then place the final generic retry beyond sequential +// 3s PowerShell and WMIC enrichment scans. const COMMAND_SETTLE_MS = 350 const VISIBLE_PTY_SETTLE_MS = 350 -const WRAPPER_RESOLVE_RETRY_DELAYS_MS = [1200, 3500] as const +const WRAPPER_RESOLVE_RETRY_DELAYS_MS = [1200, 6000] as const type ForegroundReadReason = 'command' | 'visible-pty' | 'command-finished' type PaneForegroundAgentTrackerDeps = { @@ -19,6 +19,8 @@ type PaneForegroundAgentTrackerDeps = { * their replayed OSC streams must not produce process evidence. */ isTrackablePtyId: (ptyId: string) => boolean readForegroundProcess: (ptyId: string) => Promise + /** Fresh, provider-owned evidence used only when input routing may change. */ + confirmForegroundProcess?: (ptyId: string) => Promise publish: (entry: PaneForegroundAgentEntry) => void /** True when the pane is otherwise known to run an agent (launchAgent, live * hook status). Lets a restored agent pane confirm — rather than trust — a @@ -27,7 +29,9 @@ type PaneForegroundAgentTrackerDeps = { /** Fired when a confirming read proves the foreground genuinely returned to a * shell (agent exited). Lets callers clear a stale agent-named tab title that * the shell never repaints. */ - onConfirmedShellForeground?: () => void + onConfirmedShellForeground?: (reason: 'visible-pty' | 'command-finished') => void + onCommandFinishedUnavailable?: () => void + onVisibleForegroundSettled?: (outcome: 'agent' | 'shell' | 'inconclusive') => void } /** @@ -39,9 +43,10 @@ type PaneForegroundAgentTrackerDeps = { * leak their own 133;D onto the main PTY. */ export function createPaneForegroundAgentTracker(deps: PaneForegroundAgentTrackerDeps): { - onVisiblePtyBound: () => void - onCommandStarted: () => void - onCommandFinished: () => void + onVisiblePtyBound: (expectsAgent?: boolean) => boolean + onCommandStarted: (expectedAgent?: TuiAgent | null) => void + /** True when pane identity must remain visible until an async shell confirmation. */ + onCommandFinished: () => boolean dispose: () => void } { let disposed = false @@ -53,6 +58,10 @@ export function createPaneForegroundAgentTracker(deps: PaneForegroundAgentTracke // OSC 133;D leaks onto the main PTY. For a pane an agent has owned, that D is // not proof the prompt returned, so confirm the foreground before clearing. let hasForegroundAgentEvidence = false + // Why: latch launch/hook evidence until confirmation finishes so cleanup + // cannot remove the identity that authorizes the bounded retry ladder. + let hasKnownAgentEvidence = false + let hasAgentExpectation = false const trackablePtyId = (): string | null => { const ptyId = deps.getPtyId() @@ -98,18 +107,35 @@ export function createPaneForegroundAgentTracker(deps: PaneForegroundAgentTracke return } let processName: string | null = null + const requiresRoutingConfirmation = + reason === 'command-finished' || + hasForegroundAgentEvidence || + hasKnownAgentEvidence || + hasAgentExpectation try { - processName = await deps.readForegroundProcess(ptyId) + processName = await (requiresRoutingConfirmation + ? (deps.confirmForegroundProcess ?? deps.readForegroundProcess)(ptyId) + : deps.readForegroundProcess(ptyId)) } catch { processName = null } - if (disposed || generation !== readGeneration) { + // Why: a pane key can be rebound while process inspection is pending; the + // old PTY's identity must never publish into its replacement session. + if (disposed || generation !== readGeneration || trackablePtyId() !== ptyId) { return } const recognized = recognizeAgentProcess(processName) if (recognized) { hasForegroundAgentEvidence = true - deps.publish({ agent: recognized.agent, shellForeground: false }) + hasAgentExpectation = false + deps.publish({ + agent: recognized.agent, + shellForeground: false, + ...(requiresRoutingConfirmation ? { routingTrusted: true } : {}) + }) + if (reason === 'visible-pty') { + deps.onVisibleForegroundSettled?.('agent') + } return } // Why: a shell seen here is NOT prompt proof — 133;D cancels pending reads, @@ -117,32 +143,72 @@ export function createPaneForegroundAgentTracker(deps: PaneForegroundAgentTracke // a nested one (sh/bash without integration); marking shell-foreground // would suppress live title identity. Only 133;D proves the prompt. const retryDelay = WRAPPER_RESOLVE_RETRY_DELAYS_MS[retryIndex] + const hasConfirmationExpectation = + hasForegroundAgentEvidence || hasKnownAgentEvidence || hasAgentExpectation + const shouldRetryExpectedIdentity = + hasConfirmationExpectation && (reason !== 'command-finished' || processName === null) const shouldRetry = retryDelay !== undefined && - processName && - (reason === 'command' || isAgentForegroundWrapperProcess(processName)) + (shouldRetryExpectedIdentity || + (processName !== null && + (reason === 'command' || isAgentForegroundWrapperProcess(processName)))) if (shouldRetry) { + // Why: provisional PowerShell may hide a live agent; the bounded ladder + // spans PowerShell-to-WMIC enrichment without becoming a polling loop. scheduleRead(retryDelay, retryIndex + 1, reason) return } if (reason === 'command') { + hasAgentExpectation = false deps.publish({ agent: null, shellForeground: false }) return } + if (reason === 'visible-pty') { + if ( + (hasForegroundAgentEvidence || hasKnownAgentEvidence) && + processName !== null && + isShellProcess(processName) + ) { + hasForegroundAgentEvidence = false + hasKnownAgentEvidence = false + hasAgentExpectation = false + deps.publish({ agent: null, shellForeground: true }) + deps.onConfirmedShellForeground?.(reason) + deps.onVisibleForegroundSettled?.('shell') + } else { + deps.onVisibleForegroundSettled?.('inconclusive') + } + return + } if (reason === 'command-finished') { + if (processName === null) { + // Why: unavailable inspection is not confirmed shell evidence; retire + // stale routing after the bounded D ladder without asserting shell truth. + hasForegroundAgentEvidence = false + hasKnownAgentEvidence = false + hasAgentExpectation = false + deps.publish({ agent: null, shellForeground: false }) + deps.onCommandFinishedUnavailable?.() + return + } + if ((hasForegroundAgentEvidence || hasKnownAgentEvidence) && !isShellProcess(processName)) { + return + } // Why: the 133;D fired AND the foreground shows no agent — together that is // real prompt proof, so the agent truly exited. Reset the evidence so the // pane's ordinary shell commands go back to the no-RPC finished path. hasForegroundAgentEvidence = false + hasKnownAgentEvidence = false + hasAgentExpectation = false deps.publish({ agent: null, shellForeground: true }) // Why: confirmed exit — let callers clear a stale agent title the shell // won't repaint (a plain `codex`/`grok` leaves its OSC title behind). - deps.onConfirmedShellForeground?.() + deps.onConfirmedShellForeground?.(reason) } } return { - onVisiblePtyBound() { + onVisiblePtyBound(expectsAgent = false) { // Why: command-start and command-finished reads own the exit decision; // visibility recovery is lower-authority and must never cancel them. if ( @@ -151,27 +217,39 @@ export function createPaneForegroundAgentTracker(deps: PaneForegroundAgentTracke scheduledReadReason === 'command-finished' || activeReadReason === 'command-finished' ) { - return + return false } cancelPendingRead() if (!trackablePtyId()) { - return + return false + } + if (expectsAgent || deps.hasKnownAgentIdentity?.() === true) { + hasKnownAgentEvidence = true } // Why: restored/manual agent panes can become visible while Codex is // already foreground, so no OSC 133 command-start event will seed the tab icon. scheduleRead(VISIBLE_PTY_SETTLE_MS, 0, 'visible-pty') + return true }, - onCommandStarted() { + onCommandStarted(expectedAgent = null) { cancelPendingRead() if (!trackablePtyId()) { return } - // Why: the foreground left the prompt the moment C fired — stale - // shell-foreground evidence must not clear the command that just started. + const alreadyHasKnownIdentity = deps.hasKnownAgentIdentity?.() === true + hasAgentExpectation = expectedAgent !== null + if (alreadyHasKnownIdentity) { + hasKnownAgentEvidence = true + } + // Why: every new command invalidates the previous byte-routing authority. + // Launch/hook identity remains only an expectation until fresh evidence. deps.publish({ agent: null, shellForeground: false }) scheduleRead(COMMAND_SETTLE_MS, 0, 'command') }, onCommandFinished() { + if (deps.hasKnownAgentIdentity?.() === true) { + hasKnownAgentEvidence = true + } // Why: a rapid 133;C→133;D pair cancels the command-start read before it // can identify the foreground — that pair is exactly a leaked nested-shell // command under a full-screen agent (or a fast real shell command), so on a @@ -182,25 +260,21 @@ export function createPaneForegroundAgentTracker(deps: PaneForegroundAgentTracke // a D that cancels one must re-confirm — never fast-path to shell, which the // sampleVisiblePaneForegroundAgent gate would then latch, permanently hiding // an idle reattached agent's icon (the "codex reattached at rest" bug). - const identityReadWasPending = scheduledReadReason !== null || activeReadReason !== null cancelPendingRead() if (!trackablePtyId()) { - return + return false } // Why: trust the 133;D and mark shell without an RPC only when nothing hints // at an agent — no prior agent evidence, no launch/hook identity, and no // identity read racing this finish. - if ( - !hasForegroundAgentEvidence && - deps.hasKnownAgentIdentity?.() !== true && - !identityReadWasPending - ) { + if (!hasForegroundAgentEvidence && !hasKnownAgentEvidence && !hasAgentExpectation) { deps.publish({ agent: null, shellForeground: true }) - return + return false } // Why: confirm the foreground before clearing — if the agent still owns it, // the read republishes its identity; only a genuine shell result clears it. scheduleRead(COMMAND_SETTLE_MS, 0, 'command-finished') + return true }, dispose() { disposed = true diff --git a/src/renderer/src/components/terminal-pane/pty-connection.test.ts b/src/renderer/src/components/terminal-pane/pty-connection.test.ts index fe1b2e51c30d..895fe1eb5031 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.test.ts @@ -13,10 +13,11 @@ import { } from './layout-serialization' import { buildFreshShellViewportBlankingSequence } from './terminal-restored-viewport' import { TERMINAL_PASTE_DIRECT_MAX_BYTES } from './terminal-paste-coordinator' +import { resolveWindowsShiftEnterEncodingForPane } from './terminal-windows-shift-enter' import type * as UseNotificationDispatchModule from './use-notification-dispatch' import { getEagerPtyBufferHandle } from './pty-dispatcher' import { makePaneKey } from '../../../../shared/stable-pane-id' -import type { TerminalLayoutSnapshot } from '../../../../shared/types' +import type { TerminalLayoutSnapshot, TuiAgent } from '../../../../shared/types' import { YOLO_TUI_AGENT_ARGS } from '../../../../shared/tui-agent-permissions' import { SETUP_AGENT_SEQUENCE_STARTUP_COMMAND_ENV } from '../../../../shared/setup-agent-sequencing' import { @@ -110,7 +111,13 @@ type StoreState = { activeWorktreeId: string | null tabsByWorktree: Record< string, - { id: string; ptyId: string | null; title?: string; launchAgent?: string }[] + { + id: string + ptyId: string | null + title?: string + launchAgent?: string + shellOverride?: string + }[] > ptyIdsByTabId?: Record terminalLayoutsByTabId?: Record @@ -177,7 +184,10 @@ type StoreState = { paneForegroundAgentByPaneKey: Record sleepingAgentSessionsByPaneKey: Record suppressedPtyExitIds: Record - agentLaunchConfigByPaneKey: Record + agentLaunchConfigByPaneKey: Record< + string, + { launchConfig: unknown; identity?: { agentType?: string } } + > getAgentLaunchConfigForStatusEntry: ReturnType getAgentLaunchConfigForStatusMetadata: ReturnType clearSleepingAgentSession: ReturnType @@ -196,6 +206,22 @@ type StoreState = { markAgentCompletionPaneUnread: ReturnType } +type WindowsShiftEnterPaneState = Parameters[0] + +function resolveMockPaneWindowsShiftEnterEncoding( + state: StoreState, + paneKey: string +): ReturnType { + return resolveWindowsShiftEnterEncodingForPane( + { + paneForegroundAgentByPaneKey: state.paneForegroundAgentByPaneKey, + agentLaunchConfigByPaneKey: + state.agentLaunchConfigByPaneKey as WindowsShiftEnterPaneState['agentLaunchConfigByPaneKey'] + }, + paneKey + ) +} + type ConnectCallbacks = { onData?: ( data: string, @@ -823,6 +849,7 @@ describe('connectPanePty', () => { reportGeometry: vi.fn(), getMainBufferSnapshot: vi.fn().mockResolvedValue(null), getForegroundProcess: vi.fn().mockResolvedValue(null), + confirmForegroundProcess: vi.fn().mockResolvedValue(null), hasChildProcesses: vi.fn().mockResolvedValue(false), write: vi.fn(), writeAccepted: vi.fn().mockResolvedValue(true), @@ -853,6 +880,9 @@ describe('connectPanePty', () => { addEventListener: vi.fn(), removeEventListener: vi.fn() } + vi.mocked(window.api.pty.confirmForegroundProcess).mockImplementation((id) => + window.api.pty.getForegroundProcess(id) + ) globalThis.requestAnimationFrame = vi.fn((callback: FrameRequestCallback) => { callback(0) return 1 @@ -4936,6 +4966,416 @@ describe('connectPanePty', () => { expect(mockStoreState.dropAgentStatus).not.toHaveBeenCalled() }) + it('routes a manually typed Droid only after foreground enrichment confirms it', async () => { + vi.useFakeTimers() + const { connectPanePty } = await import('./pty-connection') + const dataCallbackRef: { current: ((data: string) => void) | null } = { current: null } + const pane = createPane(1) + const ptyId = 'pty-manually-typed-droid' + const tabId = 'tab-manually-typed-droid' + const foregroundResults = ['powershell.exe', 'droid'] + vi.mocked(window.api.pty.confirmForegroundProcess).mockImplementation(async (id: string) => + id === ptyId ? (foregroundResults.shift() ?? 'droid') : null + ) + const transport = createMockTransport(ptyId) + transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => { + dataCallbackRef.current = callbacks.onData ?? null + return { id: ptyId } + }) + transportFactoryQueue.push(transport) + const paneKey = makePaneKey(tabId, LEAF_1) + + connectPanePty( + pane as never, + createManager(1) as never, + createDeps({ tabId, isVisibleRef: { current: false } }) as never + ) + await vi.advanceTimersByTimeAsync(20) + await flushAsyncTicks() + + sendTerminalInputThroughPane(pane, 'droid\r') + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter') + + dataCallbackRef.current?.('\x1b]133;C\x07') + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter') + await vi.advanceTimersByTimeAsync(350) + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter') + await vi.advanceTimersByTimeAsync(1200) + expect(mockStoreState.paneForegroundAgentByPaneKey[paneKey]).toEqual({ + agent: 'droid', + routingTrusted: true, + shellForeground: false + }) + }) + + it('confirms a manually typed Droid without OSC command boundaries', async () => { + vi.useFakeTimers() + const { connectPanePty } = await import('./pty-connection') + vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue('droid') + const pane = createPane(1) + const ptyId = 'pty-manual-droid-no-osc' + const tabId = 'tab-manual-droid-no-osc' + const paneKey = makePaneKey(tabId, LEAF_1) + transportFactoryQueue.push(createMockTransport(ptyId)) + + connectPanePty( + pane as never, + createManager(1) as never, + createDeps({ tabId, isVisibleRef: { current: false } }) as never + ) + await vi.advanceTimersByTimeAsync(20) + await flushAsyncTicks() + + sendTerminalInputThroughPane(pane, 'droid\r') + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter') + + await vi.advanceTimersByTimeAsync(350) + + expect(window.api.pty.confirmForegroundProcess).toHaveBeenCalledWith(ptyId) + expect(mockStoreState.paneForegroundAgentByPaneKey[paneKey]).toEqual({ + agent: 'droid', + routingTrusted: true, + shellForeground: false + }) + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('csi-u') + }) + + it('revokes trusted Droid after accepted no-OSC exit input until shell confirmation', async () => { + vi.useFakeTimers() + const { connectPanePty } = await import('./pty-connection') + vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue('cmd.exe') + const pane = createPane(1) + const ptyId = 'pty-droid-exit-no-osc' + const tabId = 'tab-droid-exit-no-osc' + const paneKey = makePaneKey(tabId, LEAF_1) + transportFactoryQueue.push(createMockTransport(ptyId)) + + connectPanePty(pane as never, createManager(1) as never, createDeps({ tabId }) as never) + await vi.advanceTimersByTimeAsync(20) + await flushAsyncTicks() + mockStoreState.paneForegroundAgentByPaneKey[paneKey] = { + agent: 'droid', + routingTrusted: true, + shellForeground: false + } + + sendTerminalInputThroughPane(pane, '\x03') + await flushAsyncTicks() + + expect(mockStoreState.paneForegroundAgentByPaneKey[paneKey]).toEqual({ + agent: 'droid', + shellForeground: false + }) + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter') + + await vi.advanceTimersByTimeAsync(350 + 1200 + 6000) + + expect(mockStoreState.paneForegroundAgentByPaneKey[paneKey]).toEqual({ + agent: null, + shellForeground: true + }) + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter') + }) + + it('never promotes typed Droid text when foreground enrichment is unavailable', async () => { + vi.useFakeTimers() + const { connectPanePty } = await import('./pty-connection') + vi.mocked(window.api.pty.confirmForegroundProcess) + .mockResolvedValueOnce(null) + .mockRejectedValueOnce(new Error('inspection unavailable')) + .mockResolvedValueOnce(null) + const dataCallbackRef: { current: ((data: string) => void) | null } = { current: null } + const pane = createPane(1) + const ptyId = 'pty-typed-droid-unavailable-start' + const tabId = 'tab-typed-droid-unavailable-start' + const paneKey = makePaneKey(tabId, LEAF_1) + const transport = createMockTransport(ptyId) + transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => { + dataCallbackRef.current = callbacks.onData ?? null + return { id: ptyId } + }) + transportFactoryQueue.push(transport) + + connectPanePty( + pane as never, + createManager(1) as never, + createDeps({ tabId, isVisibleRef: { current: false } }) as never + ) + await vi.advanceTimersByTimeAsync(20) + await flushAsyncTicks() + + sendTerminalInputThroughPane(pane, 'droid\r') + dataCallbackRef.current?.('\x1b]133;C\x07') + await vi.advanceTimersByTimeAsync(350) + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter') + + await vi.advanceTimersByTimeAsync(1200) + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter') + + await vi.advanceTimersByTimeAsync(5999) + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter') + await vi.advanceTimersByTimeAsync(1) + + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter') + }) + + it.each(['process', 'launch'] as const)( + 'does not let typed Droid input replace another live TUI %s identity', + async (identitySource) => { + vi.useFakeTimers() + const { connectPanePty } = await import('./pty-connection') + const dataCallbackRef: { current: ((data: string) => void) | null } = { current: null } + const pane = createPane(1) + const ptyId = `pty-antigravity-${identitySource}-typed-droid` + const tabId = `tab-antigravity-${identitySource}-typed-droid` + const paneKey = makePaneKey(tabId, LEAF_1) + const transport = createMockTransport(ptyId) + transport.connect.mockImplementation( + async ({ callbacks }: { callbacks: ConnectCallbacks }) => { + dataCallbackRef.current = callbacks.onData ?? null + return { id: ptyId } + } + ) + transportFactoryQueue.push(transport) + + connectPanePty( + pane as never, + createManager(1) as never, + createDeps({ tabId, isVisibleRef: { current: false } }) as never + ) + await vi.advanceTimersByTimeAsync(20) + await flushAsyncTicks() + if (identitySource === 'process') { + mockStoreState.paneForegroundAgentByPaneKey[paneKey] = { + agent: 'antigravity', + shellForeground: false + } + } else { + mockStoreState.agentLaunchConfigByPaneKey[paneKey] = { + launchConfig: { agentArgs: '', agentEnv: {} }, + identity: { agentType: 'antigravity' } + } + } + + sendTerminalInputThroughPane(pane, 'droid\r') + dataCallbackRef.current?.('\x1b]133;C\x07') + + expect(mockStoreState.paneForegroundAgentByPaneKey[paneKey]).toEqual({ + agent: null, + shellForeground: false + }) + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter') + } + ) + + it.each([ + ['SSH', 'ssh:conn@@pty-typed-droid', 'tab-ssh-typed-droid'], + ['remote runtime', 'remote:web-env-1@@pty-typed-droid', 'tab-remote-typed-droid'] + ])( + 'does not persist typed command process evidence for %s panes', + async (_label, ptyId, tabId) => { + vi.useFakeTimers() + const { connectPanePty } = await import('./pty-connection') + const dataCallbackRef: { current: ((data: string) => void) | null } = { current: null } + const pane = createPane(1) + const paneKey = makePaneKey(tabId, LEAF_1) + const transport = createMockTransport(ptyId) + transport.connect.mockImplementation( + async ({ callbacks }: { callbacks: ConnectCallbacks }) => { + dataCallbackRef.current = callbacks.onData ?? null + return { id: ptyId } + } + ) + transportFactoryQueue.push(transport) + + connectPanePty( + pane as never, + createManager(1) as never, + createDeps({ tabId, isVisibleRef: { current: false } }) as never + ) + await vi.advanceTimersByTimeAsync(20) + await flushAsyncTicks() + + sendTerminalInputThroughPane(pane, 'droid\r') + dataCallbackRef.current?.('\x1b]133;C\x07\x1b]133;D;0\x07') + + expect(mockStoreState.paneForegroundAgentByPaneKey[paneKey]).toBeUndefined() + expect(mockStoreState.setPaneForegroundAgent).not.toHaveBeenCalledWith( + paneKey, + expect.anything() + ) + } + ) + + it('keeps Droid routing visible through command-finished foreground confirmation', async () => { + vi.useFakeTimers() + const { connectPanePty } = await import('./pty-connection') + const getForegroundProcess = vi.mocked(window.api.pty.confirmForegroundProcess) + getForegroundProcess.mockResolvedValue('droid') + const dataCallbackRef: { current: ((data: string) => void) | null } = { current: null } + const ptyId = 'pty-droid-confirmation-window' + const transport = createMockTransport(ptyId) + transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => { + dataCallbackRef.current = callbacks.onData ?? null + return { id: ptyId } + }) + transportFactoryQueue.push(transport) + const paneKey = makePaneKey('tab-1', LEAF_1) + + connectPanePty( + createPane(1) as never, + createManager(1) as never, + createDeps({ isVisibleRef: { current: false } }) as never + ) + await vi.advanceTimersByTimeAsync(20) + await flushAsyncTicks() + mockStoreState.agentLaunchConfigByPaneKey[paneKey] = { + launchConfig: { agentArgs: '', agentEnv: {} }, + identity: { agentType: 'droid' } + } + mockStoreState.clearAgentLaunchConfig.mockImplementation((key: string) => { + delete mockStoreState.agentLaunchConfigByPaneKey[key] + }) + + const readsBeforeFinish = getForegroundProcess.mock.calls.length + dataCallbackRef.current?.('\x1b]133;D;0\x07') + expect(mockStoreState.clearAgentLaunchConfig).not.toHaveBeenCalled() + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter') + + await vi.advanceTimersByTimeAsync(350) + expect(mockStoreState.clearAgentLaunchConfig).not.toHaveBeenCalled() + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('csi-u') + + expect(getForegroundProcess).toHaveBeenCalledTimes(readsBeforeFinish + 1) + expect(mockStoreState.clearAgentLaunchConfig).not.toHaveBeenCalled() + expect(mockStoreState.paneForegroundAgentByPaneKey[paneKey]).toEqual({ + agent: 'droid', + routingTrusted: true, + shellForeground: false + }) + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('csi-u') + }) + + it('retires pane launch routing after one fresh scan confirms shell', async () => { + vi.useFakeTimers() + const { connectPanePty } = await import('./pty-connection') + vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue('powershell.exe') + const dataCallbackRef: { current: ((data: string) => void) | null } = { current: null } + const ptyId = 'pty-droid-confirmed-shell' + const transport = createMockTransport(ptyId) + transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => { + dataCallbackRef.current = callbacks.onData ?? null + return { id: ptyId } + }) + transportFactoryQueue.push(transport) + const paneKey = makePaneKey('tab-1', LEAF_1) + + connectPanePty( + createPane(1) as never, + createManager(1) as never, + createDeps({ isVisibleRef: { current: false } }) as never + ) + await vi.advanceTimersByTimeAsync(20) + await flushAsyncTicks() + mockStoreState.agentLaunchConfigByPaneKey[paneKey] = { + launchConfig: { agentArgs: '', agentEnv: {} }, + identity: { agentType: 'droid' } + } + mockStoreState.clearAgentLaunchConfig.mockImplementation((key: string) => { + delete mockStoreState.agentLaunchConfigByPaneKey[key] + }) + + dataCallbackRef.current?.('\x1b]133;D;0\x07') + await vi.advanceTimersByTimeAsync(350) + expect(mockStoreState.clearAgentLaunchConfig).toHaveBeenCalledExactlyOnceWith(paneKey) + expect(mockStoreState.paneForegroundAgentByPaneKey[paneKey]).toEqual({ + agent: null, + shellForeground: true + }) + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter') + }) + + it('retires stale routing after unavailable command-finish reads without asserting shell', async () => { + vi.useFakeTimers() + const { connectPanePty } = await import('./pty-connection') + vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue(null) + const dataCallbackRef: { current: ((data: string) => void) | null } = { current: null } + const ptyId = 'pty-droid-unavailable-finish' + const tabId = 'tab-droid-unavailable-finish' + const transport = createMockTransport(ptyId) + transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => { + dataCallbackRef.current = callbacks.onData ?? null + return { id: ptyId } + }) + transportFactoryQueue.push(transport) + const paneKey = makePaneKey(tabId, LEAF_1) + + connectPanePty( + createPane(1) as never, + createManager(1) as never, + createDeps({ tabId, isVisibleRef: { current: false } }) as never + ) + await vi.advanceTimersByTimeAsync(20) + await flushAsyncTicks() + mockStoreState.agentLaunchConfigByPaneKey[paneKey] = { + launchConfig: { agentArgs: '', agentEnv: {} }, + identity: { agentType: 'droid' } + } + mockStoreState.clearAgentLaunchConfig.mockImplementation((key: string) => { + delete mockStoreState.agentLaunchConfigByPaneKey[key] + }) + + dataCallbackRef.current?.('\x1b]133;D;0\x07') + await vi.advanceTimersByTimeAsync(350 + 1200 + 6000) + + expect(mockStoreState.clearAgentLaunchConfig).toHaveBeenCalledExactlyOnceWith(paneKey) + expect(mockStoreState.paneForegroundAgentByPaneKey[paneKey]).toEqual({ + agent: null, + shellForeground: false + }) + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter') + }) + + it('cancels deferred cleanup on a new command and retires identity at its later shell', async () => { + vi.useFakeTimers() + const { connectPanePty } = await import('./pty-connection') + vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue('powershell.exe') + const dataCallbackRef: { current: ((data: string) => void) | null } = { current: null } + const ptyId = 'pty-droid-superseded-confirmation' + const transport = createMockTransport(ptyId) + transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => { + dataCallbackRef.current = callbacks.onData ?? null + return { id: ptyId } + }) + transportFactoryQueue.push(transport) + const paneKey = makePaneKey('tab-1', LEAF_1) + connectPanePty( + createPane(1) as never, + createManager(1) as never, + createDeps({ isVisibleRef: { current: false } }) as never + ) + await vi.advanceTimersByTimeAsync(20) + await flushAsyncTicks() + mockStoreState.agentLaunchConfigByPaneKey[paneKey] = { + launchConfig: { agentArgs: '', agentEnv: {} }, + identity: { agentType: 'droid' } + } + mockStoreState.clearAgentLaunchConfig.mockImplementation((key: string) => { + delete mockStoreState.agentLaunchConfigByPaneKey[key] + }) + + dataCallbackRef.current?.('\x1b]133;D;0\x07') + dataCallbackRef.current?.('\x1b]133;C\x07') + expect(mockStoreState.clearAgentLaunchConfig).not.toHaveBeenCalled() + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter') + + dataCallbackRef.current?.('\x1b]133;D;0\x07') + await vi.advanceTimersByTimeAsync(350 + 1200 + 6000) + + expect(mockStoreState.clearAgentLaunchConfig).toHaveBeenCalledExactlyOnceWith(paneKey) + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter') + }) + it('flushes pending interrupt inference before dropping an exited foreground agent command', async () => { const { connectPanePty } = await import('./pty-connection') @@ -16966,6 +17406,8 @@ describe('connectPanePty', () => { describe('visible foreground agent sampling (perf)', () => { const VISIBLE_PTY_SETTLE_MS = 350 + const WRAPPER_RESOLVE_RETRY_MS = 1200 + const SECOND_WRAPPER_RETRY_MS = 6000 // Why: every connectPanePty binding in this file shares the tab-1/LEAF_1 pane // key, and an undisposed reattach binding elsewhere can resolve a foreground @@ -16976,9 +17418,19 @@ describe('connectPanePty', () => { ptyId?: string tabId?: string isVisibleRef?: { current: boolean } + launchConfig?: { + agentCommand?: string + agentArgs: string + agentEnv: Record + } + launchAgent?: TuiAgent } = {} ): Promise<{ - binding: { noteVisibilityResume: () => void } + binding: { + noteVisibilityResume: () => void + sampleForegroundAgentOnFocus: () => void + requestDroidReconfirmation: () => void + } deps: ReturnType transport: MockTransport cacheKey: string @@ -16986,9 +17438,19 @@ describe('connectPanePty', () => { const { connectPanePty } = await import('./pty-connection') const ptyId = args.ptyId ?? 'tab-pty' const tabId = args.tabId ?? `tab-${ptyId}` - const transport = createMockTransport(ptyId) + const hasReattachMetadata = args.launchConfig !== undefined || args.launchAgent !== undefined + const transport = createMockTransport(hasReattachMetadata ? null : ptyId) + let connectedPtyId: string | null = hasReattachMetadata ? null : ptyId + transport.getPtyId.mockImplementation(() => connectedPtyId) transport.connect.mockImplementation(async ({ sessionId }: { sessionId?: string }) => { - return sessionId ? { id: sessionId } : null + connectedPtyId = sessionId ?? null + return sessionId + ? { + id: sessionId, + ...(args.launchConfig ? { launchConfig: args.launchConfig } : {}), + ...(args.launchAgent ? { launchAgent: args.launchAgent } : {}) + } + : null }) transportFactoryQueue.push(transport) const deps = createDeps({ @@ -17001,7 +17463,11 @@ describe('connectPanePty', () => { createPane(1) as never, createManager(1) as never, deps as never - ) as unknown as { noteVisibilityResume: () => void } + ) as unknown as { + noteVisibilityResume: () => void + sampleForegroundAgentOnFocus: () => void + requestDroidReconfirmation: () => void + } await vi.advanceTimersByTimeAsync(20) await flushAsyncTicks(20) return { binding, deps, transport, cacheKey: makePaneKey(tabId, LEAF_1) } @@ -17084,6 +17550,92 @@ describe('connectPanePty', () => { expect(foregroundReadCallsFor(ptyId)).toHaveLength(0) }) + it('does not confirm foreground routing for a Windows WSL pane', async () => { + vi.useFakeTimers() + const restoreUserAgent = temporarilySetNavigatorUserAgent( + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' + ) + const ptyId = 'pty-wsl-no-confirm' + const tabId = `tab-${ptyId}` + mockStoreState.tabsByWorktree = { + 'wt-1': [{ id: tabId, ptyId, shellOverride: 'wsl.exe' }] + } + + try { + const { binding, cacheKey } = await connectRestoredPaneForForegroundSampling({ + ptyId, + tabId + }) + mockStoreState.paneForegroundAgentByPaneKey[cacheKey] = { + agent: 'droid', + routingTrusted: true, + shellForeground: false + } + + binding.sampleForegroundAgentOnFocus() + await vi.advanceTimersByTimeAsync(10_000) + + expect(window.api.pty.confirmForegroundProcess).not.toHaveBeenCalled() + } finally { + restoreUserAgent() + } + }) + + it('keeps trusted Droid routing through a rapid Shift+Enter burst', async () => { + vi.useFakeTimers() + const ptyId = 'pty-droid-shift-enter-burst' + const tabId = `tab-${ptyId}` + const { binding, cacheKey } = await connectRestoredPaneForForegroundSampling({ + ptyId, + tabId + }) + mockStoreState.paneForegroundAgentByPaneKey[cacheKey] = { + agent: 'droid', + routingTrusted: true, + shellForeground: false + } + mockStoreState.agentStatusByPaneKey[cacheKey] = { + state: 'working', + agentType: 'droid' + } + vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue('droid') + + binding.requestDroidReconfirmation() + await vi.advanceTimersByTimeAsync(200) + binding.requestDroidReconfirmation() + await vi.advanceTimersByTimeAsync(349) + + expect(mockStoreState.paneForegroundAgentByPaneKey[cacheKey]).toEqual({ + agent: 'droid', + routingTrusted: true, + shellForeground: false + }) + + await vi.advanceTimersByTimeAsync(1) + expect(mockStoreState.paneForegroundAgentByPaneKey[cacheKey]).toEqual({ + agent: 'droid', + shellForeground: false + }) + + await vi.advanceTimersByTimeAsync(350) + await flushAsyncTicks() + expect(window.api.pty.confirmForegroundProcess).toHaveBeenCalledWith(ptyId) + expect(mockStoreState.paneForegroundAgentByPaneKey[cacheKey]).toEqual({ + agent: 'droid', + routingTrusted: true, + shellForeground: false + }) + + binding.requestDroidReconfirmation() + await vi.advanceTimersByTimeAsync(700) + await flushAsyncTicks() + expect(mockStoreState.paneForegroundAgentByPaneKey[cacheKey]).toEqual({ + agent: 'droid', + routingTrusted: true, + shellForeground: false + }) + }) + it('samples once when an identityless hidden pane resumes visible', async () => { vi.useFakeTimers() const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) @@ -17101,20 +17653,162 @@ describe('connectPanePty', () => { expect(foregroundReadCallsFor(ptyId)).toEqual([[ptyId]]) }) - it('does not sample when launch metadata already supplies tab identity', async () => { + it('confirms daemon launch identity before restoring warm-reattach routing', async () => { vi.useFakeTimers() - const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) - getForegroundProcess.mockResolvedValue('codex') + vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue('droid') const ptyId = 'pty-launch-identity-no-sample' const tabId = `tab-${ptyId}` + mockStoreState.tabsByWorktree = { 'wt-1': [{ id: tabId, ptyId }] } + + const { cacheKey } = await connectRestoredPaneForForegroundSampling({ + ptyId, + tabId, + launchAgent: 'droid' + }) + expect(mockStoreState.registerAgentLaunchConfig).not.toHaveBeenCalled() + expect(mockStoreState.paneForegroundAgentByPaneKey[cacheKey]).toEqual({ + agent: 'droid', + shellForeground: false + }) + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, cacheKey)).toBe('alt-enter') + + await advanceVisibleForegroundRead() + + expect(mockStoreState.paneForegroundAgentByPaneKey[cacheKey]).toEqual({ + agent: 'droid', + routingTrusted: true, + shellForeground: false + }) + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, cacheKey)).toBe('csi-u') + }) + + it('retires stale daemon launch identity when warm reattach finds the shell', async () => { + vi.useFakeTimers() + vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue('powershell.exe') + const ptyId = 'pty-stale-daemon-launch-identity' + const tabId = `tab-${ptyId}` + mockStoreState.tabsByWorktree = { 'wt-1': [{ id: tabId, ptyId }] } + + const { cacheKey } = await connectRestoredPaneForForegroundSampling({ + ptyId, + tabId, + launchAgent: 'droid' + }) + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, cacheKey)).toBe('alt-enter') + + await vi.advanceTimersByTimeAsync( + VISIBLE_PTY_SETTLE_MS + WRAPPER_RESOLVE_RETRY_MS + SECOND_WRAPPER_RETRY_MS + ) + await flushAsyncTicks() + + expect(window.api.pty.confirmForegroundProcess).toHaveBeenCalledTimes(3) + expect(mockStoreState.paneForegroundAgentByPaneKey[cacheKey]).toEqual({ + agent: null, + shellForeground: true + }) + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, cacheKey)).toBe('alt-enter') + }) + + it('fails closed when a warm reattach has no persisted launch identity', async () => { + vi.useFakeTimers() + const ptyId = 'pty-reattach-missing-launch-identity' + const tabId = `tab-${ptyId}` + + const { cacheKey } = await connectRestoredPaneForForegroundSampling({ + ptyId, + tabId, + isVisibleRef: { current: false } + }) + + expect(mockStoreState.paneForegroundAgentByPaneKey[cacheKey]).toBeUndefined() + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, cacheKey)).toBe('alt-enter') + }) + + it('does not let persisted args spoof pane identity without an allowlisted command', async () => { + vi.useFakeTimers() + const ptyId = 'pty-unknown-persisted-launch' + const tabId = `tab-${ptyId}` + mockStoreState.tabsByWorktree = { 'wt-1': [{ id: tabId, ptyId }] } + mockStoreState.registerAgentLaunchConfig.mockImplementation( + (key: string, launchConfig: unknown, identity: { agentType?: string }): void => { + mockStoreState.agentLaunchConfigByPaneKey[key] = { launchConfig, identity } + } + ) + + const { cacheKey } = await connectRestoredPaneForForegroundSampling({ + ptyId, + tabId, + isVisibleRef: { current: false }, + launchConfig: { + agentCommand: 'custom-wrapper --agent droid', + agentArgs: 'droid', + agentEnv: {} + } + }) + await vi.advanceTimersByTimeAsync(300) + await flushAsyncTicks(20) + + expect( + mockStoreState.agentLaunchConfigByPaneKey[cacheKey]?.identity?.agentType + ).toBeUndefined() + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, cacheKey)).toBe('alt-enter') + }) + + it('does not re-scan stale launch metadata after the local ladder confirms shell', async () => { + vi.useFakeTimers() + const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) + getForegroundProcess.mockResolvedValue('powershell.exe') + const isVisibleRef = { current: false } + const ptyId = 'pty-stale-launch-shell-settled' + const tabId = `tab-${ptyId}` mockStoreState.tabsByWorktree = { - 'wt-1': [{ id: tabId, ptyId, launchAgent: 'codex' }] + 'wt-1': [{ id: tabId, ptyId, launchAgent: 'droid' }] } + mockStoreState.registerAgentLaunchConfig.mockImplementation( + (key: string, launchConfig: unknown, identity: { agentType?: string }): void => { + mockStoreState.agentLaunchConfigByPaneKey[key] = { launchConfig, identity } + } + ) + mockStoreState.clearAgentLaunchConfig.mockImplementation((key: string) => { + delete mockStoreState.agentLaunchConfigByPaneKey[key] + }) - await connectRestoredPaneForForegroundSampling({ ptyId, tabId }) + const { binding, cacheKey } = await connectRestoredPaneForForegroundSampling({ + ptyId, + tabId, + isVisibleRef, + launchConfig: { agentCommand: 'droid', agentArgs: '', agentEnv: {} } + }) + await vi.advanceTimersByTimeAsync(300) + await flushAsyncTicks(20) + // Launch metadata starts confirmation but is never byte-routing authority. + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, cacheKey)).toBe('alt-enter') + isVisibleRef.current = true + binding.noteVisibilityResume() await advanceVisibleForegroundRead() + await vi.advanceTimersByTimeAsync(WRAPPER_RESOLVE_RETRY_MS) + await vi.advanceTimersByTimeAsync(SECOND_WRAPPER_RETRY_MS) - expect(foregroundReadCallsFor(ptyId)).toHaveLength(0) + expect(foregroundReadCallsFor(ptyId).length).toBeGreaterThanOrEqual(3) + expect(mockStoreState.paneForegroundAgentByPaneKey[cacheKey]).toEqual({ + agent: null, + shellForeground: true + }) + expect(mockStoreState.clearAgentLaunchConfig).toHaveBeenCalledWith(cacheKey) + + mockStoreState.paneForegroundAgentByPaneKey[cacheKey] = { + agent: null, + shellForeground: false + } + expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, cacheKey)).toBe('alt-enter') + + vi.clearAllTimers() + const settledReadCount = foregroundReadCallsFor(ptyId).length + binding.sampleForegroundAgentOnFocus() + await vi.advanceTimersByTimeAsync( + VISIBLE_PTY_SETTLE_MS + WRAPPER_RESOLVE_RETRY_MS + SECOND_WRAPPER_RETRY_MS + ) + expect(foregroundReadCallsFor(ptyId)).toHaveLength(settledReadCount) }) it('does not sample when a live hook row already supplies pane identity', async () => { @@ -17142,6 +17836,7 @@ describe('connectPanePty', () => { const tabId = `tab-${ptyId}` mockStoreState.paneForegroundAgentByPaneKey[makePaneKey(tabId, LEAF_1)] = { agent: 'codex', + routingTrusted: true, shellForeground: false } @@ -17168,10 +17863,7 @@ describe('connectPanePty', () => { expect(foregroundReadCallsFor(ptyId)).toHaveLength(0) }) - it('re-samples a shell-marked pane a launch agent still owns', async () => { - // Why: a reattach or a full-screen agent's leaked nested-shell 133;D leaves - // shellForeground on a launchAgent pane, suppressing its icon. The launch - // metadata means an agent is expected, so re-read to recover its identity. + it('does not re-sample a shell-confirmed pane from stale launch metadata', async () => { vi.useFakeTimers() const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) getForegroundProcess.mockResolvedValue('codex') @@ -17188,19 +17880,17 @@ describe('connectPanePty', () => { const { cacheKey } = await connectRestoredPaneForForegroundSampling({ ptyId, tabId }) await advanceVisibleForegroundRead() - expect(foregroundReadCallsFor(ptyId)).toEqual([[ptyId]]) - expect(mockStoreState.setPaneForegroundAgent).toHaveBeenCalledWith(cacheKey, { - agent: 'codex', - shellForeground: false - }) + expect(foregroundReadCallsFor(ptyId)).toHaveLength(0) + expect(mockStoreState.setPaneForegroundAgent).not.toHaveBeenCalledWith( + cacheKey, + expect.anything() + ) }) - it('re-confirms rather than trusting a leaked 133;D that races the recovery read', async () => { - // Why: an idle reattached agent (no launchAgent/hook/title) schedules the - // visible-pty recovery read. A full-screen agent's nested shell then leaks a - // 133;D onto the main PTY. Trusting that D would mark the pane shell- - // foreground and the sample gate would latch it, hiding the agent icon - // forever — instead the leak must re-confirm the foreground. + it('fails closed when a leaked 133;D cancels identityless recovery', async () => { + // Why: a cached visible read has no routing authority. If a command + // boundary races it without an agent hint, cancel the sample and trust + // the shell marker instead of promoting stale process identity. vi.useFakeTimers() const { connectPanePty } = await import('./pty-connection') const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) @@ -17230,12 +17920,58 @@ describe('connectPanePty', () => { await advanceVisibleForegroundRead() + expect(mockStoreState.setPaneForegroundAgent).toHaveBeenCalledWith(cacheKey, { + agent: null, + shellForeground: true + }) + expect(foregroundReadCallsFor(ptyId)).toHaveLength(0) + }) + + it('re-confirms leaked 133;D after detach moved pane-scoped Droid identity', async () => { + vi.useFakeTimers() + const { connectPanePty } = await import('./pty-connection') + const getForegroundProcess = vi.mocked(window.api.pty.getForegroundProcess) + getForegroundProcess.mockResolvedValue('droid') + const ptyId = 'pty-detached-droid-leaked-d' + const tabId = 'tab-detached-droid' + const cacheKey = makePaneKey(tabId, LEAF_1) + const dataCallbackRef: { current: ((data: string) => void) | null } = { current: null } + const transport = createMockTransport(ptyId) + transport.connect.mockImplementation( + async ({ sessionId, callbacks }: { sessionId?: string; callbacks?: ConnectCallbacks }) => { + dataCallbackRef.current = callbacks?.onData ?? null + return sessionId ? { id: sessionId } : null + } + ) + transportFactoryQueue.push(transport) + mockStoreState.paneForegroundAgentByPaneKey[cacheKey] = { + agent: 'droid', + shellForeground: false + } + mockStoreState.agentLaunchConfigByPaneKey[cacheKey] = { + launchConfig: { agentArgs: '', agentEnv: {} }, + identity: { agentType: 'droid' } + } + const deps = createDeps({ + tabId, + restoredLeafId: LEAF_1, + restoredPtyIdByLeafId: { [LEAF_1]: ptyId } + }) + + connectPanePty(createPane(1) as never, createManager(1) as never, deps as never) + await vi.advanceTimersByTimeAsync(20) + await flushAsyncTicks(20) + dataCallbackRef.current?.('\x1b]133;D;0\x07') + await advanceVisibleForegroundRead() + + expect(foregroundReadCallsFor(ptyId)).toEqual([[ptyId]]) expect(mockStoreState.setPaneForegroundAgent).not.toHaveBeenCalledWith(cacheKey, { agent: null, shellForeground: true }) expect(mockStoreState.setPaneForegroundAgent).toHaveBeenCalledWith(cacheKey, { - agent: 'codex', + agent: 'droid', + routingTrusted: true, shellForeground: false }) }) diff --git a/src/renderer/src/components/terminal-pane/pty-connection.ts b/src/renderer/src/components/terminal-pane/pty-connection.ts index f93bba90068a..d1345865cf1a 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection.ts @@ -215,7 +215,7 @@ import { } from '../../../../shared/agent-process-recognition' import type { SetupSplitDirection, TuiAgent } from '../../../../shared/types' import { isWslUncPath } from '../../../../shared/wsl-paths' -import { TUI_AGENT_CONFIG } from '../../../../shared/tui-agent-config' +import { isTuiAgent, TUI_AGENT_CONFIG } from '../../../../shared/tui-agent-config' import { createDraftPasteReadyScanner } from '../../../../shared/draft-paste-ready-scanner' import { sendAgentDraftPasteContent } from '@/lib/agent-draft-paste-content' import { @@ -273,6 +273,7 @@ const CURSOR_HIDE_SEQUENCE = '\x1b[?25l' const TERMINAL_FOCUS_IN_SEQUENCE = '\x1b[I' const FOCUS_REPORTING_DISABLE_SEQUENCE = '\x1b[?1004l' const REATTACH_IDLE_AGENT_CURSOR_RESET_DELAY_MS = 250 +const SHIFT_ENTER_RECONFIRM_IDLE_MS = 350 const FOREGROUND_THROUGHPUT_IMMEDIATE_CHARS = 2048 const FOREGROUND_INTERACTIVE_REDRAW_CHARS = 128 * 1024 const FOREGROUND_INTERACTIVE_REDRAW_WINDOW_MS = 150 @@ -598,6 +599,8 @@ type PanePtyBinding = IDisposable & { * icon follows the active leaf, and a shell-marked entry on a still-running * agent pane has no OSC boundary left to correct it. */ sampleForegroundAgentOnFocus: () => void + /** Reconfirm after direct shortcut input, which bypasses PTY onData. */ + requestDroidReconfirmation: () => void reconcileIfSessionDead: (liveSessionIds: Set, snapshotRequestedAt?: number) => void reconcileIfSessionMissing: (hasPty: HasPty, livenessRequestedAt?: number) => void /** True when the hidden-delivery gate structurally manages the pane's @@ -966,6 +969,7 @@ export function connectPanePty( let pendingTerminalBellNotification = false let reattachIdleAgentCursorResetTimer: ReturnType | null = null let alternateScreenBackgroundRepaintTimer: ReturnType | null = null + let shiftEnterReconfirmTimer: ReturnType | null = null let synchronizedForegroundOutputActive = false // Why: tracks the keystroke proximity captured when the current synchronized // foreground frame opened, so a split end marker that lands after the redraw @@ -1146,11 +1150,27 @@ export function connectPanePty( metadata?: { launchToken?: string; launchAgent?: TuiAgent } ): void => { if (!effectiveLaunchConfig) { + if (metadata?.launchAgent) { + // Why: daemon launch identity can outlive the process while Orca is + // closed. Use it to request confirmation, never as current byte authority. + useAppStore.getState().setPaneForegroundAgent(cacheKey, { + agent: metadata.launchAgent, + shellForeground: false + }) + } return } + // Why: daemon reattach preserves the pane's exact launch command but not + // renderer metadata; recover only allowlisted command identity from it. + const persistedLaunchAgent = recognizeAgentProcessFromCommandLine( + effectiveLaunchConfig.agentCommand + )?.agent useAppStore.getState().registerAgentLaunchConfig(cacheKey, effectiveLaunchConfig, { agentType: - metadata?.launchAgent ?? paneStartup?.launchAgent ?? paneStartup?.initialAgentStatus?.agent, + metadata?.launchAgent ?? + paneStartup?.launchAgent ?? + paneStartup?.initialAgentStatus?.agent ?? + persistedLaunchAgent, ...((metadata?.launchToken ?? launchToken) ? { launchToken: metadata?.launchToken ?? launchToken } : {}), @@ -1177,6 +1197,8 @@ export function connectPanePty( let pendingShellCommandCursor = 0 let commandInferredPaneAgentGeneration = 0 let shellCommandInferenceSuspendedUntilCommandEnd = false + let startAcceptedInferredCommand = (_agent: TuiAgent): void => {} + let requestKnownDroidReconfirmation = (): void => {} const resetPendingShellCommandLine = (): void => { pendingShellCommandLine = '' pendingShellCommandCursor = 0 @@ -1184,11 +1206,22 @@ export function connectPanePty( const rememberCommandInferredPaneAgent = (): void => { const commandLine = pendingShellCommandLine.trim() resetPendingShellCommandLine() - const nextAgent = commandLine + const candidateAgent = commandLine ? (recognizeAgentProcessFromCommandLine(commandLine)?.agent ?? null) : null + const state = useAppStore.getState() + const registeredLaunchAgent = state.agentLaunchConfigByPaneKey[cacheKey]?.identity.agentType + // Why: input inside a live TUI can spell another agent command; process or + // pane-scoped launch ownership is stronger than typed shell inference. + const nextAgent = + state.paneForegroundAgentByPaneKey[cacheKey]?.agent || isTuiAgent(registeredLaunchAgent) + ? null + : candidateAgent commandInferredPaneAgent = nextAgent commandInferredPaneAgentGeneration += 1 + if (nextAgent) { + startAcceptedInferredCommand(nextAgent) + } } const clearCommandInferredPaneAgent = (): void => { commandInferredPaneAgent = null @@ -1404,6 +1437,16 @@ export function connectPanePty( return detectAgentStatusFromTitle(liveTitle ?? '') !== null } const observeAcceptedShellCommandInput = (data: string): void => { + if ( + data.includes('\r') || + data.includes('\n') || + data.includes('\x03') || + data.includes('\x04') + ) { + // Why: shells without OSC 133 give no command/exit boundary. An accepted + // submit or interrupt revokes only stale Droid routing and confirms once. + requestKnownDroidReconfirmation() + } if (commandInferredPaneAgent) { return } @@ -1786,8 +1829,12 @@ export function connectPanePty( const tab = (state.tabsByWorktree[deps.worktreeId] ?? []).find( (candidate) => candidate.id === deps.tabId ) + const registeredLaunchAgent = state.agentLaunchConfigByPaneKey[cacheKey]?.identity.agentType return Boolean( - tab?.launchAgent ?? paneStartup?.launchAgent ?? paneStartup?.initialAgentStatus?.agent + tab?.launchAgent ?? + paneStartup?.launchAgent ?? + paneStartup?.initialAgentStatus?.agent ?? + (isTuiAgent(registeredLaunchAgent) ? registeredLaunchAgent : undefined) ) } // Why: a launched/hook-known agent pane must confirm — not trust — a 133;D so a @@ -1795,7 +1842,12 @@ export function connectPanePty( // even on a restore where no command-start read has recorded evidence yet. const paneHasKnownAgentIdentity = (): boolean => { const state = useAppStore.getState() - return paneHasLiveHookAgentIcon(state) || paneExpectsLaunchAgent(state) + const registeredLaunchAgent = state.agentLaunchConfigByPaneKey[cacheKey]?.identity.agentType + return ( + Boolean(state.paneForegroundAgentByPaneKey[cacheKey]?.agent) || + paneHasLiveHookAgentIcon(state) || + isTuiAgent(registeredLaunchAgent) + ) } // Why: a plain `codex`/`grok` sets its OSC title and the shell never repaints // it on exit, so a confirmed return-to-shell must clear a title that still @@ -1817,13 +1869,55 @@ export function connectPanePty( deps.updateTabTitle(deps.tabId, neutralTitle) } } + let deferredCommandFinishedStatusDrop: (() => void) | null = null + let visibleForegroundSamplePending = false + let visibleForegroundSampleSettled = false + const settleDeferredCommandFinishedStatusDrop = (): void => { + const dropStatus = deferredCommandFinishedStatusDrop + deferredCommandFinishedStatusDrop = null + dropStatus?.() + } + const isForegroundTrackingAllowed = (id: string): boolean => { + if (isRemoteRuntimePtyId(id) || parseAppSshPtyId(id) !== null) { + return false + } + if (!navigator.userAgent.includes('Windows')) { + return true + } + const state = useAppStore.getState() + const tab = (state.tabsByWorktree[deps.worktreeId] ?? []).find( + (candidate) => candidate.id === deps.tabId + ) + // Why: WSL and remote-runtime panes can never authorize native ConPTY + // bytes, so do not pay for Windows process scans that cannot affect routing. + return isLocalNativeWindowsConpty({ + userAgent: navigator.userAgent, + connectionId: getConnectionId(deps.worktreeId) ?? null, + cwd: deps.cwd, + shellOverride: tab?.shellOverride, + executionHostId: getExecutionHostIdForWorktree(state, deps.worktreeId) + }) + } const paneForegroundAgentTracker = createPaneForegroundAgentTracker({ getPtyId: () => transport.getPtyId(), - isTrackablePtyId: (id) => !isRemoteRuntimePtyId(id) && parseAppSshPtyId(id) === null, + isTrackablePtyId: isForegroundTrackingAllowed, readForegroundProcess: (id) => window.api.pty.getForegroundProcess(id), + confirmForegroundProcess: (id) => window.api.pty.confirmForegroundProcess(id), publish: (entry) => useAppStore.getState().setPaneForegroundAgent(cacheKey, entry), hasKnownAgentIdentity: paneHasKnownAgentIdentity, - onConfirmedShellForeground: clearStaleAgentTabTitleOnConfirmedShell + onConfirmedShellForeground: (reason) => { + clearStaleAgentTabTitleOnConfirmedShell() + if (reason === 'visible-pty') { + useAppStore.getState().clearAgentLaunchConfig(cacheKey) + return + } + settleDeferredCommandFinishedStatusDrop() + }, + onCommandFinishedUnavailable: settleDeferredCommandFinishedStatusDrop, + onVisibleForegroundSettled: (outcome) => { + visibleForegroundSamplePending = false + visibleForegroundSampleSettled = outcome !== 'inconclusive' + } }) // Why: one command-finished policy whether the signal arrives as bytes // (remote PTYs, kill switch off) or as a main-derived pty:sideEffect fact — @@ -1831,66 +1925,101 @@ export function connectPanePty( // identical across authority modes. const handleCommandFinished = (_bestEffortExitCode: number | null): void => { clearCommandInferredPaneAgentAfterPtySideEffects() - paneForegroundAgentTracker.onCommandFinished() + visibleForegroundSamplePending = false + const shouldDeferStatusDrop = paneForegroundAgentTracker.onCommandFinished() // Why: the finished command may have moved HEAD or the index (e.g. // `git checkout`); nudge git UI now instead of waiting for a poll. dispatchTerminalCommandFinishedEvent(deps.worktreeId) const state = useAppStore.getState() const entry = state.agentStatusByPaneKey[cacheKey] const inferenceResult = flushPendingInterruptInference() - if (inferenceResult === true) { - // Why: OSC 133 D means the foreground shell command exited. If an - // interrupt was inferred first, drop only when the current interrupted - // row is still the same turn; otherwise a killed OpenCode CLI leaves a - // stale "interrupted" row even though the process is gone. - dropCommandFinishedStatusIfSameTurn(entry, { allowInferredInterrupt: true }) - return - } - if (inferenceResult instanceof Promise) { - void inferenceResult.then((applied) => { - dropCommandFinishedStatusIfSameTurn(entry, { - allowInferredInterrupt: applied === true + const dropStatus = (): void => { + if (inferenceResult === true) { + dropCommandFinishedStatusIfSameTurn(entry, { allowInferredInterrupt: true }) + return + } + if (inferenceResult instanceof Promise) { + void inferenceResult.then((applied) => { + dropCommandFinishedStatusIfSameTurn(entry, { + allowInferredInterrupt: applied === true + }) }) - }) + return + } + dropCommandFinishedStatusIfSameTurn(entry) + } + if (shouldDeferStatusDrop) { + // Why: keep the concrete pane identity routable while the local process + // check distinguishes a leaked nested-shell D from a genuine agent exit. + deferredCommandFinishedStatusDrop = dropStatus return } - // Why: OSC 133 D marks the foreground shell command exiting. Remove the - // row without retaining a done snapshot; this section represents a live - // agent process, and the shell prompt means that process is gone. - dropCommandFinishedStatusIfSameTurn(entry) + deferredCommandFinishedStatusDrop = null + dropStatus() } - const sampleVisiblePaneForegroundAgent = (): void => { - if (!deps.isVisibleRef.current) { + const sampleVisiblePaneForegroundAgent = (forceRoutingConfirmation = false): void => { + if ( + !deps.isVisibleRef.current || + visibleForegroundSamplePending || + visibleForegroundSampleSettled + ) { return } const state = useAppStore.getState() const foreground = state.paneForegroundAgentByPaneKey[cacheKey] - // Why: live process identity already paints the icon — nothing to read. - if (foreground?.agent) { + // Why: a daemon reattach may restore display identity without current + // routing authority. Only fresh evidence can suppress its confirmation. + if (foreground?.agent && foreground.routingTrusted === true) { return } - if (paneHasLiveHookAgentIcon(state)) { + if (!forceRoutingConfirmation && paneHasLiveHookAgentIcon(state)) { return } const expectsAgent = paneExpectsLaunchAgent(state) - // Why: with no shell mark yet, launchAgent bootstrap already paints the icon, - // so a read is pointless. Otherwise probe the foreground: a shell mark (from a - // reattach or a full-screen agent's leaked nested-shell 133;D) can hide a - // still-running agent the launch/hook identity says is expected, which no - // later 133;C will reseed. A genuinely idle shell just returns a shell name - // and publishes nothing, so the probe is self-limiting. - if (!foreground?.shellForeground && expectsAgent) { + // Why: a completed local process ladder is stronger than stale tab/startup + // launch metadata. Command-start clears this mark if the pane becomes busy. + if (foreground?.shellForeground) { return } - // Why: a 133;D already proved this pane is back at a shell prompt; with no - // agent expectation there is nothing to recover, so trust it and don't re-read. - if (foreground?.shellForeground && !expectsAgent) { + // Why: tab launch metadata can leak across split panes; rebuild pane-scoped + // identity from local process state, with remote/SSH excluded by the tracker. + visibleForegroundSamplePending = paneForegroundAgentTracker.onVisiblePtyBound(expectsAgent) + } + startAcceptedInferredCommand = (agent) => { + paneForegroundAgentTracker.onCommandStarted(agent) + } + requestKnownDroidReconfirmation = () => { + const foreground = useAppStore.getState().paneForegroundAgentByPaneKey[cacheKey] + // Why: daemon reattach/launch metadata is display-only until a live + // provider read confirms it. Submit/interrupt/title-exit evidence must + // revoke that launch-only hint too, otherwise Shift+Enter can route bytes + // to a Droid that already exited before confirmation ever ran. + if (foreground?.agent !== 'droid') { return } - paneForegroundAgentTracker.onVisiblePtyBound() + // Why: cmd.exe and Git Bash have no OSC command boundaries. Keep the icon + // as a hint, but revoke bytes until one current provider confirmation lands. + useAppStore.getState().setPaneForegroundAgent(cacheKey, { + agent: 'droid', + shellForeground: false + }) + visibleForegroundSamplePending = false + visibleForegroundSampleSettled = false + // Why: hook rows can suppress display-only sampling, but cannot restore + // byte authority after this function explicitly revoked routing trust. + sampleVisiblePaneForegroundAgent(true) } const commandLifecycle = createTerminalCommandLifecycle({ - onCommandStarted: () => paneForegroundAgentTracker.onCommandStarted(), + onCommandStarted: () => { + // Why: a new command invalidates cleanup waiting on the previous D; only + // a later confirmed shell boundary may retire this pane's live identity. + deferredCommandFinishedStatusDrop = null + visibleForegroundSamplePending = false + visibleForegroundSampleSettled = false + // Why: typed commands can be aliases, so they only widen the bounded + // process-confirmation window; they never become routing evidence. + paneForegroundAgentTracker.onCommandStarted(commandInferredPaneAgent) + }, onCommandFinished: handleCommandFinished }) // Why: the xterm OSC 133 swallow is rendering hygiene, not a side effect — @@ -2849,6 +2978,7 @@ export function connectPanePty( const onAgentExited = (): void => { clearSuppressedTitleSideEffects() clearCommandInferredPaneAgent() + requestKnownDroidReconfirmation() // Why: when the terminal title reverts to a plain shell (e.g., "bash", "zsh"), // the agent has exited. Clear any running cache timer so the sidebar doesn't // show a stale countdown for a tab that no longer has an active Claude session. @@ -6259,7 +6389,11 @@ export function connectPanePty( } registerEffectiveLaunchConfig(connectResult?.launchConfig, { ...(coldRestoreStartup ? { launchToken: coldRestoreStartup.launchToken } : {}), - ...(coldRestoreStartup ? { launchAgent: coldRestoreStartup.agent } : {}) + ...(connectResult?.launchAgent + ? { launchAgent: connectResult.launchAgent } + : coldRestoreStartup + ? { launchAgent: coldRestoreStartup.agent } + : {}) }) if (connectResult?.sessionExpired) { if (staleSessionId) { @@ -7094,6 +7228,7 @@ export function connectPanePty( noteVisibilityResume() { ptySizeReassertion.request({ fit: false }) consumeHibernatedAgentWake() + requestKnownDroidReconfirmation() sampleVisiblePaneForegroundAgent() }, // Why: mobile wake reaches this pane while it stays hidden on the desktop, so @@ -7138,8 +7273,21 @@ export function connectPanePty( return null }, sampleForegroundAgentOnFocus() { + requestKnownDroidReconfirmation() sampleVisiblePaneForegroundAgent() }, + requestDroidReconfirmation() { + if (shiftEnterReconfirmTimer !== null) { + clearTimeout(shiftEnterReconfirmTimer) + } + // Why: preserve rapid multiline input inside a confirmed Droid composer; + // confirm only after the Shift+Enter burst goes idle. + shiftEnterReconfirmTimer = setTimeout(() => { + shiftEnterReconfirmTimer = null + requestKnownDroidReconfirmation() + sampleVisiblePaneForegroundAgent() + }, SHIFT_ENTER_RECONFIRM_IDLE_MS) + }, reconcileIfSessionDead, reconcileIfSessionMissing, dispose() { @@ -7166,6 +7314,10 @@ export function connectPanePty( interruptInference.dispose() clearTitleOnlyInterruptTimer() clearCommandCodeOutputDoneTimer() + if (shiftEnterReconfirmTimer !== null) { + clearTimeout(shiftEnterReconfirmTimer) + shiftEnterReconfirmTimer = null + } // Why: actively resolve any in-flight passphrase-gate waits so their // zustand subscribers + async IIFEs don't hang for the rest of the // session when the pane is torn down before SSH state changes. @@ -7238,6 +7390,9 @@ export function connectPanePty( pendingGeometryReportRaf = null } commandLifecycle.dispose() + deferredCommandFinishedStatusDrop = null + visibleForegroundSamplePending = false + visibleForegroundSampleSettled = false paneForegroundAgentTracker.dispose() agentCompletionCoordinator.dispose() } diff --git a/src/renderer/src/components/terminal-pane/pty-transport-types.ts b/src/renderer/src/components/terminal-pane/pty-transport-types.ts index e5ab8c38cf3b..408920019634 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport-types.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport-types.ts @@ -36,6 +36,7 @@ export type LocalPtySessionMetadata = { cwd?: string; shellOverride?: string } export type PtyConnectResult = { id: string + launchAgent?: TuiAgent launchConfig?: SleepingAgentLaunchConfig snapshot?: string snapshotCols?: number diff --git a/src/renderer/src/components/terminal-pane/pty-transport.test.ts b/src/renderer/src/components/terminal-pane/pty-transport.test.ts index b676fd2fdfee..ff4ffd5faa4b 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport.test.ts @@ -1155,6 +1155,7 @@ describe('createIpcPtyTransport', () => { const spawnMock = vi.fn().mockResolvedValue({ id: 'pty-reattach', isReattach: true, + launchAgent: 'droid', snapshot: 'snapshot data', snapshotCols: 132, snapshotRows: 43 @@ -1192,6 +1193,7 @@ describe('createIpcPtyTransport', () => { expect(result).toEqual({ id: 'pty-reattach', + launchAgent: 'droid', snapshot: 'snapshot data', snapshotCols: 132, snapshotRows: 43, @@ -1202,6 +1204,30 @@ describe('createIpcPtyTransport', () => { }) }) + it('drops an unknown daemon launch identity from the connection result', async () => { + const { createIpcPtyTransport } = await import('./pty-transport') + const spawn = window.api.pty.spawn as unknown as ReturnType + spawn.mockResolvedValueOnce({ + id: 'pty-unknown-launch-agent', + isReattach: true, + launchAgent: 'not-an-agent' + }) + + const result = await createIpcPtyTransport({}).connect({ url: '', callbacks: {} }) + + expect(result).toEqual({ + id: 'pty-unknown-launch-agent', + snapshot: undefined, + snapshotCols: undefined, + snapshotRows: undefined, + isAlternateScreen: undefined, + sessionExpired: undefined, + coldRestore: undefined, + replay: undefined, + pendingEscapeTailAnsi: undefined + }) + }) + it('threads the daemon pendingEscapeTailAnsi through the reattach connect result (#7329)', async () => { // Why: the local daemon ships the mid-escape tail on the spawn/reattach // result; dropping it here silently regressed the local half of #7329 diff --git a/src/renderer/src/components/terminal-pane/pty-transport.ts b/src/renderer/src/components/terminal-pane/pty-transport.ts index f2c107e441be..cffa3def6fab 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport.ts @@ -36,6 +36,7 @@ import { type ProcessedAgentStatusChunk } from '../../../../shared/agent-status-osc' import { extractIpcErrorMessage } from '@/lib/ipc-error' +import { isTuiAgent } from '../../../../shared/tui-agent-config' // Re-export public API so existing consumers keep working. export { @@ -704,6 +705,9 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra ...(telemetry ? { telemetry } : {}) }) const spawnResult = result as PtyConnectResult & { isReattach?: boolean } + const resultLaunchAgent = isTuiAgent(spawnResult.launchAgent) + ? spawnResult.launchAgent + : undefined // If destroyed while spawn was in flight, kill the new pty and bail if (destroyed) { @@ -733,6 +737,7 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra if (spawnResult.isReattach || spawnResult.coldRestore || spawnResult.sessionExpired) { return { id: spawnResult.id, + ...(resultLaunchAgent ? { launchAgent: resultLaunchAgent } : {}), ...(spawnResult.launchConfig ? { launchConfig: spawnResult.launchConfig } : {}), snapshot: spawnResult.snapshot, snapshotCols: spawnResult.snapshotCols, @@ -744,9 +749,10 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra pendingEscapeTailAnsi: spawnResult.pendingEscapeTailAnsi } satisfies PtyConnectResult } - if (spawnResult.launchConfig || spawnResult.startupCwdFallback) { + if (resultLaunchAgent || spawnResult.launchConfig || spawnResult.startupCwdFallback) { return { id: spawnResult.id, + ...(resultLaunchAgent ? { launchAgent: resultLaunchAgent } : {}), ...(spawnResult.launchConfig ? { launchConfig: spawnResult.launchConfig } : {}), ...(spawnResult.startupCwdFallback ? { startupCwdFallback: spawnResult.startupCwdFallback } diff --git a/src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts b/src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts index a92e03cce8cd..3d5108da6181 100644 --- a/src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.test.ts @@ -49,7 +49,7 @@ function splitLayout(): TerminalLayoutSnapshot { } } -function createTerminalTab(id: string, ptyId: string | null): TerminalTab { +function createTerminalTab(id: string, ptyId: string | null, shellOverride?: string): TerminalTab { return { id, ptyId, @@ -59,13 +59,15 @@ function createTerminalTab(id: string, ptyId: string | null): TerminalTab { customTitle: null, color: null, sortOrder: 1, - createdAt: 1 + createdAt: 1, + ...(shellOverride !== undefined ? { shellOverride } : {}) } } function createStore( layout: TerminalLayoutSnapshot = splitLayout(), - targetTabOrder: string[] = [EXISTING_TAB_1, EXISTING_TAB_2] + targetTabOrder: string[] = [EXISTING_TAB_1, EXISTING_TAB_2], + sourceShellOverride = 'powershell.exe' ): TerminalPaneTabDetachStore { const store = { createTab: vi.fn((_worktreeId, _targetGroupId, _shellOverride, options) => { @@ -107,6 +109,9 @@ function createStore( } }), syncPaneDetachPtyOwnership: vi.fn(), + tabsByWorktree: { + [WORKTREE_ID]: [createTerminalTab(SOURCE_TAB_ID, 'pty-left', sourceShellOverride)] + }, terminalLayoutsByTabId: { [SOURCE_TAB_ID]: layout } @@ -242,7 +247,7 @@ describe('detachTerminalPaneToTab', () => { expect(result?.ptyId).toBe('remote:env-1@@terminal-1') expect(manager.detachPaneForExternalMove).toHaveBeenCalledWith(2) - expect(store.createTab).toHaveBeenCalledWith(WORKTREE_ID, TARGET_GROUP_ID, undefined, { + expect(store.createTab).toHaveBeenCalledWith(WORKTREE_ID, TARGET_GROUP_ID, 'powershell.exe', { activate: true, initialPtyId: 'remote:env-1@@terminal-1', recordInteraction: true @@ -262,6 +267,7 @@ describe('detachTerminalPaneToTab', () => { titlesByLeafId: { [LEAF_2]: 'remote shell' } }) expect(store.syncPaneDetachPtyOwnership).toHaveBeenCalledWith({ + detachedLeafId: LEAF_2, detachedPtyId: 'remote:env-1@@terminal-1', sourceLayout: { root: { type: 'leaf', leafId: LEAF_1 }, @@ -277,6 +283,35 @@ describe('detachTerminalPaneToTab', () => { expect(persistLayoutSnapshot).toHaveBeenCalled() }) + it.each(['powershell.exe', 'wsl.exe'])( + 'preserves the moved PTY shell override when the source uses %s', + (shellOverride) => { + const store = createStore(splitLayout(), [EXISTING_TAB_1], shellOverride) + const manager = { + getPanes: vi.fn(() => [{ id: 1 }, { id: 2 }]), + getLeafId: vi.fn(() => LEAF_1), + detachPaneForExternalMove: vi.fn(() => true) + } + + detachTerminalPaneToTab({ + getStore: () => store, + manager, + persistLayoutSnapshot: vi.fn(), + sourcePaneId: 1, + sourceTabId: SOURCE_TAB_ID, + targetGroupId: TARGET_GROUP_ID, + worktreeId: WORKTREE_ID + }) + + expect(store.createTab).toHaveBeenCalledWith( + WORKTREE_ID, + TARGET_GROUP_ID, + shellOverride, + expect.objectContaining({ initialPtyId: 'pty-left' }) + ) + } + ) + it('syncs PTY ownership when the primary source pane is detached', () => { const store = createStore() const manager = { @@ -305,6 +340,7 @@ describe('detachTerminalPaneToTab', () => { titlesByLeafId: { [LEAF_2]: 'remote shell' } }) expect(store.syncPaneDetachPtyOwnership).toHaveBeenCalledWith({ + detachedLeafId: LEAF_1, detachedPtyId: 'pty-left', sourceLayout: { root: { type: 'leaf', leafId: LEAF_2 }, diff --git a/src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.ts b/src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.ts index 26f3d5996e3c..7cbc9c095f1b 100644 --- a/src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.ts +++ b/src/renderer/src/components/terminal-pane/terminal-pane-tab-detach.ts @@ -14,6 +14,7 @@ export type TerminalPaneTabDetachStore = Pick< | 'setActiveTabType' | 'setTabLayout' | 'syncPaneDetachPtyOwnership' + | 'tabsByWorktree' | 'terminalLayoutsByTabId' > @@ -278,7 +279,10 @@ export function detachTerminalPaneToTab(args: { } const latestStore = args.getStore() - const tab = latestStore.createTab(args.worktreeId, args.targetGroupId, undefined, { + const sourceShellOverride = latestStore.tabsByWorktree[args.worktreeId]?.find( + (candidate) => candidate.id === args.sourceTabId + )?.shellOverride + const tab = latestStore.createTab(args.worktreeId, args.targetGroupId, sourceShellOverride, { activate: true, initialPtyId: ptyId ?? undefined, recordInteraction: true @@ -294,6 +298,7 @@ export function detachTerminalPaneToTab(args: { afterCreateStore.setTabLayout(args.sourceTabId, detached.sourceLayout) afterCreateStore.setTabLayout(tab.id, detachedLayout) afterCreateStore.syncPaneDetachPtyOwnership({ + detachedLeafId: sourceLeafId, detachedPtyId: ptyId, sourceLayout: detached.sourceLayout, sourceTabId: args.sourceTabId, diff --git a/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts b/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts index 8bf8159d9d17..a99299514494 100644 --- a/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts +++ b/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { resolveTerminalShortcutAction, type TerminalShortcutEvent @@ -89,7 +89,9 @@ describe('resolveTerminalShortcutAction', () => { }) }) - it('uses the Codex-compatible Shift+Enter sequence on Windows', () => { + it('uses the Codex-compatible Shift+Enter sequence on Windows win32-input-mode panes', () => { + // Default and explicit legacy encodings both keep Codex-on-PowerShell + // newlining instead of ignoring the chord. expect( resolveTerminalShortcutAction( event({ key: 'Enter', code: 'Enter', shiftKey: true }), @@ -102,6 +104,140 @@ describe('resolveTerminalShortcutAction', () => { type: 'sendInput', data: '\x1b\r' }) + expect( + resolveTerminalShortcutAction( + event({ key: 'Enter', code: 'Enter', shiftKey: true }), + false, + 'false', + 0, + true, + undefined, + undefined, + undefined, + undefined, + () => 'alt-enter' + ) + ).toEqual({ type: 'sendInput', data: '\x1b\r' }) + }) + + it('sends CSI-u Shift+Enter to Windows panes whose active agent requires it (#7620)', () => { + // Why: droid parses CSI-u directly and treats the Alt+Enter byte as a plain + // Enter that submits, so its pane capability must produce `\x1b[13;2u`. + expect( + resolveTerminalShortcutAction( + event({ key: 'Enter', code: 'Enter', shiftKey: true }), + false, + 'false', + 0, + true, + undefined, + undefined, + undefined, + undefined, + () => 'csi-u' + ) + ).toEqual({ type: 'sendInput', data: '\x1b[13;2u' }) + }) + + it('preserves the Windows fallback for SSH, WSL, and remote panes', () => { + // Why: a Windows client cannot safely infer a remote peer's decoder, so the + // local Droid exception must not broaden main's existing remote behavior. + const isLocalWindowsConptyPane = vi.fn(() => false) + const getWindowsShiftEnterEncoding = vi.fn(() => 'csi-u' as const) + for (let index = 0; index < 2; index += 1) { + expect( + resolveTerminalShortcutAction( + event({ key: 'Enter', code: 'Enter', shiftKey: true }), + false, + 'false', + 0, + true, + undefined, + isLocalWindowsConptyPane, + undefined, + undefined, + getWindowsShiftEnterEncoding + ) + ).toEqual({ type: 'sendInput', data: '\x1b\r' }) + } + expect(isLocalWindowsConptyPane).toHaveBeenCalledTimes(2) + expect(getWindowsShiftEnterEncoding).not.toHaveBeenCalled() + }) + + it('always uses CSI-u Shift+Enter off Windows regardless of Windows encoding', () => { + for (const encoding of [() => 'csi-u' as const, () => 'alt-enter' as const, undefined]) { + expect( + resolveTerminalShortcutAction( + event({ key: 'Enter', code: 'Enter', shiftKey: true }), + false, + 'false', + 0, + false, + undefined, + undefined, + undefined, + undefined, + encoding + ) + ).toEqual({ type: 'sendInput', data: '\x1b[13;2u' }) + } + }) + + it('keeps ConPTY and agent lookups off unrelated keystrokes', () => { + const isLocalWindowsConptyPane = vi.fn(() => true) + const getWindowsShiftEnterEncoding = vi.fn(() => 'csi-u' as const) + + expect( + resolveTerminalShortcutAction( + event({ key: 'a', code: 'KeyA' }), + false, + 'false', + 0, + true, + undefined, + isLocalWindowsConptyPane, + undefined, + undefined, + getWindowsShiftEnterEncoding + ) + ).toBeNull() + expect(isLocalWindowsConptyPane).not.toHaveBeenCalled() + expect(getWindowsShiftEnterEncoding).not.toHaveBeenCalled() + + expect( + resolveTerminalShortcutAction( + event({ key: 'Enter', code: 'Enter', shiftKey: true }), + false, + 'false', + 0, + true, + undefined, + isLocalWindowsConptyPane, + undefined, + undefined, + getWindowsShiftEnterEncoding + ) + ).toEqual({ type: 'sendInput', data: '\x1b[13;2u' }) + expect(isLocalWindowsConptyPane).toHaveBeenCalledTimes(1) + expect(getWindowsShiftEnterEncoding).toHaveBeenCalledTimes(1) + + isLocalWindowsConptyPane.mockReturnValue(false) + expect( + resolveTerminalShortcutAction( + event({ key: 'Enter', code: 'Enter', shiftKey: true }), + false, + 'false', + 0, + true, + undefined, + isLocalWindowsConptyPane, + undefined, + undefined, + getWindowsShiftEnterEncoding + ) + ).toEqual({ type: 'sendInput', data: '\x1b\r' }) + expect(isLocalWindowsConptyPane).toHaveBeenCalledTimes(2) + expect(getWindowsShiftEnterEncoding).toHaveBeenCalledTimes(1) }) it('forwards Ctrl+Enter as the kitty CSI-u chord so TUIs can cue instead of send', () => { diff --git a/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.ts b/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.ts index 69bc914d0482..f0f284d167fd 100644 --- a/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.ts +++ b/src/renderer/src/components/terminal-pane/terminal-shortcut-policy.ts @@ -1,4 +1,5 @@ import { keybindingMatchesAction, type KeybindingOverrides } from '../../../../shared/keybindings' +import type { WindowsShiftEnterEncoding } from './terminal-windows-shift-enter' export type TerminalShortcutEvent = { key: string @@ -75,9 +76,8 @@ export function resolveTerminalShortcutAction( isWindows: boolean = false, keybindings?: KeybindingOverrides, // Why: lazily reports whether the active pane is a local native Windows - // ConPTY (PowerShell/cmd via PSReadLine). Only consulted for the Ctrl+Arrow - // word-nav rule below, so the execution-host lookup it performs stays off the - // hot path for every other keystroke. + // ConPTY. Only consulted for Shift+Enter and Ctrl+Arrow, so execution-host + // lookup stays off every other keystroke. isLocalWindowsConptyPane?: () => boolean, // Why: lazily reports whether the active pane's application has enabled the // kitty keyboard protocol (CSI > u). Gates the Option-as-Alt compensation @@ -87,7 +87,10 @@ export function resolveTerminalShortcutAction( // layout; the physical-code table above is US QWERTY and reports the wrong // key on Dvorak/Colemak/AZERTY-class layouts. This resolves through // Chromium's KeyboardLayoutMap when it is available. - layoutBaseCharacterForCode?: (code: string) => string | undefined + layoutBaseCharacterForCode?: (code: string) => string | undefined, + // Why: lazily resolves the active pane's Windows encoding. Only consulted for + // Shift+Enter so agent-state lookup stays off every other keystroke. + getWindowsShiftEnterEncoding?: () => WindowsShiftEnterEncoding ): TerminalShortcutAction | null { const platform: NodeJS.Platform = isMac ? 'darwin' : isWindows ? 'win32' : 'linux' if (!event.repeat) { @@ -147,9 +150,15 @@ export function resolveTerminalShortcutAction( event.shiftKey && event.key === 'Enter' ) { - // Why: Codex on Windows PowerShell treats CSI-u Shift+Enter as inert, - // while the Alt+Enter byte path inserts a composer newline. - return { type: 'sendInput', data: isWindows ? '\x1b\r' : '\x1b[13;2u' } + // Why: Droid needs CSI-u but Codex needs Esc+CR; preserve legacy bytes for + // SSH/WSL/remote peers that cannot be safely classified from this client. + const useLocalWindowsCapability = isWindows && isLocalWindowsConptyPane?.() !== false + const encoding = useLocalWindowsCapability + ? (getWindowsShiftEnterEncoding?.() ?? 'alt-enter') + : isWindows + ? 'alt-enter' + : 'csi-u' + return { type: 'sendInput', data: encoding === 'csi-u' ? '\x1b[13;2u' : '\x1b\r' } } if ( diff --git a/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts b/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts new file mode 100644 index 000000000000..d19059b8e13f --- /dev/null +++ b/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it } from 'vitest' +import { + resolveWindowsShiftEnterEncoding, + resolveWindowsShiftEnterEncodingForPane +} from './terminal-windows-shift-enter' + +describe('resolveWindowsShiftEnterEncoding', () => { + it('uses CSI-u only for trusted Droid process evidence', () => { + expect( + resolveWindowsShiftEnterEncoding({ + foreground: { agent: 'droid', routingTrusted: true, shellForeground: false } + }) + ).toBe('csi-u') + expect(resolveWindowsShiftEnterEncoding({ launchAgentType: 'droid' })).toBe('alt-enter') + }) + + it('does not let hook or OSC-derived status forge Droid input routing', () => { + const state = { + paneForegroundAgentByPaneKey: {}, + agentStatusByPaneKey: { + 'tab:pane': { agentType: 'droid' as const } + }, + agentLaunchConfigByPaneKey: {} + } + + expect(resolveWindowsShiftEnterEncodingForPane(state, 'tab:pane')).toBe('alt-enter') + }) + + it('keeps the legacy byte for Codex, Antigravity, unknown, and plain panes', () => { + for (const agent of ['codex', 'antigravity', 'claude', null] as const) { + expect( + resolveWindowsShiftEnterEncoding({ + foreground: { agent, shellForeground: false } + }) + ).toBe('alt-enter') + } + expect(resolveWindowsShiftEnterEncoding({})).toBe('alt-enter') + }) + + it('lets current process identity override stale launch ownership', () => { + expect( + resolveWindowsShiftEnterEncoding({ + foreground: { agent: 'antigravity', routingTrusted: true, shellForeground: false }, + launchAgentType: 'droid' + }) + ).toBe('alt-enter') + }) + + it('fails closed while a newer command generation awaits trusted evidence', () => { + expect( + resolveWindowsShiftEnterEncoding({ + foreground: { agent: 'droid', shellForeground: false }, + launchAgentType: 'droid' + }) + ).toBe('alt-enter') + expect( + resolveWindowsShiftEnterEncoding({ + foreground: { agent: null, shellForeground: false }, + launchAgentType: 'droid' + }) + ).toBe('alt-enter') + }) + + it('keeps launch ownership on its original leaf after a split sibling survives', () => { + const state = { + paneForegroundAgentByPaneKey: {}, + agentLaunchConfigByPaneKey: { + 'tab:launched-droid': { identity: { agentType: 'droid' } } + } + } + + expect(resolveWindowsShiftEnterEncodingForPane(state, 'tab:launched-droid')).toBe('alt-enter') + // Why: after split→close leaves only the sibling, pane count is no longer + // ownership evidence; the surviving leaf must keep the legacy fallback. + expect(resolveWindowsShiftEnterEncodingForPane(state, 'tab:surviving-sibling')).toBe( + 'alt-enter' + ) + }) + + it('clears stale Droid ownership after the foreground returns to the shell', () => { + expect( + resolveWindowsShiftEnterEncoding({ + foreground: { agent: null, shellForeground: true }, + launchAgentType: 'droid' + }) + ).toBe('alt-enter') + }) +}) diff --git a/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.ts b/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.ts new file mode 100644 index 000000000000..4f55f13b9433 --- /dev/null +++ b/src/renderer/src/components/terminal-pane/terminal-windows-shift-enter.ts @@ -0,0 +1,43 @@ +import type { AgentType } from '../../../../shared/agent-status-types' +import { TUI_AGENT_CONFIG } from '../../../../shared/tui-agent-config' +import type { PaneForegroundAgentEntry } from '@/store/slices/pane-foreground-agent' + +export type WindowsShiftEnterEncoding = 'alt-enter' | 'csi-u' + +type WindowsShiftEnterAgentSignals = { + foreground?: PaneForegroundAgentEntry + launchAgentType?: AgentType +} + +type WindowsShiftEnterPaneState = { + paneForegroundAgentByPaneKey: Record + agentLaunchConfigByPaneKey: Record +} + +/** Resolve without key-path PTY I/O; current process/shell evidence overrides + * launch ownership. Hook status is excluded because PTY output can forge it. */ +export function resolveWindowsShiftEnterEncoding( + signals: WindowsShiftEnterAgentSignals +): WindowsShiftEnterEncoding { + if (signals.foreground?.shellForeground) { + return 'alt-enter' + } + // Why: an entry marks a newer command/process generation. Until fresh + // confirmation trusts it, stale launch ownership must not route input. + // Launch metadata is only an expectation used to start confirmation; it is + // never byte-routing authority because warm/stale daemon state can outlive + // the process that originally launched the agent. + const agent = signals.foreground?.routingTrusted === true ? signals.foreground.agent : null + return agent ? (TUI_AGENT_CONFIG[agent].windowsShiftEnterEncoding ?? 'alt-enter') : 'alt-enter' +} + +/** Resolves only pane-keyed evidence so a split sibling cannot inherit tab ownership. */ +export function resolveWindowsShiftEnterEncodingForPane( + state: WindowsShiftEnterPaneState, + paneKey: string +): WindowsShiftEnterEncoding { + return resolveWindowsShiftEnterEncoding({ + foreground: state.paneForegroundAgentByPaneKey[paneKey], + launchAgentType: state.agentLaunchConfigByPaneKey[paneKey]?.identity.agentType + }) +} diff --git a/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts b/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts index b0e2cd10ef8d..372a222e9acc 100644 --- a/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts +++ b/src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts @@ -1872,6 +1872,28 @@ export function useTerminalPaneLifecycle({ // eslint-disable-next-line react-hooks/exhaustive-deps -- Why: visibility and terminal identity changes must refresh existing PTY process tracking even though the ref object identity is stable. }, [cwd, isVisible, isVisibleRef, panePtyBindingsRef, tabId]) + useEffect(() => { + if (!isActive || !isVisible || typeof window === 'undefined') { + return + } + const onWindowFocus = (): void => { + const activePane = managerRef.current?.getActivePane() + if (!activePane) { + return + } + const binding = panePtyBindingsRef.current.get(activePane.id) as + | (IDisposable & { sampleForegroundAgentOnFocus?: () => void }) + | undefined + // Why: window refocus does not change the active leaf, so the pane + // manager's onActivePaneChange hook is not fired. Re-sample the same + // pane to revoke stale launch-only identity and confirm current Droid + // ownership before the next Windows Shift+Enter. + binding?.sampleForegroundAgentOnFocus?.() + } + window.addEventListener('focus', onWindowFocus) + return () => window.removeEventListener('focus', onWindowFocus) + }, [isActive, isVisible, managerRef, panePtyBindingsRef]) + useEffect(() => { const manager = managerRef.current if (!manager || !settings) { diff --git a/src/renderer/src/store/slices/pane-foreground-agent.ts b/src/renderer/src/store/slices/pane-foreground-agent.ts index c779c05b0182..4349b25e2ca3 100644 --- a/src/renderer/src/store/slices/pane-foreground-agent.ts +++ b/src/renderer/src/store/slices/pane-foreground-agent.ts @@ -5,6 +5,8 @@ import type { TuiAgent } from '../../../../shared/types' export type PaneForegroundAgentEntry = { /** Recognized agent process in the pane's foreground; null when unknown. */ agent: TuiAgent | null + /** True only when fresh provider evidence is safe for input-byte routing. */ + routingTrusted?: boolean /** True once the foreground is proven back at the shell (OSC 133;D) — * process-grade launched-agent exit evidence, independent of titles. */ shellForeground: boolean @@ -38,6 +40,7 @@ export const createPaneForegroundAgentSlice: StateCreator< if ( current && current.agent === entry.agent && + current.routingTrusted === entry.routingTrusted && current.shellForeground === entry.shellForeground ) { return s diff --git a/src/renderer/src/store/slices/store-cascades.test.ts b/src/renderer/src/store/slices/store-cascades.test.ts index bb0043b3adbf..a7cbac5cca26 100644 --- a/src/renderer/src/store/slices/store-cascades.test.ts +++ b/src/renderer/src/store/slices/store-cascades.test.ts @@ -1271,6 +1271,7 @@ describe('setActiveWorktree', () => { }) store.getState().syncPaneDetachPtyOwnership({ + detachedLeafId: '11111111-1111-4111-8111-111111111111', detachedPtyId: 'pty-detached', sourceLayout: { root: { type: 'leaf', leafId: 'survivor-leaf' }, diff --git a/src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts b/src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts new file mode 100644 index 000000000000..5afdcb6fe438 --- /dev/null +++ b/src/renderer/src/store/slices/terminal-pane-detach-agent-identity.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from 'vitest' +import { resolveWindowsShiftEnterEncodingForPane } from '@/components/terminal-pane/terminal-windows-shift-enter' +import { createTestStore, makeTab, makeWorktree, seedStore } from './store-test-helpers' + +describe('syncPaneDetachPtyOwnership agent identity', () => { + it('moves process and launch identity to the detached leaf without forging hook identity', () => { + const store = createTestStore() + const worktreeId = 'repo::/repo/worktree' + const sourceTabId = 'tab-source' + const targetTabId = 'tab-target' + const detachedLeafId = '11111111-1111-4111-8111-111111111111' + const siblingLeafId = '22222222-2222-4222-8222-222222222222' + const sourcePaneKey = `${sourceTabId}:${detachedLeafId}` + const targetPaneKey = `${targetTabId}:${detachedLeafId}` + const siblingPaneKey = `${sourceTabId}:${siblingLeafId}` + + seedStore(store, { + worktreesByRepo: { + repo: [makeWorktree({ id: worktreeId, repoId: 'repo', path: '/repo/worktree' })] + }, + tabsByWorktree: { + [worktreeId]: [ + makeTab({ id: sourceTabId, worktreeId, ptyId: 'pty-droid' }), + makeTab({ id: targetTabId, worktreeId, ptyId: null }) + ] + }, + ptyIdsByTabId: { + [sourceTabId]: ['pty-droid', 'pty-sibling'], + [targetTabId]: [] + } + }) + store.getState().setPaneForegroundAgent(sourcePaneKey, { + agent: 'droid', + routingTrusted: true, + shellForeground: false + }) + store + .getState() + .setPaneForegroundAgent(siblingPaneKey, { agent: 'antigravity', shellForeground: false }) + store + .getState() + .registerAgentLaunchConfig( + sourcePaneKey, + { agentArgs: '', agentEnv: {} }, + { agentType: 'droid', tabId: sourceTabId, leafId: detachedLeafId } + ) + store.getState().setAgentStatus(sourcePaneKey, { + state: 'working', + prompt: '', + agentType: 'droid' + }) + + store.getState().syncPaneDetachPtyOwnership({ + detachedLeafId, + detachedPtyId: 'pty-droid', + sourceLayout: { + root: { type: 'leaf', leafId: siblingLeafId }, + activeLeafId: siblingLeafId, + expandedLeafId: null, + ptyIdsByLeafId: { [siblingLeafId]: 'pty-sibling' } + }, + sourceTabId, + targetTabId + }) + + const state = store.getState() + expect(state.paneForegroundAgentByPaneKey[sourcePaneKey]).toBeUndefined() + expect(state.paneForegroundAgentByPaneKey[targetPaneKey]).toEqual({ + agent: 'droid', + routingTrusted: true, + shellForeground: false + }) + expect(state.agentLaunchConfigByPaneKey[sourcePaneKey]).toBeUndefined() + expect(state.agentLaunchConfigByPaneKey[targetPaneKey]?.identity).toMatchObject({ + agentType: 'droid', + tabId: targetTabId, + leafId: detachedLeafId + }) + // Why: the PTY keeps emitting its immutable source ORCA_PANE_KEY. A copied + // target hook row would look live but could never receive later updates. + expect(state.agentStatusByPaneKey[sourcePaneKey]).toBeUndefined() + expect(state.agentStatusByPaneKey[targetPaneKey]).toBeUndefined() + expect(state.retentionSuppressedPaneKeys[sourcePaneKey]).toBe(true) + expect(state.paneForegroundAgentByPaneKey[siblingPaneKey]).toEqual({ + agent: 'antigravity', + shellForeground: false + }) + expect(resolveWindowsShiftEnterEncodingForPane(state, targetPaneKey)).toBe('csi-u') + expect(resolveWindowsShiftEnterEncodingForPane(state, siblingPaneKey)).toBe('alt-enter') + }) +}) diff --git a/src/renderer/src/store/slices/terminals.ts b/src/renderer/src/store/slices/terminals.ts index 77d93f75d19b..514f5b01e7c3 100644 --- a/src/renderer/src/store/slices/terminals.ts +++ b/src/renderer/src/store/slices/terminals.ts @@ -28,7 +28,11 @@ import { } from '../../../../shared/workspace-scope' import { deriveGeneratedTabTitle } from '../../../../shared/agent-tab-title' import { isDecorativeAgentTitleFrameChange } from '../../../../shared/agent-decorative-title-signature' -import { parseLegacyNumericPaneKey, parsePaneKey } from '../../../../shared/stable-pane-id' +import { + makePaneKey, + parseLegacyNumericPaneKey, + parsePaneKey +} from '../../../../shared/stable-pane-id' import { isValidHostTerminalTabId, isValidTerminalTabId } from '../../../../shared/terminal-tab-id' import { getRepoIdFromWorktreeId, splitWorktreeId } from '../../../../shared/worktree-id' import { isWslUncPath } from '../../../../shared/wsl-paths' @@ -647,6 +651,7 @@ export type TerminalSlice = { setTabCanExpandPane: (tabId: string, canExpand: boolean) => void setTabLayout: (tabId: string, layout: TerminalLayoutSnapshot | null) => void syncPaneDetachPtyOwnership: (args: { + detachedLeafId: string detachedPtyId: string | null sourceLayout: TerminalLayoutSnapshot sourceTabId: string @@ -2710,7 +2715,13 @@ export const createTerminalSlice: StateCreator }) }, - syncPaneDetachPtyOwnership: ({ detachedPtyId, sourceLayout, sourceTabId, targetTabId }) => { + syncPaneDetachPtyOwnership: ({ + detachedLeafId, + detachedPtyId, + sourceLayout, + sourceTabId, + targetTabId + }) => { set((s) => { const layoutSourcePtyIds = uniquePtyIds(Object.values(sourceLayout.ptyIdsByLeafId ?? {})) const existingSourcePtyIds = (s.ptyIdsByTabId[sourceTabId] ?? []).filter( @@ -2739,8 +2750,8 @@ export const createTerminalSlice: StateCreator nextLastKnownRelayPtyIdByTabId[targetTabId] = detachedPtyId } - // Why: pane-to-tab detach moves live PTY ownership without spawning or - // exiting processes, so sync identity maps directly without activity bumps. + // Why: pane-to-tab detach moves a live PTY without spawning or exiting, + // so transfer its safe pane-owned identity without activity bumps. const sourceTabsByWorktree = withTerminalTabPtyId( s.tabsByWorktree, sourceTabId, @@ -2750,10 +2761,60 @@ export const createTerminalSlice: StateCreator ? withTerminalTabPtyId(sourceTabsByWorktree, targetTabId, detachedPtyId) : sourceTabsByWorktree + const sourcePaneKey = makePaneKey(sourceTabId, detachedLeafId) + const targetPaneKey = makePaneKey(targetTabId, detachedLeafId) + const sourceForeground = s.paneForegroundAgentByPaneKey[sourcePaneKey] + const sourceLaunchConfig = s.agentLaunchConfigByPaneKey[sourcePaneKey] + const hadSourceHookStatus = sourcePaneKey in s.agentStatusByPaneKey + let nextPaneForegroundAgentByPaneKey = s.paneForegroundAgentByPaneKey + let nextAgentLaunchConfigByPaneKey = s.agentLaunchConfigByPaneKey + let nextAgentStatusByPaneKey = s.agentStatusByPaneKey + let nextRetentionSuppressedPaneKeys = s.retentionSuppressedPaneKeys + if (sourceForeground) { + nextPaneForegroundAgentByPaneKey = { ...s.paneForegroundAgentByPaneKey } + delete nextPaneForegroundAgentByPaneKey[sourcePaneKey] + nextPaneForegroundAgentByPaneKey[targetPaneKey] = sourceForeground + } + if (sourceLaunchConfig) { + nextAgentLaunchConfigByPaneKey = { ...s.agentLaunchConfigByPaneKey } + delete nextAgentLaunchConfigByPaneKey[sourcePaneKey] + nextAgentLaunchConfigByPaneKey[targetPaneKey] = { + ...sourceLaunchConfig, + identity: { + ...sourceLaunchConfig.identity, + tabId: targetTabId, + leafId: detachedLeafId + } + } + } + if (hadSourceHookStatus) { + nextAgentStatusByPaneKey = { ...s.agentStatusByPaneKey } + delete nextAgentStatusByPaneKey[sourcePaneKey] + nextRetentionSuppressedPaneKeys = { + ...s.retentionSuppressedPaneKeys, + [sourcePaneKey]: true + } + } + return { ptyIdsByTabId: nextPtyIdsByTabId, lastKnownRelayPtyIdByTabId: nextLastKnownRelayPtyIdByTabId, - ...(nextTabsByWorktree !== s.tabsByWorktree ? { tabsByWorktree: nextTabsByWorktree } : {}) + ...(nextTabsByWorktree !== s.tabsByWorktree ? { tabsByWorktree: nextTabsByWorktree } : {}), + ...(nextPaneForegroundAgentByPaneKey !== s.paneForegroundAgentByPaneKey + ? { paneForegroundAgentByPaneKey: nextPaneForegroundAgentByPaneKey } + : {}), + ...(nextAgentLaunchConfigByPaneKey !== s.agentLaunchConfigByPaneKey + ? { agentLaunchConfigByPaneKey: nextAgentLaunchConfigByPaneKey } + : {}), + ...(nextAgentStatusByPaneKey !== s.agentStatusByPaneKey + ? { + // Why: the PTY keeps its immutable source ORCA_PANE_KEY; retire + // rather than re-key a hook row that future events cannot update. + agentStatusByPaneKey: nextAgentStatusByPaneKey, + agentStatusEpoch: s.agentStatusEpoch + 1, + retentionSuppressedPaneKeys: nextRetentionSuppressedPaneKeys + } + : {}) } }) }, diff --git a/src/renderer/src/web/web-preload-api.ts b/src/renderer/src/web/web-preload-api.ts index be642916a6ea..e477f5a00d03 100644 --- a/src/renderer/src/web/web-preload-api.ts +++ b/src/renderer/src/web/web-preload-api.ts @@ -2729,6 +2729,8 @@ function createPtyApi(): NonNullable['pty']> { publishTerminalViewAttributes: () => {}, hasChildProcesses: () => Promise.resolve(false), getForegroundProcess: () => Promise.resolve(null), + // Why: paired web panes cannot provide a local post-boundary process scan. + confirmForegroundProcess: () => Promise.resolve(null), getCwd: () => Promise.resolve('~'), getSize: () => Promise.resolve(null), listSessions: () => Promise.resolve([]), diff --git a/src/shared/agent-process-recognition.test.ts b/src/shared/agent-process-recognition.test.ts index 297e8e405f95..11e11fe2f538 100644 --- a/src/shared/agent-process-recognition.test.ts +++ b/src/shared/agent-process-recognition.test.ts @@ -25,6 +25,13 @@ describe('agent process recognition', () => { expect(isExpectedAgentProcess('/usr/local/bin/openclaude', 'claude')).toBe(false) }) + it('recognizes the Droid foreground process on Windows', () => { + expect(recognizeAgentProcess(String.raw`C:\Users\dev\AppData\Roaming\npm\droid.cmd`)).toEqual({ + agent: 'droid', + processName: 'droid' + }) + }) + it('matches expected agents from platform-specific foreground process paths', () => { expect(recognizeAgentProcess('claude')).toEqual({ agent: 'claude', diff --git a/src/shared/process-table-snapshot.test.ts b/src/shared/process-table-snapshot.test.ts index f1a5df2be9fc..e9ec86bb3f54 100644 --- a/src/shared/process-table-snapshot.test.ts +++ b/src/shared/process-table-snapshot.test.ts @@ -121,6 +121,58 @@ describe('process-table-snapshot reader', () => { expect(scans).toBe(2) }) + it('forces a post-request scan even when a same-tick cache exists', async () => { + let scans = 0 + const reader = createProcessTableSnapshotReader({ + runPs: async () => `scan-${++scans}`, + now: () => 0 + }) + + expect(await reader.getSnapshot()).toBe('scan-1') + expect(await reader.getFreshSnapshot()).toBe('scan-2') + expect(scans).toBe(2) + }) + + it('shares same-turn fresh requests but queues one scan after a pre-existing scan', async () => { + let scans = 0 + const first = deferred() + const second = deferred() + const reader = createProcessTableSnapshotReader({ + runPs: () => { + scans += 1 + return scans === 1 ? first.promise : second.promise + }, + now: () => 0 + }) + + const stale = reader.getSnapshot() + const freshA = reader.getFreshSnapshot() + const freshB = reader.getFreshSnapshot() + expect(scans).toBe(1) + first.resolve('stale') + expect(await stale).toBe('stale') + await Promise.resolve() + expect(scans).toBe(2) + second.resolve('fresh') + expect(await freshA).toBe('fresh') + expect(await freshB).toBe('fresh') + expect(scans).toBe(2) + }) + + it('does not let an ordinary same-turn miss race a queued fresh scan', async () => { + let scans = 0 + const reader = createProcessTableSnapshotReader({ + runPs: async () => `scan-${++scans}`, + now: () => 0 + }) + + const fresh = reader.getFreshSnapshot() + const ordinary = reader.getSnapshot() + + await expect(Promise.all([fresh, ordinary])).resolves.toEqual(['scan-1', 'scan-1']) + expect(scans).toBe(1) + }) + it('shares one parsed-rows array across a burst so panes do not each re-parse', async () => { // Mirrors the POSIX default reader: runPs parses inside the deduped scan, so // every caller in the TTL window gets the SAME ProcessTableRow[] instance diff --git a/src/shared/process-table-snapshot.ts b/src/shared/process-table-snapshot.ts index bb6ce561db83..9827d1e8523c 100644 --- a/src/shared/process-table-snapshot.ts +++ b/src/shared/process-table-snapshot.ts @@ -70,19 +70,16 @@ export function createProcessTableSnapshotReader( deps: ProcessTableSnapshotReaderDeps ): { getSnapshot: () => Promise + getFreshSnapshot: () => Promise reset: () => void } { const ttlMs = deps.ttlMs ?? DEFAULT_SNAPSHOT_TTL_MS let cached: Snapshot | null = null let inFlight: Promise | null = null + let sequence = 0 + let freshQueued: { promise: Promise; startSequence: number | null } | null = null - async function getSnapshot(): Promise { - if (cached && deps.now() - cached.capturedAtMs < ttlMs) { - return cached.value - } - if (inFlight) { - return inFlight - } + async function runSnapshot(): Promise { const promise = deps.runPs() inFlight = promise try { @@ -92,22 +89,78 @@ export function createProcessTableSnapshotReader( cached = { value, capturedAtMs: deps.now() } return value } finally { - // Clear in-flight on success and failure so a transient `ps` error - // (timeout, nonzero exit) retries on the next call instead of being - // cached; callers keep their existing best-effort fall-through. if (inFlight === promise) { inFlight = null } } } + async function getSnapshot(): Promise { + if (cached && deps.now() - cached.capturedAtMs < ttlMs) { + return cached.value + } + if (inFlight) { + return inFlight + } + if (freshQueued) { + // Why: a fresh request schedules its scan in a microtask so same-turn + // callers can share it; an ordinary miss must not start a competing scan. + return freshQueued.promise + } + return runSnapshot() + } + + function getFreshSnapshot(): Promise { + const requestSequence = ++sequence + if (freshQueued?.startSequence === null) { + return freshQueued.promise + } + const priorFresh = freshQueued?.promise ?? null + const priorScan = inFlight + const entry: { promise: Promise; startSequence: number | null } = { + promise: Promise.resolve(undefined as never), + startSequence: null + } + entry.promise = Promise.resolve().then(async () => { + for (const prior of [priorFresh, priorScan]) { + if (!prior) { + continue + } + try { + await prior + } catch { + // The post-boundary scan below owns the confirmation result. + } + } + // Why: same-turn callers join while startSequence is null; later callers + // queue behind this scan. The sequence proves every shared scan began + // strictly after each request without relying on wall-clock precision. + entry.startSequence = ++sequence + if (entry.startSequence <= requestSequence) { + throw new Error('fresh process snapshot did not start after request') + } + return runSnapshot() + }) + freshQueued = entry + const clearQueued = (): void => { + if (freshQueued === entry) { + freshQueued = null + } + } + void entry.promise.then(clearQueued, clearQueued) + return entry.promise + } + return { getSnapshot, + getFreshSnapshot, // Why: lets tests that mock `ps` per case clear the cross-call cache so one // case's snapshot can't satisfy the next within the TTL window. reset: () => { cached = null inFlight = null + sequence = 0 + freshQueued = null } } } @@ -135,6 +188,11 @@ export function getProcessTableSnapshot(): Promise { return defaultReader.getSnapshot() } +/** Capture process rows from a scan that starts after this request. */ +export function getFreshProcessTableSnapshot(): Promise { + return defaultReader.getFreshSnapshot() +} + /** * Test-only: clear the shared snapshot cache so suites that mock `ps` between * cases don't have one case's snapshot served to the next within the TTL. diff --git a/src/shared/tui-agent-config.ts b/src/shared/tui-agent-config.ts index ff4427bb5da1..29a03d14bc49 100644 --- a/src/shared/tui-agent-config.ts +++ b/src/shared/tui-agent-config.ts @@ -63,6 +63,9 @@ export type TuiAgentConfig = { * `›` prompt only when the composer row exists, so Orca can paste as soon * as that prompt appears after bracketed paste is enabled. */ draftPasteReadySignal?: DraftPasteReadySignal + /** Windows Shift+Enter override. Omitted agents keep the legacy Esc+CR path + * because the renderer cannot infer every local or remote TUI's decoder. */ + windowsShiftEnterEncoding?: 'csi-u' } export const TUI_AGENT_CONFIG: Record = { @@ -281,7 +284,10 @@ export const TUI_AGENT_CONFIG: Record = { detectCmd: 'droid', launchCmd: 'droid', expectedProcess: 'droid', - promptInjectionMode: 'argv' + promptInjectionMode: 'argv', + // Why: Droid decodes CSI-u on Windows and treats Orca's legacy Esc+CR + // fallback as plain Enter, which submits instead of inserting a newline. + windowsShiftEnterEncoding: 'csi-u' }, kimi: { detectCmd: 'kimi', diff --git a/tests/e2e/terminal-foreground-confirmation.unit.test.ts b/tests/e2e/terminal-foreground-confirmation.unit.test.ts new file mode 100644 index 000000000000..cede865696c2 --- /dev/null +++ b/tests/e2e/terminal-foreground-confirmation.unit.test.ts @@ -0,0 +1,130 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { spawnMock, resolveForegroundMock } = vi.hoisted(() => ({ + spawnMock: vi.fn(), + resolveForegroundMock: vi.fn() +})) + +vi.mock('node-pty', () => ({ spawn: spawnMock })) +vi.mock('../../src/main/pwsh', () => ({ isPwshAvailable: vi.fn(() => false) })) +vi.mock('../../src/main/providers/windows-powershell-executable', () => ({ + resolveWindowsPowerShellExecutablePath: () => + 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe', + resolveWindowsPowerShellSpawnChain: () => [ + 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe' + ], + getWindowsCmdPath: () => 'C:\\Windows\\System32\\cmd.exe' +})) +vi.mock('../../src/main/providers/agent-foreground-process', () => ({ + resolveAgentForegroundProcessWithAvailability: async (...args: unknown[]) => { + const value = await resolveForegroundMock(...args) + return value && typeof value === 'object' && 'available' in value + ? value + : { available: true, processName: value } + } +})) + +import { createPtySubprocess } from '../../src/main/daemon/pty-subprocess' +import { createPaneForegroundAgentTracker } from '../../src/renderer/src/components/terminal-pane/pane-foreground-agent-tracker' + +function mockWindowsPty() { + const exitListeners: ((event: { exitCode: number }) => void)[] = [] + return { + pid: 12345, + process: 'powershell.exe', + write: vi.fn(), + resize: vi.fn(), + kill: vi.fn(), + onData: vi.fn(() => ({ dispose: vi.fn() })), + onExit: vi.fn((callback: (event: { exitCode: number }) => void) => { + exitListeners.push(callback) + return { dispose: vi.fn() } + }) + } +} + +describe('daemon foreground confirmation composes with pane tracking', () => { + let platform: PropertyDescriptor | undefined + + beforeEach(() => { + vi.useFakeTimers() + spawnMock.mockReset() + resolveForegroundMock.mockReset() + platform = Object.getOwnPropertyDescriptor(process, 'platform') + Object.defineProperty(process, 'platform', { value: 'win32' }) + }) + + afterEach(() => { + vi.useRealTimers() + if (platform) { + Object.defineProperty(process, 'platform', platform) + } + }) + + function createComposedTracker(publish: ReturnType) { + const handle = createPtySubprocess({ sessionId: 'test', cols: 80, rows: 24 }) + const tracker = createPaneForegroundAgentTracker({ + getPtyId: () => 'pty-1', + isTrackablePtyId: () => true, + readForegroundProcess: () => handle.confirmForegroundProcess!(), + publish, + hasKnownAgentIdentity: () => true + }) + return { handle, tracker } + } + + it('keeps a restored Droid through a scan resolving after the old cache window', async () => { + spawnMock.mockReturnValue(mockWindowsPty()) + let resolveFresh!: (value: string) => void + resolveForegroundMock.mockReturnValue( + new Promise((resolve) => { + resolveFresh = resolve + }) + ) + const publish = vi.fn() + const { tracker } = createComposedTracker(publish) + + tracker.onVisiblePtyBound(true) + await vi.advanceTimersByTimeAsync(350) + await vi.advanceTimersByTimeAsync(2_000) + expect(publish).not.toHaveBeenCalled() + resolveFresh('droid') + await vi.advanceTimersByTimeAsync(0) + + expect(publish).toHaveBeenCalledExactlyOnceWith({ + agent: 'droid', + routingTrusted: true, + shellForeground: false + }) + expect(resolveForegroundMock).toHaveBeenCalledTimes(1) + }) + + it('clears launch identity after one fresh scan confirms a real shell exit', async () => { + spawnMock.mockReturnValue(mockWindowsPty()) + resolveForegroundMock.mockResolvedValue('powershell.exe') + const publish = vi.fn() + const { tracker } = createComposedTracker(publish) + + tracker.onCommandFinished() + await vi.advanceTimersByTimeAsync(350) + + expect(publish).toHaveBeenCalledExactlyOnceWith({ agent: null, shellForeground: true }) + expect(resolveForegroundMock).toHaveBeenCalledTimes(1) + }) + + it('fails closed without claiming shell when every fresh scan is unavailable', async () => { + spawnMock.mockReturnValue(mockWindowsPty()) + resolveForegroundMock.mockResolvedValue({ + available: false, + processName: 'powershell.exe' + }) + const publish = vi.fn() + const { tracker } = createComposedTracker(publish) + + tracker.onCommandFinished() + await vi.advanceTimersByTimeAsync(350 + 1_200 + 6_000) + + expect(publish).toHaveBeenCalledExactlyOnceWith({ agent: null, shellForeground: false }) + expect(resolveForegroundMock).toHaveBeenCalledTimes(3) + }) +}) diff --git a/tests/e2e/terminal-shortcuts.spec.ts b/tests/e2e/terminal-shortcuts.spec.ts index d0243f5cc039..c6c40afe6fc9 100644 --- a/tests/e2e/terminal-shortcuts.spec.ts +++ b/tests/e2e/terminal-shortcuts.spec.ts @@ -24,7 +24,8 @@ import { waitForTerminalOutput, waitForPaneCount, getTerminalContent, - waitForActivePanePtyId + waitForActivePanePtyId, + focusActiveTerminalInput } from './helpers/terminal' import { waitForSessionReady, waitForActiveWorktree, ensureTerminalVisible } from './helpers/store' @@ -82,14 +83,34 @@ async function getPtyWrites(app: ElectronApplication): Promise { }) } -// Why: the window-level keydown handler is gated on non-editable targets; the -// xterm helper textarea is treated as non-editable on purpose. Focusing it -// guarantees each chord reaches the shortcut policy through the real DOM path. -async function focusActiveTerminal(page: Page): Promise { - await page.evaluate(() => { - const textarea = document.querySelector('.xterm-helper-textarea') as HTMLTextAreaElement | null - textarea?.focus() - }) +async function setActivePaneForegroundAgent( + page: Page, + agent: 'droid' | 'antigravity' | null +): Promise { + return page.evaluate((agent) => { + const state = window.__store?.getState() + const worktreeId = state?.activeWorktreeId + const tabId = + state?.activeTabType === 'terminal' + ? state.activeTabId + : worktreeId + ? (state?.activeTabIdByWorktree?.[worktreeId] ?? null) + : null + const manager = tabId ? window.__paneManagers?.get(tabId) : null + const pane = manager?.getActivePane?.() ?? manager?.getPanes?.()[0] ?? null + if (!state || !tabId || !pane) { + throw new Error('No active terminal pane for foreground-agent setup') + } + const paneKey = `${tabId}:${pane.leafId}` + state.setPaneForegroundAgent(paneKey, { + agent, + shellForeground: false, + // The shortcut only emits CSI-u for a process identity confirmed to + // belong to this PTY; keep the fixture aligned with that trust gate. + routingTrusted: agent === 'droid' + }) + return paneKey + }, agent) } async function dispatchCtrlCToActiveTerminalTextarea( @@ -416,22 +437,25 @@ async function pressAndExpectWrite( page: Page, app: ElectronApplication, chord: string, - expectedData: string + expectedData: string, + repetitions = 1 ): Promise { await clearPtyWriteLog(app) - await focusActiveTerminal(page) - await page.keyboard.press(chord) + await focusActiveTerminalInput(page) + for (let index = 0; index < repetitions; index++) { + await page.keyboard.press(chord) + } // Why: assert exact equality, not substring match. Short control codes like // \x01 (Ctrl+A) and \x05 (Ctrl+E) are single bytes that can appear inside // unrelated writes (shell prompt redraws, bracketed-paste sequences), so a // substring match would produce false positives. await expect - .poll(async () => (await getPtyWrites(app)).some((w) => w === expectedData), { + .poll(async () => (await getPtyWrites(app)).filter((write) => write === expectedData).length, { timeout: 5_000, message: `Expected chord "${chord}" to write ${JSON.stringify(expectedData)}` }) - .toBe(true) + .toBeGreaterThanOrEqual(repetitions) } const isMac = process.platform === 'darwin' @@ -447,7 +471,9 @@ const splitHorizontalChord = isMac ? `${mod}+Shift+d` : 'Alt+Shift+d' // Why: a freshly split pane can transiently still report a running child, so // poll for the confirm dialog and pane-count settling instead of a fixed wait. async function closeActivePaneAndSettle(page: Page, expectedCount: number): Promise { - await focusActiveTerminal(page) + // Why: split panes own multiple textareas; the shared helper focuses the + // PaneManager's active terminal instead of whichever appears first in the DOM. + await focusActiveTerminalInput(page) await page.keyboard.press(`${mod}+w`) // The "Stop running command?" confirm surfaces a "Stop and Close" action when // the pane still reports a running child. @@ -507,6 +533,26 @@ test.describe('Terminal Shortcuts', () => { ) }) + test('Droid gets CSI-u Shift+Enter on Windows without changing Antigravity', async ({ + orcaPage, + electronApp + }) => { + test.skip(process.platform !== 'win32', 'Windows ConPTY encoding contract') + await installMainProcessPtyWriteSpy(electronApp) + await waitForActivePanePtyId(orcaPage) + const paneKey = await setActivePaneForegroundAgent(orcaPage, 'droid') + try { + await pressAndExpectWrite(orcaPage, electronApp, 'Shift+Enter', '\x1b[13;2u', 2) + await setActivePaneForegroundAgent(orcaPage, 'antigravity') + await pressAndExpectWrite(orcaPage, electronApp, 'Shift+Enter', '\x1b\r') + } finally { + await orcaPage.evaluate( + (key) => window.__store?.getState().clearPaneForegroundAgent(key), + paneKey + ) + } + }) + test('Ctrl+Enter writes the kitty modified-enter chord for terminal TUIs', async ({ orcaPage, electronApp @@ -525,7 +571,7 @@ test.describe('Terminal Shortcuts', () => { await waitForActivePanePtyId(orcaPage) await enableKittyKeyboardReporting(orcaPage, 31) await clearPtyWriteLog(electronApp) - await focusActiveTerminal(orcaPage) + await focusActiveTerminalInput(orcaPage) await orcaPage.keyboard.down('Control') await orcaPage.keyboard.up('Control') expect((await getPtyWrites(electronApp)).join('')).toBe('') @@ -554,7 +600,7 @@ test.describe('Terminal Shortcuts', () => { .toBe(0) await clearPtyWriteLog(electronApp) - await focusActiveTerminal(orcaPage) + await focusActiveTerminalInput(orcaPage) await orcaPage.keyboard.type('x') await expect .poll(async () => (await getPtyWrites(electronApp)).some((write) => write === 'x'), { @@ -723,8 +769,8 @@ test.describe('Terminal Shortcuts', () => { // Ctrl+Backspace → \x17 (unix-word-rubout). await pressAndExpectWrite(orcaPage, electronApp, 'Control+Backspace', '\x17') - // Shift+Enter → a modified Enter byte path so agents can distinguish it - // from plain Enter. Windows uses Esc+CR because Codex ignores CSI-u there. + // Shift+Enter stays distinct; Windows keeps Esc+CR unless the active agent + // explicitly requires CSI-u (currently Droid, #7620). await pressAndExpectWrite( orcaPage, electronApp, @@ -747,7 +793,7 @@ test.describe('Terminal Shortcuts', () => { // --- action chords (no PTY byte; assert via visible effect) --- // Cmd/Ctrl+K clears the pane. - await focusActiveTerminal(orcaPage) + await focusActiveTerminalInput(orcaPage) await orcaPage.keyboard.press(`${mod}+k`) await expect .poll(async () => (await getTerminalContent(orcaPage)).includes(marker), { @@ -758,7 +804,7 @@ test.describe('Terminal Shortcuts', () => { // Split vertically (chord varies by platform — see splitVerticalChord). const panesBeforeSplit = await countVisibleTerminalPanes(orcaPage) - await focusActiveTerminal(orcaPage) + await focusActiveTerminalInput(orcaPage) await orcaPage.keyboard.press(splitVerticalChord) await waitForPaneCount(orcaPage, panesBeforeSplit + 1) // Why: ensure the new split pane's PTY is actually bound before we later @@ -766,9 +812,9 @@ test.describe('Terminal Shortcuts', () => { await waitForActivePanePtyId(orcaPage) // Cmd/Ctrl+] and Cmd/Ctrl+[ cycle focus (no pane-count change). - await focusActiveTerminal(orcaPage) + await focusActiveTerminalInput(orcaPage) await orcaPage.keyboard.press(`${mod}+BracketRight`) - await focusActiveTerminal(orcaPage) + await focusActiveTerminalInput(orcaPage) await orcaPage.keyboard.press(`${mod}+BracketLeft`) expect(await countVisibleTerminalPanes(orcaPage)).toBe(panesBeforeSplit + 1) @@ -784,12 +830,12 @@ test.describe('Terminal Shortcuts', () => { return state.expandedPaneByTabId[tabId] === true }) expect(await readExpanded()).toBe(false) - await focusActiveTerminal(orcaPage) + await focusActiveTerminalInput(orcaPage) await orcaPage.keyboard.press(`${mod}+Shift+Enter`) await expect .poll(readExpanded, { timeout: 3_000, message: 'Cmd+Shift+Enter did not expand pane' }) .toBe(true) - await focusActiveTerminal(orcaPage) + await focusActiveTerminalInput(orcaPage) await orcaPage.keyboard.press(`${mod}+Shift+Enter`) await expect .poll(readExpanded, { timeout: 3_000, message: 'Cmd+Shift+Enter did not collapse pane' }) @@ -800,14 +846,14 @@ test.describe('Terminal Shortcuts', () => { // Split horizontally (chord varies by platform — see splitHorizontalChord). const panesBeforeHSplit = await countVisibleTerminalPanes(orcaPage) - await focusActiveTerminal(orcaPage) + await focusActiveTerminalInput(orcaPage) await orcaPage.keyboard.press(splitHorizontalChord) await waitForPaneCount(orcaPage, panesBeforeHSplit + 1) await waitForActivePanePtyId(orcaPage) await closeActivePaneAndSettle(orcaPage, panesBeforeHSplit) // Cmd/Ctrl+F toggles the search overlay. - await focusActiveTerminal(orcaPage) + await focusActiveTerminalInput(orcaPage) await orcaPage.keyboard.press(`${mod}+f`) const searchInput = orcaPage.locator('[data-terminal-search-root] input').first() // Why: Escape is handled by TerminalSearch's React onKeyDown, which only @@ -849,7 +895,7 @@ test.describe('Terminal Shortcuts', () => { .toBe(true) await clearPtyWriteLog(electronApp) - await focusActiveTerminal(orcaPage) + await focusActiveTerminalInput(orcaPage) await orcaPage.keyboard.press('Meta+ArrowUp') await expect .poll(async () => getActiveTerminalViewport(orcaPage), { @@ -859,7 +905,7 @@ test.describe('Terminal Shortcuts', () => { .toMatchObject({ viewportY: 0 }) expect(await getPtyWrites(electronApp)).toEqual([]) - await focusActiveTerminal(orcaPage) + await focusActiveTerminalInput(orcaPage) await orcaPage.keyboard.press('Meta+ArrowDown') await expect .poll(