diff --git a/.github/workflows/performance-contracts.yml b/.github/workflows/performance-contracts.yml index c2c330ea00f..e8132e2aa79 100644 --- a/.github/workflows/performance-contracts.yml +++ b/.github/workflows/performance-contracts.yml @@ -19,7 +19,6 @@ on: # Contracts without the .performance suffix. Keep in sync with config/vitest.performance.config.ts; # without these a rename lands green and only breaks the next nightly. - 'src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts' - - 'src/renderer/src/components/terminal-pane/pty-connection/startup/saved-resume-cancellation.test.ts' - 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts' - 'src/shared/agent-launch/permissions/tui-agent-permission-choice.test.ts' - 'src/main/runtime/rpc/methods/projects/repo.test.ts' diff --git a/config/main-sync-fs-baseline.txt b/config/main-sync-fs-baseline.txt index a4efe1beedc..67ac9d1f775 100644 --- a/config/main-sync-fs-baseline.txt +++ b/config/main-sync-fs-baseline.txt @@ -282,6 +282,7 @@ 1 src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-subscribe.ts 1 src/main/ipc/filesystem/watcher-process/rebinding-file-watch.ts 1 src/main/ipc/filesystem/watcher-process/watcher-event-root-path-rewrite.ts +1 src/main/ipc/floating-workspace-directory.ts 1 src/main/ipc/macos-keyboard-layout-snapshot.ts 1 src/main/ipc/notification-authorization-status.ts 1 src/main/ipc/pty/spawn-pane-env.ts diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 66ecfbe88cb..5f439adf633 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -2183,22 +2183,15 @@ "invariant": "Adopting a prestarted terminal preserves its existing process and paints snapshot-covered startup output once while retaining subsequent live output. Missing sequence proof or blank snapshots must not authorize dropping output.", "oracle": "Audit2694 source-only review: Remove14 authored/14 expanded cases in the renderer completion wrapper family, including the complete bell/query-reply/stale-input factory, without replacement. Retain29 authored/34 expanded cases with unchanged callback bodies. Three removals are the existing pending2203 overlap and must be adopted/count-reconciled once; eleven are fresh removals. No current-source runtime or gate execution is supplied by this packet; dated evidence retains its original source scope and does not validate the reduced factory bytes. No equivalent replacement, physical provider, mixed-version, mobile, rendered UI, cross-platform, soak or measured-performance result is claimed. The retained directory-level discovery command continues to discover the reduced family; historical wrapper mentions are not fresh import-closure or execution evidence. Historical prior account (preserved verbatim): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit2065 (sources2063/2064): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-startup-cwd-fallback-notice.spec.ts: prints a terminal notice when the startup cwd fell back to the workspace root. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-coalesce.test.ts: surfaces working frames when many spinner frames arrive in one chunk. src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-pi-spinner.test.ts: surfaces normalized working and idle labels across a spinner cycle; surfaces working even when a single chunk contains multiple spinner frames. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionStartupCwdFallbackNoticeTests } from '../startup/pty-connection-startup-cwd-fallback-notice.spec'; registerPtyConnectionStartupCwdFallbackNoticeTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Frozen current literal-import graph reaches these changed test bytes; unresolved local and computed edges remain debt, and current reachability is not historical execution or equivalent replacement evidence. Historical prior account (preserved verbatim): Audit2061 (sources2059/2060): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-agent-trust-hold.test.ts: spawns only after the answer, carrying \"let agents ask\" to main for this launch; reattaches a section terminal without asking or changing trust; spawns with today's default when the prompt is released without an answer. src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-connection-ssh-hook-status-authority.spec.ts: leaves SSH IPC OSC 9999 status ownership in the main runtime. src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-completion-and-notification.test.ts: ordinary registration cleanup removes only import { registerPtyConnectionSshHookStatusAuthorityTests } from '../host-ownership/pty-connection-ssh-hook-status-authority.spec'; registerPtyConnectionSshHookStatusAuthorityTests(). Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit2056 (sources2054/2055): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-spawn-intent.test.ts: declares the intent only when the spawn resumes an agent; reports a deferral to the pane instead of an error toast. src/renderer/src/components/terminal-pane/pty-connection/startup/in-place-resume-hold.test.ts: owns the record while the start runs, through a nested start, and releases on settle; holds nothing for a start not resuming a record, or once the pane is disposed. Existing unrelated evidenceRuns retain their original scope; unchanged dated receipt objects do not validate changed source bytes or reduced selectors. No fresh gate execution or historical import-closure equivalence is claimed. Historical prior account (preserved verbatim): Audit1939 (sources1934/1935): The existing directory-level pnpm test selector includes eleven changed source files and automatically omits the three whole deletions. Keep this nonempty discovery command unchanged; no dated receipt uses this broad path. Removed agent admission fields, mock transport routing and terminal-id projection alarms are lost. Retained foreground state, actual headless xterm, redraw, abort/rebind reader and bridge claim progression remain scoped to their unchanged callbacks. No current-source execution, independent replacement, native transport or physical provider result is assigned. Preserve meaningful remaining selectors/assertions and unchanged dated receipts within their original scope. Reduced selectors have no fresh gate execution evidence in this metadata packet. No equivalent replacement, physical watcher/PTY/provider, live SSH/remote/mobile, rendered, cross-platform, soak or measured-budget result is claimed. Historical prior account (preserved verbatim): Retained exact unchanged-source receipts remain the only current execution evidence. Reduced selectors have no fresh execution result. Historical pre-audit oracle account for changed sources: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): Pass snapshot sequence and proven zero keyboard flags through real IPC transport projection. Deliver snapshot-covered and newer output before reattach resolves; drain replay parse callbacks and require one startup marker and the newer output. Repeat with no sequence and blank snapshot to retain unproven bytes. In Electron select a prestarted workspace, type a generated marker and compare PID and stable terminal identities before and after.", "commands": [ - "pnpm test src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-connect-spawn.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts", - "pnpm test src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-connect-spawn.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts", + "pnpm test src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts", + "pnpm test src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts", "pnpm test src/renderer/src/components/terminal-pane/pty-connection src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport", "pnpm test src/shared/terminal/protocol/escape/terminal-synchronized-output-socket-splits.test.ts" ], "testFiles": [ - "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-connect-spawn.test.ts", "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts" ], "assertionRefs": [ - { - "file": "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-connect-spawn.test.ts", - "assertions": [ - "zero and nonzero snapshot sequence and proven zero keyboard flags survive IPC projection" - ] - }, { "file": "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-hidden-replay.test.ts", "assertions": [ @@ -2242,6 +2235,7 @@ "Exercise live SSH and paired-runtime snapshot adoption before claiming full provider coverage." ], "knownGaps": [ + "Audit3077 retires the IPC zero/nonzero snapshot-sequence and zero-keyboard-proof examples and their direct selectors. The retained join projects only sequence 7 and flags 3. No equivalent replacement or fresh gate execution is claimed.", "Audit3069 retires nominal spawn/resume/banner wiring, first-fit and lookup-budget variants, private pending-map checks, the split-CWD disposal suite and startup command/draft baseline variants. Distinct regression alarms are intentionally lost without equivalent replacement; retained ownership, cancellation and recovery cases remain. Existing selectors and dated evidence retain their original scope.", "Audit3061 retires the park-model supplied snapshot suite and nominal mode, cursor, focus, geometry and remote resume metadata variants. Their distinct alarms are intentionally lost; six retained mode/remote cases preserve selected tail-order, authority and parse-readiness boundaries without equivalent replacement. Existing selectors and dated evidence retain their original scope.", "Audit3053 reduces hidden-replay coverage by retiring nominal overlap, resize, cursor metadata and standalone stalled-restore variants. Timeout, overflow, identity/generation fences and retained live-output coordination remain; the removed alarms are intentionally lost without equivalent replacement. Existing commands, assertion references and dated evidence retain their original scope.", @@ -6089,6 +6083,7 @@ "Keep missing-proof mixed-version behavior identical to the incumbent client path." ], "knownGaps": [ + "Audit3077 deletes the Kitty restore/reset integration suite and its registrar. The input-and-repaint driver remains populated; the retired emission/mirror/host-request alarms have no equivalent replacement.", "Audit3061 retires the park-model supplied snapshot suite and nominal mode, cursor, focus, geometry and remote resume metadata variants. Their distinct alarms are intentionally lost; six retained mode/remote cases preserve selected tail-order, authority and parse-readiness boundaries without equivalent replacement. Existing selectors and dated evidence retain their original scope.", "Audit3053 reduces hidden-replay coverage by retiring nominal overlap, resize, cursor metadata and standalone stalled-restore variants. Timeout, overflow, identity/generation fences and retained live-output coordination remain; the removed alarms are intentionally lost without equivalent replacement. Existing commands, assertion references and dated evidence retain their original scope.", "Audit3037 removes seven supplied-input baseline cases from the terminal-input-gating registrar. Input-and-repaint wrapper selectors and unrelated assertions remain; historical receipts do not validate the reduced source bytes. Pane authority, acknowledgment refusal and quarantine recovery cases remain, without native or RPC execution claims.", @@ -6775,7 +6770,7 @@ "id": "terminal-session.startup-cwd-missing-dir-recovery", "title": "Terminal working-directory recovery stays scoped and provider-safe", "maturity": "experimental", - "protection": "partial", + "protection": "none", "owner": "terminal-runtime", "layer": "shared-main-renderer-and-posix-shell-contract", "surfaces": [ @@ -6787,9 +6782,9 @@ ], "platforms": ["macos", "linux", "windows", "mobile"], "providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"], - "coveredPlatforms": ["linux"], + "coveredPlatforms": [], "coveredProviders": [], - "coverageNotes": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1760 removes the standalone startup-cwd policy suite without equivalent replacement. One fresh Linux run passed21 retained IPC transport unit cases; cwd-specific coverage returns mocked fallback metadata only. Original receipts and scope are archived in knownGaps; current platform scope reflects this unit run, not a native provider. Historical coverage account (not current evidence): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1396 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Local macOS evidence covers the shared missing-dir fallback policy, main pty:spawn recovery and metadata, no-flag and reattach strictness, renderer IPC flag routing, SSH-tagged and remote-runtime omission, and the visibility-gated terminal notice. Real Bash and Zsh node-pty tests replace the active cwd inode and exercise the shared POSIX OMP wrapper; audit829 removes generated-file snapshots and their current byte-parity claim. No equivalent replacement for generated-script byte checks is claimed. Daemon shares the same pre-provider main cwd decision but lacks a live daemon-provider run; WSL UNC paths are exempt from the spawn probe and lack a live run; native PowerShell is unaffected; Linux/Windows and mobile/API strictness remain gaps. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed.", + "coverageNotes": "Audit3077 retires the sole active passed IPC receipt; no current execution evidence remains for this gate. Historical account (not current coverage): Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1760 removes the standalone startup-cwd policy suite without equivalent replacement. One fresh Linux run passed21 retained IPC transport unit cases; cwd-specific coverage returns mocked fallback metadata only. Original receipts and scope are archived in knownGaps; current platform scope reflects this unit run, not a native provider. Historical coverage account (not current evidence): Audit1683 removes low-value test projections, mock wiring, private-state assertions, inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained public behavior and refusal boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1640 removes low-value IPC, SSH, workspace and transcript-watcher tests without equivalent replacement coverage. Per-source reviews record retained public refusal, cancellation, execution-host and real-filesystem outcomes with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded. Historical scope before this audit: Audit1396 changes referenced sources. Retained unchanged-source receipts apply only to their unchanged commands; the reduced selectors have no new execution result. Historical coverage account (not a current claim for changed sources): Local macOS evidence covers the shared missing-dir fallback policy, main pty:spawn recovery and metadata, no-flag and reattach strictness, renderer IPC flag routing, SSH-tagged and remote-runtime omission, and the visibility-gated terminal notice. Real Bash and Zsh node-pty tests replace the active cwd inode and exercise the shared POSIX OMP wrapper; audit829 removes generated-file snapshots and their current byte-parity claim. No equivalent replacement for generated-script byte checks is claimed. Daemon shares the same pre-provider main cwd decision but lacks a live daemon-provider run; WSL UNC paths are exempt from the spawn probe and lack a live run; native PowerShell is unaffected; Linux/Windows and mobile/API strictness remain gaps. Audit1396: src/renderer/src/components/terminal-pane/pty-connection-pending-spawn.spec.ts reduced. Lose standalone debug-state retention/log silence alarm. React StrictMode is not mounted; bindings manually simulate remount over mocked transport. No equivalent replacement coverage is claimed.", "motivatingLinks": [ "https://github.com/stablyai/orca/issues/7239", "https://github.com/stablyai/orca/pull/7750", @@ -6799,49 +6794,17 @@ ], "invariant": "A fresh local renderer terminal spawn may recover from a saved startup cwd whose directory no longer exists only by spawning at the selected workspace root and printing a generic in-terminal notice; existing directories — including ones outside the worktree (#7685) — spawn as requested, and reattach, SSH, remote-runtime, runtime/API, and mobile callers keep exact cwd semantics. A long-lived POSIX shell whose cwd inode was deleted and replaced may run a wrapped OMP command from the live path named by its logical PWD only in a subshell; the parent shell cwd, OMP argv, status extension, and exit status remain unchanged, while a genuinely unavailable path fails visibly without invoking OMP. A usable physical cwd remains authoritative when PWD is unset or names a removed logical symlink instead of being remapped to a workspace fallback.", "oracle": "Audit2133 current-parent preparation: Current reduced sources/selectors intentionally retire the alarms listed in knownGaps; prior dated runs and replacement claims do not validate the changed set. Historical prior account (preserved verbatim): Audit1683 retires changed-source assertion and execution scope without equivalent replacement coverage. Existing unchanged-selector receipts remain scoped to their original sources. Historical prior-source oracle: The retained unchanged-source receipts are the only current execution evidence; reduced-source assertions await validation. Historical oracle account (not a current claim for changed sources): The shared resolver falls back to the workspace root only when the injected existence probe reports the resolved cwd missing and the workspace root present, and never probes floating terminals or a cwd equal to the root. The renderer sends cwdFallback only for fresh local IPC spawns, main honors it only when connectionId and sessionId are absent, WSL UNC paths never engage the probe-based fallback, main returns fallback metadata only after an actual fallback, the IPC transport preserves that metadata, and the connection layer writes a generic notice that omits the missing path. In real interactive Bash and Zsh PTYs, unset PWD and remove a logical symlink while the physical cwd stays usable, requiring OMP to remain there; then delete and recreate the active project path, require extension-enabled and extension-skipping invocations to observe the replacement inode with byte-exact argv and nonzero status preserved, require the parent shell to remain on the stale inode, unset PWD and require recovery through ORCA_WORKTREE_PATH, clear every logical fallback and require an actionable failure without invoking OMP, and finally delete the replacement and require the same for the missing PWD path.", - "commands": [ - "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-connect-spawn.test.ts --maxWorkers=2", - "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts", - "pnpm exec vitest run --config config/vitest.config.ts src/main/pty/shell-startup/omp-shell-wrapper.node-pty.test.ts src/main/pty/shell-startup/omp-shell-wrapper-alias-safety.test.ts" - ], - "testFiles": [ - "src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts", - "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-connect-spawn.test.ts", - "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts", - "src/main/pty/shell-startup/omp-shell-wrapper.node-pty.test.ts", - "src/main/pty/shell-startup/omp-shell-wrapper-alias-safety.test.ts" - ], - "assertionRefs": [ - { - "file": "src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-connect-spawn.test.ts", - "assertions": [ - "IPC transport returns startup cwd fallback metadata to the connection layer" - ] - }, - { - "file": "src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts", - "assertions": ["fresh local IPC worktree spawns are marked with cwdFallback worktree"] - } - ], - "evidenceRuns": [ - { - "date": "2026-11-07", - "runner": "local", - "platform": "linux", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-connect-spawn.test.ts --maxWorkers=2", - "result": "passed", - "durationSeconds": 38.8, - "summary": "21 retained IPC transport unit cases passed on Linux, including return of mocked startupCwdFallback metadata. No live PTY, real missing directory, recovery notice, native shell, SSH/WSL, phone, p95 or soak evidence. Executed via pinned Node24 Vitest entry, same root config and selected file; no actual provider coverage claimed." - } - ], + "commands": [], + "testFiles": [], + "assertionRefs": [], + "evidenceRuns": [], "runtimeBudget": { "p95Seconds": 40, "scope": "Historical pre-audit selector budget; changed selectors have no new runtime measurement. Unchanged receipts remain scoped to their own commands." }, "flakeHistory": { "status": "unknown", - "evidence": "Audit1760: one Linux IPC transport unit run passed21 cases; no current soak evidence. Original flake history archived in knownGaps." + "evidence": "Audit3077: no current execution or soak result remains after retiring the reduced IPC source receipt. Historical account: Audit1760: one Linux IPC transport unit run passed21 cases; no current soak evidence. Original flake history archived in knownGaps." }, "redGreenEvidence": { "status": "missing", @@ -6858,6 +6821,9 @@ "Add WSL/mobile/API spawn provider-contract coverage or explicitly narrow their risk scope." ], "knownGaps": [ + "Audit3077 archives the remaining startup-CWD selectors and aliases because protection none permits no active selectors. These unchanged sources are unvalidated candidates, not current execution evidence. The worktree-marker alias remains mapping debt; this metadata retirement adds no test-removal credit. Original candidate fields verbatim:\ncommands: [\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts\",\n \"pnpm exec vitest run --config config/vitest.config.ts src/main/pty/shell-startup/omp-shell-wrapper.node-pty.test.ts src/main/pty/shell-startup/omp-shell-wrapper-alias-safety.test.ts\"\n ]\ntestFiles: [\n \"src/main/ipc/pty/pty-spawn-cwd-fallback.test.ts\",\n \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts\",\n \"src/main/pty/shell-startup/omp-shell-wrapper.node-pty.test.ts\",\n \"src/main/pty/shell-startup/omp-shell-wrapper-alias-safety.test.ts\"\n ]\nassertionRefs: [\n {\n \"file\": \"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts\",\n \"assertions\": [\"fresh local IPC worktree spawns are marked with cwdFallback worktree\"]\n }\n ]", + "Audit3077 retires the direct IPC startup-CWD metadata example, selector and alias. Other startup-CWD selectors and the existing worktree-marker mapping debt remain; no equivalent replacement is claimed.", + "Audit3077 retires this complete dated receipt because its selected source was reduced. It does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-11-07\",\n \"runner\": \"local\",\n \"platform\": \"linux\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-connect-spawn.test.ts --maxWorkers=2\",\n \"result\": \"passed\",\n \"durationSeconds\": 38.8,\n \"summary\": \"21 retained IPC transport unit cases passed on Linux, including return of mocked startupCwdFallback metadata. No live PTY, real missing directory, recovery notice, native shell, SSH/WSL, phone, p95 or soak evidence. Executed via pinned Node24 Vitest entry, same root config and selected file; no actual provider coverage claimed.\"\n }", "Audit3069 retires nominal spawn/resume/banner wiring, first-fit and lookup-budget variants, private pending-map checks, the split-CWD disposal suite and startup command/draft baseline variants. Distinct regression alarms are intentionally lost without equivalent replacement; retained ownership, cancellation and recovery cases remain. Existing selectors and dated evidence retain their original scope. The earlier generic-notice alias was already retired by audit3061; the remaining cwdFallback marker alias is unchanged mapping debt.", "Audit3061 retires the park-model supplied snapshot suite and nominal mode, cursor, focus, geometry and remote resume metadata variants. Their distinct alarms are intentionally lost; six retained mode/remote cases preserve selected tail-order, authority and parse-readiness boundaries without equivalent replacement. Existing selectors and dated evidence retain their original scope. The generic startup-cwd notice alias was already stale and is removed as pre-existing metadata debt; this batch receives no new removal credit for that alias. The separate cwdFallback marker alias remains outside this bounded reconciliation.", "Audit3037 retires the runtime-owner spawn-routing suite and its remote cwdFallback-absence assertion claim. Actual routing-composition alarms are intentionally lost; no replacement or renewed execution credit. Other historical claims and receipts retain their original scope.", @@ -9851,16 +9817,6 @@ "durationSeconds": 2.54, "summary": "Seven deterministic STA-3107 contracts passed across six-pane multiplex rematerialization and client-owned sidebar-row retention after sleep/wake.", "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/remote-runtime/paired-reconnect-multi-pane-materialization.test.ts src/renderer/src/runtime/web-session-tabs-sync/agent-status/paired-reconnect-sidebar-agent-count.test.ts --reporter=dot" - }, - { - "date": "2026-07-28", - "runner": "local", - "platform": "macos", - "command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport-reattach-admission.test.ts src/renderer/src/components/terminal-pane/pty-transport-detach-attach-handoff.test.ts", - "result": "passed", - "durationSeconds": 1.48, - "summary": "All 90 transport tests passed, including pre-publication admission rejection, handler-complete non-destructive detach for obsolete SSH reattach transports, settled retirement of rejected or destroyed fresh fallbacks, and reported shutdown refusal.", - "currentCommand": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-reattach-admission.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts" } ], "runtimeBudget": { @@ -9885,6 +9841,8 @@ "Include reconnect/polling artifacts that identify provider, connection id, and lease state." ], "knownGaps": [ + "Audit3077 reduces the IPC handoff suite while retaining the obsolete-reattach detach observer case and its alias. Removed nominal no-kill and gauge-cleanup alarms have no equivalent replacement.", + "Audit3077 retires this complete dated receipt because its selected source was reduced. It does not validate the reduced selector. Original receipt verbatim:\n{\n \"date\": \"2026-07-28\",\n \"runner\": \"local\",\n \"platform\": \"macos\",\n \"command\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport-reattach-admission.test.ts src/renderer/src/components/terminal-pane/pty-transport-detach-attach-handoff.test.ts\",\n \"result\": \"passed\",\n \"durationSeconds\": 1.48,\n \"summary\": \"All 90 transport tests passed, including pre-publication admission rejection, handler-complete non-destructive detach for obsolete SSH reattach transports, settled retirement of rejected or destroyed fresh fallbacks, and reported shutdown refusal.\",\n \"currentCommand\": \"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-reattach-admission.test.ts src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts\"\n }", "Audit3069 retires nominal spawn/resume/banner wiring, first-fit and lookup-budget variants, private pending-map checks, the split-CWD disposal suite and startup command/draft baseline variants. Distinct regression alarms are intentionally lost without equivalent replacement; retained ownership, cancellation and recovery cases remain. Existing selectors and dated evidence retain their original scope.", "Audit3061 retires the park-model supplied snapshot suite and nominal mode, cursor, focus, geometry and remote resume metadata variants. Their distinct alarms are intentionally lost; six retained mode/remote cases preserve selected tail-order, authority and parse-readiness boundaries without equivalent replacement. Existing selectors and dated evidence retain their original scope.", "Audit2133 current-parent preparation (988 authored removals; independently reviewed2099/2107/2115/2116 decisions; upstream clear-buffer and recovery-image regressions retained): Intentionally retire these low-value alarms without replacement: src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts: remove only literal registration import/call pairs import { registerPtyConnectionTerminalBellAttentionTests } from '../notifications/pty-connection-terminal-bell-attention.spec', registerPtyConnectionTerminalBellAttentionTests(); no additional authored credit. src/renderer/src/store/terminals/workspace-terminal-reconnect-hydration.test.ts: restores daemon terminal wake hints before declaring the session ready. src/main/ssh/connection/ssh-connection.test.ts: transitions to connected on successful connect; captures the negotiated SSH server key fingerprint; allows concurrent exec commands for ssh2 transport; removes startup listeners after ssh2 connect succeeds; scopes lifecycle events and pending handshake timers to one mock client; enables TCP_NODELAY on the new ssh2 client after a reconnect cycle; transitions through connecting → connected states; reports error state on connection failure; disconnect cleans up and sets state to disconnected; getTarget returns a copy of the target; getState returns a copy of the state; throws when connecting a disposed connection. src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-terminal-bell-attention.spec.ts: forwards onBell to pane attention and notification policy; hands the bell to the attention module with its pane even when pane attention is off. Current changed source bytes, wrapper registrations and reduced selectors have no fresh execution or red/green credit. Unrelated surviving receipt objects keep their original narrow scope; current literal graph reachability does not establish historical import closure or equivalent replacement coverage. Current conservative command/import graph reaches src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts, src/renderer/src/components/terminal-pane/pty-connection/notifications/pty-connection-terminal-bell-attention.spec.ts, src/renderer/src/store/terminals/workspace-terminal-reconnect-hydration.test.ts, src/main/ssh/connection/ssh-connection.test.ts. Unresolved local/computed edges remain explicit debt. Retired active assertionRefs (raw original objects retained as historical only): {\n \"file\": \"src/renderer/src/store/terminals/workspace-terminal-reconnect-hydration.test.ts\",\n \"assertions\": [\"restores daemon terminal wake hints before declaring the session ready\"]\n }", @@ -11916,14 +11874,8 @@ { "file": "src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts", "assertions": [ - "a synchronous 10,000-reply flood writes only the immediate first and newest 64 pending replies before a trailing keystroke", - "10,000 ordinary queued inputs survive a later reply flood while reply retention remains bounded", - "reply-shaped bytes from the ordinary input path never enter the shed-able reply budget", - "reply count and text overflow remove only the oldest pending replies", - "real xterm OSC 10/11 query handlers remain subject to the same retention ceiling", - "retained OSC, DA1, and CPR replies stay one provider write each and both OSC and DA1 floods remain bounded", "provider-write and yield failures settle without unhandled rejection, repeated same-generation admission, or stale-generation clearing", - "clear releases saturated reply accounting and fences in-flight validation before later input", + "clear fences in-flight validation before later input", "acknowledged input is serialized between earlier and later ordinary/reply writes", "clear settles active and pending acknowledged input before same-id queue reuse", "reentrant enqueue cannot start a second drain worker past an unacknowledged write", @@ -12026,6 +11978,7 @@ "Accumulate the normal soak window with zero unexplained flakes." ], "knownGaps": [ + "Audit3077 deletes the delivery-watchdog suite and retires queue flood, conservation, atomicity, retention, echo and heap examples plus preconnect cap/seed/abandon examples. The remaining queue failure/FIFO/reentrancy/generation and preconnect lifetime cases are narrower; no equivalent replacement is claimed.", "No live daemon, paired-runtime, WSL, physical Linux/Windows client, mixed-version, or network-fault run is registered.", "Ordinary-input queue growth predates this change and is outside this reply-only gate.", "Reply overload intentionally sheds the oldest synthetic replies; the modified-F3/CPR byte collision shares that budget, and live application behavior under a pathological query flood is not measured.", @@ -12689,7 +12642,7 @@ "https://github.com/stablyai/orca/pull/8034" ], "invariant": "After a renderer lifecycle reset (main-frame did-start-navigation / render-process-gone / destroyed), no surviving PTY remains delivery-gated by pre-reset unacked bytes: main's in-flight counters and pending backlog equal the true state of the new page (zero in-flight, zero pending). Delivery then resumes only once the reloaded page's pty:data dispatcher re-registers and signals pty:rendererDispatcherReady; during the boot window before that handshake main holds all sends (data accrues losslessly in the capped pending backlog) so bytes cannot be dropped into a listener-less page and re-pin the gate. The hold itself cannot become a permanent freeze: a one-shot ~10s watchdog armed on each reset force-opens the gate (incrementing rendererDispatcherReadyForcedCount) if the handshake is lost, and the real handshake or a re-registration cancels it. The reset fires only for a new-document main-frame navigation: did-start-navigation carries exact frame and same-document details, so overlapping subframe or in-page navigation never clears accounting or holds the gate on the still-alive page. If a renderer lifecycle edge is otherwise missed, a backstop still recovers: because the handshake is one-shot per page load, receiving pty:rendererDispatcherReady while the gate is already open proves a reset was missed (or the watchdog force-opened the gate), so the handler reconciles by clearing the stale accounting before re-opening. The renderer sends that handshake exactly once per page load, after its pty:data listener registers.", - "oracle": "Ingest more than 512 KB of PTY output with no renderer ACKs and assert the per-PTY gate closes (sends stop at the 512 KB high-water, remainder accrues as pending). Fire the registered main-frame did-start-navigation listener and assert rendererInFlightChars and pendingChars are zero and the new diagnostics record the reset (rendererLifecycleResetCount 1, lastLifecycleResetClearedChars 512 KB). Then, before any dispatcher-ready handshake, ingest another chunk and assert it is NOT sent and NOT counted in-flight (held for the boot window, accruing in pending). Finally fire the pty:rendererDispatcherReady handshake and assert the held chunk is delivered to the renderer. Counters-zero without proving both the boot-window hold and that delivery resumes is insufficient. Additional cases prove the boot-window hold also covers the interactive direct-send fast path (input-primed keystroke echo is held, not sent, until the handshake) and that the self-heal watchdog force-opens the gate (rendererDispatcherReadyForcedCount 1) when no handshake arrives, while a timely handshake cancels the watchdog and leaves no orphaned timer. A further case opens the new page with a main-frame navigation and dispatcher handshake, then fires an overlapping subframe navigation and asserts the gate stays ready, the reset count stays at exactly one, and fresh output delivers without the watchdog — proving an iframe cannot reclose the live page. A backstop case saturates the gate, then fires pty:rendererDispatcherReady while the gate is still open (ready true) with no preceding reset — modeling a missed lifecycle edge — and asserts the handler reconciles: in-flight and pending clear, rendererLifecycleResetCount increments, and fresh output flows immediately (a straggler ACK is clamped and cannot underflow). A renderer-side case (pty-dispatcher-pi-routing.test.ts) asserts ensurePtyDispatcher() sends pty:rendererDispatcherReady exactly once across two attach calls — proving the send fires (it is optional-chained) and the one-shot guard holds.", + "oracle": "Ingest more than 512 KB of PTY output with no renderer ACKs and assert the per-PTY gate closes (sends stop at the 512 KB high-water, remainder accrues as pending). Fire the registered main-frame did-start-navigation listener and assert rendererInFlightChars and pendingChars are zero and the new diagnostics record the reset (rendererLifecycleResetCount 1, lastLifecycleResetClearedChars 512 KB). Then, before any dispatcher-ready handshake, ingest another chunk and assert it is NOT sent and NOT counted in-flight (held for the boot window, accruing in pending). Finally fire the pty:rendererDispatcherReady handshake and assert the held chunk is delivered to the renderer. Counters-zero without proving both the boot-window hold and that delivery resumes is insufficient. Additional cases prove the boot-window hold also covers the interactive direct-send fast path (input-primed keystroke echo is held, not sent, until the handshake) and that the self-heal watchdog force-opens the gate (rendererDispatcherReadyForcedCount 1) when no handshake arrives, while a timely handshake cancels the watchdog and leaves no orphaned timer. A further case opens the new page with a main-frame navigation and dispatcher handshake, then fires an overlapping subframe navigation and asserts the gate stays ready, the reset count stays at exactly one, and fresh output delivers without the watchdog — proving an iframe cannot reclose the live page. A backstop case saturates the gate, then fires pty:rendererDispatcherReady while the gate is still open (ready true) with no preceding reset — modeling a missed lifecycle edge — and asserts the handler reconciles: in-flight and pending clear, rendererLifecycleResetCount increments, and fresh output flows immediately (a straggler ACK is clamped and cannot underflow).", "commands": [], "testFiles": [], "assertionRefs": [], @@ -12716,6 +12669,7 @@ "Add an Electron-level reload survival test that proves a saturated pane resumes rendering and input after Cmd+R / crash recovery." ], "knownGaps": [ + "Audit3077 retires the renderer once-per-page dispatcher-ready request example. It called ensurePtyDispatcher twice, without proving two attach calls or handshake ordering. Main-side lifecycle/hold/watchdog evidence and the desired invariant retain their original scope.", "Audit1634 removes low-value IPC, filesystem and runtime projections, argument inventories and duplicate examples without equivalent replacement coverage. Per-source reviews record retained cancellation, ownership, authorization, filesystem and SQLite boundaries with injected/native/remote limits. Affected historical receipts are retired; gates without active current evidence are downgraded.", "The unit oracle drives a local mock PTY; daemon and WSL coverage rides the same pipeline but has no dedicated provider-contract test yet.", "The dev repro covers the output-delivery freeze only; the arrow-key input symptom and mouse-mode flood observed in the same incident are out of scope and need their own repros.", diff --git a/config/scripts/ci/sharding/ci-shard-timings.json b/config/scripts/ci/sharding/ci-shard-timings.json index 83440c55a25..5e75c5805d2 100644 --- a/config/scripts/ci/sharding/ci-shard-timings.json +++ b/config/scripts/ci/sharding/ci-shard-timings.json @@ -5897,7 +5897,6 @@ "src/renderer/src/components/terminal-pane/pty-connection/spawn/main-pane-start-wait.test.ts": 76, "src/renderer/src/components/terminal-pane/pty-connection/serialization/pane-serializer-register.test.ts": 123, "src/renderer/src/components/terminal-pane/pty-connection/host-ownership/pty-kitty-file-reader.test.ts": 297, - "src/renderer/src/components/terminal-pane/pty-connection/startup/saved-resume-cancellation.test.ts": 1882, "src/renderer/src/components/terminal-pane/pty-connection/output-restore/snapshot-covered-terminal-queries.test.ts": 150, "src/renderer/src/components/terminal-pane/pty-connection/output/terminal-input-echo-delay.test.ts": 132, "src/renderer/src/components/terminal-pane/pty-connection/host-ownership/unserved-ssh-pane-bridge.test.ts": 70, @@ -5992,7 +5991,6 @@ "src/renderer/src/components/terminal-pane/emulation/terminal-capability-replies.test.ts": 131, "src/renderer/src/components/terminal-pane/clipboard/terminal-clipboard-paste.test.ts": 76, "src/renderer/src/components/terminal-pane/parking/retention/terminal-cold-park-timer-rearm.test.tsx": 701, - "src/renderer/src/components/terminal-pane/pty-transport/delivery/terminal-delivery-watchdog.test.ts": 111, "src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-handler.test.ts": 638, "src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-image-path.test.ts": 61, "src/renderer/src/components/terminal-pane/input/file-drop/terminal-drop-internal-handler.test.ts": 800, diff --git a/config/vitest.performance.config.ts b/config/vitest.performance.config.ts index f05c41e95f5..ceb2d73b083 100644 --- a/config/vitest.performance.config.ts +++ b/config/vitest.performance.config.ts @@ -6,7 +6,6 @@ import { nodeRuntimePool } from './scripts/test-runtime/node-worker/vitest-node- const contracts = [ 'src/main/runtime/session-tabs/session-tabs-phone-layout-moves.test.ts', - 'src/renderer/src/components/terminal-pane/pty-connection/startup/saved-resume-cancellation.test.ts', 'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts', 'src/shared/agent-launch/permissions/tui-agent-permission-choice.test.ts', 'src/main/runtime/rpc/methods/projects/repo.test.ts', diff --git a/src/renderer/src/components/terminal-pane/pty-connection/startup/saved-resume-cancellation.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/startup/saved-resume-cancellation.test.ts deleted file mode 100644 index 06539eff9f4..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-connection/startup/saved-resume-cancellation.test.ts +++ /dev/null @@ -1,546 +0,0 @@ -import { bindBuildColdRestoreAgentResumeStartup } from './cold-restore-resume-startup' -import { afterEach, describe, expect, it, vi } from 'vitest' -import type { AgentStatusEntry } from '../../../../../../shared/agent-status/contracts/agent-status-types' -import type { - AgentLaunchConfigRegistryEntry, - AgentLaunchConfigRegistrationMetadata -} from '@/store/slices/agent-status/agent-status-contract' -import type { ColdRestoreAgentResumeStartup } from './fresh-spawn-types' -import type { ConnectPanePtySession } from '../connect-pane-pty-session' -import { bindPaneSerializerReadiness } from '../serialization/pane-serializer-readiness' -import { bindStartupDraftPaste } from './startup-draft-paste' -import { bindSessionRestoredBannerAdmission } from '../notifications/session-restored-banner-admission' -import { bindDeferredColdRestoreAndSnapshot } from '../deferred-cold-restore-and-snapshot' -import { installSleepingRecordAccess } from './sleeping-record-access' -import { createTestStore } from '@/store/testing/app-store-test-fixture' -import { makeTab } from '@/store/terminals/terminal-tab.test-fixture' -import { createStoreSessionMockApi } from '@/store/testing/app-store-session-api.test-fixture' -import { - applyTerminalLaunchResult, - captureTerminalLaunchContext -} from './terminal-launch-result-policy' - -const fixture = vi.hoisted(() => ({ - state: {}, - setState: vi.fn(), - paste: vi.fn(), - parsed: vi.fn(async () => {}) -})) -vi.mock('@/store/index', () => ({ - useAppStore: { getState: () => fixture.state, setState: fixture.setState } -})) -vi.mock('@/lib/pane-manager/pane-terminal-output-scheduler', () => ({ - waitForTerminalOutputParsed: fixture.parsed -})) -vi.mock('../../input/paste/terminal-startup-command-paste', () => ({ - executeTerminalStartupCommandPaste: fixture.paste -})) -vi.mock('../../input/paste/terminal-paste-runtime', () => ({ - resolveTerminalPasteRuntime: () => ({}) -})) -vi.mock('@/lib/new-workspace', () => ({ CLIENT_PLATFORM: 'win32' })) -vi.mock('../agent-identity/command-inferred-pane-agent', () => ({ - installCommandInferredPaneAgent: vi.fn() -})) - -afterEach(() => { - vi.useRealTimers() - vi.clearAllMocks() - fixture.setState.mockReset() - vi.unstubAllGlobals() -}) - -describe('a refused saved startup and its delayed paste', () => { - it.each(['original', 'same-C', 'different-D', 'unverifiable'] as const)( - 'cancels only its captured source and keeps newer work (%s)', - async (kind) => { - vi.useFakeTimers() - const record = { - paneKey: 'tab:leaf', - tabId: 'tab', - worktreeId: 'wt', - agent: 'codex' as const, - providerSession: { key: 'session_id' as const, id: 'C' }, - connectionId: null, - state: 'done' as const, - prompt: '', - capturedAt: 10, - updatedAt: 10, - origin: 'worktree-sleep' as const - } - const source = { cancelled: false, record } - const startup = { - command: 'codex resume C', - launchAgent: 'codex' as const, - resumeProviderSession: record.providerSession, - resumeOrigin: 'saved' as const, - resumeSource: source - } - const records = kind === 'unverifiable' ? {} : { [record.paneKey]: record } - const clear = vi.fn() - const remember = vi.fn() - fixture.state = { - sleepingAgentSessionsByPaneKey: records, - automaticAgentResumeClaimsByTabId: {}, - agentLaunchConfigByPaneKey: {}, - pendingStartupByTabId: {}, - tabsByWorktree: {}, - registerAgentLaunchConfig: vi.fn(), - clearAgentLaunchConfig: vi.fn(), - consumeTabStartupCommand: vi.fn(), - clearSleepingAgentSession: clear, - rememberSleepingAgentSession: remember - } - const sendInput = vi.fn(() => true) - const transport = { getPtyId: () => 'shell', sendInput } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the installers' accessed session members are supplied here. - const session = { - pane: { id: 1, leafId: 'leaf', terminal: {} }, - manager: {}, - transport, - deps: { - worktreeId: 'wt', - tabId: 'tab', - paneTransportsRef: { current: new Map([[1, transport]]) } - }, - cacheKey: record.paneKey, - paneStartup: startup, - startupInjectTimer: null, - disposed: false, - transportStreamGeneration: 1, - shouldDeliverStartupViaTerminalPaste: true, - releaseUnattemptedStartupDraftPasteDelivery: vi.fn() - } as unknown as ConnectPanePtySession - installSleepingRecordAccess(session) - bindPaneSerializerReadiness(session) - bindStartupDraftPaste(session) - bindSessionRestoredBannerAdmission(session) - bindDeferredColdRestoreAndSnapshot(session) - let finishPaste: (() => void) | undefined - fixture.paste.mockImplementation( - () => - new Promise((resolve) => { - finishPaste = () => resolve({ status: 'pasted' }) - }) - ) - session.schedulePendingStartupCommandDelivery() - await vi.advanceTimersByTimeAsync(50) - expect(fixture.paste).toHaveBeenCalledOnce() - - const newer = { command: kind === 'different-D' ? 'codex resume D' : 'codex resume C' } - session.pendingStartupCommand = newer - if (kind === 'same-C' || kind === 'different-D') { - Object.assign(records, { - [record.paneKey]: { - ...record, - providerSession: { ...record.providerSession, id: kind === 'same-C' ? 'C' : 'D' }, - updatedAt: 20 - } - }) - } - session.cancelSavedResumeStartup(startup, { - id: 'shell', - agentResumeRefused: kind === 'unverifiable' ? 'unverifiable' : 'chat-home' - }) - expect(source.cancelled).toBe(true) - expect(session.pendingStartupCommand).toBe(newer) - finishPaste?.() - await vi.advanceTimersByTimeAsync(0) - expect(sendInput).not.toHaveBeenCalled() - expect(session.pendingStartupCommand).toBe(newer) - if (kind === 'unverifiable') { - expect(remember).toHaveBeenCalledWith(record) - } else if (kind === 'original') { - expect(clear).toHaveBeenCalledWith(record.paneKey) - } else { - expect(clear).not.toHaveBeenCalled() - } - } - ) -}) - -it.each(['refused', 'same-C', 'different-D'] as const)( - 'clears the real generated cold/wake registration and conditional tab identity only while owned (%s)', - (kind) => { - const cacheKey = 'tab:leaf' - const source = { cancelled: false } - const startup: ColdRestoreAgentResumeStartup = { - agent: 'codex', - command: 'codex resume C', - launchToken: 'saved-token', - launchConfig: { agentCommand: 'codex', agentArgs: 'resume C', agentEnv: {} }, - resumeProviderSession: { key: 'session_id', id: 'C' }, - resumeOrigin: 'saved', - resumeSource: source, - useLiveEntry: false, - hasSleepingRecord: false, - sleepingRecordEntry: null - } - const registry: Record = {} - const pending: Record = {} - const tab = { id: 'tab', title: 'Codex', launchAgent: 'codex', generation: 1 } - const clearTabLaunchAgent = vi.fn() - const registerAgentLaunchConfig = ( - paneKey: string, - launchConfig: AgentLaunchConfigRegistryEntry['launchConfig'], - identity: AgentLaunchConfigRegistrationMetadata - ) => { - registry[paneKey] = { launchConfig, identity, registeredAt: 1 } - } - fixture.state = { - agentLaunchConfigByPaneKey: registry, - pendingStartupByTabId: pending, - automaticAgentResumeClaimsByTabId: {}, - sleepingAgentSessionsByPaneKey: {}, - tabsByWorktree: { wt: [tab] }, - registerAgentLaunchConfig, - clearAgentLaunchConfig: (key: string) => { - delete registry[key] - }, - consumeTabStartupCommand: vi.fn(), - clearTabLaunchAgent - } - const updateTabTitle = vi.fn() - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the real installers/cancellation access only the supplied session members in this contract. - const session = { - cacheKey, - paneStartup: null, - pane: { id: 1, leafId: 'leaf' }, - manager: { getActivePane: () => ({ id: 1 }) }, - deps: { tabId: 'tab', worktreeId: 'wt', setRuntimePaneTitle: vi.fn(), updateTabTitle }, - tabGeneration: 1, - startupInjectTimer: null, - transport: {}, - shouldDeliverStartupViaTerminalPaste: false - } as unknown as ConnectPanePtySession - installSleepingRecordAccess(session) - bindDeferredColdRestoreAndSnapshot(session) - expect(session.applyColdRestoreAgentResumeStartup(startup)).toBe(true) - const saved = registry[cacheKey] - expect(saved?.identity.launchToken).toBe('saved-token') - if (kind !== 'refused') { - const command = kind === 'same-C' ? 'resume C' : 'resume D' - registerAgentLaunchConfig( - cacheKey, - { ...startup.launchConfig, agentArgs: command }, - { - agentType: 'codex', - launchToken: 'explicit-token' - } - ) - pending.tab = { command } - } - const current = registry[cacheKey] - const newer = pending.tab - session.cancelSavedResumeStartup(startup, { id: 'shell', agentResumeRefused: 'chat-home' }) - session.registerEffectiveLaunchConfig(undefined, {}) - expect(source.cancelled).toBe(true) - expect(session.paneStartup).toBeNull() - if (kind === 'refused') { - expect(registry[cacheKey]).toBeUndefined() - expect(clearTabLaunchAgent).toHaveBeenCalledWith('tab') - expect(updateTabTitle).toHaveBeenCalledWith('tab', 'Terminal') - } else { - expect(registry[cacheKey]).toBe(current) - expect(pending.tab).toBe(newer) - expect(clearTabLaunchAgent).not.toHaveBeenCalled() - expect(updateTabTitle).not.toHaveBeenCalled() - } - } -) - -it.each([10, 100])('counts real saved-startup cancellation map work at %i entries', (size) => { - vi.stubGlobal('window', undefined) - createStoreSessionMockApi() - for (const newer of [true, false]) { - const store = createTestStore() - fixture.state = store.getState() - fixture.setState.mockImplementation(store.setState) - let notifications = 0 - const unsubscribe = store.subscribe((state) => { - fixture.state = state - notifications += 1 - }) - const source = { cancelled: false } - const startup = { - command: 'codex resume C', - launchAgent: 'codex' as const, - launchToken: 'saved-token', - launchConfig: { agentCommand: 'codex', agentArgs: 'resume C', agentEnv: {} }, - resumeProviderSession: { key: 'session_id' as const, id: 'C' }, - resumeOrigin: 'saved' as const, - resumeSource: source - } - const claim = { - worktreeId: 'wt', - launchAgent: 'codex' as const, - providerSession: startup.resumeProviderSession - } - const status: AgentStatusEntry = { - paneKey: 'tab:leaf', - state: 'done', - prompt: '', - updatedAt: 1, - stateStartedAt: 1, - stateHistory: [] - } - store.setState({ automaticAgentResumeClaimsByTabId: { tab: claim } }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the actual installers/result policy access only these supplied session members. - const session = { - cacheKey: 'tab:leaf', - pane: { id: 1, leafId: 'leaf' }, - paneStartup: startup, - pendingStartupCommand: startup, - startupInjectTimer: null, - deps: { tabId: 'tab', worktreeId: 'wt' }, - showSessionRestoredBanner: vi.fn() - } as unknown as ConnectPanePtySession - installSleepingRecordAccess(session) - const registration = store.getState().agentLaunchConfigByPaneKey['tab:leaf']! - session.savedStartupStatus = { source, entry: status } - let enumerated = 0 - let copied = 0 - const counted = (map: T): T => - new Proxy(map, { - ownKeys(target) { - const keys = Reflect.ownKeys(target) - enumerated += keys.length - return keys - }, - getOwnPropertyDescriptor(target, key) { - const descriptor = Object.getOwnPropertyDescriptor(target, key) - if (descriptor?.enumerable) { - copied += 1 - } - return descriptor - } - }) - const population = (target: string, value: T) => - Object.fromEntries( - Array.from({ length: size }, (_, index) => [ - index === size - 1 ? target : `other-${index}`, - value - ]) - ) - let tabVisits = 0 - const tabs = Array.from({ length: size }, (_, index) => - makeTab({ - id: index === size - 1 ? 'tab' : `other-${index}`, - worktreeId: 'wt' - }) - ) - // Keep the real tab objects; count the actual find predicate's identity reads. - tabs.forEach((tab, index) => - Object.defineProperty(tab, 'id', { - get: () => { - tabVisits += 1 - return index === size - 1 ? 'tab' : `other-${index}` - } - }) - ) - store.setState({ - pendingStartupByTabId: counted(population('tab', startup)), - automaticAgentResumeClaimsByTabId: counted(population('tab', claim)), - agentLaunchConfigByPaneKey: counted(population('tab:leaf', registration)), - agentStatusByPaneKey: counted(population('tab:leaf', status)), - tabsByWorktree: { wt: tabs } - }) - const accepted = vi.fn() - const disposeAccepted = store.getState().subscribeAgentStatusChanges(accepted) - const context = captureTerminalLaunchContext(session, startup) - const successor = { ...startup, resumeSource: { cancelled: false } } - const successorRegistration = { ...registration, registeredAt: 2 } - if (newer) { - session.paneStartup = successor - session.pendingStartupCommand = successor - store.setState({ - pendingStartupByTabId: counted(population('tab', successor)), - automaticAgentResumeClaimsByTabId: counted(population('tab', { ...claim })), - agentLaunchConfigByPaneKey: counted(population('tab:leaf', successorRegistration)), - agentStatusByPaneKey: counted(population('tab:leaf', { ...status, updatedAt: 2 })) - }) - } - enumerated = 0 - copied = 0 - notifications = 0 - tabVisits = 0 - const result = { - agentResumeRefused: 'chat-home' as const, - savedResumeDecision: { - agent: 'codex', - providerSession: startup.resumeProviderSession, - verdict: 'chat-home' as const - } - } - try { - expect(applyTerminalLaunchResult(session, result, context, 'creator')).toBe(true) - expect(source.cancelled).toBe(true) - if (newer) { - expect(accepted).not.toHaveBeenCalled() - } else { - expect(accepted).toHaveBeenCalledExactlyOnceWith([ - { paneKey: 'tab:leaf', previous: status, current: undefined } - ]) - } - // Four independent whole-map spreads, once each; this is work per result, not a latency bound. - expect([enumerated, copied, notifications, tabVisits]).toEqual( - newer ? [0, 0, 0, 0] : [4 * size, 4 * size, 4, size] - ) - const current = store.getState() - if (newer) { - expect(current.pendingStartupByTabId.tab).toBe(successor) - expect(current.agentLaunchConfigByPaneKey['tab:leaf']).toBe(successorRegistration) - expect(current.automaticAgentResumeClaimsByTabId.tab).not.toBe(claim) - expect(current.agentStatusByPaneKey['tab:leaf']?.updatedAt).toBe(2) - expect(session.paneStartup).toBe(successor) - expect(successor.resumeSource.cancelled).toBe(false) - } else { - expect(current.pendingStartupByTabId.tab).toBeUndefined() - expect(current.agentLaunchConfigByPaneKey['tab:leaf']).toBeUndefined() - expect(current.automaticAgentResumeClaimsByTabId.tab).toBeUndefined() - expect(current.agentStatusByPaneKey['tab:leaf']).toBeUndefined() - expect(current.pendingStartupByTabId['other-0']).toBe(startup) - expect(session.pendingStartupCommand).toBeNull() - } - enumerated = 0 - copied = 0 - notifications = 0 - tabVisits = 0 - applyTerminalLaunchResult(session, result, context, 'creator') - expect([enumerated, copied, notifications, tabVisits]).toEqual([0, 0, 0, 0]) - } finally { - disposeAccepted() - unsubscribe() - } - } -}) - -it.each(['canonical', 'legacy', 'live'] as const)( - 'does not recreate a confirmed-exited cold-restore source (%s)', - (kind) => { - const store = createTestStore() - fixture.state = store.getState() - const unsubscribe = store.subscribe((state) => { - fixture.state = state - }) - const paneKey = 'tab:leaf' - const record = { - paneKey: kind === 'legacy' ? 'tab:1' : paneKey, - tabId: 'tab', - worktreeId: 'wt', - agent: 'codex' as const, - providerSession: { key: 'session_id' as const, id: 'C' }, - prompt: '', - state: 'done' as const, - capturedAt: 1, - updatedAt: 1 - } - store.getState().rememberSleepingAgentSession(record) - const startup: ColdRestoreAgentResumeStartup = { - agent: 'codex', - command: 'codex resume C', - launchToken: 'token', - launchConfig: { agentCommand: 'codex', agentArgs: '', agentEnv: {} }, - resumeProviderSession: record.providerSession, - resumeOrigin: 'saved', - resumeSource: { - cancelled: false, - record, - expectedStatus: { paneKey, receivedAt: 1, stateStartedAt: 1 } - }, - useLiveEntry: kind === 'live', - hasSleepingRecord: kind !== 'live', - sleepingRecordEntry: kind === 'live' ? null : { paneKey: record.paneKey, record } - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only binding and retention run; all their accessed members are supplied. - const session = { - cacheKey: paneKey, - deps: { tabId: 'tab', worktreeId: 'wt' }, - pane: { id: 1, leafId: 'leaf' }, - manager: {}, - paneStartup: null - } as unknown as ConnectPanePtySession - installSleepingRecordAccess(session) - bindDeferredColdRestoreAndSnapshot(session) - store.getState().clearSleepingAgentSession(record.paneKey) - session.keepResumeRecordAfterColdRestoreSpawn(startup) - expect(store.getState().sleepingAgentSessionsByPaneKey).toEqual({}) - unsubscribe() - } -) - -it.each([ - { - liveId: 'C', - savedId: 'C', - savedHost: 'ssh-A', - liveHost: undefined, - expected: 'ssh-A', - host: 'ssh:ssh-A' - }, - { - liveId: 'D', - savedId: 'C', - savedHost: 'ssh-A', - liveHost: undefined, - expected: undefined, - host: 'ssh:ssh-A' - }, - { liveId: 'C', savedId: 'C', savedHost: null, liveHost: null, expected: null, host: 'local' } -])('retains only matching captured host evidence ($liveId, $savedHost, $liveHost)', (testCase) => { - const store = createTestStore() - fixture.state = store.getState() - const unsubscribe = store.subscribe((state) => { - fixture.state = state - }) - const paneKey = 'tab:leaf' - store.setState({ - agentStatusByPaneKey: { - [paneKey]: { - paneKey, - agentType: 'codex', - state: 'working', - prompt: '', - updatedAt: 1, - stateStartedAt: 1, - stateHistory: [], - connectionId: testCase.liveHost, - providerSession: { key: 'session_id', id: testCase.liveId } - } - }, - sleepingAgentSessionsByPaneKey: { - [paneKey]: { - paneKey, - worktreeId: 'wt', - agent: 'codex', - state: 'working', - prompt: '', - updatedAt: 1, - capturedAt: 1, - connectionId: testCase.savedHost, - providerSession: { key: 'session_id', id: testCase.savedId } - } - } - }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only startup construction and retention run; all accessed session members are supplied. - const session = { - cacheKey: paneKey, - deps: { tabId: 'tab', worktreeId: 'wt' }, - pane: { id: 1, leafId: 'leaf' }, - manager: {}, - paneStartup: null, - worktree: { path: '/tmp' }, - executionHostId: testCase.host, - transport: { getRuntimeEnvironmentId: () => null } - } as unknown as ConnectPanePtySession - installSleepingRecordAccess(session) - bindBuildColdRestoreAgentResumeStartup(session) - bindDeferredColdRestoreAndSnapshot(session) - const startup = session.buildColdRestoreAgentResumeStartup() - expect(startup).not.toBeNull() - session.keepResumeRecordAfterColdRestoreSpawn(startup) - expect(store.getState().sleepingAgentSessionsByPaneKey[paneKey]?.connectionId).toBe( - testCase.expected - ) - unsubscribe() -}) diff --git a/src/renderer/src/components/terminal-pane/pty-connection/tests/input-modes/pty-connection-kitty-keyboard-restore.spec.ts b/src/renderer/src/components/terminal-pane/pty-connection/tests/input-modes/pty-connection-kitty-keyboard-restore.spec.ts deleted file mode 100644 index 55e68dbfc4a..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-connection/tests/input-modes/pty-connection-kitty-keyboard-restore.spec.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { bindPtyConnectionTestMocks } from '../../test-fixtures/pty-connection-mocks.spec' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - POST_REPLAY_REATTACH_RESET, - PROCESS_BOUNDARY_GROUND -} from '../../../../../../../shared/terminal/protocol/input-modes/terminal-mode-reset-profiles' -import { TerminalKittyKeyboardModeTracker } from '../../../../../../../shared/terminal/protocol/input-modes/terminal-kitty-keyboard-mode-tracker' -import { replayEpilogue } from '../../test-fixtures/pty-connection-test-replay-epilogue' -import { flushAsyncTicks } from '../../test-fixtures/pty-connection-test-async' -import { - LEAF_1, - createMockTransport, - createPane, - createManager, - type MockTransport -} from '../../test-fixtures/pty-connection-test-pane-fixtures' -import { - buildPaneConnectionDeps, - type PtyConnectionAgentTitleMocks, - bindPaneAgentTitleMocks -} from '../../test-fixtures/pty-connection-test-deps' -import { createInitialStoreState } from '../../test-fixtures/pty-connection-test-store-fixtures' -import type { StoreState } from '../../test-fixtures/pty-connection-test-store-state' -import { - installTerminalTestGlobals, - restoreTerminalTestGlobals -} from '../../test-fixtures/pty-connection-test-environment' -import { mockPanePtyArgs } from '../../test-fixtures/pty-connection-test-connect-mock-pane' - -export function registerPtyConnectionKittyKeyboardRestoreTests(): void { - let mockStoreState: StoreState - let transportFactoryQueue: MockTransport[] = [] - let createdTransportOptions: Record[] = [] - let storeSubscribers: ((state: StoreState) => void)[] = [] - - function createDeps(overrides: Record = {}) { - return buildPaneConnectionDeps(() => mockStoreState, overrides) - } - - // Why: xterm and the pane mirror must end every restore on the same kitty flags. - describe('connectPanePty kitty keyboard restore', () => { - beforeEach(async () => { - vi.resetModules() - vi.clearAllMocks() - transportFactoryQueue = [] - createdTransportOptions = [] - storeSubscribers = [] - mockStoreState = createInitialStoreState(() => mockStoreState) - bindPtyConnectionTestMocks({ - getState: () => mockStoreState, - getTransportQueue: () => transportFactoryQueue, - getTransportOptions: () => createdTransportOptions, - getStoreSubscribers: () => storeSubscribers, - setStoreSubscribers: (subscribers) => { - storeSubscribers = subscribers - } - }) - await installTerminalTestGlobals() - }) - - afterEach(async () => { - await restoreTerminalTestGlobals() - }) - - async function reattachWithSnapshotFlags(kittyKeyboard: boolean) { - const { connectPanePty } = await import('../../connect-pane-pty') - const agentTitleMocks = await vi.importMock( - '@/lib/agent-status/aggregation/worktree-agent-status' - ) - const transport = createMockTransport('tab-pty') - transport.connect.mockImplementation(async ({ sessionId }: { sessionId?: string }) => - sessionId - ? { - id: sessionId, - snapshot: 'live app frame', - snapshotKittyKeyboardFlags: 31, - snapshotSeq: 7 - } - : null - ) - transportFactoryQueue.push(transport) - const pane = createPane(1) - pane.terminal.options.vtExtensions.kittyKeyboard = kittyKeyboard - const deps = createDeps({ - restoredLeafId: LEAF_1, - restoredPtyIdByLeafId: { [LEAF_1]: 'tab-pty' } - }) - connectPanePty( - ...mockPanePtyArgs(pane, createManager(1), bindPaneAgentTitleMocks(deps, agentTitleMocks)) - ) - await flushAsyncTicks(20) - return { pane, mirror: deps.paneKittyKeyboardModesRef.current.get(pane.id) } - } - - it("restores a live app's host-proven flags into xterm and the mirror on reattach", async () => { - const { pane, mirror } = await reattachWithSnapshotFlags(true) - - expect(pane.terminal.write).toHaveBeenCalledWith( - `${POST_REPLAY_REATTACH_RESET}\x1b[<99u\x1b[=31u`, - expect.any(Function) - ) - expect(mirror?.flags).toBe(31) - }) - - // Why: xterm ignores CSI u while the protocol is withheld (ConPTY), so its mirror must too. - it('keeps a withheld-protocol pane at 0 in both records despite host flags', async () => { - const { pane, mirror } = await reattachWithSnapshotFlags(false) - - expect(pane.terminal.write).toHaveBeenCalledWith( - replayEpilogue(POST_REPLAY_REATTACH_RESET), - expect.any(Function) - ) - expect(mirror?.flags).toBe(0) - }) - - it('grounds xterm and the mirror with one scanned write before a restart-in-place spawns', async () => { - const { connectPanePty } = await import('../../connect-pane-pty') - const agentTitleMocks2 = await vi.importMock( - '@/lib/agent-status/aggregation/worktree-agent-status' - ) - transportFactoryQueue.push(createMockTransport()) - const pane = createPane(91) - // Use a unique tab ID to avoid other tests’ pending-spawn entries and force fresh spawn. - const deps = createDeps({ tabId: 'tab-kitty-fresh-spawn' }) - // The pane's previous occupant left the alternate screen and kitty flags on. - const mirror = new TerminalKittyKeyboardModeTracker() - mirror.scan('\x1b[?1049h\x1b[>5u') - deps.paneKittyKeyboardModesRef.current.set(pane.id, mirror) - - connectPanePty( - ...mockPanePtyArgs(pane, createManager(91), bindPaneAgentTitleMocks(deps, agentTitleMocks2)) - ) - await flushAsyncTicks(20) - - expect(pane.terminal.write).toHaveBeenCalledWith( - PROCESS_BOUNDARY_GROUND, - expect.any(Function) - ) - expect(mirror.snapshotFlags).toBe(0) - expect(mirror.isAlternateScreen).toBe(false) - }) - - it('grounds xterm and the mirror together on Reset Terminal and asks the host to ground', async () => { - const { pane, mirror } = await reattachWithSnapshotFlags(true) - expect(mirror?.flags).toBe(31) - const { resetTerminalInputModes } = await import('../../../input/terminal-input-mode-reset') - - resetTerminalInputModes('tab-pty') - - expect(pane.terminal.write).toHaveBeenLastCalledWith( - PROCESS_BOUNDARY_GROUND, - expect.any(Function) - ) - expect(mirror?.flags).toBe(0) - expect(window.api.pty.resetInputModes).toHaveBeenCalledWith('tab-pty') - }) - }) -} diff --git a/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts b/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts index 897ff913c74..34980f72e97 100644 --- a/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-input-and-repaint.test.ts @@ -1,5 +1,4 @@ import { describe, vi } from 'vitest' -import { registerPtyConnectionKittyKeyboardRestoreTests } from './input-modes/pty-connection-kitty-keyboard-restore.spec' import { registerPtyConnectionMode2031SubscriptionsTests } from '../emulation/pty-connection-mode-2031-subscriptions.spec' import { registerPtyConnectionDaemonPendingEscapeTailTests, @@ -24,7 +23,6 @@ vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => ).runtimeRpcClientWithLayoutApply(await importOriginal()) ) -describe('pty-connection-kitty-keyboard-restore', registerPtyConnectionKittyKeyboardRestoreTests) describe('pty-connection-mode-2031-subscriptions', registerPtyConnectionMode2031SubscriptionsTests) describe('pty-connection-reattach-mode-reset', () => { registerPtyConnectionDaemonPendingEscapeTailTests() diff --git a/src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-pi-routing.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-pi-routing.test.ts index f952035339e..f35b0dac1ce 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-pi-routing.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport/delivery/pty-dispatcher-pi-routing.test.ts @@ -1,17 +1,6 @@ -// Why: reproduce the renderer Pi spinner pipeline (pty:data IPC → onTitleChange); electron verification showed frames arrive but the store never sees the canonicalized "⠋ π - cwd" working title. - import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -const ESC = '\x1b' -const BEL = '\x07' -const workingFrame = (frame: string): string => `${ESC}]0;${frame} π - cwd${BEL}` -const idleTitle = (): string => `${ESC}]0;π - cwd${BEL}` - -function flushPtySideEffects(): Promise { - return new Promise((resolve) => setTimeout(resolve, 0)) -} - -describe('dispatcher → transport → onTitleChange for Pi spinner', () => { +describe('dispatcher delivery before attachment and during exit', () => { const originalWindow = (globalThis as { window?: typeof window }).window // The singleton dispatcher subscribes one global onData callback; we capture it to simulate main delivering IPC events directly. @@ -72,175 +61,6 @@ describe('dispatcher → transport → onTitleChange for Pi spinner', () => { } }) - it('ACKs PTY data after dispatcher consumers accept the chunk', async () => { - const { ensurePtyDispatcher } = await import('./pty-dispatcher') - const { ptyDataHandlers } = await import('../shutdown/pty-shutdown-data-suspension') - const handler = vi.fn() - - ensurePtyDispatcher() - ptyDataHandlers.set('pty-pi', handler) - - dispatcherCallback?.({ id: 'pty-pi', data: 'chunk', rawLength: 10, background: true } as never) - - expect(handler).toHaveBeenCalledWith('chunk', { rawLength: 10, background: true }) - expect(window.api.pty.ackData).toHaveBeenCalledWith('pty-pi', 10, 10) - ptyDataHandlers.delete('pty-pi') - }) - - it('signals main that the pty:data listener is live exactly once per page load', async () => { - // Why: main gates all pty sends on this handshake, so a silent no-op would stall delivery until the 10s watchdog; assert it fires exactly once. - const { ensurePtyDispatcher } = await import('./pty-dispatcher') - - ensurePtyDispatcher() - ensurePtyDispatcher() - - expect(window.api.pty.rendererDispatcherReady).toHaveBeenCalledTimes(1) - }) - - it('routes Pi OSC title frames from pty:data → onTitleChange via the dispatcher', async () => { - const { createIpcPtyTransport } = await import('../ipc/pty-transport') - const onTitleChange = vi.fn() - - const transport = createIpcPtyTransport({ onTitleChange }) - await transport.connect({ url: '', callbacks: {} }) - - expect(dispatcherCallback).not.toBeNull() - - dispatcherCallback?.({ id: 'pty-pi', data: idleTitle() }) - dispatcherCallback?.({ id: 'pty-pi', data: workingFrame('⠋') }) - dispatcherCallback?.({ id: 'pty-pi', data: workingFrame('⠙') }) - dispatcherCallback?.({ id: 'pty-pi', data: idleTitle() }) - await flushPtySideEffects() - - const seenTitles = onTitleChange.mock.calls.map((c) => c[0]) - expect(seenTitles).toContain('⠋ π - cwd') - - transport.disconnect() - }) - - it('pipeline survives a chunk carrying shell output interleaved with spinner frames', async () => { - // Why: node-pty's 8ms batching packs multiple OSC titles + body into one chunk; the handler takes the LAST title, which must still surface working frames. - const { createIpcPtyTransport } = await import('../ipc/pty-transport') - const onTitleChange = vi.fn() - - const transport = createIpcPtyTransport({ onTitleChange }) - await transport.connect({ url: '', callbacks: {} }) - - dispatcherCallback?.({ - id: 'pty-pi', - data: `assistant output line 1\r\n${workingFrame('⠋')}more body text` - }) - await flushPtySideEffects() - - const seenTitles = onTitleChange.mock.calls.map((c) => c[0]) - expect(seenTitles).toContain('⠋ π - cwd') - - transport.disconnect() - }) - - it('attach()-flow pipeline delivers working frames to onTitleChange', async () => { - // Why: reattach uses attach() not connect(); if handler registration drifted between them, remounted Pi sessions would stop emitting spinner signals. - const { createIpcPtyTransport } = await import('../ipc/pty-transport') - const onTitleChange = vi.fn() - - const transport = createIpcPtyTransport({ onTitleChange }) - transport.attach({ existingPtyId: 'pty-pi', callbacks: {} }) - - // attach()'s eager-buffer replay can flush initial titles; only assert on frames pushed after attach resolves. - onTitleChange.mockClear() - - dispatcherCallback?.({ id: 'pty-pi', data: workingFrame('⠋') }) - await flushPtySideEffects() - - const seenTitles = onTitleChange.mock.calls.map((c) => c[0]) - expect(seenTitles).toContain('⠋ π - cwd') - - transport.disconnect() - }) - - it('reproduces "Pi is idle" state: after working→idle, onTitleChange ends on the idle title', async () => { - // Why: bug shows the store stuck at the idle title while working — assert both working and idle titles reach onTitleChange, in order. - const { createIpcPtyTransport } = await import('../ipc/pty-transport') - const onTitleChange = vi.fn() - - const transport = createIpcPtyTransport({ onTitleChange }) - await transport.connect({ url: '', callbacks: {} }) - - dispatcherCallback?.({ id: 'pty-pi', data: idleTitle() }) - dispatcherCallback?.({ id: 'pty-pi', data: workingFrame('⠋') }) - dispatcherCallback?.({ id: 'pty-pi', data: workingFrame('⠙') }) - dispatcherCallback?.({ id: 'pty-pi', data: idleTitle() }) - await flushPtySideEffects() - - const seenTitles = onTitleChange.mock.calls.map((c) => c[0]) - const workingIdx = seenTitles.indexOf('⠋ π - cwd') - const finalIdleIdx = seenTitles.lastIndexOf('π - cwd') - expect(workingIdx).toBeGreaterThanOrEqual(0) - expect(finalIdleIdx).toBeGreaterThan(workingIdx) - - transport.disconnect() - }) - - // Cursor’s bare native redraw must not overwrite the synthesized working spinner mid-turn. - it('drops cursor-agent native "Cursor Agent" title so it cannot overwrite the synthesized spinner', async () => { - const { createIpcPtyTransport } = await import('../ipc/pty-transport') - const onTitleChange = vi.fn() - - const transport = createIpcPtyTransport({ onTitleChange }) - await transport.connect({ url: '', callbacks: {} }) - - dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;⠋ Cursor Agent${BEL}` }) - dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;Cursor Agent${BEL}` }) - dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;⠙ Cursor Agent${BEL}` }) - dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;Cursor Agent${BEL}` }) - await flushPtySideEffects() - - const seenTitles = onTitleChange.mock.calls.map((c) => c[0]) - expect(seenTitles).not.toContain('Cursor Agent') - expect(seenTitles).toContain('⠋ Cursor Agent') - expect(seenTitles).toContain('⠙ Cursor Agent') - - transport.disconnect() - }) - - it('still surfaces the synthesized "Cursor ready" idle title after working', async () => { - // Why: the bare-title drop must not also catch the decorated "Cursor ready" done frame Orca synthesizes on the stop hook. - const { createIpcPtyTransport } = await import('../ipc/pty-transport') - const onTitleChange = vi.fn() - - const transport = createIpcPtyTransport({ onTitleChange }) - await transport.connect({ url: '', callbacks: {} }) - - dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;⠋ Cursor Agent${BEL}` }) - dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;Cursor Agent${BEL}` }) - dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;Cursor ready${BEL}${BEL}` }) - await flushPtySideEffects() - - const seenTitles = onTitleChange.mock.calls.map((c) => c[0]) - expect(seenTitles).toContain('⠋ Cursor Agent') - expect(seenTitles).toContain('Cursor ready') - - transport.disconnect() - }) - - it('surfaces synthesized "Codex ready" idle titles after Codex spinner titles', async () => { - const { createIpcPtyTransport } = await import('../ipc/pty-transport') - const onTitleChange = vi.fn() - - const transport = createIpcPtyTransport({ onTitleChange }) - await transport.connect({ url: '', callbacks: {} }) - - dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;\u280b Codex${BEL}` }) - dispatcherCallback?.({ id: 'pty-pi', data: `${ESC}]0;Codex ready${BEL}` }) - await flushPtySideEffects() - - const seenTitles = onTitleChange.mock.calls.map((c) => c[0]) - expect(seenTitles).toContain('\u280b Codex') - expect(seenTitles).toContain('Codex ready') - - transport.disconnect() - }) - it('replays PTY data that arrives before connect() registers the pane handler', async () => { const { createIpcPtyTransport } = await import('../ipc/pty-transport') const onData = vi.fn() diff --git a/src/renderer/src/components/terminal-pane/pty-transport/delivery/terminal-delivery-watchdog.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/delivery/terminal-delivery-watchdog.test.ts deleted file mode 100644 index f220ce9fdb4..00000000000 --- a/src/renderer/src/components/terminal-pane/pty-transport/delivery/terminal-delivery-watchdog.test.ts +++ /dev/null @@ -1,167 +0,0 @@ -// Confirm dead push delivery over two silent ticks, then heal through invoke once per cooldown: reattach first and deliver pulled restore markers locally. -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import type { PtyRendererDeliveryHealthReply } from '../../../../../../shared/terminal/pty/diagnostics/pty-renderer-delivery-health' - -vi.mock('@/lib/e2e-config', () => ({ e2eConfig: { exposeStore: false } })) - -const INTERVAL_MS = 15_000 - -const HEALTHY: PtyRendererDeliveryHealthReply = { - inFlightTotalChars: 0, - inFlightPtyCount: 0, - msSinceLastAck: 1_000 -} - -const STALLED: PtyRendererDeliveryHealthReply = { - inFlightTotalChars: 512 * 1024, - inFlightPtyCount: 2, - msSinceLastAck: null -} - -describe('terminal delivery watchdog', () => { - const originalWindow = (globalThis as { window?: typeof window }).window - const reportMock = vi.fn<(args: unknown) => Promise>() - const listenerCountMock = vi.fn(() => 1) - const reattachMock = vi.fn() - let warnSpy: ReturnType - - beforeEach(() => { - vi.resetModules() - vi.useFakeTimers() - reportMock.mockReset() - listenerCountMock.mockClear() - reattachMock.mockClear() - warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}) - ;(globalThis as { window: typeof window }).window = { - ...originalWindow, - api: { - ...originalWindow?.api, - pty: { - ...originalWindow?.api?.pty, - reportRendererDeliveryState: reportMock, - getPtyDataListenerCount: listenerCountMock - } - } - } as unknown as typeof window - }) - - afterEach(() => { - warnSpy.mockRestore() - vi.useRealTimers() - if (originalWindow) { - ;(globalThis as { window: typeof window }).window = originalWindow - } else { - delete (globalThis as { window?: typeof window }).window - } - }) - - async function startWatchdog(): Promise<{ - recordPtyDataReceived: (ptyId: string, chars: number) => void - registerRestoreHandler: ( - ptyId: string, - handler: (event: { id: string; reason: string; markerSeq?: number }) => void - ) => void - }> { - const watchdog = await import('./terminal-delivery-watchdog') - const restoreChannel = await import('./pty-model-restore-channel') - watchdog.startTerminalDeliveryWatchdog({ - reattachPushListeners: reattachMock, - hasAttachedPtys: () => true - }) - return { - recordPtyDataReceived: watchdog.recordPtyDataReceived, - registerRestoreHandler: (ptyId, handler) => { - restoreChannel.registerPtyModelRestoreNeededHandler(ptyId, handler) - } - } - } - - it('does zero IPC while pty output is flowing', async () => { - const { recordPtyDataReceived } = await startWatchdog() - - for (let tick = 0; tick < 8; tick++) { - recordPtyDataReceived('pty-1', 64) - await vi.advanceTimersByTimeAsync(INTERVAL_MS) - } - - expect(reportMock).not.toHaveBeenCalled() - }) - - it('reports during silence but never heals a healthy-idle main', async () => { - reportMock.mockResolvedValue(HEALTHY) - await startWatchdog() - - await vi.advanceTimersByTimeAsync(INTERVAL_MS * 4) - - expect(reportMock).toHaveBeenCalledTimes(4) - for (const call of reportMock.mock.calls) { - expect((call[0] as { heal?: boolean }).heal).toBeUndefined() - } - expect(reattachMock).not.toHaveBeenCalled() - }) - - it('confirms a wedge across two silent ticks, re-attaches, and routes pulled restore markers', async () => { - reportMock.mockImplementation((args) => - Promise.resolve( - (args as { heal?: boolean }).heal - ? { - ...STALLED, - inFlightTotalChars: 0, - inFlightPtyCount: 0, - writtenOff: [{ id: 'pty-1', markerSeq: 42, writtenOffChars: 512 * 1024 }] - } - : STALLED - ) - ) - const { recordPtyDataReceived, registerRestoreHandler } = await startWatchdog() - const restoreEvents: { id: string; reason: string; markerSeq?: number }[] = [] - registerRestoreHandler('pty-1', (event) => restoreEvents.push(event)) - - // Bytes flowed once, then the push channel died: the field shape. - recordPtyDataReceived('pty-1', 128) - await vi.advanceTimersByTimeAsync(INTERVAL_MS) - expect(reportMock).not.toHaveBeenCalled() - - // First silent tick: report only, no heal yet. - await vi.advanceTimersByTimeAsync(INTERVAL_MS) - expect(reportMock).toHaveBeenCalledTimes(1) - expect(reattachMock).not.toHaveBeenCalled() - - // Require reattach before heal and local marker delivery without any push event; retain the prior listener count for diagnosis. - await vi.advanceTimersByTimeAsync(INTERVAL_MS) - expect(reattachMock).toHaveBeenCalledTimes(1) - const healCalls = reportMock.mock.calls.filter( - (call) => (call[0] as { heal?: boolean }).heal === true - ) - expect(healCalls).toHaveLength(1) - expect(healCalls[0]![0]).toMatchObject({ - heal: true, - rendererPtyDataListenerCount: 1, - receivedCharsByPty: { 'pty-1': 128 } - }) - expect(restoreEvents).toEqual([{ id: 'pty-1', reason: 'delivery-heal', markerSeq: 42 }]) - }) - - it('rate-limits heals to the cooldown while the wedge persists', async () => { - reportMock.mockImplementation((args) => - Promise.resolve((args as { heal?: boolean }).heal ? { ...STALLED, writtenOff: [] } : STALLED) - ) - await startWatchdog() - - const countHeals = (): number => - reportMock.mock.calls.filter((call) => (call[0] as { heal?: boolean }).heal === true).length - - // Ticks at 15s/30s: confirm + first heal. - await vi.advanceTimersByTimeAsync(INTERVAL_MS * 2) - expect(countHeals()).toBe(1) - - // 45s/60s/75s: streak rebuilds but the 60s cooldown holds. - await vi.advanceTimersByTimeAsync(INTERVAL_MS * 3) - expect(countHeals()).toBe(1) - - // 90s: cooldown elapsed — one more heal, not one per tick. - await vi.advanceTimersByTimeAsync(INTERVAL_MS) - expect(countHeals()).toBe(2) - expect(reattachMock).toHaveBeenCalledTimes(2) - }) -}) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts index 99c22fd0fca..8ce3a4eee22 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport/input/pty-input-write-queue.test.ts @@ -1,31 +1,12 @@ import { describe, expect, it, vi } from 'vitest' -import { Terminal } from '@xterm/headless' import { createPtyInputWriteQueue } from './pty-input-write-queue' -import { - PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES, - PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLY_CODE_UNITS, - TERMINAL_INPUT_COALESCE_MAX_CODE_UNITS -} from './pty-input-write-queue-contract' -import { - TERMINAL_INPUT_CHUNK_MAX_BYTES, - TERMINAL_INPUT_MAX_BYTES -} from '../../../../../../shared/terminal/input/terminal-input' +import { TERMINAL_INPUT_CHUNK_MAX_BYTES } from '../../../../../../shared/terminal/input/terminal-input' import { CLIPBOARD_TEXT_MEASURE_YIELD_CODE_UNITS } from '../../../../../../shared/clipboard-text' -import { mode2031SequenceFor } from '../../../../../../shared/terminal/protocol/queries/terminal-color-scheme-protocol' -import { PtyStartupIngress } from '../../../../../../shared/terminal/pty/ingress/pty-startup-ingress' -import type { PtyIngressEmission } from '../../../../../../shared/terminal/pty/ingress/pty-startup-ingress-contract' -import { - extractOnlyCookedEchoSafeQueryReplies, - needsCookedEchoSafeQueryReply -} from '../../../../../../shared/terminal/protocol/queries/terminal-query-reply' -import { installTerminalCapabilityReplyHandlers } from '../../emulation/terminal-capability-replies' import { createDeferred, flushAsyncTicks } from '../../pty-connection/test-fixtures/pty-connection-test-async' -const WHEEL_UP_REPORT = '\x1b[<64;60;20M' - type WriteRecord = { id: string; data: string } function createRecordingQueue(options: { writable?: () => boolean } = {}): { @@ -40,364 +21,7 @@ function createRecordingQueue(options: { writable?: () => boolean } = {}): { return { writes, queue } } -function createParkedQueue(): { - writes: WriteRecord[] - pendingYields: (() => void)[] - queue: ReturnType -} { - const writes: WriteRecord[] = [] - const pendingYields: (() => void)[] = [] - const queue = createPtyInputWriteQueue({ - isWritable: () => true, - write: (id, data) => writes.push({ id, data }), - yieldBetweenWrites: () => - new Promise((resolve) => { - pendingYields.push(resolve) - }) - }) - return { writes, pendingYields, queue } -} - -async function releaseNextWrite( - writes: WriteRecord[], - pendingYields: (() => void)[] -): Promise { - const before = writes.length - const release = pendingYields.shift() - expect(release).toBeDefined() - release?.() - await Promise.resolve() - expect(writes.length).toBeGreaterThan(before) -} - -function writeTerminal(term: Terminal, data: string): Promise { - return new Promise((resolve) => term.write(data, resolve)) -} - -function extractReplyWrites(writes: WriteRecord[]): string[] { - return writes.flatMap((write) => extractOnlyCookedEchoSafeQueryReplies(write.data) ?? []) -} - describe('pty input write queue', () => { - it('coalesces a dense burst of wheel reports instead of one write per macrotask turn', async () => { - const { writes, queue } = createRecordingQueue() - - // Queue a 120Hz two-second gesture; the first report is immediate and the rest must coalesce without hundreds of timer turns. - for (let i = 0; i < 240; i += 1) { - expect(queue.enqueue('pty-1', WHEEL_UP_REPORT, 'driving')).toBe(true) - } - await queue.waitForDrain() - - // First report flushes immediately (keystroke latency); everything queued - // behind it must drain as a single coalesced write, not 239 timer turns. - expect(writes.length).toBe(2) - expect(writes[0]?.data).toBe(WHEEL_UP_REPORT) - expect(writes[1]?.data).toBe(WHEEL_UP_REPORT.repeat(239)) - expect(writes.map((write) => write.id)).toEqual(['pty-1', 'pty-1']) - }) - - it('preserves byte order and content across coalesced writes', async () => { - const { writes, queue } = createRecordingQueue() - - const inputs = ['a', '\x1b[<65;1;1M', 'bc', '\x1b[A', 'd'] - for (const input of inputs) { - queue.enqueue('pty-1', input, 'driving') - } - await queue.waitForDrain() - - expect(writes.map((write) => write.data).join('')).toBe(inputs.join('')) - }) - - it('does not coalesce across different PTY ids', async () => { - const writes: WriteRecord[] = [] - const queue = createPtyInputWriteQueue({ - isWritable: () => true, - write: (id, data) => writes.push({ id, data }) - }) - - queue.enqueue('pty-1', 'a', 'driving') - queue.enqueue('pty-1', 'b', 'driving') - queue.enqueue('pty-2', 'c', 'driving') - queue.enqueue('pty-1', 'd', 'driving') - await queue.waitForDrain() - - expect(writes).toEqual([ - { id: 'pty-1', data: 'a' }, - { id: 'pty-1', data: 'b' }, - { id: 'pty-2', data: 'c' }, - { id: 'pty-1', data: 'd' } - ]) - }) - - it('keeps coalesced payloads under the input chunk byte cap', async () => { - const { writes, queue } = createRecordingQueue() - - const piece = 'x'.repeat(1000) - for (let i = 0; i < 12; i += 1) { - queue.enqueue('pty-1', piece, 'driving') - } - await queue.waitForDrain() - - expect(writes.map((write) => write.data).join('')).toBe(piece.repeat(12)) - for (const write of writes) { - expect(write.data.length).toBeLessThanOrEqual(TERMINAL_INPUT_COALESCE_MAX_CODE_UNITS) - } - expect(writes.length).toBeGreaterThan(1) - }) - - it('still chunks oversized items and keeps trailing input ordered behind them', async () => { - const { writes, queue } = createRecordingQueue() - - const large = 'y'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES * 2 + 100) - queue.enqueue('pty-1', 'before', 'driving') - queue.enqueue('pty-1', large, 'driving') - queue.enqueue('pty-1', 'after', 'driving') - await queue.waitForDrain() - - expect(writes.map((write) => write.data).join('')).toBe(`before${large}after`) - expect(writes.at(-1)?.data).toBe('after') - for (const write of writes) { - expect(write.data.length).toBeLessThanOrEqual(TERMINAL_INPUT_CHUNK_MAX_BYTES) - } - }) - - it('rejects input over the terminal input byte limit without writing', async () => { - const { writes, queue } = createRecordingQueue() - - expect(queue.enqueue('pty-1', 'z'.repeat(TERMINAL_INPUT_MAX_BYTES + 1), 'driving')).toBe(false) - await queue.waitForDrain() - - expect(writes).toEqual([]) - }) - - it('drops queued input for PTYs that are no longer writable', async () => { - let writable = true - const { writes, queue } = createRecordingQueue({ writable: () => writable }) - - queue.enqueue('pty-1', 'a', 'driving') - writable = false - queue.enqueue('pty-1', 'b', 'driving') - await queue.waitForDrain() - - expect(writes).toEqual([{ id: 'pty-1', data: 'a' }]) - }) - - it('does not coalesce dual color-scheme replies into one host write (#13137)', async () => { - const { writes, queue } = createRecordingQueue() - const reply = mode2031SequenceFor('dark') - - expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true) - expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true) - await queue.waitForDrain() - - expect(writes).toEqual([ - { id: 'pty-1', data: reply }, - { id: 'pty-1', data: reply } - ]) - }) - - it('keeps all query replies atomic for host-side ordering (#13892)', async () => { - const { writes, queue } = createRecordingQueue() - const replies = ['\x1b[?1;2c', '\x1b[1;1R'] - - for (const reply of replies) { - expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true) - } - await queue.waitForDrain() - - expect(writes.map((write) => write.data)).toEqual(replies) - }) - - it('does not coalesce a color-scheme reply with a following keystroke', async () => { - const { writes, queue } = createRecordingQueue() - const reply = mode2031SequenceFor('dark') - - queue.enqueueQueryReply('pty-1', reply) - queue.enqueue('pty-1', 'y', 'driving') - await queue.waitForDrain() - - expect(writes).toEqual([ - { id: 'pty-1', data: reply }, - { id: 'pty-1', data: 'y' } - ]) - }) - - it('bounds an OSC 10/11 reply flood and drains a following keystroke', async () => { - const { writes, pendingYields, queue } = createParkedQueue() - const replies: string[] = [] - let allAccepted = true - - for (let index = 0; index < 10_000; index += 1) { - const color = index.toString(16).padStart(4, '0') - const reply = `\x1b]${index % 2 === 0 ? 10 : 11};rgb:${color}/0000/0000\x1b\\` - replies.push(reply) - allAccepted = queue.enqueueQueryReply('pty-1', reply) && allAccepted - } - expect(allAccepted).toBe(true) - expect(queue.enqueue('pty-1', 'k', 'driving')).toBe(true) - - await Promise.resolve() - expect(pendingYields).toHaveLength(1) - for (let turn = 0; turn < PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES; turn += 1) { - await releaseNextWrite(writes, pendingYields) - } - await queue.waitForDrain() - - const replyWrites = writes.filter((write) => write.data.startsWith('\x1b]')) - expect(replyWrites.map((write) => write.data)).toEqual([ - replies[0], - ...replies.slice(-PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES) - ]) - expect(replyWrites.every((write) => needsCookedEchoSafeQueryReply(write.data))).toBe(true) - expect(writes.at(-1)?.data).toBe('k') - }) - - it('applies the same bound to DA1 replies kept atomic for ordering', async () => { - const { writes, pendingYields, queue } = createParkedQueue() - const replies = Array.from({ length: 10_000 }, (_, index) => `\x1b[?${index};2c`) - - for (const reply of replies) { - expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true) - } - expect(queue.enqueue('pty-1', 'k', 'driving')).toBe(true) - - await Promise.resolve() - for (let turn = 0; turn < PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES; turn += 1) { - await releaseNextWrite(writes, pendingYields) - } - await queue.waitForDrain() - - expect(writes.map((write) => write.data)).toEqual([ - replies[0], - ...replies.slice(-PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES), - 'k' - ]) - }) - - it('drops the oldest reply-only payload when the reply text budget fills', async () => { - const reply = (slot: 10 | 11, marker: string): string => - `\x1b]${slot};${marker.repeat(1_400)}\x1b\\` - const first = reply(10, '1') - const dropped = reply(11, '2') - const second = reply(10, '3') - const third = reply(11, '4') - const { writes, pendingYields, queue } = createParkedQueue() - - expect(second.length * 2).toBeLessThanOrEqual( - PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLY_CODE_UNITS - ) - expect(second.length * 3).toBeGreaterThan(PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLY_CODE_UNITS) - queue.enqueueQueryReply('pty-1', first) - queue.enqueueQueryReply('pty-1', dropped) - queue.enqueue('pty-1', 'x', 'driving') - queue.enqueueQueryReply('pty-1', second) - queue.enqueueQueryReply('pty-1', third) - queue.enqueue('pty-1', 'k', 'driving') - - await Promise.resolve() - expect(pendingYields).toHaveLength(1) - for (let turn = 0; turn < 3; turn += 1) { - await releaseNextWrite(writes, pendingYields) - } - await queue.waitForDrain() - - expect(writes).toEqual([ - { id: 'pty-1', data: first }, - { id: 'pty-1', data: 'x' }, - { id: 'pty-1', data: second }, - { id: 'pty-1', data: third }, - { id: 'pty-1', data: 'k' } - ]) - }) - - it('bounds replies generated by a real xterm OSC query flood', async () => { - const term = new Terminal({ cols: 80, rows: 24, allowProposedApi: true }) - term.options.theme = { foreground: '#2e3434', background: '#ffffff' } - const { writes, queue } = createRecordingQueue() - const generated: string[] = [] - const disposable = installTerminalCapabilityReplyHandlers({ - terminal: { - cols: term.cols, - rows: term.rows, - element: undefined, - options: term.options - }, - parser: term.parser, - sendInput: (data) => { - generated.push(data) - return queue.enqueueQueryReply('pty-1', data) - }, - isReplaying: () => false - }) - - try { - await writeTerminal(term, '\x1b]10;?;?\x1b\\'.repeat(34)) - await queue.waitForDrain() - - const foreground = '\x1b]10;rgb:2e2e/3434/3434\x1b\\' - const background = '\x1b]11;rgb:ffff/ffff/ffff\x1b\\' - expect(generated).toEqual(Array.from({ length: 34 }, () => [foreground, background]).flat()) - expect(extractReplyWrites(writes)).toEqual([ - foreground, - ...generated.slice(-PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES) - ]) - } finally { - disposable.dispose() - term.dispose() - } - }) - - it('rejects one reply larger than the total reply retention budget', async () => { - const { writes, queue } = createRecordingQueue() - const prefix = '\x1b]10;' - const suffix = '\x1b\\' - const input = `${prefix}${'x'.repeat( - TERMINAL_INPUT_COALESCE_MAX_CODE_UNITS + 1 - prefix.length - suffix.length - )}${suffix}` - - expect(input).toHaveLength(TERMINAL_INPUT_COALESCE_MAX_CODE_UNITS + 1) - expect(queue.enqueueQueryReply('pty-1', input)).toBe(false) - await queue.waitForDrain() - - expect(writes).toEqual([]) - }) - - it('preserves an ordinary backlog while bounding later replies', async () => { - const { writes, queue } = createRecordingQueue() - const ordinary = Array.from({ length: 10_000 }, (_, index) => String(index % 10)) - const replies = Array.from({ length: 10_000 }, (_, index) => `\x1b[?${index};1n`) - - for (const input of ordinary) { - expect(queue.enqueue('pty-1', input, 'driving')).toBe(true) - } - for (const reply of replies) { - expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true) - } - await queue.waitForDrain() - - expect(writes.map((write) => write.data).join('')).toBe( - [...ordinary, ...replies.slice(-PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES)].join('') - ) - expect(extractReplyWrites(writes)).toEqual( - replies.slice(-PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES) - ) - }) - - it('never sheds reply-shaped bytes sent through the ordinary input path', async () => { - const { writes, queue } = createRecordingQueue() - const ordinary = '\x1b]10;user-ordinary-marker\x1b\\' - const replies = Array.from({ length: 10_000 }, (_, index) => `\x1b[?${index};1n`) - - expect(queue.enqueueQueryReply('pty-1', '\x1b[?10000;1n')).toBe(true) - expect(queue.enqueue('pty-1', ordinary, 'driving')).toBe(true) - for (const reply of replies) { - expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true) - } - await queue.waitForDrain() - - expect(writes.map((write) => write.data).join('')).toContain(ordinary) - }) - it('contains drain failures and rejects input until queue reuse', async () => { const failure = new Error('write failed') const writes: WriteRecord[] = [] @@ -554,42 +178,6 @@ describe('pty input write queue', () => { expect(delivered).toEqual(['accepted:stale-active', 'ordinary:fresh']) }) - it('reports the pty id that failed so a rebound owner can ignore the drain failure', async () => { - const failure = new Error('yield failed') - const onDrainFailure = vi.fn() - let rejectYield: ((error: Error) => void) | undefined - const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) - const queue = createPtyInputWriteQueue({ - isWritable: () => true, - write: () => undefined, - yieldBetweenWrites: () => - new Promise((_resolve, reject) => { - rejectYield = reject - }), - onDrainFailure - }) - - try { - expect( - queue.enqueue('pty-1', 'x'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES * 2), 'driving') - ).toBe(true) - expect(rejectYield).toBeDefined() - rejectYield?.(failure) - await queue.waitForDrain() - - expect(onDrainFailure).toHaveBeenCalledExactlyOnceWith('pty-1') - } finally { - warn.mockRestore() - } - }) - - it('keeps a pending reply small enough that one drain step writes and removes it', () => { - // Larger replies would span chunks, so admitReply could evict a half-written entry. - expect(PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLY_CODE_UNITS * 3).toBeLessThanOrEqual( - TERMINAL_INPUT_CHUNK_MAX_BYTES - ) - }) - it('does not let a stale drain failure clear input queued after reuse', async () => { const failure = new Error('stale yield failed') const writes: WriteRecord[] = [] @@ -630,89 +218,6 @@ describe('pty input write queue', () => { } }) - it('dual mode-2031 enqueues through the real queue never paint 997 under host echo-safe write', async () => { - // Mixed versions can coalesce late 997 replies; drive queue→host intercept→echo strip and require no literal leakage at confirmation prompts (#9993). - vi.useFakeTimers() - const reply = mode2031SequenceFor('dark') - // Model ECHOCTL for every control byte so this fixture stays aligned with the encoder. - const caretEcho = (data: string): string => - [...data] - .map((ch) => - ch.charCodeAt(0) < 0x20 ? `^${String.fromCharCode(ch.charCodeAt(0) + 0x40)}` : ch - ) - .join('') - const masterWrites: string[] = [] - const emissions: PtyIngressEmission[] = [] - let ingress!: PtyStartupIngress - ingress = new PtyStartupIngress({ - ownerBackend: 'posix-pty', - write: (data) => { - masterWrites.push(data) - ingress.accept(caretEcho(data)) - }, - onEmission: (emission) => emissions.push(emission) - }) - - // Same intercept shape as LocalPtyProvider.write / Session.write / relay writeData. - const hostWrite = (_id: string, data: string): void => { - if (ingress.answerLiveQueryReply(data)) { - return - } - masterWrites.push(`RAW:${data}`) - ingress.accept(caretEcho(data)) - } - - const queue = createPtyInputWriteQueue({ - isWritable: () => true, - write: hostWrite - }) - - expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true) - expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true) - await queue.waitForDrain() - await vi.advanceTimersByTimeAsync(0) - - expect(masterWrites).toEqual([reply, reply]) - expect(masterWrites.some((write) => write.startsWith('RAW:'))).toBe(false) - const visible = emissions.map((emission) => emission.data).join('') - expect(visible).toBe('') - expect(visible).not.toContain('997') - - ingress.accept('Ok to proceed? (y) ') - const afterPrompt = emissions.map((emission) => emission.data).join('') - expect(afterPrompt).toBe('Ok to proceed? (y) ') - expect(afterPrompt).not.toContain('997;1n') - expect(afterPrompt).not.toContain(reply) - ingress.drainAndClose() - vi.useRealTimers() - }) - - it('clear() drops pending input that has not been written yet', async () => { - const writes: WriteRecord[] = [] - const pendingYields: (() => void)[] = [] - const queue = createPtyInputWriteQueue({ - isWritable: () => true, - write: (id, data) => writes.push({ id, data }), - yieldBetweenWrites: () => - new Promise((resolve) => { - pendingYields.push(resolve) - }) - }) - - const large = 'y'.repeat(TERMINAL_INPUT_CHUNK_MAX_BYTES * 3) - queue.enqueue('pty-1', large, 'driving') - queue.enqueue('pty-1', 'tail', 'driving') - // First chunk is written synchronously, then the drain parks on the yield. - expect(writes.length).toBe(1) - - queue.clear() - pendingYields.shift()?.() - await queue.waitForDrain() - - expect(writes.length).toBe(1) - expect(writes.map((write) => write.data).join('')).not.toContain('tail') - }) - it('clear() fences an in-flight validation before queue reuse', async () => { vi.useFakeTimers() const { writes, queue } = createRecordingQueue() @@ -731,37 +236,4 @@ describe('pty input write queue', () => { vi.useRealTimers() } }) - - it('clear() resets reply capacity for later input', async () => { - const { writes, queue } = createRecordingQueue() - const reply = mode2031SequenceFor('dark') - - for (let index = 0; index <= PTY_INPUT_WRITE_QUEUE_MAX_PENDING_REPLIES; index += 1) { - expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true) - } - queue.clear() - expect(queue.enqueueQueryReply('pty-1', reply)).toBe(true) - await queue.waitForDrain() - - expect(extractReplyWrites(writes)).toEqual([reply, reply]) - }) - - it('does not retain a reaction record per acknowledged write', async () => { - // Queue-lifetime promise races retained a reaction per accepted write until teardown, leaking roughly 440 bytes each. - const queue = createPtyInputWriteQueue({ - isWritable: () => true, - write: () => undefined, - writeAccepted: async () => true, - yieldBetweenWrites: async () => undefined - }) - globalThis.gc?.() - const heapBefore = process.memoryUsage().heapUsed - for (let index = 0; index < 20_000; index += 1) { - await queue.enqueueAccepted('pty-1', 'x', 'driving') - } - await queue.waitForDrain() - globalThis.gc?.() - const growthMb = (process.memoryUsage().heapUsed - heapBefore) / 1024 / 1024 - expect(growthMb).toBeLessThan(2) - }) }) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-buffer.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-buffer.test.ts index b0e74ef3df6..d615e79ca8a 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-buffer.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport/input/pty-preconnect-input-buffer.test.ts @@ -3,11 +3,7 @@ import { createDeferred, flushAsyncTicks } from '../../pty-connection/test-fixtures/pty-connection-test-async' -import { - createPtyPreconnectInputBuffer, - PTY_PRECONNECT_INPUT_MAX_CODE_UNITS, - PTY_PRECONNECT_INPUT_MAX_ENTRIES -} from './pty-preconnect-input-buffer' +import { createPtyPreconnectInputBuffer } from './pty-preconnect-input-buffer' describe('createPtyPreconnectInputBuffer', () => { it('shares one flush worker and preserves mixed input order', async () => { @@ -88,116 +84,4 @@ describe('createPtyPreconnectInputBuffer', () => { await expect(accepted).resolves.toBe(false) } ) - - it('counts an in-flight accepted write toward both retention caps', async () => { - const codeUnitWrite = createDeferred() - const codeUnitWriteStarted = createDeferred() - const codeUnitBuffer = createPtyPreconnectInputBuffer() - const codeUnitAccepted = codeUnitBuffer.enqueueAccepted( - 'x'.repeat(PTY_PRECONNECT_INPUT_MAX_CODE_UNITS), - 'driving' - ) - const codeUnitFlush = codeUnitBuffer.flush({ - isCurrent: () => true, - sendInput: () => true, - sendInputImmediate: () => true, - sendInputAccepted: async () => { - codeUnitWriteStarted.resolve() - return codeUnitWrite.promise - } - }) - await codeUnitWriteStarted.promise - - expect(codeUnitBuffer.enqueue('overflow', 'ordinary', 'driving')).toBe(false) - - codeUnitBuffer.clear() - codeUnitWrite.resolve(true) - await expect(codeUnitAccepted).resolves.toBe(false) - await codeUnitFlush - - const entryWrite = createDeferred() - const entryWriteStarted = createDeferred() - const entryBuffer = createPtyPreconnectInputBuffer() - const entryAccepted = entryBuffer.enqueueAccepted('first', 'driving') - for (let index = 1; index < PTY_PRECONNECT_INPUT_MAX_ENTRIES; index += 1) { - expect(entryBuffer.enqueue('', 'ordinary', 'driving')).toBe(true) - } - const entryFlush = entryBuffer.flush({ - isCurrent: () => true, - sendInput: () => true, - sendInputImmediate: () => true, - sendInputAccepted: async () => { - entryWriteStarted.resolve() - return entryWrite.promise - } - }) - await entryWriteStarted.promise - - expect(entryBuffer.enqueue('', 'ordinary', 'driving')).toBe(false) - - entryBuffer.clear() - entryWrite.resolve(true) - await expect(entryAccepted).resolves.toBe(false) - await entryFlush - }) - - it('applies entry and code-unit caps to seeded input', async () => { - const entryBuffer = createPtyPreconnectInputBuffer( - Array.from({ length: PTY_PRECONNECT_INPUT_MAX_ENTRIES + 1 }, () => ({ - data: '', - kind: 'ordinary' as const, - inputKind: 'driving' as const - })) - ) - let entryWrites = 0 - - expect(entryBuffer.enqueue('', 'ordinary', 'driving')).toBe(false) - await entryBuffer.flush({ - isCurrent: () => true, - sendInput: () => { - entryWrites += 1 - return true - }, - sendInputImmediate: () => true - }) - expect(entryWrites).toBe(PTY_PRECONNECT_INPUT_MAX_ENTRIES) - - const codeUnitBuffer = createPtyPreconnectInputBuffer([ - { - data: 'x'.repeat(PTY_PRECONNECT_INPUT_MAX_CODE_UNITS), - kind: 'ordinary', - inputKind: 'driving' - }, - { data: 'overflow', kind: 'ordinary', inputKind: 'driving' } - ]) - const codeUnitWrites: number[] = [] - - expect(codeUnitBuffer.enqueue('new', 'ordinary', 'driving')).toBe(false) - await codeUnitBuffer.flush({ - isCurrent: () => true, - sendInput: (data) => { - codeUnitWrites.push(data.length) - return true - }, - sendInputImmediate: () => true - }) - expect(codeUnitWrites).toEqual([PTY_PRECONNECT_INPUT_MAX_CODE_UNITS]) - }) - - it('settles retained acknowledged input when the spawn is abandoned before connect', async () => { - // Abandoned deferred spawns never connect; disposal must settle buffered accepted writes instead of hanging paste. - const buffer = createPtyPreconnectInputBuffer() - const pastePending = buffer.enqueueAccepted('pasted text', 'driving') - let settled = false - void pastePending.then(() => { - settled = true - }) - await Promise.resolve() - expect(settled).toBe(false) - - buffer.clear() - - await expect(pastePending).resolves.toBe(false) - expect(buffer.isBuffering()).toBe(false) - }) }) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-connect-spawn.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-connect-spawn.test.ts index 91ffb9b5cca..4d2119cc9ac 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-connect-spawn.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-connect-spawn.test.ts @@ -1,10 +1,3 @@ -import { - type PtyConnectionAgentTitleMocks, - bindPaneAgentTitleMocks -} from '../../pty-connection/test-fixtures/pty-connection-test-deps' -import type { ManagedPane } from '@/lib/pane-manager/pane-manager-types' -import type { PtyConnectionDeps } from '../../pty-connection/pty-connection-deps' -import type { ConnectCallbacks } from '../../pty-connection/test-fixtures/pty-connection-test-pane-fixtures' import { terminalAttachResult } from '../../../../../../shared/terminal/pty/lifecycle/terminal-attach-result' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { installIpcPtyWindow, restorePtySpecWindow } from './pty-transport-test-harness' @@ -39,34 +32,6 @@ describe('createIpcPtyTransport', () => { restorePtySpecWindow(originalWindow) }) - it('exposes explicit local or direct SSH ownership without inferring it from the workspace', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - for (const connectionId of [undefined, 'qa']) { - const transport = createIpcPtyTransport({ connectionId }) - expect(transport.getExecutionHostId?.()).toBe(connectionId ? 'ssh:qa' : 'local') - expect(transport.getRuntimeEnvironmentId?.()).toBeNull() - transport.destroy?.() - } - }) - - it.each([0, 1, 420])( - 'preserves snapshot sequence and keyboard proof %s across IPC reattach', - async (seq) => { - const { createIpcPtyTransport } = await import('./pty-transport') - vi.mocked(window.api.pty.spawn).mockResolvedValue({ - id: 'existing', - isReattach: true, - snapshot: 'ready', - snapshotSeq: seq, - snapshotKittyKeyboardFlags: 0 - }) - const transport = createIpcPtyTransport({}) - const result = await transport.connect({ url: '', sessionId: 'existing', callbacks: {} }) - expect(result).toMatchObject({ snapshotSeq: seq, snapshotKittyKeyboardFlags: 0 }) - transport.detach?.() - } - ) - it('drains an exited join with pre-request output and preserves its snapshot projection', async () => { const { createIpcPtyTransport } = await import('./pty-transport') const { ensurePtyDispatcher } = await import('../delivery/pty-dispatcher') @@ -112,284 +77,6 @@ describe('createIpcPtyTransport', () => { snapshotView.detach?.() }) - it('leaves title tracking to the PTY data stream (no OpenCode IPC channel)', async () => { - // Why: the OpenCode status IPC channel is gone (now the agent-hooks server), so the transport has no per-agent status callback. - const { createIpcPtyTransport } = await import('./pty-transport') - const transport = createIpcPtyTransport({}) - - await transport.connect({ url: '', callbacks: {} }) - - expect(onData).not.toBeNull() - expect(onExit).not.toBeNull() - transport.disconnect() - }) - - // A pane drag waits out a spawn whose result would bind the leaf to its old tab. - it('reports a connect as pending only until its PTY id arrives', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - let resolveSpawn!: (value: { id: string }) => void - vi.mocked(window.api.pty.spawn).mockReturnValue( - new Promise((resolve) => { - resolveSpawn = resolve - }) - ) - const transport = createIpcPtyTransport({}) - expect(transport.isConnectPending?.()).toBe(false) - - const connecting = transport.connect({ url: '', callbacks: {} }) - expect(transport.isConnectPending?.()).toBe(true) - resolveSpawn({ id: 'pty-late' }) - await connecting - - expect(transport.getPtyId()).toBe('pty-late') - expect(transport.isConnectPending?.()).toBe(false) - transport.disconnect() - }) - - it('does not create a PTY when the pane generation is stale', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const spawn = window.api.pty.spawn as unknown as ReturnType - const transport = createIpcPtyTransport({}) - - await expect( - transport.connect({ url: '', shouldContinue: () => false, callbacks: {} }) - ).resolves.toBeUndefined() - - expect(spawn).not.toHaveBeenCalled() - }) - - it("carries an AI button's launch in its pane's spawn, and says whether the agent started", async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const { awaitAgentLaunchPaneStart } = - await import('@/lib/agent-session/launch/pane/agent-launch-pane-start') - const spawn = window.api.pty.spawn as unknown as ReturnType - const agentLaunch = { launch: { agent: 'claude' } } - const pane = { worktreeId: 'wt', tabId: 'tab-launch', leafId: 'leaf-launch' } - - const started = awaitAgentLaunchPaneStart(pane.tabId, pane.leafId) - spawn.mockResolvedValueOnce({ id: 'pty-launch' }) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the transport forwards the request untouched; main validates it. - await createIpcPtyTransport({ ...pane, agentLaunch } as never).connect({ - url: '', - callbacks: {} - }) - expect(spawn).toHaveBeenCalledWith( - expect.objectContaining({ tabId: 'tab-launch', agentLaunch }) - ) - await expect(started).resolves.toBe('pty-launch') - - spawn.mockRejectedValueOnce(new Error('agent_launch_pane_refused')) - const refused = awaitAgentLaunchPaneStart(pane.tabId, pane.leafId) - await createIpcPtyTransport(pane).connect({ url: '', callbacks: { onError: vi.fn() } }) - await expect(refused).resolves.toBeNull() - }) - - it('keeps the recovery hint and raw diagnostic from a wrapped spawn error', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - vi.mocked(window.api.pty.spawn).mockRejectedValueOnce( - new Error( - "Error invoking remote method 'pty:spawn': Error: Close unused terminals, then try again.\nnode-pty: open_slave failed: EMFILE (errno 24)" - ) - ) - const onError = vi.fn() - - await createIpcPtyTransport({}).connect({ url: '', callbacks: { onError } }) - - expect(onError).toHaveBeenCalledWith( - 'Close unused terminals, then try again.\nnode-pty: open_slave failed: EMFILE (errno 24)' - ) - }) - - it('threads provider command ownership through the spawn IPC', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const transport = createIpcPtyTransport({ - command: 'printf ready', - commandDelivery: 'provider' - }) - - await transport.connect({ url: '', callbacks: {} }) - - expect(window.api.pty.spawn).toHaveBeenCalledWith( - expect.objectContaining({ - command: 'printf ready', - commandDelivery: 'provider' - }) - ) - transport.disconnect() - }) - - it('forwards requested environment deletions to the PTY spawn', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const spawn = window.api.pty.spawn as unknown as ReturnType - const transport = createIpcPtyTransport({ - envToDelete: ['CODEX_HOME', 'ORCA_CODEX_HOME'] - }) - - await transport.connect({ url: '', callbacks: {} }) - - expect(spawn).toHaveBeenCalledWith( - expect.objectContaining({ envToDelete: ['CODEX_HOME', 'ORCA_CODEX_HOME'] }) - ) - }) - - it('forwards automatic resume provenance to the PTY spawn', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const spawn = window.api.pty.spawn as unknown as ReturnType - const resumeProviderSession = { - key: 'session_id' as const, - id: 'session-a', - transcriptPath: '/Users/example/.codex/sessions/2026/07/20/rollout-a.jsonl' - } - const transport = createIpcPtyTransport({ resumeProviderSession }) - - await transport.connect({ url: '', callbacks: {} }) - - expect(spawn).toHaveBeenCalledWith(expect.objectContaining({ resumeProviderSession })) - }) - - it('exposes the connection identity captured at transport creation', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - - expect(createIpcPtyTransport({}).getConnectionId?.()).toBeNull() - expect(createIpcPtyTransport({ connectionId: 'ssh-1' }).getConnectionId?.()).toBe('ssh-1') - }) - - it('exposes local session metadata only for local IPC PTYs', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const localTransport = createIpcPtyTransport({ - cwd: '\\\\wsl.localhost\\Ubuntu-24.04\\home\\alice\\repo', - shellOverride: 'wsl.exe', - projectRuntime: { - status: 'resolved', - runtime: { - kind: 'wsl', - hostPlatform: 'wsl', - projectId: 'repo', - distro: 'Ubuntu-24.04', - reason: 'project-override', - cacheKey: 'repo:wsl' - } - } - }) - const sshTransport = createIpcPtyTransport({ - connectionId: 'ssh-1', - cwd: 'C:\\Users\\alice\\repo', - shellOverride: 'cmd.exe' - }) - - expect(localTransport.getLocalSessionMetadata?.()).toEqual({ - cwd: '\\\\wsl.localhost\\Ubuntu-24.04\\home\\alice\\repo', - shellOverride: 'wsl.exe' - }) - expect(sshTransport.getLocalSessionMetadata?.()).toBeNull() - }) - - it('keeps captured Windows and WSL metadata when existing PTYs reattach', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const currentWslForWindowsPty = createIpcPtyTransport({ - cwd: 'C:\\repo', - shellOverride: 'pwsh.exe', - projectRuntime: { - status: 'resolved', - runtime: { - kind: 'wsl', - hostPlatform: 'wsl', - projectId: 'repo', - distro: 'Ubuntu-24.04', - reason: 'project-override', - cacheKey: 'repo:wsl' - } - } - }) - const currentWindowsForWslPty = createIpcPtyTransport({ - cwd: '\\\\wsl.localhost\\Ubuntu-24.04\\home\\alice\\repo', - shellOverride: 'wsl.exe', - projectRuntime: { - status: 'resolved', - runtime: { - kind: 'windows-host', - hostPlatform: 'win32', - projectId: 'repo', - reason: 'project-override', - cacheKey: 'repo:windows' - } - } - }) - - currentWslForWindowsPty.attach({ existingPtyId: 'windows-pty', callbacks: {} }) - currentWindowsForWslPty.attach({ existingPtyId: 'wsl-pty', callbacks: {} }) - - expect(currentWslForWindowsPty.getLocalSessionMetadata?.()).toEqual({ - cwd: 'C:\\repo', - shellOverride: 'pwsh.exe' - }) - expect(currentWindowsForWslPty.getLocalSessionMetadata?.()).toEqual({ - cwd: '\\\\wsl.localhost\\Ubuntu-24.04\\home\\alice\\repo', - shellOverride: 'wsl.exe' - }) - }) - - it('sends placement on a fresh spawn but not on a session reattach', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const spawn = window.api.pty.spawn as unknown as ReturnType - const placement = { - kind: 'split', - parentLeafId: '11111111-1111-4111-8111-111111111111', - direction: 'horizontal' - } as const - - const fresh = createIpcPtyTransport({ placement }) - await fresh.connect({ url: '', callbacks: {} }) - expect(spawn).toHaveBeenLastCalledWith(expect.objectContaining({ placement })) - fresh.disconnect() - - const reattach = createIpcPtyTransport({ placement }) - await reattach.connect({ url: '', callbacks: {}, sessionId: 'session-1' }) - expect(spawn).toHaveBeenLastCalledWith(expect.not.objectContaining({ placement })) - reattach.disconnect() - }) - - it('returns startup cwd fallback metadata to the connection layer', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const spawn = window.api.pty.spawn as unknown as ReturnType - spawn.mockResolvedValueOnce({ - id: 'pty-1', - startupCwdFallback: { kind: 'worktree', cwd: '/repo/app' } - }) - - const transport = createIpcPtyTransport({}) - - await expect(transport.connect({ url: '', callbacks: {} })).resolves.toEqual({ - id: 'pty-1', - startupCwdFallback: { kind: 'worktree', cwd: '/repo/app' } - }) - transport.disconnect() - }) - - it('forwards the declined-resume signal on fresh and cold-restore spawns alike', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const spawn = window.api.pty.spawn as unknown as ReturnType - spawn.mockResolvedValueOnce({ id: 'pty-1', agentResumeUnavailable: true }) - - const freshTransport = createIpcPtyTransport({}) - await expect(freshTransport.connect({ url: '', callbacks: {} })).resolves.toEqual({ - id: 'pty-1', - agentResumeUnavailable: true - }) - freshTransport.disconnect() - - spawn.mockResolvedValueOnce({ - id: 'pty-2', - coldRestore: { scrollback: 'recovered', cwd: '/repo/app' }, - agentResumeUnavailable: true - }) - const coldTransport = createIpcPtyTransport({}) - await expect(coldTransport.connect({ url: '', callbacks: {} })).resolves.toEqual( - expect.objectContaining({ id: 'pty-2', agentResumeUnavailable: true }) - ) - coldTransport.disconnect() - }) - it('stops gone-parking a session whose cold restore resolves after its transport was destroyed', async () => { const { createIpcPtyTransport } = await import('./pty-transport') const gone = await import('../../../terminal/terminal-provider-gone-sessions') @@ -427,201 +114,4 @@ describe('createIpcPtyTransport', () => { // Live again without an authoritative snapshot, so it must stay mounted where its own watchers run. expect(canWatcherCoverParkedTerminalTab('repo::/wt', tab)).toBe(false) }) - - it('passes startup commands through PTY spawn instead of writing them after connect', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const spawnMock = vi.fn().mockResolvedValue({ id: 'pty-1' }) - const writeMock = vi.fn() - - ;(globalThis as { window: typeof window }).window = { - ...originalWindow, - api: { - ...originalWindow?.api, - pty: { - ...originalWindow?.api?.pty, - spawn: spawnMock, - write: writeMock, - resize: vi.fn(), - kill: vi.fn(), - onData: vi.fn((callback: (payload: { id: string; data: string }) => void) => { - onData = callback - return () => {} - }), - onReplay: vi.fn(() => () => {}), - onExit: vi.fn((callback: (payload: { id: string; code: number }) => void) => { - onExit = callback - return () => {} - }) - } - } - } as unknown as typeof window - - const transport = createIpcPtyTransport({ - cwd: '/tmp/worktree', - env: { FOO: 'bar' }, - command: 'echo hello' - }) - - await transport.connect({ - url: '', - cols: 120, - rows: 40, - callbacks: {} - }) - - expect(spawnMock).toHaveBeenCalledWith({ - cols: 120, - rows: 40, - cwd: '/tmp/worktree', - env: { FOO: 'bar' }, - command: 'echo hello' - }) - expect(writeMock).not.toHaveBeenCalled() - }) - it('paints an old image and delayed live bytes once without claiming their newer frontier', async () => { - const { provenSpawnResponse } = - await import('../../../../../../shared/terminal/pty/lifecycle/terminal-spawn-response') - const { bindPtyConnectionTestMocks } = - await import('../../pty-connection/test-fixtures/pty-connection-mocks.spec') - const { createInitialStoreState } = - await import('../../pty-connection/test-fixtures/pty-connection-test-store-fixtures') - const { buildPaneConnectionDeps } = - await import('../../pty-connection/test-fixtures/pty-connection-test-deps') - const { createMockTransport, createPaneContainer, LEAF_1 } = - await import('../../pty-connection/test-fixtures/pty-connection-test-pane-fixtures') - const { Terminal } = await import('@xterm/xterm') - const { FitAddon } = await import('@xterm/addon-fit') - const { SearchAddon } = await import('@xterm/addon-search') - const { SerializeAddon } = await import('@xterm/addon-serialize') - const { PaneManager } = await import('@/lib/pane-manager/pane-manager') - const { isTerminalLeafId } = - await import('../../../../../../shared/workspace-layout/stable-pane-id') - const { installTerminalTestGlobals, restoreTerminalTestGlobals } = - await import('../../pty-connection/test-fixtures/pty-connection-test-environment') - const { flushAsyncTicks } = - await import('../../pty-connection/test-fixtures/pty-connection-test-async') - let state = createInitialStoreState(() => state) - const transports: ReturnType[] = [] - bindPtyConnectionTestMocks({ - getState: () => state, - getTransportQueue: () => transports, - getTransportOptions: () => [], - getStoreSubscribers: () => [], - setStoreSubscribers: () => {} - }) - await installTerminalTestGlobals() - try { - const { connectPanePty } = await import('../../pty-connection/connect-pane-pty') - const agentTitleMocks = await vi.importMock( - '@/lib/agent-status/aggregation/worktree-agent-status' - ) - for (const proof of ['interleaved', 'covered', 'no-flags'] as const) { - state = createInitialStoreState(() => state) - const result = provenSpawnResponse( - { - id: 'tab-pty', - isReattach: true, - snapshot: 'OLD', - providerSequence: { value: 900, generation: 'continued' as const }, - ...(proof !== 'no-flags' ? { snapshotKittyKeyboardFlags: 0 } : {}) - }, - proof === 'covered' ? 900 : undefined - ) - const transport = createMockTransport('tab-pty') - let callbacks: ConnectCallbacks | undefined - transport.connect.mockImplementation(async (options: { callbacks?: ConnectCallbacks }) => { - callbacks = options.callbacks - return result - }) - transports.push(transport) - const leafId: string = LEAF_1 - if (!isTerminalLeafId(leafId)) { - throw new Error('Expected a terminal leaf UUID') - } - const terminal = new Terminal({ - cols: 120, - rows: 40, - scrollback: 5_000, - allowProposedApi: true, - theme: { foreground: '#eeeeee', background: '#111111' }, - vtExtensions: { kittyKeyboard: true } - }) - const writes: string[] = [] - const parseCallbacks: (() => void)[] = [] - vi.spyOn(terminal, 'write').mockImplementation((data, callback) => { - writes.push(typeof data === 'string' ? data : new TextDecoder().decode(data)) - if (callback) { - parseCallbacks.push(callback) - } - }) - const container = createPaneContainer() - Object.defineProperty(container, 'querySelectorAll', { value: () => [] }) - const pane: ManagedPane = { - id: 1, - leafId, - stablePaneId: leafId, - terminal, - container, - linkTooltip: createPaneContainer(), - fitAddon: new FitAddon(), - searchAddon: new SearchAddon(), - serializeAddon: new SerializeAddon() - } - vi.spyOn(pane.fitAddon, 'fit').mockImplementation(() => {}) - vi.spyOn(pane.fitAddon, 'proposeDimensions').mockReturnValue({ cols: 120, rows: 40 }) - const manager = new PaneManager(container, { linkOpenHint: () => '' }) - vi.spyOn(manager, 'getPanes').mockReturnValue([pane]) - vi.spyOn(manager, 'getLeafId').mockReturnValue(leafId) - vi.spyOn(manager, 'getNumericIdForLeaf').mockReturnValue(1) - const fixtureDeps = buildPaneConnectionDeps(() => state, { - isVisibleRef: { current: true }, - restoredLeafId: LEAF_1, - restoredPtyIdByLeafId: { [LEAF_1]: 'tab-pty' } - }) - const deps: PtyConnectionDeps = { - ...fixtureDeps, - paneTransportsRef: { current: new Map() }, - paneMode2031Ref: { current: new Map() }, - paneLastThemeModeRef: { current: new Map() }, - replayingPanesRef: { current: new Map() }, - syncPanePtyLayoutBinding: (paneId, ptyId) => { - if (ptyId !== null) { - fixtureDeps.syncPanePtyLayoutBinding(paneId, ptyId) - } - } - } - const binding = connectPanePty( - pane, - manager, - bindPaneAgentTitleMocks(deps, agentTitleMocks) - ) - try { - await flushAsyncTicks(20) - for (let step = 0; step < 40; step += 1) { - parseCallbacks.shift()?.() - await flushAsyncTicks(2) - } - // The stream reaches main at 903 before the control reply; its delivery to this view is delayed until after OLD paints. - expect(writes.join('')).toContain('OLD') - callbacks?.onData?.('NEW', { seq: 903, rawLength: 3 }) - for (let step = 0; step < 40; step += 1) { - parseCallbacks.shift()?.() - await flushAsyncTicks(2) - } - expect(writes.join('').match(/OLD/g), proof).toHaveLength(1) - expect(writes.join('').match(/NEW/g), proof).toHaveLength(1) - expect(result.snapshotSeq).toBe(proof === 'covered' ? 900 : undefined) - } finally { - binding.dispose() - manager.destroy() - pane.fitAddon.dispose() - pane.searchAddon.dispose() - pane.serializeAddon.dispose() - terminal.dispose() - } - } - } finally { - await restoreTerminalTestGlobals() - } - }) }) diff --git a/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts index bc94c58c628..b4a4f934e5f 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-detach-attach-handoff.test.ts @@ -36,54 +36,6 @@ describe('createIpcPtyTransport', () => { restorePtySpecWindow(originalWindow) }) - it('does not create a second kill authority when a mounted pane detaches', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const kill = window.api.pty.kill as unknown as ReturnType - const transport = createIpcPtyTransport({}) - await transport.connect({ url: '', callbacks: {} }) - - transport.detach?.() - - expect(kill).not.toHaveBeenCalled() - }) - - // Why: retained gauges would inflate every later high-water profile. - it.each(['detach', 'destroy'] as const)( - 'drops its side-effect gauge from the census on %s', - async (teardown) => { - await import('../output/pty-side-effect-pending-census') - const { collectRendererMemoryProfileCounts } = await import('@/lib/renderer-memory-profile') - const { createIpcPtyTransport } = await import('./pty-transport') - expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(0) - - const transport = createIpcPtyTransport({}) - await transport.connect({ url: '', callbacks: {} }) - expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(1) - - transport[teardown]?.() - - expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(0) - } - ) - - // Why: teardown that already failed is exactly when a stranded gauge would pin the processor. - it('drops its side-effect gauge even when destroy throws mid-disconnect', async () => { - await import('../output/pty-side-effect-pending-census') - const { collectRendererMemoryProfileCounts } = await import('@/lib/renderer-memory-profile') - const { createIpcPtyTransport } = await import('./pty-transport') - const kill = window.api.pty.kill as unknown as ReturnType - const transport = createIpcPtyTransport({}) - await transport.connect({ url: '', callbacks: {} }) - expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(1) - - kill.mockImplementationOnce(() => { - throw new Error('ipc channel closed') - }) - - expect(() => transport.destroy?.()).toThrow('ipc channel closed') - expect(collectRendererMemoryProfileCounts()['ptySideEffects.processors']).toBe(0) - }) - it('keeps the live handler when detach() runs after a newer transport attached to the same PTY', async () => { // Why: a new pane can attach the same ptyId before the old detaches; unconditional unregister deletes the live handler (frozen-pane bug). const { createIpcPtyTransport } = await import('./pty-transport') diff --git a/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-eager-buffer-replay.test.ts b/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-eager-buffer-replay.test.ts index 1b0f0c952ad..c48712f7b77 100644 --- a/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-eager-buffer-replay.test.ts +++ b/src/renderer/src/components/terminal-pane/pty-transport/ipc/pty-transport-eager-buffer-replay.test.ts @@ -1,9 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - flushPtySideEffects, - installIpcPtyWindow, - restorePtySpecWindow -} from './pty-transport-test-harness' +import { installIpcPtyWindow, restorePtySpecWindow } from './pty-transport-test-harness' describe('createIpcPtyTransport', () => { const originalWindow = (globalThis as { window?: typeof window }).window @@ -30,63 +26,6 @@ describe('createIpcPtyTransport', () => { restorePtySpecWindow(originalWindow) }) - it('suppresses attention side effects when replaying eager-buffered data during attach', async () => { - // Why: replayed eager output must not raise fresh alerts — bell/idle suppressed, title still restores. - const { createIpcPtyTransport } = await import('./pty-transport') - const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher') - const onTitleChange = vi.fn() - const onBell = vi.fn() - const onAgentBecameIdle = vi.fn() - - const handle = registerEagerPtyBuffer('pty-restored', vi.fn()) - onData?.({ - id: 'pty-restored', - data: ']0;. Claude working]0;* Claude done' - }) - - const transport = createIpcPtyTransport({ - onTitleChange, - onBell, - onAgentBecameIdle - }) - - transport.attach({ - existingPtyId: 'pty-restored', - callbacks: {} - }) - - expect(handle.flush()).toBe('') - await flushPtySideEffects() - expect(onTitleChange).toHaveBeenCalledWith('* Claude done', '* Claude done') - expect(onBell).not.toHaveBeenCalled() - expect(onAgentBecameIdle).not.toHaveBeenCalled() - }) - - it('resets replay parser state after deferred side effects drain', async () => { - // Why: cleanup must await deferred replay side effects, else a partial OSC makes the first live BEL look like an OSC terminator. - const { createIpcPtyTransport } = await import('./pty-transport') - const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher') - const onBell = vi.fn() - - registerEagerPtyBuffer('pty-restored', vi.fn()) - onData?.({ - id: 'pty-restored', - data: '\x1b]0;partial-title' - }) - - const transport = createIpcPtyTransport({ onBell }) - transport.attach({ - existingPtyId: 'pty-restored', - callbacks: {} - }) - - await flushPtySideEffects() - onData?.({ id: 'pty-restored', data: '\x07' }) - await flushPtySideEffects() - - expect(onBell).toHaveBeenCalledTimes(1) - }) - it('keeps exit sidecars after eager-buffered PTYs attach to a terminal', async () => { const { createIpcPtyTransport } = await import('./pty-transport') const { registerEagerPtyBuffer, subscribeToPtyExit } = @@ -107,36 +46,6 @@ describe('createIpcPtyTransport', () => { expect(sidecarExit).toHaveBeenCalledWith(0, { hadPrimary: true }) }) - it('bounds the eager buffer to its cap and keeps the most recent output', async () => { - const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher') - const cap = 512 * 1024 - const handle = registerEagerPtyBuffer('pty-restored', vi.fn()) - - // 800 KB of chunks exceeds the 512 KB cap; earliest chunks drop while the prompt-bearing tail is kept. - for (let i = 0; i < 8; i += 1) { - onData?.({ id: 'pty-restored', data: String.fromCharCode(65 + i).repeat(100 * 1024) }) - } - onData?.({ id: 'pty-restored', data: 'PROMPT$' }) - - const flushed = handle.flush() - expect(flushed.length).toBeLessThanOrEqual(cap) - expect(flushed.endsWith('PROMPT$')).toBe(true) - expect(flushed).not.toContain('A') - }) - - it('caps a single oversized eager chunk to its most-recent tail', async () => { - const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher') - const cap = 512 * 1024 - const handle = registerEagerPtyBuffer('pty-restored', vi.fn()) - - // One chunk larger than the cap must not be stored whole. - onData?.({ id: 'pty-restored', data: `${'x'.repeat(cap)}TAIL$` }) - - const flushed = handle.flush() - expect(flushed.length).toBeLessThanOrEqual(cap) - expect(flushed.endsWith('TAIL$')).toBe(true) - }) - it('drains pre-handler data and exit into eager buffers for fast background PTYs', async () => { const { ensurePtyDispatcher, registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher') @@ -153,62 +62,6 @@ describe('createIpcPtyTransport', () => { expect(onEagerExit).toHaveBeenCalledWith('pty-fast-setup', 1) }) - it('enforces the eager buffer cap in UTF-8 bytes for multi-byte output', async () => { - const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher') - const cap = 512 * 1024 - const handle = registerEagerPtyBuffer('pty-restored', vi.fn()) - const output = `${'界'.repeat(cap)}PROMPT$` - const encodeSpy = vi.spyOn(TextEncoder.prototype, 'encode') - - onData?.({ id: 'pty-restored', data: output }) - - const flushed = handle.flush() - expect(new TextEncoder().encode(flushed).byteLength).toBeLessThanOrEqual(cap) - expect(flushed.endsWith('PROMPT$')).toBe(true) - expect(encodeSpy).not.toHaveBeenCalledWith(output) - encodeSpy.mockRestore() - }) - - it('preserves a BOM when it starts the retained oversized eager-buffer tail', async () => { - const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher') - const cap = 512 * 1024 - const handle = registerEagerPtyBuffer('pty-restored', vi.fn()) - - onData?.({ id: 'pty-restored', data: `${'x'.repeat(16)}\uFEFF${'y'.repeat(cap - 3)}` }) - - const flushed = handle.flush() - expect(new TextEncoder().encode(flushed).byteLength).toBe(cap) - expect(flushed.startsWith('\uFEFF')).toBe(true) - }) - - it('does not use Array.shift while trimming many eager chunks', async () => { - const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher') - const handle = registerEagerPtyBuffer('pty-restored', vi.fn()) - const originalShift = Array.prototype.shift - - try { - // Why: Array.shift() per trim reindexed the buffer, making many small chunks quadratic. - Object.defineProperty(Array.prototype, 'shift', { - configurable: true, - writable: true, - value() { - throw new Error('Array.shift should not be used by the eager buffer') - } - }) - for (let i = 0; i < 2048; i += 1) { - onData?.({ id: 'pty-restored', data: 'x'.repeat(1024) }) - } - } finally { - Object.defineProperty(Array.prototype, 'shift', { - configurable: true, - writable: true, - value: originalShift - }) - } - - expect(handle.flush().length).toBeLessThanOrEqual(512 * 1024) - }) - it('routes eager-buffered bytes through onReplayData so the renderer can engage the replay guard', async () => { const { createIpcPtyTransport } = await import('./pty-transport') const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher') @@ -239,85 +92,6 @@ describe('createIpcPtyTransport', () => { expect(onDataCallback).not.toHaveBeenCalledWith(bufferedPayload) }) - it('replays display-bearing eager-buffered output with default clear semantics', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher') - - const bufferedPayload = '\x1b[?1049hAutomation agent is running' - registerEagerPtyBuffer('pty-automation', vi.fn()) - onData?.({ - id: 'pty-automation', - data: bufferedPayload - }) - - const transport = createIpcPtyTransport() - const onReplayData = vi.fn() - - transport.attach({ - existingPtyId: 'pty-automation', - callbacks: { - onReplayData - } - }) - - expect(onReplayData.mock.calls).toEqual([[bufferedPayload]]) - }) - - it('does not clear before replaying title-only eager-buffered output', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher') - - const bufferedPayload = '\x1b]0;Restored title\x07' - registerEagerPtyBuffer('pty-title-only', vi.fn()) - onData?.({ - id: 'pty-title-only', - data: bufferedPayload - }) - - const onTitleChange = vi.fn() - const transport = createIpcPtyTransport({ onTitleChange }) - const onReplayData = vi.fn() - - transport.attach({ - existingPtyId: 'pty-title-only', - callbacks: { - onReplayData - } - }) - - // Why: title/control frames restore metadata but don't redraw, so clearing before them would erase persisted scrollback. - const clear = '\x1b[2J\x1b[3J\x1b[H' - expect(onReplayData.mock.calls).toEqual([[bufferedPayload, { clearBeforeReplay: false }]]) - expect(onReplayData).not.toHaveBeenCalledWith(clear) - expect(onTitleChange).toHaveBeenCalledWith('Restored title', 'Restored title') - }) - - it('does not write an unterminated title-only eager buffer into replay', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher') - - const bufferedPayload = '\x1b]0;partial restored title' - registerEagerPtyBuffer('pty-partial-title', vi.fn()) - onData?.({ - id: 'pty-partial-title', - data: bufferedPayload - }) - - const transport = createIpcPtyTransport() - const onReplayData = vi.fn() - - transport.attach({ - existingPtyId: 'pty-partial-title', - callbacks: { - onReplayData - } - }) - - const clear = '\x1b[2J\x1b[3J\x1b[H' - expect(onReplayData.mock.calls).toEqual([['', { clearBeforeReplay: false }]]) - expect(onReplayData).not.toHaveBeenCalledWith(clear) - }) - it('does not let an unterminated OSC 9999 eager buffer swallow live output', async () => { const { createIpcPtyTransport } = await import('./pty-transport') const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher') @@ -349,103 +123,4 @@ describe('createIpcPtyTransport', () => { expect(onDataCallback).toHaveBeenCalledWith('live output') }) - - it('does not clear before replaying OSC 9999-only eager-buffered output', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher') - - registerEagerPtyBuffer('pty-status-only', vi.fn()) - onData?.({ - id: 'pty-status-only', - data: '\x1b]9999;{"state":"working","prompt":"ship it","agentType":"codex"}\x07' - }) - - const transport = createIpcPtyTransport() - const onReplayData = vi.fn() - - transport.attach({ - existingPtyId: 'pty-status-only', - callbacks: { - onReplayData - } - }) - - // Why: OSC 9999 is stripped before xterm; a raw status frame must not clear restored scrollback and replay nothing. - const clear = '\x1b[2J\x1b[3J\x1b[H' - expect(onReplayData.mock.calls).toEqual([['', { clearBeforeReplay: false }]]) - expect(onReplayData).not.toHaveBeenCalledWith(clear) - }) - - it('does not clear on attach when there is no eager-buffered output', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - - const transport = createIpcPtyTransport() - const onDataCallback = vi.fn() - const onReplayData = vi.fn() - - transport.attach({ - existingPtyId: 'pty-attached', - callbacks: { - onData: onDataCallback, - onReplayData - } - }) - - // Why: restored scrollback may already be in xterm before attach; an empty eager buffer must not erase it. - expect(onReplayData).not.toHaveBeenCalled() - expect(onDataCallback).not.toHaveBeenCalled() - }) - - it('does not clear on attach when the eager buffer is empty', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher') - - registerEagerPtyBuffer('pty-attached', vi.fn()) - const transport = createIpcPtyTransport() - const onDataCallback = vi.fn() - const onReplayData = vi.fn() - - transport.attach({ - existingPtyId: 'pty-attached', - callbacks: { - onData: onDataCallback, - onReplayData - } - }) - - // Why: a live PTY can have an eager handle before any bytes arrive; clearing would destroy scrollback restored at mount. - expect(onReplayData).not.toHaveBeenCalled() - expect(onDataCallback).not.toHaveBeenCalled() - }) - - it('skips the attach-time clear sequence for alternate-screen sessions', async () => { - const { createIpcPtyTransport } = await import('./pty-transport') - const { registerEagerPtyBuffer } = await import('../delivery/pty-dispatcher') - - const bufferedPayload = '\x1b[?1049hAlternate screen is already restored' - registerEagerPtyBuffer('pty-alt-screen', vi.fn()) - onData?.({ - id: 'pty-alt-screen', - data: bufferedPayload - }) - - const transport = createIpcPtyTransport() - const onDataCallback = vi.fn() - const onReplayData = vi.fn() - - transport.attach({ - existingPtyId: 'pty-alt-screen', - isAlternateScreen: true, - callbacks: { - onData: onDataCallback, - onReplayData - } - }) - - // Why: alternate-screen snapshots already fill the viewport, so emitting the clear would erase restored content. - const clear = '\x1b[2J\x1b[3J\x1b[H' - expect(onReplayData.mock.calls).toEqual([[bufferedPayload, { clearBeforeReplay: false }]]) - expect(onReplayData).not.toHaveBeenCalledWith(clear) - expect(onDataCallback).not.toHaveBeenCalledWith(clear) - }) })