mirror of
https://github.com/stablyai/orca.git
synced 2026-10-23 08:03:39 +00:00
Merge branch 'main' of https://github.com/stablyai/orca into improve-cmd-j-ranking-with-recency
This commit is contained in:
@@ -673,6 +673,9 @@ jobs:
|
||||
ORCA_REUSE_PREPARED_NATIVE_RUNTIME: '1'
|
||||
run: pnpm exec electron-builder --config config/electron-builder.config.cjs --dir
|
||||
|
||||
- name: Smoke packaged Windows PTY native capability
|
||||
run: pnpm run smoke:windows-pty-native-capability -- --exe=dist/win-unpacked/Orca.exe
|
||||
|
||||
- name: Smoke packaged CLI
|
||||
run: node config/scripts/smoke-packaged-cli.mjs --app-dir=dist/win-unpacked
|
||||
|
||||
@@ -707,38 +710,9 @@ jobs:
|
||||
BASE="${{ github.event.pull_request.base.sha }}"
|
||||
HEAD="${{ github.event.pull_request.head.sha }}"
|
||||
CHANGED="$(git diff --name-only --diff-filter=AMCR --merge-base "$BASE" "$HEAD")"
|
||||
TEST_FILES="$(printf '%s\n' "$CHANGED" | grep -E '^tests/e2e/.*\.spec\.ts$' || true)"
|
||||
if printf '%s\n' "$CHANGED" | grep -Eq '^src/(main/ephemeral-vm-(runtime-(service|provisioning-persistence)|failed-start-cleanup)|shared/(ephemeral-vm-runtime-(store|feature-store|rollback-projection|runtimes)|ephemeral-vm-recipes|orca-yaml-hook-types))\.ts$'; then
|
||||
TEST_FILES="$(printf '%s\n%s\n' "$TEST_FILES" 'tests/e2e/ephemeral-vm-provisioned-root.spec.ts' | sort -u)"
|
||||
fi
|
||||
# Why: the Docker-SSH specs only ever ran when someone edited a spec, so four
|
||||
# pane-restore regressions shipped from SSH source edits that touched no test.
|
||||
# Unit tests are excluded because they prove the same source without Docker.
|
||||
# ssh-startup-exec-readiness.spec.ts is listed to route e2e.yml's dedicated
|
||||
# ssh-docker-watcher-isolation lane, which filters it out of changed-e2e.
|
||||
if printf '%s\n' "$CHANGED" | grep -Ev '\.test\.tsx?$' | grep -Eq '^(src/main/ssh/|src/main/providers/ssh-|src/main/ipc/(ssh-|pty)|src/relay/|src/renderer/src/components/terminal-pane/(pty-|ssh-|remote-runtime-|terminal-parked-pty))'; then
|
||||
TEST_FILES="$(printf '%s\n' "$TEST_FILES" \
|
||||
'tests/e2e/pty-input-write-queue-ssh.spec.ts' \
|
||||
'tests/e2e/ssh-cold-activation-restore.spec.ts' \
|
||||
'tests/e2e/ssh-docker-reconnect-pane-restore.spec.ts' \
|
||||
'tests/e2e/ssh-startup-exec-readiness.spec.ts' \
|
||||
'tests/e2e/ssh-terminal-window-wake-stale-grid-repro.spec.ts' | sort -u)"
|
||||
fi
|
||||
# Why: same lesson as the SSH specs above. The IME e2e suite asserts real pty bytes and
|
||||
# real overlay geometry, but only ran when someone edited a spec, so every IME fix in the
|
||||
# 1.4.18x window shipped without it - including one whose diagnosis hardware later refuted.
|
||||
# config/patches is listed because the terminal's input handling lives in the xterm patch.
|
||||
if printf '%s\n' "$CHANGED" | grep -Ev '\.test\.tsx?$' | grep -Eq '^(config/patches/|src/renderer/src/components/terminal-pane/(terminal-ime-|use-terminal-pane-lifecycle|xterm-bypass-policy|terminal-option-shortcut-policy))'; then
|
||||
TEST_FILES="$(printf '%s\n' "$TEST_FILES" \
|
||||
'tests/e2e/terminal-cjk-ime-committed-text.spec.ts' \
|
||||
'tests/e2e/terminal-hangul-wrap-boundary-bytes.spec.ts' \
|
||||
'tests/e2e/terminal-ime-exact-byte.spec.ts' \
|
||||
'tests/e2e/terminal-korean-composing-chord-order.spec.ts' \
|
||||
'tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts' \
|
||||
'tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts' \
|
||||
'tests/e2e/terminal-korean-preedit-visibility.spec.ts' | sort -u)"
|
||||
fi
|
||||
TEST_FILES_JSON="$(printf '%s\n' "$TEST_FILES" | jq --raw-input --slurp --compact-output 'split("\n") | map(select(length > 0))')"
|
||||
# Source routes are executable contracts so a test can prove exact
|
||||
# authorities, exclusions, and sentinels without evaluating workflow shell.
|
||||
TEST_FILES_JSON="$(printf '%s\n' "$CHANGED" | node config/scripts/pr-e2e-source-routing.mjs)"
|
||||
echo "test_files=$TEST_FILES_JSON" >> "$GITHUB_OUTPUT"
|
||||
if [ "$TEST_FILES_JSON" != '[]' ]; then
|
||||
echo "should_run=true" >> "$GITHUB_OUTPUT"
|
||||
|
||||
+406
-10
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"updatedAt": "2026-08-20",
|
||||
"updatedAt": "2026-08-23",
|
||||
"policy": {
|
||||
"maturityLevels": ["experimental", "soak", "blocking", "accepted-gap", "deprecated"],
|
||||
"blockingPromotion": {
|
||||
@@ -3680,14 +3680,16 @@
|
||||
"providers": ["local", "daemon", "ssh", "runtime"],
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["local", "daemon", "ssh", "runtime"],
|
||||
"coverageNotes": "Live macOS Electron tests prove exact local PTY disappearance after parked-tab close and detached-pgid descendant death after agent close. Deterministic tests cover final-pane CLI close durability, persisted-empty restart suppression, same-incarnation handle continuity, replacement and hard graph-loss stale fencing, preallocated-handle supersession, daemon and SSH routing, local/daemon pending-snapshot ownership across natural exit, stale-root descendant-signal suppression, graceful-to-immediate kill upgrades, duplicate-kill completion sharing, locale-stable bounded/fresh/coalesced process-table reads, deadline-safe successor scans, cycle-safe linear descendant traversal, target-only escalation indexing, 32-wide bulk teardown, source-scan timestamp identity, same-second PID ambiguity, ordinary runtime close ownership, unified-only hydration, split ownership, pane detach transfer, restart alias hydration, and late-hook suppression; live Linux, Windows, WSL, SSH, and remote-runtime process evidence remains pending. A paired macOS Electron journey (real attached-window desktop host plus a separate real paired desktop client, isolated profiles) covers the inverse authority direction for host-created terminals: a renderer graph sync must not retire a tab that `orca terminal create` made. That claim now covers BOTH shapes, including the incident shape the real CLI produces - a repo's FIRST host-created terminal, since src/cli/handlers/terminal.ts sends no clientMutationId - each asserted by its own test. An earlier reading of this gate called a preceding host-created terminal and a `clientMutationId` protective; main-process instrumentation refuted that. The renderer's stale session write deleted the host tab from persistence in every variant, and only the delete's timing relative to the measured sync differed, so those rows were false negatives of a single-sync oracle. The defect was in persistence: persistPtyBinding did not raise the repo's terminal topology fence for the first host-admitted tab, leaving the renderer's pre-create tab list free to replay over it. Elapsed time and paired-client mirroring never decided anything. A windowless `orca serve` parity arm runs the identical oracle and passes on both the merge-base and the branch, confirming that topology does not exhibit the defect (the gate it turns on is window-conditioned) and that making the host binding unconditional did not regress it. All of this is macOS-local only. The reported incident occurred on a physical Windows host; we did not run against one. The claim that the mechanism is platform-independent rests on the authoritative-window gate and publication-epoch inheritance being OS-agnostic, not on Windows evidence, so no ConPTY, Windows window-lifecycle, update, or sleep behavior is covered here.",
|
||||
"coverageNotes": "Live macOS Electron tests prove exact local PTY disappearance after parked-tab close and detached-pgid descendant death after agent close. A deterministic final-pane interleaving now proves durable tab retirement commits before externally owned PTY teardown can publish graph loss, and preserves an unrelated live canary through duplicate exit retirement. Deterministic tests also cover final-pane CLI close durability, persisted-empty restart suppression, same-incarnation handle continuity, replacement and hard graph-loss stale fencing, preallocated-handle supersession, daemon and SSH routing, local/daemon pending-snapshot ownership across natural exit, stale-root descendant-signal suppression, graceful-to-immediate kill upgrades, duplicate-kill completion sharing, locale-stable bounded/fresh/coalesced process-table reads, deadline-safe successor scans, cycle-safe linear descendant traversal, target-only escalation indexing, 32-wide bulk teardown, source-scan timestamp identity, same-second PID ambiguity, ordinary runtime close ownership, unified-only hydration, split ownership, pane detach transfer, restart alias hydration, and late-hook suppression; live Linux, Windows, WSL, SSH, and remote-runtime process evidence remains pending. A paired macOS Electron journey (real attached-window desktop host plus a separate real paired desktop client, isolated profiles) covers the inverse authority direction for host-created terminals: a renderer graph sync must not retire a tab that `orca terminal create` made. That claim now covers BOTH shapes, including the incident shape the real CLI produces - a repo's FIRST host-created terminal, since src/cli/handlers/terminal.ts sends no clientMutationId - each asserted by its own test. An earlier reading of this gate called a preceding host-created terminal and a `clientMutationId` protective; main-process instrumentation refuted that. The renderer's stale session write deleted the host tab from persistence in every variant, and only the delete's timing relative to the measured sync differed, so those rows were false negatives of a single-sync oracle. The defect was in persistence: persistPtyBinding did not raise the repo's terminal topology fence for the first host-admitted tab, leaving the renderer's pre-create tab list free to replay over it. Elapsed time and paired-client mirroring never decided anything. A windowless `orca serve` parity arm runs the identical oracle and passes on both the merge-base and the branch, confirming that topology does not exhibit the defect (the gate it turns on is window-conditioned) and that making the host binding unconditional did not regress it. All of this is macOS-local only. The reported incident occurred on a physical Windows host; we did not run against one. The claim that the mechanism is platform-independent rests on the authoritative-window gate and publication-epoch inheritance being OS-agnostic, not on Windows evidence, so no ConPTY, Windows window-lifecycle, update, or sleep behavior is covered here.",
|
||||
"motivatingLinks": [
|
||||
"https://linear.app/stably/issue/STA-4327",
|
||||
"https://github.com/stablyai/orca/pull/14590",
|
||||
"https://github.com/stablyai/orca/pull/8628",
|
||||
"https://github.com/stablyai/orca/pull/8706",
|
||||
"https://github.com/stablyai/orca/issues/14524"
|
||||
],
|
||||
"invariant": "Close permanently removes the owned provider session, agent descendants, persisted tab/layout authority, and resume authority even when no TerminalPane is mounted; final-pane CLI close does not acknowledge before durable tab retirement, and a persisted explicit-empty state prevents initial-tab fallback from repopulating the workspace after reload or restart. A handle remains valid while the same provider-attested PTY incarnation survives renderer reload or re-key, and becomes stale without adopting a replacement incarnation. A terminating id remains reserved through natural exit, duplicate callers await the same completion, and immediate teardown upgrades any graceful request without signalling a recycled PID or a descendant tree after root ownership is lost; process-table work is locale-stable, bounded, fresh for each post-start request, same-turn coalesced, and begins within the requesting caller's deadline, including bulk worktree cleanup; detach and park preserve ownership; aliases prevent a detached agent's immutable physical pane key from being retired with its former tab.",
|
||||
"oracle": "Capture exact tab, pane, PTY, handle, incarnation, and persisted layout identities. Final-pane terminal.close must kill the exact PTY once, invoke one durability-acknowledged tab retirement, stay pending until the persisted row is removed, and never fall back to the fire-and-forget pane event; reload/restart must keep the explicitly emptied worktree at zero terminal tabs and provider sessions. Reloading the renderer with the same tab/pane/PTY/incarnation must keep the handle readable; changing only the incarnation behind the same PTY id, losing the authoritative graph, or superseding the renderer handle with a preallocated handle must reject the old handle with terminal_handle_stale. Parked-close tests prove the exact PTY disappears; descendant/process tests keep natural exits reserved, upgrade teardown safely, bound/coalesce process-table work, and protect recycled identities.",
|
||||
"invariant": "Close permanently removes the owned provider session, agent descendants, persisted tab/layout authority, and resume authority even when no TerminalPane is mounted; final-pane CLI close commits durable tab retirement before PTY stop can publish graph loss, does not acknowledge before that retirement, and treats the later exit retirement as idempotent. A persisted explicit-empty state prevents initial-tab fallback from repopulating the workspace after reload or restart. A handle remains valid while the same provider-attested PTY incarnation survives renderer reload or re-key, and becomes stale without adopting a replacement incarnation. A terminating id remains reserved through natural exit, duplicate callers await the same completion, and immediate teardown upgrades any graceful request without signalling a recycled PID or a descendant tree after root ownership is lost; process-table work is locale-stable, bounded, fresh for each post-start request, same-turn coalesced, and begins within the requesting caller's deadline, including bulk worktree cleanup; detach and park preserve ownership; aliases prevent a detached agent's immutable physical pane key from being retired with its former tab.",
|
||||
"oracle": "Capture exact tab, pane, PTY, handle, incarnation, and persisted layout identities. Final-pane terminal.close must invoke one durability-acknowledged tab retirement before exact PTY teardown; controlled PTY exit and graph removal afterward must remain idempotent, omit the target from persistence and provider inventory, and leave an unrelated canary handle live. The ordinary path stays pending until the persisted row is removed and never falls back to the fire-and-forget pane event; reload/restart must keep the explicitly emptied worktree at zero terminal tabs and provider sessions. Reloading the renderer with the same tab/pane/PTY/incarnation must keep the handle readable; changing only the incarnation behind the same PTY id, losing the authoritative graph, or superseding the renderer handle with a preallocated handle must reject the old handle with terminal_handle_stale. Parked-close tests prove the exact PTY disappears; descendant/process tests keep natural exits reserved, upgrade teardown safely, bound/coalesce process-table work, and protect recycled identities.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime-terminal-close-continuity.test.ts",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal/initial-terminal.test.ts src/renderer/src/lib/worktree-activation-default-tabs.test.ts src/renderer/src/store/slices/terminals-explicit-empty-hydration.test.ts",
|
||||
@@ -3733,6 +3735,7 @@
|
||||
"file": "src/main/runtime/orca-runtime-terminal-close-continuity.test.ts",
|
||||
"assertions": [
|
||||
"final-pane terminal.close remains pending until one renderer durability acknowledgement retires the persisted tab and layout",
|
||||
"final-pane externally owned teardown commits session retirement before PTY stop, tolerates duplicate exit retirement, and preserves an unrelated live canary",
|
||||
"post-ack workspace-session loss falls back to renderer cleanup and verified PTY teardown while every pre-ack retirement error remains non-destructive",
|
||||
"renderer reload with the same provider-attested PTY incarnation preserves the exact handle",
|
||||
"same-id replacement incarnation publishes a new handle and makes the old handle deterministically stale",
|
||||
@@ -3913,7 +3916,7 @@
|
||||
},
|
||||
"redGreenEvidence": {
|
||||
"status": "complete",
|
||||
"evidence": "STA-4327 used two byte-identical oracles. Runtime oracle cd248b67cc10ef64f2def315b86c3b0236b102639d03c65a0c5d9519e538d3af failed the same three durability/continuity checks on reported v1.4.180 (0b62333cf1), latest main (9bb8836bb6), and disabled fix; runtime candidate 3cf8a37447 passed 5/5, and final code candidate 121e112d77 separately passed its expanded 6/6 oracle. Renderer oracle 3b0949eef8b792cf5b09cfa55341f4216c08714f158e4b132e988e8114636cea failed both explicit-empty hydration/fallback checks on v1.4.180, latest main, and disabled fix, while renderer candidate 121e112d77 passed 2/2."
|
||||
"evidence": "STA-4327 used two byte-identical oracles. Runtime oracle cd248b67cc10ef64f2def315b86c3b0236b102639d03c65a0c5d9519e538d3af failed the same three durability/continuity checks on reported v1.4.180 (0b62333cf1), latest main (9bb8836bb6), and disabled fix; runtime candidate 3cf8a37447 passed 5/5, and final code candidate 121e112d77 separately passed its expanded 6/6 oracle. Renderer oracle 3b0949eef8b792cf5b09cfa55341f4216c08714f158e4b132e988e8114636cea failed both explicit-empty hydration/fallback checks on v1.4.180, latest main, and disabled fix, while renderer candidate 121e112d77 passed 2/2. The 1.4.187 recurrence oracle deterministically failed with historical tab_not_found when PTY stop was moved ahead of durable retirement, then passed with retirement committed before externally owned teardown while the canary remained live."
|
||||
},
|
||||
"performanceBudget": {
|
||||
"required": true,
|
||||
@@ -8047,6 +8050,7 @@
|
||||
"remote-runtime host surface materialization",
|
||||
"remote-runtime mirror polling",
|
||||
"remote-runtime network recovery",
|
||||
"paired client sleep/wake reconnect",
|
||||
"terminal create idempotency",
|
||||
"provider listing",
|
||||
"reattach",
|
||||
@@ -8059,6 +8063,8 @@
|
||||
"coveredProviders": ["ssh", "remote-runtime"],
|
||||
"coverageNotes": "Deterministic renderer coverage proves startup publishes the state returned by ssh.connect, retained native and runtime SSH payloads are admitted through production routes only with valid complete authority, stale cleanup cannot unregister a replacement runtime terminal, direct SSH Git and folder panes clear and retry by exact authority, one authority chain stops after two automatic attempts even when each timeout exceeds the rolling window, rejected acknowledgements mutate no store maps, and one shared exact attempt admits every concurrent split-pane spawn and reattach while preserving the first PTY as the tab fallback. A later sibling failure rotates the tab once, stale callbacks from the prior attempt mutate no state, split remount activity suppression is counted per leaf, primary PTY exit promotes a bound survivor or preserves an empty continuation gap for a late sibling, and primary, non-primary, or null-PTY detach preserves exact authority on both resulting tabs. Intentional pane disposal cancels its settlement timer without breaking StrictMode remount timeout ownership. Target snapshot hydration/reconnect preserves sibling SSH/local/WSL/runtime state, and a mounted remote-runtime terminal survives repeated transport partitions without changing PTY identity. A real encrypted-WebSocket oracle proves a successful reachability probe can replace a pre-ready shared-control socket without rejecting or duplicating the waiting RPC. Direct SSH coordinator tests cover immediate terminal finalization, hydration correction, damping, bounded retry, and telemetry non-interference. Client/server heartbeat tests cover timer suspension, socket generations fence stale callbacks, cold restored-terminal attachment retries, cached pixels remain unhealthy until authoritative replay, automatic retries stop after one minute, manual reconnect preserves the PTY, and pane closure releases recovery UI state. Current macOS Electron journeys against an ephemeral Linux Docker SSH target cover exact-authority repo/worktree hydration, live terminal recovery after disconnect/reconnect, and eager six-terminal remount after renderer reload. A Windows remote-runtime smoke covers reachability and PTY round-trip. Multi-target live fanout, paired-close, WSL, and patched live partition journeys remain gaps.",
|
||||
"motivatingLinks": [
|
||||
"https://linear.app/stably/issue/STA-3107",
|
||||
"https://github.com/stablyai/orca/pull/12664",
|
||||
"https://github.com/stablyai/orca/pull/6951",
|
||||
"https://github.com/stablyai/orca/pull/6955",
|
||||
"https://github.com/stablyai/orca/pull/6979",
|
||||
@@ -8070,6 +8076,7 @@
|
||||
"oracle": "Deterministic tests cover bounded stale-handle replacement, suspended heartbeat clocks, cold and established subscription failure, ten partition/recovery cycles, automatic-recovery cutoff, manual reconnect, and exact direct SSH binding recovery. They assert one atomic store publication clears only exact-target PTY indexes, null-PTY activation remains unchanged, relay identity survives, Git and folder panes retry symmetrically, another target/local/WSL/runtime panes remain byte-identical through target snapshot hydration and reconnect, only an accepted exact failure or timeout starts the second attempt, two 31-second timeouts cannot start a third settlement-triggered attempt, rejected stale/mismatched acknowledgements preserve every store map, and concurrent split-pane spawn and reattach callbacks both commit under the same attempt ID after the first success replaces pending state with live shared authority. A sibling failure revokes that shared authority and starts exactly one second attempt; duplicate failures and late first-attempt PTY callbacks preserve the second attempt and every state map. Attempt-two failure retains continuation authority for later siblings, primary exit promotes a bound survivor or preserves the lease until a late sibling binds, and primary plus non-primary detach retain exact authority and history on both resulting tabs. Both remount callbacks consume split-count activity suppression, intentional dispose emits no failure/timeout, and a same-attempt StrictMode remount still owns one timeout. Hydration clears an untrusted PTY hint without clearing its current pending owner, healthy current-authority bindings suppress correction, hydration finalizes once, and reconnect emits no paired close lifecycle. A provider-level session-ID reattach returns an incarnation, then a legacy exit without an incarnation must resolve to that returned identity rather than minting a fallback identity. The shared-control oracle withholds the first encrypted ready frame, starts one RPC, triggers the successful-probe refresh, then requires exactly two client connections, one host request, a successful response, zero pending calls, and zero retained request bytes. Tests also assert one unsubscribe per remote-runtime epoch, observable recovery phases, stable PTY identity, resumed snapshot/output/input, no healthy state before replay, no retry or input after cutoff, a new manual epoch against the same PTY, quiet recovery UI with an explicit Reconnect action, pane-close state cleanup, one stable create mutation id, old-runtime no-retry behavior, cross-process PTY adoption, and bounded in-flight coordination.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/providers/ssh-pty-provider-reattach-incarnation.test.ts --reporter=dot",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/paired-reconnect-multi-pane-materialization.test.ts src/renderer/src/runtime/paired-reconnect-sidebar-agent-count.test.ts --reporter=dot",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/startup/ssh-startup-reconnect.test.ts src/renderer/src/lib/resolved-worktree-execution-host.test.ts src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/runtime/sync-runtime-graph-scheduling.test.ts src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts src/renderer/src/components/terminal-pane/pty-connection-direct-ssh-spawn-retry.test.ts src/renderer/src/components/terminal-pane/pty-connection-direct-ssh-reattach-retry.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/runtime/remote-runtime-session-tabs-inflight.test.ts src/renderer/src/runtime/web-session-terminal-handle-events.test.ts src/renderer/src/store/slices/terminal-pty-identity-replacement.test.ts",
|
||||
"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",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-attach-subscription.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-host-surface-replacement.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-stream-reconnect.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-expired-pane-recovery.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-create-outcome-recovery.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-create-handoff.test.ts src/renderer/src/components/terminal-pane/remote-runtime-pty-recovery-state.test.ts src/renderer/src/components/terminal-pane/TerminalRemoteRuntimeReconnectBanner.test.tsx src/renderer/src/components/terminal-pane/terminal-remote-runtime-recovery-ui-state.test.ts src/shared/remote-runtime-socket-liveness.test.ts src/shared/remote-runtime-shared-control-connection.test.ts src/shared/remote-runtime-shared-control-socket-generation.test.ts src/shared/remote-runtime-client-error-classification.test.ts src/main/runtime/rpc/remote-runtime-server-heartbeat.test.ts src/main/runtime/rpc/methods/terminal-create-idempotency.test.ts src/main/runtime/orca-runtime-terminal-create-idempotency.test.ts",
|
||||
@@ -8084,6 +8091,8 @@
|
||||
],
|
||||
"testFiles": [
|
||||
"src/main/providers/ssh-pty-provider-reattach-incarnation.test.ts",
|
||||
"src/renderer/src/components/terminal-pane/paired-reconnect-multi-pane-materialization.test.ts",
|
||||
"src/renderer/src/runtime/paired-reconnect-sidebar-agent-count.test.ts",
|
||||
"src/renderer/src/startup/ssh-startup-reconnect.test.ts",
|
||||
"src/renderer/src/lib/resolved-worktree-execution-host.test.ts",
|
||||
"src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts",
|
||||
@@ -8142,6 +8151,20 @@
|
||||
"tests/e2e/ssh-docker-relay-perf.spec.ts"
|
||||
],
|
||||
"assertionRefs": [
|
||||
{
|
||||
"file": "src/renderer/src/components/terminal-pane/paired-reconnect-multi-pane-materialization.test.ts",
|
||||
"assertions": [
|
||||
"six panes sharing one dropped multiplex connection each resubscribe to a distinct live host handle",
|
||||
"a pane parked while the client slept is authoritatively activated and rematerialized without leaving any pane handle null"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/renderer/src/runtime/paired-reconnect-sidebar-agent-count.test.ts",
|
||||
"assertions": [
|
||||
"after a long sleep every live host PTY and tab retains its client-owned sidebar agent row",
|
||||
"unwritten or explicitly released pane authority still cedes deletion to the host"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/renderer/src/startup/ssh-startup-reconnect.test.ts",
|
||||
"assertions": [
|
||||
@@ -8471,6 +8494,15 @@
|
||||
}
|
||||
],
|
||||
"evidenceRuns": [
|
||||
{
|
||||
"date": "2026-08-23",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/paired-reconnect-multi-pane-materialization.test.ts src/renderer/src/runtime/paired-reconnect-sidebar-agent-count.test.ts --reporter=dot",
|
||||
"result": "passed",
|
||||
"durationSeconds": 2.54,
|
||||
"summary": "Seven deterministic STA-3107 contracts passed across six-pane multiplex rematerialization and client-owned sidebar-row retention after sleep/wake."
|
||||
},
|
||||
{
|
||||
"date": "2026-07-14",
|
||||
"runner": "local",
|
||||
@@ -8554,7 +8586,7 @@
|
||||
},
|
||||
"redGreenEvidence": {
|
||||
"status": "partial",
|
||||
"evidence": "The remote-runtime fault tests failed before the recovery changes by leaving a cold restored subscription detached, reporting connected before authoritative replay, delivering a fatal setup error twice, and allowing an unknown create outcome to spawn again after process-local state was lost. On exact pre-fix HEAD 939719443, the split-pane store, fresh-spawn, and reattach oracles failed because the first success removed pending authority and the sibling could not bind; the same three oracles pass after live bindings retain the exact attempt ID. On exact committed HEAD d501f2e96, primary-exit-before-sibling and primary/non-primary split-detach oracles failed because live authority was deleted during the empty gap or transferred to only one resulting tab; all three pass after continuation-gap preservation and two-sided detach projection. On exact committed HEAD d44ea382b with test-only oracles, a pending-only all-null detach deleted the attempt ledger, a sibling mounted after first success committed without its lease, and that sibling could bind after authority rotation; all three pass after pending-only projection and retained-live-lease capture with provider retirement. On exact committed HEAD 9fa84dacf, the production-manager in-progress oracle rejected the fresh authority and the forward-removal barrier delayed stale transport cancellation; both pass after replacement starts cancellation immediately, shares concurrent fresh callers, and waits for teardown before connecting. On exact committed HEAD e5ba9a9e5, overlapping disconnect allowed a replacement connect before forward teardown completed and delayed transport cancellation behind that barrier; disconnect, removal, and terminate now share a target lifecycle barrier, start transport cancellation immediately, retain captured-session identity, and admit the replacement only after cleanup. On exact committed HEAD 9a29e7a81, a rejected forward teardown short-circuited the lifecycle while transport disconnect was pending, removal left its captured relay session alive, same-turn connect escaped admission, and reset remained outside the target barrier; the exact failure oracles pass after both cleanup branches settle, captured sessions always retire, admission is authority-fenced, and reset shares the barrier. On exact committed HEAD 47c7198f2, reset's remaining bespoke forward teardown could still reject after authority rotation but before captured-session retirement; reset now uses the same hardened session teardown and a failed reset remains cleanly retryable. Other direct SSH tests encode red conditions for non-atomic binding clear, cross-target retry, folder omission, duplicate same-authority attempts, hydration overwrite, terminal finalization delayed behind provider work, obsolete-authority pending-spawn adoption, Git lineage namespace mismatch, and snapshot PTY hint promotion without exact-attempt acknowledgement. Existing SSH and stale-handle reattach coverage remains green. Needs WSL, paired-close, and a patched live remote-runtime partition journey before promotion."
|
||||
"evidence": "The remote-runtime fault tests failed before the recovery changes by leaving a cold restored subscription detached, reporting connected before authoritative replay, delivering a fatal setup error twice, and allowing an unknown create outcome to spawn again after process-local state was lost. For STA-3107, reverting #11542 in the six-pane multiplex harness leaves exactly one parked pane without a resubscribed handle while its siblings recover; before #12664, the first post-sleep host snapshot erases every stale client-owned sidebar row despite live tabs and host PTYs. The deterministic contracts pass after host activation rematerializes the missing pane and client-written ownership, rather than freshness, controls row retention. On exact pre-fix HEAD 939719443, the split-pane store, fresh-spawn, and reattach oracles failed because the first success removed pending authority and the sibling could not bind; the same three oracles pass after live bindings retain the exact attempt ID. On exact committed HEAD d501f2e96, primary-exit-before-sibling and primary/non-primary split-detach oracles failed because live authority was deleted during the empty gap or transferred to only one resulting tab; all three pass after continuation-gap preservation and two-sided detach projection. On exact committed HEAD d44ea382b with test-only oracles, a pending-only all-null detach deleted the attempt ledger, a sibling mounted after first success committed without its lease, and that sibling could bind after authority rotation; all three pass after pending-only projection and retained-live-lease capture with provider retirement. On exact committed HEAD 9fa84dacf, the production-manager in-progress oracle rejected the fresh authority and the forward-removal barrier delayed stale transport cancellation; both pass after replacement starts cancellation immediately, shares concurrent fresh callers, and waits for teardown before connecting. On exact committed HEAD e5ba9a9e5, overlapping disconnect allowed a replacement connect before forward teardown completed and delayed transport cancellation behind that barrier; disconnect, removal, and terminate now share a target lifecycle barrier, start transport cancellation immediately, retain captured-session identity, and admit the replacement only after cleanup. On exact committed HEAD 9a29e7a81, a rejected forward teardown short-circuited the lifecycle while transport disconnect was pending, removal left its captured relay session alive, same-turn connect escaped admission, and reset remained outside the target barrier; the exact failure oracles pass after both cleanup branches settle, captured sessions always retire, admission is authority-fenced, and reset shares the barrier. On exact committed HEAD 47c7198f2, reset's remaining bespoke forward teardown could still reject after authority rotation but before captured-session retirement; reset now uses the same hardened session teardown and a failed reset remains cleanly retryable. Other direct SSH tests encode red conditions for non-atomic binding clear, cross-target retry, folder omission, duplicate same-authority attempts, hydration overwrite, terminal finalization delayed behind provider work, obsolete-authority pending-spawn adoption, Git lineage namespace mismatch, and snapshot PTY hint promotion without exact-attempt acknowledgement. Existing SSH and stale-handle reattach coverage remains green. Needs WSL, paired-close, and a patched live remote-runtime partition journey before promotion."
|
||||
},
|
||||
"performanceBudget": {
|
||||
"required": true,
|
||||
@@ -9878,22 +9910,27 @@
|
||||
"providers": ["local", "daemon", "ssh", "remote-runtime"],
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["local"],
|
||||
"coverageNotes": "Local macOS evidence covers the runtime PTY write contract, live Codex orchestration, a dev-runtime CLI repro, and Claude and Codex composer traces. The render gate stays on the PTY-owning runtime, so paired and SSH callers use the same provider write/output path without a wire change. SSH, daemon, remote-runtime, Linux, and Windows live journeys remain gaps.",
|
||||
"coverageNotes": "Local macOS evidence covers the runtime PTY write contract, live Codex orchestration, a dev-runtime CLI repro, and Claude and Codex composer traces. A deterministic worker-start RPC/SQLite contract proves delayed Codex composer acceptance, exactly one submitted turn, durable Dispatch success, and explicit stalled failure when Enter is swallowed without a rescue send. The render gate stays on the PTY-owning runtime, so paired and SSH callers use the same provider write/output path without a wire change. SSH, daemon, remote-runtime, Linux, and Windows live journeys remain gaps.",
|
||||
"motivatingLinks": [
|
||||
"https://linear.app/stably/issue/STA-3800",
|
||||
"https://linear.app/stably/issue/STA-3904",
|
||||
"https://linear.app/stably/issue/STA-4328",
|
||||
"https://github.com/stablyai/orca/issues/7226",
|
||||
"https://github.com/stablyai/orca/issues/13821",
|
||||
"https://github.com/stablyai/orca/issues/14347"
|
||||
],
|
||||
"invariant": "Injected orchestration task prompts for recognized agent CLIs must send the prompt body inside one bracketed-paste frame, sanitize embedded ESC bytes, preserve chunk boundaries without losing the frame, and submit exactly once only after the agent can accept Enter. Claude and Codex must emit a post-paste composer marker and then settle, or reach the bounded fallback first; every other agent retains the platform delay.",
|
||||
"oracle": "Runtime tests assert the exact PTY write sequence, failure cleanup, Claude/Codex marker-gated multi-frame renders, and the legacy platform delay for every other configured agent. The candidate resets settlement on later frames, gives a late marker a fresh bounded window, and still submits once at the hard deadline if output never settles. Orchestration tests assert dispatch/coordinator use the agent prompt path; the live CLI harness covers long Codex-like framing.",
|
||||
"invariant": "Injected orchestration task prompts for recognized agent CLIs must send the prompt body inside one bracketed-paste frame, sanitize embedded ESC bytes, preserve chunk boundaries without losing the frame, and submit exactly once only after the agent can accept Enter. A successful orchestration.workerStart must durably record exactly one accepted and started turn; a swallowed Enter must fail with agent_prompt_stalled and never trigger a blind rescue Enter. Claude and Codex must emit a post-paste composer marker and then settle, or reach the bounded fallback first; every other agent retains the platform delay.",
|
||||
"oracle": "Runtime tests assert the exact PTY write sequence, failure cleanup, Claude/Codex marker-gated multi-frame renders, and the legacy platform delay for every other configured agent. The candidate resets settlement on later frames, gives a late marker a fresh bounded window, and still submits once at the hard deadline if output never settles. The worker-start contract drives the production RPC through a delayed fake Codex composer and independently checks exact turn/Enter counts plus reopened SQLite Task, Dispatch, worker receipt, and mutation receipt state for accepted and swallowed outcomes. Other orchestration tests assert dispatch/coordinator use the agent prompt path; the live CLI harness covers long Codex-like framing.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/shared/agent-prompt-injection.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/orchestration-tasks-dispatch.test.ts src/main/runtime/orchestration/coordinator.test.ts",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration-worker-start-prompt-contract.test.ts --reporter=dot",
|
||||
"node tests/tools/repro-orchestration-long-prompt.mjs --cli out/bin/orca-dev --mode codex-like --size-kb 32 --timeout-ms 20000"
|
||||
],
|
||||
"testFiles": [
|
||||
"src/shared/agent-prompt-injection.test.ts",
|
||||
"src/main/runtime/orca-runtime.test.ts",
|
||||
"src/main/runtime/rpc/methods/orchestration-tasks-dispatch.test.ts",
|
||||
"src/main/runtime/rpc/methods/orchestration-worker-start-prompt-contract.test.ts",
|
||||
"src/main/runtime/orchestration/coordinator.test.ts",
|
||||
"tests/tools/repro-orchestration-long-prompt.mjs"
|
||||
],
|
||||
@@ -9928,6 +9965,13 @@
|
||||
"failed prompt injection rolls back the active dispatch"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/main/runtime/rpc/methods/orchestration-worker-start-prompt-contract.test.ts",
|
||||
"assertions": [
|
||||
"delayed composer readiness produces exactly one submitted and started turn with no premature Enter and durable ready receipts",
|
||||
"a swallowed Enter records agent_prompt_stalled across Task, Dispatch, worker, and mutation receipts without a rescue Enter"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/main/runtime/orchestration/coordinator.test.ts",
|
||||
"assertions": [
|
||||
@@ -9945,6 +9989,15 @@
|
||||
}
|
||||
],
|
||||
"evidenceRuns": [
|
||||
{
|
||||
"date": "2026-08-23",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/orchestration-worker-start-prompt-contract.test.ts --reporter=dot",
|
||||
"result": "passed",
|
||||
"durationSeconds": 21.84,
|
||||
"summary": "Two deterministic worker-start RPC contracts passed with fake clocks and reopened SQLite receipts for one accepted turn and one swallowed-Enter stalled outcome."
|
||||
},
|
||||
{
|
||||
"date": "2026-08-14",
|
||||
"runner": "local",
|
||||
@@ -10001,7 +10054,7 @@
|
||||
},
|
||||
"redGreenEvidence": {
|
||||
"status": "partial",
|
||||
"evidence": "The original Claude-shaped oracle fails on unmodified main and passes with the render gate. The hardened multi-frame oracle then fails on the first-marker candidate, which submits at 751 ms during an intermediate frame, and passes when the gate requires post-marker quiescence. Codex used the legacy platform delay before this candidate; the late-marker oracle proves the original deadline would pre-empt slow-host settlement without re-arming. The earlier live harness also reproduced the unsafe raw multiline contract before its framing fix. Intentional-break evidence remains local rather than a separate CI job."
|
||||
"evidence": "The original Claude-shaped oracle fails on unmodified main and passes with the render gate. The hardened multi-frame oracle then fails on the first-marker candidate, which submits at 751 ms during an intermediate frame, and passes when the gate requires post-marker quiescence. Codex used the legacy platform delay before this candidate; the late-marker oracle proves the original deadline would pre-empt slow-host settlement without re-arming. The worker-start negative controls caught both premature submission before composer readiness and a false-ready swallowed Enter; the accepted candidate records one started turn, while the swallowed arm records agent_prompt_stalled without a rescue Enter. The earlier live harness also reproduced the unsafe raw multiline contract before its framing fix. Intentional-break evidence remains local rather than a separate CI job."
|
||||
},
|
||||
"performanceBudget": {
|
||||
"required": true,
|
||||
@@ -14249,6 +14302,349 @@
|
||||
"The legacy remote-uploads root is intentionally not reclaimed while a mixed-version relay may still own bytes there; eventual legacy-root retirement requires a separate compatibility decision."
|
||||
],
|
||||
"demotionRule": "Demote if one live owner can remove another owner's bytes, cleanup exceeds 64 inspected entries per attempt, a lifecycle path retains its exact owned archive after settlement, or the process oracle flakes without an identified harness or product defect."
|
||||
},
|
||||
{
|
||||
"id": "terminal-startup.quick-command-pre-bind-recovery",
|
||||
"title": "Quick Command survives a pre-bind terminal recovery",
|
||||
"maturity": "experimental",
|
||||
"protection": "partial",
|
||||
"owner": "terminal-renderer-lifecycle",
|
||||
"layer": "electron-ui-and-real-local-pty",
|
||||
"surfaces": ["Quick Commands", "terminal pane recovery", "fresh PTY startup"],
|
||||
"platforms": ["macos", "linux", "windows"],
|
||||
"providers": ["local"],
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["local"],
|
||||
"coverageNotes": "A forced pre-spawn barrier makes one visible Quick Command cross a recovery remount before its successor PTY binds. Store and lifecycle contracts retain lower-layer ownership; the Electron sentinel adds the rendered affordance, real PTY, exact-once terminal marker, staged identity file, and unrelated sibling canary.",
|
||||
"motivatingLinks": [
|
||||
"https://linear.app/stably/issue/STA-4876",
|
||||
"https://github.com/stablyai/orca/pull/15630"
|
||||
],
|
||||
"invariant": "A Quick Command selected for a new terminal remains owned by that tab through a recovery remount, executes exactly once only after the successor PTY binds, and never reaches an unrelated terminal.",
|
||||
"oracle": "Arm the E2E-only pre-spawn barrier, click the visible Quick Command, force one recovery generation while the original spawn is blocked, and release it. Require one exact semantic xterm marker, an independently written pane/tab identity file matching the bound live PTY, queue consumption only after bind, and a live interactive sibling canary.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection-queued-startup-consume.test.ts src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts src/renderer/src/store/slices/terminal-startup-command-retention.test.ts --reporter=dot",
|
||||
"pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
|
||||
"ORCA_E2E_FORCE_HEADFUL=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1"
|
||||
],
|
||||
"testFiles": [
|
||||
"src/renderer/src/components/terminal-pane/pty-connection-queued-startup-consume.test.ts",
|
||||
"src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.test.ts",
|
||||
"src/renderer/src/store/slices/terminal-startup-command-retention.test.ts",
|
||||
"tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts"
|
||||
],
|
||||
"assertionRefs": [
|
||||
{
|
||||
"file": "src/renderer/src/store/slices/terminal-startup-command-retention.test.ts",
|
||||
"assertions": ["recovery remount retains the exact queued startup command"]
|
||||
},
|
||||
{
|
||||
"file": "tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts",
|
||||
"assertions": [
|
||||
"the visible Quick Command executes exactly once in the intended fresh PTY",
|
||||
"queue consumption follows PTY binding and the sibling terminal remains live"
|
||||
]
|
||||
}
|
||||
],
|
||||
"evidenceRuns": [
|
||||
{
|
||||
"date": "2026-08-23",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"result": "passed",
|
||||
"command": "pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
|
||||
"durationSeconds": 23,
|
||||
"summary": "The exact rebased PR head passed the headless Electron flow in 23.0 seconds after an E2E-mode build."
|
||||
},
|
||||
{
|
||||
"date": "2026-08-23",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"result": "passed",
|
||||
"command": "ORCA_E2E_FORCE_HEADFUL=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
|
||||
"durationSeconds": 24,
|
||||
"summary": "The exact rebased PR head passed the visible-window Electron flow in 23.9 seconds using the same E2E build."
|
||||
}
|
||||
],
|
||||
"runtimeBudget": {
|
||||
"p95Seconds": 90,
|
||||
"scope": "one isolated Electron app, one forced recovery remount, and two local PTYs"
|
||||
},
|
||||
"flakeHistory": {
|
||||
"status": "not-started",
|
||||
"evidence": "The new sentinel has local headless and forced-headful evidence but no routed CI soak history."
|
||||
},
|
||||
"redGreenEvidence": {
|
||||
"status": "complete",
|
||||
"evidence": "The byte-identical spec failed with pending:null before PTY bind when the pre-6e25a900 eager-consume behavior was restored, then passed after restoration."
|
||||
},
|
||||
"performanceBudget": {
|
||||
"required": true,
|
||||
"evidence": "The barrier exists only in E2E builds, adds no production timer or polling, and the live sentinel completed in under 20 seconds locally."
|
||||
},
|
||||
"promotionCriteria": [
|
||||
"Collect 100 consecutive routed CI passes over at least 14 days without an unexplained flake.",
|
||||
"Keep retries at zero and retain both semantic and identity oracles.",
|
||||
"Collect Linux Electron evidence before promoting the focused lane to blocking."
|
||||
],
|
||||
"knownGaps": [
|
||||
"Windows, Linux, SSH, WSL, and paired-runtime topologies are not covered because they were not causal to STA-4876.",
|
||||
"The sentinel remains advisory while the repository-wide E2E signal is red."
|
||||
],
|
||||
"demotionRule": "Demote if the barrier can be bypassed nondeterministically, either independent oracle is removed, the sibling canary is no longer isolated, or one unexplained flake occurs."
|
||||
},
|
||||
{
|
||||
"id": "quick-open.paired-host-path-search",
|
||||
"title": "Paired Quick Open searches bounded host paths",
|
||||
"maturity": "experimental",
|
||||
"protection": "partial",
|
||||
"owner": "runtime-filesystem",
|
||||
"layer": "host-file-search-and-paired-runtime",
|
||||
"surfaces": ["Quick Open", "paired desktop runtime", "headless runtime host"],
|
||||
"platforms": ["macos", "linux", "windows"],
|
||||
"providers": ["local", "ssh", "paired-runtime"],
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["local", "paired-runtime"],
|
||||
"coverageNotes": "Focused contracts cover bounded host search, ignore traversal, RPC response bounds, renderer cancellation, deterministic ordering, and transport payload size. Headed and headless paired-runtime journeys use an 88,763-file fixture and are source-routed into advisory PR E2E; physical SSH and Windows remain gaps.",
|
||||
"motivatingLinks": [
|
||||
"https://linear.app/stably/issue/STA-4354",
|
||||
"https://github.com/stablyai/orca/pull/15158"
|
||||
],
|
||||
"invariant": "Quick Open queries execute on the worktree host, find exact ignored-path matches beyond the legacy inventory prefix, return deterministic bounded results, and keep the paired runtime usable without overflowing its outbound reply buffer.",
|
||||
"oracle": "Create 88,763 paths with 77,792 ignored entries and a nominal 22 GiB sparse file, query exact late gitignored and .orcaignored targets through headed and headless paired runtimes, and require one deterministic match, a payload below 4 KiB, and a healthy follow-up worktree call.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem-search-file-paths.test.ts src/main/runtime/orca-runtime-files-search.test.ts src/main/runtime/rpc/methods/files-path-search.test.ts src/renderer/src/components/quick-open-file-list.react.test.tsx src/renderer/src/runtime/runtime-file-client-search-listing.test.ts src/shared/quick-open-transport-budget.test.ts --reporter=dot",
|
||||
"pnpm exec playwright test tests/e2e/paired-quick-open-large-tree.spec.ts --config tests/playwright.config.ts --workers=1"
|
||||
],
|
||||
"testFiles": [
|
||||
"src/main/ipc/filesystem-search-file-paths.test.ts",
|
||||
"src/main/runtime/orca-runtime-files-search.test.ts",
|
||||
"src/main/runtime/rpc/methods/files-path-search.test.ts",
|
||||
"src/renderer/src/components/quick-open-file-list.react.test.tsx",
|
||||
"src/renderer/src/runtime/runtime-file-client-search-listing.test.ts",
|
||||
"src/shared/quick-open-transport-budget.test.ts",
|
||||
"tests/e2e/paired-quick-open-large-tree.spec.ts"
|
||||
],
|
||||
"assertionRefs": [
|
||||
{
|
||||
"file": "src/main/ipc/filesystem-search-file-paths.test.ts",
|
||||
"assertions": [
|
||||
"host search stays bounded and respects gitignore plus .orcaignore traversal"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/renderer/src/runtime/runtime-file-client-search-listing.test.ts",
|
||||
"assertions": ["paired path queries stay deterministic and bounded across transport"]
|
||||
},
|
||||
{
|
||||
"file": "tests/e2e/paired-quick-open-large-tree.spec.ts",
|
||||
"assertions": ["headed and headless hosts find late ignored targets and remain callable"]
|
||||
}
|
||||
],
|
||||
"evidenceRuns": [
|
||||
{
|
||||
"date": "2026-08-23",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"result": "passed",
|
||||
"command": "pnpm exec vitest run --config config/vitest.config.ts src/main/ipc/filesystem-search-file-paths.test.ts src/main/runtime/orca-runtime-files-search.test.ts src/main/runtime/rpc/methods/files-path-search.test.ts src/renderer/src/components/quick-open-file-list.react.test.tsx src/renderer/src/runtime/runtime-file-client-search-listing.test.ts src/shared/quick-open-transport-budget.test.ts --reporter=dot",
|
||||
"durationSeconds": 5,
|
||||
"summary": "Six focused files passed 52 tests across host search, runtime RPC, renderer query ownership, and transport bounds; existing React act warnings remained non-fatal."
|
||||
}
|
||||
],
|
||||
"runtimeBudget": {
|
||||
"p95Seconds": 300,
|
||||
"scope": "focused deterministic contracts plus two serial paired Electron large-tree journeys"
|
||||
},
|
||||
"flakeHistory": {
|
||||
"status": "not-started",
|
||||
"evidence": "The sentinel is newly source-routed for PR collection; no route-specific soak history exists yet."
|
||||
},
|
||||
"redGreenEvidence": {
|
||||
"status": "complete",
|
||||
"evidence": "The merged STA-4354 oracle places both targets beyond the removed inventory prefix; the old client-side prefix inventory misses them, while host search returns the exact deterministic paths."
|
||||
},
|
||||
"performanceBudget": {
|
||||
"required": true,
|
||||
"evidence": "Search is query-driven, result-limited, cancellation-aware, and payload-bounded; PR routing selects this fixture only for its exact production authorities or direct spec edits."
|
||||
},
|
||||
"promotionCriteria": [
|
||||
"Collect 100 consecutive routed CI passes or 14 days without an unexplained flake.",
|
||||
"Collect physical SSH and Windows paired-runtime evidence.",
|
||||
"Keep deterministic result hashes, payload bounds, and post-query runtime health green."
|
||||
],
|
||||
"knownGaps": [
|
||||
"The live large-tree evidence uses local headed and headless hosts rather than physical SSH.",
|
||||
"Windows path-search tooling and filesystem behavior are not represented by the local evidence."
|
||||
],
|
||||
"demotionRule": "Demote if the routed fixture flakes without a diagnosed product or harness cause, returns unbounded payloads, misses either late ignored target, or leaves the paired runtime unhealthy."
|
||||
},
|
||||
{
|
||||
"id": "terminal-session.host-cold-park-stream-continuity",
|
||||
"title": "Host cold parking preserves paired terminal streams",
|
||||
"maturity": "experimental",
|
||||
"protection": "partial",
|
||||
"owner": "terminal-runtime-graph",
|
||||
"layer": "renderer-runtime-graph-and-terminal-stream",
|
||||
"surfaces": ["host terminal cold park", "paired remote viewer", "multi-pane runtime graph"],
|
||||
"platforms": ["macos", "linux", "windows"],
|
||||
"providers": ["local-daemon", "ssh-daemon", "paired-runtime"],
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["local-daemon", "paired-runtime"],
|
||||
"coverageNotes": "Deterministic policy and multiplex tests separate renderer parking from authoritative stream liveness, while runtime-graph tests cover exact parked leaf, pane runtime ID, title, multi-pane active-leaf, and disposal behavior. One headed paired journey proves input and echoed output while the host pane remains cold-parked.",
|
||||
"motivatingLinks": [
|
||||
"https://linear.app/stably/issue/STA-2854",
|
||||
"https://github.com/stablyai/orca/pull/15514"
|
||||
],
|
||||
"invariant": "Cold parking a host renderer pane never retires its live PTY's runtime-graph leaf or interrupts a paired subscriber's stream, input, reconnect, pane identity, or multi-pane routing; the leaf retires only when exact PTY ownership ends.",
|
||||
"oracle": "Cold-park a host-owned pane while a paired client actively views it, require the host manager to unmount, then type through the client and require the same PTY to receive and echo the token without any disconnected sample. Separately publish multi-pane parked leaves with exact pane runtime IDs and require per-PTY disposal to remove only the retired leaf.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts src/renderer/src/runtime/sync-runtime-graph-parked-leaf.test.ts tests/e2e/host-cold-park-remote-subscriber.unit.test.ts --reporter=dot",
|
||||
"pnpm exec playwright test tests/e2e/host-parked-pane-remote-viewer.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1"
|
||||
],
|
||||
"testFiles": [
|
||||
"src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts",
|
||||
"src/renderer/src/runtime/sync-runtime-graph-parked-leaf.test.ts",
|
||||
"tests/e2e/host-cold-park-remote-subscriber.unit.test.ts",
|
||||
"tests/e2e/host-parked-pane-remote-viewer.spec.ts"
|
||||
],
|
||||
"assertionRefs": [
|
||||
{
|
||||
"file": "src/renderer/src/runtime/sync-runtime-graph-parked-leaf.test.ts",
|
||||
"assertions": [
|
||||
"a live parked watcher publishes the exact leaf, pane runtime ID, and title",
|
||||
"multi-pane publication never names an unsent active leaf and exact disposal retires ownership"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "tests/e2e/host-cold-park-remote-subscriber.unit.test.ts",
|
||||
"assertions": [
|
||||
"a fully unmounted host renderer still streams, accepts input, and resubscribes"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "tests/e2e/host-parked-pane-remote-viewer.spec.ts",
|
||||
"assertions": [
|
||||
"a cold-parked host pane carries a complete paired-client input and echo round trip"
|
||||
]
|
||||
}
|
||||
],
|
||||
"evidenceRuns": [
|
||||
{
|
||||
"date": "2026-08-23",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"result": "passed",
|
||||
"command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.test.ts src/renderer/src/runtime/sync-runtime-graph-parked-leaf.test.ts tests/e2e/host-cold-park-remote-subscriber.unit.test.ts --reporter=dot",
|
||||
"durationSeconds": 8,
|
||||
"summary": "Three focused files passed 64 watcher, multi-pane runtime-graph, cold-park policy, and authoritative-stream tests."
|
||||
}
|
||||
],
|
||||
"runtimeBudget": {
|
||||
"p95Seconds": 180,
|
||||
"scope": "focused deterministic contracts plus one serial headed paired cold-park journey"
|
||||
},
|
||||
"flakeHistory": {
|
||||
"status": "not-started",
|
||||
"evidence": "The existing sentinel is newly source-routed for PR collection; route-specific CI history has not started."
|
||||
},
|
||||
"redGreenEvidence": {
|
||||
"status": "complete",
|
||||
"evidence": "On the affected STA-2854 path, cold parking removed the runtime-graph leaf and the paired stream disconnected; retaining the exact live parked watcher leaf keeps every sampled client phase connected and completes input plus echo."
|
||||
},
|
||||
"performanceBudget": {
|
||||
"required": true,
|
||||
"evidence": "Publication reads the existing bounded parked-watcher registry and adds no timer, polling, provider scan, subprocess, or wire field; the 90-second live timeline is selected only by exact parking and graph authorities."
|
||||
},
|
||||
"promotionCriteria": [
|
||||
"Collect 100 consecutive routed CI passes or 14 days without an unexplained flake.",
|
||||
"Collect Linux, Windows, WSL, and physical SSH cold-park evidence.",
|
||||
"Keep exact per-leaf disposal, multi-pane identity, and full client round-trip assertions green."
|
||||
],
|
||||
"knownGaps": [
|
||||
"The live paired cold-park journey is macOS-only and uses a local daemon PTY.",
|
||||
"Physical SSH, WSL, Linux, Windows, and host-restart cold-park journeys are not recorded."
|
||||
],
|
||||
"demotionRule": "Demote if a live parked PTY loses its exact graph leaf, a retired PTY remains published, multi-pane identity drifts, or the routed client round trip flakes without a diagnosed cause."
|
||||
},
|
||||
{
|
||||
"id": "terminal-session.remote-pane-layout-retry",
|
||||
"title": "Remote pane layouts retry identical state after reconnect",
|
||||
"maturity": "experimental",
|
||||
"protection": "partial",
|
||||
"owner": "terminal-layout-sync",
|
||||
"layer": "renderer-paired-runtime-layout",
|
||||
"surfaces": ["paired terminal split layout", "pane title", "runtime reconnect"],
|
||||
"platforms": ["macos", "linux", "windows"],
|
||||
"providers": ["paired-runtime"],
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["paired-runtime"],
|
||||
"coverageNotes": "Pure contracts cover identity-equal local write bailouts and remote push deduplication, while a headless-host paired Electron journey proves that an identical local layout is retried after a failed disconnected push and becomes visible to an independent observer.",
|
||||
"motivatingLinks": ["https://github.com/stablyai/orca/pull/12420"],
|
||||
"invariant": "Identity-equal pane layout writes avoid local churn but never suppress a remote retry whose prior push failed; reconnecting and repeating the same layout persists it on the host and publishes it to other paired clients.",
|
||||
"oracle": "Disconnect a paired client, change a pane title, and observe the failed host push while local state retains the layout. Reconnect without remounting, submit the identical title again, and require the headless host plus a second paired observer to receive it.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/remote-pane-layout-push.test.ts src/renderer/src/store/slices/terminal-write-identity-bailouts.test.ts --reporter=dot",
|
||||
"pnpm exec playwright test tests/e2e/paired-remote-pane-layout-retry.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1"
|
||||
],
|
||||
"testFiles": [
|
||||
"src/renderer/src/components/terminal-pane/remote-pane-layout-push.test.ts",
|
||||
"src/renderer/src/store/slices/terminal-write-identity-bailouts.test.ts",
|
||||
"tests/e2e/paired-remote-pane-layout-retry.spec.ts"
|
||||
],
|
||||
"assertionRefs": [
|
||||
{
|
||||
"file": "src/renderer/src/components/terminal-pane/remote-pane-layout-push.test.ts",
|
||||
"assertions": ["only successfully pushed layouts deduplicate later remote writes"]
|
||||
},
|
||||
{
|
||||
"file": "src/renderer/src/store/slices/terminal-write-identity-bailouts.test.ts",
|
||||
"assertions": ["identity-equal layout and timer writes avoid redundant local updates"]
|
||||
},
|
||||
{
|
||||
"file": "tests/e2e/paired-remote-pane-layout-retry.spec.ts",
|
||||
"assertions": [
|
||||
"an identical layout retries after reconnect and reaches a second paired observer"
|
||||
]
|
||||
}
|
||||
],
|
||||
"evidenceRuns": [
|
||||
{
|
||||
"date": "2026-08-23",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"result": "passed",
|
||||
"command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/remote-pane-layout-push.test.ts src/renderer/src/store/slices/terminal-write-identity-bailouts.test.ts --reporter=dot",
|
||||
"durationSeconds": 5,
|
||||
"summary": "Two focused files passed 20 remote-push and identity-bailout contracts."
|
||||
}
|
||||
],
|
||||
"runtimeBudget": {
|
||||
"p95Seconds": 90,
|
||||
"scope": "two focused renderer contracts plus one serial headless-host paired journey"
|
||||
},
|
||||
"flakeHistory": {
|
||||
"status": "not-started",
|
||||
"evidence": "The existing paired sentinel is newly source-routed and has no route-specific CI soak history."
|
||||
},
|
||||
"redGreenEvidence": {
|
||||
"status": "complete",
|
||||
"evidence": "The affected implementation cached the disconnected layout before host acknowledgment and suppressed the identical retry; the merged oracle keeps only successful remote pushes deduplicated and the observer receives the retried title."
|
||||
},
|
||||
"performanceBudget": {
|
||||
"required": true,
|
||||
"evidence": "Successful identity-equal writes remain O(1) bailouts; one failed remote push permits one later identical retry, with no polling, timer, provider scan, subprocess, or new wire field."
|
||||
},
|
||||
"promotionCriteria": [
|
||||
"Collect 100 consecutive routed CI passes or 14 days without an unexplained flake.",
|
||||
"Collect Linux and Windows paired-runtime reconnect evidence.",
|
||||
"Keep local identity bailouts and failed-push retry ownership green."
|
||||
],
|
||||
"knownGaps": [
|
||||
"The paired reconnect journey has only local macOS evidence.",
|
||||
"The sentinel changes a pane title within an existing layout; concurrent split and close conflicts remain separate coverage."
|
||||
],
|
||||
"demotionRule": "Demote if a failed push suppresses an identical retry, a successful equal write resumes redundant churn, or the routed observer journey flakes without a diagnosed cause."
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { parse as parseJsonc } from 'jsonc-parser'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parse } from 'yaml'
|
||||
import { parse as parseYaml } from 'yaml'
|
||||
import { PR_E2E_SOURCE_ROUTES, selectPrE2eSpecs } from './pr-e2e-source-routing.mjs'
|
||||
|
||||
const projectDir = resolve(import.meta.dirname, '../..')
|
||||
const prWorkflow = parse(readFileSync(join(projectDir, '.github/workflows/pr.yml'), 'utf8'))
|
||||
const e2eWorkflow = parse(readFileSync(join(projectDir, '.github/workflows/e2e.yml'), 'utf8'))
|
||||
const prWorkflow = parseYaml(readFileSync(join(projectDir, '.github/workflows/pr.yml'), 'utf8'))
|
||||
const e2eWorkflow = parseYaml(readFileSync(join(projectDir, '.github/workflows/e2e.yml'), 'utf8'))
|
||||
const reliabilityManifest = parseJsonc(
|
||||
readFileSync(join(projectDir, 'config/reliability-gates.jsonc'), 'utf8')
|
||||
)
|
||||
const playwrightConfig = readFileSync(join(projectDir, 'tests/playwright.config.ts'), 'utf8')
|
||||
const sshDockerRunner = readFileSync(
|
||||
join(projectDir, 'config/scripts/run-ssh-docker-terminal-parking-e2e.mjs'),
|
||||
'utf8'
|
||||
@@ -69,8 +75,15 @@ describe('PR E2E gate contract', () => {
|
||||
|
||||
it('selects modified Playwright specs without running deleted tests', () => {
|
||||
expect(filterStep.run).toContain('--diff-filter=AMCR')
|
||||
expect(filterStep.run).toContain("'^tests/e2e/.*\\.spec\\.ts$'")
|
||||
expect(filterStep.run).toContain('config/scripts/pr-e2e-source-routing.mjs')
|
||||
expect(filterStep.run).not.toContain('tests/playwright\\.')
|
||||
expect(
|
||||
selectPrE2eSpecs([
|
||||
'tests/e2e/active-view-restart-restore.spec.ts',
|
||||
'tests/e2e/deleted.spec.ts.bak',
|
||||
'tests/e2e/global-teardown.unit.test.ts'
|
||||
])
|
||||
).toEqual(['tests/e2e/active-view-restart-restore.spec.ts'])
|
||||
})
|
||||
|
||||
it('uses one runner for changed specs and keeps full runs sharded', () => {
|
||||
@@ -89,6 +102,7 @@ describe('PR E2E gate contract', () => {
|
||||
expect(changedRun.run).toContain(
|
||||
'pnpm run test:e2e "${TEST_FILES[@]}" --workers=1 "${E2E_PROJECT_ARGS[@]}"'
|
||||
)
|
||||
expect(playwrightConfig).toContain('retries: 0')
|
||||
})
|
||||
|
||||
it('keeps startup-exec live parity in the isolated SSH lane', () => {
|
||||
@@ -121,7 +135,7 @@ describe('PR E2E gate contract', () => {
|
||||
]
|
||||
|
||||
for (const file of dedicatedWorkflows) {
|
||||
const workflow = parse(readFileSync(join(projectDir, '.github/workflows', file), 'utf8'))
|
||||
const workflow = parseYaml(readFileSync(join(projectDir, '.github/workflows', file), 'utf8'))
|
||||
expect(workflow.on.pull_request, file).toBeUndefined()
|
||||
}
|
||||
})
|
||||
@@ -138,12 +152,14 @@ describe('PR E2E gate contract', () => {
|
||||
const sshSourceAuthorities = [
|
||||
'src/main/ssh/',
|
||||
'src/main/providers/ssh-',
|
||||
'src/main/ipc/(ssh-|pty)',
|
||||
'src/main/ipc/pty',
|
||||
'src/relay/',
|
||||
'src/renderer/src/components/terminal-pane/(pty-|ssh-|remote-runtime-|terminal-parked-pty)'
|
||||
'src/renderer/src/components/terminal-pane/remote-runtime-'
|
||||
]
|
||||
for (const authority of sshSourceAuthorities) {
|
||||
expect(filterStep.run).toContain(authority)
|
||||
expect(selectPrE2eSpecs([`${authority}routing.ts`])).toContain(
|
||||
'tests/e2e/ssh-docker-reconnect-pane-restore.spec.ts'
|
||||
)
|
||||
}
|
||||
|
||||
const mappedSpecs = [
|
||||
@@ -154,7 +170,7 @@ describe('PR E2E gate contract', () => {
|
||||
'tests/e2e/ssh-terminal-window-wake-stale-grid-repro.spec.ts'
|
||||
]
|
||||
for (const spec of mappedSpecs) {
|
||||
expect(filterStep.run).toContain(`'${spec}'`)
|
||||
expect(selectPrE2eSpecs(['src/main/ssh/connection.ts'])).toContain(spec)
|
||||
expect(existsSync(join(projectDir, spec)), spec).toBe(true)
|
||||
// Why: a spec that stops reading the flag would silently run without Docker.
|
||||
if (spec !== 'tests/e2e/ssh-startup-exec-readiness.spec.ts') {
|
||||
@@ -162,8 +178,7 @@ describe('PR E2E gate contract', () => {
|
||||
}
|
||||
}
|
||||
|
||||
// Why: unit tests next to the mapped sources prove the same code without Docker.
|
||||
expect(filterStep.run).toContain("grep -Ev '\\.test\\.tsx?$'")
|
||||
expect(selectPrE2eSpecs(['src/main/ssh/connection.test.ts'])).toEqual([])
|
||||
|
||||
// Why: startup readiness is filtered out of changed-e2e, so listing it is only
|
||||
// meaningful while it still routes the dedicated Docker lane.
|
||||
@@ -183,6 +198,99 @@ describe('PR E2E gate contract', () => {
|
||||
expect(rollbackStep.run).toContain('--merge-base "$BASE_SHA" "$HEAD_SHA"')
|
||||
expect(rollbackStep.run).toContain('src/shared/ephemeral-vm-recipes.ts')
|
||||
expect(rollbackStep.run).toContain('src/shared/orca-yaml-hook-types.ts')
|
||||
expect(filterStep.run).toContain('ephemeral-vm-recipes|orca-yaml-hook-types')
|
||||
expect(selectPrE2eSpecs(['src/shared/ephemeral-vm-recipes.ts'])).toEqual([
|
||||
'tests/e2e/ephemeral-vm-provisioned-root.spec.ts'
|
||||
])
|
||||
})
|
||||
|
||||
it('routes P0 sentinels from their causal sources', () => {
|
||||
const cases = [
|
||||
[
|
||||
'src/renderer/src/components/tab-bar/TabBarQuickCommandsMenu.tsx',
|
||||
'tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts'
|
||||
],
|
||||
['src/main/runtime/orca-runtime-files.ts', 'tests/e2e/paired-quick-open-large-tree.spec.ts'],
|
||||
[
|
||||
'src/renderer/src/runtime/sync-runtime-graph.ts',
|
||||
'tests/e2e/host-parked-pane-remote-viewer.spec.ts'
|
||||
],
|
||||
[
|
||||
'src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts',
|
||||
'tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts'
|
||||
],
|
||||
[
|
||||
'src/renderer/src/components/terminal-pane/remote-pane-layout-push.ts',
|
||||
'tests/e2e/paired-remote-pane-layout-retry.spec.ts'
|
||||
]
|
||||
]
|
||||
for (const [source, spec] of cases) {
|
||||
expect(selectPrE2eSpecs([source]), source).toEqual([spec])
|
||||
expect(selectPrE2eSpecs([source.replace(/\.tsx?$/, '.test.ts')]), source).toEqual([])
|
||||
expect(existsSync(join(projectDir, spec)), spec).toBe(true)
|
||||
}
|
||||
const quickCommandSpec = 'tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts'
|
||||
for (const source of [
|
||||
'src/renderer/src/components/terminal-pane/pty-connection.ts',
|
||||
'src/renderer/src/components/terminal-pane/pty-connection/connect-pane-pty.ts',
|
||||
'src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts',
|
||||
'src/renderer/src/components/terminal-pane/pty-connection/pane-pty-visibility-bind.ts',
|
||||
'src/renderer/src/components/terminal-pane/pty-connection/pty-input-recovery.ts'
|
||||
]) {
|
||||
expect(selectPrE2eSpecs([source]), source).toContain(quickCommandSpec)
|
||||
expect(selectPrE2eSpecs([source.replace(/\.ts$/, '.test.ts')]), source).not.toContain(
|
||||
quickCommandSpec
|
||||
)
|
||||
}
|
||||
for (const source of [
|
||||
'src/main/ipc/rg-availability.ts',
|
||||
'src/shared/ripgrep-process-availability.ts'
|
||||
]) {
|
||||
expect(selectPrE2eSpecs([source]), source).toEqual([
|
||||
'tests/e2e/paired-quick-open-large-tree.spec.ts'
|
||||
])
|
||||
}
|
||||
expect(
|
||||
selectPrE2eSpecs([
|
||||
'src/main/runtime/orca-runtime-files.ts',
|
||||
'tests/e2e/paired-quick-open-large-tree.spec.ts'
|
||||
])
|
||||
).toEqual(['tests/e2e/paired-quick-open-large-tree.spec.ts'])
|
||||
expect(selectPrE2eSpecs(['src/renderer/src/components/FileExplorer.tsx'])).toEqual([])
|
||||
expect(
|
||||
selectPrE2eSpecs([
|
||||
'src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts'
|
||||
])
|
||||
).toContain('tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts')
|
||||
expect(
|
||||
selectPrE2eSpecs([
|
||||
'src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-test-harness.ts'
|
||||
])
|
||||
).not.toContain('tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts')
|
||||
expect(selectPrE2eSpecs(['src/main/ipc/pty.ts'])).not.toContain(
|
||||
'tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts'
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps source-routed sentinels registered to their reliability gates', () => {
|
||||
const routedGateIds = [
|
||||
'terminal-startup.quick-command-pre-bind-recovery',
|
||||
'quick-open.paired-host-path-search',
|
||||
'terminal-session.host-cold-park-stream-continuity',
|
||||
'terminal-provider.ssh-remote-reattach-contract',
|
||||
'terminal-session.remote-pane-layout-retry'
|
||||
]
|
||||
for (const gateId of routedGateIds) {
|
||||
const route = PR_E2E_SOURCE_ROUTES.find((candidate) => candidate.id === gateId)
|
||||
const gate = reliabilityManifest.gates.find((candidate) => candidate.id === gateId)
|
||||
expect(route, gateId).toBeDefined()
|
||||
expect(gate, gateId).toMatchObject({ maturity: 'experimental', protection: 'partial' })
|
||||
for (const spec of route.specs) {
|
||||
expect(gate.testFiles, gateId).toContain(spec)
|
||||
expect(
|
||||
gate.commands.some((command) => command.includes(spec)),
|
||||
gateId
|
||||
).toBe(true)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import process from 'node:process'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
|
||||
const isProductSource = (file) => !/\.test\.tsx?$/.test(file)
|
||||
|
||||
export const PR_E2E_SOURCE_ROUTES = [
|
||||
{
|
||||
id: 'ephemeral-vm-runtime.rollback-readable-sidecar',
|
||||
specs: ['tests/e2e/ephemeral-vm-provisioned-root.spec.ts'],
|
||||
matches: (file) =>
|
||||
/^(?:src\/main\/ephemeral-vm-(?:runtime-(?:service|provisioning-persistence)|failed-start-cleanup)|src\/shared\/(?:ephemeral-vm-runtime-(?:store|feature-store|rollback-projection|runtimes)|ephemeral-vm-recipes|orca-yaml-hook-types))\.ts$/.test(
|
||||
file
|
||||
)
|
||||
},
|
||||
{
|
||||
id: 'ssh-terminal-source',
|
||||
specs: [
|
||||
'tests/e2e/pty-input-write-queue-ssh.spec.ts',
|
||||
'tests/e2e/ssh-cold-activation-restore.spec.ts',
|
||||
'tests/e2e/ssh-docker-reconnect-pane-restore.spec.ts',
|
||||
'tests/e2e/ssh-startup-exec-readiness.spec.ts',
|
||||
'tests/e2e/ssh-terminal-window-wake-stale-grid-repro.spec.ts'
|
||||
],
|
||||
matches: (file) =>
|
||||
isProductSource(file) &&
|
||||
/^(?:src\/main\/ssh\/|src\/main\/providers\/ssh-|src\/main\/ipc\/(?:ssh-|pty)|src\/relay\/|src\/renderer\/src\/components\/terminal-pane\/(?:pty-|ssh-|remote-runtime-|terminal-parked-pty))/.test(
|
||||
file
|
||||
)
|
||||
},
|
||||
{
|
||||
id: 'terminal-input.ime-and-synthetic-forwarding',
|
||||
specs: [
|
||||
'tests/e2e/terminal-cjk-ime-committed-text.spec.ts',
|
||||
'tests/e2e/terminal-hangul-wrap-boundary-bytes.spec.ts',
|
||||
'tests/e2e/terminal-ime-exact-byte.spec.ts',
|
||||
'tests/e2e/terminal-korean-composing-chord-order.spec.ts',
|
||||
'tests/e2e/terminal-korean-endofrow-preedit-cell-span.spec.ts',
|
||||
'tests/e2e/terminal-korean-midline-preedit-occlusion.spec.ts',
|
||||
'tests/e2e/terminal-korean-preedit-visibility.spec.ts'
|
||||
],
|
||||
matches: (file) =>
|
||||
isProductSource(file) &&
|
||||
/^(?:config\/patches\/|src\/renderer\/src\/components\/terminal-pane\/(?:terminal-ime-|use-terminal-pane-lifecycle|xterm-bypass-policy|terminal-option-shortcut-policy))/.test(
|
||||
file
|
||||
)
|
||||
},
|
||||
{
|
||||
id: 'terminal-startup.quick-command-pre-bind-recovery',
|
||||
specs: ['tests/e2e/terminal-quick-command-pre-bind-recovery.spec.ts'],
|
||||
matches: (file) =>
|
||||
isProductSource(file) &&
|
||||
/^(?:src\/renderer\/src\/components\/tab-bar\/TabBarQuickCommandsMenu\.tsx|src\/renderer\/src\/hooks\/use-terminal-quick-command-hosts\.ts|src\/renderer\/src\/components\/terminal-pane\/(?:pty-connection|pty-transport|terminal-pty-pre-spawn-e2e-barrier)\.ts|src\/renderer\/src\/components\/terminal-pane\/pty-connection\/(?:connect-pane-pty|fresh-spawn-start|pane-pty-visibility-bind|pty-input-recovery)\.ts|src\/renderer\/src\/components\/terminal-pane\/(?:TerminalPane|use-terminal-pane-lifecycle)\.tsx?|src\/renderer\/src\/store\/slices\/terminals\.ts)$/.test(
|
||||
file
|
||||
)
|
||||
},
|
||||
{
|
||||
id: 'quick-open.paired-host-path-search',
|
||||
specs: ['tests/e2e/paired-quick-open-large-tree.spec.ts'],
|
||||
matches: (file) =>
|
||||
isProductSource(file) &&
|
||||
/^(?:src\/main\/ipc\/(?:filesystem-(?:list-files|search-file-paths)|rg-availability)\.ts|src\/main\/providers\/(?:filesystem-provider-contract|ssh-filesystem-provider(?:-capabilities)?)\.ts|src\/main\/runtime\/(?:orca-runtime-files|rpc\/methods\/files)\.ts|src\/relay\/(?:fs-handler(?:-install-rg|-list-files|-ripgrep-fallback)?|fs-list-files-fallback-chain)\.ts|src\/renderer\/src\/(?:components\/(?:QuickOpen|quick-open-file-list|quick-open-search)\.tsx?|runtime\/(?:runtime-file-client|runtime-legacy-quick-open-inventory)\.ts)|src\/shared\/(?:quick-open-(?:install-rg|path-search|transport-budget)|ripgrep-process-availability)\.ts)$/.test(
|
||||
file
|
||||
)
|
||||
},
|
||||
{
|
||||
id: 'terminal-session.host-cold-park-stream-continuity',
|
||||
specs: ['tests/e2e/host-parked-pane-remote-viewer.spec.ts'],
|
||||
matches: (file) =>
|
||||
isProductSource(file) &&
|
||||
/^(?:src\/renderer\/src\/components\/terminal-pane\/(?:terminal-hidden-view-parking|terminal-tab-park-candidates|terminal-tab-activation-order|terminal-parked-pty-watcher|terminal-parked-tab-watchers|terminal-parked-watcher-registry)\.ts|src\/renderer\/src\/runtime\/sync-runtime-graph\.ts)$/.test(
|
||||
file
|
||||
)
|
||||
},
|
||||
{
|
||||
id: 'terminal-provider.ssh-remote-reattach-contract',
|
||||
specs: ['tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts'],
|
||||
matches: (file) =>
|
||||
isProductSource(file) &&
|
||||
!file.endsWith('-test-harness.ts') &&
|
||||
/^(?:src\/renderer\/src\/components\/terminal-pane\/remote-runtime-pty-transport(?:-[a-z0-9-]+)?\.ts|src\/renderer\/src\/runtime\/remote-runtime-terminal-multiplexer\.ts)$/.test(
|
||||
file
|
||||
)
|
||||
},
|
||||
{
|
||||
id: 'terminal-session.remote-pane-layout-retry',
|
||||
specs: ['tests/e2e/paired-remote-pane-layout-retry.spec.ts'],
|
||||
matches: (file) =>
|
||||
isProductSource(file) &&
|
||||
/^(?:src\/renderer\/src\/components\/terminal-pane\/(?:remote-pane-layout-push|TerminalPane)\.tsx?|src\/renderer\/src\/lib\/terminal-layout-equality\.ts|src\/renderer\/src\/runtime\/web-session-tabs-sync\.ts|src\/renderer\/src\/store\/slices\/terminals\.ts)$/.test(
|
||||
file
|
||||
)
|
||||
}
|
||||
]
|
||||
|
||||
export function selectPrE2eSpecs(changedPaths, reportRoute = () => undefined) {
|
||||
const specs = new Set(changedPaths.filter((file) => /^tests\/e2e\/.*\.spec\.ts$/.test(file)))
|
||||
for (const route of PR_E2E_SOURCE_ROUTES) {
|
||||
const matchedFiles = changedPaths.filter(route.matches)
|
||||
if (matchedFiles.length === 0) {
|
||||
continue
|
||||
}
|
||||
route.specs.forEach((spec) => specs.add(spec))
|
||||
reportRoute(`[pr-e2e] ${route.id}: ${route.specs.join(', ')}`)
|
||||
}
|
||||
return [...specs].sort((left, right) => left.localeCompare(right))
|
||||
}
|
||||
|
||||
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
||||
let input = ''
|
||||
process.stdin.setEncoding('utf8')
|
||||
for await (const chunk of process.stdin) {
|
||||
input += chunk
|
||||
}
|
||||
const changedPaths = input.split(/\r?\n/).filter(Boolean)
|
||||
const specs = selectPrE2eSpecs(changedPaths, (message) => console.error(message))
|
||||
process.stdout.write(`${JSON.stringify(specs)}\n`)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parse } from 'yaml'
|
||||
|
||||
const workflow = parse(readFileSync('.github/workflows/pr.yml', 'utf8'))
|
||||
const packageJson = JSON.parse(readFileSync('package.json', 'utf8'))
|
||||
|
||||
describe('packaged Windows PTY native capability routing', () => {
|
||||
it('runs the packaged executable immediately after the unpacked app is built', () => {
|
||||
const job = workflow.jobs.package_windows
|
||||
const packageIndex = job.steps.findIndex((step) => step.name === 'Package unpacked app')
|
||||
const smokeIndex = job.steps.findIndex(
|
||||
(step) => step.name === 'Smoke packaged Windows PTY native capability'
|
||||
)
|
||||
const smoke = job.steps[smokeIndex]
|
||||
|
||||
expect(job['runs-on']).toBe('windows-2022')
|
||||
expect(smokeIndex).toBe(packageIndex + 1)
|
||||
expect(smoke.run).toBe(
|
||||
'pnpm run smoke:windows-pty-native-capability -- --exe=dist/win-unpacked/Orca.exe'
|
||||
)
|
||||
expect(smoke.if).toBeUndefined()
|
||||
expect(smoke['continue-on-error']).toBeUndefined()
|
||||
expect(packageJson.scripts['smoke:windows-pty-native-capability']).toBe(
|
||||
'node tests/tools/windows-pty-native-capability-smoke/run.mjs'
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps patched source rebuild, release build, runtime reuse, and aggregate routing intact', () => {
|
||||
const job = workflow.jobs.package_windows
|
||||
const sourceRebuild = job.steps.find(
|
||||
(step) => step.name === 'Rebuild node-pty from patched source'
|
||||
)
|
||||
const build = job.steps.find((step) => step.name === 'Build package inputs')
|
||||
const prepare = job.steps.find((step) => step.name === 'Prepare Electron native runtime')
|
||||
const packageStep = job.steps.find((step) => step.name === 'Package unpacked app')
|
||||
const verify = workflow.jobs.verify.steps.find(
|
||||
(step) => step.name === 'Require successful checks'
|
||||
)
|
||||
|
||||
expect(sourceRebuild.env.npm_config_build_from_source).toBe('true')
|
||||
expect(sourceRebuild.run).toBe('pnpm rebuild node-pty')
|
||||
expect(build.run).toBe('pnpm run build:release:parallel')
|
||||
expect(prepare.run).toBe('node config/scripts/ensure-native-runtime.mjs --runtime=electron')
|
||||
expect(packageStep.env.ORCA_REUSE_PREPARED_NATIVE_RUNTIME).toBe('1')
|
||||
expect(workflow.jobs.verify.needs).toContain('package_windows')
|
||||
expect(verify.env.PACKAGE_WINDOWS).toBe('${{ needs.package_windows.result }}')
|
||||
expect(verify.run).toContain('"$PACKAGE_WINDOWS"')
|
||||
})
|
||||
|
||||
it('keeps the native probe event-based, scoped, and runnable in packaged Node mode', () => {
|
||||
const driver = readFileSync('tests/tools/windows-pty-native-capability-smoke/run.mjs', 'utf8')
|
||||
const probe = readFileSync(
|
||||
'tests/tools/windows-pty-native-capability-smoke/packaged-node-pty-capability-probe.cjs',
|
||||
'utf8'
|
||||
)
|
||||
const source = `${driver}\n${probe}`
|
||||
|
||||
expect(driver).toContain("ELECTRON_RUN_AS_NODE: '1'")
|
||||
expect(source).not.toMatch(/\b(?:sleep|tasklist|taskkill)\b/i)
|
||||
expect(source).not.toContain('maxRetries')
|
||||
expect(source).not.toContain('retryDelay')
|
||||
expect(source).not.toContain("from 'node:child_process'")
|
||||
expect(source).not.toContain("require('node:child_process')")
|
||||
expect(probe).toContain("'System32', 'wscript.exe'")
|
||||
expect(probe).toContain('real-orca-detached-launcher.vbs')
|
||||
expect(probe).not.toMatch(/cmd\.exe|start "" \/b/i)
|
||||
expect(probe).toContain('native.terminateJob(target._pty, target.pid)')
|
||||
})
|
||||
})
|
||||
@@ -115,6 +115,7 @@
|
||||
"test:e2e:source-control-scale": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/source-control-large-file-count.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
|
||||
"win-update-e2e": "node tests/tools/win-update-e2e/run.mjs",
|
||||
"win-crash-survival-e2e": "node tests/tools/win-crash-survival-e2e/run.mjs",
|
||||
"smoke:windows-pty-native-capability": "node tests/tools/windows-pty-native-capability-smoke/run.mjs",
|
||||
"test:e2e:ssh-codex-artifacts-repro": "node config/scripts/run-ssh-codex-artifacts-repro-e2e.mjs",
|
||||
"test:e2e:headful": "pnpm run ensure:electron-runtime && npx playwright test --config tests/playwright.config.ts --project electron-headful",
|
||||
"test:e2e:terminal-ime-native": "node config/scripts/run-terminal-ibus-hangul-e2e.mjs",
|
||||
|
||||
@@ -46,7 +46,10 @@ export function forwardGuestShortcutInput(
|
||||
return true
|
||||
}
|
||||
if (input.isAutoRepeat) {
|
||||
if (action?.type === 'dictationKeyDown' && shouldForwardDictationShortcut?.()) {
|
||||
if (
|
||||
(action?.type === 'dictationKeyDown' && shouldForwardDictationShortcut?.()) ||
|
||||
action?.type === 'deleteCurrentWorkspace'
|
||||
) {
|
||||
event.preventDefault()
|
||||
return true
|
||||
}
|
||||
@@ -176,6 +179,8 @@ export function forwardGuestShortcutInput(
|
||||
renderer.send('ui:toggleQuickCommandsMenu')
|
||||
} else if (action?.type === 'openNewWorkspace') {
|
||||
renderer.send('ui:openNewWorkspace')
|
||||
} else if (action?.type === 'deleteCurrentWorkspace') {
|
||||
renderer.send('ui:deleteCurrentWorkspace')
|
||||
} else if (action?.type === 'openWorkspaceBoard') {
|
||||
renderer.send('ui:openWorkspaceBoard')
|
||||
} else if (action?.type === 'openTasks') {
|
||||
|
||||
@@ -623,6 +623,47 @@ describe('setupGuestShortcutForwarding', () => {
|
||||
expect(rendererSendMock).toHaveBeenCalledWith('ui:toggleQuickCommandsMenu')
|
||||
})
|
||||
|
||||
it('forwards workspace delete shortcuts from focused guest pages', () => {
|
||||
setupGuestShortcutForwarding({
|
||||
browserTabId,
|
||||
guest: makeGuest(),
|
||||
resolveRenderer: () => makeRenderer()
|
||||
})
|
||||
|
||||
const isMac = process.platform === 'darwin'
|
||||
const preventDefault = triggerBeforeInput({
|
||||
code: 'Backspace',
|
||||
key: 'Backspace',
|
||||
meta: isMac,
|
||||
control: !isMac,
|
||||
shift: true
|
||||
})
|
||||
|
||||
expect(preventDefault).toHaveBeenCalledOnce()
|
||||
expect(rendererSendMock).toHaveBeenCalledWith('ui:deleteCurrentWorkspace')
|
||||
})
|
||||
|
||||
it('consumes repeated workspace delete shortcuts from focused guest pages', () => {
|
||||
setupGuestShortcutForwarding({
|
||||
browserTabId,
|
||||
guest: makeGuest(),
|
||||
resolveRenderer: () => makeRenderer()
|
||||
})
|
||||
|
||||
const isMac = process.platform === 'darwin'
|
||||
const preventDefault = triggerBeforeInput({
|
||||
code: 'Backspace',
|
||||
key: 'Backspace',
|
||||
meta: isMac,
|
||||
control: !isMac,
|
||||
shift: true,
|
||||
isAutoRepeat: true
|
||||
})
|
||||
|
||||
expect(preventDefault).toHaveBeenCalledOnce()
|
||||
expect(rendererSendMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('consumes guest zoom shortcuts even when the renderer is unavailable', () => {
|
||||
setupGuestShortcutForwarding({
|
||||
browserTabId,
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as NodeFs from 'node:fs'
|
||||
import type * as NodeOs from 'node:os'
|
||||
import type * as CodexManagedTrustReconciliation from './codex-managed-trust-reconciliation'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
// Follow-up to STA-4823: two more reads on the Codex hook paths acted on
|
||||
// "absent" when the real answer was "could not read". Both were found while
|
||||
// reviewing #15417 and are not covered by it.
|
||||
//
|
||||
// The denial shape here is the MEASURED one: chmod 000 / icacls deny leave
|
||||
// existsSync true and stat succeeding, and fail only the content read
|
||||
// (EACCES -13 on macOS, EPERM -4048 on Windows). No mode fakes existsSync,
|
||||
// because no platform does.
|
||||
|
||||
const denials = vi.hoisted(() => {
|
||||
const state = {
|
||||
paths: new Set<string>(),
|
||||
deny(path: string): void {
|
||||
state.paths.add(path)
|
||||
},
|
||||
reset(): void {
|
||||
state.paths.clear()
|
||||
},
|
||||
check(target: unknown, syscall: string): void {
|
||||
if (typeof target !== 'string' || !state.paths.has(target)) {
|
||||
return
|
||||
}
|
||||
const error: NodeJS.ErrnoException = new Error(
|
||||
`EACCES: permission denied, ${syscall} '${target}'`
|
||||
)
|
||||
error.code = 'EACCES'
|
||||
error.errno = -13
|
||||
error.syscall = syscall
|
||||
error.path = target
|
||||
throw error
|
||||
}
|
||||
}
|
||||
return state
|
||||
})
|
||||
|
||||
vi.mock('node:fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof NodeFs>()
|
||||
const guardRead = (fn: unknown, syscall: string): unknown => {
|
||||
const original = fn as (...args: unknown[]) => unknown
|
||||
const wrapped = (...args: unknown[]): unknown => {
|
||||
denials.check(args[0], syscall)
|
||||
return original(...args)
|
||||
}
|
||||
return Object.assign(wrapped, original)
|
||||
}
|
||||
const patched: Record<string, unknown> = {
|
||||
...actual,
|
||||
readFileSync: guardRead(actual.readFileSync, 'read'),
|
||||
// Why: existsSync and stat stay HEALTHY. That is the whole point — a
|
||||
// permission denial does not hide the file, it only refuses its contents.
|
||||
openSync: Object.assign((...args: unknown[]): unknown => {
|
||||
const flags = args[1]
|
||||
if (flags === undefined || (typeof flags === 'string' && flags.startsWith('r'))) {
|
||||
denials.check(args[0], 'open')
|
||||
}
|
||||
return (actual.openSync as (...a: unknown[]) => unknown)(...args)
|
||||
}, actual.openSync)
|
||||
}
|
||||
return { ...patched, default: patched }
|
||||
})
|
||||
|
||||
const { getPathMock, homedirMock } = vi.hoisted(() => ({
|
||||
getPathMock: vi.fn<(name: string) => string>(),
|
||||
homedirMock: vi.fn<() => string>()
|
||||
}))
|
||||
|
||||
vi.mock('electron', () => ({ app: { getPath: getPathMock } }))
|
||||
vi.mock('node:os', async () => {
|
||||
const actual = await vi.importActual<typeof NodeOs>('node:os')
|
||||
return { ...actual, homedir: homedirMock }
|
||||
})
|
||||
|
||||
const realFs = await vi.importActual<typeof NodeFs>('node:fs')
|
||||
|
||||
let fakeHomeDir: string
|
||||
let userDataDir: string
|
||||
let previousUserDataPath: string | undefined
|
||||
|
||||
beforeEach(() => {
|
||||
denials.reset()
|
||||
fakeHomeDir = realFs.mkdtempSync(join(tmpdir(), 'orca-hooksread-home-'))
|
||||
userDataDir = realFs.mkdtempSync(join(tmpdir(), 'orca-hooksread-data-'))
|
||||
previousUserDataPath = process.env.ORCA_USER_DATA_PATH
|
||||
process.env.ORCA_USER_DATA_PATH = userDataDir
|
||||
homedirMock.mockReturnValue(fakeHomeDir)
|
||||
getPathMock.mockImplementation((name: string) => {
|
||||
if (name === 'userData') {
|
||||
return userDataDir
|
||||
}
|
||||
throw new Error(`unexpected app.getPath(${name})`)
|
||||
})
|
||||
realFs.mkdirSync(join(fakeHomeDir, '.codex'), { recursive: true })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
denials.reset()
|
||||
realFs.rmSync(fakeHomeDir, { recursive: true, force: true })
|
||||
realFs.rmSync(userDataDir, { recursive: true, force: true })
|
||||
if (previousUserDataPath === undefined) {
|
||||
delete process.env.ORCA_USER_DATA_PATH
|
||||
} else {
|
||||
process.env.ORCA_USER_DATA_PATH = previousUserDataPath
|
||||
}
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
describe('an unreadable legacy hooks.json must not clear managed trust or its ledger', () => {
|
||||
it('returns before the removal branch instead of discarding approvals', async () => {
|
||||
const legacyHooksPath = join(fakeHomeDir, '.codex', 'hooks.json')
|
||||
realFs.writeFileSync(legacyHooksPath, JSON.stringify({ hooks: { Stop: [] } }), 'utf-8')
|
||||
|
||||
const removeSpy = vi.fn()
|
||||
vi.resetModules()
|
||||
vi.doMock('./codex-managed-trust-reconciliation', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof CodexManagedTrustReconciliation>()
|
||||
return { ...actual, removeCodexManagedHookTrustEntries: removeSpy }
|
||||
})
|
||||
try {
|
||||
// The removal only fires when a real-home grant is on record — without
|
||||
// this the branch is inert and the test proves nothing either way.
|
||||
const ledger = await import('./codex-trust-grant-ledger')
|
||||
ledger.writeCodexTrustGrantLedgerHome(
|
||||
join(fakeHomeDir, '.codex'),
|
||||
{ entries: { 'seed:1': { trustedHash: 'sha256:seed' } } } as never,
|
||||
ledger.getCodexTrustGrantLedgerPath()
|
||||
)
|
||||
|
||||
const hookService = await import('./hook-service')
|
||||
denials.deny(legacyHooksPath)
|
||||
|
||||
hookService._internals.cleanupLegacySystemManagedHooks()
|
||||
|
||||
// `readHooksJsonWithRaw` catches the denial and reports {raw:null,
|
||||
// config:null} — "could not read". Before the fix that fell into the same
|
||||
// branch as "no hooks configured", which removes the managed trust
|
||||
// entries AND their grant-ledger record. A read that failed is not
|
||||
// permission to discard approvals the user already gave.
|
||||
expect(removeSpy).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
vi.doUnmock('./codex-managed-trust-reconciliation')
|
||||
vi.resetModules()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -601,6 +601,13 @@ function cleanupLegacySystemManagedHooks(): void {
|
||||
// Why: the pre-write guard below compares against these bytes; a separate
|
||||
// later read would let a concurrent save land between parse and snapshot.
|
||||
const { raw: previousRaw, config } = readHooksJsonWithRaw(legacyConfigPath)
|
||||
// Why: `config === null` with no raw is the "could not read" answer, not the
|
||||
// "no hooks here" one — the branch below removes managed trust entries AND
|
||||
// their grant-ledger record, so acting on it would discard approvals over a
|
||||
// read that merely failed. A genuine absence still returns `config: {}`.
|
||||
if (config === null && previousRaw === null) {
|
||||
return
|
||||
}
|
||||
if (!config?.hooks || previousRaw === null) {
|
||||
if (hasRecordedRealHomeGrant) {
|
||||
removeSystemManagedHookTrustEntries(systemHomePath, legacyConfigPath)
|
||||
@@ -1637,6 +1644,7 @@ export class CodexHookService {
|
||||
export const codexHookService = new CodexHookService()
|
||||
|
||||
export const _internals = {
|
||||
cleanupLegacySystemManagedHooks,
|
||||
getManagedScript,
|
||||
installManagedHooksIntoWslRuntime,
|
||||
refreshWslRuntimeUserHooks,
|
||||
|
||||
@@ -132,6 +132,16 @@ function makeStore(repos: Repo[] = [REPO], allMeta: Record<string, WorktreeMeta>
|
||||
} as unknown as Store
|
||||
}
|
||||
|
||||
/** `repo-1::/repo-old` is in the shared fixture map, so pinning it needs a getWorktreeMeta override. */
|
||||
function makePinnedStore(): Store {
|
||||
const pinned = makeWorktreeMeta({ isPinned: true, lastActivityAt: NOW - 40 * DAY_MS })
|
||||
return {
|
||||
...makeStore(),
|
||||
getWorktreeMeta: (worktreeId: string) =>
|
||||
worktreeId === 'repo-1::/repo-old' ? pinned : META_BY_WORKTREE_ID[worktreeId]
|
||||
} as Store
|
||||
}
|
||||
|
||||
describe('workspace cleanup broad scan opt-in', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
@@ -230,6 +240,34 @@ describe('workspace cleanup broad scan opt-in', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('skips git for a pinned workspace on a broad scan, which is the cost saving', async () => {
|
||||
const store = makePinnedStore()
|
||||
|
||||
await scanWorkspaceCleanup(store, { includeAllWorkspaces: true })
|
||||
|
||||
expect(getStatusMock).not.toHaveBeenCalledWith(
|
||||
expect.stringContaining('/repo-old'),
|
||||
expect.anything()
|
||||
)
|
||||
})
|
||||
|
||||
it('reads git for a pinned workspace on a targeted preflight, which decides force-removal', async () => {
|
||||
// Why this matters: `pinned` is not a queue blocker, so a pinned idle workspace is
|
||||
// hand-selectable today, and removal forces whenever git is unknown. Skipping the
|
||||
// forced read meant it could be force-deleted with no evidence ever obtained.
|
||||
const worktreeId = 'repo-1::/repo-old'
|
||||
|
||||
const result = await scanWorkspaceCleanup(makePinnedStore(), { worktreeIds: [worktreeId] })
|
||||
|
||||
expect(getStatusMock).toHaveBeenCalledWith(
|
||||
expect.stringContaining('/repo-old'),
|
||||
expect.anything()
|
||||
)
|
||||
const pinned = result.candidates.find((candidate) => candidate.worktreeId === worktreeId)
|
||||
expect(pinned?.blockers).toContain('pinned')
|
||||
expect(pinned?.git.checkedAt).not.toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the legacy suggestion-only projection when the flag is absent', async () => {
|
||||
const result = await scanWorkspaceCleanup(makeStore())
|
||||
|
||||
|
||||
@@ -192,11 +192,16 @@ function shouldReadWorkspaceCleanupGitEvidence(args: {
|
||||
if ((skipGit && !forceGitCheck) || repoIsFolder || worktree.isMainWorktree) {
|
||||
return false
|
||||
}
|
||||
if (
|
||||
blockers.includes('pinned') ||
|
||||
blockers.includes('main-worktree') ||
|
||||
blockers.includes('folder-repo')
|
||||
) {
|
||||
// Why pinned sits with the cost skips and not the refusals: a pinned workspace is
|
||||
// still queueable (`pinned` is not a queue blocker), so it can reach removal -- and
|
||||
// removal forces whenever git is unknown. Skipping its git read on a broad scan is a
|
||||
// fair saving; skipping it on the confirm-time forced read meant deleting with no
|
||||
// evidence ever obtained. main-worktree and folder-repo stay unconditional: those are
|
||||
// refused before removal, so reading git for them is pure cost.
|
||||
if (blockers.includes('pinned') && !forceGitCheck) {
|
||||
return false
|
||||
}
|
||||
if (blockers.includes('main-worktree') || blockers.includes('folder-repo')) {
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { TuiAgent } from '../../shared/tui-agent'
|
||||
import { OrcaRuntimeService } from './orca-runtime'
|
||||
import { makeStore } from './runtime-rpc-worktree-store-fixtures'
|
||||
|
||||
export const AGENT_PROMPT_TEST_WORKTREE_PATH = '/tmp/worktree-a'
|
||||
export const AGENT_PROMPT_TEST_WORKTREE_ID = 'repo-1::/tmp/worktree-a'
|
||||
|
||||
export async function createAgentPromptSubmissionRuntime(
|
||||
onWrite: (runtime: OrcaRuntimeService, data: string, writeIndex: number) => void,
|
||||
launchAgent: TuiAgent = 'aider'
|
||||
): Promise<{ runtime: OrcaRuntimeService; handle: string; writes: string[] }> {
|
||||
const runtime = new OrcaRuntimeService(makeStore() as never)
|
||||
const writes: string[] = []
|
||||
runtime.setPtyController({
|
||||
spawn: async () => ({ id: 'pty-prompt' }),
|
||||
write: (_ptyId, data) => {
|
||||
writes.push(data)
|
||||
onWrite(runtime, data, writes.length)
|
||||
return true
|
||||
},
|
||||
kill: () => true,
|
||||
getForegroundProcess: async () => null
|
||||
})
|
||||
const terminal = await runtime.createTerminal(`path:${AGENT_PROMPT_TEST_WORKTREE_PATH}`, {
|
||||
launchAgent
|
||||
})
|
||||
return { runtime, handle: terminal.handle, writes }
|
||||
}
|
||||
@@ -3,10 +3,14 @@ import {
|
||||
AGENT_PROMPT_BRACKETED_PASTE_END,
|
||||
AGENT_PROMPT_SUBMIT_DELAY_MS
|
||||
} from '../../shared/agent-prompt-injection'
|
||||
import {
|
||||
AGENT_PROMPT_TEST_WORKTREE_PATH,
|
||||
createAgentPromptSubmissionRuntime
|
||||
} from './agent-prompt-submission-runtime-test-fixture'
|
||||
import { OrcaRuntimeService } from './orca-runtime'
|
||||
import { makeStore } from './runtime-rpc-worktree-store-fixtures'
|
||||
|
||||
const WORKTREE_PATH = '/tmp/worktree-a'
|
||||
const createPromptRuntime = createAgentPromptSubmissionRuntime
|
||||
|
||||
vi.mock('../git/worktree', () => ({
|
||||
listWorktrees: vi.fn().mockResolvedValue([
|
||||
@@ -29,37 +33,18 @@ vi.mock('../git/worktree', () => ({
|
||||
])
|
||||
}))
|
||||
|
||||
async function createPromptRuntime(
|
||||
onWrite: (runtime: OrcaRuntimeService, data: string, writeIndex: number) => void
|
||||
): Promise<{ runtime: OrcaRuntimeService; handle: string; writes: string[] }> {
|
||||
const runtime = new OrcaRuntimeService(makeStore() as never)
|
||||
const writes: string[] = []
|
||||
runtime.setPtyController({
|
||||
spawn: vi.fn().mockResolvedValue({ id: 'pty-prompt' }),
|
||||
write: (_ptyId, data) => {
|
||||
writes.push(data)
|
||||
onWrite(runtime, data, writes.length)
|
||||
return true
|
||||
},
|
||||
kill: () => true,
|
||||
getForegroundProcess: async () => null
|
||||
})
|
||||
const terminal = await runtime.createTerminal(`path:${WORKTREE_PATH}`, {
|
||||
launchAgent: 'aider'
|
||||
})
|
||||
return { runtime, handle: terminal.handle, writes }
|
||||
}
|
||||
|
||||
describe('agent prompt submission runtime', () => {
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
it('submits exactly once after an observed lifecycle transition', async () => {
|
||||
vi.useFakeTimers()
|
||||
const { runtime, handle, writes } = await createPromptRuntime((runtime, data) => {
|
||||
if (data === '\r') {
|
||||
runtime.onPtyData('pty-prompt', '\x1b]0;Codex working\x07', Date.now())
|
||||
const { runtime, handle, writes } = await createAgentPromptSubmissionRuntime(
|
||||
(runtime, data) => {
|
||||
if (data === '\r') {
|
||||
runtime.onPtyData('pty-prompt', '\x1b]0;Codex working\x07', Date.now())
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
const submission = runtime.sendTerminalAgentPrompt(handle, 'review this')
|
||||
await vi.runAllTimersAsync()
|
||||
@@ -374,8 +359,11 @@ describe('agent prompt submission runtime', () => {
|
||||
kill: () => true,
|
||||
getForegroundProcess: async () => null
|
||||
})
|
||||
handle = (await runtime.createTerminal(`path:${WORKTREE_PATH}`, { launchAgent: 'aider' }))
|
||||
.handle
|
||||
handle = (
|
||||
await runtime.createTerminal(`path:${AGENT_PROMPT_TEST_WORKTREE_PATH}`, {
|
||||
launchAgent: 'aider'
|
||||
})
|
||||
).handle
|
||||
runtime.onPtyData(
|
||||
'pty-prompt',
|
||||
'Permission required\nAllow once\nAllow always\nReject\n' +
|
||||
|
||||
@@ -10,13 +10,62 @@ const WORKTREE_ID = `${REPO_ID}::${WORKTREE_PATH}`
|
||||
const TAB_ID = 'tab-close-continuity'
|
||||
const LEAF_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const SIBLING_LEAF_ID = '33333333-3333-4333-8333-333333333333'
|
||||
const CANARY_TAB_ID = 'tab-close-continuity-canary'
|
||||
const CANARY_LEAF_ID = '55555555-5555-4555-8555-555555555555'
|
||||
const PTY_ID = 'pty-close-continuity'
|
||||
const RUNTIME_OWNED_PTY_ID = 'serve-close-continuity'
|
||||
const SIBLING_PTY_ID = 'pty-close-continuity-sibling'
|
||||
const CANARY_PTY_ID = 'pty-close-continuity-canary'
|
||||
const INCARNATION_ID = '22222222-2222-4222-8222-222222222222'
|
||||
const SIBLING_INCARNATION_ID = '44444444-4444-4444-8444-444444444444'
|
||||
const CANARY_INCARNATION_ID = '66666666-6666-4666-8666-666666666666'
|
||||
const canarySessionTab = {
|
||||
id: CANARY_TAB_ID,
|
||||
ptyId: CANARY_PTY_ID,
|
||||
worktreeId: WORKTREE_ID,
|
||||
title: 'Canary shell',
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 1,
|
||||
createdAt: 2
|
||||
}
|
||||
const canarySessionLayout = {
|
||||
root: { type: 'leaf' as const, leafId: CANARY_LEAF_ID },
|
||||
activeLeafId: CANARY_LEAF_ID,
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { [CANARY_LEAF_ID]: CANARY_PTY_ID }
|
||||
}
|
||||
const canarySyncedTab = {
|
||||
tabId: CANARY_TAB_ID,
|
||||
worktreeId: WORKTREE_ID,
|
||||
title: 'Canary shell',
|
||||
activeLeafId: CANARY_LEAF_ID,
|
||||
layout: { type: 'leaf' as const, leafId: CANARY_LEAF_ID }
|
||||
}
|
||||
const canarySyncedLeaf = {
|
||||
tabId: CANARY_TAB_ID,
|
||||
worktreeId: WORKTREE_ID,
|
||||
leafId: CANARY_LEAF_ID,
|
||||
paneRuntimeId: 9,
|
||||
ptyId: CANARY_PTY_ID
|
||||
}
|
||||
const canaryMobileTab = {
|
||||
type: 'terminal' as const,
|
||||
id: `${CANARY_TAB_ID}::${CANARY_LEAF_ID}`,
|
||||
parentTabId: CANARY_TAB_ID,
|
||||
leafId: CANARY_LEAF_ID,
|
||||
ptyId: CANARY_PTY_ID,
|
||||
title: 'Canary shell',
|
||||
isActive: false
|
||||
}
|
||||
const canaryProcess = {
|
||||
id: CANARY_PTY_ID,
|
||||
incarnationId: CANARY_INCARNATION_ID,
|
||||
cwd: WORKTREE_PATH,
|
||||
title: 'Canary shell'
|
||||
}
|
||||
|
||||
function makeSession(ptyId = PTY_ID): WorkspaceSessionState {
|
||||
function makeSession(ptyId = PTY_ID, includeCanary = false): WorkspaceSessionState {
|
||||
return {
|
||||
...getDefaultWorkspaceSession(),
|
||||
tabsByWorktree: {
|
||||
@@ -30,7 +79,8 @@ function makeSession(ptyId = PTY_ID): WorkspaceSessionState {
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
}
|
||||
},
|
||||
...(includeCanary ? [canarySessionTab] : [])
|
||||
]
|
||||
},
|
||||
terminalLayoutsByTabId: {
|
||||
@@ -39,10 +89,14 @@ function makeSession(ptyId = PTY_ID): WorkspaceSessionState {
|
||||
activeLeafId: LEAF_ID,
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { [LEAF_ID]: ptyId }
|
||||
}
|
||||
},
|
||||
...(includeCanary ? { [CANARY_TAB_ID]: canarySessionLayout } : {})
|
||||
},
|
||||
terminalPtyIncarnationsByPaneKey: {
|
||||
[makePaneKey(TAB_ID, LEAF_ID)]: INCARNATION_ID
|
||||
[makePaneKey(TAB_ID, LEAF_ID)]: INCARNATION_ID,
|
||||
...(includeCanary
|
||||
? { [makePaneKey(CANARY_TAB_ID, CANARY_LEAF_ID)]: CANARY_INCARNATION_ID }
|
||||
: {})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,13 +110,19 @@ function makeDeferred() {
|
||||
}
|
||||
|
||||
function createHarness(
|
||||
options: { ptyId?: string; publishMobileSurface?: boolean; registerPtyBacked?: boolean } = {}
|
||||
options: {
|
||||
ptyId?: string
|
||||
publishMobileSurface?: boolean
|
||||
registerPtyBacked?: boolean
|
||||
includeCanary?: boolean
|
||||
} = {}
|
||||
) {
|
||||
const ptyId = options.ptyId ?? PTY_ID
|
||||
let session = makeSession(ptyId)
|
||||
let session = makeSession(ptyId, options.includeCanary)
|
||||
let sessionAvailable = true
|
||||
let incarnationId = INCARNATION_ID
|
||||
let includeSiblingPty = false
|
||||
let victimPtyListed = true
|
||||
const repo = {
|
||||
id: REPO_ID,
|
||||
path: WORKTREE_PATH,
|
||||
@@ -80,29 +140,40 @@ function createHarness(
|
||||
getWorkspaceSession: () => (sessionAvailable ? session : undefined),
|
||||
setWorkspaceSession: (next: WorkspaceSessionState) => {
|
||||
session = next
|
||||
}
|
||||
},
|
||||
flushOrThrow: () => {}
|
||||
}
|
||||
const acknowledged = makeDeferred()
|
||||
let closeTerminalTabError: Error | null = null
|
||||
let closeTerminalTabAction: (() => void | Promise<void>) | null = null
|
||||
const closeTerminal = vi.fn()
|
||||
const closeTerminalTab = vi.fn(() =>
|
||||
closeTerminalTabError ? Promise.reject(closeTerminalTabError) : acknowledged.promise
|
||||
)
|
||||
const closeTerminalTab = vi.fn(() => {
|
||||
if (closeTerminalTabError) {
|
||||
return Promise.reject(closeTerminalTabError)
|
||||
}
|
||||
return closeTerminalTabAction ? Promise.resolve(closeTerminalTabAction()) : acknowledged.promise
|
||||
})
|
||||
const kill = vi.fn(() => true)
|
||||
let verifiedStopResult: boolean | Error = false
|
||||
const stopAndWait = vi.fn(async () => {
|
||||
let stopAndWaitAction: ((stoppingPtyId: string) => void | Promise<void>) | null = null
|
||||
const stopAndWait = vi.fn(async (stoppingPtyId: string) => {
|
||||
await stopAndWaitAction?.(stoppingPtyId)
|
||||
if (verifiedStopResult instanceof Error) {
|
||||
throw verifiedStopResult
|
||||
}
|
||||
return verifiedStopResult
|
||||
})
|
||||
const listProcesses = vi.fn(async () => [
|
||||
{
|
||||
id: ptyId,
|
||||
incarnationId,
|
||||
cwd: WORKTREE_PATH,
|
||||
title: 'Fixture shell'
|
||||
},
|
||||
...(victimPtyListed
|
||||
? [
|
||||
{
|
||||
id: ptyId,
|
||||
incarnationId,
|
||||
cwd: WORKTREE_PATH,
|
||||
title: 'Fixture shell'
|
||||
}
|
||||
]
|
||||
: []),
|
||||
...(includeSiblingPty
|
||||
? [
|
||||
{
|
||||
@@ -112,7 +183,8 @@ function createHarness(
|
||||
title: 'Fixture sibling shell'
|
||||
}
|
||||
]
|
||||
: [])
|
||||
: []),
|
||||
...(options.includeCanary ? [canaryProcess] : [])
|
||||
])
|
||||
const runtime = new OrcaRuntimeService(store as never)
|
||||
runtime.setNotifier({ closeTerminal, closeTerminalTab } as never)
|
||||
@@ -134,7 +206,8 @@ function createHarness(
|
||||
title: 'Fixture shell',
|
||||
activeLeafId: LEAF_ID,
|
||||
layout: { type: 'leaf', leafId: LEAF_ID }
|
||||
}
|
||||
},
|
||||
...(options.includeCanary ? [canarySyncedTab] : [])
|
||||
],
|
||||
leaves: [
|
||||
{
|
||||
@@ -143,7 +216,8 @@ function createHarness(
|
||||
leafId: LEAF_ID,
|
||||
paneRuntimeId: 7,
|
||||
ptyId
|
||||
}
|
||||
},
|
||||
...(options.includeCanary ? [canarySyncedLeaf] : [])
|
||||
],
|
||||
...(options.publishMobileSurface
|
||||
? {
|
||||
@@ -164,13 +238,34 @@ function createHarness(
|
||||
ptyId,
|
||||
title: 'Fixture shell',
|
||||
isActive: true
|
||||
}
|
||||
},
|
||||
...(options.includeCanary ? [canaryMobileTab] : [])
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
: {})
|
||||
})
|
||||
const syncCanaryGraph = () =>
|
||||
runtime.syncWindowGraph(1, {
|
||||
tabs: [canarySyncedTab],
|
||||
leaves: [canarySyncedLeaf],
|
||||
...(options.publishMobileSurface
|
||||
? {
|
||||
mobileSessionTabs: [
|
||||
{
|
||||
worktree: WORKTREE_ID,
|
||||
publicationEpoch: 'renderer:close-continuity',
|
||||
snapshotVersion: 2,
|
||||
activeGroupId: null,
|
||||
activeTabId: `${CANARY_TAB_ID}::${CANARY_LEAF_ID}`,
|
||||
activeTabType: 'terminal' as const,
|
||||
tabs: [{ ...canaryMobileTab, isActive: true }]
|
||||
}
|
||||
]
|
||||
}
|
||||
: {})
|
||||
})
|
||||
const syncEmptyGraph = () => runtime.syncWindowGraph(1, { tabs: [], leaves: [] })
|
||||
const syncFixtureTabWithoutLeaf = () =>
|
||||
runtime.syncWindowGraph(1, {
|
||||
@@ -181,9 +276,10 @@ function createHarness(
|
||||
title: 'Fixture shell',
|
||||
activeLeafId: LEAF_ID,
|
||||
layout: { type: 'leaf', leafId: LEAF_ID }
|
||||
}
|
||||
},
|
||||
...(options.includeCanary ? [canarySyncedTab] : [])
|
||||
],
|
||||
leaves: []
|
||||
leaves: options.includeCanary ? [canarySyncedLeaf] : []
|
||||
})
|
||||
const syncSplitFixtureGraph = () => {
|
||||
includeSiblingPty = true
|
||||
@@ -245,6 +341,13 @@ function createHarness(
|
||||
leafId: LEAF_ID,
|
||||
incarnationId: INCARNATION_ID
|
||||
})
|
||||
if (options.includeCanary) {
|
||||
runtime.registerPty(CANARY_PTY_ID, WORKTREE_ID, null, {
|
||||
tabId: CANARY_TAB_ID,
|
||||
leafId: CANARY_LEAF_ID,
|
||||
incarnationId: CANARY_INCARNATION_ID
|
||||
})
|
||||
}
|
||||
}
|
||||
syncFixtureGraph()
|
||||
return {
|
||||
@@ -254,6 +357,7 @@ function createHarness(
|
||||
closeTerminalTab,
|
||||
kill,
|
||||
stopAndWait,
|
||||
syncCanaryGraph,
|
||||
syncEmptyGraph,
|
||||
syncFixtureGraph,
|
||||
syncFixtureTabWithoutLeaf,
|
||||
@@ -262,20 +366,41 @@ function createHarness(
|
||||
makeSessionUnavailable: () => {
|
||||
sessionAvailable = false
|
||||
},
|
||||
removeVictimFromInventory: () => {
|
||||
victimPtyListed = false
|
||||
},
|
||||
retirePersistedTab: () => {
|
||||
const victimPaneKey = makePaneKey(TAB_ID, LEAF_ID)
|
||||
session = {
|
||||
...session,
|
||||
tabsByWorktree: { ...session.tabsByWorktree, [WORKTREE_ID]: [] },
|
||||
terminalLayoutsByTabId: {},
|
||||
terminalPtyIncarnationsByPaneKey: {}
|
||||
tabsByWorktree: {
|
||||
...session.tabsByWorktree,
|
||||
[WORKTREE_ID]: (session.tabsByWorktree[WORKTREE_ID] ?? []).filter(
|
||||
(tab) => tab.id !== TAB_ID
|
||||
)
|
||||
},
|
||||
terminalLayoutsByTabId: Object.fromEntries(
|
||||
Object.entries(session.terminalLayoutsByTabId).filter(([tabId]) => tabId !== TAB_ID)
|
||||
),
|
||||
terminalPtyIncarnationsByPaneKey: Object.fromEntries(
|
||||
Object.entries(session.terminalPtyIncarnationsByPaneKey ?? {}).filter(
|
||||
([paneKey]) => paneKey !== victimPaneKey
|
||||
)
|
||||
)
|
||||
}
|
||||
},
|
||||
setCloseTerminalTabAction: (action: () => void | Promise<void>) => {
|
||||
closeTerminalTabAction = action
|
||||
},
|
||||
rejectTerminalTabClose: (error: Error) => {
|
||||
closeTerminalTabError = error
|
||||
},
|
||||
setVerifiedStopResult: (result: boolean | Error) => {
|
||||
verifiedStopResult = result
|
||||
},
|
||||
setStopAndWaitAction: (action: (stoppingPtyId: string) => void | Promise<void>) => {
|
||||
stopAndWaitAction = action
|
||||
},
|
||||
replaceIncarnation: (next: string) => {
|
||||
incarnationId = next
|
||||
}
|
||||
@@ -317,6 +442,79 @@ describe('terminal close and handle incarnation continuity', () => {
|
||||
expect(harness.getSession().tabsByWorktree[WORKTREE_ID]).toEqual([])
|
||||
})
|
||||
|
||||
it('fences final-pane exit ordering until exact retirement commits', async () => {
|
||||
const harness = createHarness({
|
||||
includeCanary: true,
|
||||
publishMobileSurface: true,
|
||||
registerPtyBacked: true
|
||||
})
|
||||
harness.syncFixtureTabWithoutLeaf()
|
||||
const closeMobileSessionTab = vi.spyOn(harness.runtime, 'closeMobileSessionTab')
|
||||
const order: string[] = []
|
||||
harness.setCloseTerminalTabAction(() => {
|
||||
order.push('session-retirement')
|
||||
harness.retirePersistedTab()
|
||||
harness.syncCanaryGraph()
|
||||
order.push('committed-graph-removal')
|
||||
})
|
||||
harness.setVerifiedStopResult(true)
|
||||
harness.setStopAndWaitAction((stoppingPtyId) => {
|
||||
order.push('pty-stop')
|
||||
harness.removeVictimFromInventory()
|
||||
harness.syncCanaryGraph()
|
||||
order.push('idempotent-graph-removal')
|
||||
harness.runtime.onPtyExit(stoppingPtyId, 0, INCARNATION_ID)
|
||||
order.push('idempotent-session-retirement')
|
||||
})
|
||||
const terminals = (await harness.runtime.listTerminals(`id:${WORKTREE_ID}`)).terminals
|
||||
const victim = terminals.find((terminal) => terminal.ptyId === PTY_ID)!
|
||||
const canary = terminals.find((terminal) => terminal.ptyId === CANARY_PTY_ID)!
|
||||
|
||||
await expect(harness.runtime.closeTerminal(victim.handle)).resolves.toMatchObject({
|
||||
handle: victim.handle,
|
||||
tabId: TAB_ID,
|
||||
ptyKilled: true
|
||||
})
|
||||
|
||||
expect(order).toEqual([
|
||||
'session-retirement',
|
||||
'committed-graph-removal',
|
||||
'pty-stop',
|
||||
'idempotent-graph-removal',
|
||||
'idempotent-session-retirement'
|
||||
])
|
||||
expect(harness.stopAndWait).toHaveBeenCalledTimes(1)
|
||||
expect(harness.stopAndWait).toHaveBeenCalledWith(PTY_ID, {
|
||||
deadlineMs: expect.any(Number)
|
||||
})
|
||||
expect(harness.kill).not.toHaveBeenCalled()
|
||||
expect(closeMobileSessionTab).toHaveBeenCalledTimes(1)
|
||||
expect(closeMobileSessionTab).toHaveBeenCalledWith(`id:${WORKTREE_ID}`, TAB_ID, {
|
||||
localPtyTeardownOwnedExternally: true
|
||||
})
|
||||
expect(harness.closeTerminalTab).toHaveBeenCalledTimes(1)
|
||||
expect(harness.getSession().tabsByWorktree[WORKTREE_ID]).toEqual([
|
||||
expect.objectContaining({ id: CANARY_TAB_ID, ptyId: CANARY_PTY_ID })
|
||||
])
|
||||
expect(harness.getSession().terminalLayoutsByTabId).toEqual({
|
||||
[CANARY_TAB_ID]: expect.objectContaining({
|
||||
ptyIdsByLeafId: { [CANARY_LEAF_ID]: CANARY_PTY_ID }
|
||||
})
|
||||
})
|
||||
expect(harness.getSession().terminalPtyIncarnationsByPaneKey).toEqual({
|
||||
[makePaneKey(CANARY_TAB_ID, CANARY_LEAF_ID)]: CANARY_INCARNATION_ID
|
||||
})
|
||||
const survivors = (await harness.runtime.listTerminals(`id:${WORKTREE_ID}`)).terminals
|
||||
expect(survivors).toHaveLength(1)
|
||||
const [survivor] = survivors
|
||||
expect(survivor).toMatchObject({ ptyId: CANARY_PTY_ID })
|
||||
await expect(harness.runtime.readTerminal(survivor.handle)).resolves.toMatchObject({
|
||||
handle: survivor.handle,
|
||||
status: 'running'
|
||||
})
|
||||
expect(canary.ptyId).toBe(survivor.ptyId)
|
||||
})
|
||||
|
||||
it('does not kill the final PTY when durable tab retirement is rejected', async () => {
|
||||
const harness = createHarness()
|
||||
const [{ handle }] = (await harness.runtime.listTerminals(`id:${WORKTREE_ID}`)).terminals
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { AGENT_PROMPT_BRACKETED_PASTE_END } from '../../../../shared/agent-prompt-injection'
|
||||
import { ORCHESTRATION_CONTRACT_VERSION } from '../../../../shared/protocol-version'
|
||||
import {
|
||||
AGENT_PROMPT_TEST_WORKTREE_ID,
|
||||
createAgentPromptSubmissionRuntime
|
||||
} from '../../agent-prompt-submission-runtime-test-fixture'
|
||||
import { OrchestrationDb } from '../../orchestration/db'
|
||||
import type { RpcRequest } from '../core'
|
||||
import { RpcDispatcher } from '../dispatcher'
|
||||
import { ORCHESTRATION_METHODS } from './orchestration'
|
||||
|
||||
vi.mock('../../../git/worktree', () => ({
|
||||
listWorktrees: vi.fn().mockResolvedValue([
|
||||
{
|
||||
path: '/tmp/worktree-a',
|
||||
head: 'abc',
|
||||
branch: 'feature/prompt-contract',
|
||||
isBare: false,
|
||||
isMainWorktree: false
|
||||
}
|
||||
]),
|
||||
listWorktreesStrict: vi.fn().mockResolvedValue([
|
||||
{
|
||||
path: '/tmp/worktree-a',
|
||||
head: 'abc',
|
||||
branch: 'feature/prompt-contract',
|
||||
isBare: false,
|
||||
isMainWorktree: false
|
||||
}
|
||||
])
|
||||
}))
|
||||
|
||||
const COORDINATOR_PANE_KEY = 'tab_coord:aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'
|
||||
const WORKER_PANE_KEY = 'tab_worker:bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'
|
||||
const REQUEST_ID = 'worker_start_prompt_contract'
|
||||
const openDatabases: OrchestrationDb[] = []
|
||||
const temporaryRoots: string[] = []
|
||||
|
||||
type PromptContractHarness = {
|
||||
db: OrchestrationDb
|
||||
dbPath: string
|
||||
dispatcher: RpcDispatcher
|
||||
request: RpcRequest
|
||||
requestId: string
|
||||
taskId: string
|
||||
submittedTurns: () => number
|
||||
startedTurns: () => number
|
||||
prematureSubmits: () => number
|
||||
writes: string[]
|
||||
}
|
||||
|
||||
async function createPromptContractHarness(
|
||||
outcome: 'accepted' | 'swallowed'
|
||||
): Promise<PromptContractHarness> {
|
||||
let composerReady = false
|
||||
let submittedTurns = 0
|
||||
let startedTurns = 0
|
||||
let prematureSubmits = 0
|
||||
const fixture = await createAgentPromptSubmissionRuntime((runtime, data) => {
|
||||
if (data.includes(AGENT_PROMPT_BRACKETED_PASTE_END)) {
|
||||
setTimeout(() => runtime.onPtyData('pty-prompt', 'partial composer frame', Date.now()), 650)
|
||||
setTimeout(() => runtime.onPtyData('pty-prompt', '\x1b[?25h', Date.now()), 750)
|
||||
setTimeout(() => {
|
||||
composerReady = true
|
||||
runtime.onPtyData('pty-prompt', 'final composer frame', Date.now())
|
||||
}, 1_000)
|
||||
return
|
||||
}
|
||||
if (data !== '\r') {
|
||||
return
|
||||
}
|
||||
submittedTurns += 1
|
||||
if (!composerReady) {
|
||||
prematureSubmits += 1
|
||||
}
|
||||
if (outcome === 'accepted') {
|
||||
startedTurns += 1
|
||||
runtime.onPtyData('pty-prompt', '\x1b]0;Codex working\x07', Date.now())
|
||||
}
|
||||
}, 'codex')
|
||||
const { runtime, handle } = fixture
|
||||
runtime.onPtyData('pty-prompt', '\x1b]0;Codex idle\x07', Date.now())
|
||||
|
||||
const temporaryRoot = mkdtempSync(join(tmpdir(), 'orca-worker-prompt-contract-'))
|
||||
temporaryRoots.push(temporaryRoot)
|
||||
const dbPath = join(temporaryRoot, 'orchestration.db')
|
||||
const db = new OrchestrationDb(dbPath)
|
||||
openDatabases.push(db)
|
||||
runtime.setOrchestrationDb(db)
|
||||
const run = db.createRun({
|
||||
objective: 'Worker prompt contract',
|
||||
coordinatorHandle: 'term_coord',
|
||||
coordinatorPaneKey: COORDINATOR_PANE_KEY
|
||||
})
|
||||
const task = db.createTask({ spec: 'start exactly one worker turn', runId: run.id })
|
||||
vi.spyOn(runtime, 'getTerminalPaneKey').mockImplementation((candidate) =>
|
||||
candidate === 'term_coord'
|
||||
? COORDINATOR_PANE_KEY
|
||||
: candidate === handle
|
||||
? WORKER_PANE_KEY
|
||||
: null
|
||||
)
|
||||
vi.spyOn(runtime, 'getTerminalProcessIncarnation').mockImplementation((candidate) =>
|
||||
candidate === handle ? `runtime_test:${handle}:1` : null
|
||||
)
|
||||
vi.spyOn(runtime, 'validateOrchestrationAgentLauncher').mockImplementation(() => {})
|
||||
vi.spyOn(runtime, 'showTerminal').mockResolvedValue({
|
||||
handle: 'term_coord',
|
||||
worktreeId: 'repo::parent',
|
||||
status: 'running'
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'showManagedWorktree').mockResolvedValue({
|
||||
id: 'repo::parent',
|
||||
repoId: 'repo-1'
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'showRepo').mockResolvedValue({ id: 'repo-1', kind: 'git' } as never)
|
||||
vi.spyOn(runtime, 'createManagedWorktree').mockResolvedValue({
|
||||
worktree: { id: AGENT_PROMPT_TEST_WORKTREE_ID, repoId: 'repo-1' },
|
||||
startupTerminal: { spawned: true, handle },
|
||||
setupReceipt: {
|
||||
requested: 'run',
|
||||
hookFound: false,
|
||||
startupPolicy: 'start-immediately',
|
||||
state: 'not_configured'
|
||||
}
|
||||
} as never)
|
||||
vi.spyOn(runtime, 'getTerminalOrchestrationCliCommand').mockReturnValue('orca')
|
||||
|
||||
return {
|
||||
db,
|
||||
dbPath,
|
||||
dispatcher: new RpcDispatcher({ runtime, methods: ORCHESTRATION_METHODS }),
|
||||
request: {
|
||||
id: `rpc_${outcome}`,
|
||||
authToken: 'caller-token',
|
||||
orchestrationContractVersion: ORCHESTRATION_CONTRACT_VERSION,
|
||||
orchestrationRequestId: `${REQUEST_ID}_${outcome}`,
|
||||
method: 'orchestration.workerStart',
|
||||
params: {
|
||||
task: task.id,
|
||||
from: 'term_coord',
|
||||
worktree: 'new-child',
|
||||
name: `prompt-contract-${outcome}`,
|
||||
agent: 'codex'
|
||||
}
|
||||
},
|
||||
requestId: `${REQUEST_ID}_${outcome}`,
|
||||
taskId: task.id,
|
||||
submittedTurns: () => submittedTurns,
|
||||
startedTurns: () => startedTurns,
|
||||
prematureSubmits: () => prematureSubmits,
|
||||
writes: fixture.writes
|
||||
}
|
||||
}
|
||||
|
||||
function reopenPromptContractDb(harness: PromptContractHarness): OrchestrationDb {
|
||||
const index = openDatabases.indexOf(harness.db)
|
||||
if (index !== -1) {
|
||||
openDatabases.splice(index, 1)
|
||||
}
|
||||
harness.db.close()
|
||||
harness.db = new OrchestrationDb(harness.dbPath)
|
||||
openDatabases.push(harness.db)
|
||||
return harness.db
|
||||
}
|
||||
|
||||
describe('orchestration worker-start prompt contract', () => {
|
||||
afterEach(() => {
|
||||
for (const db of openDatabases.splice(0)) {
|
||||
db.close()
|
||||
}
|
||||
for (const root of temporaryRoots.splice(0)) {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('durably accepts exactly one submitted and started turn', async () => {
|
||||
vi.useFakeTimers()
|
||||
const harness = await createPromptContractHarness('accepted')
|
||||
const pending = harness.dispatcher.dispatch(harness.request)
|
||||
|
||||
await vi.runAllTimersAsync()
|
||||
const response = await pending
|
||||
expect(response).toMatchObject({
|
||||
ok: true,
|
||||
result: {
|
||||
state: 'ready',
|
||||
stage: 'input_accepted',
|
||||
mutation: { requestId: harness.requestId, replayed: false },
|
||||
effects: expect.arrayContaining([
|
||||
expect.objectContaining({ kind: 'dispatch_input', state: 'accepted' })
|
||||
])
|
||||
}
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(response.error.message)
|
||||
}
|
||||
const dispatchId = (response.result as { dispatchId: string }).dispatchId
|
||||
expect(harness.submittedTurns()).toBe(1)
|
||||
expect(harness.startedTurns()).toBe(1)
|
||||
expect(harness.prematureSubmits()).toBe(0)
|
||||
expect(harness.writes.filter((data) => data === '\r')).toHaveLength(1)
|
||||
const persisted = reopenPromptContractDb(harness)
|
||||
expect(persisted.getTask(harness.taskId)?.status).toBe('dispatched')
|
||||
expect(persisted.getDispatchContextById(dispatchId)).toMatchObject({
|
||||
status: 'dispatched',
|
||||
capability_hash: expect.any(String),
|
||||
capability_revoked_at: null
|
||||
})
|
||||
expect(persisted.getWorkerDispatch(dispatchId)).toMatchObject({
|
||||
state: 'ready',
|
||||
stage: 'input_accepted',
|
||||
last_error: null
|
||||
})
|
||||
const callerFingerprint = persisted.getOrCreateLocalMutationCallerFingerprint()
|
||||
const receipt = persisted.getMutationReceipt(callerFingerprint, harness.requestId)
|
||||
expect(receipt).toMatchObject({ state: 'completed' })
|
||||
expect(JSON.parse(receipt?.receipt ?? 'null')).toMatchObject({
|
||||
dispatchId,
|
||||
state: 'ready',
|
||||
stage: 'input_accepted'
|
||||
})
|
||||
})
|
||||
|
||||
it('reports a swallowed Enter as stalled without sending a rescue Enter', async () => {
|
||||
vi.useFakeTimers()
|
||||
const harness = await createPromptContractHarness('swallowed')
|
||||
const pending = harness.dispatcher.dispatch(harness.request)
|
||||
|
||||
await vi.runAllTimersAsync()
|
||||
const response = await pending
|
||||
expect(response).toMatchObject({
|
||||
ok: true,
|
||||
result: {
|
||||
state: 'failed',
|
||||
failedStage: 'dispatch_input',
|
||||
lastError: 'agent_prompt_stalled',
|
||||
mutation: { requestId: harness.requestId, replayed: false }
|
||||
}
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(response.error.message)
|
||||
}
|
||||
const dispatchId = (response.result as { dispatchId: string }).dispatchId
|
||||
await vi.advanceTimersByTimeAsync(20_000)
|
||||
expect(harness.submittedTurns()).toBe(1)
|
||||
expect(harness.startedTurns()).toBe(0)
|
||||
expect(harness.prematureSubmits()).toBe(0)
|
||||
expect(harness.writes.filter((data) => data === '\r')).toHaveLength(1)
|
||||
const persisted = reopenPromptContractDb(harness)
|
||||
expect(persisted.getTask(harness.taskId)?.status).toBe('failed')
|
||||
expect(persisted.getDispatchContextById(dispatchId)).toMatchObject({
|
||||
status: 'failed',
|
||||
last_failure: 'agent_prompt_stalled',
|
||||
capability_revoked_at: expect.any(String)
|
||||
})
|
||||
expect(persisted.getWorkerDispatch(dispatchId)).toMatchObject({
|
||||
state: 'failed',
|
||||
stage: 'dispatch_input',
|
||||
last_error: 'agent_prompt_stalled'
|
||||
})
|
||||
const callerFingerprint = persisted.getOrCreateLocalMutationCallerFingerprint()
|
||||
const receipt = persisted.getMutationReceipt(callerFingerprint, harness.requestId)
|
||||
expect(receipt).toMatchObject({ state: 'completed' })
|
||||
expect(JSON.parse(receipt?.receipt ?? 'null')).toMatchObject({
|
||||
dispatchId,
|
||||
state: 'failed',
|
||||
failedStage: 'dispatch_input',
|
||||
lastError: 'agent_prompt_stalled'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -341,6 +341,64 @@ describe('createMainWindow', () => {
|
||||
expect(webContents.send).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('suppresses auto-repeat workspace deletes from before-input-event', () => {
|
||||
const windowHandlers: Record<string, (...args: any[]) => void> = {}
|
||||
const webContents = {
|
||||
on: vi.fn((event, handler) => {
|
||||
windowHandlers[event] = handler
|
||||
}),
|
||||
setZoomLevel: vi.fn(),
|
||||
setBackgroundThrottling: vi.fn(),
|
||||
invalidate: vi.fn(),
|
||||
setWindowOpenHandler: vi.fn(),
|
||||
send: vi.fn(),
|
||||
isDevToolsOpened: vi.fn(),
|
||||
openDevTools: vi.fn(),
|
||||
closeDevTools: vi.fn()
|
||||
}
|
||||
const browserWindowInstance = {
|
||||
webContents,
|
||||
on: vi.fn(),
|
||||
isDestroyed: vi.fn(() => false),
|
||||
isMaximized: vi.fn(() => true),
|
||||
isFullScreen: vi.fn(() => false),
|
||||
getSize: vi.fn(() => [1200, 800]),
|
||||
setSize: vi.fn(),
|
||||
maximize: vi.fn(),
|
||||
show: vi.fn(),
|
||||
loadFile: vi.fn(),
|
||||
loadURL: vi.fn()
|
||||
}
|
||||
browserWindowMock.mockImplementation(function () {
|
||||
return browserWindowInstance
|
||||
})
|
||||
|
||||
createMainWindow(null)
|
||||
|
||||
const isDarwin = process.platform === 'darwin'
|
||||
const input = {
|
||||
type: 'keyDown',
|
||||
code: 'Backspace',
|
||||
key: 'Backspace',
|
||||
meta: isDarwin,
|
||||
control: !isDarwin,
|
||||
alt: false,
|
||||
shift: true
|
||||
}
|
||||
windowHandlers['before-input-event']({ preventDefault: vi.fn() } as never, input)
|
||||
expect(webContents.send).toHaveBeenCalledWith('ui:deleteCurrentWorkspace')
|
||||
|
||||
webContents.send.mockClear()
|
||||
const repeatPreventDefault = vi.fn()
|
||||
windowHandlers['before-input-event']({ preventDefault: repeatPreventDefault } as never, {
|
||||
...input,
|
||||
isAutoRepeat: true
|
||||
})
|
||||
|
||||
expect(repeatPreventDefault).toHaveBeenCalledOnce()
|
||||
expect(webContents.send).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('lets Terminal-first pass risky app shortcuts through when terminal input is focused', () => {
|
||||
const windowHandlers: Record<string, (...args: any[]) => void> = {}
|
||||
const webContents = {
|
||||
@@ -624,7 +682,7 @@ describe('createMainWindow', () => {
|
||||
expect(webContents.send).toHaveBeenNthCalledWith(2, 'ui:openQuickOpen')
|
||||
})
|
||||
|
||||
it('forwards the configured workspace delete shortcut while terminal input is focused', () => {
|
||||
it('forwards the default workspace delete shortcut while terminal input is focused', () => {
|
||||
const windowHandlers: Record<string, (...args: any[]) => void> = {}
|
||||
const webContents = {
|
||||
on: vi.fn((event, handler) => {
|
||||
@@ -662,7 +720,7 @@ describe('createMainWindow', () => {
|
||||
getSettings: () => ({ terminalShortcutPolicy: 'terminal-first' })
|
||||
} as never,
|
||||
{
|
||||
getKeybindings: () => ({ 'workspace.delete': ['Mod+Shift+Backspace'] })
|
||||
getKeybindings: () => ({})
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -811,7 +811,10 @@ export function createMainWindow(
|
||||
return true
|
||||
}
|
||||
|
||||
if (action.type === 'toggleQuickCommandsMenu' && isAutoRepeat) {
|
||||
if (
|
||||
(action.type === 'toggleQuickCommandsMenu' || action.type === 'deleteCurrentWorkspace') &&
|
||||
isAutoRepeat
|
||||
) {
|
||||
event.preventDefault()
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { AppState } from '@/store/types'
|
||||
import type { HoveredWorkspaceDeleteTarget } from '../components/sidebar/hovered-workspace-delete'
|
||||
import type { AppShortcutState, ShortcutDispatchInput } from './app-command-handlers'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
deleteHoveredWorkspaceImmediately: vi.fn(),
|
||||
hoveredTarget: { kind: 'worktree', worktree: {} } as HoveredWorkspaceDeleteTarget | null,
|
||||
store: {} as AppState
|
||||
}))
|
||||
|
||||
vi.mock('../store', () => ({
|
||||
useAppStore: Object.assign(vi.fn(), { getState: () => mocks.store })
|
||||
}))
|
||||
|
||||
vi.mock('../components/sidebar/hovered-workspace-delete', () => ({
|
||||
deleteHoveredWorkspaceImmediately: mocks.deleteHoveredWorkspaceImmediately,
|
||||
resolveHoveredWorkspaceDeleteTarget: () => mocks.hoveredTarget
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/floating-workspace-terminal-actions', () => ({
|
||||
isFloatingWorkspacePanelFocused: () => false
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/terminal-shortcut-capture-notification', () => ({
|
||||
showTerminalShortcutCaptureNotification: vi.fn()
|
||||
}))
|
||||
|
||||
import { createAppCommandHandlers } from './app-command-handlers'
|
||||
|
||||
function shortcutState(overrides: Partial<AppShortcutState> = {}): AppShortcutState {
|
||||
return {
|
||||
activeView: 'terminal',
|
||||
activeWorktreeId: 'repo::/feature',
|
||||
actions: {} as AppShortcutState['actions'],
|
||||
creationLayoutActive: false,
|
||||
floatingTerminalEnabled: false,
|
||||
floatingTerminalOpen: false,
|
||||
floatingVisibleTabCount: 0,
|
||||
keybindings: {},
|
||||
openFloatingWorkspaceMaximized: vi.fn(),
|
||||
pluginCommands: [],
|
||||
setFloatingTerminalOpen: vi.fn(),
|
||||
terminalShortcutPolicy: 'orca-first',
|
||||
workspaceChromeActive: true,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function shortcutInput(): ShortcutDispatchInput {
|
||||
return {
|
||||
target: null,
|
||||
defaultPrevented: false,
|
||||
preventDefault: vi.fn()
|
||||
}
|
||||
}
|
||||
|
||||
describe('workspace delete app command', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.store = { activeWorktreeId: 'repo::/feature' } as AppState
|
||||
mocks.hoveredTarget = { kind: 'worktree', worktree: {} as never }
|
||||
})
|
||||
|
||||
it('claims the chord and immediately deletes the active workspace', () => {
|
||||
const input = shortcutInput()
|
||||
const handler = createAppCommandHandlers(shortcutState(), input, 'terminal').get(
|
||||
'workspace.delete'
|
||||
)
|
||||
|
||||
expect(handler?.()).toBe(true)
|
||||
expect(input.preventDefault).toHaveBeenCalledOnce()
|
||||
expect(mocks.deleteHoveredWorkspaceImmediately).toHaveBeenCalledWith(
|
||||
mocks.store,
|
||||
mocks.hoveredTarget
|
||||
)
|
||||
})
|
||||
|
||||
it('does not claim the chord without a hovered workspace', () => {
|
||||
const input = shortcutInput()
|
||||
const handler = createAppCommandHandlers(shortcutState(), input).get('workspace.delete')
|
||||
|
||||
mocks.hoveredTarget = null
|
||||
expect(handler?.()).toBe(false)
|
||||
expect(input.preventDefault).not.toHaveBeenCalled()
|
||||
expect(mocks.deleteHoveredWorkspaceImmediately).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -5,6 +5,10 @@ import { requestScrollToCurrentWorkspaceRevealAndRename } from '@/lib/scroll-to-
|
||||
import { showTerminalShortcutCaptureNotification } from '@/lib/terminal-shortcut-capture-notification'
|
||||
import { shouldShowWorktreeHistoryControls } from '../lib/titlebar-worktree-history-controls'
|
||||
import { TOGGLE_WORKSPACE_BOARD_EVENT } from '../components/sidebar/useWorkspaceBoardPanel'
|
||||
import {
|
||||
deleteHoveredWorkspaceImmediately,
|
||||
resolveHoveredWorkspaceDeleteTarget
|
||||
} from '../components/sidebar/hovered-workspace-delete'
|
||||
import { useAppStore } from '../store'
|
||||
import type { usePluginCommands } from '@/store/plugin-panels'
|
||||
import { isGitRepoKind } from '../../../shared/repo-kind'
|
||||
@@ -191,6 +195,22 @@ export function createAppCommandHandlers(
|
||||
})
|
||||
}
|
||||
],
|
||||
[
|
||||
'workspace.delete',
|
||||
() => {
|
||||
if (floatingWorkspaceFocused) {
|
||||
return false
|
||||
}
|
||||
const store = useAppStore.getState()
|
||||
const target = resolveHoveredWorkspaceDeleteTarget(store)
|
||||
if (!target) {
|
||||
return false
|
||||
}
|
||||
return claim('workspace.delete', () => {
|
||||
deleteHoveredWorkspaceImmediately(store, target)
|
||||
})
|
||||
}
|
||||
],
|
||||
[
|
||||
'workspace.openBoard',
|
||||
() => {
|
||||
|
||||
@@ -236,6 +236,9 @@ export function useGlobalKeybindings(args: {
|
||||
}
|
||||
|
||||
const handlers = createAppCommandHandlers(state, input, context)
|
||||
if (matchShortcut('workspace.delete') && handlers.get('workspace.delete')?.()) {
|
||||
return
|
||||
}
|
||||
for (const actionId of PLUGIN_COMMAND_ALIAS_ACTION_IDS) {
|
||||
if (matchShortcut(actionId) && handlers.get(actionId)?.()) {
|
||||
return
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
/**
|
||||
* @vitest-environment happy-dom
|
||||
*/
|
||||
import { act } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Worktree } from '../../../../shared/worktree/types'
|
||||
import WorktreeContextMenu from './WorktreeContextMenu'
|
||||
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
|
||||
const shortcutLabelMock = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('@/hooks/useShortcutLabel', () => ({
|
||||
useOptionalShortcutLabel: shortcutLabelMock,
|
||||
formatShortcutLabel: () => '',
|
||||
formatOptionalShortcutLabel: () => null
|
||||
}))
|
||||
|
||||
vi.mock('@/components/ui/dropdown-menu', () => ({
|
||||
DropdownMenu: function DropdownMenu(props: { children?: React.ReactNode; open?: boolean }) {
|
||||
return <div data-testid="dropdown-menu">{props.children}</div>
|
||||
},
|
||||
DropdownMenuContent: function DropdownMenuContent(props: { children?: React.ReactNode }) {
|
||||
return <div data-testid="dropdown-menu-content">{props.children}</div>
|
||||
},
|
||||
DropdownMenuItem: function DropdownMenuItem(props: {
|
||||
children?: React.ReactNode
|
||||
disabled?: boolean
|
||||
variant?: string
|
||||
}) {
|
||||
return (
|
||||
<div
|
||||
data-testid="dropdown-menu-item"
|
||||
data-variant={props.variant}
|
||||
data-disabled={props.disabled}
|
||||
>
|
||||
{props.children}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
DropdownMenuSeparator: function DropdownMenuSeparator() {
|
||||
return <hr />
|
||||
},
|
||||
DropdownMenuShortcut: function DropdownMenuShortcut(props: { children?: React.ReactNode }) {
|
||||
return <span data-testid="dropdown-menu-shortcut">{props.children}</span>
|
||||
},
|
||||
DropdownMenuLabel: function DropdownMenuLabel(props: { children?: React.ReactNode }) {
|
||||
return <div>{props.children}</div>
|
||||
},
|
||||
DropdownMenuSub: function DropdownMenuSub(props: { children?: React.ReactNode }) {
|
||||
return <div>{props.children}</div>
|
||||
},
|
||||
DropdownMenuSubContent: function DropdownMenuSubContent(props: { children?: React.ReactNode }) {
|
||||
return <div>{props.children}</div>
|
||||
},
|
||||
DropdownMenuSubTrigger: function DropdownMenuSubTrigger(props: { children?: React.ReactNode }) {
|
||||
return <div>{props.children}</div>
|
||||
},
|
||||
DropdownMenuTrigger: function DropdownMenuTrigger(props: { children?: React.ReactNode }) {
|
||||
return <div>{props.children}</div>
|
||||
},
|
||||
DropdownMenuRadioGroup: function DropdownMenuRadioGroup(props: { children?: React.ReactNode }) {
|
||||
return <div>{props.children}</div>
|
||||
},
|
||||
DropdownMenuRadioItem: function DropdownMenuRadioItem(props: { children?: React.ReactNode }) {
|
||||
return <div>{props.children}</div>
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/components/ui/tooltip', () => ({
|
||||
Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
TooltipContent: ({ children }: { children: React.ReactNode }) => <>{children}</>
|
||||
}))
|
||||
|
||||
vi.mock('lucide-react', async () =>
|
||||
(await import('../tab-bar/lucide-icon-stub-fixture')).stubEveryIcon()
|
||||
)
|
||||
|
||||
vi.mock('@/i18n/i18n', () => ({
|
||||
translate: (_key: string, fallback: string) => fallback
|
||||
}))
|
||||
|
||||
const defaultStoreState = {
|
||||
updateWorktreeMeta: vi.fn(),
|
||||
setWorktreesPinnedAndReveal: vi.fn(),
|
||||
workspaceStatuses: [],
|
||||
openModal: vi.fn(),
|
||||
projectGroups: [],
|
||||
createProjectGroup: vi.fn(),
|
||||
moveProjectToGroup: vi.fn(),
|
||||
deleteStateByWorktreeId: {},
|
||||
worktreeLineageById: {},
|
||||
workspaceLineageByChildKey: {},
|
||||
updateWorktreeLineage: vi.fn(),
|
||||
tabsByWorktree: {},
|
||||
ptyIdsByTabId: {},
|
||||
browserTabsByWorktree: {},
|
||||
worktreesByRepo: {},
|
||||
repos: []
|
||||
}
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
useAppStore: Object.assign(
|
||||
(selector: (state: typeof defaultStoreState) => unknown) => selector(defaultStoreState),
|
||||
{
|
||||
getState: () => defaultStoreState
|
||||
}
|
||||
)
|
||||
}))
|
||||
|
||||
vi.mock('@/store/selectors', () => ({
|
||||
useAllWorktrees: () => [],
|
||||
useRepoById: (repoId?: string) =>
|
||||
repoId ? { id: repoId, name: repoId, displayName: repoId } : undefined,
|
||||
useRepoMap: () => new Map(),
|
||||
useWorktreeMap: () => new Map()
|
||||
}))
|
||||
|
||||
vi.mock('./ProjectGroupNameDialog', () => ({
|
||||
ProjectGroupNameDialog: () => null
|
||||
}))
|
||||
|
||||
vi.mock('./WorktreeParentPickerPopover', () => ({
|
||||
WorktreeParentPickerPopover: () => null
|
||||
}))
|
||||
|
||||
vi.mock('./WorktreeDeveloperMenu', () => ({
|
||||
WorktreeDeveloperMenu: () => null
|
||||
}))
|
||||
|
||||
vi.mock('./WorktreeOpenInMenu', () => ({
|
||||
WorktreeOpenInSubMenu: () => null
|
||||
}))
|
||||
|
||||
vi.mock('./WorkspaceSleepMenuItems', () => ({
|
||||
WorkspaceSleepMenuItems: () => null
|
||||
}))
|
||||
|
||||
const mounted: { container: HTMLDivElement; root: Root }[] = []
|
||||
|
||||
function renderContextMenu(worktree: Worktree) {
|
||||
const container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
const root = createRoot(container)
|
||||
act(() => {
|
||||
root.render(
|
||||
<WorktreeContextMenu worktree={worktree}>
|
||||
<div data-testid="card-child">Card Content</div>
|
||||
</WorktreeContextMenu>
|
||||
)
|
||||
})
|
||||
mounted.push({ container, root })
|
||||
return container
|
||||
}
|
||||
|
||||
describe('WorktreeContextMenu delete shortcut display', () => {
|
||||
beforeEach(() => {
|
||||
shortcutLabelMock.mockImplementation((action: string) => {
|
||||
if (action === 'workspace.delete') {
|
||||
return '⌘⇧⌫'
|
||||
}
|
||||
return null
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const { root, container } of mounted) {
|
||||
act(() => {
|
||||
root.unmount()
|
||||
})
|
||||
container.remove()
|
||||
}
|
||||
mounted.length = 0
|
||||
})
|
||||
|
||||
it('renders the delete shortcut badge for standard worktree delete', () => {
|
||||
const worktree = {
|
||||
id: 'repo::wt-1',
|
||||
repoId: 'repo',
|
||||
name: 'wt-1',
|
||||
path: '/path/to/wt-1',
|
||||
isMainWorktree: false
|
||||
} as unknown as Worktree
|
||||
|
||||
const container = renderContextMenu(worktree)
|
||||
const target = container.querySelector('[data-worktree-context-menu-scope]') as HTMLElement
|
||||
expect(target).toBeTruthy()
|
||||
act(() => {
|
||||
target.dispatchEvent(
|
||||
new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 10, clientY: 10 })
|
||||
)
|
||||
})
|
||||
|
||||
const shortcuts = container.querySelectorAll('[data-testid="dropdown-menu-shortcut"]')
|
||||
const deleteShortcuts = Array.from(shortcuts).filter((el) => el.textContent === '⌘⇧⌫')
|
||||
expect(deleteShortcuts.length).toBe(1)
|
||||
})
|
||||
|
||||
it('omits the delete shortcut on disabled Delete Worktree for primary checkout', () => {
|
||||
const worktree = {
|
||||
id: 'repo-1::main',
|
||||
repoId: 'repo-1',
|
||||
name: 'main',
|
||||
path: '/path/to/main',
|
||||
isMainWorktree: true
|
||||
} as unknown as Worktree
|
||||
|
||||
const container = renderContextMenu(worktree)
|
||||
const target = container.querySelector('[data-worktree-context-menu-scope]') as HTMLElement
|
||||
act(() => {
|
||||
target.dispatchEvent(
|
||||
new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 10, clientY: 10 })
|
||||
)
|
||||
})
|
||||
|
||||
const shortcuts = container.querySelectorAll('[data-testid="dropdown-menu-shortcut"]')
|
||||
const deleteShortcuts = Array.from(shortcuts).filter((el) => el.textContent === '⌘⇧⌫')
|
||||
expect(deleteShortcuts.length).toBe(0)
|
||||
})
|
||||
|
||||
it('omits the shortcut badge when the action is unassigned', () => {
|
||||
shortcutLabelMock.mockReturnValue(null)
|
||||
const worktree = {
|
||||
id: 'repo::wt-1',
|
||||
repoId: 'repo',
|
||||
name: 'wt-1',
|
||||
path: '/path/to/wt-1',
|
||||
isMainWorktree: false
|
||||
} as unknown as Worktree
|
||||
|
||||
const container = renderContextMenu(worktree)
|
||||
const target = container.querySelector('[data-worktree-context-menu-scope]') as HTMLElement
|
||||
act(() => {
|
||||
target.dispatchEvent(
|
||||
new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 10, clientY: 10 })
|
||||
)
|
||||
})
|
||||
|
||||
const shortcuts = container.querySelectorAll('[data-testid="dropdown-menu-shortcut"]')
|
||||
expect(shortcuts.length).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubContent,
|
||||
DropdownMenuSubTrigger,
|
||||
@@ -68,6 +69,7 @@ import { translate } from '@/i18n/i18n'
|
||||
import { unnestWorktrees } from './worktree-unnest'
|
||||
import { parseWorkspaceKey, worktreeWorkspaceKey } from '../../../../shared/workspace-scope'
|
||||
import { getDeleteStateForWorktreeHost } from './worktree-delete-state-host-match'
|
||||
import { useOptionalShortcutLabel } from '@/hooks/useShortcutLabel'
|
||||
|
||||
type Props = {
|
||||
worktree: Worktree
|
||||
@@ -337,6 +339,7 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({
|
||||
const deleteState = useAppStore((s) =>
|
||||
getDeleteStateForWorktreeHost(worktree, s.deleteStateByWorktreeId)
|
||||
)
|
||||
const deleteShortcut = useOptionalShortcutLabel('workspace.delete')
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
// Why: the Developer submenu is a power-user affordance, so it is revealed by
|
||||
// holding Option/Alt at right-click — captured at open time (like the Help
|
||||
@@ -1086,6 +1089,9 @@ const WorktreeContextMenu = React.memo(function WorktreeContextMenu({
|
||||
'auto.components.sidebar.WorktreeContextMenu.f4475537d8',
|
||||
'Delete'
|
||||
)}
|
||||
{!isMultiContext && !removesProject && deleteShortcut ? (
|
||||
<DropdownMenuShortcut>{deleteShortcut}</DropdownMenuShortcut>
|
||||
) : null}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
@@ -66,7 +66,8 @@ vi.mock('@/components/ui/dropdown-menu', () => {
|
||||
DropdownMenuSub: passthrough,
|
||||
DropdownMenuSubContent: passthrough,
|
||||
DropdownMenuSubTrigger: passthrough,
|
||||
DropdownMenuTrigger: passthrough
|
||||
DropdownMenuTrigger: passthrough,
|
||||
DropdownMenuShortcut: passthrough
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { AppState } from '@/store/types'
|
||||
import type { Worktree } from '../../../../shared/worktree/types'
|
||||
import {
|
||||
deleteHoveredWorkspaceImmediately,
|
||||
getHoveredWorkspaceIdentity,
|
||||
resolveHoveredWorkspaceDeleteTarget
|
||||
} from './hovered-workspace-delete'
|
||||
|
||||
function worktree(overrides: Partial<Worktree> = {}): Worktree {
|
||||
return {
|
||||
id: 'repo::/feature',
|
||||
repoId: 'repo',
|
||||
path: '/feature',
|
||||
branch: 'feature',
|
||||
isMainWorktree: false,
|
||||
...overrides
|
||||
} as Worktree
|
||||
}
|
||||
|
||||
function hoveredDocument(...rows: { workspaceId: string; hostIdentity: string }[]) {
|
||||
return {
|
||||
activeElement: null,
|
||||
querySelectorAll: () => ({
|
||||
length: rows.length,
|
||||
item: (index: number) => {
|
||||
const row = rows[index]
|
||||
return row
|
||||
? ({
|
||||
dataset: {
|
||||
worktreeId: row.workspaceId,
|
||||
worktreeHostIdentity: row.hostIdentity
|
||||
}
|
||||
} as unknown as HTMLElement)
|
||||
: null
|
||||
}
|
||||
})
|
||||
} as unknown as Pick<Document, 'activeElement' | 'querySelectorAll'>
|
||||
}
|
||||
|
||||
function state(worktrees: Worktree[] = []): AppState {
|
||||
return {
|
||||
activeModal: 'none',
|
||||
activeWorkspaceExecutionHostId: worktrees[0]?.hostId ?? null,
|
||||
activeWorktreeId: worktrees[0]?.id ?? null,
|
||||
deleteFolderWorkspace: vi.fn(),
|
||||
deleteStateByWorktreeId: {},
|
||||
setActiveWorktree: vi.fn(),
|
||||
worktreesByRepo: { repo: worktrees }
|
||||
} as unknown as AppState
|
||||
}
|
||||
|
||||
describe('hovered workspace delete', () => {
|
||||
it('uses the deepest hovered worktree row', () => {
|
||||
expect(
|
||||
getHoveredWorkspaceIdentity(
|
||||
hoveredDocument(
|
||||
{ workspaceId: 'parent', hostIdentity: 'local|parent' },
|
||||
{ workspaceId: 'child', hostIdentity: 'local|child' }
|
||||
)
|
||||
)
|
||||
).toEqual({ workspaceId: 'child', hostIdentity: 'local|child' })
|
||||
})
|
||||
|
||||
it('resolves the exact hovered host instead of the active workspace', () => {
|
||||
const active = worktree({ id: 'repo::/active', path: '/active', hostId: 'local' })
|
||||
const hovered = worktree({ hostId: 'ssh:build', instanceId: 'instance-2' })
|
||||
|
||||
expect(
|
||||
resolveHoveredWorkspaceDeleteTarget(
|
||||
state([active, hovered]),
|
||||
hoveredDocument({ workspaceId: hovered.id, hostIdentity: 'ssh:build|repo::/feature' })
|
||||
)
|
||||
).toEqual({ kind: 'worktree', worktree: hovered })
|
||||
})
|
||||
|
||||
it('retains the hovered host when resolving a folder workspace', () => {
|
||||
expect(
|
||||
resolveHoveredWorkspaceDeleteTarget(
|
||||
state(),
|
||||
hoveredDocument({
|
||||
workspaceId: 'folder:folder-1',
|
||||
hostIdentity: 'runtime:remote-1|folder:folder-1'
|
||||
})
|
||||
)
|
||||
).toEqual({
|
||||
kind: 'folder',
|
||||
executionHostId: 'runtime:remote-1',
|
||||
folderWorkspaceId: 'folder-1',
|
||||
workspaceKey: 'folder:folder-1'
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects primary worktrees, stale rows, and missing hover', () => {
|
||||
const primary = worktree({ hostId: 'local', isMainWorktree: true })
|
||||
const current = state([primary])
|
||||
|
||||
expect(
|
||||
resolveHoveredWorkspaceDeleteTarget(
|
||||
current,
|
||||
hoveredDocument({ workspaceId: primary.id, hostIdentity: 'local|repo::/feature' })
|
||||
)
|
||||
).toBeNull()
|
||||
expect(
|
||||
resolveHoveredWorkspaceDeleteTarget(
|
||||
current,
|
||||
hoveredDocument({ workspaceId: 'stale', hostIdentity: 'local|stale' })
|
||||
)
|
||||
).toBeNull()
|
||||
expect(resolveHoveredWorkspaceDeleteTarget(current, hoveredDocument())).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects worktrees that are already deleting', () => {
|
||||
const target = worktree({ hostId: 'ssh:build' })
|
||||
const current = state([target])
|
||||
current.deleteStateByWorktreeId = {
|
||||
'ssh:build|repo::/feature': {
|
||||
isDeleting: true,
|
||||
error: null,
|
||||
canForceDelete: false,
|
||||
forceDeleteReason: null
|
||||
}
|
||||
}
|
||||
|
||||
expect(
|
||||
resolveHoveredWorkspaceDeleteTarget(
|
||||
current,
|
||||
hoveredDocument({ workspaceId: target.id, hostIdentity: 'ssh:build|repo::/feature' })
|
||||
)
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects hovered rows while an editable control has focus', () => {
|
||||
class EditableElement {
|
||||
classList = { contains: () => false }
|
||||
isContentEditable = false
|
||||
closest = () => this
|
||||
}
|
||||
vi.stubGlobal('HTMLElement', EditableElement)
|
||||
const target = worktree({ hostId: 'local' })
|
||||
const doc = hoveredDocument({
|
||||
workspaceId: target.id,
|
||||
hostIdentity: 'local|repo::/feature'
|
||||
}) as Pick<Document, 'activeElement' | 'querySelectorAll'>
|
||||
Object.defineProperty(doc, 'activeElement', { value: new EditableElement() })
|
||||
|
||||
try {
|
||||
expect(resolveHoveredWorkspaceDeleteTarget(state([target]), doc)).toBeNull()
|
||||
} finally {
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
})
|
||||
|
||||
it('routes the hovered worktree through the host-qualified safety flow', () => {
|
||||
const target = worktree({ hostId: 'ssh:build', instanceId: 'instance-2' })
|
||||
const deleteWorktree = vi.fn()
|
||||
const current = state([target])
|
||||
|
||||
expect(
|
||||
deleteHoveredWorkspaceImmediately(
|
||||
current,
|
||||
{ kind: 'worktree', worktree: target },
|
||||
{
|
||||
deleteWorktree,
|
||||
getCurrentState: () => current
|
||||
}
|
||||
)
|
||||
).toBe(true)
|
||||
expect(deleteWorktree).toHaveBeenCalledWith(target.id, {
|
||||
expectedHostId: 'ssh:build',
|
||||
expectedInstanceId: 'instance-2'
|
||||
})
|
||||
})
|
||||
|
||||
it('removes a hovered folder workspace from Orca without deleting its directory', async () => {
|
||||
const current = state()
|
||||
current.activeWorktreeId = 'folder:folder-1'
|
||||
current.activeWorkspaceExecutionHostId = 'runtime:remote-1'
|
||||
current.deleteFolderWorkspace = vi.fn().mockResolvedValue(true)
|
||||
|
||||
expect(
|
||||
deleteHoveredWorkspaceImmediately(
|
||||
current,
|
||||
{
|
||||
kind: 'folder',
|
||||
executionHostId: 'runtime:remote-1',
|
||||
folderWorkspaceId: 'folder-1',
|
||||
workspaceKey: 'folder:folder-1'
|
||||
},
|
||||
{ deleteWorktree: vi.fn(), getCurrentState: () => current }
|
||||
)
|
||||
).toBe(true)
|
||||
await vi.waitFor(() => expect(current.setActiveWorktree).toHaveBeenCalledWith(null))
|
||||
expect(current.deleteFolderWorkspace).toHaveBeenCalledWith('folder-1', {
|
||||
executionHostId: 'runtime:remote-1'
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects a duplicate folder delete while the first request is pending', async () => {
|
||||
let finishDelete!: (deleted: boolean) => void
|
||||
const current = state()
|
||||
current.deleteFolderWorkspace = vi.fn(
|
||||
() => new Promise<boolean>((resolve) => (finishDelete = resolve))
|
||||
)
|
||||
const target = {
|
||||
kind: 'folder' as const,
|
||||
executionHostId: 'runtime:remote-2' as const,
|
||||
folderWorkspaceId: 'folder-2',
|
||||
workspaceKey: 'folder:folder-2'
|
||||
}
|
||||
const dependencies = { deleteWorktree: vi.fn(), getCurrentState: () => current }
|
||||
|
||||
expect(deleteHoveredWorkspaceImmediately(current, target, dependencies)).toBe(true)
|
||||
expect(deleteHoveredWorkspaceImmediately(current, target, dependencies)).toBe(false)
|
||||
expect(current.deleteFolderWorkspace).toHaveBeenCalledOnce()
|
||||
|
||||
finishDelete(false)
|
||||
await vi.waitFor(() =>
|
||||
expect(deleteHoveredWorkspaceImmediately(current, target, dependencies)).toBe(true)
|
||||
)
|
||||
finishDelete(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,133 @@
|
||||
import { useAppStore } from '@/store'
|
||||
import { getAllWorktreesFromState } from '@/store/selectors'
|
||||
import type { AppState } from '@/store/types'
|
||||
import { isEditableTarget } from '@/lib/editable-target'
|
||||
import {
|
||||
composeWorktreeHostIdentity,
|
||||
getExecutionHostIdFromWorktreeHostIdentity,
|
||||
getWorktreeHostIdentity
|
||||
} from '../../../../shared/worktree/host-qualified-identity'
|
||||
import type { Worktree } from '../../../../shared/worktree/types'
|
||||
import { parseWorkspaceKey } from '../../../../shared/workspace-scope'
|
||||
import type { ExecutionHostId } from '../../../../shared/execution-host'
|
||||
import { runWorktreeDelete } from './delete-worktree-flow'
|
||||
import { getDeleteStateForWorktreeHost } from './worktree-delete-state-host-match'
|
||||
|
||||
const pendingFolderDeletes = new Set<string>()
|
||||
|
||||
type DeleteWorktree = typeof runWorktreeDelete
|
||||
type HoveredWorkspaceDeleteState = Pick<
|
||||
AppState,
|
||||
| 'activeModal'
|
||||
| 'activeWorktreeId'
|
||||
| 'deleteFolderWorkspace'
|
||||
| 'deleteStateByWorktreeId'
|
||||
| 'worktreesByRepo'
|
||||
>
|
||||
type CurrentWorkspaceState = Pick<
|
||||
AppState,
|
||||
'activeWorkspaceExecutionHostId' | 'activeWorktreeId' | 'setActiveWorktree'
|
||||
>
|
||||
type HoveredWorkspaceDeleteDependencies = {
|
||||
deleteWorktree: DeleteWorktree
|
||||
getCurrentState: () => CurrentWorkspaceState
|
||||
}
|
||||
type HoveredWorkspaceDocument = Pick<Document, 'activeElement' | 'querySelectorAll'>
|
||||
|
||||
export type HoveredWorkspaceDeleteTarget =
|
||||
| {
|
||||
kind: 'folder'
|
||||
executionHostId: ExecutionHostId
|
||||
folderWorkspaceId: string
|
||||
workspaceKey: string
|
||||
}
|
||||
| { kind: 'worktree'; worktree: Worktree }
|
||||
|
||||
export function getHoveredWorkspaceIdentity(
|
||||
doc: HoveredWorkspaceDocument = document
|
||||
): { hostIdentity: string; workspaceId: string } | null {
|
||||
const hoveredRows = doc.querySelectorAll<HTMLElement>(
|
||||
'[data-worktree-sidebar] [role="option"][data-worktree-id]:hover'
|
||||
)
|
||||
const row = hoveredRows.item(hoveredRows.length - 1)
|
||||
const workspaceId = row?.dataset.worktreeId
|
||||
const hostIdentity = row?.dataset.worktreeHostIdentity
|
||||
return workspaceId && hostIdentity ? { workspaceId, hostIdentity } : null
|
||||
}
|
||||
|
||||
export function resolveHoveredWorkspaceDeleteTarget(
|
||||
state: HoveredWorkspaceDeleteState,
|
||||
doc: HoveredWorkspaceDocument = document
|
||||
): HoveredWorkspaceDeleteTarget | null {
|
||||
if (state.activeModal !== 'none' || (doc.activeElement && isEditableTarget(doc.activeElement))) {
|
||||
return null
|
||||
}
|
||||
const hovered = getHoveredWorkspaceIdentity(doc)
|
||||
if (!hovered) {
|
||||
return null
|
||||
}
|
||||
const workspaceScope = parseWorkspaceKey(hovered.workspaceId)
|
||||
if (workspaceScope?.type === 'folder') {
|
||||
const executionHostId = getExecutionHostIdFromWorktreeHostIdentity(hovered.hostIdentity)
|
||||
if (!executionHostId) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
kind: 'folder',
|
||||
executionHostId,
|
||||
folderWorkspaceId: workspaceScope.folderWorkspaceId,
|
||||
workspaceKey: hovered.workspaceId
|
||||
}
|
||||
}
|
||||
const worktree = getAllWorktreesFromState(state).find(
|
||||
(candidate) =>
|
||||
candidate.id === hovered.workspaceId &&
|
||||
getWorktreeHostIdentity(candidate) === hovered.hostIdentity
|
||||
)
|
||||
return worktree &&
|
||||
!worktree.isMainWorktree &&
|
||||
!getDeleteStateForWorktreeHost(worktree, state.deleteStateByWorktreeId)?.isDeleting
|
||||
? { kind: 'worktree', worktree }
|
||||
: null
|
||||
}
|
||||
|
||||
export function deleteHoveredWorkspaceImmediately(
|
||||
state: HoveredWorkspaceDeleteState,
|
||||
target: HoveredWorkspaceDeleteTarget | null = resolveHoveredWorkspaceDeleteTarget(state),
|
||||
dependencies: HoveredWorkspaceDeleteDependencies = {
|
||||
deleteWorktree: runWorktreeDelete,
|
||||
getCurrentState: useAppStore.getState
|
||||
}
|
||||
): boolean {
|
||||
if (!target) {
|
||||
return false
|
||||
}
|
||||
if (target.kind === 'folder') {
|
||||
const pendingIdentity = composeWorktreeHostIdentity(target.executionHostId, target.workspaceKey)
|
||||
if (pendingFolderDeletes.has(pendingIdentity)) {
|
||||
return false
|
||||
}
|
||||
pendingFolderDeletes.add(pendingIdentity)
|
||||
void state
|
||||
.deleteFolderWorkspace(target.folderWorkspaceId, {
|
||||
executionHostId: target.executionHostId
|
||||
})
|
||||
.then((deleted) => {
|
||||
const current = dependencies.getCurrentState()
|
||||
if (
|
||||
deleted &&
|
||||
current.activeWorktreeId === target.workspaceKey &&
|
||||
current.activeWorkspaceExecutionHostId === target.executionHostId
|
||||
) {
|
||||
current.setActiveWorktree(null)
|
||||
}
|
||||
})
|
||||
.finally(() => pendingFolderDeletes.delete(pendingIdentity))
|
||||
return true
|
||||
}
|
||||
dependencies.deleteWorktree(target.worktree.id, {
|
||||
expectedInstanceId: target.worktree.instanceId,
|
||||
...(target.worktree.hostId ? { expectedHostId: target.worktree.hostId } : {})
|
||||
})
|
||||
return true
|
||||
}
|
||||
+42
@@ -6,6 +6,10 @@ import { createMockTransport, createPane, createManager } from './pty-connection
|
||||
import { buildPaneConnectionDeps, buildDirectSshSplitRetryCommit } from './pty-connection-test-deps'
|
||||
import { createInitialStoreState } from './pty-connection-test-store-fixtures'
|
||||
import type { StoreState } from './pty-connection-test-store-state'
|
||||
import {
|
||||
pendingSpawnByPaneKey,
|
||||
pendingSpawnGenerationByPaneKey
|
||||
} from './pty-connection/pty-connect-limits'
|
||||
import type { MockTransport } from './pty-connection-test-pane-fixtures'
|
||||
import {
|
||||
installTerminalTestGlobals,
|
||||
@@ -139,6 +143,8 @@ describe('connectPanePty', () => {
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
pendingSpawnByPaneKey.clear()
|
||||
pendingSpawnGenerationByPaneKey.clear()
|
||||
await restoreTerminalTestGlobals()
|
||||
})
|
||||
|
||||
@@ -161,6 +167,42 @@ describe('connectPanePty', () => {
|
||||
logSpy.mockRestore()
|
||||
}, 30_000)
|
||||
|
||||
it('does not hold a successor behind a canceled spawn serializer declaration', async () => {
|
||||
const { connectPanePty } = await import('./pty-connection')
|
||||
const declaration = createDeferred<number>()
|
||||
const spawn = createDeferred<null>()
|
||||
const transport = createMockTransport()
|
||||
transport.connect.mockReturnValueOnce(spawn.promise)
|
||||
transportFactoryQueue.push(transport)
|
||||
mockStoreState = {
|
||||
...mockStoreState,
|
||||
tabsByWorktree: { 'wt-1': [{ id: 'tab-1', ptyId: null }] },
|
||||
ptyIdsByTabId: { 'tab-1': [] }
|
||||
}
|
||||
vi.mocked(window.api.pty.declarePendingPaneSerializer).mockReturnValueOnce(declaration.promise)
|
||||
|
||||
const binding = connectPanePty(
|
||||
createPane(1) as never,
|
||||
createManager(1) as never,
|
||||
createDeps() as never
|
||||
)
|
||||
await flushAsyncTicks(12)
|
||||
binding.dispose()
|
||||
spawn.resolve(null)
|
||||
await flushAsyncTicks(12)
|
||||
|
||||
expect(pendingSpawnByPaneKey.size).toBe(0)
|
||||
expect(window.api.pty.clearPendingPaneSerializer).not.toHaveBeenCalled()
|
||||
|
||||
declaration.resolve(7)
|
||||
await flushAsyncTicks(12)
|
||||
|
||||
expect(window.api.pty.clearPendingPaneSerializer).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.any(String),
|
||||
7
|
||||
)
|
||||
})
|
||||
|
||||
it.each(['rejects', 'resolves empty'] as const)(
|
||||
'settles the exact direct SSH retry when its fresh spawn %s',
|
||||
async (outcome) => {
|
||||
|
||||
+8
-3
@@ -151,9 +151,14 @@ export function installAgentIdleWorkingHandlers(session: ConnectPanePtySession):
|
||||
: undefined
|
||||
return attempt
|
||||
})()
|
||||
session.pendingSpawnKey = session.directSshRetryAttempt
|
||||
? JSON.stringify([session.cacheKey, session.directSshRetryAttempt.attemptId])
|
||||
: session.cacheKey
|
||||
// Generation is part of ownership: a recovery remount must not join a spawn
|
||||
// started by the pane instance it replaced, while StrictMode remounts keep
|
||||
// the same generation and may still share their in-flight spawn.
|
||||
session.pendingSpawnKey = JSON.stringify([
|
||||
session.cacheKey,
|
||||
session.tabGeneration,
|
||||
session.directSshRetryAttempt?.attemptId ?? null
|
||||
])
|
||||
session.capturedDirectSshRetryPtyAccepted = false
|
||||
session.directSshPaneRetrySettlementCancelled = false
|
||||
session.directSshPaneRetrySettlementTimers = new Set<ReturnType<typeof setTimeout>>()
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { PaneManager, ManagedPane } from '@/lib/pane-manager/pane-manager'
|
||||
import { useAppStore } from '@/store'
|
||||
import { TerminalKittyKeyboardModeTracker } from '../../../../../shared/terminal-kitty-keyboard-mode-tracker'
|
||||
import type { PtyConnectionDeps } from '../pty-connection-types'
|
||||
import {
|
||||
@@ -35,6 +36,7 @@ import { installPtyInputRecovery } from './pty-input-recovery'
|
||||
import { installPtyInputForward } from './pty-input-forward'
|
||||
import { installPtyResizeGeometry } from './pty-resize-geometry'
|
||||
import { installSessionReconcileDispose } from './session-reconcile-dispose'
|
||||
import { resolveTerminalTabId } from './terminal-tab-id'
|
||||
|
||||
/**
|
||||
* Establishes a binding between a terminal pane and its corresponding PTY stream,
|
||||
@@ -48,6 +50,43 @@ export function connectPanePty(
|
||||
const session = { pane, manager, deps } as ConnectPanePtySession
|
||||
session.shouldRefreshForegroundSynchronously = (): boolean =>
|
||||
!session.manager.hasWebglRenderer(session.pane.id)
|
||||
const state = useAppStore.getState()
|
||||
const unifiedTab = state.getTab?.(deps.tabId)
|
||||
const initialOwnerWorktreeId =
|
||||
state.getTerminalTabOwnerWorktreeId?.(deps.tabId) ??
|
||||
(unifiedTab?.contentType === 'terminal'
|
||||
? state.getTerminalTabOwnerWorktreeId?.(unifiedTab.entityId)
|
||||
: null)
|
||||
const terminalTabId = resolveTerminalTabId(
|
||||
{
|
||||
getTab: state.getTab,
|
||||
hasTerminalTab: (candidateId) =>
|
||||
Boolean(
|
||||
state.tabsByWorktree[deps.worktreeId]?.some(
|
||||
(candidate) => candidate.id === candidateId
|
||||
) ||
|
||||
(initialOwnerWorktreeId
|
||||
? state.tabsByWorktree[initialOwnerWorktreeId]?.some(
|
||||
(candidate) => candidate.id === candidateId
|
||||
)
|
||||
: false)
|
||||
)
|
||||
},
|
||||
deps.tabId
|
||||
)
|
||||
const ownerWorktreeId =
|
||||
state.getTerminalTabOwnerWorktreeId?.(terminalTabId) ?? initialOwnerWorktreeId
|
||||
const terminalTab =
|
||||
state.tabsByWorktree[deps.worktreeId]?.find((candidate) => candidate.id === terminalTabId) ??
|
||||
(ownerWorktreeId
|
||||
? state.tabsByWorktree[ownerWorktreeId]?.find((candidate) => candidate.id === terminalTabId)
|
||||
: undefined) ??
|
||||
// Why: folder/worktree migrations can leave the pane's render key stale for one commit.
|
||||
Object.values(state.tabsByWorktree)
|
||||
.find((tabs) => tabs.some((candidate) => candidate.id === terminalTabId))
|
||||
?.find((candidate) => candidate.id === terminalTabId)
|
||||
const tab = terminalTab ?? (unifiedTab && 'generation' in unifiedTab ? unifiedTab : null)
|
||||
session.tabGeneration = tab?.generation ?? 0
|
||||
// Why: recovery ownership belongs to this xterm instance. A request that
|
||||
// settles after remount must not remount its already-replaced successor.
|
||||
session.terminalRecoveryGeneration = captureTerminalPaneRecoveryGeneration(session.deps.tabId)
|
||||
|
||||
+12
-1
@@ -3,7 +3,11 @@ import { useAppStore } from '@/store'
|
||||
import { isWebTerminalSurfaceTabId } from '@/runtime/web-terminal-surface-id'
|
||||
import { getEagerPtyBufferHandle } from '../pty-dispatcher'
|
||||
|
||||
import { pendingSpawnByPaneKey, recordPtyConnectDiagnostic } from './pty-connect-limits'
|
||||
import {
|
||||
pendingSpawnByPaneKey,
|
||||
pendingSpawnGenerationByPaneKey,
|
||||
recordPtyConnectDiagnostic
|
||||
} from './pty-connect-limits'
|
||||
import {
|
||||
isRemoteRuntimePtyId,
|
||||
canRestorePairedParkedTerminal,
|
||||
@@ -158,6 +162,13 @@ export function runDeferredSessionReattachChoice(session: ConnectPanePtySession)
|
||||
session.allowInitialIdleCacheSeed = false
|
||||
const pendingSpawn = pendingSpawnByPaneKey.get(session.pendingSpawnKey)
|
||||
if (pendingSpawn) {
|
||||
const pendingGeneration = pendingSpawnGenerationByPaneKey.get(session.pendingSpawnKey)
|
||||
if (pendingGeneration !== undefined && pendingGeneration !== session.tabGeneration) {
|
||||
recordPtyConnectDiagnostic(`pane=${session.pane.id} -> STALE PENDING SPAWN`)
|
||||
session.startFreshSpawn()
|
||||
scheduleRuntimeGraphSync()
|
||||
return
|
||||
}
|
||||
recordPtyConnectDiagnostic(`pane=${session.pane.id} -> PENDING SPAWN`)
|
||||
session.armDirectSshPaneRetryTimeout(pendingSpawn, session.directSshRetryAttempt)
|
||||
void pendingSpawn
|
||||
|
||||
@@ -3,7 +3,7 @@ import { hasPtySerializer } from '../pty-buffer-serializer'
|
||||
import { writeTerminalOutput } from '@/lib/pane-manager/pane-terminal-output-scheduler'
|
||||
|
||||
import { STARTUP_CWD_FALLBACK_NOTICE } from './startup-cwd-fallback-notice'
|
||||
import { pendingSpawnByPaneKey } from './pty-connect-limits'
|
||||
import { pendingSpawnByPaneKey, pendingSpawnGenerationByPaneKey } from './pty-connect-limits'
|
||||
import { shouldWritePtyOutputForeground } from './foreground-output-scan'
|
||||
import { isRemoteRuntimePtyId } from './paired-parked-terminal-restore'
|
||||
import { toProcessExitStartup } from './process-exit-startup'
|
||||
@@ -14,6 +14,7 @@ import type {
|
||||
} from './fresh-spawn-types'
|
||||
|
||||
import type { ConnectPanePtySession } from './connect-pane-pty-session'
|
||||
import { resolveTerminalTabId } from './terminal-tab-id'
|
||||
|
||||
export function bindStartFreshSpawn(session: ConnectPanePtySession): void {
|
||||
session.startFreshSpawn = (
|
||||
@@ -56,6 +57,15 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void {
|
||||
const preSignalPromise = session.runtimeEnvironmentId
|
||||
? Promise.resolve(null)
|
||||
: window.api.pty.declarePendingPaneSerializer(session.cacheKey).catch(() => null)
|
||||
const clearPreSignaledSerializer = (): void => {
|
||||
// A disposed pre-bind connect must not keep a successor behind a slow
|
||||
// serializer declaration. Cleanup can finish independently of spawn ownership.
|
||||
void preSignalPromise.then((gen) => {
|
||||
if (typeof gen === 'number') {
|
||||
void window.api.pty.clearPendingPaneSerializer(session.cacheKey, gen).catch(() => {})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
session.transportConnectInFlightSince = Date.now()
|
||||
const effectiveStartup = startupOverride === undefined ? session.paneStartup : startupOverride
|
||||
@@ -86,6 +96,51 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void {
|
||||
...(coldRestoreOverride ? { launchToken: coldRestoreOverride.launchToken } : {}),
|
||||
...(coldRestoreOverride ? { launchAgent: coldRestoreOverride.agent } : {}),
|
||||
...(session.shouldDeclareHiddenAtSpawn() ? { initiallyHidden: true } : {}),
|
||||
shouldContinue: () => {
|
||||
const state = useAppStore.getState()
|
||||
const unifiedTab = state.getTab?.(session.deps.tabId)
|
||||
const initialOwnerWorktreeId =
|
||||
state.getTerminalTabOwnerWorktreeId?.(session.deps.tabId) ??
|
||||
(unifiedTab?.contentType === 'terminal'
|
||||
? state.getTerminalTabOwnerWorktreeId?.(unifiedTab.entityId)
|
||||
: null)
|
||||
const terminalTabId = resolveTerminalTabId(
|
||||
{
|
||||
getTab: state.getTab,
|
||||
hasTerminalTab: (candidateId) =>
|
||||
Boolean(
|
||||
state.tabsByWorktree[session.deps.worktreeId]?.some(
|
||||
(candidate) => candidate.id === candidateId
|
||||
) ||
|
||||
(initialOwnerWorktreeId
|
||||
? state.tabsByWorktree[initialOwnerWorktreeId]?.some(
|
||||
(candidate) => candidate.id === candidateId
|
||||
)
|
||||
: false)
|
||||
)
|
||||
},
|
||||
session.deps.tabId
|
||||
)
|
||||
const ownerWorktreeId =
|
||||
state.getTerminalTabOwnerWorktreeId?.(terminalTabId) ?? initialOwnerWorktreeId
|
||||
const terminalTab =
|
||||
state.tabsByWorktree[session.deps.worktreeId]?.find(
|
||||
(candidate) => candidate.id === terminalTabId
|
||||
) ??
|
||||
(ownerWorktreeId
|
||||
? state.tabsByWorktree[ownerWorktreeId]?.find(
|
||||
(candidate) => candidate.id === terminalTabId
|
||||
)
|
||||
: undefined)
|
||||
const fallbackTab = Object.values(state.tabsByWorktree)
|
||||
.find((tabs) => tabs.some((candidate) => candidate.id === terminalTabId))
|
||||
?.find((candidate) => candidate.id === terminalTabId)
|
||||
const currentTab =
|
||||
terminalTab ??
|
||||
fallbackTab ??
|
||||
(unifiedTab && 'generation' in unifiedTab ? unifiedTab : null)
|
||||
return !session.disposed && (currentTab?.generation ?? 0) === session.tabGeneration
|
||||
},
|
||||
callbacks: outputCallbacks.callbacks
|
||||
})
|
||||
|
||||
@@ -98,10 +153,7 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void {
|
||||
.then(async (spawnedPtyId) => {
|
||||
if (outputCallbacks.generation !== session.transportStreamGeneration) {
|
||||
session.finishReattachLiveDataDeferral(false, outputCallbacks.generation)
|
||||
const gen = await preSignalPromise
|
||||
if (typeof gen === 'number') {
|
||||
void window.api.pty.clearPendingPaneSerializer(session.cacheKey, gen).catch(() => {})
|
||||
}
|
||||
clearPreSignaledSerializer()
|
||||
return null
|
||||
}
|
||||
const resolvedPtyId =
|
||||
@@ -114,10 +166,7 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void {
|
||||
session.finishReattachLiveDataDeferral(false, outputCallbacks.generation)
|
||||
// Why: an outstanding declare keeps main's cooperation gate suppressing
|
||||
// this paneKey's daemon-snapshot seed until something releases it.
|
||||
const gen = await preSignalPromise
|
||||
if (typeof gen === 'number') {
|
||||
void window.api.pty.clearPendingPaneSerializer(session.cacheKey, gen).catch(() => {})
|
||||
}
|
||||
clearPreSignaledSerializer()
|
||||
return null
|
||||
}
|
||||
const connectResult =
|
||||
@@ -196,6 +245,11 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void {
|
||||
if (resolvedPtyId) {
|
||||
session.reconcilePtySizeAfterSpawn(resolvedPtyId, session.cols, session.rows)
|
||||
}
|
||||
if (!resolvedPtyId) {
|
||||
clearPreSignaledSerializer()
|
||||
session.finishReattachLiveDataDeferral(false, outputCallbacks.generation)
|
||||
return null
|
||||
}
|
||||
const gen = await preSignalPromise
|
||||
// Why: a bound PTY owns the renderer serializer even when the declare was
|
||||
// rejected; the gen token only settles or clears the pending declaration.
|
||||
@@ -206,8 +260,6 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void {
|
||||
if (typeof gen === 'number') {
|
||||
void window.api.pty.settlePaneSerializer(session.cacheKey, gen).catch(() => {})
|
||||
}
|
||||
} else if (typeof gen === 'number') {
|
||||
void window.api.pty.clearPendingPaneSerializer(session.cacheKey, gen).catch(() => {})
|
||||
}
|
||||
if (resolvedPtyId && session.connectionId) {
|
||||
if (
|
||||
@@ -229,15 +281,13 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void {
|
||||
) {
|
||||
session.clearRegisteredStartupLaunchConfig()
|
||||
}
|
||||
const gen = await preSignalPromise
|
||||
if (typeof gen === 'number') {
|
||||
void window.api.pty.clearPendingPaneSerializer(session.cacheKey, gen).catch(() => {})
|
||||
}
|
||||
clearPreSignaledSerializer()
|
||||
return null
|
||||
})
|
||||
.finally(() => {
|
||||
if (pendingSpawnByPaneKey.get(session.pendingSpawnKey) === trackedPromise) {
|
||||
pendingSpawnByPaneKey.delete(session.pendingSpawnKey)
|
||||
pendingSpawnGenerationByPaneKey.delete(session.pendingSpawnKey)
|
||||
}
|
||||
})
|
||||
session.armDirectSshPaneRetryTimeout(trackedPromise, session.directSshRetryAttempt)
|
||||
@@ -259,6 +309,7 @@ export function bindStartFreshSpawn(session: ConnectPanePtySession): void {
|
||||
// Why: split panes in the same tab can spawn concurrently. Key by pane
|
||||
// as well as tab so a remount cannot attach to a sibling setup pane's PTY.
|
||||
pendingSpawnByPaneKey.set(session.pendingSpawnKey, trackedPromise)
|
||||
pendingSpawnGenerationByPaneKey.set(session.pendingSpawnKey, session.tabGeneration)
|
||||
return trackedPromise
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { e2eConfig } from '@/lib/e2e-config'
|
||||
|
||||
export const pendingSpawnByPaneKey = new Map<string, Promise<string | null>>()
|
||||
export const pendingSpawnGenerationByPaneKey = new Map<string, number>()
|
||||
export const SSH_SESSION_EXPIRED_ERROR = 'SSH_SESSION_EXPIRED'
|
||||
// Why: relay requests expire at 30s; leave one second for their fallback before re-arming locally.
|
||||
export const DIRECT_SSH_PANE_RETRY_SETTLEMENT_TIMEOUT_MS = 31_000
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { resolveTerminalTabId } from './terminal-tab-id'
|
||||
|
||||
describe('resolveTerminalTabId', () => {
|
||||
it('maps a unified terminal tab id to its legacy owner id', () => {
|
||||
const getTab = vi.fn(() => ({ contentType: 'terminal', entityId: 'legacy-tab' }))
|
||||
|
||||
expect(resolveTerminalTabId({ getTab }, 'unified-tab')).toBe('legacy-tab')
|
||||
expect(getTab).toHaveBeenCalledWith('unified-tab')
|
||||
})
|
||||
|
||||
it('keeps non-terminal and unknown ids unchanged', () => {
|
||||
expect(
|
||||
resolveTerminalTabId(
|
||||
{ getTab: () => ({ contentType: 'editor', entityId: '/tmp/file.ts' }) },
|
||||
'editor-tab'
|
||||
)
|
||||
).toBe('editor-tab')
|
||||
expect(resolveTerminalTabId({}, 'legacy-tab')).toBe('legacy-tab')
|
||||
})
|
||||
|
||||
it('keeps an exact terminal owner ahead of a stale unified alias', () => {
|
||||
expect(
|
||||
resolveTerminalTabId(
|
||||
{
|
||||
getTab: () => ({ contentType: 'terminal', entityId: 'old-owner' }),
|
||||
hasTerminalTab: (tabId) => tabId === 'live-owner'
|
||||
},
|
||||
'live-owner'
|
||||
)
|
||||
).toBe('live-owner')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,15 @@
|
||||
type TerminalTabLookup = {
|
||||
getTab?: (tabId: string) => { contentType: string; entityId: string } | null
|
||||
hasTerminalTab?: (tabId: string) => boolean
|
||||
}
|
||||
|
||||
/** Resolve a renderer tab id to the legacy terminal-tab id used by PTY state. */
|
||||
export function resolveTerminalTabId(state: TerminalTabLookup, tabId: string): string {
|
||||
// The terminal-tab table is authoritative when both id forms are briefly present.
|
||||
// A stale unified entry must not redirect a live PTY owner to an older entity id.
|
||||
if (state.hasTerminalTab?.(tabId)) {
|
||||
return tabId
|
||||
}
|
||||
const unifiedTab = state.getTab?.(tabId)
|
||||
return unifiedTab?.contentType === 'terminal' ? unifiedTab.entityId : tabId
|
||||
}
|
||||
@@ -38,6 +38,18 @@ describe('createIpcPtyTransport', () => {
|
||||
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<typeof vi.fn>
|
||||
const transport = createIpcPtyTransport({})
|
||||
|
||||
await expect(
|
||||
transport.connect({ url: '', shouldContinue: () => false, callbacks: {} })
|
||||
).resolves.toBeUndefined()
|
||||
|
||||
expect(spawn).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('threads provider command ownership through the spawn IPC', async () => {
|
||||
const { createIpcPtyTransport } = await import('./pty-transport')
|
||||
const transport = createIpcPtyTransport({
|
||||
|
||||
@@ -154,6 +154,8 @@ export type PtyTransport = {
|
||||
startupCommandDelivery?: StartupCommandDelivery
|
||||
/** Reject a stale restored identity before this transport can publish global PTY handlers. */
|
||||
admitPtyId?: (ptyId: string) => boolean
|
||||
/** Reject a stale pane after any pre-spawn test gate but before creating a PTY. */
|
||||
shouldContinue?: () => boolean
|
||||
callbacks: PtyCallbacks
|
||||
}) => void | Promise<void | string | PtyConnectResult>
|
||||
attach: (options: {
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
isPreHandlerPtyStateDiscarded
|
||||
} from './pty-pre-handler-buffer'
|
||||
import { createPtyInputWriteQueue } from './pty-input-write-queue'
|
||||
import { waitAtTerminalPtyPreSpawnE2EBarrier } from './terminal-pty-pre-spawn-e2e-barrier'
|
||||
import type { PtyDataMeta } from './pty-dispatcher'
|
||||
import type { IpcPtyTransportOptions, PtyConnectResult, PtyTransport } from './pty-transport-types'
|
||||
import { createBellDetector } from '../../../../shared/terminal-bell-detector'
|
||||
@@ -807,6 +808,16 @@ export function createIpcPtyTransport(opts: IpcPtyTransportOptions = {}): PtyTra
|
||||
}
|
||||
|
||||
try {
|
||||
const preSpawnBarrier = waitAtTerminalPtyPreSpawnE2EBarrier()
|
||||
if (preSpawnBarrier) {
|
||||
await preSpawnBarrier
|
||||
if (destroyed) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if (options.shouldContinue && !options.shouldContinue()) {
|
||||
return
|
||||
}
|
||||
// Why: cwd fallback is only for fresh local spawns — reattach keeps the session's cwd and SSH transports resolve cwd on the remote host.
|
||||
const shouldSendLocalCwdFallback =
|
||||
cwdFallback === 'worktree' && !connectionId && !admittedSessionId
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import { e2eConfig } from '@/lib/e2e-config'
|
||||
|
||||
type BarrierState = {
|
||||
blocked: boolean
|
||||
release: () => void
|
||||
released: Promise<void>
|
||||
reportBlocked: () => void
|
||||
blockedReported: Promise<void>
|
||||
}
|
||||
|
||||
export type TerminalPtyPreSpawnE2EBarrier = {
|
||||
arm: () => void
|
||||
waitUntilBlocked: () => Promise<void>
|
||||
release: () => void
|
||||
status: () => 'idle' | 'armed' | 'blocked'
|
||||
}
|
||||
|
||||
let barrier: BarrierState | null = null
|
||||
|
||||
function createBarrier(): BarrierState {
|
||||
let release = (): void => {}
|
||||
let reportBlocked = (): void => {}
|
||||
const released = new Promise<void>((resolve) => {
|
||||
release = resolve
|
||||
})
|
||||
const blockedReported = new Promise<void>((resolve) => {
|
||||
reportBlocked = resolve
|
||||
})
|
||||
return { blocked: false, release, released, reportBlocked, blockedReported }
|
||||
}
|
||||
|
||||
function exposeBarrier(): void {
|
||||
if (!e2eConfig.exposeStore || typeof window === 'undefined') {
|
||||
return
|
||||
}
|
||||
window.__terminalPtyPreSpawnE2EBarrier ??= {
|
||||
arm: () => {
|
||||
if (barrier) {
|
||||
throw new Error('Terminal PTY pre-spawn E2E barrier is already armed')
|
||||
}
|
||||
barrier = createBarrier()
|
||||
},
|
||||
waitUntilBlocked: async () => {
|
||||
if (!barrier) {
|
||||
throw new Error('Terminal PTY pre-spawn E2E barrier is not armed')
|
||||
}
|
||||
await barrier.blockedReported
|
||||
},
|
||||
release: () => {
|
||||
barrier?.release()
|
||||
},
|
||||
status: () => (barrier ? (barrier.blocked ? 'blocked' : 'armed') : 'idle')
|
||||
}
|
||||
}
|
||||
|
||||
export function waitAtTerminalPtyPreSpawnE2EBarrier(): Promise<void> | null {
|
||||
if (!e2eConfig.exposeStore || typeof window === 'undefined') {
|
||||
return null
|
||||
}
|
||||
exposeBarrier()
|
||||
const current = barrier
|
||||
if (!current || current.blocked) {
|
||||
return null
|
||||
}
|
||||
current.blocked = true
|
||||
current.reportBlocked()
|
||||
return current.released.then(() => {
|
||||
if (barrier === current) {
|
||||
barrier = null
|
||||
}
|
||||
})
|
||||
}
|
||||
Vendored
+2
@@ -5,6 +5,7 @@ import type { OnboardingFeatureSetupDeps } from '@/components/onboarding/onboard
|
||||
import type { languages } from 'monaco-editor'
|
||||
import type { MonacoE2EProbe } from './components/editor/monaco-e2e-probe'
|
||||
import type { TerminalWorktreeParkingDebugVerdict } from './components/terminal-pane/terminal-parking-e2e-overrides'
|
||||
import type { TerminalPtyPreSpawnE2EBarrier } from './components/terminal-pane/terminal-pty-pre-spawn-e2e-barrier'
|
||||
|
||||
declare module 'monaco-editor/esm/vs/basic-languages/python/python.js' {
|
||||
export const conf: languages.LanguageConfiguration
|
||||
@@ -77,6 +78,7 @@ declare global {
|
||||
}
|
||||
__monacoEditorE2E?: MonacoE2EProbe
|
||||
__e2ePtyAppliedSizeReadDelayMs?: number
|
||||
__terminalPtyPreSpawnE2EBarrier?: TerminalPtyPreSpawnE2EBarrier
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import { getWorktreeMapFromState, getRepoMapFromState } from '@/store/selectors'
|
||||
import { applyUIZoom } from '@/lib/ui-zoom'
|
||||
import { activateAndRevealWorktree, activateAndRevealWorkspace } from '@/lib/worktree-activation'
|
||||
import { buildLinearIssueLinkedWorkItem } from '@/lib/linear-linked-work-item'
|
||||
import { runWorktreeDelete } from '@/components/sidebar/delete-worktree-flow'
|
||||
import { deleteHoveredWorkspaceImmediately } from '@/components/sidebar/hovered-workspace-delete'
|
||||
import { runSleepWorktree } from '@/components/sidebar/sleep-worktree-flow'
|
||||
import { createBackgroundSleepingAgentWakeDispatcher } from '@/lib/wake-sleeping-agents-in-background'
|
||||
import { TOGGLE_WORKSPACE_BOARD_EVENT } from '@/components/sidebar/useWorkspaceBoardPanel'
|
||||
@@ -1431,20 +1431,10 @@ export function useIpcEvents(): void {
|
||||
if (window.api.ui.onDeleteCurrentWorkspace) {
|
||||
unsubs.push(
|
||||
window.api.ui.onDeleteCurrentWorkspace(() => {
|
||||
const store = useAppStore.getState()
|
||||
if (
|
||||
store.activeModal !== 'none' ||
|
||||
store.activeView !== 'terminal' ||
|
||||
!store.activeWorktreeId
|
||||
) {
|
||||
if (isFloatingWorkspacePanelFocused()) {
|
||||
return
|
||||
}
|
||||
runWorktreeDelete(
|
||||
store.activeWorktreeId,
|
||||
store.activeWorkspaceExecutionHostId
|
||||
? { expectedHostId: store.activeWorkspaceExecutionHostId }
|
||||
: {}
|
||||
)
|
||||
deleteHoveredWorkspaceImmediately(useAppStore.getState())
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ type IndexedProjectGroupOwnerResolution =
|
||||
| { kind: 'missing' }
|
||||
| { kind: 'ambiguous' }
|
||||
|
||||
function catalogOwnerHostId(owner: {
|
||||
export function getCatalogOwnerHostId(owner: {
|
||||
connectionId?: string | null
|
||||
executionHostId?: string | null
|
||||
}): ExecutionHostId {
|
||||
@@ -74,11 +74,11 @@ function buildCatalogOwnerIndex<
|
||||
const next = new Map<string, { kind: 'resolved'; owner: T } | { kind: 'ambiguous' }>()
|
||||
for (const record of records) {
|
||||
const id = record.id
|
||||
const hostId = catalogOwnerHostId(record)
|
||||
const hostId = getCatalogOwnerHostId(record)
|
||||
const current = next.get(id)
|
||||
if (!current) {
|
||||
next.set(id, { kind: 'resolved', owner: record })
|
||||
} else if (current.kind === 'resolved' && catalogOwnerHostId(current.owner) !== hostId) {
|
||||
} else if (current.kind === 'resolved' && getCatalogOwnerHostId(current.owner) !== hostId) {
|
||||
next.set(id, { kind: 'ambiguous' })
|
||||
}
|
||||
next.set(`${id}\0${hostId}`, {
|
||||
|
||||
@@ -427,5 +427,39 @@ describe('folder workspace owner-routed mutations', () => {
|
||||
timeoutMs: 15_000
|
||||
})
|
||||
expect(folderWorkspacesDelete).not.toHaveBeenCalled()
|
||||
expect(store.getState().folderWorkspaces).toEqual([])
|
||||
})
|
||||
|
||||
it('deletes only the host-qualified folder when ids collide', async () => {
|
||||
const localFolder = makeFolderWorkspace({ executionHostId: 'local' })
|
||||
const runtimeFolder = makeFolderWorkspace({ executionHostId: 'runtime:env-owner' })
|
||||
runtimeEnvironmentCall.mockResolvedValue({
|
||||
id: 'rpc-delete-folder',
|
||||
ok: true,
|
||||
result: { deleted: true },
|
||||
_meta: { runtimeId: 'runtime-owner' }
|
||||
})
|
||||
const store = createTestStore()
|
||||
store.setState({
|
||||
activeWorktreeId: `folder:${runtimeFolder.id}`,
|
||||
activeWorkspaceExecutionHostId: 'runtime:env-owner',
|
||||
settings: { activeRuntimeEnvironmentId: 'env-owner' } as never,
|
||||
projectGroups: [{ ...projectGroup, executionHostId: 'local' }],
|
||||
folderWorkspaces: [localFolder, runtimeFolder]
|
||||
})
|
||||
|
||||
await expect(
|
||||
store
|
||||
.getState()
|
||||
.deleteFolderWorkspace(runtimeFolder.id, { executionHostId: 'runtime:env-owner' })
|
||||
).resolves.toBe(true)
|
||||
|
||||
expect(runtimeEnvironmentCall).toHaveBeenCalledWith({
|
||||
selector: 'env-owner',
|
||||
method: 'folderWorkspace.delete',
|
||||
params: { folderWorkspaceId: runtimeFolder.id },
|
||||
timeoutMs: 15_000
|
||||
})
|
||||
expect(store.getState().folderWorkspaces).toEqual([localFolder])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -113,6 +113,7 @@ import { getEnvironmentSshStateGeneration } from './runtime-environment-ssh'
|
||||
import { getRuntimeEnvironmentConnectionGeneration } from './runtime-status'
|
||||
import {
|
||||
findFolderWorkspaceOwner,
|
||||
getExecutionHostIdForFolderWorkspace,
|
||||
getRuntimeEnvironmentIdForFolderWorkspace
|
||||
} from '@/lib/folder-workspace-runtime-owner'
|
||||
import {
|
||||
@@ -1909,7 +1910,10 @@ export type RepoSlice = {
|
||||
updates: FolderWorkspaceUpdates,
|
||||
options?: { executionHostId?: ExecutionHostId }
|
||||
) => Promise<boolean>
|
||||
deleteFolderWorkspace: (folderWorkspaceId: string) => Promise<boolean>
|
||||
deleteFolderWorkspace: (
|
||||
folderWorkspaceId: string,
|
||||
options?: { executionHostId?: ExecutionHostId }
|
||||
) => Promise<boolean>
|
||||
// options.hostId targets a specific host's row + RPC target when the id exists on multiple hosts; else the group's own host owns the call.
|
||||
updateProjectGroup: (
|
||||
groupId: string,
|
||||
@@ -2981,12 +2985,22 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
|
||||
}
|
||||
},
|
||||
|
||||
deleteFolderWorkspace: async (folderWorkspaceId) => {
|
||||
deleteFolderWorkspace: async (folderWorkspaceId, options) => {
|
||||
const state = get()
|
||||
if (!findFolderWorkspaceOwner(state, folderWorkspaceId)) {
|
||||
const executionHostId = options?.executionHostId
|
||||
if (!findFolderWorkspaceOwner(state, folderWorkspaceId, executionHostId)) {
|
||||
return false
|
||||
}
|
||||
const runtimeEnvironmentId = getRuntimeEnvironmentIdForFolderWorkspace(state, folderWorkspaceId)
|
||||
const ownerHostId = getExecutionHostIdForFolderWorkspace(
|
||||
state,
|
||||
folderWorkspaceId,
|
||||
executionHostId
|
||||
)
|
||||
const runtimeEnvironmentId = getRuntimeEnvironmentIdForFolderWorkspace(
|
||||
state,
|
||||
folderWorkspaceId,
|
||||
executionHostId
|
||||
)
|
||||
try {
|
||||
// Why: deletion targets the folder's owner; focus may be on a different host.
|
||||
const target = getActiveRuntimeTarget({ activeRuntimeEnvironmentId: runtimeEnvironmentId })
|
||||
@@ -3007,11 +3021,15 @@ export const createRepoSlice: StateCreator<AppState, [], [], RepoSlice> = (set,
|
||||
const workspaceKey = folderWorkspaceKey(folderWorkspaceId)
|
||||
set((s) => ({
|
||||
folderWorkspaces: s.folderWorkspaces.filter(
|
||||
(workspace) => workspace.id !== folderWorkspaceId
|
||||
(workspace) =>
|
||||
workspace.id !== folderWorkspaceId ||
|
||||
getFolderWorkspaceHostId(workspace, s.projectGroups) !== ownerHostId
|
||||
),
|
||||
folderWorkspacePathStatuses: {}
|
||||
}))
|
||||
get().purgeWorktreeTerminalState([workspaceKey])
|
||||
if (!get().folderWorkspaces.some((workspace) => workspace.id === folderWorkspaceId)) {
|
||||
get().purgeWorktreeTerminalState([workspaceKey])
|
||||
}
|
||||
return true
|
||||
} catch (err) {
|
||||
console.error('Failed to delete folder workspace:', err)
|
||||
|
||||
@@ -28,6 +28,20 @@ describe('remountTerminalTabForRecovery', () => {
|
||||
expect(after?.pendingActivationSpawn).toBeTruthy()
|
||||
})
|
||||
|
||||
it('gives a remounted pane a distinct queued startup owner', () => {
|
||||
const store = createTestStore()
|
||||
const tabId = seedWorktreeWithTab(store)
|
||||
const startup = { command: 'echo recover' }
|
||||
store.getState().queueTabStartupCommand(tabId, startup)
|
||||
const before = store.getState().pendingStartupByTabId[tabId]
|
||||
|
||||
expect(store.getState().remountTerminalTabForRecovery(tabId)).toBe(true)
|
||||
|
||||
const after = store.getState().pendingStartupByTabId[tabId]
|
||||
expect(after).toEqual(before)
|
||||
expect(after).not.toBe(before)
|
||||
})
|
||||
|
||||
it('leaves sibling tabs untouched', () => {
|
||||
const store = createTestStore()
|
||||
const tabId = seedWorktreeWithTab(store)
|
||||
|
||||
@@ -649,6 +649,8 @@ export type TerminalSlice = {
|
||||
setTabBarOrder: (worktreeId: string, order: string[]) => void
|
||||
setActiveTab: (tabId: string) => void
|
||||
setActiveTabForWorktree: (worktreeId: string, tabId: string) => void
|
||||
/** Resolve the canonical legacy terminal-tab owner key for renderer lifecycle guards. */
|
||||
getTerminalTabOwnerWorktreeId?: (tabId: string) => string | null
|
||||
updateTabTitle: (tabId: string, title: string) => void
|
||||
updateTabTitles: (updates: readonly TerminalTabTitleUpdate[]) => void
|
||||
setAiVaultTabTitle: (tabId: string, aiVaultTitle: AiVaultSessionTitle | null) => void
|
||||
@@ -1498,6 +1500,9 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
return tab
|
||||
},
|
||||
|
||||
getTerminalTabOwnerWorktreeId: (tabId) =>
|
||||
getTerminalTabOwnerWorktreeId(get().tabsByWorktree, tabId),
|
||||
|
||||
openNewTerminalTabInActiveWorkspace: async (groupId) => {
|
||||
const state = get()
|
||||
const worktreeId = state.activeWorktreeId
|
||||
|
||||
@@ -30,6 +30,7 @@ export function createRemountTerminalTabForRecovery(
|
||||
}
|
||||
const tab = tabs[index]
|
||||
const nextTabs = tabs.slice()
|
||||
const pendingStartup = s.pendingStartupByTabId[tabId]
|
||||
nextTabs[index] = {
|
||||
...tab,
|
||||
// Why: bump generation to remount a pane whose renderer died while its PTY stayed alive, so it reattaches, not spawns.
|
||||
@@ -44,7 +45,17 @@ export function createRemountTerminalTabForRecovery(
|
||||
tabsByWorktree: {
|
||||
...s.tabsByWorktree,
|
||||
[worktreeId]: nextTabs
|
||||
}
|
||||
},
|
||||
...(pendingStartup
|
||||
? {
|
||||
// Why: a remounted pane must own a distinct one-shot startup record so a stale
|
||||
// pane cannot consume the successor's command during teardown.
|
||||
pendingStartupByTabId: {
|
||||
...s.pendingStartupByTabId,
|
||||
[tabId]: { ...pendingStartup }
|
||||
}
|
||||
}
|
||||
: {})
|
||||
}
|
||||
}
|
||||
return {}
|
||||
|
||||
@@ -144,6 +144,8 @@ describe('keybindings', () => {
|
||||
it('formats keybindings with platform labels', () => {
|
||||
expect(formatKeybindingList(['Mod+Shift+J'], 'darwin')).toBe('⌘⇧J')
|
||||
expect(formatKeybindingList(['Mod+Shift+J'], 'linux')).toBe('Ctrl+Shift+J')
|
||||
expect(formatKeybindingList(['Mod+Shift+Backspace'], 'darwin')).toBe('⌘⇧⌫')
|
||||
expect(formatKeybindingList(['Mod+Shift+Backspace'], 'linux')).toBe('Ctrl+Shift+Backspace')
|
||||
expect(formatKeybindingList([], 'win32')).toBe('Unassigned')
|
||||
})
|
||||
|
||||
|
||||
@@ -56,7 +56,7 @@ describe('keybindings', () => {
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps workspace delete unassigned until users customize it', () => {
|
||||
it('binds immediate workspace delete without claiming terminal split right', () => {
|
||||
const binding = {
|
||||
key: 'Backspace',
|
||||
code: 'Backspace',
|
||||
@@ -66,13 +66,28 @@ describe('keybindings', () => {
|
||||
shift: true
|
||||
}
|
||||
|
||||
expect(getEffectiveKeybindingsForAction('workspace.delete', 'linux')).toEqual([])
|
||||
expect(keybindingMatchesAction('workspace.delete', binding, 'linux')).toBe(false)
|
||||
expect(getEffectiveKeybindingsForAction('workspace.delete', 'darwin')).toEqual([
|
||||
'Mod+Shift+Backspace'
|
||||
])
|
||||
expect(getEffectiveKeybindingsForAction('workspace.delete', 'linux')).toEqual([
|
||||
'Mod+Shift+Backspace'
|
||||
])
|
||||
expect(getEffectiveKeybindingsForAction('workspace.delete', 'win32')).toEqual([
|
||||
'Mod+Shift+Backspace'
|
||||
])
|
||||
expect(keybindingMatchesAction('workspace.delete', binding, 'linux')).toBe(true)
|
||||
expect(
|
||||
keybindingMatchesAction('workspace.delete', binding, 'linux', {
|
||||
'workspace.delete': ['Mod+Shift+Backspace']
|
||||
'workspace.delete': []
|
||||
})
|
||||
).toBe(true)
|
||||
).toBe(false)
|
||||
expect(
|
||||
keybindingMatchesAction(
|
||||
'workspace.delete',
|
||||
{ key: 'd', code: 'KeyD', control: false, meta: true, alt: true, shift: false },
|
||||
'darwin'
|
||||
)
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps workspace board unassigned until users customize it', () => {
|
||||
|
||||
@@ -293,8 +293,8 @@ export const KEYBINDING_DEFINITIONS: readonly KeybindingDefinition[] = [
|
||||
'remove',
|
||||
'trash'
|
||||
],
|
||||
// Why: ship now without a default chord; user overrides still win when a future default is assigned.
|
||||
defaultBindings: platformBindings([]),
|
||||
// Why: Backspace avoids the terminal pane's D-based split shortcuts on every platform.
|
||||
defaultBindings: platformBindings(['Mod+Shift+Backspace']),
|
||||
allowInTerminal: true
|
||||
},
|
||||
{
|
||||
@@ -2281,7 +2281,7 @@ export function formatKeybinding(binding: string, platform: NodeJS.Platform): st
|
||||
if (parsed.shift) {
|
||||
parts.push(isMac ? '⇧' : 'Shift')
|
||||
}
|
||||
parts.push(formatKeyToken(parsed.key))
|
||||
parts.push(formatKeyToken(parsed.key, isMac))
|
||||
return parts
|
||||
}
|
||||
|
||||
@@ -2317,7 +2317,7 @@ export function findKeybindingActionsForBinding(
|
||||
).map((definition) => definition.id)
|
||||
}
|
||||
|
||||
function formatKeyToken(token: string): string {
|
||||
function formatKeyToken(token: string, isMac: boolean): string {
|
||||
const labels: Record<string, string> = {
|
||||
BracketLeft: '[',
|
||||
BracketRight: ']',
|
||||
@@ -2341,7 +2341,7 @@ function formatKeyToken(token: string): string {
|
||||
Quote: "'",
|
||||
Backquote: '`',
|
||||
Enter: 'Enter',
|
||||
Backspace: 'Backspace',
|
||||
Backspace: isMac ? '⌫' : 'Backspace',
|
||||
Delete: 'Delete',
|
||||
Insert: 'Insert',
|
||||
Tab: 'Tab',
|
||||
|
||||
@@ -377,7 +377,7 @@ describe('resolveWindowShortcutAction', () => {
|
||||
).toEqual({ type: 'openTasks' })
|
||||
})
|
||||
|
||||
it('leaves workspace delete unbound by default but honors custom terminal-active bindings', () => {
|
||||
it('resolves workspace delete by default and honors custom terminal-active bindings', () => {
|
||||
const input = {
|
||||
code: 'Backspace',
|
||||
key: 'Backspace',
|
||||
@@ -387,17 +387,18 @@ describe('resolveWindowShortcutAction', () => {
|
||||
shift: true
|
||||
}
|
||||
|
||||
expect(resolveWindowShortcutAction(input, 'linux')).toBeNull()
|
||||
expect(resolveWindowShortcutAction(input, 'linux')).toEqual({ type: 'deleteCurrentWorkspace' })
|
||||
const customInput = { ...input, code: 'KeyX', key: 'x', alt: true, shift: false }
|
||||
expect(
|
||||
resolveWindowShortcutAction(input, 'linux', {
|
||||
'workspace.delete': ['Mod+Shift+Backspace']
|
||||
resolveWindowShortcutAction(customInput, 'linux', {
|
||||
'workspace.delete': ['Mod+Alt+X']
|
||||
})
|
||||
).toEqual({ type: 'deleteCurrentWorkspace' })
|
||||
expect(
|
||||
resolveWindowShortcutAction(
|
||||
input,
|
||||
customInput,
|
||||
'linux',
|
||||
{ 'workspace.delete': ['Mod+Shift+Backspace'] },
|
||||
{ 'workspace.delete': ['Mod+Alt+X'] },
|
||||
{ context: 'terminal', terminalShortcutPolicy: 'terminal-first' }
|
||||
)
|
||||
).toEqual({ type: 'deleteCurrentWorkspace' })
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'
|
||||
import { toRuntimeExecutionHostId, toSshExecutionHostId } from '../execution-host'
|
||||
import {
|
||||
composeWorktreeHostIdentity,
|
||||
getExecutionHostIdFromWorktreeHostIdentity,
|
||||
getWorktreeHostIdentity,
|
||||
getWorktreeIdFromHostIdentity
|
||||
} from './host-qualified-identity'
|
||||
@@ -58,4 +59,29 @@ describe('worktree host identity', () => {
|
||||
expect(toSshExecutionHostId('we|rd')).not.toContain('|')
|
||||
expect(toRuntimeExecutionHostId('we|rd')).not.toContain('|')
|
||||
})
|
||||
|
||||
it('rejects identities without a host separator', () => {
|
||||
expect(getExecutionHostIdFromWorktreeHostIdentity('ssh:build-box')).toBeUndefined()
|
||||
})
|
||||
|
||||
// An unqualified row must not be assumed local: a destructive action keyed off
|
||||
// this would then run against the wrong host.
|
||||
it('leaves an unqualified identity without a host', () => {
|
||||
expect(
|
||||
getExecutionHostIdFromWorktreeHostIdentity(
|
||||
composeWorktreeHostIdentity(undefined, WORKTREE_ID)
|
||||
)
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
it('recovers the host from a qualified identity', () => {
|
||||
expect(
|
||||
getExecutionHostIdFromWorktreeHostIdentity(composeWorktreeHostIdentity('local', WORKTREE_ID))
|
||||
).toBe('local')
|
||||
expect(
|
||||
getExecutionHostIdFromWorktreeHostIdentity(
|
||||
composeWorktreeHostIdentity(toSshExecutionHostId('build-box'), WORKTREE_ID)
|
||||
)
|
||||
).toBe(toSshExecutionHostId('build-box'))
|
||||
})
|
||||
})
|
||||
|
||||
@@ -38,6 +38,23 @@ export function composeWorktreeHostIdentity(
|
||||
return `${hostId ?? ''}${HOST_SEPARATOR}${worktreeId}`
|
||||
}
|
||||
|
||||
/**
|
||||
* The host back out of an identity, when the identity names one.
|
||||
*
|
||||
* An empty prefix (`|<worktreeId>`) stays undefined rather than defaulting to
|
||||
* `local`: an unqualified row may be on any host, and callers use this to pick
|
||||
* the host a destructive action runs against.
|
||||
*/
|
||||
export function getExecutionHostIdFromWorktreeHostIdentity(
|
||||
identity: string
|
||||
): ExecutionHostId | undefined {
|
||||
const separatorIndex = identity.indexOf(HOST_SEPARATOR)
|
||||
if (separatorIndex <= 0) {
|
||||
return undefined
|
||||
}
|
||||
return parseExecutionHostId(identity.slice(0, separatorIndex))?.id
|
||||
}
|
||||
|
||||
/**
|
||||
* The workspace id back out of an identity.
|
||||
*
|
||||
|
||||
@@ -5,10 +5,48 @@
|
||||
* test run so we don't litter the user's /tmp with test directories.
|
||||
*/
|
||||
|
||||
import { readFileSync, existsSync, rmSync, readdirSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { readFileSync, existsSync, realpathSync, rmSync } from 'node:fs'
|
||||
import { TEST_REPO_PATH_FILE } from './global-setup'
|
||||
|
||||
export function linkedWorktreePaths(testRepoDir: string): string[] {
|
||||
const root = realpathSync(testRepoDir)
|
||||
const output = execFileSync('git', ['-C', testRepoDir, 'worktree', 'list', '--porcelain'], {
|
||||
encoding: 'utf8'
|
||||
})
|
||||
const linked = new Set<string>()
|
||||
for (const line of output.split(/\r?\n/)) {
|
||||
if (!line.startsWith('worktree ')) {
|
||||
continue
|
||||
}
|
||||
const recordedPath = line.slice('worktree '.length)
|
||||
if (!existsSync(recordedPath)) {
|
||||
continue
|
||||
}
|
||||
const canonicalPath = realpathSync(recordedPath)
|
||||
if (canonicalPath !== root) {
|
||||
linked.add(canonicalPath)
|
||||
}
|
||||
}
|
||||
return [...linked]
|
||||
}
|
||||
|
||||
export function cleanupTestRepository(testRepoDir: string): void {
|
||||
const root = realpathSync(testRepoDir)
|
||||
let worktreePaths: string[] = []
|
||||
try {
|
||||
worktreePaths = linkedWorktreePaths(root)
|
||||
} catch {
|
||||
// The isolated repo is still safe to remove when Git metadata is unreadable.
|
||||
}
|
||||
for (const worktreeDir of worktreePaths) {
|
||||
if (existsSync(worktreeDir)) {
|
||||
rmSync(worktreeDir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
|
||||
export default function globalTeardown(): void {
|
||||
if (!existsSync(TEST_REPO_PATH_FILE)) {
|
||||
return
|
||||
@@ -16,22 +54,7 @@ export default function globalTeardown(): void {
|
||||
|
||||
const testRepoDir = readFileSync(TEST_REPO_PATH_FILE, 'utf-8').trim()
|
||||
if (testRepoDir && existsSync(testRepoDir)) {
|
||||
// Why: git worktree add creates directories as siblings. Clean up any
|
||||
// seeded or test-created worktrees in the same parent so reruns remain
|
||||
// idempotent and do not leak temp repos into /tmp.
|
||||
const parentDir = path.dirname(testRepoDir)
|
||||
try {
|
||||
const siblings = readdirSync(parentDir)
|
||||
for (const name of siblings) {
|
||||
if (name.startsWith('orca-e2e-worktree-') || name.startsWith('e2e-test-')) {
|
||||
rmSync(path.join(parentDir, name), { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Best-effort cleanup of worktrees
|
||||
}
|
||||
|
||||
rmSync(testRepoDir, { recursive: true, force: true })
|
||||
cleanupTestRepository(testRepoDir)
|
||||
console.error(`[e2e] Cleaned up test repo at ${testRepoDir}`)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { cleanupTestRepository, linkedWorktreePaths } from './global-teardown'
|
||||
|
||||
const roots: string[] = []
|
||||
|
||||
function git(cwd: string, args: string[]): void {
|
||||
execFileSync('git', ['-C', cwd, ...args], { stdio: 'pipe' })
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
describe('E2E global teardown ownership', () => {
|
||||
it('removes every linked run worktree and preserves unrelated siblings', () => {
|
||||
const root = mkdtempSync(path.join(os.tmpdir(), 'orca-e2e-teardown-contract-'))
|
||||
roots.push(root)
|
||||
const repoPath = path.join(root, 'orca-e2e-repo-run')
|
||||
const firstWorktreePath = path.join(root, 'orca-e2e-worktree-owned')
|
||||
const secondWorktreePath = path.join(root, 'e2e-test-owned')
|
||||
const concurrentWorktreePath = path.join(root, 'orca-e2e-worktree-concurrent')
|
||||
const unrelatedTestPath = path.join(root, 'e2e-test-unrelated')
|
||||
mkdirSync(repoPath)
|
||||
mkdirSync(concurrentWorktreePath)
|
||||
mkdirSync(unrelatedTestPath)
|
||||
writeFileSync(path.join(repoPath, 'README.md'), 'fixture\n')
|
||||
git(repoPath, ['init'])
|
||||
git(repoPath, ['config', 'user.email', 'e2e@test.local'])
|
||||
git(repoPath, ['config', 'user.name', 'E2E Test'])
|
||||
git(repoPath, ['add', 'README.md'])
|
||||
git(repoPath, ['commit', '-m', 'seed'])
|
||||
git(repoPath, ['worktree', 'add', '-b', 'first-owned', firstWorktreePath])
|
||||
git(repoPath, ['worktree', 'add', '-b', 'second-owned', secondWorktreePath])
|
||||
|
||||
expect(new Set(linkedWorktreePaths(repoPath))).toEqual(
|
||||
new Set([realpathSync(firstWorktreePath), realpathSync(secondWorktreePath)])
|
||||
)
|
||||
cleanupTestRepository(repoPath)
|
||||
|
||||
expect(existsSync(repoPath)).toBe(false)
|
||||
expect(existsSync(firstWorktreePath)).toBe(false)
|
||||
expect(existsSync(secondWorktreePath)).toBe(false)
|
||||
expect(existsSync(concurrentWorktreePath)).toBe(true)
|
||||
expect(existsSync(unrelatedTestPath)).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,349 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { existsSync, readFileSync, rmSync } from 'node:fs'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { stripAnsiEscapeSequences } from '../../src/shared/ansi-escape-sequences'
|
||||
import { test, expect } from './helpers/orca-app'
|
||||
import {
|
||||
runNodeScriptInTerminal,
|
||||
stageNodeScriptForTerminal
|
||||
} from './helpers/run-node-script-in-terminal'
|
||||
import { registerTerminalPaneMountReadiness } from './helpers/terminal-pane-mount-readiness'
|
||||
import {
|
||||
focusActiveTerminalInput,
|
||||
getTerminalContent,
|
||||
waitForPaneIdentitySnapshot,
|
||||
waitForTerminalOutput
|
||||
} from './helpers/terminal'
|
||||
|
||||
type QuickCommandIdentity = {
|
||||
marker: string
|
||||
paneKey: string
|
||||
pid: number
|
||||
tabId: string
|
||||
}
|
||||
|
||||
type QueueObservation = {
|
||||
pending: boolean
|
||||
ptyIds: string[]
|
||||
}
|
||||
|
||||
type QueueObservationWindow = Window & {
|
||||
__quickCommandQueueObservations?: QueueObservation[]
|
||||
__stopQuickCommandQueueObservations?: () => void
|
||||
}
|
||||
|
||||
function exactMarkerLineCount(content: string, marker: string): number {
|
||||
return stripAnsiEscapeSequences(content)
|
||||
.split(/\r?\n/)
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line === marker).length
|
||||
}
|
||||
|
||||
test.describe('Quick Command startup recovery', () => {
|
||||
registerTerminalPaneMountReadiness()
|
||||
|
||||
test('visible Quick Command survives a forced pre-bind recovery on one fresh PTY', async ({
|
||||
orcaPage
|
||||
}) => {
|
||||
const siblingBefore = await waitForPaneIdentitySnapshot(orcaPage, 1)
|
||||
const siblingPtyId = siblingBefore.panes[0]?.ptyId
|
||||
if (!siblingPtyId) {
|
||||
throw new Error('Sibling terminal has no live PTY')
|
||||
}
|
||||
|
||||
const siblingMarker = `ORCA_QUICK_COMMAND_SIBLING_${randomUUID()}`
|
||||
const siblingProbe = await runNodeScriptInTerminal(
|
||||
orcaPage,
|
||||
siblingPtyId,
|
||||
`process.stdout.write(${JSON.stringify(`${siblingMarker}\n`)})`
|
||||
)
|
||||
await waitForTerminalOutput(orcaPage, siblingMarker)
|
||||
siblingProbe.cleanup()
|
||||
|
||||
const marker = `ORCA_QUICK_COMMAND_RECOVERY_${randomUUID()}`
|
||||
const label = `Recovery sentinel ${randomUUID()}`
|
||||
const identityPath = path.join(os.tmpdir(), `orca-quick-command-identity-${randomUUID()}.json`)
|
||||
const staged = stageNodeScriptForTerminal(
|
||||
`
|
||||
const { writeFileSync } = require('node:fs')
|
||||
const identity = {
|
||||
marker: ${JSON.stringify(marker)},
|
||||
paneKey: process.env.ORCA_PANE_KEY || '',
|
||||
pid: process.pid,
|
||||
tabId: process.env.ORCA_TAB_ID || ''
|
||||
}
|
||||
writeFileSync(${JSON.stringify(identityPath)}, JSON.stringify(identity), { flag: 'wx' })
|
||||
process.stdout.write(${JSON.stringify(`${marker}\n`)})
|
||||
`.trim()
|
||||
)
|
||||
|
||||
try {
|
||||
await orcaPage.evaluate(
|
||||
async ({ command, label }) => {
|
||||
const store = window.__store
|
||||
if (!store) {
|
||||
throw new Error('Renderer store unavailable')
|
||||
}
|
||||
await store.getState().updateSettings({
|
||||
terminalQuickCommands: [
|
||||
{
|
||||
id: 'e2e-pre-bind-recovery',
|
||||
label,
|
||||
scope: { type: 'global' },
|
||||
action: 'terminal-command',
|
||||
command,
|
||||
appendEnter: true
|
||||
}
|
||||
]
|
||||
})
|
||||
const spawnBarrier = window.__terminalPtyPreSpawnE2EBarrier
|
||||
if (!spawnBarrier) {
|
||||
throw new Error('Terminal PTY pre-spawn E2E barrier unavailable')
|
||||
}
|
||||
spawnBarrier.arm()
|
||||
},
|
||||
{ command: staged.command, label }
|
||||
)
|
||||
|
||||
const quickCommandButton = orcaPage.getByRole('button', {
|
||||
name: `Run quick command: ${label}`
|
||||
})
|
||||
await expect(quickCommandButton).toBeVisible()
|
||||
await quickCommandButton.click()
|
||||
await orcaPage.evaluate(async () => {
|
||||
const spawnBarrier = window.__terminalPtyPreSpawnE2EBarrier
|
||||
if (!spawnBarrier) {
|
||||
throw new Error('Terminal PTY pre-spawn E2E barrier unavailable')
|
||||
}
|
||||
await spawnBarrier.waitUntilBlocked()
|
||||
})
|
||||
|
||||
const blocked = await orcaPage.evaluate(() => {
|
||||
const store = window.__store
|
||||
if (!store) {
|
||||
throw new Error('Renderer store unavailable')
|
||||
}
|
||||
const state = store.getState()
|
||||
const tabId = state.activeTabId
|
||||
if (!tabId) {
|
||||
throw new Error('Quick Command did not create an active tab')
|
||||
}
|
||||
return {
|
||||
generation:
|
||||
state.tabsByWorktree[state.activeWorktreeId ?? '']?.find((tab) => tab.id === tabId)
|
||||
?.generation ?? 0,
|
||||
pending: state.pendingStartupByTabId[tabId]?.command ?? null,
|
||||
status: window.__terminalPtyPreSpawnE2EBarrier?.status(),
|
||||
tabId
|
||||
}
|
||||
})
|
||||
expect(blocked.pending).toBe(staged.command)
|
||||
expect(blocked.status).toBe('blocked')
|
||||
|
||||
await orcaPage.evaluate((tabId) => {
|
||||
const store = window.__store
|
||||
if (!store) {
|
||||
throw new Error('Renderer store unavailable')
|
||||
}
|
||||
const target = window as QueueObservationWindow
|
||||
const observations: QueueObservation[] = []
|
||||
const observe = (): void => {
|
||||
const state = store.getState()
|
||||
observations.push({
|
||||
pending: state.pendingStartupByTabId[tabId] !== undefined,
|
||||
ptyIds: [...(state.ptyIdsByTabId[tabId] ?? [])]
|
||||
})
|
||||
}
|
||||
target.__quickCommandQueueObservations = observations
|
||||
target.__stopQuickCommandQueueObservations = store.subscribe(observe)
|
||||
observe()
|
||||
}, blocked.tabId)
|
||||
|
||||
const remounted = await orcaPage.evaluate((tabId) => {
|
||||
const state = window.__store?.getState()
|
||||
if (!state) {
|
||||
throw new Error('Renderer store unavailable')
|
||||
}
|
||||
return state.remountTerminalTabForRecovery(tabId)
|
||||
}, blocked.tabId)
|
||||
expect(remounted).toBe(true)
|
||||
|
||||
// Keep the original pre-spawn attempt gated until React has committed the
|
||||
// successor pane. Releasing earlier lets a loaded CI renderer finish the
|
||||
// old mount's teardown before the replacement reaches its connect path.
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
orcaPage.evaluate(
|
||||
({ expectedGeneration, tabId }) => {
|
||||
const state = window.__store?.getState()
|
||||
const manager = window.__paneManagers?.get(tabId)
|
||||
const pane = manager?.getPanes()[0]
|
||||
const tab = state?.tabsByWorktree[state.activeWorktreeId ?? '']?.find(
|
||||
(candidate) => candidate.id === tabId
|
||||
)
|
||||
return {
|
||||
generation: tab?.generation ?? 0,
|
||||
leafReady: Boolean(pane?.leafId),
|
||||
pending: state?.pendingStartupByTabId[tabId]?.command ?? null,
|
||||
expectedGeneration
|
||||
}
|
||||
},
|
||||
{ expectedGeneration: blocked.generation + 1, tabId: blocked.tabId }
|
||||
),
|
||||
{ message: 'Successor mount did not become ready before barrier release' }
|
||||
)
|
||||
.toEqual({
|
||||
generation: blocked.generation + 1,
|
||||
leafReady: true,
|
||||
pending: staged.command,
|
||||
expectedGeneration: blocked.generation + 1
|
||||
})
|
||||
await orcaPage.evaluate(() => window.__terminalPtyPreSpawnE2EBarrier?.release())
|
||||
|
||||
let targetPtyId = ''
|
||||
let targetLeafId = ''
|
||||
const successorReady = (): Promise<{
|
||||
generation: number
|
||||
leafReady: boolean
|
||||
pending: string | null
|
||||
ptyReady: boolean
|
||||
expectedGeneration: number
|
||||
}> =>
|
||||
orcaPage.evaluate(
|
||||
({ expectedGeneration, tabId }) => {
|
||||
const state = window.__store?.getState()
|
||||
const manager = window.__paneManagers?.get(tabId)
|
||||
const pane = manager?.getPanes()[0]
|
||||
const tab = state?.tabsByWorktree[state.activeWorktreeId ?? '']?.find(
|
||||
(candidate) => candidate.id === tabId
|
||||
)
|
||||
return {
|
||||
generation: tab?.generation ?? 0,
|
||||
leafReady: Boolean(pane?.leafId),
|
||||
pending: state?.pendingStartupByTabId[tabId]?.command ?? null,
|
||||
ptyReady: Boolean(pane?.container.dataset.ptyId),
|
||||
expectedGeneration
|
||||
}
|
||||
},
|
||||
{ expectedGeneration: blocked.generation + 1, tabId: blocked.tabId }
|
||||
)
|
||||
try {
|
||||
await expect
|
||||
.poll(successorReady, {
|
||||
timeout: 60_000,
|
||||
message: 'Successor mount did not bind its fresh Quick Command PTY'
|
||||
})
|
||||
.toEqual({
|
||||
generation: blocked.generation + 1,
|
||||
leafReady: true,
|
||||
pending: null,
|
||||
ptyReady: true,
|
||||
expectedGeneration: blocked.generation + 1
|
||||
})
|
||||
} catch (error) {
|
||||
const diagnostics = await orcaPage.evaluate(() => ({
|
||||
ptyConnect: (window as Window & { __ptyConnectDiag?: string[] }).__ptyConnectDiag ?? [],
|
||||
barrier: window.__terminalPtyPreSpawnE2EBarrier?.status() ?? 'missing'
|
||||
}))
|
||||
throw new Error(
|
||||
`${error instanceof Error ? error.message : String(error)}\nDiagnostics: ${JSON.stringify(diagnostics)}`
|
||||
)
|
||||
}
|
||||
|
||||
const successor = await orcaPage.evaluate((tabId) => {
|
||||
const pane = window.__paneManagers?.get(tabId)?.getPanes()[0]
|
||||
return {
|
||||
leafId: pane?.leafId ?? '',
|
||||
ptyId: pane?.container.dataset.ptyId ?? ''
|
||||
}
|
||||
}, blocked.tabId)
|
||||
targetPtyId = successor.ptyId
|
||||
targetLeafId = successor.leafId
|
||||
expect(targetPtyId).not.toBe('')
|
||||
expect(targetLeafId).not.toBe('')
|
||||
expect(targetPtyId).not.toBe(siblingPtyId)
|
||||
|
||||
const queueObservations = await orcaPage.evaluate(() => {
|
||||
const target = window as QueueObservationWindow
|
||||
target.__stopQuickCommandQueueObservations?.()
|
||||
target.__stopQuickCommandQueueObservations = undefined
|
||||
return target.__quickCommandQueueObservations ?? []
|
||||
})
|
||||
const firstConsumed = queueObservations.find((observation) => !observation.pending)
|
||||
expect(firstConsumed?.ptyIds).toContain(targetPtyId)
|
||||
|
||||
await expect
|
||||
.poll(
|
||||
() =>
|
||||
orcaPage.evaluate((tabId) => {
|
||||
const pane = window.__paneManagers?.get(tabId)?.getPanes()[0]
|
||||
return pane?.serializeAddon.serialize() ?? ''
|
||||
}, blocked.tabId),
|
||||
{ message: 'Quick Command marker never reached the visible xterm' }
|
||||
)
|
||||
.toContain(marker)
|
||||
const targetContent = await orcaPage.evaluate((tabId) => {
|
||||
const pane = window.__paneManagers?.get(tabId)?.getPanes()[0]
|
||||
return pane?.serializeAddon.serialize() ?? ''
|
||||
}, blocked.tabId)
|
||||
expect(exactMarkerLineCount(targetContent, marker)).toBe(1)
|
||||
|
||||
await expect.poll(() => existsSync(identityPath)).toBe(true)
|
||||
const identity = JSON.parse(readFileSync(identityPath, 'utf8')) as QuickCommandIdentity
|
||||
expect(identity).toMatchObject({
|
||||
marker,
|
||||
paneKey: `${blocked.tabId}:${targetLeafId}`,
|
||||
tabId: blocked.tabId
|
||||
})
|
||||
expect(identity.pid).toBeGreaterThan(0)
|
||||
|
||||
const ptyIdentity = await orcaPage.evaluate(
|
||||
async ({ siblingPtyId, siblingTabId, tabId, targetPtyId }) => {
|
||||
const state = window.__store?.getState()
|
||||
const layout = state?.terminalLayoutsByTabId[tabId]
|
||||
const sessions = await window.api.pty.listSessions()
|
||||
return {
|
||||
layoutPtyIds: Object.values(layout?.ptyIdsByLeafId ?? {}),
|
||||
siblingLive: await window.api.pty.hasPty(siblingPtyId),
|
||||
siblingStorePtyIds: state?.ptyIdsByTabId[siblingTabId] ?? [],
|
||||
targetLive: await window.api.pty.hasPty(targetPtyId),
|
||||
targetSessionIds: sessions
|
||||
.filter((session) => session.id === targetPtyId)
|
||||
.map((session) => session.id),
|
||||
targetStorePtyIds: state?.ptyIdsByTabId[tabId] ?? []
|
||||
}
|
||||
},
|
||||
{ siblingPtyId, siblingTabId: siblingBefore.tabId, tabId: blocked.tabId, targetPtyId }
|
||||
)
|
||||
expect(ptyIdentity.targetLive).toBe(true)
|
||||
expect(ptyIdentity.targetSessionIds).toEqual([targetPtyId])
|
||||
expect(ptyIdentity.targetStorePtyIds).toContain(targetPtyId)
|
||||
expect(ptyIdentity.layoutPtyIds).toContain(targetPtyId)
|
||||
expect(ptyIdentity.siblingLive).toBe(true)
|
||||
expect(ptyIdentity.siblingStorePtyIds).toContain(siblingPtyId)
|
||||
|
||||
const siblingAfterMarker = `ORCA_QUICK_COMMAND_SIBLING_AFTER_${randomUUID()}`
|
||||
await orcaPage.evaluate(
|
||||
(tabId) => window.__store?.getState().setActiveTab(tabId),
|
||||
siblingBefore.tabId
|
||||
)
|
||||
await expect
|
||||
.poll(() => orcaPage.evaluate(() => window.__store?.getState().activeTabId))
|
||||
.toBe(siblingBefore.tabId)
|
||||
await focusActiveTerminalInput(orcaPage)
|
||||
await orcaPage.keyboard.type(`echo ${siblingAfterMarker}`)
|
||||
await orcaPage.keyboard.press('Enter')
|
||||
await expect
|
||||
.poll(async () => (await getTerminalContent(orcaPage)).split(siblingAfterMarker).length - 1)
|
||||
.toBeGreaterThanOrEqual(1)
|
||||
} finally {
|
||||
await orcaPage
|
||||
.evaluate(() => window.__terminalPtyPreSpawnE2EBarrier?.release())
|
||||
.catch(() => {})
|
||||
staged.cleanup()
|
||||
rmSync(identityPath, { force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,76 @@
|
||||
import { test, expect } from './helpers/orca-app'
|
||||
import { getAllWorktreeIds, waitForActiveWorktree, waitForSessionReady } from './helpers/store'
|
||||
import { pressShortcut } from './helpers/shortcuts'
|
||||
import { worktreeRow } from './worktree-row-locators'
|
||||
|
||||
async function createIsolatedWorktree(
|
||||
page: Parameters<typeof waitForActiveWorktree>[0]
|
||||
): Promise<string> {
|
||||
const name = `e2e-delete-shortcut-${Date.now()}`
|
||||
return page.evaluate(async (worktreeName) => {
|
||||
const state = window.__store?.getState()
|
||||
if (!state?.activeWorktreeId) {
|
||||
throw new Error('No active worktree to derive repo from')
|
||||
}
|
||||
const worktree = Object.values(state.worktreesByRepo)
|
||||
.flat()
|
||||
.find((candidate) => candidate.id === state.activeWorktreeId)
|
||||
if (!worktree) {
|
||||
throw new Error('Active worktree was not found')
|
||||
}
|
||||
|
||||
const result = await state.createWorktree(worktree.repoId, worktreeName)
|
||||
await state.fetchWorktrees(worktree.repoId)
|
||||
return result.worktree.id
|
||||
}, name)
|
||||
}
|
||||
|
||||
test.describe('Worktree Delete Shortcut', () => {
|
||||
let createdWorktreeId: string | null = null
|
||||
|
||||
test.beforeEach(async ({ orcaPage }) => {
|
||||
await waitForSessionReady(orcaPage)
|
||||
await waitForActiveWorktree(orcaPage)
|
||||
})
|
||||
|
||||
test.afterEach(async ({ orcaPage }) => {
|
||||
if (!createdWorktreeId) {
|
||||
return
|
||||
}
|
||||
const worktreeId = createdWorktreeId
|
||||
createdWorktreeId = null
|
||||
await orcaPage
|
||||
.evaluate(async (id) => {
|
||||
const state = window.__store?.getState()
|
||||
await state?.removeWorktree(
|
||||
{ id, executionHostId: state.getKnownWorktreeById(id)?.hostId ?? null },
|
||||
true
|
||||
)
|
||||
}, worktreeId)
|
||||
.catch(() => undefined)
|
||||
})
|
||||
|
||||
test('deletes the hovered worktree after Mod+Shift+Backspace confirmation', async ({
|
||||
orcaPage
|
||||
}) => {
|
||||
createdWorktreeId = await createIsolatedWorktree(orcaPage)
|
||||
const worktreeId = createdWorktreeId
|
||||
const row = worktreeRow(orcaPage, worktreeId)
|
||||
await expect(row).toBeVisible()
|
||||
|
||||
await row.hover()
|
||||
await pressShortcut(orcaPage, 'Backspace', { shift: true })
|
||||
|
||||
const dialog = orcaPage.getByRole('dialog')
|
||||
await expect(dialog).toBeVisible()
|
||||
await dialog.getByRole('button', { name: 'Delete Workspace', exact: true }).click()
|
||||
|
||||
await expect
|
||||
.poll(async () => getAllWorktreeIds(orcaPage), {
|
||||
timeout: 15_000,
|
||||
message: 'hovered worktree was not removed by the delete shortcut'
|
||||
})
|
||||
.not.toContain(worktreeId)
|
||||
createdWorktreeId = null
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,16 @@
|
||||
# Packaged Windows PTY native capability smoke
|
||||
|
||||
This narrow harness runs the packaged `Orca.exe` with `ELECTRON_RUN_AS_NODE=1` and loads its bundled `node-pty`. Checkout Node processes provide the target/canary shell fixtures, so the smoke proves the packaged native addon without putting a GUI-subsystem Electron executable under ConPTY. A 256-bit fixture token binds the target shell, a grandchild that remains live after its intermediate launcher exits, and an unrelated canary to one unique named-pipe channel; the oracle checks the patched exports, job PIDs, exact job-handle termination, PTY/socket exit events, and canary survival.
|
||||
|
||||
Run it against an unpacked Windows package:
|
||||
|
||||
```text
|
||||
pnpm run smoke:windows-pty-native-capability -- --exe=dist/win-unpacked/Orca.exe
|
||||
```
|
||||
|
||||
The official `v1.4.158` package is the causal red artifact: it fails immediately because its
|
||||
packaged `node-pty` lacks `assignCurrentProcessToJob`. Candidate green evidence comes from the
|
||||
required Windows packaging job, which runs this smoke without retries. The one-shot probe flushes
|
||||
its evidence and exits explicitly because direct native job termination intentionally bypasses
|
||||
node-pty's ConPTY-worker disposal path; a 45-second outer ceiling reports bounded stdout, stderr,
|
||||
and native-stage breadcrumbs if any boundary stops progressing.
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
const REQUIRED_EXPORTS = ['assignCurrentProcessToJob', 'listJobProcessIds', 'terminateJob']
|
||||
const FIXTURE_TOKEN_PATTERN = /^[a-f0-9]{64}$/
|
||||
|
||||
function isFixtureObservation(value, expected) {
|
||||
return (
|
||||
Number.isInteger(value?.pid) &&
|
||||
value.pid > 0 &&
|
||||
value.fixtureToken === expected.fixtureToken &&
|
||||
value.channel === expected.channel &&
|
||||
value.role === expected.role
|
||||
)
|
||||
}
|
||||
|
||||
function isFixtureClosure(value, expected) {
|
||||
return (
|
||||
value?.fixtureToken === expected.fixtureToken &&
|
||||
value.channel === expected.channel &&
|
||||
value.role === expected.role
|
||||
)
|
||||
}
|
||||
|
||||
function isPtyExit(value, terminalHandle) {
|
||||
return value?.terminalHandle === terminalHandle && Number.isInteger(value.exitCode)
|
||||
}
|
||||
|
||||
export function evaluatePackagedNodePtyCapability(evidence) {
|
||||
const failures = []
|
||||
const exports = new Set(evidence?.patchedExports ?? [])
|
||||
const fixtureToken = evidence?.fixtureToken
|
||||
const channel = evidence?.channel
|
||||
const target = evidence?.target
|
||||
const canary = evidence?.canary
|
||||
|
||||
if (REQUIRED_EXPORTS.some((name) => !exports.has(name))) {
|
||||
failures.push('the packaged node-pty addon is missing a required patched export')
|
||||
}
|
||||
if (!FIXTURE_TOKEN_PATTERN.test(fixtureToken) || !channel?.includes(fixtureToken)) {
|
||||
failures.push('the fixture channel is not bound to the per-run unguessable token')
|
||||
}
|
||||
if (!isFixtureObservation(target?.shell, { fixtureToken, channel, role: 'target-shell' })) {
|
||||
failures.push('the target shell was not observed on its unique fixture channel')
|
||||
}
|
||||
if (
|
||||
!isFixtureObservation(target?.launcherExited, {
|
||||
fixtureToken,
|
||||
channel,
|
||||
role: 'target-launcher-exited'
|
||||
})
|
||||
) {
|
||||
failures.push('the transient launcher exit was not observed')
|
||||
}
|
||||
if (
|
||||
!isFixtureObservation(target?.grandchild, {
|
||||
fixtureToken,
|
||||
channel,
|
||||
role: 'target-grandchild'
|
||||
})
|
||||
) {
|
||||
failures.push('the grandchild was not observed after its launcher exited')
|
||||
}
|
||||
if (!isFixtureObservation(canary?.process, { fixtureToken, channel, role: 'canary-shell' })) {
|
||||
failures.push('the unrelated canary was not observed on its unique fixture channel')
|
||||
}
|
||||
const observedPids = [
|
||||
target?.shell?.pid,
|
||||
target?.launcherExited?.pid,
|
||||
target?.grandchild?.pid,
|
||||
canary?.process?.pid
|
||||
]
|
||||
if (observedPids.every((pid) => Number.isInteger(pid)) && new Set(observedPids).size !== 4) {
|
||||
failures.push('target shell, launcher, grandchild, and canary must be distinct processes')
|
||||
}
|
||||
|
||||
if (!Array.isArray(target?.jobProcessIds) || target.jobProcessIds.length === 0) {
|
||||
failures.push('the target job membership must be available and nonempty')
|
||||
} else if (!target.jobProcessIds.includes(target?.shell?.pid)) {
|
||||
failures.push('the target job does not contain the observed shell PID')
|
||||
} else if (!target.jobProcessIds.includes(target?.grandchild?.pid)) {
|
||||
failures.push('the target job does not contain the observed grandchild PID')
|
||||
} else if (target.jobProcessIds.includes(target?.launcherExited?.pid)) {
|
||||
failures.push('the transient launcher is still live in the target job')
|
||||
}
|
||||
const close = evidence?.close
|
||||
if (
|
||||
close?.method !== 'terminate-job' ||
|
||||
close?.requestedHandle !== target?.terminalHandle ||
|
||||
close?.completedHandle !== target?.terminalHandle
|
||||
) {
|
||||
failures.push('close must complete for the one requested PTY job handle')
|
||||
}
|
||||
if (
|
||||
!isPtyExit(close?.targetExit, target?.terminalHandle) ||
|
||||
!isFixtureClosure(close?.targetShellClosed, {
|
||||
fixtureToken,
|
||||
channel,
|
||||
role: 'target-shell'
|
||||
}) ||
|
||||
!isFixtureClosure(close?.targetGrandchildClosed, {
|
||||
fixtureToken,
|
||||
channel,
|
||||
role: 'target-grandchild'
|
||||
})
|
||||
) {
|
||||
failures.push('target close did not complete from PTY and fixture socket exit events')
|
||||
}
|
||||
|
||||
if (canary?.connectedAfterTargetClose !== true) {
|
||||
failures.push('the unrelated canary fixture connection was lost during target close')
|
||||
}
|
||||
if (
|
||||
!Array.isArray(canary?.jobProcessIdsAfterTargetClose) ||
|
||||
!canary.jobProcessIdsAfterTargetClose.includes(canary?.process?.pid)
|
||||
) {
|
||||
failures.push('the unrelated canary PID is not live in its job after target close')
|
||||
}
|
||||
if (!isPtyExit(canary?.exit, canary?.terminalHandle)) {
|
||||
failures.push('the unrelated canary PTY exit was not observed')
|
||||
}
|
||||
if (
|
||||
!isFixtureClosure(canary?.socketClosed, {
|
||||
fixtureToken,
|
||||
channel,
|
||||
role: 'canary-shell'
|
||||
})
|
||||
) {
|
||||
failures.push('the unrelated canary did not complete its later exact teardown')
|
||||
}
|
||||
|
||||
return { pass: failures.length === 0, failures }
|
||||
}
|
||||
|
||||
export function assertPackagedNodePtyCapability(evidence) {
|
||||
const result = evaluatePackagedNodePtyCapability(evidence)
|
||||
if (!result.pass) {
|
||||
throw new Error(
|
||||
`Packaged node-pty native capability failed:\n- ${result.failures.join('\n- ')}`
|
||||
)
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { evaluatePackagedNodePtyCapability } from './packaged-node-pty-capability-oracle.mjs'
|
||||
|
||||
const fixtureToken = 'a'.repeat(64)
|
||||
const channel = `\\\\.\\pipe\\orca-pty-native-capability-${fixtureToken}`
|
||||
|
||||
function observation(pid, role) {
|
||||
return { pid, fixtureToken, role, channel }
|
||||
}
|
||||
|
||||
function closure(role) {
|
||||
return { fixtureToken, role, channel }
|
||||
}
|
||||
|
||||
function passingEvidence() {
|
||||
const shell = observation(4100, 'target-shell')
|
||||
const launcherExited = observation(4101, 'target-launcher-exited')
|
||||
const grandchild = observation(4102, 'target-grandchild')
|
||||
const canary = observation(5100, 'canary-shell')
|
||||
return {
|
||||
patchedExports: ['assignCurrentProcessToJob', 'listJobProcessIds', 'terminateJob'],
|
||||
fixtureToken,
|
||||
channel,
|
||||
target: {
|
||||
terminalHandle: 'pty-job:7:4100',
|
||||
shell,
|
||||
launcherExited,
|
||||
grandchild,
|
||||
jobProcessIds: [shell.pid, grandchild.pid]
|
||||
},
|
||||
canary: {
|
||||
terminalHandle: 'pty-job:8:5100',
|
||||
process: canary,
|
||||
connectedAfterTargetClose: true,
|
||||
jobProcessIdsAfterTargetClose: [canary.pid],
|
||||
exit: { terminalHandle: 'pty-job:8:5100', exitCode: 1, signal: 0 },
|
||||
socketClosed: closure('canary-shell')
|
||||
},
|
||||
close: {
|
||||
method: 'terminate-job',
|
||||
requestedHandle: 'pty-job:7:4100',
|
||||
completedHandle: 'pty-job:7:4100',
|
||||
targetExit: { terminalHandle: 'pty-job:7:4100', exitCode: 1, signal: 0 },
|
||||
targetShellClosed: closure('target-shell'),
|
||||
targetGrandchildClosed: closure('target-grandchild')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('packaged node-pty native capability oracle', () => {
|
||||
it('accepts exact target teardown while the unrelated canary remains live', () => {
|
||||
expect(evaluatePackagedNodePtyCapability(passingEvidence())).toEqual({
|
||||
pass: true,
|
||||
failures: []
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
['missing patched export', (evidence) => evidence.patchedExports.pop()],
|
||||
['launcher exit absent', (evidence) => delete evidence.target.launcherExited],
|
||||
['empty job membership', (evidence) => (evidence.target.jobProcessIds = [])],
|
||||
[
|
||||
'target shell outside membership',
|
||||
(evidence) => (evidence.target.jobProcessIds = [evidence.target.grandchild.pid])
|
||||
],
|
||||
[
|
||||
'launcher-surviving grandchild outside membership',
|
||||
(evidence) => (evidence.target.jobProcessIds = [evidence.target.shell.pid])
|
||||
],
|
||||
['target exit absent', (evidence) => delete evidence.close.targetExit],
|
||||
['canary connection loss', (evidence) => (evidence.canary.connectedAfterTargetClose = false)]
|
||||
])('rejects %s', (_name, mutate) => {
|
||||
const evidence = passingEvidence()
|
||||
mutate(evidence)
|
||||
|
||||
expect(evaluatePackagedNodePtyCapability(evidence).pass).toBe(false)
|
||||
})
|
||||
|
||||
it.each([
|
||||
['guessable token', (evidence) => (evidence.fixtureToken = 'run-1')],
|
||||
[
|
||||
'grandchild from another channel',
|
||||
(evidence) => (evidence.target.grandchild.channel = '\\\\.\\pipe\\other')
|
||||
],
|
||||
['wrong completed handle', (evidence) => (evidence.close.completedHandle = 'pty-job:9:9999')],
|
||||
[
|
||||
'launcher still in target job',
|
||||
(evidence) => evidence.target.jobProcessIds.push(evidence.target.launcherExited.pid)
|
||||
],
|
||||
['canary outside its job', (evidence) => (evidence.canary.jobProcessIdsAfterTargetClose = [])],
|
||||
['canary teardown absent', (evidence) => delete evidence.canary.socketClosed]
|
||||
])('rejects scope violation: %s', (_name, mutate) => {
|
||||
const evidence = passingEvidence()
|
||||
mutate(evidence)
|
||||
|
||||
expect(evaluatePackagedNodePtyCapability(evidence).pass).toBe(false)
|
||||
})
|
||||
})
|
||||
+448
@@ -0,0 +1,448 @@
|
||||
const { randomBytes } = require('node:crypto')
|
||||
const { writeSync } = require('node:fs')
|
||||
const net = require('node:net')
|
||||
const path = require('node:path')
|
||||
|
||||
const EVIDENCE_PREFIX = 'ORCA_NODE_PTY_CAPABILITY_EVIDENCE='
|
||||
const EXPECTED_ROLES = new Set([
|
||||
'target-shell',
|
||||
'target-launcher-exited',
|
||||
'target-grandchild',
|
||||
'canary-shell'
|
||||
])
|
||||
const ONE_SHOT_MODES = new Set(['--exercise', '--exit-contract-fixture'])
|
||||
|
||||
function isOneShotMode(mode) {
|
||||
return ONE_SHOT_MODES.has(mode)
|
||||
}
|
||||
|
||||
function stage(name) {
|
||||
writeSync(2, `[windows-pty-native-capability-smoke] stage=${name}\n`)
|
||||
}
|
||||
|
||||
function writeStream(stream, value = '') {
|
||||
return new Promise((resolve, reject) => {
|
||||
stream.write(value, (error) => (error ? reject(error) : resolve()))
|
||||
})
|
||||
}
|
||||
|
||||
async function exitOneShot(code, exit = process.exit) {
|
||||
await Promise.all([writeStream(process.stdout), writeStream(process.stderr)])
|
||||
exit(code)
|
||||
}
|
||||
|
||||
function fixtureObservation(fixtureToken, role, channel, extra = {}) {
|
||||
return { pid: process.pid, fixtureToken, role, channel, ...extra }
|
||||
}
|
||||
|
||||
function connectFixture(channel, fixtureToken, role, extra = {}) {
|
||||
const socket = net.createConnection(channel)
|
||||
socket.once('connect', () => {
|
||||
socket.write(`${JSON.stringify(fixtureObservation(fixtureToken, role, channel, extra))}\n`)
|
||||
})
|
||||
socket.on('error', (error) => {
|
||||
process.stderr.write(`${error.stack || error.message}\n`)
|
||||
process.exitCode = 1
|
||||
})
|
||||
return socket
|
||||
}
|
||||
|
||||
function reportFixtureObservation(channel, fixtureToken, role, extra = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = net.createConnection(channel)
|
||||
socket.once('connect', () => {
|
||||
socket.end(`${JSON.stringify(fixtureObservation(fixtureToken, role, channel, extra))}\n`)
|
||||
})
|
||||
socket.once('error', reject)
|
||||
socket.once('close', resolve)
|
||||
})
|
||||
}
|
||||
|
||||
function buildGrandchildLaunch(channel, fixtureToken) {
|
||||
return {
|
||||
program: path.join(process.env.SystemRoot, 'System32', 'wscript.exe'),
|
||||
args: [
|
||||
path.join(__dirname, 'real-orca-detached-launcher.vbs'),
|
||||
process.execPath,
|
||||
__filename,
|
||||
'--grandchild-member',
|
||||
channel,
|
||||
fixtureToken,
|
||||
'target-grandchild'
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
function startGrandchildAfterLauncherExit(channel, fixtureToken, resourcesDir) {
|
||||
const { spawnProcess } = require(
|
||||
path.join(resourcesDir, 'app.asar.unpacked', 'out', 'shared', 'child-process', 'run-process.js')
|
||||
)
|
||||
const launch = buildGrandchildLaunch(channel, fixtureToken)
|
||||
const child = spawnProcess({
|
||||
...launch,
|
||||
env: process.env
|
||||
})
|
||||
for (const stream of [child.stdin, child.stdout, child.stderr]) {
|
||||
stream?.on('error', () => {})
|
||||
}
|
||||
child.stdin?.end()
|
||||
return new Promise((resolve, reject) => {
|
||||
child.once('error', reject)
|
||||
child.once('exit', (code) => {
|
||||
if (code !== 0) {
|
||||
reject(new Error(`grandchild launcher exited ${code}`))
|
||||
return
|
||||
}
|
||||
reportFixtureObservation(channel, fixtureToken, 'target-launcher-exited', {
|
||||
pid: child.pid
|
||||
}).then(() => resolve(child.pid), reject)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
async function runPtyShell(channel, fixtureToken, role, resourcesDir) {
|
||||
const socket = connectFixture(channel, fixtureToken, `${role}-shell`)
|
||||
try {
|
||||
if (role === 'target') {
|
||||
await startGrandchildAfterLauncherExit(channel, fixtureToken, resourcesDir)
|
||||
}
|
||||
} catch (error) {
|
||||
socket.destroy()
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
function createFixtureServer(channel, fixtureToken) {
|
||||
const pending = new Map()
|
||||
const observations = new Map()
|
||||
const sockets = new Map()
|
||||
const closures = new Map()
|
||||
const acceptedSockets = new Set()
|
||||
let serverClosed = false
|
||||
|
||||
function closureFor(role) {
|
||||
const existing = closures.get(role)
|
||||
if (existing) {
|
||||
return existing
|
||||
}
|
||||
let resolve
|
||||
const promise = new Promise((done) => {
|
||||
resolve = done
|
||||
})
|
||||
const closure = { promise, resolve }
|
||||
closures.set(role, closure)
|
||||
return closure
|
||||
}
|
||||
|
||||
function waitForRole(role) {
|
||||
const existing = observations.get(role)
|
||||
if (existing) {
|
||||
return Promise.resolve(existing)
|
||||
}
|
||||
return new Promise((resolve) => pending.set(role, resolve))
|
||||
}
|
||||
|
||||
const server = net.createServer((socket) => {
|
||||
let input = ''
|
||||
acceptedSockets.add(socket)
|
||||
socket.once('close', () => acceptedSockets.delete(socket))
|
||||
socket.setEncoding('utf8')
|
||||
socket.on('data', (chunk) => {
|
||||
input += String(chunk)
|
||||
const newline = input.indexOf('\n')
|
||||
if (newline === -1) {
|
||||
return
|
||||
}
|
||||
const observation = JSON.parse(input.slice(0, newline))
|
||||
if (
|
||||
observation.fixtureToken !== fixtureToken ||
|
||||
observation.channel !== channel ||
|
||||
!EXPECTED_ROLES.has(observation.role)
|
||||
) {
|
||||
throw new Error('fixture observation did not match its unique token, channel, and role')
|
||||
}
|
||||
observations.set(observation.role, observation)
|
||||
sockets.set(observation.role, socket)
|
||||
pending.get(observation.role)?.(observation)
|
||||
pending.delete(observation.role)
|
||||
socket.once('close', () => {
|
||||
closureFor(observation.role).resolve({
|
||||
fixtureToken,
|
||||
channel,
|
||||
role: observation.role
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
const listening = new Promise((resolve, reject) => {
|
||||
server.once('error', reject)
|
||||
server.listen(channel, resolve)
|
||||
})
|
||||
const close = () => {
|
||||
if (serverClosed) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
serverClosed = true
|
||||
return new Promise((resolve, reject) => {
|
||||
server.close((error) => (error ? reject(error) : resolve()))
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
listening,
|
||||
waitForRole,
|
||||
waitForClose: (role) => closureFor(role).promise,
|
||||
sockets,
|
||||
destroySockets: () => {
|
||||
for (const socket of acceptedSockets) {
|
||||
socket.destroy()
|
||||
}
|
||||
server.closeAllConnections?.()
|
||||
server.unref()
|
||||
},
|
||||
close
|
||||
}
|
||||
}
|
||||
|
||||
function terminalHandle(pty) {
|
||||
return `pty-job:${pty._pty}:${pty.pid}`
|
||||
}
|
||||
|
||||
function exitEvent(pty) {
|
||||
const handle = terminalHandle(pty)
|
||||
return new Promise((resolve) =>
|
||||
pty.onExit((event) => resolve({ terminalHandle: handle, ...event }))
|
||||
)
|
||||
}
|
||||
|
||||
function waitForBarrier(promise, label, timeoutMs = 30_000) {
|
||||
let timer
|
||||
const deadline = new Promise((_, reject) => {
|
||||
timer = setTimeout(
|
||||
() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)),
|
||||
timeoutMs
|
||||
)
|
||||
})
|
||||
return Promise.race([promise, deadline]).finally(() => clearTimeout(timer))
|
||||
}
|
||||
|
||||
async function exercise(resourcesDir, fixtureExecutable) {
|
||||
const nodePtyDir = path.join(resourcesDir, 'node_modules', 'node-pty')
|
||||
stage('addon-load:start')
|
||||
const nodePty = require(nodePtyDir)
|
||||
const { module: native } = require(path.join(nodePtyDir, 'lib', 'utils.js')).loadNativeModule(
|
||||
'conpty'
|
||||
)
|
||||
stage('addon-load:done')
|
||||
const patchedExports = ['assignCurrentProcessToJob', 'listJobProcessIds', 'terminateJob']
|
||||
for (const name of patchedExports) {
|
||||
if (typeof native[name] !== 'function') {
|
||||
throw new Error(`packaged node-pty is missing ${name}`)
|
||||
}
|
||||
}
|
||||
stage('host-job-assign:start')
|
||||
const hostJobAssigned = native.assignCurrentProcessToJob()
|
||||
stage('host-job-assign:done')
|
||||
if (!hostJobAssigned) {
|
||||
throw new Error('packaged probe could not establish host job ownership')
|
||||
}
|
||||
|
||||
const fixtureToken = randomBytes(32).toString('hex')
|
||||
const channel = `\\\\.\\pipe\\orca-pty-native-capability-${fixtureToken}`
|
||||
const fixtures = createFixtureServer(channel, fixtureToken)
|
||||
stage('fixture-listen:start')
|
||||
await waitForBarrier(fixtures.listening, 'fixture server listen')
|
||||
stage('fixture-listen:done')
|
||||
const options = {
|
||||
name: 'xterm-256color',
|
||||
cols: 80,
|
||||
rows: 30,
|
||||
cwd: process.cwd(),
|
||||
env: process.env,
|
||||
useConptyDll: true
|
||||
}
|
||||
const created = []
|
||||
const closed = new Set()
|
||||
const exitPromises = []
|
||||
let completed = false
|
||||
|
||||
try {
|
||||
stage('target-spawn:start')
|
||||
const target = nodePty.spawn(
|
||||
fixtureExecutable,
|
||||
[__filename, '--pty-shell', channel, fixtureToken, 'target', resourcesDir],
|
||||
options
|
||||
)
|
||||
stage('target-spawn:done')
|
||||
created.push(target)
|
||||
const targetExited = exitEvent(target)
|
||||
exitPromises.push(targetExited)
|
||||
stage('canary-spawn:start')
|
||||
const canary = nodePty.spawn(
|
||||
fixtureExecutable,
|
||||
[__filename, '--pty-shell', channel, fixtureToken, 'canary', resourcesDir],
|
||||
options
|
||||
)
|
||||
stage('canary-spawn:done')
|
||||
created.push(canary)
|
||||
const canaryHandle = terminalHandle(canary)
|
||||
const canaryExited = exitEvent(canary)
|
||||
exitPromises.push(canaryExited)
|
||||
|
||||
stage('fixture-readiness:start')
|
||||
const [shell, launcherExited, grandchild, canaryProcess] = await Promise.all([
|
||||
waitForBarrier(fixtures.waitForRole('target-shell'), 'target shell readiness'),
|
||||
waitForBarrier(fixtures.waitForRole('target-launcher-exited'), 'grandchild launcher exit'),
|
||||
waitForBarrier(fixtures.waitForRole('target-grandchild'), 'target grandchild readiness'),
|
||||
waitForBarrier(fixtures.waitForRole('canary-shell'), 'canary shell readiness')
|
||||
])
|
||||
stage('fixture-readiness:done')
|
||||
stage('target-job-list:start')
|
||||
const targetJobProcessIds = native.listJobProcessIds(target._pty, target.pid)
|
||||
stage('target-job-list:done')
|
||||
const targetHandle = terminalHandle(target)
|
||||
stage('target-job-terminate:start')
|
||||
const targetTerminated = native.terminateJob(target._pty, target.pid)
|
||||
stage('target-job-terminate:done')
|
||||
if (!targetTerminated) {
|
||||
throw new Error('exact target job termination was refused')
|
||||
}
|
||||
closed.add(target)
|
||||
stage('target-exit-barriers:start')
|
||||
const [targetExit, targetShellClosed, targetGrandchildClosed] = await Promise.all([
|
||||
waitForBarrier(targetExited, 'target PTY exit'),
|
||||
waitForBarrier(fixtures.waitForClose('target-shell'), 'target shell connection close'),
|
||||
waitForBarrier(
|
||||
fixtures.waitForClose('target-grandchild'),
|
||||
'target grandchild connection close'
|
||||
)
|
||||
])
|
||||
stage('target-exit-barriers:done')
|
||||
|
||||
stage('canary-job-list:start')
|
||||
const canaryJobProcessIdsAfterTargetClose = native.listJobProcessIds(canary._pty, canary.pid)
|
||||
stage('canary-job-list:done')
|
||||
const canarySocket = fixtures.sockets.get('canary-shell')
|
||||
const connectedAfterTargetClose = Boolean(canarySocket && !canarySocket.destroyed)
|
||||
stage('canary-job-terminate:start')
|
||||
const canaryTerminated = native.terminateJob(canary._pty, canary.pid)
|
||||
stage('canary-job-terminate:done')
|
||||
if (!canaryTerminated) {
|
||||
throw new Error('exact canary job termination was refused')
|
||||
}
|
||||
closed.add(canary)
|
||||
stage('canary-exit-barriers:start')
|
||||
const [canaryExit, canaryClosed] = await Promise.all([
|
||||
waitForBarrier(canaryExited, 'canary PTY exit'),
|
||||
waitForBarrier(fixtures.waitForClose('canary-shell'), 'canary shell connection close')
|
||||
])
|
||||
stage('canary-exit-barriers:done')
|
||||
|
||||
const evidence = {
|
||||
patchedExports,
|
||||
fixtureToken,
|
||||
channel,
|
||||
target: {
|
||||
terminalHandle: targetHandle,
|
||||
shell,
|
||||
launcherExited,
|
||||
grandchild,
|
||||
jobProcessIds: targetJobProcessIds
|
||||
},
|
||||
canary: {
|
||||
terminalHandle: canaryHandle,
|
||||
process: canaryProcess,
|
||||
connectedAfterTargetClose,
|
||||
jobProcessIdsAfterTargetClose: canaryJobProcessIdsAfterTargetClose,
|
||||
exit: canaryExit,
|
||||
socketClosed: canaryClosed
|
||||
},
|
||||
close: {
|
||||
method: 'terminate-job',
|
||||
requestedHandle: targetHandle,
|
||||
completedHandle: targetHandle,
|
||||
targetExit,
|
||||
targetShellClosed,
|
||||
targetGrandchildClosed
|
||||
}
|
||||
}
|
||||
stage('fixture-close:start')
|
||||
await waitForBarrier(fixtures.close(), 'fixture server close')
|
||||
stage('fixture-close:done')
|
||||
await writeStream(process.stdout, `${EVIDENCE_PREFIX}${JSON.stringify(evidence)}\n`)
|
||||
stage('evidence:flushed')
|
||||
completed = true
|
||||
} catch (error) {
|
||||
process.stderr.write(`[windows-pty-native-capability-smoke] ${error.message}\n`)
|
||||
throw error
|
||||
} finally {
|
||||
for (const pty of created) {
|
||||
if (!closed.has(pty)) {
|
||||
stage('cleanup-job-terminate:start')
|
||||
native.terminateJob(pty._pty, pty.pid)
|
||||
stage('cleanup-job-terminate:done')
|
||||
}
|
||||
}
|
||||
if (!completed) {
|
||||
await Promise.allSettled(
|
||||
exitPromises.map((exit) => waitForBarrier(exit, 'cleanup PTY exit', 5_000))
|
||||
)
|
||||
fixtures.destroySockets()
|
||||
try {
|
||||
await waitForBarrier(fixtures.close(), 'fixture server cleanup', 5_000)
|
||||
} catch (error) {
|
||||
process.stderr.write(`[windows-pty-native-capability-smoke] ${error.message}\n`)
|
||||
}
|
||||
} else {
|
||||
await fixtures.close()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const [mode, ...args] = process.argv.slice(2)
|
||||
if (mode === '--pty-shell') {
|
||||
await runPtyShell(args[0], args[1], args[2], args[3])
|
||||
return
|
||||
}
|
||||
if (mode === '--grandchild-member') {
|
||||
connectFixture(args[0], args[1], args[2])
|
||||
return
|
||||
}
|
||||
if (mode === '--exercise') {
|
||||
if (!args[1]) {
|
||||
throw new Error('exercise mode requires a fixture Node executable')
|
||||
}
|
||||
await exercise(args[0], args[1])
|
||||
return
|
||||
}
|
||||
if (mode === '--exit-contract-fixture') {
|
||||
process.stdout.write('ORCA_ONE_SHOT_EVIDENCE=flushed\n')
|
||||
setInterval(() => {}, 60_000)
|
||||
return
|
||||
}
|
||||
throw new Error(`unknown packaged node-pty capability probe mode: ${mode}`)
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
buildGrandchildLaunch,
|
||||
createFixtureServer,
|
||||
isOneShotMode,
|
||||
reportFixtureObservation
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
const mode = process.argv[2]
|
||||
main().then(
|
||||
() => (isOneShotMode(mode) ? exitOneShot(0) : undefined),
|
||||
async (error) => {
|
||||
await writeStream(process.stderr, `${error.stack || error.message}\n`)
|
||||
if (isOneShotMode(mode)) {
|
||||
await exitOneShot(1)
|
||||
} else {
|
||||
process.exitCode = 1
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { createRequire } from 'node:module'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { runProcess } from '../../../src/shared/child-process/run-process'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const probePath = require.resolve('./packaged-node-pty-capability-probe.cjs')
|
||||
const {
|
||||
buildGrandchildLaunch,
|
||||
createFixtureServer,
|
||||
isOneShotMode,
|
||||
reportFixtureObservation
|
||||
} = require(probePath)
|
||||
const originalSystemRoot = process.env.SystemRoot
|
||||
|
||||
afterEach(() => {
|
||||
if (originalSystemRoot === undefined) {
|
||||
delete process.env.SystemRoot
|
||||
} else {
|
||||
process.env.SystemRoot = originalSystemRoot
|
||||
}
|
||||
})
|
||||
|
||||
describe('packaged node-pty launcher-surviving grandchild', () => {
|
||||
it('flushes one-shot evidence and exits despite a referenced handle', async () => {
|
||||
expect(isOneShotMode('--exercise')).toBe(true)
|
||||
expect(isOneShotMode('--exit-contract-fixture')).toBe(true)
|
||||
expect(isOneShotMode('--pty-shell')).toBe(false)
|
||||
|
||||
const result = await runProcess({
|
||||
program: process.execPath,
|
||||
args: [probePath, '--exit-contract-fixture'],
|
||||
timeoutMs: 5_000
|
||||
})
|
||||
|
||||
expect(result).toMatchObject({ code: 0, timedOut: false })
|
||||
expect(result.stdout).toBe('ORCA_ONE_SHOT_EVIDENCE=flushed\n')
|
||||
expect(result.stderr).toBe('')
|
||||
})
|
||||
|
||||
it('uses the hidden WScript launcher without cmd or start/b', () => {
|
||||
process.env.SystemRoot = 'C:\\Windows'
|
||||
const channel = '\\\\.\\pipe\\fixture & literal'
|
||||
|
||||
const launch = buildGrandchildLaunch(channel, 'fixture-token^literal')
|
||||
|
||||
expect(launch.program).toMatch(/wscript\.exe$/i)
|
||||
expect(launch.args).toEqual([
|
||||
expect.stringMatching(/real-orca-detached-launcher\.vbs$/),
|
||||
process.execPath,
|
||||
probePath,
|
||||
'--grandchild-member',
|
||||
channel,
|
||||
'fixture-token^literal',
|
||||
'target-grandchild'
|
||||
])
|
||||
expect(JSON.stringify(launch)).not.toMatch(/cmd\.exe|start "" \/b/i)
|
||||
})
|
||||
|
||||
it('closes one-shot fixture observations before server teardown', async () => {
|
||||
const fixtureDir = await mkdtemp(join(tmpdir(), 'orca-pty-capability-'))
|
||||
const channel = join(fixtureDir, 'fixture.sock')
|
||||
const fixtureToken = 'fixture-token'
|
||||
const fixtures = createFixtureServer(channel, fixtureToken)
|
||||
|
||||
try {
|
||||
await fixtures.listening
|
||||
const observationPromise = fixtures.waitForRole('target-launcher-exited')
|
||||
|
||||
await reportFixtureObservation(channel, fixtureToken, 'target-launcher-exited', {
|
||||
pid: 1234
|
||||
})
|
||||
|
||||
await expect(observationPromise).resolves.toEqual({
|
||||
pid: 1234,
|
||||
fixtureToken,
|
||||
role: 'target-launcher-exited',
|
||||
channel
|
||||
})
|
||||
await expect(fixtures.close()).resolves.toBeUndefined()
|
||||
} finally {
|
||||
fixtures.destroySockets()
|
||||
await fixtures.close()
|
||||
await rm(fixtureDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
Option Explicit
|
||||
|
||||
Function QuoteArgument(value)
|
||||
If InStr(value, Chr(34)) > 0 Or InStr(value, vbCr) > 0 Or InStr(value, vbLf) > 0 Then
|
||||
Err.Raise vbObjectError + 1, "real-orca-detached-launcher", "Invalid argument"
|
||||
End If
|
||||
QuoteArgument = Chr(34) & value & Chr(34)
|
||||
End Function
|
||||
|
||||
Dim args, command, index, shell, status
|
||||
Set args = WScript.Arguments
|
||||
If args.Count = 0 Then
|
||||
Err.Raise vbObjectError + 2, "real-orca-detached-launcher", "Missing executable"
|
||||
End If
|
||||
|
||||
command = ""
|
||||
For index = 0 To args.Count - 1
|
||||
If Len(command) > 0 Then command = command & " "
|
||||
command = command & QuoteArgument(CStr(args(index)))
|
||||
Next
|
||||
|
||||
Set shell = CreateObject("WScript.Shell")
|
||||
status = shell.Run(command, 0, False)
|
||||
If status <> 0 Then WScript.Quit status
|
||||
@@ -0,0 +1,72 @@
|
||||
import { createRequire } from 'node:module'
|
||||
import path from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { assertPackagedNodePtyCapability } from './packaged-node-pty-capability-oracle.mjs'
|
||||
|
||||
const EVIDENCE_PREFIX = 'ORCA_NODE_PTY_CAPABILITY_EVIDENCE='
|
||||
const PROBE_TIMEOUT_MS = 45_000
|
||||
const MAX_DIAGNOSTIC_CHARS = 8_000
|
||||
|
||||
function executableArgument(argv) {
|
||||
const value = argv.find((arg) => arg.startsWith('--exe='))?.slice('--exe='.length)
|
||||
if (!value) {
|
||||
throw new Error('usage: windows-pty-native-capability-smoke --exe=<packaged Orca.exe>')
|
||||
}
|
||||
return path.resolve(value)
|
||||
}
|
||||
|
||||
export function checkoutRunProcessPath() {
|
||||
return path.resolve(import.meta.dirname, '../../../out/shared/child-process/run-process.js')
|
||||
}
|
||||
|
||||
export function packagedProbeInvocation(executable, environment = process.env) {
|
||||
const resolvedExecutable = path.resolve(executable)
|
||||
const resourcesDir = path.join(path.dirname(resolvedExecutable), 'resources')
|
||||
const probe = path.join(import.meta.dirname, 'packaged-node-pty-capability-probe.cjs')
|
||||
return {
|
||||
program: resolvedExecutable,
|
||||
args: [probe, '--exercise', resourcesDir, process.execPath],
|
||||
env: { ...environment, ELECTRON_RUN_AS_NODE: '1' },
|
||||
timeoutMs: PROBE_TIMEOUT_MS
|
||||
}
|
||||
}
|
||||
|
||||
function diagnosticTail(value) {
|
||||
return value.length <= MAX_DIAGNOSTIC_CHARS ? value : value.slice(-MAX_DIAGNOSTIC_CHARS)
|
||||
}
|
||||
|
||||
export function formatProbeFailure(result) {
|
||||
return [
|
||||
`packaged native capability probe failed (code=${result.code}, timedOut=${result.timedOut})`,
|
||||
`stdout:\n${diagnosticTail(result.stdout) || '<empty>'}`,
|
||||
`stderr:\n${diagnosticTail(result.stderr) || '<empty>'}`
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function parseEvidence(stdout) {
|
||||
const line = stdout.split(/\r?\n/).find((candidate) => candidate.startsWith(EVIDENCE_PREFIX))
|
||||
if (!line) {
|
||||
throw new Error(`packaged probe did not emit ${EVIDENCE_PREFIX}`)
|
||||
}
|
||||
return JSON.parse(line.slice(EVIDENCE_PREFIX.length))
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (process.platform !== 'win32') {
|
||||
throw new Error('windows-pty-native-capability-smoke requires a physical Windows host')
|
||||
}
|
||||
const executable = executableArgument(process.argv.slice(2))
|
||||
const require = createRequire(import.meta.url)
|
||||
const { runProcess } = require(checkoutRunProcessPath())
|
||||
const result = await runProcess(packagedProbeInvocation(executable))
|
||||
if (result.code !== 0 || result.timedOut) {
|
||||
throw new Error(formatProbeFailure(result))
|
||||
}
|
||||
|
||||
assertPackagedNodePtyCapability(parseEvidence(result.stdout))
|
||||
process.stdout.write(`[windows-pty-native-capability-smoke] PASS ${executable}\n`)
|
||||
}
|
||||
|
||||
if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
|
||||
await main()
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { checkoutRunProcessPath, formatProbeFailure, packagedProbeInvocation } from './run.mjs'
|
||||
|
||||
const runnerSource = readFileSync(new URL('./run.mjs', import.meta.url), 'utf8')
|
||||
|
||||
describe('packaged Windows native smoke runner boundary', () => {
|
||||
it('uses one checkout-owned runner for current and affected package paths', () => {
|
||||
const current = packagedProbeInvocation('/ci/current/dist/win-unpacked/Orca.exe')
|
||||
const affected = packagedProbeInvocation('/ci/1.4.158/dist/win-unpacked/Orca.exe')
|
||||
|
||||
expect(checkoutRunProcessPath()).toBe(path.resolve('out/shared/child-process/run-process.js'))
|
||||
expect(current.program).not.toBe(affected.program)
|
||||
expect(current.args[0]).toBe(affected.args[0])
|
||||
expect(current.args[1]).toBe('--exercise')
|
||||
expect(current.args[2]).not.toBe(affected.args[2])
|
||||
expect(current.args[3]).toBe(process.execPath)
|
||||
expect(affected.args[3]).toBe(process.execPath)
|
||||
expect(current.env.ELECTRON_RUN_AS_NODE).toBe('1')
|
||||
expect(affected.env.ELECTRON_RUN_AS_NODE).toBe('1')
|
||||
expect(current.timeoutMs).toBe(affected.timeoutMs)
|
||||
expect(current.timeoutMs).toBe(45_000)
|
||||
})
|
||||
|
||||
it('keeps timeout evidence bounded and preserves both output channels', () => {
|
||||
const failure = formatProbeFailure({
|
||||
code: null,
|
||||
timedOut: true,
|
||||
stdout: `old-${'x'.repeat(9_000)}-stdout-tail`,
|
||||
stderr: 'stage=target-spawn:start'
|
||||
})
|
||||
|
||||
expect(failure).toContain('code=null, timedOut=true')
|
||||
expect(failure).not.toContain('old-')
|
||||
expect(failure).toContain('stdout-tail')
|
||||
expect(failure).toContain('stage=target-spawn:start')
|
||||
})
|
||||
|
||||
it('does not import child_process or resolve the runner from the artifact', () => {
|
||||
expect(runnerSource).not.toContain('node:child_process')
|
||||
expect(runnerSource).not.toMatch(
|
||||
/path\.join\(resourcesDir[\s\S]*?app\.asar\.unpacked[\s\S]*?run-process\.js/
|
||||
)
|
||||
expect(runnerSource).toContain("'../../../out/shared/child-process/run-process.js'")
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user