mirror of
https://github.com/stablyai/orca.git
synced 2026-10-23 16:03:49 +00:00
Merge remote-tracking branch 'origin/main' into brennanb2025/popover-wheel-scroll-in-dialog
This commit is contained in:
@@ -74,6 +74,7 @@ jobs:
|
||||
xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-golden
|
||||
xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:posix-profile-index-golden
|
||||
xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:agent-tui-golden
|
||||
xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:tab-bar-agent-launch-golden
|
||||
xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:source-control-golden
|
||||
|
||||
- name: Run golden E2E tests on macOS
|
||||
@@ -87,6 +88,7 @@ jobs:
|
||||
env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:terminal-rendering-golden
|
||||
env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:posix-profile-index-golden
|
||||
env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:agent-tui-golden
|
||||
env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:tab-bar-agent-launch-golden
|
||||
env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run --if-present test:e2e:source-control-golden
|
||||
|
||||
- name: Run golden E2E tests on Windows
|
||||
@@ -97,6 +99,7 @@ jobs:
|
||||
$env:ORCA_E2E_FORWARD_APP_LOGS = '1'
|
||||
pnpm run --if-present test:e2e:workspace-session-golden
|
||||
pnpm run --if-present test:e2e:windows-fresh-startup-golden
|
||||
pnpm run --if-present test:e2e:tab-bar-agent-launch-golden
|
||||
if (Test-Path tests/e2e/golden-fresh-profile-terminal.spec.ts) {
|
||||
pnpm run test:e2e -- tests/e2e/golden-fresh-profile-terminal.spec.ts tests/e2e/golden-shell-command.spec.ts
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
+588
-32
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"updatedAt": "2026-08-20",
|
||||
"updatedAt": "2026-08-23",
|
||||
"policy": {
|
||||
"maturityLevels": ["experimental", "soak", "blocking", "accepted-gap", "deprecated"],
|
||||
"blockingPromotion": {
|
||||
@@ -2674,7 +2674,7 @@
|
||||
"platform": "macos",
|
||||
"command": "ORCA_E2E_WEB_CLIENT=1 ORCA_E2E_FORCE_HEADFUL=1 pnpm exec playwright test tests/e2e/paired-remote-terminal-browser-link.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
|
||||
"result": "failed",
|
||||
"durationSeconds": 60,
|
||||
"durationSeconds": 53,
|
||||
"summary": "The byte-identical final Electron oracle failed at its exact host/client identity barrier when the sole source delta replaced src/renderer/src/store/index.ts registration lines 110-113 with registerRuntimeHttpLinkBrowserOpener(null); no host-owned browser appeared within the deterministic 60-second bound."
|
||||
}
|
||||
],
|
||||
@@ -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,
|
||||
@@ -12284,7 +12337,7 @@
|
||||
"id": "terminal-render.pixel-refresh-repair",
|
||||
"title": "Forced repaint does not change revealed pane pixels",
|
||||
"maturity": "experimental",
|
||||
"protection": "none",
|
||||
"protection": "partial",
|
||||
"owner": "terminal-rendering",
|
||||
"layer": "electron-visual-golden",
|
||||
"surfaces": [
|
||||
@@ -12296,47 +12349,207 @@
|
||||
],
|
||||
"platforms": ["macos", "linux", "windows"],
|
||||
"providers": ["local", "daemon"],
|
||||
"coveredPlatforms": [],
|
||||
"coveredProviders": [],
|
||||
"coverageNotes": "Registered gap only; the live repro harness with a refresh-repair oracle exists but is not productized into the release-blocking terminal-rendering-golden suite.",
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["local"],
|
||||
"coverageNotes": "A headed macOS Electron test drives explicit destructive atlas recovery while DEC 2026 output is held, then compares compositor screenshots before and after a direct full-buffer present. The same renderer choreography is provider-local, but daemon, SSH, remote-runtime, Linux, and Windows GPU runs remain gaps.",
|
||||
"motivatingLinks": [
|
||||
"https://github.com/stablyai/orca/pull/7133",
|
||||
"https://github.com/stablyai/orca/pull/7054"
|
||||
],
|
||||
"invariant": "After any reveal, restore, or wake, the pixels a pane displays must equal what a forced full model-invalidating repaint would draw from the buffer; a material refresh-repair diff means stale rendering escaped, whatever the mechanism.",
|
||||
"oracle": "Screenshot the revealed pane, force a model-invalidating full repaint, screenshot again, and assert the bounded pixel diff is immaterial; pair with a JS-level render-model-vs-buffer comparison. Compositor screenshots only, because WebGL canvas readback is blank with preserveDrawingBuffer disabled.",
|
||||
"commands": [],
|
||||
"testFiles": [],
|
||||
"assertionRefs": [],
|
||||
"evidenceRuns": [],
|
||||
"invariant": "After proven renderer damage triggers destructive recovery, visible pixels equal a full model-invalidating present of the current buffer.",
|
||||
"oracle": "Hold DEC 2026, invoke explicit atlas recovery, require an atlas clear, screenshot the pane, force a direct renderer present, and assert the bounded pixel diff is immaterial. Compositor screenshots only, because WebGL canvas readback is blank with preserveDrawingBuffer disabled.",
|
||||
"commands": [
|
||||
"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection-hidden-backlog-snapshot.test.ts src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts src/renderer/src/lib/pane-manager/pane-manager-registry.test.ts src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.test.ts src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts",
|
||||
"ORCA_E2E_RECORD_VIDEO=1 pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --repeat-each=3"
|
||||
],
|
||||
"testFiles": [
|
||||
"src/renderer/src/components/terminal-pane/pty-connection-hidden-backlog-snapshot.test.ts",
|
||||
"src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts",
|
||||
"src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts",
|
||||
"src/renderer/src/lib/pane-manager/pane-manager-registry.test.ts",
|
||||
"src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts",
|
||||
"src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.test.ts",
|
||||
"src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts",
|
||||
"tests/e2e/terminal-reveal-paused-render-repro.spec.ts"
|
||||
],
|
||||
"assertionRefs": [
|
||||
{
|
||||
"file": "src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts",
|
||||
"assertions": [
|
||||
"deduplicates a deferred dpr retry and consumes it after repair succeeds",
|
||||
"caps a deferred dpr transition at sixteen animation-frame retries"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts",
|
||||
"assertions": ["defers a heavy-reveal dpr present until the shared atlas recovery"]
|
||||
},
|
||||
{
|
||||
"file": "src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.test.ts",
|
||||
"assertions": [
|
||||
"repairs when the canvas and renderer dimensions share a stale dpr cache",
|
||||
"defers an unmeasurable WebGL canvas but accepts a renderer-less pane"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "tests/e2e/terminal-reveal-paused-render-repro.spec.ts",
|
||||
"assertions": ["@headful atlas recovery presents a synchronized-output WebGL frame"]
|
||||
}
|
||||
],
|
||||
"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/pty-connection-hidden-backlog-snapshot.test.ts src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts src/renderer/src/components/terminal-pane/use-terminal-window-wake-recovery.test.ts src/renderer/src/lib/pane-manager/pane-manager-registry.test.ts src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts src/renderer/src/lib/pane-manager/terminal-canvas-dpr-repair.test.ts src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts",
|
||||
"result": "passed",
|
||||
"durationSeconds": 2,
|
||||
"summary": "All 98 renderer contracts passed, including same-DPR zero-scan behavior, visible-only fanout, tri-state DPR repair, deduplicated bounded retry, heavy-reveal repair, and listener cleanup."
|
||||
},
|
||||
{
|
||||
"date": "2026-08-23",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1",
|
||||
"result": "passed",
|
||||
"durationSeconds": 60,
|
||||
"summary": "Both headed oracles passed together. Explicit destructive atlas recovery presented the held synchronized-output buffer with zero pixels different from a direct renderer present; the test attached before/after screenshots plus pixel-diff metadata."
|
||||
},
|
||||
{
|
||||
"date": "2026-08-22",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "ORCA_E2E_RECORD_VIDEO=1 pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1 --repeat-each=3",
|
||||
"result": "passed",
|
||||
"durationSeconds": 48,
|
||||
"summary": "Three consecutive headed real-WebGL runs passed in 15.0-15.7 seconds each and emitted a 1920x1080 video per BrowserWindow."
|
||||
}
|
||||
],
|
||||
"runtimeBudget": {
|
||||
"p95Seconds": 300,
|
||||
"scope": "release-blocking golden Electron visual test"
|
||||
"p95Seconds": 120,
|
||||
"scope": "focused prebuilt headed Electron visual test"
|
||||
},
|
||||
"flakeHistory": {
|
||||
"status": "not-started",
|
||||
"evidence": "Runs nightly only while the per-platform diff threshold stabilizes; the destination is the release-blocking terminal-rendering-golden suite in release-cut.yml."
|
||||
"status": "unknown",
|
||||
"evidence": "Five local macOS headed runs passed, including one on the final branch state and three consecutive video-recorded repeats; CI soak history and cross-platform GPU runs are not yet available."
|
||||
},
|
||||
"redGreenEvidence": {
|
||||
"status": "missing",
|
||||
"evidence": "Needs an intentionally fossilized render model (skip the model invalidation on reveal) proving the refresh-repair diff fires."
|
||||
"status": "complete",
|
||||
"evidence": "Without the forced synchronized-output present, the damaged compositor differed from a direct renderer present across 87.68% of pixels even though serialization already contained the new frame. With explicit destructive recovery, the same oracle passes the 1.5% material-diff threshold."
|
||||
},
|
||||
"performanceBudget": {
|
||||
"required": true,
|
||||
"evidence": "Soak-only; must not add product-path repaints beyond the existing reveal hardening."
|
||||
"evidence": "Destructive recovery remains event-driven and limited to confirmed renderer-lifecycle boundaries. Gate-local contracts prove ordinary same-DPR resize performs zero pane scans; a true transition scans only the visible manager; unavailable canvas retry is deduplicated and capped at 16 frames; and heavy reveal adds one bounded visible-pane scan. The shared terminal-render.atlas-recovery-fanout contracts separately prove zero hidden-manager atlas clears or presents and a per-pane display:none retry capped at 16 frames."
|
||||
},
|
||||
"promotionCriteria": [
|
||||
"Productize the existing stale-render repro harness with the refresh-repair oracle and failure artifacts.",
|
||||
"Establish a stable material-diff threshold across platforms via nightly runs.",
|
||||
"Promotion means membership in the release-blocking terminal-rendering-golden suite that release-cut.yml runs against every release tag; never PR-blocking.",
|
||||
"Register the gate command as a direct spec-file invocation; the checker rejects --grep tag selectors, so do not reuse the existing --grep-based golden script as the command."
|
||||
"Add Linux and Windows GPU evidence or retain those platform gaps explicitly."
|
||||
],
|
||||
"knownGaps": [
|
||||
"No manifest command yet.",
|
||||
"Buffer-clean, pixels-stale variants are otherwise invisible to every buffer oracle in the manifest."
|
||||
"The deterministic recovery test disables xterm's one-second safety timeout so the held-frame damage remains stable until recovery.",
|
||||
"The renderer-level frame injection isolates the paint failure; provider delivery and hidden-output snapshot restore have separate gates.",
|
||||
"Linux, Windows, daemon, SSH, and remote-runtime live GPU evidence is not yet recorded."
|
||||
],
|
||||
"demotionRule": "Drop from the golden suite back to nightly diagnostic if diff thresholds cannot be kept stable across CI runners."
|
||||
},
|
||||
{
|
||||
"id": "terminal-render.synchronized-reveal-coherence",
|
||||
"title": "Ordinary reveal preserves synchronized-output frame coherence",
|
||||
"maturity": "experimental",
|
||||
"protection": "partial",
|
||||
"owner": "terminal-rendering",
|
||||
"layer": "electron-visual-golden",
|
||||
"surfaces": ["WebGL rendering", "tab reveal", "snapshot restore", "DEC 2026"],
|
||||
"platforms": ["macos", "linux", "windows"],
|
||||
"providers": ["local", "daemon", "ssh", "remote-runtime"],
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["local"],
|
||||
"coverageNotes": "A headed macOS Electron test uses a real xterm WebGL renderer and production tab reveal. It proves the coherent pre-hide canvas remains visible while DEC 2026 holds a newer buffer, then proves normal release and xterm's one-second watchdog publish complete frames. Renderer behavior is provider-neutral; live Linux, Windows, daemon, SSH, and remote-runtime GPU runs remain gaps.",
|
||||
"motivatingLinks": [
|
||||
"https://github.com/stablyai/orca/pull/7133",
|
||||
"https://github.com/stablyai/orca/pull/7054"
|
||||
],
|
||||
"invariant": "terminal-render.synchronized-reveal-coherence: an ordinary reveal never clears a healthy shared atlas or publishes a partially built DEC 2026 frame; it retains the last coherent canvas until release or xterm's bounded watchdog.",
|
||||
"oracle": "Paint and capture a coherent frame, hide the real terminal tab, build a distinct full-screen frame while DEC 2026 is held, reveal through production, and require zero atlas clears plus pixel-equivalence with the coherent frame. Then release normally and through the one-second watchdog, requiring both compositor frames to match a direct renderer present.",
|
||||
"commands": [
|
||||
"pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection-hidden-backlog-snapshot.test.ts src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts"
|
||||
],
|
||||
"testFiles": [
|
||||
"src/renderer/src/components/terminal-pane/pty-connection-hidden-backlog-snapshot.test.ts",
|
||||
"src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts",
|
||||
"src/renderer/src/components/terminal-pane/terminal-webgl-atlas-recovery.test.ts",
|
||||
"src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts",
|
||||
"src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts",
|
||||
"tests/e2e/terminal-reveal-paused-render-repro.spec.ts"
|
||||
],
|
||||
"assertionRefs": [
|
||||
{
|
||||
"file": "src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts",
|
||||
"assertions": [
|
||||
"schedules an atlas-preserving present on a light tab reveal",
|
||||
"keeps heavy atlas recovery off a plain window refocus"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/renderer/src/lib/pane-manager/pane-webgl-renderer.test.ts",
|
||||
"assertions": ["preserves a synchronized frame on an ordinary reveal present"]
|
||||
},
|
||||
{
|
||||
"file": "src/renderer/src/lib/pane-manager/terminal-render-pause-release.test.ts",
|
||||
"assertions": [
|
||||
"routes synchronized output through RenderService instead of the renderer",
|
||||
"releases observer pause before requesting the synchronized frame"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "tests/e2e/terminal-reveal-paused-render-repro.spec.ts",
|
||||
"assertions": [
|
||||
"@headful reveal preserves the coherent frame until synchronized output releases"
|
||||
]
|
||||
}
|
||||
],
|
||||
"evidenceRuns": [
|
||||
{
|
||||
"date": "2026-08-23",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "pnpm run ensure:electron-runtime && pnpm exec playwright test tests/e2e/terminal-reveal-paused-render-repro.spec.ts --config tests/playwright.config.ts --project electron-headful --workers=1",
|
||||
"result": "passed",
|
||||
"durationSeconds": 53,
|
||||
"summary": "Both final-head headed oracles passed together. The coherent held frame differed by 73 of 1,404,288 pixels (0.0052%), ordinary reveal performed zero atlas clears, normal release differed from the direct present by 95 pixels (0.0068%), and watchdog release matched exactly. All three ratios passed the 1.5% compositor threshold."
|
||||
}
|
||||
],
|
||||
"runtimeBudget": {
|
||||
"p95Seconds": 120,
|
||||
"scope": "focused prebuilt headed Electron prevention and watchdog test"
|
||||
},
|
||||
"flakeHistory": {
|
||||
"status": "unknown",
|
||||
"evidence": "One final watchdog-inclusive macOS headed run passed; CI soak history and cross-platform GPU runs are not yet available."
|
||||
},
|
||||
"redGreenEvidence": {
|
||||
"status": "complete",
|
||||
"evidence": "Before the prevention change, the ordinary reveal oracle failed deterministically because it observed three atlas clears. After the change, reveal performs zero clears and the first visible frame remains pixel-equivalent to the coherent pre-hide frame."
|
||||
},
|
||||
"performanceBudget": {
|
||||
"required": true,
|
||||
"evidence": "Ordinary reveal removes three shared-atlas clears and their global visible-manager presents. It adds one settled, event-driven full-viewport refresh request per revealed pane; DEC 2026 coalesces it and uses xterm's existing one-second watchdog. No polling, subprocess, provider call, PTY inventory, background-output work, listener, or unbounded retry was added; the display-none retry remains deduplicated and capped at 16 frames."
|
||||
},
|
||||
"promotionCriteria": [
|
||||
"Accumulate stable macOS runs for both normal release and watchdog release.",
|
||||
"Add Linux and Windows GPU evidence or retain those platform gaps explicitly.",
|
||||
"Keep the destructive atlas-recovery oracle separate and passing."
|
||||
],
|
||||
"knownGaps": [
|
||||
"The deterministic test injects full-screen marker frames through xterm rather than invoking a live model; genuine OpenCode full-window evidence separately proves the original corruption.",
|
||||
"Linux, Windows, daemon, SSH, and remote-runtime live GPU evidence is not yet recorded.",
|
||||
"The 1.5% compositor threshold tolerates cursor and shell-prompt timing noise; exact buffer content and atlas-clear counts are asserted separately."
|
||||
],
|
||||
"demotionRule": "Demote if ordinary reveal clears the shared atlas, the held frame stops matching its coherent baseline, release/watchdog output diverges from a direct present, or the headed oracle cannot remain deterministic."
|
||||
},
|
||||
{
|
||||
"id": "pty-delivery.renderer-lifecycle-accounting-reset",
|
||||
"title": "Renderer lifecycle reset clears leaked PTY delivery accounting so surviving PTYs cannot freeze",
|
||||
@@ -14089,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)')
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="106" height="20" role="img" aria-label="downloads: 27m">
|
||||
<title>downloads: 27m</title>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="106" height="20" role="img" aria-label="downloads: 28m">
|
||||
<title>downloads: 28m</title>
|
||||
<linearGradient id="s" x2="0" y2="100%">
|
||||
<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>
|
||||
<stop offset="1" stop-opacity=".1"/>
|
||||
@@ -15,7 +15,7 @@
|
||||
<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" text-rendering="geometricPrecision" font-size="11">
|
||||
<text x="37" y="15" fill="#010101" fill-opacity=".3">downloads</text>
|
||||
<text x="37" y="14">downloads</text>
|
||||
<text x="90" y="15" fill="#010101" fill-opacity=".3">27m</text>
|
||||
<text x="90" y="14">27m</text>
|
||||
<text x="90" y="15" fill="#010101" fill-opacity=".3">28m</text>
|
||||
<text x="90" y="14">28m</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
||||
|
Before Width: | Height: | Size: 935 B After Width: | Height: | Size: 935 B |
@@ -100,6 +100,7 @@
|
||||
"test:e2e:posix-profile-index-golden": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/golden-posix-fresh-startup.spec.ts tests/e2e/golden-posix-profile-index-fsync.spec.ts --grep @posix-profile-index-golden --config tests/playwright.config.ts --project electron-headless --workers=1",
|
||||
"test:e2e:windows-fresh-startup-golden": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/golden-windows-fresh-startup.spec.ts --grep @windows-fresh-startup-golden --config tests/playwright.config.ts --project electron-headless --workers=1",
|
||||
"test:e2e:agent-tui-golden": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/golden-agent-tui-launch.spec.ts tests/e2e/golden-shell-after-agent-exit.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
|
||||
"test:e2e:tab-bar-agent-launch-golden": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/golden-tab-bar-agent-launch.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
|
||||
"test:e2e:terminal-rendering-release-evidence": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/terminal-opencode-emoji-table-rendering.spec.ts tests/e2e/terminal-long-table-scroll-restore.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=2",
|
||||
"test:e2e:terminal-perf": "pnpm run ensure:electron-runtime && npx playwright test tests/e2e/terminal-typing-latency.spec.ts tests/e2e/terminal-foreground-redraw-freeze.spec.ts tests/e2e/terminal-output-scheduler.spec.ts tests/e2e/terminal-hidden-tui-visual-restore.spec.ts tests/e2e/artificial-opencode-terminal-load.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=2",
|
||||
"test:e2e:terminal-perf:scale": "pnpm run ensure:electron-runtime && node config/scripts/run-terminal-scale-perf-e2e.mjs",
|
||||
@@ -114,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",
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { makePaneKey } from '../../shared/stable-pane-id'
|
||||
import { AgentHookServer } from './server'
|
||||
|
||||
const LEAF = '11111111-1111-4111-8111-111111111111'
|
||||
const PANE = makePaneKey('tab-1', LEAF)
|
||||
|
||||
let dir: string
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'orca-ended-process-'))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
async function startServer(): Promise<AgentHookServer> {
|
||||
const server = new AgentHookServer()
|
||||
await server.start({ env: 'production', userDataPath: dir })
|
||||
return server
|
||||
}
|
||||
|
||||
function claudeRow(server: AgentHookServer, state: 'working' | 'waiting' | 'done'): void {
|
||||
server.ingestTerminalStatus({
|
||||
paneKey: PANE,
|
||||
tabId: 'tab-1',
|
||||
worktreeId: 'wt-1',
|
||||
connectionId: null,
|
||||
payload: { state, prompt: 'review the PR', agentType: 'claude' }
|
||||
})
|
||||
}
|
||||
|
||||
/** A row carrying a resumable provider session — the only shape `dropStatusEntry` retains. */
|
||||
function resumableClaudeRow(server: AgentHookServer): void {
|
||||
server.ingestRemote(
|
||||
{
|
||||
paneKey: PANE,
|
||||
tabId: 'tab-1',
|
||||
worktreeId: 'wt-1',
|
||||
source: 'claude',
|
||||
hookEventName: 'UserPromptSubmit',
|
||||
launchToken: 'dead-launch-token',
|
||||
providerSession: { key: 'session_id', id: 'resume-me' },
|
||||
payload: { state: 'working', prompt: 'review the PR', agentType: 'claude' }
|
||||
},
|
||||
'conn-a'
|
||||
)
|
||||
}
|
||||
|
||||
function paneState(server: AgentHookServer): string {
|
||||
return server.getStatusSnapshotForPane(PANE)[0]?.state ?? 'missing'
|
||||
}
|
||||
|
||||
// The teardown that normally clears a dead pane depends on the spawn-time ptyPaneKey mapping, which
|
||||
// a restored PTY may never rebuild — leaving the row and its latches with nothing left to retire
|
||||
// them. See PLAN-STA-4612 §4.2.
|
||||
describe('reconcileEndedProcessForPaneKeys', () => {
|
||||
it('retires a working row whose process is certifiably dead', async () => {
|
||||
const server = await startServer()
|
||||
try {
|
||||
claudeRow(server, 'working')
|
||||
expect(paneState(server)).toBe('working')
|
||||
|
||||
expect(server.reconcileEndedProcessForPaneKeys([PANE])).toBe(1)
|
||||
|
||||
expect(paneState(server)).toBe('missing')
|
||||
} finally {
|
||||
server.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('retires a waiting row — a wait whose owner is dead is not a wait', async () => {
|
||||
const server = await startServer()
|
||||
try {
|
||||
claudeRow(server, 'waiting')
|
||||
|
||||
expect(server.reconcileEndedProcessForPaneKeys([PANE])).toBe(1)
|
||||
|
||||
expect(paneState(server)).toBe('missing')
|
||||
} finally {
|
||||
server.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('clears Claude latches even when the stored row already reads done', async () => {
|
||||
// An interrupted lead suppresses the gate while leaving the latch set, so a row can read `done`
|
||||
// with a latch that would re-gate `working` on the pane's very next event.
|
||||
const server = await startServer()
|
||||
try {
|
||||
claudeRow(server, 'done')
|
||||
server._getStateForTests().claudeRunningNonAgentTaskPaneKeys.add(PANE)
|
||||
server._getStateForTests().claudeActiveSessionCronPaneKeys.add(PANE)
|
||||
|
||||
expect(server.reconcileEndedProcessForPaneKeys([PANE])).toBe(1)
|
||||
|
||||
expect(server._getStateForTests().claudeRunningNonAgentTaskPaneKeys.has(PANE)).toBe(false)
|
||||
expect(server._getStateForTests().claudeActiveSessionCronPaneKeys.has(PANE)).toBe(false)
|
||||
} finally {
|
||||
server.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('is a no-op for a pane with nothing to retire', async () => {
|
||||
const server = await startServer()
|
||||
try {
|
||||
expect(server.reconcileEndedProcessForPaneKeys([PANE])).toBe(0)
|
||||
} finally {
|
||||
server.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps the resume identity a paired dismissal minted when the shell outlived the agent', async () => {
|
||||
// The renderer's confirmed-shell route calls agentStatus:drop FIRST, which deliberately mints a
|
||||
// providerSessionOnly remnant, then this. That remnant carries no state claim — it cannot gate a
|
||||
// pane `working` — and the pane's PTY is still there to resume into, so retiring the pane's live
|
||||
// claims must not take it. Without the option it goes with everything else.
|
||||
const server = await startServer()
|
||||
try {
|
||||
resumableClaudeRow(server)
|
||||
server.dropStatusEntry(PANE)
|
||||
const afterDrop = server.getStatusSnapshotForPane(PANE)[0]
|
||||
expect(afterDrop?.providerSessionOnly).toBe(true)
|
||||
expect(afterDrop?.providerSession?.id).toBe('resume-me')
|
||||
|
||||
expect(
|
||||
server.reconcileEndedProcessForPaneKeys([PANE], { preserveResumeIdentity: true })
|
||||
).toBe(1)
|
||||
|
||||
const kept = server.getStatusSnapshotForPane(PANE)[0]
|
||||
expect(kept?.providerSessionOnly).toBe(true)
|
||||
expect(kept?.providerSession?.id).toBe('resume-me')
|
||||
expect(kept?.launchToken).toBeUndefined()
|
||||
// The live claims still went: a latch left behind would re-gate the pane on its next event.
|
||||
expect(server._getStateForTests().claudeRunningNonAgentTaskPaneKeys.has(PANE)).toBe(false)
|
||||
|
||||
// The retained identity must not recreate dead launch authority after restart.
|
||||
server.flushStatusPersistSync()
|
||||
server.stop()
|
||||
const restarted = await startServer()
|
||||
expect(restarted.getStatusSnapshotForPane(PANE)[0]?.launchToken).toBeUndefined()
|
||||
expect(restarted.getHydratedAuthorityCommitments()).toHaveLength(0)
|
||||
restarted.stop()
|
||||
} finally {
|
||||
server.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('takes the resume identity too on a certified PTY exit, where no pane is left to resume into', async () => {
|
||||
const server = await startServer()
|
||||
try {
|
||||
resumableClaudeRow(server)
|
||||
server.dropStatusEntry(PANE)
|
||||
|
||||
expect(server.reconcileEndedProcessForPaneKeys([PANE])).toBe(1)
|
||||
|
||||
expect(paneState(server)).toBe('missing')
|
||||
} finally {
|
||||
server.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('drops the session owner so a rebound pane is not read as a session replacement', async () => {
|
||||
const server = await startServer()
|
||||
try {
|
||||
claudeRow(server, 'working')
|
||||
server._getStateForTests().claudeSessionOwnerByPaneKey.set(PANE, 'session-a')
|
||||
|
||||
server.reconcileEndedProcessForPaneKeys([PANE])
|
||||
|
||||
expect(server._getStateForTests().claudeSessionOwnerByPaneKey.has(PANE)).toBe(false)
|
||||
} finally {
|
||||
server.stop()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -211,7 +211,10 @@ describe('restored subagent liveness sweep', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('does not probe a hydrated Claude pane without restored rows', async () => {
|
||||
it('reaps a hydrated non-terminal row with no roster at all (STA-4612)', async () => {
|
||||
// A restored roster is only one shape of stranded claim. A lead row left `working` with no
|
||||
// children has nothing left to retire it — no child event, no inventory, no hook — so it holds
|
||||
// the pane working for good and locks its agent out of hibernation.
|
||||
const server = await restartWithInFlightSubagent({ subagents: [] })
|
||||
const probeLiveLocalPty = vi.fn(() => false)
|
||||
try {
|
||||
@@ -220,9 +223,42 @@ describe('restored subagent liveness sweep', () => {
|
||||
probeLiveLocalPty,
|
||||
persistedPtyIdByPaneKey: { [PANE]: PTY }
|
||||
})
|
||||
).toBe(1)
|
||||
|
||||
expect(probeLiveLocalPty).toHaveBeenCalled()
|
||||
expect(paneStatus(server).state).toBe('missing')
|
||||
} finally {
|
||||
server.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps a hydrated non-terminal row with no roster when its PTY is still live', async () => {
|
||||
const server = await restartWithInFlightSubagent({ subagents: [] })
|
||||
try {
|
||||
expect(
|
||||
await sweepWith(server, {
|
||||
probeLiveLocalPty: () => true,
|
||||
persistedPtyIdByPaneKey: { [PANE]: PTY }
|
||||
})
|
||||
).toBe(0)
|
||||
|
||||
expect(probeLiveLocalPty).not.toHaveBeenCalled()
|
||||
expect(paneStatus(server).state).toBe('working')
|
||||
} finally {
|
||||
server.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps a hydrated non-terminal row with no roster when the probe cannot prove either state', async () => {
|
||||
const server = await restartWithInFlightSubagent({ subagents: [] })
|
||||
try {
|
||||
expect(
|
||||
await sweepWith(server, {
|
||||
probeLiveLocalPty: () => null,
|
||||
persistedPtyIdByPaneKey: { [PANE]: PTY }
|
||||
})
|
||||
).toBe(0)
|
||||
|
||||
expect(paneStatus(server).state).toBe('working')
|
||||
} finally {
|
||||
server.stop()
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import { ORCA_HOOK_PROTOCOL_VERSION } from '../../shared/agent-hook-types'
|
||||
import {
|
||||
clearAllListenerCaches,
|
||||
clearPaneCacheState,
|
||||
paneHasStateClaims,
|
||||
clearClaudeAnsweredQuestionWait,
|
||||
createHookListenerState,
|
||||
getEndpointFileName,
|
||||
@@ -2652,28 +2653,87 @@ export class AgentHookServer {
|
||||
this.notifyStatusChangeListeners()
|
||||
}
|
||||
|
||||
/** The resume-identity remnant of a dropped row: a `providerSessionOnly` entry carries no state
|
||||
* claim — it cannot gate a pane `working` — so it survives teardowns that end the pane's live
|
||||
* claims. Returns null when the row has no resumable session to keep. */
|
||||
private toRetainedProviderSessionRow(
|
||||
entry: EnrichedAgentHookEventPayload | null | undefined
|
||||
): EnrichedAgentHookEventPayload | null {
|
||||
if (
|
||||
!entry?.providerSession ||
|
||||
!entry.payload.agentType ||
|
||||
entry.payload.agentType === 'unknown'
|
||||
) {
|
||||
return null
|
||||
}
|
||||
const { launchToken: _launchToken, ...resumeIdentity } = entry
|
||||
return { ...resumeIdentity, providerSessionOnly: true, retainedForLiveness: true }
|
||||
}
|
||||
|
||||
/** Drop only the status row (user dismissal); do NOT wipe prompt/tool caches since the pane's agent may still be alive. Use clearPaneState for PTY-teardown. */
|
||||
dropStatusEntry(paneKey: string): void {
|
||||
const deleted = this.deleteStatusEntry(paneKey, { preserveAuthority: true })
|
||||
if (!deleted) {
|
||||
return
|
||||
}
|
||||
if (
|
||||
deleted.providerSession &&
|
||||
deleted.payload.agentType &&
|
||||
deleted.payload.agentType !== 'unknown'
|
||||
) {
|
||||
const retained: EnrichedAgentHookEventPayload = {
|
||||
...deleted,
|
||||
providerSessionOnly: true,
|
||||
retainedForLiveness: true
|
||||
}
|
||||
const retained = this.toRetainedProviderSessionRow(deleted)
|
||||
if (retained) {
|
||||
this.state.lastStatusByPaneKey.set(deleted.paneKey, retained)
|
||||
}
|
||||
this.scheduleStatusPersist()
|
||||
this.notifyStatusChangeListeners()
|
||||
}
|
||||
|
||||
/** Retire panes whose owning process is certifiably dead.
|
||||
*
|
||||
* The ordinary teardown already does this: every attributable PTY exit reaches
|
||||
* `clearProviderPtyState`, which resolves the pane key and calls `clearPaneState`. But that
|
||||
* resolution depends on the spawn-time `ptyPaneKey` mapping, which a restored/reattached PTY may
|
||||
* never rebuild — so those panes keep a `working` row and its latches for good, with no hook left
|
||||
* to retire them. This is the same operation reached from the runtime's own pane-key knowledge,
|
||||
* so a dead pane is cleaned up identically however its keys were resolved. */
|
||||
reconcileEndedProcessForPaneKeys(
|
||||
paneKeys: Iterable<string>,
|
||||
options?: {
|
||||
/** The pane's PTY outlived its agent (a confirmed shell foreground), so the session can still
|
||||
* be resumed in place — keep the `providerSessionOnly` remnant the paired `agentStatus:drop`
|
||||
* minted for exactly this case. A certified PTY exit passes nothing: there is no pane left to
|
||||
* resume into, and dropping it matches what `clearProviderPtyState` already does. */
|
||||
preserveResumeIdentity?: boolean
|
||||
}
|
||||
): number {
|
||||
let cleared = 0
|
||||
for (const paneKey of paneKeys) {
|
||||
const resolvedPaneKey = this.resolvePaneKeyAlias(paneKey)
|
||||
if (!this.hasLiveClaimsForPaneKey(resolvedPaneKey)) {
|
||||
continue
|
||||
}
|
||||
const retained = options?.preserveResumeIdentity
|
||||
? this.toRetainedProviderSessionRow(
|
||||
this.state.lastStatusByPaneKey.get(resolvedPaneKey) as
|
||||
| EnrichedAgentHookEventPayload
|
||||
| undefined
|
||||
)
|
||||
: null
|
||||
this.clearPaneState(resolvedPaneKey)
|
||||
if (retained) {
|
||||
this.state.lastStatusByPaneKey.set(resolvedPaneKey, retained)
|
||||
this.scheduleStatusPersist()
|
||||
this.notifyStatusChangeListeners()
|
||||
}
|
||||
cleared += 1
|
||||
}
|
||||
return cleared
|
||||
}
|
||||
|
||||
/** Anything a dead pane could still be asserting: a row, or a latch that would re-gate one through
|
||||
* `resolveClaudePaneState` on the pane's next event even after the row reads `done`. The list
|
||||
* itself lives beside `clearPaneCacheState`, so adding a latch cannot leave this behind in a
|
||||
* different file. */
|
||||
private hasLiveClaimsForPaneKey(paneKey: string): boolean {
|
||||
return paneHasStateClaims(this.state, paneKey)
|
||||
}
|
||||
|
||||
/** Clear statuses proven to belong to one lost SSH transport. */
|
||||
clearStatusEntriesForConnection(connectionId: string): void {
|
||||
const normalizedConnectionId = connectionId.trim()
|
||||
@@ -2704,6 +2764,7 @@ export class AgentHookServer {
|
||||
this.state.claudeLeadStateByPaneKey.delete(paneKey)
|
||||
this.state.claudeRunningNonAgentTaskPaneKeys.delete(paneKey)
|
||||
this.state.claudeActiveSessionCronPaneKeys.delete(paneKey)
|
||||
this.state.claudeSessionOwnerByPaneKey.delete(paneKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2894,9 +2955,15 @@ export class AgentHookServer {
|
||||
enriched.payload.agentType === 'claude' &&
|
||||
enriched.connectionId === null &&
|
||||
isLocalExecutionHost(enriched.worktreeId) &&
|
||||
claudeRosterHasRestoredSnapshotSubagent(
|
||||
// Why: a restored roster is only one shape of stranded claim. A lead row left non-terminal,
|
||||
// or a background-task/cron latch nothing will refresh, strands the pane just as
|
||||
// permanently — and unlike the roster case there is no child event left to reap it.
|
||||
(claudeRosterHasRestoredSnapshotSubagent(
|
||||
this.state.claudeSubagentRosterByPaneKey.get(paneKey)
|
||||
) &&
|
||||
) ||
|
||||
enriched.payload.state !== 'done' ||
|
||||
this.state.claudeRunningNonAgentTaskPaneKeys.has(paneKey) ||
|
||||
this.state.claudeActiveSessionCronPaneKeys.has(paneKey)) &&
|
||||
!this.runtimeObservedStatusPaneKeys.has(paneKey)
|
||||
) {
|
||||
candidates.push({ paneKey, entry: enriched })
|
||||
@@ -2924,6 +2991,20 @@ export class AgentHookServer {
|
||||
continue
|
||||
}
|
||||
if (!reapRestoredClaudeSubagentsForDeadPane(this.state, paneKey)) {
|
||||
// Why: the roster reap only speaks for restored child rows. A pane whose PTY is provably
|
||||
// gone and whose claim is a lead row or a latch has nothing for it to reap, so retire the
|
||||
// pane the same way an observed exit would — otherwise the widened candidate set is inert.
|
||||
//
|
||||
// Why delete rather than downgrade to `done` like the reap branch below: that branch has a
|
||||
// real turn to describe — a parent whose children it just reaped — while these panes' only
|
||||
// claim IS the stale non-terminal row. Rewriting a `waiting`/`blocked` row to `done` would
|
||||
// invent a completion that never happened, and leaving it non-terminal keeps the bug. This
|
||||
// sweep stands in for the exit Orca never observed, so it does what that exit does:
|
||||
// `clearProviderPtyState` -> `clearPaneState`.
|
||||
if (this.hasLiveClaimsForPaneKey(paneKey)) {
|
||||
this.clearPaneState(paneKey)
|
||||
changedPanes += 1
|
||||
}
|
||||
continue
|
||||
}
|
||||
changedPanes += 1
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -2719,6 +2719,9 @@ void app.whenReady().then(async () => {
|
||||
agentHookServer.attestCompatibilityAuthority(candidate),
|
||||
retireAgentHookCompatibilityAuthority: (paneKey) =>
|
||||
agentHookServer.retirePaneAuthority(paneKey),
|
||||
reconcileAgentStatusForEndedProcess: (paneKeys) => {
|
||||
agentHookServer.reconcileEndedProcessForPaneKeys(paneKeys)
|
||||
},
|
||||
canRecoverPersistentLocalPtys: () => getDaemonProvider() !== null,
|
||||
// Why: source codex-home here (runs in window AND serve) so aiVault.listSessions includes managed-Codex sessions; registerCoreHandlers is window-only.
|
||||
getAdditionalAiVaultCodexHomePaths: () =>
|
||||
|
||||
@@ -6,13 +6,9 @@ import type {
|
||||
} from '../../shared/agent-status-types'
|
||||
import type { AgentInterruptInferenceRequest } from '../../shared/agent-interrupt-intent'
|
||||
import type { AgentQuestionAnsweredInferenceRequest } from '../../shared/agent-question-answered-intent'
|
||||
import { agentHookServer, isValidPaneKey } from '../agent-hooks/server'
|
||||
import { agentHookServer } from '../agent-hooks/server'
|
||||
import { ampHookService } from '../amp/hook-service'
|
||||
import {
|
||||
clearMigrationUnsupportedPtysByTabPrefix,
|
||||
clearMigrationUnsupportedPtysForPaneKey,
|
||||
getMigrationUnsupportedPtySnapshot
|
||||
} from '../agent-hooks/migration-unsupported-pty-state'
|
||||
import { getMigrationUnsupportedPtySnapshot } from '../agent-hooks/migration-unsupported-pty-state'
|
||||
import { claudeHookService } from '../claude/hook-service'
|
||||
import { codexHookService } from '../codex/hook-service'
|
||||
import { geminiHookService } from '../gemini/hook-service'
|
||||
@@ -27,10 +23,10 @@ import { devinHookService } from '../devin/hook-service'
|
||||
import { kimiHookService } from '../kimi/hook-service'
|
||||
import { openClaudeHookService } from '../openclaude/hook-service'
|
||||
import { registerAgentPaneAuthorityIpcHandlers } from './agent-pane-authority-ipc'
|
||||
import { registerAgentStatusRowTeardownIpcHandlers } from './agent-status-row-teardown-ipc'
|
||||
import { createAgentPaneAuthorityOwnership } from './agent-pane-authority-ownership'
|
||||
import {
|
||||
enrichAgentStatusIpcPayload,
|
||||
isValidAgentStatusDropTabId,
|
||||
type AgentStatusRuntimeEnrichment
|
||||
} from './agent-status-ipc-boundary'
|
||||
|
||||
@@ -70,38 +66,7 @@ export function registerAgentHookHandlers(
|
||||
ipcMain.removeHandler('agentStatus:inferInterrupt')
|
||||
ipcMain.removeHandler('agentStatus:inferQuestionAnswered')
|
||||
ipcMain.removeHandler('agentStatus:getMigrationUnsupportedSnapshot')
|
||||
// Why: agentStatus:drop is sent fire-and-forget from the renderer via
|
||||
// ipcRenderer.send(); we listen with ipcMain.on (not handle) so we don't
|
||||
// round-trip a response. Removing first keeps re-registration safe even
|
||||
// though the module-level registered guard already prevents re-entry today.
|
||||
ipcMain.removeAllListeners('agentStatus:drop')
|
||||
ipcMain.removeAllListeners('agentStatus:dropByTabPrefix')
|
||||
ipcMain.on('agentStatus:drop', (_event, paneKey: unknown) => {
|
||||
if (typeof paneKey !== 'string' || !isValidPaneKey(paneKey)) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
// Why: dropStatusEntry (not clearPaneState) is correct here — the user is
|
||||
// dismissing a status row, not tearing down a PTY. clearPaneState would also
|
||||
// wipe the per-pane prompt/tool caches, which the next hook event for that
|
||||
// (still-alive) pane needs to render a coherent row.
|
||||
agentHookServer.dropStatusEntry(paneKey)
|
||||
clearMigrationUnsupportedPtysForPaneKey(paneKey)
|
||||
} catch (err) {
|
||||
console.warn('[agent-hooks] dropStatusEntry failed:', err)
|
||||
}
|
||||
})
|
||||
ipcMain.on('agentStatus:dropByTabPrefix', (_event, tabId: unknown) => {
|
||||
if (!isValidAgentStatusDropTabId(tabId)) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
agentHookServer.dropStatusEntriesByTabPrefix(tabId)
|
||||
clearMigrationUnsupportedPtysByTabPrefix(tabId)
|
||||
} catch (err) {
|
||||
console.warn('[agent-hooks] dropStatusEntriesByTabPrefix failed:', err)
|
||||
}
|
||||
})
|
||||
registerAgentStatusRowTeardownIpcHandlers()
|
||||
registerAgentPaneAuthorityIpcHandlers({
|
||||
ownsPty: createAgentPaneAuthorityOwnership({
|
||||
getPtyIdForPaneKey: dependencies.getPtyIdForPaneKey,
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { ipcMain } from 'electron'
|
||||
import { agentHookServer, isValidPaneKey } from '../agent-hooks/server'
|
||||
import {
|
||||
clearMigrationUnsupportedPtysByTabPrefix,
|
||||
clearMigrationUnsupportedPtysForPaneKey
|
||||
} from '../agent-hooks/migration-unsupported-pty-state'
|
||||
import { isValidAgentStatusDropTabId } from './agent-status-ipc-boundary'
|
||||
|
||||
/**
|
||||
* The three renderer-initiated ways a status row goes away. All fire-and-forget
|
||||
* (`ipcRenderer.send` → `ipcMain.on`), so none round-trips a response; removing the
|
||||
* listeners first keeps re-registration safe.
|
||||
*
|
||||
* They are NOT interchangeable. A dismissal keeps the pane's per-pane caches because its agent may
|
||||
* still be alive; a confirmed process exit must take them too, or a surviving Claude latch resolves
|
||||
* the pane's next event straight back to `working`.
|
||||
*/
|
||||
export function registerAgentStatusRowTeardownIpcHandlers(): void {
|
||||
ipcMain.removeAllListeners('agentStatus:drop')
|
||||
ipcMain.removeAllListeners('agentStatus:reconcileEndedProcess')
|
||||
ipcMain.removeAllListeners('agentStatus:dropByTabPrefix')
|
||||
|
||||
ipcMain.on('agentStatus:drop', (_event, paneKey: unknown) => {
|
||||
if (typeof paneKey !== 'string' || !isValidPaneKey(paneKey)) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
// Why: dropStatusEntry (not clearPaneState) is correct here — the user is
|
||||
// dismissing a status row, not tearing down a PTY. clearPaneState would also
|
||||
// wipe the per-pane prompt/tool caches, which the next hook event for that
|
||||
// (still-alive) pane needs to render a coherent row.
|
||||
agentHookServer.dropStatusEntry(paneKey)
|
||||
clearMigrationUnsupportedPtysForPaneKey(paneKey)
|
||||
} catch (err) {
|
||||
console.warn('[agent-hooks] dropStatusEntry failed:', err)
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.on('agentStatus:reconcileEndedProcess', (_event, paneKey: unknown) => {
|
||||
if (typeof paneKey !== 'string' || !isValidPaneKey(paneKey)) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
// Why: a process-table-confirmed agent exit is exactly the case the dismissal above excludes
|
||||
// — the pane's agent is NOT still alive — so its latches must go with the row (STA-4612).
|
||||
agentHookServer.reconcileEndedProcessForPaneKeys([paneKey], {
|
||||
// Why: this route only fires on a confirmed shell foreground, so the PTY outlived the
|
||||
// agent. The row's resume identity is still usable in that very pane — only its live
|
||||
// claims are dead.
|
||||
preserveResumeIdentity: true
|
||||
})
|
||||
clearMigrationUnsupportedPtysForPaneKey(paneKey)
|
||||
} catch (err) {
|
||||
console.warn('[agent-hooks] reconcileEndedProcessForPaneKeys failed:', err)
|
||||
}
|
||||
})
|
||||
|
||||
ipcMain.on('agentStatus:dropByTabPrefix', (_event, tabId: unknown) => {
|
||||
if (!isValidAgentStatusDropTabId(tabId)) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
agentHookServer.dropStatusEntriesByTabPrefix(tabId)
|
||||
clearMigrationUnsupportedPtysByTabPrefix(tabId)
|
||||
} catch (err) {
|
||||
console.warn('[agent-hooks] dropStatusEntriesByTabPrefix failed:', err)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -289,7 +289,9 @@ describe('registerPtyHandlers', () => {
|
||||
await Promise.resolve()
|
||||
|
||||
expect(runtime.onPtyExit).toHaveBeenCalledTimes(1)
|
||||
expect(runtime.onPtyExit).toHaveBeenCalledWith('local-pty', 0, undefined, undefined)
|
||||
expect(runtime.onPtyExit).toHaveBeenCalledWith('local-pty', 0, undefined, {
|
||||
providerExitObserved: true
|
||||
})
|
||||
expect(
|
||||
mainWindow.webContents.send.mock.calls.filter((call) => call[0] === 'pty:exit')
|
||||
).toEqual([['pty:exit', { id: 'local-pty', code: 0 }]])
|
||||
@@ -342,7 +344,9 @@ describe('registerPtyHandlers', () => {
|
||||
await expect(stopPromise).resolves.toBe(true)
|
||||
|
||||
expect(runtime.onPtyExit).toHaveBeenCalledTimes(1)
|
||||
expect(runtime.onPtyExit).toHaveBeenCalledWith('local-pty', 0, undefined, undefined)
|
||||
expect(runtime.onPtyExit).toHaveBeenCalledWith('local-pty', 0, undefined, {
|
||||
providerExitObserved: true
|
||||
})
|
||||
expect(
|
||||
mainWindow.webContents.send.mock.calls.filter((call) => call[0] === 'pty:exit')
|
||||
).toEqual([['pty:exit', { id: 'local-pty', code: 0 }]])
|
||||
|
||||
@@ -440,6 +440,7 @@ describe('registerPtyHandlers', () => {
|
||||
|
||||
expect(killSpy).toHaveBeenCalled()
|
||||
expect(runtime.onPtyExit).toHaveBeenCalledWith(spawnResult.id, -1, spawnResult.incarnationId, {
|
||||
providerExitObserved: true,
|
||||
cause: { kind: 'unknown', reason: 'stop_unverified' }
|
||||
})
|
||||
const listed = await getLocalPtyProvider().listProcesses()
|
||||
|
||||
@@ -287,7 +287,9 @@ describe('registerPtyHandlers', () => {
|
||||
await handlers.get('pty:kill')!(null, { id: 'local-pty' })
|
||||
|
||||
expect(runtime.onPtyExit).toHaveBeenCalledTimes(1)
|
||||
expect(runtime.onPtyExit).toHaveBeenCalledWith('local-pty', 0, undefined, undefined)
|
||||
expect(runtime.onPtyExit).toHaveBeenCalledWith('local-pty', 0, undefined, {
|
||||
providerExitObserved: true
|
||||
})
|
||||
expect(mainWindow.webContents.send.mock.calls.filter((call) => call[0] === 'pty:exit')).toEqual(
|
||||
[['pty:exit', { id: 'local-pty', code: 0 }]]
|
||||
)
|
||||
@@ -529,7 +531,9 @@ describe('registerPtyHandlers', () => {
|
||||
seq: 13,
|
||||
rawLength: 'daemon output'.length
|
||||
})
|
||||
expect(runtime.onPtyExit).toHaveBeenCalledWith(result.id, 0, undefined, undefined)
|
||||
expect(runtime.onPtyExit).toHaveBeenCalledWith(result.id, 0, undefined, {
|
||||
providerExitObserved: true
|
||||
})
|
||||
expect(mainWindow.webContents.send).toHaveBeenCalledWith('pty:exit', {
|
||||
id: result.id,
|
||||
code: 0
|
||||
|
||||
+12
-7
@@ -2575,7 +2575,12 @@ export function registerPtyHandlers(
|
||||
clearProviderPtyState(id)
|
||||
ptyOwnership.delete(id)
|
||||
markClaudePtyExited(id)
|
||||
runtime?.onPtyExit(id, code, incarnationId, cause ? { cause } : undefined)
|
||||
// Why: the provider's physical exit callback is a death certificate even when node-pty
|
||||
// reports the code as -1; only the synthesized failed/unverified stop calls omit this.
|
||||
runtime?.onPtyExit(id, code, incarnationId, {
|
||||
providerExitObserved: true,
|
||||
...(cause ? { cause } : {})
|
||||
})
|
||||
},
|
||||
onData: (id, data, timestamp, sequenceChars, transformed) =>
|
||||
runtime?.onPtyData(id, data, timestamp, sequenceChars ?? data.length, transformed)
|
||||
@@ -4116,12 +4121,12 @@ export function registerPtyHandlers(
|
||||
clearProviderPtyState(payload.id)
|
||||
ptyOwnership.delete(payload.id)
|
||||
markClaudePtyExited(payload.id)
|
||||
runtime?.onPtyExit(
|
||||
payload.id,
|
||||
payload.code,
|
||||
payload.incarnationId,
|
||||
payload.cause ? { cause: payload.cause } : undefined
|
||||
)
|
||||
// Why: same physical-exit certificate as the LocalPtyProvider branch above — this is the
|
||||
// daemon/WSL callback, and on macOS it is the branch that actually runs.
|
||||
runtime?.onPtyExit(payload.id, payload.code, payload.incarnationId, {
|
||||
providerExitObserved: true,
|
||||
...(payload.cause ? { cause: payload.cause } : {})
|
||||
})
|
||||
}
|
||||
// Why not the whole payload: the exit cause is a main-process fact for the
|
||||
// runtime's records; the renderer's pty:exit contract stays as it was.
|
||||
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
} from '../../shared/remote-workspace-types'
|
||||
import type { WorkspaceSessionState } from '../../shared/workspace-session-state-types'
|
||||
import { getRepoIdFromWorktreeId } from '../../shared/worktree/id'
|
||||
import { parseExecutionHostId } from '../../shared/execution-host'
|
||||
import { getRemoteWorkspaceNamespace } from './remote-workspace-namespace'
|
||||
import { registerRemoteWorkspaceNotificationHandler } from './remote-workspace-events'
|
||||
import { CLIENT_ID } from './remote-workspace-client-identity'
|
||||
@@ -55,7 +56,15 @@ function getExplicitHydratedTargetIds(value: unknown): Set<string> | null {
|
||||
return new Set(value)
|
||||
}
|
||||
|
||||
function targetForWorktree(store: Store, worktreeId: string): string | null {
|
||||
function targetForWorktree(
|
||||
store: Store,
|
||||
worktreeId: string,
|
||||
executionHostId?: string
|
||||
): string | null {
|
||||
const parsedHostId = parseExecutionHostId(executionHostId)
|
||||
if (parsedHostId?.kind === 'ssh') {
|
||||
return parsedHostId.targetId
|
||||
}
|
||||
const repoId = getRepoIdFromWorktreeId(worktreeId)
|
||||
return store.getRepo(repoId)?.connectionId ?? null
|
||||
}
|
||||
@@ -66,7 +75,8 @@ function exportSessionForTarget(
|
||||
session: WorkspaceSessionState
|
||||
): RemoteWorkspaceSession {
|
||||
return exportRemoteWorkspaceSession(session, {
|
||||
isTargetWorktree: (worktreeId) => targetForWorktree(store, worktreeId) === targetId
|
||||
isTargetWorktree: (worktreeId, executionHostId) =>
|
||||
targetForWorktree(store, worktreeId, executionHostId) === targetId
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ function hasTransferredSessionState(session: WorkspaceSessionState): boolean {
|
||||
Object.keys(session.browserTabsByWorktree ?? {}).length > 0 ||
|
||||
Object.keys(session.unifiedTabs ?? {}).length > 0 ||
|
||||
Object.keys(session.tabGroups ?? {}).length > 0 ||
|
||||
Object.keys(session.lastVisitedAtByWorktreeId ?? {}).length > 0 ||
|
||||
Object.keys(session.terminalTopologyRevisionByRepoId ?? {}).length > 0
|
||||
)
|
||||
}
|
||||
|
||||
@@ -2,6 +2,10 @@ import type { PersistedState } from '../../shared/persisted-state-types'
|
||||
import { parseWorkspaceKey } from '../../shared/workspace-scope'
|
||||
import type { TransferProfileState } from './profile-project-state-file'
|
||||
import { isRepoWorktreeId } from './profile-project-worktree-identity'
|
||||
import {
|
||||
getWorktreeIdFromHostIdentity,
|
||||
isWorktreeHostIdentity
|
||||
} from '../../shared/worktree/host-qualified-identity'
|
||||
|
||||
export function collectTransferWorktreeIds(
|
||||
state: TransferProfileState,
|
||||
@@ -51,8 +55,9 @@ function collectSessionWorktreeIds(
|
||||
}
|
||||
const addOwnerKeys = (record: Record<string, unknown> | undefined): void => {
|
||||
for (const key of Object.keys(record ?? {})) {
|
||||
if (isRepoWorktreeId(repoId, key)) {
|
||||
ids.add(key)
|
||||
const rawKey = isWorktreeHostIdentity(key) ? getWorktreeIdFromHostIdentity(key) : key
|
||||
if (isRepoWorktreeId(repoId, rawKey)) {
|
||||
ids.add(rawKey)
|
||||
}
|
||||
const parsed = parseWorkspaceKey(key)
|
||||
if (parsed?.type === 'worktree' && isRepoWorktreeId(repoId, parsed.worktreeId)) {
|
||||
|
||||
@@ -4,6 +4,10 @@ import type { WorkspaceKey } from '../../shared/folder-workspace-types'
|
||||
import type { Repo } from '../../shared/repo-types'
|
||||
import { parseWorkspaceKey, worktreeWorkspaceKey } from '../../shared/workspace-scope'
|
||||
import { WORKTREE_ID_SEPARATOR } from '../../shared/worktree/id'
|
||||
import {
|
||||
getWorktreeIdFromHostIdentity,
|
||||
isWorktreeHostIdentity
|
||||
} from '../../shared/worktree/host-qualified-identity'
|
||||
|
||||
export function repoPhysicalKey(
|
||||
repo: Pick<Repo, 'path' | 'connectionId' | 'executionHostId'>
|
||||
@@ -46,8 +50,14 @@ export function rekeyOwnerKey(
|
||||
newRepoId: string,
|
||||
ownerKey: string
|
||||
): string | null {
|
||||
if (isRepoWorktreeId(oldRepoId, ownerKey)) {
|
||||
return rekeyWorktreeId(oldRepoId, newRepoId, ownerKey)
|
||||
const rawOwnerKey = isWorktreeHostIdentity(ownerKey)
|
||||
? getWorktreeIdFromHostIdentity(ownerKey)
|
||||
: ownerKey
|
||||
if (isRepoWorktreeId(oldRepoId, rawOwnerKey)) {
|
||||
const rekeyed = rekeyWorktreeId(oldRepoId, newRepoId, rawOwnerKey)
|
||||
return isWorktreeHostIdentity(ownerKey)
|
||||
? `${ownerKey.slice(0, ownerKey.length - rawOwnerKey.length)}${rekeyed}`
|
||||
: rekeyed
|
||||
}
|
||||
const parsed = parseWorkspaceKey(ownerKey)
|
||||
if (parsed?.type === 'worktree' && isRepoWorktreeId(oldRepoId, parsed.worktreeId)) {
|
||||
@@ -57,7 +67,10 @@ export function rekeyOwnerKey(
|
||||
}
|
||||
|
||||
export function ownerKeyBelongsToRepo(ownerKey: string, repoId: string): boolean {
|
||||
if (isRepoWorktreeId(repoId, ownerKey)) {
|
||||
const rawOwnerKey = isWorktreeHostIdentity(ownerKey)
|
||||
? getWorktreeIdFromHostIdentity(ownerKey)
|
||||
: ownerKey
|
||||
if (isRepoWorktreeId(repoId, rawOwnerKey)) {
|
||||
return true
|
||||
}
|
||||
const parsed = parseWorkspaceKey(ownerKey)
|
||||
|
||||
@@ -387,6 +387,19 @@ describe('Store.migrateWorktreeIdentity', () => {
|
||||
expect(store.getWorktreeMeta(NEWER)?.priorWorktreeIds).toEqual([OLD, NEW])
|
||||
})
|
||||
|
||||
it('keeps the newest visit timestamp when a partial migration left both identities', async () => {
|
||||
const store = await createStore()
|
||||
store.setWorkspaceSession({
|
||||
...getDefaultWorkspaceSession(),
|
||||
lastVisitedAtByWorktreeId: { [OLD]: 100, [NEW]: 900 }
|
||||
})
|
||||
|
||||
store.migrateWorktreeIdentity(OLD, NEW)
|
||||
|
||||
expect(store.getWorkspaceSession().lastVisitedAtByWorktreeId?.[OLD]).toBeUndefined()
|
||||
expect(store.getWorkspaceSession().lastVisitedAtByWorktreeId?.[NEW]).toBe(900)
|
||||
})
|
||||
|
||||
it('is a no-op when the ids match', async () => {
|
||||
const store = await createStore()
|
||||
store.setWorktreeMeta(OLD, { displayName: 'Cunner' })
|
||||
|
||||
@@ -467,6 +467,32 @@ describe('Store', () => {
|
||||
).toBe(222)
|
||||
})
|
||||
|
||||
it('removeProjectForHost on local prunes the unqualified host-identity visit key', async () => {
|
||||
const store = await createStore()
|
||||
store.addRepo(makeRepo({ id: 'shared', path: '/repo' }))
|
||||
store.addRepo(
|
||||
makeRepo({
|
||||
id: 'shared',
|
||||
path: '/repo',
|
||||
connectionId: 'ssh-a',
|
||||
executionHostId: 'ssh:ssh-a'
|
||||
})
|
||||
)
|
||||
// No meta for this worktree, so only the unqualified host-identity key names it. The host split
|
||||
// parks that canonical unknown-host form in the local partition; leaving it behind after a local
|
||||
// removal re-materializes an orphaned workspace next launch.
|
||||
store.setWorkspaceSession({
|
||||
...getDefaultWorkspaceSession(),
|
||||
lastVisitedAtByWorktreeId: { '|shared::/repo/wt-orphan': 111 }
|
||||
})
|
||||
|
||||
store.removeProjectForHost('shared', 'local')
|
||||
|
||||
expect(
|
||||
store.getWorkspaceSession().lastVisitedAtByWorktreeId?.['|shared::/repo/wt-orphan']
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
it('removeProjectForHost prunes only the removed host when a third host also shares the owner key', async () => {
|
||||
const store = await createStore()
|
||||
// Same repo id + path on local and two SSH hosts, so the owner key
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import type { TerminalTab } from '../../../shared/terminal-tab-types'
|
||||
import type { WorkspaceSessionState } from '../../../shared/workspace-session-state-types'
|
||||
import { getRepoIdFromWorktreeId } from '../../../shared/worktree/id'
|
||||
import {
|
||||
getWorktreeIdFromHostIdentity,
|
||||
isWorktreeHostIdentity
|
||||
} from '../../../shared/worktree/host-qualified-identity'
|
||||
|
||||
export function createMinimalPersistedTerminalTab(args: {
|
||||
worktreeId: string
|
||||
@@ -93,7 +97,12 @@ export function deleteOwnerKeyedSessionFields(
|
||||
delete next.activeGroupIdByWorktree[ownerKey]
|
||||
}
|
||||
if (next.lastVisitedAtByWorktreeId) {
|
||||
delete next.lastVisitedAtByWorktreeId[ownerKey]
|
||||
for (const key of Object.keys(next.lastVisitedAtByWorktreeId)) {
|
||||
const rawId = isWorktreeHostIdentity(key) ? getWorktreeIdFromHostIdentity(key) : key
|
||||
if (key === ownerKey || rawId === ownerKey) {
|
||||
delete next.lastVisitedAtByWorktreeId[key]
|
||||
}
|
||||
}
|
||||
}
|
||||
if (next.defaultTerminalTabsAppliedByWorktreeId) {
|
||||
delete next.defaultTerminalTabsAppliedByWorktreeId[ownerKey]
|
||||
|
||||
@@ -3,6 +3,10 @@ import { LOCAL_EXECUTION_HOST_ID, type ExecutionHostId } from '../../../shared/e
|
||||
import { parseWorkspaceKey } from '../../../shared/workspace-scope'
|
||||
import type { StoreOwnedPersistedState } from '../loading-store/store-owned-state'
|
||||
import { removeWorkspaceSessionOwners } from '../restoring-sessions/session-owner-removal'
|
||||
import {
|
||||
getWorktreeIdFromHostIdentity,
|
||||
isWorktreeHostIdentity
|
||||
} from '../../../shared/worktree/host-qualified-identity'
|
||||
|
||||
export function pruneWorktreeStateForRepo(
|
||||
state: StoreOwnedPersistedState,
|
||||
@@ -36,7 +40,18 @@ export function pruneWorktreeStateForRepo(
|
||||
const ownerKeysToPrune = new Set<string>()
|
||||
const collectPrefixedKeys = (keys: Iterable<string>): void => {
|
||||
for (const key of keys) {
|
||||
if (key.startsWith(prefix)) {
|
||||
const rawKey = isWorktreeHostIdentity(key) ? getWorktreeIdFromHostIdentity(key) : key
|
||||
const keyHost = isWorktreeHostIdentity(key) ? key.slice(0, key.indexOf('|')) : null
|
||||
// Why: bare keys are scoped by the per-partition gating below; only host-qualified
|
||||
// keys can sit in another host's partition and need host-matching at collection time.
|
||||
// Why the empty-host arm: the host split parks the canonical unknown-host form (`|<id>`) in
|
||||
// the local partition, so a local prune must claim it or the orphan restores next launch.
|
||||
const belongsToPrunedHost =
|
||||
hostId === null ||
|
||||
keyHost === null ||
|
||||
keyHost === hostId ||
|
||||
(keyHost === '' && hostId === LOCAL_EXECUTION_HOST_ID)
|
||||
if (belongsToPrunedHost && rawKey.startsWith(prefix)) {
|
||||
ownerKeysToPrune.add(key)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import type { WorkspaceKey } from '../../../shared/folder-workspace-types'
|
||||
import type { WorkspaceSessionState } from '../../../shared/workspace-session-state-types'
|
||||
import { worktreeWorkspaceKey } from '../../../shared/workspace-scope'
|
||||
import {
|
||||
getWorktreeIdFromHostIdentity,
|
||||
isWorktreeHostIdentity
|
||||
} from '../../../shared/worktree/host-qualified-identity'
|
||||
import type { StoreOwnedPersistedState } from '../loading-store/store-owned-state'
|
||||
|
||||
/**
|
||||
@@ -94,7 +98,29 @@ export function migrateWorktreeIdentity(
|
||||
moveSessionKey(session.tabGroups, (groups) => groups.map(withNewWorktreeId)) || sessionChanged
|
||||
sessionChanged = moveSessionKey(session.tabGroupLayouts) || sessionChanged
|
||||
sessionChanged = moveSessionKey(session.activeGroupIdByWorktree) || sessionChanged
|
||||
sessionChanged = moveSessionKey(session.lastVisitedAtByWorktreeId) || sessionChanged
|
||||
if (session.lastVisitedAtByWorktreeId) {
|
||||
const nextRecency = { ...session.lastVisitedAtByWorktreeId }
|
||||
let recencyChanged = false
|
||||
for (const [key, value] of Object.entries(session.lastVisitedAtByWorktreeId)) {
|
||||
const rawId = isWorktreeHostIdentity(key) ? getWorktreeIdFromHostIdentity(key) : key
|
||||
if (rawId !== oldWorktreeId) {
|
||||
continue
|
||||
}
|
||||
const nextKey = isWorktreeHostIdentity(key)
|
||||
? `${key.slice(0, key.length - rawId.length)}${newWorktreeId}`
|
||||
: newWorktreeId
|
||||
// Why max: a partial migration leaves both identities behind; taking the older one would
|
||||
// regress Cmd+J recency after restart.
|
||||
const existing = nextRecency[nextKey]
|
||||
nextRecency[nextKey] = existing === undefined ? value : Math.max(existing, value)
|
||||
delete nextRecency[key]
|
||||
recencyChanged = true
|
||||
}
|
||||
if (recencyChanged) {
|
||||
session.lastVisitedAtByWorktreeId = nextRecency
|
||||
sessionChanged = true
|
||||
}
|
||||
}
|
||||
sessionChanged =
|
||||
moveSessionKey(session.defaultTerminalTabsAppliedByWorktreeId) || sessionChanged
|
||||
if (session.activeWorktreeIdsOnShutdown?.includes(oldWorktreeId)) {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -3632,6 +3632,9 @@ export class OrcaRuntimeService {
|
||||
}) => AgentHookAuthorityAttestation | null)
|
||||
| null
|
||||
private readonly retireAgentHookCompatibilityAuthorityFn: ((paneKey: string) => void) | null
|
||||
private readonly reconcileAgentStatusForEndedProcessFn:
|
||||
| ((paneKeys: Iterable<string>) => void)
|
||||
| null
|
||||
private readonly canRecoverPersistentLocalPtysFn: () => boolean
|
||||
private readonly buildAgentHookPtyEnv: (() => Record<string, string>) | null
|
||||
private readonly getDesktopWindowStatusFn: () => RuntimeDesktopWindowStatus
|
||||
@@ -3713,6 +3716,7 @@ export class OrcaRuntimeService {
|
||||
terminalProvenance: 'current_runtime' | 'restored'
|
||||
}) => AgentHookAuthorityAttestation | null
|
||||
retireAgentHookCompatibilityAuthority?: (paneKey: string) => void
|
||||
reconcileAgentStatusForEndedProcess?: (paneKeys: Iterable<string>) => void
|
||||
canRecoverPersistentLocalPtys?: () => boolean
|
||||
// Why: codex-home paths for the Agent Session History scan must be sourced
|
||||
// here, not via the window-only registerCoreHandlers path — that path never
|
||||
@@ -3755,6 +3759,7 @@ export class OrcaRuntimeService {
|
||||
deps?.attestAgentHookCompatibilityAuthority ?? null
|
||||
this.retireAgentHookCompatibilityAuthorityFn =
|
||||
deps?.retireAgentHookCompatibilityAuthority ?? null
|
||||
this.reconcileAgentStatusForEndedProcessFn = deps?.reconcileAgentStatusForEndedProcess ?? null
|
||||
this.canRecoverPersistentLocalPtysFn = deps?.canRecoverPersistentLocalPtys ?? (() => true)
|
||||
// Why: configure the shared AiVault scan cache from a serve-mode-reachable
|
||||
// seam so the aiVault.listSessions RPC includes managed-Codex + WSL sessions
|
||||
@@ -13962,6 +13967,27 @@ export class OrcaRuntimeService {
|
||||
}
|
||||
}
|
||||
|
||||
/** Every pane key this PTY could be addressed by. Independent of launch authority: an ordinary
|
||||
* restored PTY has neither a launch token nor a receipt, and those are exactly the panes whose
|
||||
* spawn-time `ptyPaneKey` mapping teardown could not resolve. */
|
||||
private collectPaneKeysForPty(ptyId: string): Set<string> {
|
||||
const paneKeys = new Set<string>()
|
||||
const pty = this.ptysById.get(ptyId)
|
||||
if (pty?.paneKey && parsePaneKey(pty.paneKey)) {
|
||||
paneKeys.add(pty.paneKey)
|
||||
}
|
||||
const receipt = this.restoredOrchestrationAuthorityByPtyId.get(ptyId)
|
||||
if (receipt?.paneKey && parsePaneKey(receipt.paneKey)) {
|
||||
paneKeys.add(receipt.paneKey)
|
||||
}
|
||||
for (const leaf of this.getLeavesForPty(ptyId)) {
|
||||
if (isValidTerminalTabId(leaf.tabId) && isTerminalLeafId(leaf.leafId)) {
|
||||
paneKeys.add(makePaneKey(leaf.tabId, leaf.leafId))
|
||||
}
|
||||
}
|
||||
return paneKeys
|
||||
}
|
||||
|
||||
private retirePtyAgentLaunchAuthority(ptyId: string): void {
|
||||
const pty = this.ptysById.get(ptyId)
|
||||
if (!pty) {
|
||||
@@ -13971,21 +13997,10 @@ export class OrcaRuntimeService {
|
||||
if (!pty.launchToken && !receipt) {
|
||||
return
|
||||
}
|
||||
const paneKeys = this.collectPaneKeysForPty(ptyId)
|
||||
this.restoredOrchestrationAuthorityByPtyId.delete(ptyId)
|
||||
pty.launchToken = null
|
||||
pty.launchIncarnationId = null
|
||||
const paneKeys = new Set<string>()
|
||||
if (pty.paneKey && parsePaneKey(pty.paneKey)) {
|
||||
paneKeys.add(pty.paneKey)
|
||||
}
|
||||
if (receipt?.paneKey && parsePaneKey(receipt.paneKey)) {
|
||||
paneKeys.add(receipt.paneKey)
|
||||
}
|
||||
for (const leaf of this.getLeavesForPty(ptyId)) {
|
||||
if (isValidTerminalTabId(leaf.tabId) && isTerminalLeafId(leaf.leafId)) {
|
||||
paneKeys.add(makePaneKey(leaf.tabId, leaf.leafId))
|
||||
}
|
||||
}
|
||||
for (const paneKey of paneKeys) {
|
||||
this.retireAgentHookCompatibilityAuthorityFn?.(paneKey)
|
||||
}
|
||||
@@ -15201,7 +15216,14 @@ export class OrcaRuntimeService {
|
||||
ptyId: string,
|
||||
exitCode: number,
|
||||
exitIncarnationId?: PtyIncarnationId,
|
||||
options?: { hostExitConfirmed?: boolean; cause?: TerminalExitCause }
|
||||
options?: {
|
||||
hostExitConfirmed?: boolean
|
||||
cause?: TerminalExitCause
|
||||
/** The provider's own physical-exit callback fired. Separate from `hostExitConfirmed`, which
|
||||
* also drives the SSH surface decision and the liveness verdict: node-pty reports real exits
|
||||
* as -1, so the numeric code alone cannot tell a dead process from a failed stop. */
|
||||
providerExitObserved?: boolean
|
||||
}
|
||||
): void {
|
||||
const pty = this.ptysById.get(ptyId)
|
||||
if (exitIncarnationId && pty?.incarnationId && exitIncarnationId !== pty.incarnationId) {
|
||||
@@ -15227,6 +15249,9 @@ export class OrcaRuntimeService {
|
||||
pty?.connectionId != null &&
|
||||
exitCode < 0 &&
|
||||
options?.hostExitConfirmed !== true
|
||||
// Why: collect before retirePtyAgentLaunchAuthority, which deletes the restored-authority
|
||||
// receipt a receipt-only pane's key comes from.
|
||||
const exitPaneKeys = this.collectPaneKeysForPty(ptyId)
|
||||
if (preservesAbnormalSshSurface) {
|
||||
if (this.getPtyLivenessVerdict(ptyId)?.status !== 'unverifiable') {
|
||||
this.markPtyLivenessUnverifiable(ptyId, SSH_EXIT_UNCONFIRMED_REASON)
|
||||
@@ -15235,6 +15260,15 @@ export class OrcaRuntimeService {
|
||||
} else {
|
||||
this.retirePtyAgentLaunchAuthority(ptyId)
|
||||
}
|
||||
// Why: a synthetic -1 from a failed or unverified stop is not a death certificate (the PTY can
|
||||
// have survived it), while a real exit can also report -1 — so neither the numeric code nor the
|
||||
// SSH surface predicate is sufficient on its own. Decided separately from
|
||||
// preservesAbnormalSshSurface, which a host-confirmed negative SSH exit would otherwise skip.
|
||||
const processDeathCertified =
|
||||
exitCode >= 0 || options?.hostExitConfirmed === true || options?.providerExitObserved === true
|
||||
if (processDeathCertified && exitPaneKeys.size > 0) {
|
||||
this.reconcileAgentStatusForEndedProcessFn?.(exitPaneKeys)
|
||||
}
|
||||
const incarnationId =
|
||||
exitIncarnationId ??
|
||||
pty?.incarnationId ??
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* A PTY that exits without a resolvable spawn-time pane key never reaches
|
||||
* `agentHookServer.clearPaneState`, so its row and every Claude latch outlive the process with
|
||||
* nothing left to retire them (STA-4612). `onPtyExit` knows the pane keys that teardown could not
|
||||
* resolve, so it reconciles them — but only on a real death certificate.
|
||||
*/
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { OrcaRuntimeService } from './orca-runtime'
|
||||
import { makePaneKey } from '../../shared/stable-pane-id'
|
||||
|
||||
const LEAF = '11111111-1111-4111-8111-111111111111'
|
||||
const PANE = makePaneKey('tab-1', LEAF)
|
||||
const PTY = 'wt-1__pty-1'
|
||||
|
||||
type RuntimeInternals = {
|
||||
ptysById: Map<string, { ptyId: string; paneKey: string; worktreeId: string; tabId: string }>
|
||||
}
|
||||
|
||||
function runtimeWithBoundPane(
|
||||
reconcile: (paneKeys: Iterable<string>) => void,
|
||||
options: { connectionId?: string } = {}
|
||||
): OrcaRuntimeService {
|
||||
const runtime = new OrcaRuntimeService(null, undefined, {
|
||||
reconcileAgentStatusForEndedProcess: reconcile
|
||||
})
|
||||
const ptys = (runtime as unknown as RuntimeInternals).ptysById
|
||||
ptys.set(PTY, {
|
||||
ptyId: PTY,
|
||||
paneKey: PANE,
|
||||
worktreeId: 'wt-1',
|
||||
tabId: 'tab-1',
|
||||
...(options.connectionId ? { connectionId: options.connectionId } : {})
|
||||
} as never)
|
||||
return runtime
|
||||
}
|
||||
|
||||
function reconciledPaneKeys(calls: Iterable<string>[]): string[] {
|
||||
return calls.flatMap((keys) => [...keys])
|
||||
}
|
||||
|
||||
describe('onPtyExit agent-status reconciliation', () => {
|
||||
it('reconciles on a normal zero exit code', () => {
|
||||
const reconcile = vi.fn()
|
||||
runtimeWithBoundPane(reconcile).onPtyExit(PTY, 0)
|
||||
|
||||
expect(reconciledPaneKeys(reconcile.mock.calls.map(([keys]) => keys))).toContain(PANE)
|
||||
})
|
||||
|
||||
it('reconciles a physical -1 exit reported by the provider callback', () => {
|
||||
// node-pty forwards real exits as -1 (local-pty-provider-shutdown.test.ts pins this), so the
|
||||
// numeric code alone cannot separate a dead process from a failed stop.
|
||||
const reconcile = vi.fn()
|
||||
runtimeWithBoundPane(reconcile).onPtyExit(PTY, -1, undefined, { providerExitObserved: true })
|
||||
|
||||
expect(reconciledPaneKeys(reconcile.mock.calls.map(([keys]) => keys))).toContain(PANE)
|
||||
})
|
||||
|
||||
it('reconciles a host-confirmed negative exit', () => {
|
||||
const reconcile = vi.fn()
|
||||
runtimeWithBoundPane(reconcile).onPtyExit(PTY, -1, undefined, { hostExitConfirmed: true })
|
||||
|
||||
expect(reconciledPaneKeys(reconcile.mock.calls.map(([keys]) => keys))).toContain(PANE)
|
||||
})
|
||||
|
||||
it('reconciles a provider-observed -1 on a pane bound to a transport, where the SSH surface is preserved', () => {
|
||||
// A WSL pane carries a `wsl:*` connectionId, so a negative exit keeps the abnormal-SSH surface
|
||||
// (liveness unverifiable, launch authority not retired) — but the daemon provider's own exit
|
||||
// callback still witnessed the process die. The two decisions are deliberately independent;
|
||||
// without this the connectionId arm of the certificate is never exercised.
|
||||
const reconcile = vi.fn()
|
||||
runtimeWithBoundPane(reconcile, { connectionId: 'wsl:Ubuntu' }).onPtyExit(PTY, -1, undefined, {
|
||||
providerExitObserved: true
|
||||
})
|
||||
|
||||
expect(reconciledPaneKeys(reconcile.mock.calls.map(([keys]) => keys))).toContain(PANE)
|
||||
})
|
||||
|
||||
it('does NOT reconcile a transport-bound synthetic -1, whose remote PTY is designed to survive it', () => {
|
||||
const reconcile = vi.fn()
|
||||
runtimeWithBoundPane(reconcile, { connectionId: 'ssh-conn-1' }).onPtyExit(PTY, -1)
|
||||
|
||||
expect(reconcile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does NOT reconcile a synthetic -1 from a failed stop, whose PTY may have survived', () => {
|
||||
const reconcile = vi.fn()
|
||||
runtimeWithBoundPane(reconcile).onPtyExit(PTY, -1)
|
||||
|
||||
expect(reconcile).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -30,6 +30,9 @@ export type AgentStatusApi = {
|
||||
getMigrationUnsupportedSnapshot: () => Promise<MigrationUnsupportedPtyEntry[]>
|
||||
/** Drop a paneKey from the main-process hook cache and on-disk last-status file. Fire-and-forget. */
|
||||
drop: (paneKey: string) => void
|
||||
/** Retire a pane whose agent process is proven gone — clears the row AND the per-pane caches a
|
||||
* dismissal deliberately keeps. Not `drop`: that one is a user dismissal of a live pane's row. */
|
||||
reconcileEndedProcess: (paneKey: string) => void
|
||||
/** Drop every cached hook status under one terminal tab prefix. Fire-and-forget. */
|
||||
dropByTabPrefix: (tabId: string) => void
|
||||
/** Permanently retire one pane's hook authority while siblings stay live. */
|
||||
|
||||
@@ -5032,6 +5032,9 @@ const api = {
|
||||
drop: (paneKey: string): void => {
|
||||
ipcRenderer.send('agentStatus:drop', paneKey)
|
||||
},
|
||||
reconcileEndedProcess: (paneKey: string): void => {
|
||||
ipcRenderer.send('agentStatus:reconcileEndedProcess', paneKey)
|
||||
},
|
||||
/** Drop all cached hook statuses under one terminal tab prefix; fired on explicit tab close even without a local row. */
|
||||
dropByTabPrefix: (tabId: string): void => {
|
||||
ipcRenderer.send('agentStatus:dropByTabPrefix', tabId)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -12,6 +12,7 @@ import { makePaneKey } from '../../../shared/stable-pane-id'
|
||||
import {
|
||||
LEAF_ID,
|
||||
makeAgentEntry,
|
||||
makeDuplicateRecentTabState,
|
||||
makeGroup,
|
||||
makeManyTabState,
|
||||
makeRecentTabState,
|
||||
@@ -229,6 +230,25 @@ describe('WorktreeJumpPalette recent chats & terminals', () => {
|
||||
expect(testContainer.textContent).toContain('Recent Worktrees')
|
||||
})
|
||||
|
||||
it('keeps duplicate persisted tab ids as separate recent rows and digit targets', async () => {
|
||||
await renderPalette(makeDuplicateRecentTabState())
|
||||
|
||||
expect(
|
||||
getRenderedRowIds().filter(
|
||||
(id) => id === 'workspace-tab:tab-duplicate' || id.includes(':workspace-tab:tab-duplicate')
|
||||
)
|
||||
).toEqual(['workspace-tab:tab-duplicate', 'palette-dup:1:workspace-tab:tab-duplicate'])
|
||||
|
||||
await act(async () => {
|
||||
emitCmdJRowIndexJump(1)
|
||||
})
|
||||
await flushEffects()
|
||||
|
||||
expect(activateWorkspaceTabPaletteResult).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ tabId: 'tab-duplicate', worktreeId: 'wt-beta' })
|
||||
)
|
||||
})
|
||||
|
||||
it('caps the recent section so the worktree header stays above the fold', async () => {
|
||||
await renderPalette(makeManyTabState(12))
|
||||
|
||||
|
||||
@@ -350,9 +350,56 @@ function isCurrentOpenTabItem(item: OpenTabPaletteItem): boolean {
|
||||
return item.type === 'browser-page' ? item.result.isCurrentPage : item.result.isCurrentTab
|
||||
}
|
||||
|
||||
/** Not the command id: two hosts — or a duplicate snapshot — can publish the same tab id. */
|
||||
function getRecentTabOccurrenceBase(item: OpenTabPaletteItem): string {
|
||||
if (item.type === 'browser-page') {
|
||||
const result = item.result
|
||||
return JSON.stringify([
|
||||
item.type,
|
||||
item.id,
|
||||
result.executionHostId ?? '',
|
||||
result.worktreeId,
|
||||
result.workspaceId,
|
||||
result.pageId
|
||||
])
|
||||
}
|
||||
if (item.type === 'simulator-tab') {
|
||||
const result = item.result
|
||||
// Why no groupId: it changes when a tab is regrouped mid-open, and the frozen
|
||||
// order must keep resolving the row; tabId already identifies it within a host.
|
||||
return JSON.stringify([
|
||||
item.type,
|
||||
item.id,
|
||||
result.executionHostId ?? '',
|
||||
result.worktreeId,
|
||||
result.tabId
|
||||
])
|
||||
}
|
||||
const result = item.result
|
||||
return JSON.stringify([
|
||||
item.type,
|
||||
item.id,
|
||||
result.executionHostId ?? '',
|
||||
result.worktreeId,
|
||||
result.tabId,
|
||||
result.entityId
|
||||
])
|
||||
}
|
||||
|
||||
function buildRecentTabOccurrenceIds(items: readonly OpenTabPaletteItem[]): string[] {
|
||||
const nextOrdinalByBase = new Map<string, number>()
|
||||
return items.map((item) => {
|
||||
const base = getRecentTabOccurrenceBase(item)
|
||||
const ordinal = nextOrdinalByBase.get(base) ?? 0
|
||||
nextOrdinalByBase.set(base, ordinal + 1)
|
||||
return `recent-tab:${base}:${ordinal}`
|
||||
})
|
||||
}
|
||||
|
||||
/** An open tab's recent-section row plus the inputs inclusion needs. */
|
||||
type OpenTabRecentRow = {
|
||||
item: OpenTabPaletteItem
|
||||
occurrenceId: string
|
||||
worktree: Worktree
|
||||
row: RecentWorkspaceTabRow
|
||||
}
|
||||
@@ -1419,17 +1466,22 @@ function WorktreeJumpPaletteContent({
|
||||
// once inclusion would drop it (a current tab that quiets down), or the pip blanks mid-open.
|
||||
const openTabRecentRows = useMemo<OpenTabRecentRow[]>(() => {
|
||||
const entries: OpenTabRecentRow[] = []
|
||||
for (const item of openTabItems) {
|
||||
const occurrenceIds = buildRecentTabOccurrenceIds(openTabItems)
|
||||
for (const [index, item] of openTabItems.entries()) {
|
||||
const worktree = resolveWorktree(item.result.worktreeId, item.result.executionHostId)
|
||||
if (!worktree) {
|
||||
continue
|
||||
}
|
||||
const occurrenceId = occurrenceIds[index]
|
||||
entries.push({
|
||||
item,
|
||||
occurrenceId,
|
||||
worktree,
|
||||
row: {
|
||||
id: item.id,
|
||||
occurrenceId,
|
||||
worktreeId: worktree.id,
|
||||
worktreeHostId: worktree.hostId,
|
||||
unifiedTabId: item.type === 'browser-page' ? null : item.result.tabId,
|
||||
terminalTab:
|
||||
item.type === 'workspace-tab' && item.result.contentType === 'terminal'
|
||||
@@ -1442,8 +1494,8 @@ function WorktreeJumpPaletteContent({
|
||||
return entries
|
||||
}, [openTabItems, resolveWorktree, terminalTabsById])
|
||||
|
||||
const recentTabRowById = useMemo(
|
||||
() => new Map(openTabRecentRows.map(({ row }) => [row.id, row])),
|
||||
const recentTabRowByItem = useMemo(
|
||||
() => new Map(openTabRecentRows.map(({ item, row }) => [item, row])),
|
||||
[openTabRecentRows]
|
||||
)
|
||||
|
||||
@@ -1558,15 +1610,16 @@ function WorktreeJumpPaletteContent({
|
||||
visible
|
||||
])
|
||||
|
||||
// Why: walk the frozen order rather than re-sorting the tab list — the frozen ids are the ranking,
|
||||
// so agent churn never reshuffles rows under the cursor. Cap after resolving, not before: a chip
|
||||
// applied mid-open narrows `openTabItems`, and capping first would leave the section empty.
|
||||
// Why walk the frozen order, and cap after resolving: agent churn must not reshuffle rows, and a
|
||||
// mid-open chip narrows `openTabItems` — capping first would leave the section empty.
|
||||
const recentTabItems = useMemo<PaletteItem[]>(() => {
|
||||
const itemById = new Map(openTabItems.map((item) => [item.id, item]))
|
||||
const itemByOccurrenceId = new Map(
|
||||
openTabRecentRows.map(({ occurrenceId, item }) => [occurrenceId, item])
|
||||
)
|
||||
return recentTabOrder
|
||||
.flatMap((id) => itemById.get(id) ?? [])
|
||||
.flatMap((occurrenceId) => itemByOccurrenceId.get(occurrenceId) ?? [])
|
||||
.slice(0, EMPTY_QUERY_RECENT_TAB_CAP)
|
||||
}, [openTabItems, recentTabOrder])
|
||||
}, [openTabRecentRows, recentTabOrder])
|
||||
|
||||
const settingsResults = useMemo(
|
||||
() => buildCmdJSettingsResults(settingsSections),
|
||||
@@ -1873,10 +1926,10 @@ function WorktreeJumpPaletteContent({
|
||||
])
|
||||
|
||||
// Why: badges number the snapshotted recent rows only — ⌘N is meaningless on a typed query.
|
||||
const recentTabShortcutIndexById = useMemo(
|
||||
const recentTabShortcutIndexByItem = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
hasQuery ? [] : paletteSections.visibleOpenTabItems.map((item, index) => [item.id, index])
|
||||
hasQuery ? [] : paletteSections.visibleOpenTabItems.map((item, index) => [item, index])
|
||||
),
|
||||
[hasQuery, paletteSections]
|
||||
)
|
||||
@@ -3450,7 +3503,7 @@ function WorktreeJumpPaletteContent({
|
||||
)
|
||||
// Why regardless of query: a searched-for tab is exactly when you need to know it's
|
||||
// still working — the map covers every open tab, not just the recent section.
|
||||
const recentRow = recentTabRowById.get(entry.id) ?? null
|
||||
const recentRow = recentTabRowByItem.get(entry) ?? null
|
||||
|
||||
return (
|
||||
<CommandItem
|
||||
@@ -3512,7 +3565,7 @@ function WorktreeJumpPaletteContent({
|
||||
</span>
|
||||
)}
|
||||
<PaletteRowShortcutBadge
|
||||
index={recentTabShortcutIndexById.get(entry.id)}
|
||||
index={recentTabShortcutIndexByItem.get(entry)}
|
||||
modifierKeys={digitShortcutModifiers}
|
||||
/>
|
||||
</div>
|
||||
@@ -3594,7 +3647,7 @@ function WorktreeJumpPaletteContent({
|
||||
</span>
|
||||
)}
|
||||
<PaletteRowShortcutBadge
|
||||
index={recentTabShortcutIndexById.get(entry.id)}
|
||||
index={recentTabShortcutIndexByItem.get(entry)}
|
||||
modifierKeys={digitShortcutModifiers}
|
||||
/>
|
||||
</div>
|
||||
@@ -3672,7 +3725,7 @@ function WorktreeJumpPaletteContent({
|
||||
</span>
|
||||
)}
|
||||
<PaletteRowShortcutBadge
|
||||
index={recentTabShortcutIndexById.get(entry.id)}
|
||||
index={recentTabShortcutIndexByItem.get(entry)}
|
||||
modifierKeys={digitShortcutModifiers}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
import type { AutomationTargetAvailability } from './automation-target-availability'
|
||||
import { getAutomationSourceDisplay } from './automation-source-display'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { AutomationPromptDisclosure } from './AutomationPromptDisclosure'
|
||||
|
||||
type AutomationDetailProps = {
|
||||
automation: Automation | null
|
||||
@@ -301,21 +302,10 @@ export function AutomationDetail({
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border border-border/50 bg-muted/20 shadow-sm">
|
||||
<div className="border-b border-border/50 px-3 py-2 text-sm font-medium">
|
||||
{translate('auto.components.automations.AutomationDetail.007c8ad874', 'Prompt')}
|
||||
</div>
|
||||
<div className="px-3 py-3">
|
||||
<div className="min-w-0">
|
||||
<div className="text-[11px] font-medium uppercase text-muted-foreground">
|
||||
{translate('auto.components.automations.AutomationDetail.007c8ad874', 'Prompt')}
|
||||
</div>
|
||||
<p className="mt-1 line-clamp-4 whitespace-pre-wrap text-sm text-foreground">
|
||||
{automation.prompt}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<AutomationPromptDisclosure
|
||||
key={`${automation.id}:${automation.prompt}`}
|
||||
prompt={automation.prompt}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import '@testing-library/jest-dom/vitest'
|
||||
import type React from 'react'
|
||||
import { act, cleanup, render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { Automation } from '../../../../shared/automations-types'
|
||||
import { i18n } from '@/i18n/i18n'
|
||||
import { AutomationDetail } from './AutomationDetail'
|
||||
import { AutomationPromptDisclosure } from './AutomationPromptDisclosure'
|
||||
|
||||
vi.mock('@/components/ui/tooltip', () => ({
|
||||
Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
TooltipContent: ({ children }: { children: React.ReactNode }) => <>{children}</>
|
||||
}))
|
||||
|
||||
let promptNaturalHeight = 0
|
||||
let resizeCallback: ResizeObserverCallback | null = null
|
||||
|
||||
class PromptResizeObserver implements ResizeObserver {
|
||||
constructor(callback: ResizeObserverCallback) {
|
||||
resizeCallback = callback
|
||||
}
|
||||
|
||||
disconnect(): void {}
|
||||
observe(): void {}
|
||||
unobserve(): void {}
|
||||
}
|
||||
|
||||
function makeAutomation(
|
||||
updatedAt: number,
|
||||
prompt = `Synthetic opening.\n${'Synthetic detail. '.repeat(80)}`
|
||||
): Automation {
|
||||
return {
|
||||
id: 'synthetic-automation',
|
||||
name: 'Synthetic automation',
|
||||
prompt,
|
||||
precheck: null,
|
||||
agentId: 'codex',
|
||||
projectId: 'synthetic-project',
|
||||
executionTargetType: 'local',
|
||||
executionTargetId: 'local',
|
||||
schedulerOwner: 'local_host_service',
|
||||
workspaceMode: 'existing',
|
||||
workspaceId: 'synthetic-workspace',
|
||||
baseBranch: null,
|
||||
reuseSession: false,
|
||||
timezone: 'UTC',
|
||||
rrule: 'FREQ=DAILY',
|
||||
dtstart: 1,
|
||||
enabled: false,
|
||||
nextRunAt: 2,
|
||||
missedRunPolicy: 'run_once_within_grace',
|
||||
missedRunGraceMinutes: 720,
|
||||
createdAt: 1,
|
||||
updatedAt
|
||||
}
|
||||
}
|
||||
|
||||
const detailCallbacks = {
|
||||
onRunNow: vi.fn(),
|
||||
onEdit: vi.fn(),
|
||||
onToggle: vi.fn(),
|
||||
onDelete: vi.fn()
|
||||
}
|
||||
|
||||
describe('AutomationPromptDisclosure', () => {
|
||||
beforeEach(async () => {
|
||||
await i18n.changeLanguage('en')
|
||||
vi.stubGlobal('ResizeObserver', PromptResizeObserver)
|
||||
vi.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockImplementation(
|
||||
function (this: HTMLElement) {
|
||||
if (this.tagName !== 'P') {
|
||||
return 0
|
||||
}
|
||||
return this.classList.contains('line-clamp-4')
|
||||
? Math.min(promptNaturalHeight, 80)
|
||||
: promptNaturalHeight
|
||||
}
|
||||
)
|
||||
vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(
|
||||
function (this: HTMLElement) {
|
||||
return this.tagName === 'P' ? promptNaturalHeight : 0
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
cleanup()
|
||||
resizeCallback = null
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
await i18n.changeLanguage('en')
|
||||
})
|
||||
|
||||
it('leaves a short prompt fully readable without a disclosure control', () => {
|
||||
promptNaturalHeight = 40
|
||||
render(<AutomationPromptDisclosure prompt="Synthetic short prompt." />)
|
||||
|
||||
expect(screen.getByText('Synthetic short prompt.')).toBeVisible()
|
||||
expect(screen.queryByRole('button', { name: 'Show more' })).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('labels the prompt correctly in Spanish', async () => {
|
||||
promptNaturalHeight = 40
|
||||
await i18n.changeLanguage('es')
|
||||
render(<AutomationPromptDisclosure prompt="Synthetic short prompt." />)
|
||||
|
||||
expect(screen.getByText('Prompt')).toBeVisible()
|
||||
expect(screen.queryByText('Inmediato')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reveals the complete long prompt from the keyboard and keeps it selectable', async () => {
|
||||
promptNaturalHeight = 240
|
||||
const prompt = `Synthetic opening.\n${'Synthetic detail. '.repeat(80)}\nSYNTHETIC-END-MARKER`
|
||||
const user = userEvent.setup()
|
||||
render(<AutomationPromptDisclosure prompt={prompt} />)
|
||||
|
||||
const content = screen.getByText(/SYNTHETIC-END-MARKER/)
|
||||
const toggle = screen.getByRole('button', { name: 'Show more' })
|
||||
expect(screen.getAllByText('Prompt')).toHaveLength(1)
|
||||
expect(content).toHaveClass('line-clamp-4', 'select-text', '[overflow-wrap:anywhere]')
|
||||
expect(toggle).toHaveAttribute('aria-expanded', 'false')
|
||||
expect(toggle).toHaveAttribute('aria-controls', content.id)
|
||||
expect(toggle).toHaveAttribute('data-variant', 'ghost')
|
||||
expect(toggle).toHaveAttribute('data-size', 'xs')
|
||||
expect(toggle).not.toHaveClass('h-auto', 'p-0')
|
||||
|
||||
await user.tab()
|
||||
expect(toggle).toHaveFocus()
|
||||
await user.keyboard('{Enter}')
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Show less' })).toHaveAttribute(
|
||||
'aria-expanded',
|
||||
'true'
|
||||
)
|
||||
expect(content).not.toHaveClass('line-clamp-4')
|
||||
expect(content).toHaveTextContent('SYNTHETIC-END-MARKER')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Show less' }))
|
||||
expect(screen.getByRole('button', { name: 'Show more' })).toHaveAttribute(
|
||||
'aria-expanded',
|
||||
'false'
|
||||
)
|
||||
expect(content).toHaveClass('line-clamp-4')
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Show more' }))
|
||||
act(() => resizeCallback?.([], {} as ResizeObserver))
|
||||
expect(screen.getByRole('button', { name: 'Show less' })).toHaveFocus()
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Show less' }))
|
||||
expect(screen.getByRole('button', { name: 'Show more' })).toHaveFocus()
|
||||
expect(content).toHaveClass('line-clamp-4')
|
||||
})
|
||||
|
||||
it('offers disclosure after a narrow resize makes the prompt overflow', () => {
|
||||
promptNaturalHeight = 60
|
||||
render(<AutomationPromptDisclosure prompt="Synthetic prompt that reflows at narrow widths." />)
|
||||
expect(screen.queryByRole('button', { name: 'Show more' })).not.toBeInTheDocument()
|
||||
|
||||
promptNaturalHeight = 180
|
||||
act(() => resizeCallback?.([], {} as ResizeObserver))
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Show more' })).toBeVisible()
|
||||
})
|
||||
|
||||
it('moves focus to the fully visible prompt when resizing removes the disclosure', () => {
|
||||
promptNaturalHeight = 180
|
||||
render(<AutomationPromptDisclosure prompt="Synthetic prompt that fits after widening." />)
|
||||
const content = screen.getByText('Synthetic prompt that fits after widening.')
|
||||
screen.getByRole('button', { name: 'Show more' }).focus()
|
||||
|
||||
promptNaturalHeight = 60
|
||||
act(() => resizeCallback?.([], {} as ResizeObserver))
|
||||
|
||||
expect(screen.queryByRole('button', { name: 'Show more' })).not.toBeInTheDocument()
|
||||
expect(content).toHaveFocus()
|
||||
})
|
||||
|
||||
it('preserves expansion and focus across unrelated automation updates', async () => {
|
||||
promptNaturalHeight = 240
|
||||
const user = userEvent.setup()
|
||||
const { rerender } = render(
|
||||
<AutomationDetail
|
||||
automation={makeAutomation(1)}
|
||||
runs={[]}
|
||||
projectName="Synthetic project"
|
||||
workspaceName="Synthetic workspace"
|
||||
projectDefaultBaseRef={null}
|
||||
runNowAvailability={null}
|
||||
now={1}
|
||||
{...detailCallbacks}
|
||||
/>
|
||||
)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Show more' }))
|
||||
const showLess = screen.getByRole('button', { name: 'Show less' })
|
||||
showLess.focus()
|
||||
|
||||
rerender(
|
||||
<AutomationDetail
|
||||
automation={makeAutomation(2)}
|
||||
runs={[]}
|
||||
projectName="Synthetic project"
|
||||
workspaceName="Synthetic workspace"
|
||||
projectDefaultBaseRef={null}
|
||||
runNowAvailability={null}
|
||||
now={2}
|
||||
{...detailCallbacks}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByRole('button', { name: 'Show less' })).toHaveFocus()
|
||||
|
||||
promptNaturalHeight = 40
|
||||
rerender(
|
||||
<AutomationDetail
|
||||
automation={makeAutomation(3, 'Synthetic replacement prompt.')}
|
||||
runs={[]}
|
||||
projectName="Synthetic project"
|
||||
workspaceName="Synthetic workspace"
|
||||
projectDefaultBaseRef={null}
|
||||
runNowAvailability={null}
|
||||
now={3}
|
||||
{...detailCallbacks}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText('Synthetic replacement prompt.')).toBeVisible()
|
||||
expect(screen.queryByRole('button', { name: 'Show less' })).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
import React, { useCallback, useEffect, useId, useRef, useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
|
||||
export function AutomationPromptDisclosure({ prompt }: { prompt: string }): React.JSX.Element {
|
||||
const contentId = useId()
|
||||
const expandedRef = useRef(false)
|
||||
const toggleRef = useRef<HTMLButtonElement>(null)
|
||||
const [promptElement, setPromptElement] = useState<HTMLParagraphElement | null>(null)
|
||||
const [expanded, setExpanded] = useState(false)
|
||||
const [overflows, setOverflows] = useState(false)
|
||||
|
||||
const measureOverflow = useCallback((element: HTMLParagraphElement) => {
|
||||
const nextOverflows = element.scrollHeight > element.clientHeight + 1
|
||||
if (!nextOverflows && document.activeElement === toggleRef.current) {
|
||||
element.focus({ preventScroll: true })
|
||||
}
|
||||
setOverflows((current) => (current === nextOverflows ? current : nextOverflows))
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!promptElement || expanded) {
|
||||
return
|
||||
}
|
||||
|
||||
const updateOverflow = () => {
|
||||
if (!expandedRef.current) {
|
||||
measureOverflow(promptElement)
|
||||
}
|
||||
}
|
||||
updateOverflow()
|
||||
if (typeof ResizeObserver === 'undefined') {
|
||||
window.addEventListener('resize', updateOverflow)
|
||||
return () => window.removeEventListener('resize', updateOverflow)
|
||||
}
|
||||
|
||||
const observer = new ResizeObserver(updateOverflow)
|
||||
observer.observe(promptElement)
|
||||
return () => observer.disconnect()
|
||||
}, [expanded, measureOverflow, promptElement])
|
||||
|
||||
const toggleExpanded = (): void => {
|
||||
const nextExpanded = !expanded
|
||||
expandedRef.current = nextExpanded
|
||||
setExpanded(nextExpanded)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-md border border-border/50 bg-muted/20 shadow-sm">
|
||||
<div className="flex items-center justify-between gap-3 border-b border-border/50 px-3 py-2">
|
||||
<div className="text-sm font-medium">
|
||||
{translate('auto.components.automations.AutomationEditorDialog.058c23cb3f', 'Prompt')}
|
||||
</div>
|
||||
{overflows || expanded ? (
|
||||
<Button
|
||||
ref={toggleRef}
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
className="-mr-2 text-muted-foreground hover:text-foreground"
|
||||
aria-expanded={expanded}
|
||||
aria-controls={contentId}
|
||||
onClick={toggleExpanded}
|
||||
>
|
||||
{expanded
|
||||
? translate(
|
||||
'auto.components.automations.AutomationPromptDisclosure.showLess',
|
||||
'Show less'
|
||||
)
|
||||
: translate(
|
||||
'auto.components.automations.AutomationPromptDisclosure.showMore',
|
||||
'Show more'
|
||||
)}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="min-w-0 px-3 py-3">
|
||||
<p
|
||||
ref={setPromptElement}
|
||||
id={contentId}
|
||||
tabIndex={-1}
|
||||
className={cn(
|
||||
'select-text whitespace-pre-wrap text-sm text-foreground [overflow-wrap:anywhere]',
|
||||
!expanded && 'line-clamp-4'
|
||||
)}
|
||||
>
|
||||
{prompt}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -61,6 +61,7 @@ import {
|
||||
getVisibleBranchResults,
|
||||
getVisibleHeldProviderResults,
|
||||
isBlockingJiraUrlIntent,
|
||||
isBlockingTaskUrlResolution,
|
||||
type SmartNameMode,
|
||||
type SmartWorkspaceSourceRow
|
||||
} from './smart-workspace-source-results'
|
||||
@@ -639,6 +640,20 @@ export default function SmartWorkspaceNameField({
|
||||
() => (sourceQueryWithinLimit ? parseGitHubIssueOrPRLink(debouncedQuery) : null),
|
||||
[debouncedQuery, sourceQueryWithinLimit]
|
||||
)
|
||||
const githubUrlIntent = useMemo(
|
||||
() =>
|
||||
isSmartWorkspaceSourceQueryWithinLimit(value) && (mode === 'smart' || mode === 'github')
|
||||
? parseGitHubIssueOrPRLink(value)
|
||||
: null,
|
||||
[mode, value]
|
||||
)
|
||||
const gitlabUrlIntent = useMemo(
|
||||
() =>
|
||||
isSmartWorkspaceSourceQueryWithinLimit(value) && (mode === 'smart' || mode === 'gitlab')
|
||||
? parseGitLabIssueOrMRLink(value)
|
||||
: null,
|
||||
[mode, value]
|
||||
)
|
||||
const linearUrlIntent = useMemo(
|
||||
() => parseBoundedSmartWorkspaceLinearIssueUrlIntent(value),
|
||||
[value]
|
||||
@@ -1270,12 +1285,14 @@ export default function SmartWorkspaceNameField({
|
||||
value,
|
||||
debouncedQuery
|
||||
}),
|
||||
githubUrlIntent,
|
||||
gitlabAvailable: gitlabSourceAvailable,
|
||||
gitlabItems: getVisibleHeldProviderResults({
|
||||
items: gitlabItems,
|
||||
value,
|
||||
debouncedQuery
|
||||
}),
|
||||
gitlabUrlIntent,
|
||||
jiraIntent: jiraSource.intent,
|
||||
jiraIssue: jiraSource.issue,
|
||||
jiraIssues: getVisibleHeldProviderResults({
|
||||
@@ -1302,8 +1319,10 @@ export default function SmartWorkspaceNameField({
|
||||
branchResultsSource,
|
||||
debouncedQuery,
|
||||
githubItems,
|
||||
githubUrlIntent,
|
||||
gitlabSourceAvailable,
|
||||
gitlabItems,
|
||||
gitlabUrlIntent,
|
||||
jiraSource.accountChoices,
|
||||
jiraSource.intent,
|
||||
jiraSource.issue,
|
||||
@@ -1369,6 +1388,12 @@ export default function SmartWorkspaceNameField({
|
||||
linearAvailable &&
|
||||
sourceIntent !== 'linear' &&
|
||||
(linearLoading || settledLinearUrlQuery !== linearQuery.trim())
|
||||
const blockingTaskUrlResolution = isBlockingTaskUrlResolution({
|
||||
sourceIntent: sourceIntent === 'github' || sourceIntent === 'gitlab' ? sourceIntent : null,
|
||||
isQueryStale,
|
||||
githubLoading,
|
||||
gitlabLoading
|
||||
})
|
||||
|
||||
const resolvedCommandValue = resolveSmartWorkspaceCommandValue({
|
||||
currentValue: commandValue,
|
||||
@@ -1975,7 +2000,7 @@ export default function SmartWorkspaceNameField({
|
||||
handleEmojiSelect(selectedEmojiSuggestion)
|
||||
return
|
||||
}
|
||||
if (unresolvedLinearUrlIntent) {
|
||||
if (unresolvedLinearUrlIntent || blockingTaskUrlResolution) {
|
||||
event.preventDefault()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
getVisibleBranchResults,
|
||||
getVisibleHeldProviderResults,
|
||||
isBlockingJiraUrlIntent,
|
||||
isBlockingTaskUrlResolution,
|
||||
shouldHoldSourceResultsForQuery
|
||||
} from './smart-workspace-source-results'
|
||||
import {
|
||||
@@ -684,6 +685,38 @@ describe('Linear issue source input', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Task URL Enter protection', () => {
|
||||
it('blocks Enter while a pasted GitHub or GitLab URL is resolving', () => {
|
||||
expect(
|
||||
isBlockingTaskUrlResolution({
|
||||
sourceIntent: 'github',
|
||||
isQueryStale: true,
|
||||
githubLoading: false,
|
||||
gitlabLoading: false
|
||||
})
|
||||
).toBe(true)
|
||||
expect(
|
||||
isBlockingTaskUrlResolution({
|
||||
sourceIntent: 'gitlab',
|
||||
isQueryStale: false,
|
||||
githubLoading: false,
|
||||
gitlabLoading: true
|
||||
})
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps the workspace-name fallback after lookup settles without a match', () => {
|
||||
expect(
|
||||
isBlockingTaskUrlResolution({
|
||||
sourceIntent: 'github',
|
||||
isQueryStale: false,
|
||||
githubLoading: false,
|
||||
gitlabLoading: false
|
||||
})
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('Jira issue search', () => {
|
||||
it('keeps valid Jira URL intent blocking in both Smart and Jira modes', () => {
|
||||
const firstUrl = 'https://company.atlassian.net/browse/ORCA-1'
|
||||
|
||||
@@ -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
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import { activateAndRevealWorktree } from '@/lib/worktree-activation'
|
||||
import { isRuntimeOwnedSshTargetId, parseExecutionHostId } from '../../../../shared/execution-host'
|
||||
import type { Repo } from '../../../../shared/repo-types'
|
||||
import type { Worktree } from '../../../../shared/worktree/types'
|
||||
import { getWorktreeVisitTimestamp } from '@/lib/worktree-visit-recency'
|
||||
import { getDeleteStateForWorktreeHost } from './worktree-delete-state-host-match'
|
||||
|
||||
type AppStoreState = ReturnType<typeof useAppStore.getState>
|
||||
@@ -56,7 +57,9 @@ function pickNextWorktreeIdAfterDelete(
|
||||
if (others.length > 0) {
|
||||
const lastVisited = state.lastVisitedAtByWorktreeId
|
||||
const [mostRecent] = [...others].sort(
|
||||
(a, b) => (lastVisited[b.id] ?? 0) - (lastVisited[a.id] ?? 0)
|
||||
(a, b) =>
|
||||
(getWorktreeVisitTimestamp(lastVisited, b) ?? 0) -
|
||||
(getWorktreeVisitTimestamp(lastVisited, a) ?? 0)
|
||||
)
|
||||
return mostRecent.id
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
+100
@@ -328,6 +328,106 @@ describe('connectPanePty', () => {
|
||||
shellForeground: true
|
||||
})
|
||||
expect(resolveMockPaneWindowsShiftEnterEncoding(mockStoreState, paneKey)).toBe('alt-enter')
|
||||
// Why: `agentStatus:drop` deliberately preserves a live pane's per-pane caches, so a
|
||||
// process-confirmed agent exit must go through the reconcile route instead — otherwise a
|
||||
// surviving Claude latch resolves the pane's next event straight back to 'working' (STA-4612).
|
||||
expect(window.api.agentStatus.reconcileEndedProcess).toHaveBeenCalledWith(paneKey)
|
||||
})
|
||||
|
||||
it('reconciles a pane that HAS a status row, whose own drop removes it first', async () => {
|
||||
// Why this shape: the sibling test above covers a pane with no row, where the deferred drop
|
||||
// early-returns and never touches the pane's accepted-status bookkeeping. That is not the
|
||||
// production case. A pane worth reconciling always HAS a row — and settling runs the drop
|
||||
// BEFORE the reconcile, so the reconcile must survive its own drop having already fired.
|
||||
vi.useFakeTimers()
|
||||
const { connectPanePty } = await import('./pty-connection')
|
||||
// Both imported after vi.resetModules() so they share pty-connection's module registry; a
|
||||
// static top-level import here is a DIFFERENT instance and the assertion goes vacuous.
|
||||
const { createTestStore } = await import('@/store/slices/store-test-helpers')
|
||||
vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue('powershell.exe')
|
||||
vi.mocked(window.api.agentStatus.reconcileEndedProcess).mockClear()
|
||||
const dataCallbackRef: { current: ((data: string) => void) | null } = { current: null }
|
||||
const ptyId = 'pty-claude-row-confirmed-shell'
|
||||
const transport = createMockTransport(ptyId)
|
||||
transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
|
||||
dataCallbackRef.current = callbacks.onData ?? null
|
||||
return { id: ptyId }
|
||||
})
|
||||
transportFactoryQueue.push(transport)
|
||||
const paneKey = makePaneKey('tab-1', LEAF_1)
|
||||
|
||||
connectPanePty(
|
||||
createPane(1) as never,
|
||||
createManager(1) as never,
|
||||
createDeps({ isVisibleRef: { current: false } }) as never
|
||||
)
|
||||
await vi.advanceTimersByTimeAsync(20)
|
||||
await flushAsyncTicks()
|
||||
|
||||
// A real accepted status write, through the real slice, so the row carries whatever
|
||||
// bookkeeping the store stamps on an accepted write. `working` is the shape STA-4612 is about:
|
||||
// a latch is holding the pane open and the agent is about to exit out from under it.
|
||||
const realStore = createTestStore()
|
||||
realStore
|
||||
.getState()
|
||||
.setAgentStatus(paneKey, { state: 'working', prompt: 'ship it', agentType: 'claude' })
|
||||
const row = realStore.getState().agentStatusByPaneKey[paneKey]
|
||||
expect(row).toBeDefined()
|
||||
mockStoreState.agentStatusByPaneKey[paneKey] = row
|
||||
// The real dismissal removes the row and runs the slice's own teardown; mirror both, or the
|
||||
// ordering this test exists to pin is never exercised.
|
||||
mockStoreState.dropAgentStatus.mockImplementation((key: string) => {
|
||||
delete mockStoreState.agentStatusByPaneKey[key]
|
||||
realStore.getState().dropAgentStatus(key)
|
||||
})
|
||||
|
||||
dataCallbackRef.current?.('\x1b]133;D;0\x07')
|
||||
await vi.advanceTimersByTimeAsync(350)
|
||||
|
||||
expect(mockStoreState.dropAgentStatus).toHaveBeenCalledWith(paneKey)
|
||||
expect(window.api.agentStatus.reconcileEndedProcess).toHaveBeenCalledWith(paneKey)
|
||||
})
|
||||
|
||||
it('does NOT reconcile when the process check could not confirm a shell', async () => {
|
||||
vi.useFakeTimers()
|
||||
const { connectPanePty } = await import('./pty-connection')
|
||||
vi.mocked(window.api.pty.confirmForegroundProcess).mockResolvedValue(null)
|
||||
vi.mocked(window.api.agentStatus.reconcileEndedProcess).mockClear()
|
||||
const dataCallbackRef: { current: ((data: string) => void) | null } = { current: null }
|
||||
const ptyId = 'pty-unconfirmed-shell'
|
||||
const transport = createMockTransport(ptyId)
|
||||
transport.connect.mockImplementation(async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
|
||||
dataCallbackRef.current = callbacks.onData ?? null
|
||||
return { id: ptyId }
|
||||
})
|
||||
transportFactoryQueue.push(transport)
|
||||
const paneKey = makePaneKey('tab-1', LEAF_1)
|
||||
|
||||
connectPanePty(
|
||||
createPane(1) as never,
|
||||
createManager(1) as never,
|
||||
createDeps({ isVisibleRef: { current: false } }) as never
|
||||
)
|
||||
await vi.advanceTimersByTimeAsync(20)
|
||||
await flushAsyncTicks()
|
||||
mockStoreState.agentLaunchConfigByPaneKey[paneKey] = {
|
||||
launchConfig: { agentArgs: '', agentEnv: {} },
|
||||
identity: { agentType: 'droid' }
|
||||
}
|
||||
|
||||
dataCallbackRef.current?.('\x1b]133;D;0\x07')
|
||||
// Run the whole confirm ladder. At 350ms the unavailable branch has not settled yet, so
|
||||
// asserting there proves nothing — it would pass just as happily if this path DID tear the
|
||||
// pane down a moment later.
|
||||
await vi.advanceTimersByTimeAsync(350 + 1200 + 6000)
|
||||
await flushAsyncTicks()
|
||||
|
||||
// The unavailable branch really ran: it publishes an unproven foreground before settling.
|
||||
expect(mockStoreState.paneForegroundAgentByPaneKey[paneKey]).toEqual({
|
||||
agent: null,
|
||||
shellForeground: false
|
||||
})
|
||||
expect(window.api.agentStatus.reconcileEndedProcess).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('disarms stale TUI modes in the emulator after a confirmed return to shell', async () => {
|
||||
|
||||
+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) => {
|
||||
|
||||
+10
-2
@@ -33,14 +33,16 @@ const {
|
||||
scheduleRuntimeGraphSync,
|
||||
shouldSeedCacheTimerOnInitialTitle,
|
||||
toastInfo,
|
||||
notifyCodexPaneBoundForStaleSweep
|
||||
notifyCodexPaneBoundForStaleSweep,
|
||||
presentPaneViewportPreservingSynchronizedOutput
|
||||
} = vi.hoisted(() => ({
|
||||
resetAndRefreshAllTerminalWebglAtlases: vi.fn(),
|
||||
scheduleTerminalWebglAtlasRecovery: vi.fn(),
|
||||
scheduleRuntimeGraphSync: vi.fn(),
|
||||
shouldSeedCacheTimerOnInitialTitle: vi.fn(() => false),
|
||||
toastInfo: vi.fn(),
|
||||
notifyCodexPaneBoundForStaleSweep: vi.fn()
|
||||
notifyCodexPaneBoundForStaleSweep: vi.fn(),
|
||||
presentPaneViewportPreservingSynchronizedOutput: vi.fn()
|
||||
}))
|
||||
|
||||
let mockStoreState: StoreState
|
||||
@@ -57,6 +59,11 @@ vi.mock('@/lib/pane-manager/pane-manager-registry', async (importOriginal) => ({
|
||||
resetAndRefreshAllTerminalWebglAtlases
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/pane-manager/pane-webgl-renderer', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
presentPaneViewportPreservingSynchronizedOutput
|
||||
}))
|
||||
|
||||
vi.mock('./terminal-webgl-atlas-recovery', () => ({
|
||||
scheduleTerminalWebglAtlasRecovery
|
||||
}))
|
||||
@@ -201,6 +208,7 @@ describe('connectPanePty', () => {
|
||||
expect.stringContaining('remote snapshot with hidden remote output'),
|
||||
expect.any(Function)
|
||||
)
|
||||
expect(presentPaneViewportPreservingSynchronizedOutput).toHaveBeenCalledWith(pane)
|
||||
disposable.dispose()
|
||||
})
|
||||
|
||||
|
||||
@@ -72,7 +72,8 @@ export function installTerminalTestGlobals(): void {
|
||||
restoreTerminalFit: vi.fn().mockResolvedValue({ restored: true })
|
||||
},
|
||||
agentStatus: {
|
||||
inferInterrupt: vi.fn().mockResolvedValue(false)
|
||||
inferInterrupt: vi.fn().mockResolvedValue(false),
|
||||
reconcileEndedProcess: vi.fn()
|
||||
}
|
||||
},
|
||||
dispatchEvent: vi.fn(),
|
||||
|
||||
+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
|
||||
}
|
||||
}
|
||||
|
||||
+8
@@ -11,6 +11,7 @@ import {
|
||||
writeTerminalOutput
|
||||
} from '@/lib/pane-manager/pane-terminal-output-scheduler'
|
||||
import { recordTerminalOutput } from '@/lib/pane-manager/pane-scroll'
|
||||
import { presentPaneViewportPreservingSynchronizedOutput } from '@/lib/pane-manager/pane-webgl-renderer'
|
||||
import {
|
||||
buildMainModelSnapshotReplayWrites,
|
||||
hasPositiveTerminalDimensions,
|
||||
@@ -22,6 +23,7 @@ import { HIDDEN_OUTPUT_RESTORE_UNAVAILABLE_WARNING } from './hidden-output-resto
|
||||
import { shouldWritePtyOutputForeground } from './foreground-output-scan'
|
||||
import { isRemoteRuntimePtyId } from './paired-parked-terminal-restore'
|
||||
import { restoredSnapshotPaintsPrintableContent } from '../restored-snapshot-coverage'
|
||||
import { recordTerminalFreezeBreadcrumb } from '../terminal-freeze-breadcrumbs'
|
||||
|
||||
import type { ConnectPanePtySession } from './connect-pane-pty-session'
|
||||
|
||||
@@ -152,6 +154,12 @@ export function bindHiddenOutputRestoreSnapshot(session: ConnectPanePtySession):
|
||||
session.recordRendererOrderedSeq(snapshot)
|
||||
recordTerminalOutput(session.pane.terminal)
|
||||
await waitForTerminalReplayWritesParsed(session.pane.terminal)
|
||||
if (session.deps.isVisibleRef.current) {
|
||||
presentPaneViewportPreservingSynchronizedOutput(session.pane)
|
||||
recordTerminalFreezeBreadcrumb('stale-pixel-restore-present', {
|
||||
paneId: session.pane.id
|
||||
})
|
||||
}
|
||||
},
|
||||
{
|
||||
shouldRestore: () =>
|
||||
|
||||
@@ -88,12 +88,45 @@ export function installPaneAgentIdentity(session: ConnectPanePtySession): void {
|
||||
}
|
||||
}
|
||||
session.deferredCommandFinishedStatusDrop = null
|
||||
session.deferredConfirmedShellReconcile = null
|
||||
/** The pane's foreground was proven to be a shell, so its agent exited. Unlike a user dismissal,
|
||||
* this must also retire the main-side per-pane caches — a surviving Claude latch resolves the
|
||||
* next event straight back to `working`.
|
||||
*
|
||||
* Ordered by the row's `acceptedStatusSeq`, not by row identity or `updatedAt`: the confirming
|
||||
* process read can take seconds, an unrelated field moving in that window is not evidence the
|
||||
* agent is alive, and a genuinely newer row can share the anchor's millisecond. Reading the token
|
||||
* off the row is what makes the ordering safe — the paired drop runs FIRST and removes the row,
|
||||
* and a removed row means nothing reported, not "the anchor is gone".
|
||||
*
|
||||
* Residual: a row deleted by some OTHER path mid-window and then rebuilt restarts its count, so a
|
||||
* pane armed at 1 that reports exactly once more compares equal. It needs a foreign drop inside
|
||||
* the confirm window; the relaunch case that would otherwise hit it is already discarded by
|
||||
* onCommandStarted, and the cost is retiring a pane the process table just proved is a shell. */
|
||||
const reconcileEndedProcessIfPaneQuiet = (armedAcceptedStatusSeq: number | undefined): void => {
|
||||
const current = useAppStore.getState().agentStatusByPaneKey[session.cacheKey]
|
||||
if (current && current.acceptedStatusSeq !== armedAcceptedStatusSeq) {
|
||||
return
|
||||
}
|
||||
// Why: main-side only. The renderer row and launch config are already owned by the deferred
|
||||
// drop above; what that path cannot reach is the hook server's per-pane Claude latches, which
|
||||
// `agentStatus:drop` deliberately preserves for a still-live pane. Main echoes its own clear
|
||||
// back through the pane-status-cleared channel, so both sides stay consistent.
|
||||
window.api?.agentStatus?.reconcileEndedProcess?.(session.cacheKey)
|
||||
}
|
||||
session.visibleForegroundSamplePending = false
|
||||
session.visibleForegroundSampleSettled = false
|
||||
session.settleDeferredCommandFinishedStatusDrop = (): void => {
|
||||
session.settleDeferredCommandFinishedStatusDrop = (
|
||||
options: { confirmedShell?: boolean } = {}
|
||||
): void => {
|
||||
const dropStatus = session.deferredCommandFinishedStatusDrop
|
||||
const reconcile = session.deferredConfirmedShellReconcile
|
||||
session.deferredCommandFinishedStatusDrop = null
|
||||
session.deferredConfirmedShellReconcile = null
|
||||
dropStatus?.()
|
||||
if (options.confirmedShell) {
|
||||
reconcile?.()
|
||||
}
|
||||
}
|
||||
session.isForegroundTrackingAllowed = (id: string): boolean => {
|
||||
if (isRemoteRuntimePtyId(id) || parseAppSshPtyId(id) !== null) {
|
||||
@@ -143,9 +176,11 @@ export function installPaneAgentIdentity(session: ConnectPanePtySession): void {
|
||||
useAppStore.getState().clearAgentLaunchConfig(session.cacheKey)
|
||||
return
|
||||
}
|
||||
session.settleDeferredCommandFinishedStatusDrop()
|
||||
session.settleDeferredCommandFinishedStatusDrop({ confirmedShell: true })
|
||||
},
|
||||
onCommandFinishedUnavailable: session.settleDeferredCommandFinishedStatusDrop,
|
||||
// Why wrapped: passed bare, a caller-supplied argument would be read as `options` and could
|
||||
// reconcile on the unavailable path, which has no proof the agent exited.
|
||||
onCommandFinishedUnavailable: () => session.settleDeferredCommandFinishedStatusDrop(),
|
||||
onVisibleForegroundSettled: (outcome) => {
|
||||
session.visibleForegroundSamplePending = false
|
||||
session.visibleForegroundSampleSettled = outcome !== 'inconclusive'
|
||||
@@ -195,10 +230,16 @@ export function installPaneAgentIdentity(session: ConnectPanePtySession): void {
|
||||
if (shouldDeferStatusDrop) {
|
||||
// Why: keep the concrete pane identity routable while the local process
|
||||
// check distinguishes a leaked nested-shell D from a genuine agent exit.
|
||||
// Anchor the accepted-status ordinal once, here — not per rung of the confirm ladder, which
|
||||
// can span seconds — so the gate tolerates churn across the whole window.
|
||||
const armedAcceptedStatusSeq = entry?.acceptedStatusSeq
|
||||
session.deferredCommandFinishedStatusDrop = dropStatus
|
||||
session.deferredConfirmedShellReconcile = () =>
|
||||
reconcileEndedProcessIfPaneQuiet(armedAcceptedStatusSeq)
|
||||
return
|
||||
}
|
||||
session.deferredCommandFinishedStatusDrop = null
|
||||
session.deferredConfirmedShellReconcile = null
|
||||
dropStatus()
|
||||
}
|
||||
session.sampleVisiblePaneForegroundAgent = (forceRoutingConfirmation = false): void => {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -8,6 +8,10 @@ import {
|
||||
vi.mock('@/lib/pane-manager/pane-manager-registry', () => ({
|
||||
resetAndRefreshAllTerminalWebglAtlases: vi.fn()
|
||||
}))
|
||||
const presentPaneViewport = vi.fn()
|
||||
vi.mock('@/lib/pane-manager/pane-webgl-renderer', () => ({
|
||||
presentPaneViewport: (pane: unknown) => presentPaneViewport(pane)
|
||||
}))
|
||||
vi.mock('@/lib/pane-manager/pane-terminal-output-scheduler', () => ({
|
||||
flushTerminalOutput: vi.fn(),
|
||||
requestTerminalBacklogRecovery: vi.fn()
|
||||
@@ -21,10 +25,6 @@ vi.mock('./pane-helpers', () => ({
|
||||
fitPanes: vi.fn(),
|
||||
focusActivePane: vi.fn()
|
||||
}))
|
||||
const scheduleTabRevealWebglAtlasRecovery = vi.fn()
|
||||
vi.mock('./terminal-webgl-atlas-recovery', () => ({
|
||||
scheduleTabRevealWebglAtlasRecovery: () => scheduleTabRevealWebglAtlasRecovery()
|
||||
}))
|
||||
const flushDeferredPaneMetricOptionsIfMeasurable = vi.fn((_pane: unknown) => false)
|
||||
vi.mock('@/lib/pane-manager/pane-fit', () => ({
|
||||
flushDeferredPaneMetricOptionsIfMeasurable: (pane: unknown) =>
|
||||
@@ -77,18 +77,19 @@ function resumeArgs(manager: FakeManager, shouldUseLightTabResume: boolean) {
|
||||
describe('resumeTerminalVisibility reveal repaint', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
repairPaneWebglCanvasDprMismatch.mockReturnValue(false)
|
||||
})
|
||||
|
||||
it('schedules a pane-scoped repaint on a light tab reveal', () => {
|
||||
it('schedules an atlas-preserving present on a light tab reveal', () => {
|
||||
// The light path is the "click the tab that was not open" gesture: it has
|
||||
// no rendering resume or fit, so without this repaint a hidden-while-
|
||||
// working pane keeps compositing pre-hide pixels.
|
||||
const manager = createManager()
|
||||
resumeTerminalVisibility(resumeArgs(manager, true))
|
||||
|
||||
expect(manager.scheduleRevealRepaint).toHaveBeenCalledTimes(1)
|
||||
expect(manager.scheduleRevealRepaint).not.toHaveBeenCalled()
|
||||
expect(manager.scheduleRevealPresent).toHaveBeenCalledTimes(1)
|
||||
expect(manager.resumeRendering).not.toHaveBeenCalled()
|
||||
expect(scheduleTabRevealWebglAtlasRecovery).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('captures native trim movement before enforcing viewport intent', async () => {
|
||||
@@ -147,6 +148,29 @@ describe('resumeTerminalVisibility reveal repaint', () => {
|
||||
expect(flushDeferredPaneMetricOptionsIfMeasurable).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('defers a heavy-reveal dpr present until the shared atlas recovery', async () => {
|
||||
const pane = { terminal: {} }
|
||||
const manager = createManager()
|
||||
manager.getPanes.mockReturnValue([pane])
|
||||
repairPaneWebglCanvasDprMismatch.mockReturnValueOnce(true)
|
||||
const { resetAndRefreshAllTerminalWebglAtlases } = vi.mocked(
|
||||
await import('@/lib/pane-manager/pane-manager-registry')
|
||||
)
|
||||
|
||||
resumeTerminalVisibility(resumeArgs(manager, false))
|
||||
|
||||
expect(repairPaneWebglCanvasDprMismatch).toHaveBeenCalledWith(pane)
|
||||
expect(presentPaneViewport).not.toHaveBeenCalled()
|
||||
expect(resetAndRefreshAllTerminalWebglAtlases).toHaveBeenCalledTimes(1)
|
||||
const atlasResetCallOrder = resetAndRefreshAllTerminalWebglAtlases.mock.invocationCallOrder[0]
|
||||
if (atlasResetCallOrder === undefined) {
|
||||
throw new Error('Shared atlas recovery call order missing')
|
||||
}
|
||||
expect(repairPaneWebglCanvasDprMismatch.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
atlasResetCallOrder
|
||||
)
|
||||
})
|
||||
|
||||
it('does not fit on a light tab reveal', () => {
|
||||
const manager = createManager()
|
||||
resumeTerminalVisibility(resumeArgs(manager, true))
|
||||
@@ -193,6 +217,27 @@ describe('resumeTerminalVisibility reveal repaint', () => {
|
||||
expect(manager.fitAllPanes).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('repairs WebGL canvas backing-store dpr on window wake', () => {
|
||||
// Clamshell undock: dpr changes while the pane stayed "visible" with a
|
||||
// stale backing store; tab-reveal is not in the path.
|
||||
const first = { terminal: { name: 'pane-a' } }
|
||||
const second = { terminal: { name: 'pane-b' } }
|
||||
const manager = createManager()
|
||||
manager.getPanes.mockReturnValue([first, second])
|
||||
repairPaneWebglCanvasDprMismatch.mockReturnValueOnce(true)
|
||||
|
||||
recoverVisibleTerminalWindowWake({
|
||||
manager: manager as never as PaneManager,
|
||||
isActive: true,
|
||||
clearGlyphAtlases: false
|
||||
})
|
||||
|
||||
expect(repairPaneWebglCanvasDprMismatch).toHaveBeenCalledTimes(2)
|
||||
expect(repairPaneWebglCanvasDprMismatch).toHaveBeenNthCalledWith(1, first)
|
||||
expect(repairPaneWebglCanvasDprMismatch).toHaveBeenNthCalledWith(2, second)
|
||||
expect(presentPaneViewport).toHaveBeenCalledWith(first)
|
||||
})
|
||||
|
||||
it('latches viewport intent before refocus recovery flushes streaming output', async () => {
|
||||
const terminal = { name: 'streaming-terminal' }
|
||||
const manager = createManager()
|
||||
|
||||
@@ -14,9 +14,9 @@ import {
|
||||
resetTerminalLinkifierHoverState
|
||||
} from '@/lib/pane-manager/terminal-linkifier-hover-reset'
|
||||
import { focusActivePane } from './pane-helpers'
|
||||
import { scheduleTabRevealWebglAtlasRecovery } from './terminal-webgl-atlas-recovery'
|
||||
import { flushDeferredPaneMetricOptionsIfMeasurable } from '@/lib/pane-manager/pane-fit'
|
||||
import { repairPaneWebglCanvasDprMismatch } from '@/lib/pane-manager/terminal-canvas-dpr-repair'
|
||||
import { presentPaneViewport } from '@/lib/pane-manager/pane-webgl-renderer'
|
||||
|
||||
const VISIBLE_RESUME_FLUSH_CHARS = 256 * 1024
|
||||
const WINDOW_WAKE_FLUSH_CHARS = 64 * 1024
|
||||
@@ -88,8 +88,6 @@ export function resumeTerminalVisibility({
|
||||
// overlay's delayed geometry fit. Still request hidden-output recovery:
|
||||
// agent TUIs can suppress hidden bytes until the pane is foregrounded.
|
||||
requestLightTabBacklogRecovery(manager)
|
||||
// Why: reveal is the lifecycle boundary that owns hidden renderer repair.
|
||||
scheduleTabRevealWebglAtlasRecovery()
|
||||
if (flushedDeferredMetrics) {
|
||||
// Why: the light path normally skips fitting, but flushed metrics changed
|
||||
// cell size — refit so cols/rows match before the overlay settles.
|
||||
@@ -109,10 +107,15 @@ export function resumeTerminalVisibility({
|
||||
// terminals; refresh after reset so rebuilt atlases repaint from xterm.
|
||||
resetAndRefreshAllTerminalWebglAtlases('visibility-resume')
|
||||
}
|
||||
// Why: the synchronous recovery above can fire before the revealed pane is
|
||||
// attached and laid out. Follow up after layout with one shared-atlas-safe
|
||||
// recovery covering every visible terminal manager.
|
||||
manager.scheduleRevealRepaint()
|
||||
if (shouldUseLightTabResume) {
|
||||
// Why: preserve the last coherent frame while a TUI holds DEC 2026. The
|
||||
// settled refresh arms xterm's watchdog without clearing shared GPU data.
|
||||
manager.scheduleRevealPresent()
|
||||
} else {
|
||||
// Why: rendering was recreated, so the heavy path still needs the proven
|
||||
// shared-atlas recovery after layout settles.
|
||||
manager.scheduleRevealRepaint()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -161,6 +164,13 @@ export function recoverVisibleTerminalWindowWake({
|
||||
// Why: backlog writes can expose transient viewport geometry while parsing.
|
||||
syncTerminalViewportIntents(manager)
|
||||
for (const pane of manager.getPanes()) {
|
||||
// Why: clamshell undock / monitor move changes devicePixelRatio while the
|
||||
// pane can stay "visible" with a stale WebGL backing store. The addon's
|
||||
// device-pixel observer misses that (no CSS-box change, or no box while
|
||||
// the lid was closed). Repair here — not only on tab reveal.
|
||||
if (repairPaneWebglCanvasDprMismatch(pane)) {
|
||||
presentPaneViewport(pane)
|
||||
}
|
||||
requestTerminalBacklogRecovery(pane.terminal)
|
||||
flushTerminalOutput(pane.terminal, { maxChars: WINDOW_WAKE_FLUSH_CHARS })
|
||||
// Why: window blur fires mouseleave, clearing xterm's current link but not
|
||||
@@ -214,6 +224,12 @@ function resumeTerminalVisibilityHeavy(manager: PaneManager, isActive: boolean):
|
||||
// Windows (ANGLE -> D3D11) it can be 100-500 ms but a deferred resume
|
||||
// would paint a stretched DOM-fallback flash, which is worse UX.
|
||||
manager.resumeRendering()
|
||||
// Why: unchanged grid geometry can skip the reveal fit, but a retained WebGL
|
||||
// canvas may still carry the previous display's backing-store DPR. The
|
||||
// caller's atlas recovery presents the final shared-atlas generation.
|
||||
for (const pane of manager.getPanes()) {
|
||||
repairPaneWebglCanvasDprMismatch(pane)
|
||||
}
|
||||
// Why: resumeRendering just re-attached WebGL, whose cell metrics briefly differ
|
||||
// from the DOM renderer's; a raw fit here reflows on a transient one-column-off
|
||||
// grid and garbles diff-painting inline TUIs (grok minimize→restore).
|
||||
|
||||
@@ -5,8 +5,7 @@ import {
|
||||
} from '@/lib/pane-manager/pane-manager-registry'
|
||||
import * as terminalWebglAtlasRecovery from './terminal-webgl-atlas-recovery'
|
||||
|
||||
const { scheduleImagePasteWebglAtlasRecovery, scheduleTabRevealWebglAtlasRecovery } =
|
||||
terminalWebglAtlasRecovery
|
||||
const { scheduleImagePasteWebglAtlasRecovery } = terminalWebglAtlasRecovery
|
||||
|
||||
describe('terminal WebGL atlas recovery', () => {
|
||||
const registeredManagers: { resetWebglTextureAtlases(): void }[] = []
|
||||
@@ -151,26 +150,4 @@ describe('terminal WebGL atlas recovery', () => {
|
||||
expect(healthyManager.refreshAllPanes).toHaveBeenCalledTimes(3)
|
||||
expect(manager.refreshAllPanes).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('recovers immediately on a tab reveal', () => {
|
||||
vi.useFakeTimers()
|
||||
const rafCallbacks: FrameRequestCallback[] = []
|
||||
vi.stubGlobal(
|
||||
'requestAnimationFrame',
|
||||
vi.fn((callback: FrameRequestCallback) => {
|
||||
rafCallbacks.push(callback)
|
||||
return rafCallbacks.length
|
||||
})
|
||||
)
|
||||
const manager = registerManager()
|
||||
|
||||
scheduleTabRevealWebglAtlasRecovery()
|
||||
rafCallbacks[0]?.(0)
|
||||
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1)
|
||||
expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1)
|
||||
vi.advanceTimersByTime(120)
|
||||
vi.advanceTimersByTime(380)
|
||||
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(3)
|
||||
expect(manager.refreshAllPanes).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -33,9 +33,3 @@ export function scheduleImagePasteWebglAtlasRecovery(): void {
|
||||
// one-shot event, so recover immediately rather than debouncing.
|
||||
scheduleAtlasRecoveryBurst('image-paste')
|
||||
}
|
||||
|
||||
export function scheduleTabRevealWebglAtlasRecovery(): void {
|
||||
// Why: a tab reveal is an explicit renderer lifecycle boundary where hidden
|
||||
// GPU state can be stale; ordinary PTY output must not clear the shared atlas.
|
||||
scheduleAtlasRecoveryBurst('tab-reveal')
|
||||
}
|
||||
|
||||
+12
-4
@@ -260,6 +260,8 @@ describe('useTerminalPaneGlobalEffects', () => {
|
||||
|
||||
manager.resumeRendering.mockClear()
|
||||
manager.resetWebglTextureAtlases.mockClear()
|
||||
manager.scheduleRevealRepaint.mockClear()
|
||||
manager.scheduleRevealPresent.mockClear()
|
||||
manager.refreshAllPanes.mockClear()
|
||||
manager.suspendRendering.mockClear()
|
||||
mocks.fitAndFocusPanes.mockClear()
|
||||
@@ -289,8 +291,10 @@ describe('useTerminalPaneGlobalEffects', () => {
|
||||
expect(manager.resumeRendering).not.toHaveBeenCalled()
|
||||
expect(mocks.fitAndFocusPanes).not.toHaveBeenCalled()
|
||||
expect(mocks.fitPanes).not.toHaveBeenCalled()
|
||||
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1)
|
||||
expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1)
|
||||
expect(manager.resetWebglTextureAtlases).not.toHaveBeenCalled()
|
||||
expect(manager.refreshAllPanes).not.toHaveBeenCalled()
|
||||
expect(manager.scheduleRevealRepaint).not.toHaveBeenCalled()
|
||||
expect(manager.scheduleRevealPresent).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.focusActivePane).toHaveBeenCalledWith(manager)
|
||||
vi.advanceTimersByTime(500)
|
||||
})
|
||||
@@ -342,6 +346,8 @@ describe('useTerminalPaneGlobalEffects', () => {
|
||||
|
||||
manager.resumeRendering.mockClear()
|
||||
manager.resetWebglTextureAtlases.mockClear()
|
||||
manager.scheduleRevealRepaint.mockClear()
|
||||
manager.scheduleRevealPresent.mockClear()
|
||||
manager.refreshAllPanes.mockClear()
|
||||
mocks.fitAndFocusPanes.mockClear()
|
||||
mocks.fitPanes.mockClear()
|
||||
@@ -361,8 +367,10 @@ describe('useTerminalPaneGlobalEffects', () => {
|
||||
expect(manager.resumeRendering).not.toHaveBeenCalled()
|
||||
expect(mocks.fitAndFocusPanes).not.toHaveBeenCalled()
|
||||
expect(mocks.fitPanes).not.toHaveBeenCalled()
|
||||
expect(manager.resetWebglTextureAtlases).toHaveBeenCalledTimes(1)
|
||||
expect(manager.refreshAllPanes).toHaveBeenCalledTimes(1)
|
||||
expect(manager.resetWebglTextureAtlases).not.toHaveBeenCalled()
|
||||
expect(manager.refreshAllPanes).not.toHaveBeenCalled()
|
||||
expect(manager.scheduleRevealRepaint).not.toHaveBeenCalled()
|
||||
expect(manager.scheduleRevealPresent).toHaveBeenCalledTimes(1)
|
||||
expect(mocks.focusActivePane).toHaveBeenCalledWith(manager)
|
||||
vi.advanceTimersByTime(500)
|
||||
})
|
||||
|
||||
+134
-2
@@ -2,15 +2,30 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { renderHook } from '@testing-library/react'
|
||||
import type { PaneManager } from '@/lib/pane-manager/pane-manager'
|
||||
import type { PaneWebglCanvasDprRepairState } from '@/lib/pane-manager/terminal-canvas-dpr-repair'
|
||||
|
||||
const { recoverVisibleTerminalWindowWakeMock } = vi.hoisted(() => ({
|
||||
recoverVisibleTerminalWindowWakeMock: vi.fn()
|
||||
const {
|
||||
recoverVisibleTerminalWindowWakeMock,
|
||||
repairPaneWebglCanvasDprMock,
|
||||
presentPaneViewportMock
|
||||
} = vi.hoisted(() => ({
|
||||
recoverVisibleTerminalWindowWakeMock: vi.fn(),
|
||||
repairPaneWebglCanvasDprMock: vi.fn<() => PaneWebglCanvasDprRepairState>(() => 'current'),
|
||||
presentPaneViewportMock: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('./terminal-visibility-resume', () => ({
|
||||
recoverVisibleTerminalWindowWake: recoverVisibleTerminalWindowWakeMock
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/pane-manager/terminal-canvas-dpr-repair', () => ({
|
||||
repairPaneWebglCanvasDpr: repairPaneWebglCanvasDprMock
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/pane-manager/pane-webgl-renderer', () => ({
|
||||
presentPaneViewport: presentPaneViewportMock
|
||||
}))
|
||||
|
||||
import { useTerminalWindowWakeRecovery } from './use-terminal-window-wake-recovery'
|
||||
import {
|
||||
getTerminalFreezeBreadcrumbs,
|
||||
@@ -29,6 +44,9 @@ describe('useTerminalWindowWakeRecovery', () => {
|
||||
beforeEach(() => {
|
||||
systemResumedCallback = null
|
||||
recoverVisibleTerminalWindowWakeMock.mockClear()
|
||||
repairPaneWebglCanvasDprMock.mockClear()
|
||||
presentPaneViewportMock.mockClear()
|
||||
repairPaneWebglCanvasDprMock.mockReturnValue('current')
|
||||
unsubscribeSystemResumed.mockClear()
|
||||
onSystemResumed.mockClear()
|
||||
resetTerminalFreezeBreadcrumbsForTesting()
|
||||
@@ -180,4 +198,118 @@ describe('useTerminalWindowWakeRecovery', () => {
|
||||
|
||||
expect(onSystemResumed).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('repairs WebGL canvas dpr on window resize without wiping the glyph atlas', () => {
|
||||
// Chromium emits resize when devicePixelRatio changes (undock / monitor
|
||||
// move) even if the CSS box is unchanged.
|
||||
const pane = { id: 1, terminal: {} }
|
||||
const resizeManager = { getPanes: () => [pane] } as unknown as PaneManager
|
||||
repairPaneWebglCanvasDprMock.mockReturnValue('repaired')
|
||||
vi.stubGlobal('devicePixelRatio', 1)
|
||||
const { unmount } = renderHook(() =>
|
||||
useTerminalWindowWakeRecovery({
|
||||
isVisible: true,
|
||||
managerRef: { current: resizeManager },
|
||||
isActiveRef: { current: true },
|
||||
isVisibleRef: { current: true }
|
||||
})
|
||||
)
|
||||
|
||||
window.dispatchEvent(new Event('resize'))
|
||||
expect(repairPaneWebglCanvasDprMock).not.toHaveBeenCalled()
|
||||
|
||||
vi.stubGlobal('devicePixelRatio', 2)
|
||||
window.dispatchEvent(new Event('resize'))
|
||||
|
||||
expect(repairPaneWebglCanvasDprMock).toHaveBeenCalledWith(pane)
|
||||
expect(presentPaneViewportMock).toHaveBeenCalledWith(pane)
|
||||
expect(recoverVisibleTerminalWindowWakeMock).not.toHaveBeenCalled()
|
||||
|
||||
unmount()
|
||||
vi.stubGlobal('devicePixelRatio', 3)
|
||||
window.dispatchEvent(new Event('resize'))
|
||||
expect(repairPaneWebglCanvasDprMock).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('retains a dpr transition until the visible manager is available', () => {
|
||||
const pane = { id: 1, terminal: {} }
|
||||
const managerRef: { current: PaneManager | null } = { current: null }
|
||||
vi.stubGlobal('devicePixelRatio', 1)
|
||||
renderHook(() =>
|
||||
useTerminalWindowWakeRecovery({
|
||||
isVisible: true,
|
||||
managerRef,
|
||||
isActiveRef: { current: true },
|
||||
isVisibleRef: { current: true }
|
||||
})
|
||||
)
|
||||
|
||||
vi.stubGlobal('devicePixelRatio', 2)
|
||||
window.dispatchEvent(new Event('resize'))
|
||||
expect(repairPaneWebglCanvasDprMock).not.toHaveBeenCalled()
|
||||
|
||||
managerRef.current = { getPanes: () => [pane] } as unknown as PaneManager
|
||||
window.dispatchEvent(new Event('resize'))
|
||||
expect(repairPaneWebglCanvasDprMock).toHaveBeenCalledWith(pane)
|
||||
})
|
||||
|
||||
it('deduplicates a deferred dpr retry and consumes it after repair succeeds', () => {
|
||||
const pane = { id: 1, terminal: {} }
|
||||
const callbacks: FrameRequestCallback[] = []
|
||||
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
|
||||
callbacks.push(callback)
|
||||
return callbacks.length
|
||||
})
|
||||
vi.stubGlobal('devicePixelRatio', 1)
|
||||
repairPaneWebglCanvasDprMock.mockReturnValueOnce('deferred').mockReturnValue('repaired')
|
||||
renderHook(() =>
|
||||
useTerminalWindowWakeRecovery({
|
||||
isVisible: true,
|
||||
managerRef: { current: { getPanes: () => [pane] } as unknown as PaneManager },
|
||||
isActiveRef: { current: true },
|
||||
isVisibleRef: { current: true }
|
||||
})
|
||||
)
|
||||
|
||||
vi.stubGlobal('devicePixelRatio', 2)
|
||||
window.dispatchEvent(new Event('resize'))
|
||||
window.dispatchEvent(new Event('resize'))
|
||||
expect(repairPaneWebglCanvasDprMock).toHaveBeenCalledTimes(1)
|
||||
expect(callbacks).toHaveLength(1)
|
||||
|
||||
callbacks.shift()?.(performance.now())
|
||||
expect(presentPaneViewportMock).toHaveBeenCalledWith(pane)
|
||||
window.dispatchEvent(new Event('resize'))
|
||||
expect(repairPaneWebglCanvasDprMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('caps a deferred dpr transition at sixteen animation-frame retries', () => {
|
||||
const pane = { id: 1, terminal: {} }
|
||||
const callbacks: FrameRequestCallback[] = []
|
||||
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
|
||||
callbacks.push(callback)
|
||||
return callbacks.length
|
||||
})
|
||||
vi.stubGlobal('devicePixelRatio', 1)
|
||||
repairPaneWebglCanvasDprMock.mockReturnValue('deferred')
|
||||
renderHook(() =>
|
||||
useTerminalWindowWakeRecovery({
|
||||
isVisible: true,
|
||||
managerRef: { current: { getPanes: () => [pane] } as unknown as PaneManager },
|
||||
isActiveRef: { current: true },
|
||||
isVisibleRef: { current: true }
|
||||
})
|
||||
)
|
||||
|
||||
vi.stubGlobal('devicePixelRatio', 2)
|
||||
window.dispatchEvent(new Event('resize'))
|
||||
let callbackCount = 0
|
||||
while (callbacks.length > 0) {
|
||||
callbacks.shift()?.(performance.now())
|
||||
callbackCount += 1
|
||||
}
|
||||
|
||||
expect(callbackCount).toBe(16)
|
||||
expect(repairPaneWebglCanvasDprMock).toHaveBeenCalledTimes(17)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useEffect } from 'react'
|
||||
import type { PaneManager } from '@/lib/pane-manager/pane-manager'
|
||||
import { recoverVisibleTerminalWindowWake } from './terminal-visibility-resume'
|
||||
import { repairPaneWebglCanvasDpr } from '@/lib/pane-manager/terminal-canvas-dpr-repair'
|
||||
import { presentPaneViewport } from '@/lib/pane-manager/pane-webgl-renderer'
|
||||
import { recordTerminalFreezeBreadcrumb } from './terminal-freeze-breadcrumbs'
|
||||
import type { IDisposable } from '@xterm/xterm'
|
||||
|
||||
@@ -16,6 +18,8 @@ type WindowWakePtyBinding = IDisposable & {
|
||||
reassertPtySizeAfterWindowWake?: () => void
|
||||
}
|
||||
|
||||
const DPR_RECOVERY_RETRY_FRAMES = 16
|
||||
|
||||
export function useTerminalWindowWakeRecovery({
|
||||
isVisible,
|
||||
managerRef,
|
||||
@@ -28,7 +32,10 @@ export function useTerminalWindowWakeRecovery({
|
||||
return
|
||||
}
|
||||
let wakeRecoveryFrameId: number | null = null
|
||||
let dprRecoveryFrameId: number | null = null
|
||||
let dprRecoveryFramesRemaining = 0
|
||||
let settledClearGlyphAtlases = false
|
||||
let observedDevicePixelRatio = window.devicePixelRatio
|
||||
const cancelScheduledWakeRecovery = (): void => {
|
||||
if (wakeRecoveryFrameId === null || typeof cancelAnimationFrame !== 'function') {
|
||||
wakeRecoveryFrameId = null
|
||||
@@ -37,6 +44,13 @@ export function useTerminalWindowWakeRecovery({
|
||||
cancelAnimationFrame(wakeRecoveryFrameId)
|
||||
wakeRecoveryFrameId = null
|
||||
}
|
||||
const cancelScheduledDprRecovery = (): void => {
|
||||
if (dprRecoveryFrameId !== null && typeof cancelAnimationFrame === 'function') {
|
||||
cancelAnimationFrame(dprRecoveryFrameId)
|
||||
}
|
||||
dprRecoveryFrameId = null
|
||||
dprRecoveryFramesRemaining = 0
|
||||
}
|
||||
const reassertPanePtySizes = (): void => {
|
||||
for (const binding of panePtyBindingsRef?.current.values() ?? []) {
|
||||
// Why: one settled read avoids duplicate SSH RPCs while still detecting a dropped resize.
|
||||
@@ -111,7 +125,59 @@ export function useTerminalWindowWakeRecovery({
|
||||
recoverVisibleWake(true, 'system-resumed')
|
||||
}
|
||||
}
|
||||
const repairVisiblePanesForDpr = (devicePixelRatio: number): boolean => {
|
||||
const manager = managerRef.current
|
||||
if (!manager || !isVisibleRef.current) {
|
||||
return false
|
||||
}
|
||||
let deferred = false
|
||||
for (const pane of manager.getPanes?.() ?? []) {
|
||||
const state = repairPaneWebglCanvasDpr(pane)
|
||||
deferred ||= state === 'deferred'
|
||||
if (state === 'repaired') {
|
||||
presentPaneViewport(pane)
|
||||
}
|
||||
}
|
||||
if (!deferred) {
|
||||
observedDevicePixelRatio = devicePixelRatio
|
||||
}
|
||||
return !deferred
|
||||
}
|
||||
const scheduleDprRecovery = (): void => {
|
||||
if (dprRecoveryFrameId !== null || typeof requestAnimationFrame !== 'function') {
|
||||
return
|
||||
}
|
||||
dprRecoveryFramesRemaining = DPR_RECOVERY_RETRY_FRAMES
|
||||
const retry = (): void => {
|
||||
dprRecoveryFrameId = null
|
||||
if (repairVisiblePanesForDpr(window.devicePixelRatio)) {
|
||||
dprRecoveryFramesRemaining = 0
|
||||
return
|
||||
}
|
||||
dprRecoveryFramesRemaining -= 1
|
||||
if (dprRecoveryFramesRemaining > 0) {
|
||||
dprRecoveryFrameId = requestAnimationFrame(retry)
|
||||
}
|
||||
}
|
||||
dprRecoveryFrameId = requestAnimationFrame(retry)
|
||||
}
|
||||
const onWindowResize = (): void => {
|
||||
// Why: Chromium emits window resize on devicePixelRatio changes even when
|
||||
// the CSS box is unchanged (monitor move / undock). xterm's own observer
|
||||
// misses that while the canvas had no box (laptop lid closed).
|
||||
const devicePixelRatio = window.devicePixelRatio
|
||||
if (devicePixelRatio === observedDevicePixelRatio) {
|
||||
return
|
||||
}
|
||||
if (dprRecoveryFrameId !== null) {
|
||||
return
|
||||
}
|
||||
if (!repairVisiblePanesForDpr(devicePixelRatio)) {
|
||||
scheduleDprRecovery()
|
||||
}
|
||||
}
|
||||
window.addEventListener('focus', onFocus)
|
||||
window.addEventListener('resize', onWindowResize)
|
||||
if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') {
|
||||
document.addEventListener('visibilitychange', onVisibilityChange)
|
||||
}
|
||||
@@ -125,7 +191,9 @@ export function useTerminalWindowWakeRecovery({
|
||||
: null
|
||||
return () => {
|
||||
cancelScheduledWakeRecovery()
|
||||
cancelScheduledDprRecovery()
|
||||
window.removeEventListener('focus', onFocus)
|
||||
window.removeEventListener('resize', onWindowResize)
|
||||
if (typeof document !== 'undefined' && typeof document.removeEventListener === 'function') {
|
||||
document.removeEventListener('visibilitychange', onVisibilityChange)
|
||||
}
|
||||
|
||||
+23
@@ -9,6 +9,7 @@ import {
|
||||
resetWorkspaceCleanupBrowsePersistTimer
|
||||
} from '@/store/slices/workspace-cleanup-browse'
|
||||
import { createDefaultWorkspaceCleanupBrowseState } from '../../../../shared/workspace-cleanup-browse-state'
|
||||
import { listAppliedWorkspaceCleanupFilters } from '../../../../shared/workspace-cleanup-applied-filters'
|
||||
import { useWorkspaceCleanupBrowseState } from './use-workspace-cleanup-browse-state'
|
||||
import type { WorkspaceCleanupBrowseController } from './use-workspace-cleanup-browse-state'
|
||||
|
||||
@@ -104,5 +105,27 @@ describe('useWorkspaceCleanupBrowseState', () => {
|
||||
field: 'size',
|
||||
direction: 'desc'
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps a cleared chip cleared when a facet patch lands in the same tick', () => {
|
||||
const controller = mountController()
|
||||
act(() => controller.current!.patchFilters('activity', { idleMinDays: 20 }))
|
||||
|
||||
const format = new Proxy({}, { get: () => () => 'chip' }) as Parameters<
|
||||
typeof listAppliedWorkspaceCleanupFilters
|
||||
>[1]
|
||||
const chip = listAppliedWorkspaceCleanupFilters(
|
||||
store.getState().workspaceCleanupBrowse.filters,
|
||||
format
|
||||
).find((a) => a.id === 'activity.idleMinDays')!
|
||||
|
||||
act(() => {
|
||||
controller.current!.replaceFilters(chip.clear)
|
||||
controller.current!.patchFilters('git', { states: ['dirty'] })
|
||||
})
|
||||
|
||||
const filters = store.getState().workspaceCleanupBrowse.filters
|
||||
expect(filters.activity.idleMinDays).toBeNull()
|
||||
expect(filters.git.states).toEqual(['dirty'])
|
||||
})
|
||||
})
|
||||
|
||||
+15
-1
@@ -16,6 +16,10 @@ export type WorkspaceCleanupBrowseController = {
|
||||
) => void
|
||||
toggleSortField: (field: WorkspaceCleanupSortField) => void
|
||||
clearFilters: () => void
|
||||
/** Applies a whole-state transform, for callers that clear one named constraint. */
|
||||
replaceFilters: (
|
||||
transform: (filters: WorkspaceCleanupFilterState) => WorkspaceCleanupFilterState
|
||||
) => void
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,6 +60,15 @@ export function useWorkspaceCleanupBrowseState(): WorkspaceCleanupBrowseControll
|
||||
[updateBrowse]
|
||||
)
|
||||
|
||||
// Same updater form as patchFilters: a chip clear and a facet patch can land in one
|
||||
// tick, and whichever read the render snapshot would undo the other.
|
||||
const replaceFilters = useCallback<WorkspaceCleanupBrowseController['replaceFilters']>(
|
||||
(transform) => {
|
||||
updateBrowse((current) => ({ ...current, filters: transform(current.filters) }))
|
||||
},
|
||||
[updateBrowse]
|
||||
)
|
||||
|
||||
const clearFilters = useCallback(() => {
|
||||
updateBrowse((current) => ({
|
||||
...current,
|
||||
@@ -68,6 +81,7 @@ export function useWorkspaceCleanupBrowseState(): WorkspaceCleanupBrowseControll
|
||||
sort: browse.sort,
|
||||
patchFilters,
|
||||
toggleSortField,
|
||||
clearFilters
|
||||
clearFilters,
|
||||
replaceFilters
|
||||
}
|
||||
}
|
||||
|
||||
+180
@@ -0,0 +1,180 @@
|
||||
import React from 'react'
|
||||
import { X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { toMegabytes } from './workspace-cleanup-facet-panel-model'
|
||||
import type { WorkspaceCleanupAppliedFilter } from '../../../../shared/workspace-cleanup-applied-filters'
|
||||
import { listAppliedWorkspaceCleanupFilters } from '../../../../shared/workspace-cleanup-applied-filters'
|
||||
import type { WorkspaceCleanupFilterState } from '../../../../shared/workspace-cleanup-filter-model'
|
||||
|
||||
/** Why in the bar, not the panel: a filter narrowing the list must be visible without opening anything. */
|
||||
// Why not memoized: the labels are translated at build time, so caching them on
|
||||
// `filters` alone reuses the previous language's strings after a language change.
|
||||
// Derivation is constant-size (one pass over the filter fields, not per row).
|
||||
export function useAppliedWorkspaceCleanupFilters(
|
||||
filters: WorkspaceCleanupFilterState
|
||||
): WorkspaceCleanupAppliedFilter[] {
|
||||
return listAppliedWorkspaceCleanupFilters(filters, buildAppliedFilterFormatters())
|
||||
}
|
||||
|
||||
export function WorkspaceCleanupAppliedFilterChips({
|
||||
applied,
|
||||
onClear
|
||||
}: {
|
||||
applied: readonly WorkspaceCleanupAppliedFilter[]
|
||||
onClear: (filter: WorkspaceCleanupAppliedFilter) => void
|
||||
}): React.JSX.Element | null {
|
||||
if (applied.length === 0) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<div
|
||||
className="flex w-full flex-wrap items-center gap-1"
|
||||
role="list"
|
||||
aria-label={translate(
|
||||
'components.workspace.cleanup.browse.appliedFilters',
|
||||
'Applied filters'
|
||||
)}
|
||||
>
|
||||
{applied.map((filter) => (
|
||||
<span
|
||||
key={filter.id}
|
||||
role="listitem"
|
||||
className="inline-flex items-center gap-1 rounded-full border border-border bg-background py-0.5 pl-2 pr-1 text-[11px] text-muted-foreground"
|
||||
>
|
||||
{filter.label}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-xs"
|
||||
className="rounded-full"
|
||||
aria-label={translate(
|
||||
'components.workspace.cleanup.browse.removeFilter',
|
||||
'Remove filter {{value0}}',
|
||||
{ value0: filter.label }
|
||||
)}
|
||||
onClick={() => onClear(filter)}
|
||||
>
|
||||
<X className="size-3" />
|
||||
</Button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function buildAppliedFilterFormatters(): Parameters<typeof listAppliedWorkspaceCleanupFilters>[1] {
|
||||
const mb = (bytes: number): number => toMegabytes(bytes) ?? 0
|
||||
return {
|
||||
idleDays: (days) =>
|
||||
translate('components.workspace.cleanup.browse.chip.idleDays', 'Idle {{value0}}d+', {
|
||||
value0: days
|
||||
}),
|
||||
neverVisited: () =>
|
||||
translate('components.workspace.cleanup.browse.chip.neverVisited', 'Never visited'),
|
||||
minSize: (bytes) =>
|
||||
translate('components.workspace.cleanup.browse.chip.minSize', 'At least {{value0}} MB', {
|
||||
value0: mb(bytes)
|
||||
}),
|
||||
maxSize: (bytes) =>
|
||||
translate('components.workspace.cleanup.browse.chip.maxSize', 'At most {{value0}} MB', {
|
||||
value0: mb(bytes)
|
||||
}),
|
||||
excludesUnsized: () =>
|
||||
translate('components.workspace.cleanup.browse.chip.excludesUnsized', 'Measured only'),
|
||||
excludesStatusless: () =>
|
||||
translate('components.workspace.cleanup.browse.chip.excludesStatusless', 'Has a status'),
|
||||
list: (kind, count) =>
|
||||
translate('components.workspace.cleanup.browse.chip.list', '{{value0}}: {{value1}}', {
|
||||
value0: getChipKindLabel(kind),
|
||||
value1: count
|
||||
}),
|
||||
triState: (kind, mode) =>
|
||||
translate('components.workspace.cleanup.browse.chip.triState', '{{value0}}: {{value1}}', {
|
||||
value0: getChipKindLabel(kind),
|
||||
value1:
|
||||
mode === 'only'
|
||||
? translate('components.workspace.cleanup.browse.chip.only', 'Only')
|
||||
: translate('components.workspace.cleanup.browse.chip.exclude', 'Excluded')
|
||||
}),
|
||||
minAhead: (count) =>
|
||||
translate('components.workspace.cleanup.browse.chip.minAhead', 'Ahead {{value0}}+', {
|
||||
value0: count
|
||||
}),
|
||||
minBehind: (count) =>
|
||||
translate('components.workspace.cleanup.browse.chip.minBehind', 'Behind {{value0}}+', {
|
||||
value0: count
|
||||
}),
|
||||
branchQuery: (value) =>
|
||||
translate('components.workspace.cleanup.browse.chip.branchQuery', 'Branch: {{value0}}', {
|
||||
value0: value
|
||||
}),
|
||||
pathPrefix: (value) =>
|
||||
translate('components.workspace.cleanup.browse.chip.pathPrefix', 'Path: {{value0}}', {
|
||||
value0: value
|
||||
}),
|
||||
presence: (kind, mode) =>
|
||||
translate('components.workspace.cleanup.browse.chip.presence', '{{value0}}: {{value1}}', {
|
||||
value0: getChipKindLabel(kind),
|
||||
value1:
|
||||
mode === 'some'
|
||||
? translate('components.workspace.cleanup.browse.chip.has', 'Has')
|
||||
: translate('components.workspace.cleanup.browse.chip.none', 'None')
|
||||
}),
|
||||
completelyEmpty: () =>
|
||||
translate('components.workspace.cleanup.browse.chip.completelyEmpty', 'Nothing to lose'),
|
||||
selectableOnly: () =>
|
||||
translate('components.workspace.cleanup.browse.chip.selectableOnly', 'Deletable only')
|
||||
}
|
||||
}
|
||||
|
||||
function getChipKindLabel(kind: string): string {
|
||||
switch (kind) {
|
||||
case 'status':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.status', 'Status')
|
||||
case 'agent':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.agent', 'Agent')
|
||||
case 'git':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.git', 'Git')
|
||||
case 'review':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.review', 'Review')
|
||||
case 'reviewState':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.reviewState', 'Review state')
|
||||
case 'reviewProvider':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.reviewProvider', 'Provider')
|
||||
case 'ticket':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.ticket', 'Ticket')
|
||||
case 'ticketSource':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.ticketSource', 'Ticket source')
|
||||
case 'context':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.context', 'Context')
|
||||
case 'host':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.host', 'Host')
|
||||
case 'repo':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.repo', 'Repo')
|
||||
case 'blocker':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.blocker', 'Blocker')
|
||||
case 'tier':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.tier', 'Safety')
|
||||
case 'dismissed':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.dismissed', 'Ignored')
|
||||
case 'archived':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.archived', 'Archived')
|
||||
case 'pinned':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.pinned', 'Pinned')
|
||||
case 'unread':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.unread', 'Unread')
|
||||
case 'comment':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.comment', 'Comment')
|
||||
case 'prunable':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.prunable', 'Prunable')
|
||||
case 'locked':
|
||||
return translate('components.workspace.cleanup.browse.chip.kind.locked', 'Locked')
|
||||
case 'retainedAgents':
|
||||
return translate(
|
||||
'components.workspace.cleanup.browse.chip.kind.retainedAgents',
|
||||
'Finished agents'
|
||||
)
|
||||
default:
|
||||
return kind
|
||||
}
|
||||
}
|
||||
@@ -71,6 +71,7 @@ export function WorkspaceCleanupBrowseToolbar({
|
||||
gitEvidence={{ pendingCount: gitPendingCount, totalCount: gitCheckedTotal }}
|
||||
onQueryChange={(query) => browse.patchFilters('query', query)}
|
||||
onClearFilters={browse.clearFilters}
|
||||
onClearAppliedFilter={(filter) => browse.replaceFilters(filter.clear)}
|
||||
/>
|
||||
<WorkspaceCleanupSortHeader
|
||||
sort={browse.sort}
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
getWorkspaceCleanupCandidateIdentity,
|
||||
getWorkspaceCleanupHostIdentity
|
||||
} from './workspace-cleanup-host-identity'
|
||||
import { getWorktreeVisitTimestamp } from '@/lib/worktree-visit-recency'
|
||||
|
||||
/**
|
||||
* Streaming ticks replace only the candidate objects they touched, so all
|
||||
@@ -105,7 +106,10 @@ export function computeWorkspaceCleanupFacetList(args: {
|
||||
const sizeBytes =
|
||||
sources.sizeBytesByWorktreeId.get(hostIdentity) ??
|
||||
sources.sizeBytesByWorktreeId.get(candidate.worktreeId)
|
||||
const lastVisitedAt = sources.lastVisitedAtByWorktreeId[candidate.worktreeId]
|
||||
const lastVisitedAt = getWorktreeVisitTimestamp(sources.lastVisitedAtByWorktreeId, {
|
||||
id: candidate.worktreeId,
|
||||
hostId: getWorkspaceCleanupCandidateHostId(candidate)
|
||||
})
|
||||
const agentState = sources.liveAgentStatusByWorktreeId.get(candidate.worktreeId)
|
||||
const review =
|
||||
sources.reviewInfoByWorktreeId.get(hostIdentity) ??
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
getWorkspaceCleanupHostIdentity,
|
||||
type WorkspaceCleanupWorktreeFacts
|
||||
} from './workspace-cleanup-host-identity'
|
||||
import { getWorktreeVisitTimestamp } from '@/lib/worktree-visit-recency'
|
||||
export type { WorkspaceCleanupWorktreeFacts } from './workspace-cleanup-host-identity'
|
||||
|
||||
export type WorkspaceCleanupFacetSources = {
|
||||
@@ -128,7 +129,12 @@ export function buildWorkspaceCleanupFacets(
|
||||
isSelectable: canSelectWorkspaceCleanupCandidate(candidate),
|
||||
lastActivityAt: candidate.lastActivityAt,
|
||||
createdAt: toFiniteOrNull(worktree?.createdAt ?? candidate.createdAt),
|
||||
lastVisitedAt: toFiniteOrNull(sources.lastVisitedAtByWorktreeId?.[candidate.worktreeId]),
|
||||
lastVisitedAt: toFiniteOrNull(
|
||||
getWorktreeVisitTimestamp(sources.lastVisitedAtByWorktreeId, {
|
||||
id: candidate.worktreeId,
|
||||
hostId: worktree?.hostId ?? getWorkspaceCleanupCandidateHostId(candidate)
|
||||
})
|
||||
),
|
||||
sizeBytes: toFiniteOrNull(
|
||||
sources.sizeBytesByWorktreeId?.get(hostIdentity) ??
|
||||
sources.sizeBytesByWorktreeId?.get(candidate.worktreeId)
|
||||
|
||||
+49
-4
@@ -2,15 +2,24 @@
|
||||
import { cleanup, render, screen } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createDefaultWorkspaceCleanupFilterState } from '../../../../shared/workspace-cleanup-filter-model'
|
||||
import type { WorkspaceCleanupAppliedFilter } from '../../../../shared/workspace-cleanup-applied-filters'
|
||||
import { WorkspaceCleanupFilterBar } from './workspace-cleanup-filter-bar'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
function renderFilterBar(facetPanelOpen = false): void {
|
||||
function renderFilterBar(
|
||||
facetPanelOpen = false,
|
||||
overrides: {
|
||||
filters?: ReturnType<typeof createDefaultWorkspaceCleanupFilterState>
|
||||
hasActiveFilters?: boolean
|
||||
onClearAppliedFilter?: (filter: WorkspaceCleanupAppliedFilter) => void
|
||||
onClearFilters?: () => void
|
||||
} = {}
|
||||
): void {
|
||||
render(
|
||||
<WorkspaceCleanupFilterBar
|
||||
facetProps={{
|
||||
filters: createDefaultWorkspaceCleanupFilterState(),
|
||||
filters: overrides.filters ?? createDefaultWorkspaceCleanupFilterState(),
|
||||
counts: {
|
||||
activity: 0,
|
||||
size: 0,
|
||||
@@ -31,10 +40,11 @@ function renderFilterBar(facetPanelOpen = false): void {
|
||||
onFacetPanelOpenChange={vi.fn()}
|
||||
activeFacetGroupCount={0}
|
||||
matchedCount={100}
|
||||
hasActiveFilters={false}
|
||||
hasActiveFilters={overrides.hasActiveFilters ?? false}
|
||||
gitEvidence={{ pendingCount: 0, totalCount: 0 }}
|
||||
onQueryChange={vi.fn()}
|
||||
onClearFilters={vi.fn()}
|
||||
onClearFilters={overrides.onClearFilters ?? vi.fn()}
|
||||
onClearAppliedFilter={overrides.onClearAppliedFilter ?? vi.fn()}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -46,6 +56,41 @@ describe('WorkspaceCleanupFilterBar', () => {
|
||||
expect(screen.queryByRole('button', { name: 'Scan' })).toBeNull()
|
||||
})
|
||||
|
||||
it('names an applied filter in the bar without opening the panel', () => {
|
||||
// The reported defect: a persisted idleMinDays the user never set. The bar already
|
||||
// read "Showing N of M", so only the cause was hidden.
|
||||
const filters = createDefaultWorkspaceCleanupFilterState()
|
||||
filters.activity.idleMinDays = 20
|
||||
renderFilterBar(false, { filters, hasActiveFilters: true })
|
||||
|
||||
expect(screen.getByRole('listitem').textContent).toContain('Idle 20d+')
|
||||
})
|
||||
|
||||
it('clears one named filter from its chip', () => {
|
||||
const filters = createDefaultWorkspaceCleanupFilterState()
|
||||
filters.activity.idleMinDays = 20
|
||||
const onClearAppliedFilter = vi.fn()
|
||||
renderFilterBar(false, { filters, hasActiveFilters: true, onClearAppliedFilter })
|
||||
|
||||
screen.getByRole('button', { name: 'Remove filter Idle 20d+' }).click()
|
||||
|
||||
expect(onClearAppliedFilter).toHaveBeenCalledTimes(1)
|
||||
expect(onClearAppliedFilter.mock.calls[0][0].id).toBe('activity.idleMinDays')
|
||||
})
|
||||
|
||||
it('offers Clear filters in the bar, not only inside the panel', () => {
|
||||
renderFilterBar(false, { hasActiveFilters: true })
|
||||
|
||||
expect(screen.getAllByRole('button', { name: /Clear filters/ }).length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('shows no chips and no Clear for a default profile', () => {
|
||||
renderFilterBar()
|
||||
|
||||
expect(screen.queryAllByRole('listitem')).toHaveLength(0)
|
||||
expect(screen.queryByRole('button', { name: /Clear filters/ })).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps the footer visible while the facet panel scrolls', () => {
|
||||
renderFilterBar(true)
|
||||
|
||||
|
||||
@@ -5,6 +5,11 @@ import { Input } from '@/components/ui/input'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import {
|
||||
useAppliedWorkspaceCleanupFilters,
|
||||
WorkspaceCleanupAppliedFilterChips
|
||||
} from './workspace-cleanup-applied-filter-chips'
|
||||
import type { WorkspaceCleanupAppliedFilter } from '../../../../shared/workspace-cleanup-applied-filters'
|
||||
import { WorkspaceCleanupGitReviewFacets } from './workspace-cleanup-git-review-facets'
|
||||
import { WorkspaceCleanupLifecycleFacets } from './workspace-cleanup-lifecycle-facets'
|
||||
import type { WorkspaceCleanupFacetGroupProps } from './workspace-cleanup-facet-panel-model'
|
||||
@@ -23,7 +28,8 @@ export function WorkspaceCleanupFilterBar({
|
||||
hasActiveFilters,
|
||||
gitEvidence,
|
||||
onQueryChange,
|
||||
onClearFilters
|
||||
onClearFilters,
|
||||
onClearAppliedFilter
|
||||
}: {
|
||||
facetProps: WorkspaceCleanupFacetGroupProps
|
||||
facetPanelOpen: boolean
|
||||
@@ -34,8 +40,10 @@ export function WorkspaceCleanupFilterBar({
|
||||
gitEvidence: WorkspaceCleanupGitEvidenceProgress
|
||||
onQueryChange: (query: string) => void
|
||||
onClearFilters: () => void
|
||||
onClearAppliedFilter: (filter: WorkspaceCleanupAppliedFilter) => void
|
||||
}): React.JSX.Element {
|
||||
const { filters, totalCount } = facetProps
|
||||
const applied = useAppliedWorkspaceCleanupFilters(filters)
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2 border-b border-border bg-muted/15 px-3 py-2">
|
||||
<div className="relative min-w-[180px] flex-1">
|
||||
@@ -106,6 +114,15 @@ export function WorkspaceCleanupFilterBar({
|
||||
)}
|
||||
</span>
|
||||
|
||||
{/* Why out here and not only in the popover: a filter narrowing the list must be
|
||||
clearable without first discovering which panel it lives in. */}
|
||||
{hasActiveFilters ? (
|
||||
<Button variant="ghost" size="sm" className="shrink-0" onClick={onClearFilters}>
|
||||
<RotateCcw className="size-3.5" />
|
||||
{translate('components.workspace.cleanup.browse.clearFilters', 'Clear filters')}
|
||||
</Button>
|
||||
) : null}
|
||||
|
||||
{gitEvidence.pendingCount > 0 ? (
|
||||
<span className="flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<Loader2 className="size-3.5 animate-spin" />
|
||||
@@ -116,6 +133,8 @@ export function WorkspaceCleanupFilterBar({
|
||||
)}
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
<WorkspaceCleanupAppliedFilterChips applied={applied} onClear={onClearAppliedFilter} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -136,6 +136,36 @@ export function makeRecentTabState(overrides: Partial<AppState> = {}): Partial<A
|
||||
}
|
||||
}
|
||||
|
||||
/** Two host-qualified worktrees intentionally publish the same unified tab id. */
|
||||
export function makeDuplicateRecentTabState(): Partial<AppState> {
|
||||
const alpha = makeWorktree('wt-alpha', 'Alpha workspace', { hostId: 'ssh:alpha' })
|
||||
const beta = makeWorktree('wt-beta', 'Beta workspace', { hostId: 'ssh:beta' })
|
||||
return {
|
||||
worktreesByRepo: { 'repo-1': [alpha, beta] },
|
||||
showSleepingWorkspaces: true,
|
||||
ptyIdsByTabId: {
|
||||
'term-alpha': ['pty-term-alpha'],
|
||||
'term-beta': ['pty-term-beta']
|
||||
},
|
||||
tabsByWorktree: {
|
||||
'wt-alpha': [makeTerminalTab('term-alpha', 'wt-alpha', 'Alpha duplicate')],
|
||||
'wt-beta': [makeTerminalTab('term-beta', 'wt-beta', 'Beta duplicate')]
|
||||
},
|
||||
unifiedTabsByWorktree: {
|
||||
'wt-alpha': [makeUnifiedTab('tab-duplicate', 'wt-alpha', 'term-alpha', 'Alpha duplicate')],
|
||||
'wt-beta': [makeUnifiedTab('tab-duplicate', 'wt-beta', 'term-beta', 'Beta duplicate')]
|
||||
},
|
||||
groupsByWorktree: {
|
||||
'wt-alpha': [makeGroup('wt-alpha', ['tab-duplicate'])],
|
||||
'wt-beta': [makeGroup('wt-beta', ['tab-duplicate'])]
|
||||
},
|
||||
activeGroupIdByWorktree: {
|
||||
'wt-alpha': 'group-wt-alpha',
|
||||
'wt-beta': 'group-wt-beta'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One tab-heavy worktree plus `count` bare ones, so both sections overflow their caps. */
|
||||
export function makeManyTabState(count: number): Partial<AppState> {
|
||||
const ids = Array.from({ length: count }, (_, index) => `${index}`)
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import type { TerminalTab } from '../../../shared/terminal-tab-types'
|
||||
import type { WorkspaceSessionState } from '../../../shared/workspace-session-state-types'
|
||||
import type { ExecutionHostId } from '../../../shared/execution-host'
|
||||
import { worktreeWorkspaceKey } from '../../../shared/workspace-scope'
|
||||
import { splitWorktreeId } from '../../../shared/worktree/id'
|
||||
import {
|
||||
getWorktreeIdFromHostIdentity,
|
||||
isWorktreeHostIdentity
|
||||
} from '../../../shared/worktree/host-qualified-identity'
|
||||
import type { AppState } from '../store/types'
|
||||
|
||||
function preserveNewerLocalTerminalFields(remote: TerminalTab, local: TerminalTab): TerminalTab {
|
||||
@@ -20,7 +25,8 @@ export function mergeDirectSshRemoteWorkspaceSession(
|
||||
remote: WorkspaceSessionState,
|
||||
replaceWorktreeIds: ReadonlySet<string>,
|
||||
liveTabsByWorktree: AppState['tabsByWorktree'],
|
||||
preserveLocalTerminalTabIds: ReadonlySet<string>
|
||||
preserveLocalTerminalTabIds: ReadonlySet<string>,
|
||||
replaceExecutionHostId?: ExecutionHostId
|
||||
): WorkspaceSessionState {
|
||||
const currentTabsById = new Map(
|
||||
[...replaceWorktreeIds]
|
||||
@@ -146,6 +152,25 @@ export function mergeDirectSshRemoteWorkspaceSession(
|
||||
Object.fromEntries(
|
||||
Object.entries(record ?? {}).filter(([worktreeId]) => !replaceWorktreeIds.has(worktreeId))
|
||||
)
|
||||
const omitTargetVisitRecency = (
|
||||
record: Record<string, number> | undefined
|
||||
): Record<string, number> =>
|
||||
Object.fromEntries(
|
||||
Object.entries(record ?? {}).filter(([key]) => {
|
||||
const worktreeId = isWorktreeHostIdentity(key) ? getWorktreeIdFromHostIdentity(key) : key
|
||||
if (!replaceWorktreeIds.has(worktreeId)) {
|
||||
return true
|
||||
}
|
||||
// A direct SSH snapshot replaces one host's row. Legacy bare keys
|
||||
// remain because they may be the only recency evidence for a sibling
|
||||
// host; a qualified key is removed only for the target host.
|
||||
return Boolean(
|
||||
replaceExecutionHostId &&
|
||||
(!isWorktreeHostIdentity(key) ||
|
||||
key.slice(0, key.indexOf('|')) !== replaceExecutionHostId)
|
||||
)
|
||||
})
|
||||
)
|
||||
const terminalLayoutsByTabId = {
|
||||
...Object.fromEntries(
|
||||
Object.entries(current.terminalLayoutsByTabId).filter(
|
||||
@@ -226,7 +251,7 @@ export function mergeDirectSshRemoteWorkspaceSession(
|
||||
)
|
||||
},
|
||||
lastVisitedAtByWorktreeId: {
|
||||
...omitTargetWorktrees(current.lastVisitedAtByWorktreeId),
|
||||
...omitTargetVisitRecency(current.lastVisitedAtByWorktreeId),
|
||||
...remote.lastVisitedAtByWorktreeId
|
||||
},
|
||||
defaultTerminalTabsAppliedByWorktreeId: {
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { StoreApi } from 'zustand'
|
||||
import type { RemoteWorkspaceSnapshot } from '../../../shared/remote-workspace-types'
|
||||
import { importRemoteWorkspaceSession } from '../../../shared/remote-workspace-session-projection'
|
||||
import type { DirectSshAuthority } from '../../../shared/ssh-types'
|
||||
import { toSshExecutionHostId } from '../../../shared/execution-host'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { buildWorkspaceSessionPayload } from '../lib/workspace-session'
|
||||
import { resolveDirectSshTargetScope } from '../lib/direct-ssh-target-scope'
|
||||
@@ -109,14 +110,16 @@ export async function applyDirectSshRemoteWorkspaceSnapshot({
|
||||
const state = store.getState()
|
||||
const worktreeIds = exactTargetWorktreeIds(state, authority)
|
||||
const remoteSession = importRemoteWorkspaceSession(snapshot.session, {
|
||||
resolveWorktreeId: uniqueWorktreeIdByPath(worktreeIds)
|
||||
resolveWorktreeId: uniqueWorktreeIdByPath(worktreeIds),
|
||||
executionHostId: toSshExecutionHostId(authority.targetId)
|
||||
})
|
||||
const merged = mergeDirectSshRemoteWorkspaceSession(
|
||||
buildWorkspaceSessionPayload(state),
|
||||
remoteSession,
|
||||
worktreeIds,
|
||||
state.tabsByWorktree,
|
||||
currentRecoveryTabIds(state, authority, worktreeIds)
|
||||
currentRecoveryTabIds(state, authority, worktreeIds),
|
||||
toSshExecutionHostId(authority.targetId)
|
||||
)
|
||||
if (!isArrivalCurrent(authority.targetId, arrival) || !isPreparationTokenCurrent(token)) {
|
||||
return
|
||||
|
||||
@@ -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'
|
||||
@@ -924,7 +924,12 @@ export function useIpcEvents(): void {
|
||||
`[worktree-purge] diff-based purge removing state for ${removed.length} worktree(s):`,
|
||||
removed
|
||||
)
|
||||
afterState.purgeWorktreeTerminalState(removed)
|
||||
const purgeHostId =
|
||||
options?.executionHostId ??
|
||||
(options?.forceLocalOwner ? LOCAL_EXECUTION_HOST_ID : undefined)
|
||||
afterState.purgeWorktreeTerminalState(
|
||||
purgeHostId ? removed.map((id) => ({ id, hostId: purgeHostId })) : removed
|
||||
)
|
||||
afterState.removeWorkspaceSpaceWorktrees(removed)
|
||||
}
|
||||
}
|
||||
@@ -1426,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())
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
@@ -15008,6 +15008,10 @@
|
||||
"0e1de0358b": "Month",
|
||||
"77e96bded6": "Weekday"
|
||||
},
|
||||
"AutomationPromptDisclosure": {
|
||||
"showLess": "Show less",
|
||||
"showMore": "Show more"
|
||||
},
|
||||
"AutomationDetail": {
|
||||
"007c8ad874": "Prompt",
|
||||
"a1d52c2189": "Usage coverage",
|
||||
@@ -16230,7 +16234,53 @@
|
||||
"selectionWithheldOne": "1 selected workspace is hidden by the current filters and was deselected.",
|
||||
"selectionWithheld": "{{value0}} selected workspaces are hidden by the current filters and were deselected.",
|
||||
"selectAllCountOne": "Select 1 safety-checked workspace",
|
||||
"selectAllCount": "Select all {{value0}} safety-checked workspaces"
|
||||
"selectAllCount": "Select all {{value0}} safety-checked workspaces",
|
||||
"appliedFilters": "Applied filters",
|
||||
"removeFilter": "Remove filter {{value0}}",
|
||||
"chip": {
|
||||
"idleDays": "Idle {{value0}}d+",
|
||||
"neverVisited": "Never visited",
|
||||
"minSize": "At least {{value0}} MB",
|
||||
"maxSize": "At most {{value0}} MB",
|
||||
"excludesUnsized": "Measured only",
|
||||
"excludesStatusless": "Has a status",
|
||||
"list": "{{value0}}: {{value1}}",
|
||||
"triState": "{{value0}}: {{value1}}",
|
||||
"only": "Only",
|
||||
"exclude": "Excluded",
|
||||
"minAhead": "Ahead {{value0}}+",
|
||||
"minBehind": "Behind {{value0}}+",
|
||||
"branchQuery": "Branch: {{value0}}",
|
||||
"pathPrefix": "Path: {{value0}}",
|
||||
"presence": "{{value0}}: {{value1}}",
|
||||
"has": "Has",
|
||||
"none": "None",
|
||||
"completelyEmpty": "Nothing to lose",
|
||||
"selectableOnly": "Deletable only",
|
||||
"kind": {
|
||||
"status": "Status",
|
||||
"agent": "Agent",
|
||||
"git": "Git",
|
||||
"review": "Review",
|
||||
"reviewState": "Review state",
|
||||
"reviewProvider": "Provider",
|
||||
"ticket": "Ticket",
|
||||
"ticketSource": "Ticket source",
|
||||
"context": "Context",
|
||||
"host": "Host",
|
||||
"repo": "Repo",
|
||||
"blocker": "Blocker",
|
||||
"tier": "Safety",
|
||||
"dismissed": "Ignored",
|
||||
"archived": "Archived",
|
||||
"pinned": "Pinned",
|
||||
"unread": "Unread",
|
||||
"comment": "Comment",
|
||||
"prunable": "Prunable",
|
||||
"locked": "Locked",
|
||||
"retainedAgents": "Finished agents"
|
||||
}
|
||||
}
|
||||
},
|
||||
"scan": {
|
||||
"progress": "Scanning workspaces ({{value0}}/{{value1}})",
|
||||
|
||||
@@ -13612,6 +13612,10 @@
|
||||
"0e1de0358b": "Mes",
|
||||
"77e96bded6": "Día de la semana"
|
||||
},
|
||||
"AutomationPromptDisclosure": {
|
||||
"showLess": "Mostrar menos",
|
||||
"showMore": "Mostrar más"
|
||||
},
|
||||
"AutomationDetail": {
|
||||
"007c8ad874": "Inmediato",
|
||||
"a1d52c2189": "Cobertura de uso",
|
||||
|
||||
@@ -13612,6 +13612,10 @@
|
||||
"0e1de0358b": "月",
|
||||
"77e96bded6": "曜日"
|
||||
},
|
||||
"AutomationPromptDisclosure": {
|
||||
"showLess": "折りたたむ",
|
||||
"showMore": "さらに表示"
|
||||
},
|
||||
"AutomationDetail": {
|
||||
"007c8ad874": "プロンプト",
|
||||
"a1d52c2189": "使用範囲",
|
||||
|
||||
@@ -13641,6 +13641,10 @@
|
||||
"0e1de0358b": "월",
|
||||
"77e96bded6": "요일"
|
||||
},
|
||||
"AutomationPromptDisclosure": {
|
||||
"showLess": "접기",
|
||||
"showMore": "더 보기"
|
||||
},
|
||||
"AutomationDetail": {
|
||||
"007c8ad874": "프롬프트",
|
||||
"a1d52c2189": "사용 범위",
|
||||
@@ -14562,6 +14566,54 @@
|
||||
"presentation": {
|
||||
"gitlabMergeRequestNumber": "MR #{{value0}}",
|
||||
"githubPullRequestNumber": "PR #{{value0}}"
|
||||
},
|
||||
"browse": {
|
||||
"appliedFilters": "적용된 필터",
|
||||
"removeFilter": "{{value0}} 필터 제거",
|
||||
"chip": {
|
||||
"idleDays": "{{value0}}일 이상 유휴",
|
||||
"neverVisited": "방문한 적 없음",
|
||||
"minSize": "{{value0}} MB 이상",
|
||||
"maxSize": "{{value0}} MB 이하",
|
||||
"excludesUnsized": "측정된 항목만",
|
||||
"excludesStatusless": "상태 있음",
|
||||
"list": "{{value0}}: {{value1}}",
|
||||
"triState": "{{value0}}: {{value1}}",
|
||||
"only": "만",
|
||||
"exclude": "제외",
|
||||
"minAhead": "{{value0}}개 이상 앞섬",
|
||||
"minBehind": "{{value0}}개 이상 뒤처짐",
|
||||
"branchQuery": "브랜치: {{value0}}",
|
||||
"pathPrefix": "경로: {{value0}}",
|
||||
"presence": "{{value0}}: {{value1}}",
|
||||
"has": "있음",
|
||||
"none": "없음",
|
||||
"completelyEmpty": "잃을 것 없음",
|
||||
"selectableOnly": "삭제 가능한 항목만",
|
||||
"kind": {
|
||||
"status": "상태",
|
||||
"agent": "에이전트",
|
||||
"git": "Git",
|
||||
"review": "리뷰",
|
||||
"reviewState": "리뷰 상태",
|
||||
"reviewProvider": "제공자",
|
||||
"ticket": "티켓",
|
||||
"ticketSource": "티켓 소스",
|
||||
"context": "컨텍스트",
|
||||
"host": "호스트",
|
||||
"repo": "저장소",
|
||||
"blocker": "차단 요인",
|
||||
"tier": "안전",
|
||||
"dismissed": "무시됨",
|
||||
"archived": "보관됨",
|
||||
"pinned": "고정됨",
|
||||
"unread": "읽지 않음",
|
||||
"comment": "댓글",
|
||||
"prunable": "정리 가능",
|
||||
"locked": "잠김",
|
||||
"retainedAgents": "완료된 에이전트"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user