mirror of
https://github.com/stablyai/orca.git
synced 2026-10-23 16:03:49 +00:00
Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts: # config/max-lines-baseline.txt
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
|
||||
}
|
||||
|
||||
@@ -642,6 +642,7 @@ jobs:
|
||||
- name: Test Windows-specific boundaries
|
||||
run: >-
|
||||
pnpm exec vitest run --config config/vitest.config.ts
|
||||
config/scripts/rebuild-native-deps.test.mjs
|
||||
src/main/providers/windows-conpty-wide-char-duplication.node-pty.test.ts
|
||||
src/main/providers/pty-repaint-wide-char-buffer.node-pty.test.ts
|
||||
src/shared/child-process/windows-command-line.win32.test.ts
|
||||
@@ -658,6 +659,8 @@ jobs:
|
||||
src/main/runtime/repo-worktree-admin-fingerprint.test.ts
|
||||
src/main/runtime/worktree-scan-admin-fingerprint-gate.test.ts
|
||||
src/shared/secure-file-fsync-flags.test.ts
|
||||
src/main/ipc/pty-codex-account-attribution.test.ts
|
||||
src/main/ipc/pty-spawn-env-codex-resume-provenance.test.ts
|
||||
|
||||
# Why the :parallel variant: identical to build:release except the three
|
||||
# electron-vite targets overlap instead of running back to back. The Linux package
|
||||
@@ -673,6 +676,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 +713,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"
|
||||
|
||||
@@ -14,6 +14,9 @@ const {
|
||||
const { verifyLinuxGlibcFloor } = require('./scripts/verify-linux-glibc-floor.cjs')
|
||||
const { writeMacBuildCompatibility } = require('./scripts/mac-build-compatibility.cjs')
|
||||
const { verifyPackagedPluginResources } = require('./scripts/verify-packaged-plugin-resources.cjs')
|
||||
const {
|
||||
verifyPackagedNodePtyJobOwnership
|
||||
} = require('./scripts/verify-packaged-node-pty-job-ownership.cjs')
|
||||
const { verifySkillsCliRuntime } = require('./scripts/verify-skills-cli-runtime.cjs')
|
||||
|
||||
// Why: dev-channel builds must carry the *release* identity — same bundle id,
|
||||
@@ -266,6 +269,13 @@ module.exports = {
|
||||
const archEnumByNodeArch = { ia32: 0, x64: 1, armv7l: 2, arm64: 3 }
|
||||
const hostArchEnum = archEnumByNodeArch[process.arch]
|
||||
const canExecuteTargetArch = context.arch === hostArchEnum || context.arch === 4
|
||||
if (context.electronPlatformName === 'win32') {
|
||||
if (process.platform === 'win32' && canExecuteTargetArch) {
|
||||
verifyPackagedNodePtyJobOwnership(resourcesDir)
|
||||
} else {
|
||||
console.log('[verify-packaged-node-pty] skipped cross-platform or cross-arch package')
|
||||
}
|
||||
}
|
||||
verifySkillsCliRuntime(join(resourcesDir, 'app.asar.unpacked', 'out'), resourcesDir, {
|
||||
executeCommands: canExecuteTargetArch
|
||||
})
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
# split the oversized file instead (AGENTS.md → "Do Not Disable Max Lines").
|
||||
# Regenerate/prune: pnpm check:max-lines-ratchet --prune (removes stale entries only)
|
||||
inline src/cli/handlers/automations.ts
|
||||
inline src/cli/handlers/orchestration.ts
|
||||
inline src/cli/help.ts
|
||||
inline src/main/agent-hooks/server.ts
|
||||
inline src/main/automations/external-manager.ts
|
||||
@@ -33,19 +32,15 @@ inline src/main/github/pr-refresh-coordinator.ts
|
||||
inline src/main/github/project-view.ts
|
||||
inline src/main/github/project-view/mutations.ts
|
||||
inline src/main/github/work-item-details.ts
|
||||
inline src/main/gitlab/client.ts
|
||||
inline src/main/index.ts
|
||||
inline src/main/ipc/filesystem-watcher.ts
|
||||
inline src/main/ipc/filesystem.ts
|
||||
inline src/main/ipc/github.ts
|
||||
inline src/main/ipc/pty.ts
|
||||
inline src/main/ipc/repos.ts
|
||||
inline src/main/ipc/ssh.ts
|
||||
inline src/main/ipc/worktree-remote.ts
|
||||
inline src/main/jira/issues.ts
|
||||
inline src/main/keybindings/keybinding-file.ts
|
||||
inline src/main/linear/issues.ts
|
||||
inline src/main/linear/projects.ts
|
||||
inline src/main/memory/collector.ts
|
||||
inline src/main/opencode/hook-service.ts
|
||||
inline src/main/persistence/loading-store/store.ts
|
||||
@@ -64,7 +59,6 @@ inline src/main/runtime/orca-runtime-git.ts
|
||||
inline src/main/runtime/orca-runtime.test.ts
|
||||
inline src/main/runtime/orca-runtime.ts
|
||||
inline src/main/runtime/rpc/methods/orchestration.ts
|
||||
inline src/main/runtime/rpc/methods/terminal.ts
|
||||
inline src/main/runtime/runtime-rpc.ts
|
||||
inline src/main/source-control/hosted-review-creation.ts
|
||||
inline src/main/speech/model-manager.ts
|
||||
@@ -147,7 +141,6 @@ inline src/renderer/src/runtime/web-session-tabs-sync.ts
|
||||
inline src/renderer/src/store/slices/agent-status.ts
|
||||
inline src/renderer/src/store/slices/browser.ts
|
||||
inline src/renderer/src/store/slices/diffComments.ts
|
||||
inline src/renderer/src/store/slices/github.ts
|
||||
inline src/renderer/src/store/slices/hosted-review.ts
|
||||
inline src/renderer/src/store/slices/jira.ts
|
||||
inline src/renderer/src/store/slices/linear.ts
|
||||
|
||||
@@ -2,7 +2,12 @@ diff --git a/binding.gyp b/binding.gyp
|
||||
index 5f63978b07ab50aaf7523219a2170ec737a6b5db..bbd9e06136e8922f40b5779e35d4fc835f1479ab 100644
|
||||
--- a/binding.gyp
|
||||
+++ b/binding.gyp
|
||||
@@ -5,9 +5,6 @@
|
||||
@@ -1,13 +1,10 @@
|
||||
{
|
||||
'target_defaults': {
|
||||
'dependencies': [
|
||||
- "<!(node -p \"require('node-addon-api').targets\"):node_addon_api_except",
|
||||
+ "<!(node -p \"require.resolve('node-addon-api/node_addon_api.gyp')\"):node_addon_api_except",
|
||||
],
|
||||
'conditions': [
|
||||
['OS=="win"', {
|
||||
@@ -12,6 +17,39 @@ index 5f63978b07ab50aaf7523219a2170ec737a6b5db..bbd9e06136e8922f40b5779e35d4fc83
|
||||
'msvs_settings': {
|
||||
'VCCLCompilerTool': {
|
||||
'AdditionalOptions': [
|
||||
@@ -42,32 +39,6 @@
|
||||
'-lshlwapi'
|
||||
],
|
||||
},
|
||||
- {
|
||||
- 'target_name': 'conpty_console_list',
|
||||
- 'sources' : [
|
||||
- 'src/win/conpty_console_list.cc'
|
||||
- ],
|
||||
- },
|
||||
- {
|
||||
- 'target_name': 'pty',
|
||||
- 'include_dirs' : [
|
||||
- '<!(node -p "require(\'node-addon-api\').include_dir")',
|
||||
- 'deps/winpty/src/include',
|
||||
- ],
|
||||
- # Disabled due to winpty
|
||||
- 'msvs_disabled_warnings': [ 4506, 4530 ],
|
||||
- 'dependencies' : [
|
||||
- 'deps/winpty/src/winpty.gyp:winpty-agent',
|
||||
- 'deps/winpty/src/winpty.gyp:winpty',
|
||||
- ],
|
||||
- 'sources' : [
|
||||
- 'src/win/winpty.cc',
|
||||
- 'src/win/path_util.cc'
|
||||
- ],
|
||||
- 'libraries': [
|
||||
- '-lshlwapi'
|
||||
- ],
|
||||
- }
|
||||
]
|
||||
}, { # OS!="win"
|
||||
'targets': [
|
||||
@@ -88,6 +85,16 @@
|
||||
'libraries!': [
|
||||
'-lutil'
|
||||
|
||||
+620
-54
@@ -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,
|
||||
@@ -4402,7 +4405,7 @@
|
||||
},
|
||||
{
|
||||
"id": "agent-status.manual-compact-identity",
|
||||
"title": "Manual Claude compact completion retires only its exact status generation",
|
||||
"title": "A finished Claude compact clears the pane, and an aborted one never strands it",
|
||||
"maturity": "experimental",
|
||||
"protection": "partial",
|
||||
"owner": "agent-session",
|
||||
@@ -4417,19 +4420,19 @@
|
||||
"providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"],
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["local", "ssh"],
|
||||
"coverageNotes": "Deterministic listener, loopback HTTP, relay-restart, persisted-restore, and fake-SSH transport contracts run on macOS. Claude Code 2.1.220 captures prove manual PreCompact starts a new prompt UUID and exact PreCompact/PostCompact pairs share it. The shared Node paths are platform-independent; live Linux, Windows, WSL, and paired-runtime journeys remain gaps.",
|
||||
"coverageNotes": "Deterministic listener, loopback HTTP, relay-restart, persisted-restore, and fake-SSH transport contracts run on macOS. Behavior tests deliver only events present in CLAUDE_EVENTS, so a mapping that is not registered cannot pass -- the failure mode that let the earlier compact correlation ship unreachable. Claude Code 2.1.227 PTY captures prove a successful manual compact emits PreCompact, a start-less summarizer SubagentStop, SessionStart(source=compact), then PostCompact, that an aborted compact emits PreCompact ALONE, that /compact emits no UserPromptSubmit, and that session_id is stable across the window. The shared Node paths are platform-independent; live Linux, Windows, WSL, and paired-runtime journeys remain gaps.",
|
||||
"motivatingLinks": [
|
||||
"https://github.com/stablyai/orca/issues/11352",
|
||||
"https://github.com/stablyai/orca/pull/11353"
|
||||
],
|
||||
"invariant": "A Claude manual PreCompact may replace only a current Claude row from the same receiving connection and provider session; a manual PostCompact may mark done only when the current authoritative row is its exact manual PreCompact generation, including provider prompt UUID. Missing identity is never a wildcard; later cross-provider work, replay, duplication, pane or tab retirement, and server stop invalidate completion. Automatic Claude and Kimi completion remain fail-closed until their hooks expose independently proven generation identity.",
|
||||
"oracle": "Run one byte-identical state-machine oracle plus local HTTP, relay-restart, SSH, and persisted-restore streams using Claude's observed different prior-turn and compact prompt UUIDs. Require matching manual completion to emit done while wrong or absent prompt UUID, session-presence mismatch, wrong source or connection, stale replay and duplicate delivery, later Codex work, automatic completion, and lifecycle cleanup cannot retire the current row. Assert both emitted event order and the authoritative lastStatusByPaneKey snapshot.",
|
||||
"invariant": "PreCompact is never registered and may never move a pane, because it fires before the compact is validated and an aborted compact emits it alone. Only a manual PostCompact may mark done, and it does so as a session boundary so completion-reactive consumers stay out of it; an automatic PostCompact claims nothing and writes no compact-scoped state, since its turn resumes and emits its own Stop. A completion either CLEARS a row or publishes nothing at all: it never creates a row, so a retired pane cannot be resurrected, and it never restates one it cannot clear, because a restated row loses restoredUnconfirmed and restarts the staleness clock. A manual /compact only completes at an idle prompt, so it retires a subagent that exists ONLY as a disk snapshot; live evidence -- a child observed in this runtime, an unclassifiable running background task, a registered session cron -- still holds the pane at working. A completion requires a valid provider prompt UUID, matches the pane owner by connection and provider session -- except on a restored row, which carries the previous connection and may carry no session at all -- and is applied at most once per compact. Ownership is enforced by the client that owns pane identity; a relay forwards and defers, so a cold relay cache cannot swallow the clearing event. A relay predating this contract forwards its own mapping, so ingest drops automatic envelopes, stamps the boundary on manual ones, carries the summarized turn label onto a promptless completion with or without a trigger, and classifies a trigger-stripped replay by payload state while still enforcing ownership. Kimi and other Claude-compatible vendors remain fail-closed.",
|
||||
"oracle": "Replay the measured Claude compact streams through a harness gated on the real CLAUDE_EVENTS, plus local HTTP, relay, SSH, and persisted-restore transports. Require the successful manual stream to end done with sessionBoundary set, and require the aborted stream (PreCompact alone) to leave both an idle and a working pane exactly as it found them. Drive the restart shape end to end over loopback HTTP from a hydrated row: a pane held only by a snapshot child must reach done with an empty roster, while a pane a runtime child still owns must emit NOTHING and keep its row object identical, so receivedAt and restoredUnconfirmed both survive. Deliver the restored-row cases with the hydrated row still cached at completion time and assert the summarizer published nothing, so the restored-row branch is the branch under test. Require rejection of an automatic completion, a completion with absent prompt UUID, a foreign provider session, a duplicate, and a completion for a pane with no cached row; require an automatic completion to leave the consumed-compact map untouched. Require a relay with a COLD cache to forward the completion while the client still refuses to mint a row it never had. Require ingest to drop legacy automatic envelopes, stamp the boundary on legacy manual ones, carry the summarized turn label onto a promptless completion with and without a trigger, and leave a FINISHED pane finished when a trigger-stripped working replay arrives. Require the consumed-compact map to be empty after each pane-scoped teardown route and to follow a pane move. Assert registration membership, emitted event order, and the authoritative lastStatusByPaneKey snapshot.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/shared/manual-compact-prompt-identity.test.ts src/main/agent-hooks/manual-compact-hook-stream.test.ts src/main/agent-hooks/manual-compact-status-cleanup.test.ts src/shared/agent-hook-listener-claude-turn-state.test.ts src/shared/agent-hook-listener-claude-compatible-vendors.test.ts src/shared/agent-hook-relay.test.ts src/relay/agent-hook-server.test.ts src/main/agent-hooks/server-claude-normalization.test.ts src/main/agent-hooks/server-last-status-write.test.ts src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts --reporter=dot",
|
||||
"Manual Claude Code 2.1.220 interactive compact: isolate UserPromptSubmit, PreCompact, and PostCompact hooks; submit one ordinary prompt then /compact; compare source, trigger, session_id, and prompt_id"
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/claude/compact-status-registration.test.ts src/main/agent-hooks/manual-compact-hook-stream.test.ts src/main/agent-hooks/manual-compact-status-cleanup.test.ts src/shared/agent-hook-listener-claude-turn-state.test.ts src/shared/agent-hook-listener-claude-compatible-vendors.test.ts src/shared/agent-hook-relay.test.ts src/relay/agent-hook-server.test.ts src/main/agent-hooks/server-claude-normalization.test.ts src/main/agent-hooks/server-last-status-write.test.ts src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts --reporter=dot",
|
||||
"Manual Claude Code interactive compact under a PTY: register every hook to a logging script, run one turn then /compact to observe the abort stream, then seven turns and /compact to observe the success stream; compare source, trigger, session_id, and prompt_id across both"
|
||||
],
|
||||
"testFiles": [
|
||||
"src/shared/manual-compact-prompt-identity.test.ts",
|
||||
"src/main/claude/compact-status-registration.test.ts",
|
||||
"src/main/agent-hooks/manual-compact-hook-stream.test.ts",
|
||||
"src/main/agent-hooks/manual-compact-status-cleanup.test.ts",
|
||||
"src/shared/agent-hook-listener-claude-turn-state.test.ts",
|
||||
@@ -4442,19 +4445,29 @@
|
||||
],
|
||||
"assertionRefs": [
|
||||
{
|
||||
"file": "src/shared/manual-compact-prompt-identity.test.ts",
|
||||
"file": "src/main/claude/compact-status-registration.test.ts",
|
||||
"assertions": [
|
||||
"matching manual identity settles once",
|
||||
"stale, duplicate, session-mismatched, malformed, automatic, and unproven provider completion fail closed",
|
||||
"4,097 rejected pane keys allocate no ownership state"
|
||||
"PostCompact is registered in CLAUDE_EVENTS and written into the settings Claude reads, and PreCompact is absent from both",
|
||||
"the measured successful manual compact ends a stuck working row as a done with sessionBoundary",
|
||||
"an aborted compact (PreCompact alone) leaves an idle pane idle and a working pane working",
|
||||
"an automatic completion claims nothing, writes no compact-scoped state, and the turn's own Stop still closes it",
|
||||
"a completion retires a child that exists only as a disk snapshot, but a runtime child or an active session cron still holds the pane and the completion then publishes nothing at all",
|
||||
"a completion clears a restored row -- delivered while that hydrated row is still the cached owner -- despite a stale connection id or a missing provider session, but never resurrects a retired pane",
|
||||
"absent prompt UUID, foreign provider session, and duplicate delivery fail closed",
|
||||
"the consumed-compact record is dropped by clearPaneCacheState and clearAllListenerCaches and follows movePaneCacheState"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/main/agent-hooks/manual-compact-hook-stream.test.ts",
|
||||
"assertions": [
|
||||
"local HTTP and relay-restart streams preserve the distinct prior-turn and compact prompt identities",
|
||||
"later provider work and wrong transport identity remain authoritative",
|
||||
"persisted PreCompact restores its prompt"
|
||||
"the measured local HTTP stream settles once and rejects a duplicate completion",
|
||||
"a hydrated restart-stuck pane reaches done with an empty roster, and a pane a runtime child owns emits nothing and keeps its row object identical",
|
||||
"the relay forwards the completion and preserves its compact identity in the replay cache so the client re-runs ownership before applying the clearing row",
|
||||
"a relay with a cold cache still forwards the completion, and the client still refuses to mint a row it never had",
|
||||
"a legacy relay's manual envelope is stamped as a session boundary and its automatic envelope is dropped instead of minting working",
|
||||
"a promptless completion keeps the summarized turn's label with and without a trigger on the envelope",
|
||||
"a trigger-stripped replay is classified by payload state, leaves a FINISHED pane finished, and is still rejected on an owner mismatch",
|
||||
"a PreCompact envelope never drives pane state"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -4470,22 +4483,22 @@
|
||||
],
|
||||
"evidenceRuns": [
|
||||
{
|
||||
"date": "2026-08-02",
|
||||
"date": "2026-08-18",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "pnpm exec vitest run --config config/vitest.config.ts src/shared/manual-compact-prompt-identity.test.ts src/main/agent-hooks/manual-compact-hook-stream.test.ts src/main/agent-hooks/manual-compact-status-cleanup.test.ts src/shared/agent-hook-listener-claude-turn-state.test.ts src/shared/agent-hook-listener-claude-compatible-vendors.test.ts src/shared/agent-hook-relay.test.ts src/relay/agent-hook-server.test.ts src/main/agent-hooks/server-claude-normalization.test.ts src/main/agent-hooks/server-last-status-write.test.ts src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts --reporter=dot",
|
||||
"command": "pnpm exec vitest run --config config/vitest.config.ts src/main/claude/compact-status-registration.test.ts src/main/agent-hooks/manual-compact-hook-stream.test.ts src/main/agent-hooks/manual-compact-status-cleanup.test.ts src/shared/agent-hook-listener-claude-turn-state.test.ts src/shared/agent-hook-listener-claude-compatible-vendors.test.ts src/shared/agent-hook-relay.test.ts src/relay/agent-hook-server.test.ts src/main/agent-hooks/server-claude-normalization.test.ts src/main/agent-hooks/server-last-status-write.test.ts src/main/ssh/ssh-relay-session-agent-hooks.integration.test.ts --reporter=dot",
|
||||
"result": "passed",
|
||||
"durationSeconds": 2.66,
|
||||
"summary": "Eight focused files and 435 tests passed with local HTTP, relay, SSH, persistence, adversarial identity, cleanup, and existing provider-regression coverage."
|
||||
"durationSeconds": 3.28,
|
||||
"summary": "Ten files and 116 tests passed across registration, listener, local HTTP, relay, SSH, persistence, and cleanup. Reverting only the four source files to the merge base first turned 12 of 21 registration-gated tests and 8 of 12 relay/ingest tests red, so the suite observes its own failure rather than passing over unreachable code. Every assertion was additionally mutation-tested: 18 of 18 targeted mutations -- including reaping runtime children as well as snapshot ones, restating a pane live evidence still holds, re-enforcing compact ownership on the relay, and dropping the consumed-compact map from any one teardown route -- are caught."
|
||||
},
|
||||
{
|
||||
"date": "2026-08-02",
|
||||
"date": "2026-08-17",
|
||||
"runner": "manual",
|
||||
"platform": "macos",
|
||||
"command": "Manual Claude Code 2.1.220 interactive compact: isolate UserPromptSubmit, PreCompact, and PostCompact hooks; submit one ordinary prompt then /compact; compare source, trigger, session_id, and prompt_id",
|
||||
"command": "Manual Claude Code interactive compact under a PTY: register every hook to a logging script, run one turn then /compact to observe the abort stream, then seven turns and /compact to observe the success stream; compare source, trigger, session_id, and prompt_id across both",
|
||||
"result": "passed",
|
||||
"durationSeconds": 120,
|
||||
"summary": "A fresh capture proved /compact emits no UserPromptSubmit and its PreCompact uses a new UUID distinct from the preceding user turn; the preserved authenticated capture proved the matching manual PreCompact and PostCompact share that UUID and session. Automatic capture reused one prompt UUID across multiple compact generations, so automatic completion remains disabled."
|
||||
"durationSeconds": 1080,
|
||||
"summary": "Claude Code 2.1.227. Aborted compact emitted PreCompact(manual) ALONE with no PostCompact and no SessionStart(compact). Successful compact emitted PreCompact(manual), a start-less SubagentStop (agent_type empty, no matching SubagentStart), SessionStart(source=compact), PostCompact(manual), then Notification(idle_prompt). /compact emitted no UserPromptSubmit in either the TUI or print mode; session_id was stable across the whole window while the compact allocated its own prompt_id."
|
||||
}
|
||||
],
|
||||
"runtimeBudget": {
|
||||
@@ -8047,6 +8060,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 +8073,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 +8086,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 +8101,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 +8161,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 +8504,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 +8596,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 +9920,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 +9975,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 +9999,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 +10064,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 +12347,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 +12359,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 +14312,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."
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const { assertNodePtyJobOwnership } = require('./node-pty-job-ownership.cjs')
|
||||
const NODE_PTY_PATCH = readFileSync(
|
||||
new URL('../patches/node-pty@1.1.0.patch', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
|
||||
const PATCHED = {
|
||||
dir: 'build/Release/',
|
||||
module: {
|
||||
listJobProcessIds: () => [],
|
||||
terminateJob: () => true,
|
||||
assignCurrentProcessToJob: () => true
|
||||
}
|
||||
}
|
||||
const PREBUILD = {
|
||||
dir: 'prebuilds/win32-x64/',
|
||||
module: {
|
||||
startProcess: () => {},
|
||||
connect: () => {},
|
||||
resize: () => {},
|
||||
clear: () => {},
|
||||
kill: () => {}
|
||||
}
|
||||
}
|
||||
|
||||
describe('assertNodePtyJobOwnership', () => {
|
||||
it('keeps node-addon-api project paths absolute during Windows source builds', () => {
|
||||
expect(NODE_PTY_PATCH).toContain(
|
||||
`+ "<!(node -p \\"require.resolve('node-addon-api/node_addon_api.gyp')\\"):node_addon_api_except"`
|
||||
)
|
||||
})
|
||||
|
||||
it('leaves the unchanged Windows helper and fallback on their upstream prebuilds', () => {
|
||||
expect(NODE_PTY_PATCH).toContain("- 'target_name': 'conpty_console_list'")
|
||||
expect(NODE_PTY_PATCH).toContain("- 'target_name': 'pty'")
|
||||
})
|
||||
|
||||
it('rejects the prebuild that shipped without the job exports', () => {
|
||||
expect(() =>
|
||||
assertNodePtyJobOwnership({ platform: 'win32', nativeName: 'conpty', native: PREBUILD })
|
||||
).toThrow(/listJobProcessIds, terminateJob, assignCurrentProcessToJob/)
|
||||
})
|
||||
|
||||
it('names where the bad native came from, so the fix is obvious', () => {
|
||||
expect(() =>
|
||||
assertNodePtyJobOwnership({ platform: 'win32', nativeName: 'conpty', native: PREBUILD })
|
||||
).toThrow(/prebuilds\/win32-x64/)
|
||||
})
|
||||
|
||||
it('accepts a source build carrying the patch', () => {
|
||||
expect(() =>
|
||||
assertNodePtyJobOwnership({ platform: 'win32', nativeName: 'conpty', native: PATCHED })
|
||||
).not.toThrow()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['non-Windows hosts', { platform: 'darwin', nativeName: 'pty' }],
|
||||
['the pre-ConPTY winpty backend', { platform: 'win32', nativeName: 'pty' }]
|
||||
])('stays out of the way on %s', (_case, spec) => {
|
||||
expect(() => assertNodePtyJobOwnership({ ...spec, native: PREBUILD })).not.toThrow()
|
||||
})
|
||||
})
|
||||
@@ -7,6 +7,7 @@ import { release } from 'node:os'
|
||||
import { basename, resolve } from 'node:path'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const { assertNodePtyJobOwnership } = require('./node-pty-job-ownership.cjs')
|
||||
const scriptPath = import.meta.filename
|
||||
const projectDir = resolve(import.meta.dirname, '../..')
|
||||
const runtime = readRuntimeArg()
|
||||
@@ -277,6 +278,7 @@ function loadNodePtyNativeModule() {
|
||||
// terminal is created, so require('node-pty') alone can miss ABI mismatches.
|
||||
const native = loadNativeModule(nativeName)
|
||||
assertNodePtyWindowsConptyRuntime(native?.dir)
|
||||
assertNodePtyJobOwnership({ nativeName, native })
|
||||
if (requiresPatchedNodePtySourceBuild() && !isNodePtyReleaseBuildDir(native?.dir)) {
|
||||
throw new Error(
|
||||
`node-pty resolved to ${native.dir}; expected build/Release so Orca's node-pty patch is active`
|
||||
|
||||
@@ -14,6 +14,9 @@ import { fileURLToPath } from 'node:url'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
const sourceScriptPath = fileURLToPath(new URL('./ensure-native-runtime.mjs', import.meta.url))
|
||||
const sourceNodePtyJobOwnershipPath = fileURLToPath(
|
||||
new URL('./node-pty-job-ownership.cjs', import.meta.url)
|
||||
)
|
||||
|
||||
describe('ensure-native-runtime', () => {
|
||||
it('rechecks Node native modules in fresh child processes after rebuilding', () => {
|
||||
@@ -156,6 +159,10 @@ describe('ensure-native-runtime', () => {
|
||||
function mkTempProject() {
|
||||
const projectDir = mkdtempSync(join(tmpdir(), 'orca-native-runtime-'))
|
||||
mkdirSync(join(projectDir, 'config', 'scripts'), { recursive: true })
|
||||
copyFileSync(
|
||||
sourceNodePtyJobOwnershipPath,
|
||||
join(projectDir, 'config', 'scripts', 'node-pty-job-ownership.cjs')
|
||||
)
|
||||
return projectDir
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
'use strict'
|
||||
|
||||
const NODE_PTY_JOB_EXPORTS = [
|
||||
'listJobProcessIds',
|
||||
'terminateJob',
|
||||
'assignCurrentProcessToJob'
|
||||
]
|
||||
|
||||
function assertNodePtyJobOwnership({ nativeName, native, platform = process.platform }) {
|
||||
if (platform !== 'win32' || nativeName !== 'conpty') {
|
||||
return
|
||||
}
|
||||
const exported = native?.module ?? native
|
||||
const missing = NODE_PTY_JOB_EXPORTS.filter((name) => typeof exported?.[name] !== 'function')
|
||||
if (missing.length === 0) {
|
||||
return
|
||||
}
|
||||
throw new Error(
|
||||
[
|
||||
`node-pty's conpty native is missing ${missing.join(', ')}.`,
|
||||
`Resolved from: ${native?.dir ?? 'unknown'}`,
|
||||
'That build cannot own a PTY tree, so terminatePtyJob degrades to "unavailable"',
|
||||
'and pane teardown falls back to guessing by PID ancestry.',
|
||||
'Rebuild node-pty from source so config/patches/node-pty@1.1.0.patch applies.'
|
||||
].join(' ')
|
||||
)
|
||||
}
|
||||
|
||||
module.exports = { assertNodePtyJobOwnership }
|
||||
@@ -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`)
|
||||
}
|
||||
@@ -475,9 +475,14 @@ function loadNativeModule(moduleName) {
|
||||
}
|
||||
if (moduleName === 'node-pty') {
|
||||
projectRequire('node-pty')
|
||||
const { assertNodePtyJobOwnership } = projectRequire(
|
||||
'./config/scripts/node-pty-job-ownership.cjs'
|
||||
)
|
||||
const { loadNativeModule } = projectRequire('node-pty/lib/utils')
|
||||
const native = loadNativeModule(getNodePtyNativeModuleName())
|
||||
const nativeName = getNodePtyNativeModuleName()
|
||||
const native = loadNativeModule(nativeName)
|
||||
assertNodePtyWindowsConptyRuntime(native.dir)
|
||||
assertNodePtyJobOwnership({ nativeName, native })
|
||||
if (requirePatchedNodePtySourceBuild && !isNodePtyReleaseBuildDir(native.dir)) {
|
||||
throw new Error(
|
||||
'node-pty resolved to ' +
|
||||
|
||||
@@ -18,6 +18,9 @@ const sourceScriptPath = fileURLToPath(new URL('./rebuild-native-deps.mjs', impo
|
||||
const sourceInstallScriptPath = fileURLToPath(
|
||||
new URL('./install-electron-package-binary.mjs', import.meta.url)
|
||||
)
|
||||
const sourceNodePtyJobOwnershipPath = fileURLToPath(
|
||||
new URL('./node-pty-job-ownership.cjs', import.meta.url)
|
||||
)
|
||||
|
||||
describe('rebuild-native-deps Electron install fallback', () => {
|
||||
it('continues non-strict postinstall when Electron retry download fails', () => {
|
||||
@@ -135,6 +138,7 @@ describe('rebuild-native-deps patched node-pty rebuild', () => {
|
||||
writeFakeElectronRebuild(projectDir, { logPathEnv: 'ORCA_REBUILD_TEST_LOG' })
|
||||
writeFakeLoadableNodePty(projectDir, { nativeDir: '../build/Release/' })
|
||||
writeFakeWindowsRegistry(projectDir)
|
||||
writeFakeWindowsProcessTree(projectDir)
|
||||
writeFakeNodePtyConptyPayload(projectDir, process.arch)
|
||||
|
||||
const result = runRebuildScript(projectDir, {
|
||||
@@ -189,6 +193,7 @@ describe('rebuild-native-deps patched node-pty rebuild', () => {
|
||||
writeFakeUsableElectronPackage(projectDir, { platform: 'win32' })
|
||||
writeFakeElectronRebuild(projectDir, { logPathEnv: 'ORCA_REBUILD_TEST_LOG' })
|
||||
writeFakeLoadableNodePty(projectDir)
|
||||
writeFakeWindowsProcessTree(projectDir)
|
||||
writeFakeNodePtyConptyPayload(projectDir, process.arch)
|
||||
|
||||
const result = runRebuildScript(projectDir, {
|
||||
@@ -207,6 +212,36 @@ describe('rebuild-native-deps patched node-pty rebuild', () => {
|
||||
}
|
||||
)
|
||||
|
||||
it.skipIf(process.platform !== 'win32')(
|
||||
'rebuilds a loadable ConPTY native that lacks Orca job ownership',
|
||||
() => {
|
||||
const projectDir = mkTempProject()
|
||||
|
||||
try {
|
||||
const rebuildLogPath = join(projectDir, 'electron-rebuild.log')
|
||||
writeFakeUsableElectronPackage(projectDir, { platform: 'win32' })
|
||||
writeFakeElectronRebuild(projectDir, { logPathEnv: 'ORCA_REBUILD_TEST_LOG' })
|
||||
writeFakeLoadableNodePty(projectDir, { ownsPtyJob: false })
|
||||
writeFakeWindowsRegistry(projectDir)
|
||||
writeFakeWindowsProcessTree(projectDir)
|
||||
|
||||
const result = runRebuildScript(projectDir, {
|
||||
ORCA_REBUILD_TEST_LOG: rebuildLogPath,
|
||||
npm_config_platform: 'win32',
|
||||
npm_config_arch: process.arch
|
||||
})
|
||||
|
||||
expect(result.status, result.stderr).toBe(0)
|
||||
expect(result.stdout).toContain('Rebuilding failed native modules: node-pty')
|
||||
expect(result.stdout).toContain('missing listJobProcessIds')
|
||||
const rebuildCall = JSON.parse(readFileSync(rebuildLogPath, 'utf8').trim())
|
||||
expect(rebuildCall.onlyModules).toEqual(['node-pty'])
|
||||
} finally {
|
||||
rmSync(projectDir, { recursive: true, force: true })
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'rebuilds when Electron can load node-pty but patched build artifacts are missing',
|
||||
() => {
|
||||
@@ -305,6 +340,10 @@ function mkTempProject() {
|
||||
sourceInstallScriptPath,
|
||||
join(projectDir, 'config', 'scripts', 'install-electron-package-binary.mjs')
|
||||
)
|
||||
copyFileSync(
|
||||
sourceNodePtyJobOwnershipPath,
|
||||
join(projectDir, 'config', 'scripts', 'node-pty-job-ownership.cjs')
|
||||
)
|
||||
return projectDir
|
||||
}
|
||||
|
||||
@@ -495,7 +534,10 @@ function writeFakeNodePtyConptyPayload(projectDir, arch) {
|
||||
writeFileSync(join(sourceDir, 'OpenConsole.exe'), `OpenConsole.exe ${arch}`)
|
||||
}
|
||||
|
||||
function writeFakeLoadableNodePty(projectDir, { nativeDir = 'prebuilds/pty' } = {}) {
|
||||
function writeFakeLoadableNodePty(
|
||||
projectDir,
|
||||
{ nativeDir = 'prebuilds/pty', ownsPtyJob = true } = {}
|
||||
) {
|
||||
const nodePtyDir = join(projectDir, 'node_modules', 'node-pty')
|
||||
mkdirSync(join(nodePtyDir, 'lib'), { recursive: true })
|
||||
writeFileSync(join(nodePtyDir, 'index.js'), 'module.exports = {}\n')
|
||||
@@ -503,7 +545,19 @@ function writeFakeLoadableNodePty(projectDir, { nativeDir = 'prebuilds/pty' } =
|
||||
join(nodePtyDir, 'lib', 'utils.js'),
|
||||
`
|
||||
exports.loadNativeModule = function loadNativeModule(nativeName) {
|
||||
return { dir: ${JSON.stringify(nativeDir)}, module: { nativeName } }
|
||||
return {
|
||||
dir: ${JSON.stringify(nativeDir)},
|
||||
module: {
|
||||
nativeName,
|
||||
...(${JSON.stringify(ownsPtyJob)}
|
||||
? {
|
||||
listJobProcessIds() {},
|
||||
terminateJob() {},
|
||||
assignCurrentProcessToJob() {}
|
||||
}
|
||||
: {})
|
||||
}
|
||||
}
|
||||
}
|
||||
`
|
||||
)
|
||||
@@ -518,6 +572,12 @@ function writeFakeWindowsRegistry(projectDir) {
|
||||
)
|
||||
}
|
||||
|
||||
function writeFakeWindowsProcessTree(projectDir) {
|
||||
const processTreeDir = join(projectDir, 'node_modules', '@vscode', 'windows-process-tree')
|
||||
mkdirSync(processTreeDir, { recursive: true })
|
||||
writeFileSync(join(processTreeDir, 'index.js'), 'module.exports = {}\n')
|
||||
}
|
||||
|
||||
function writeNodePtyPatchFile(projectDir) {
|
||||
mkdirSync(join(projectDir, 'config', 'patches'), { recursive: true })
|
||||
writeFileSync(join(projectDir, 'config', 'patches', 'node-pty@1.1.0.patch'), 'patch marker\n')
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
const { createRequire } = require('node:module')
|
||||
const { join } = require('node:path')
|
||||
const { assertNodePtyJobOwnership } = require('./node-pty-job-ownership.cjs')
|
||||
|
||||
function loadPackagedConpty(resourcesDir) {
|
||||
const packagedRequire = createRequire(join(resourcesDir, 'package.json'))
|
||||
const { loadNativeModule } = packagedRequire('./node_modules/node-pty/lib/utils')
|
||||
return loadNativeModule('conpty')
|
||||
}
|
||||
|
||||
function verifyPackagedNodePtyJobOwnership(resourcesDir, options = {}) {
|
||||
const platform = options.platform ?? process.platform
|
||||
if (platform !== 'win32') {
|
||||
return
|
||||
}
|
||||
|
||||
const native = (options.loadNative ?? loadPackagedConpty)(resourcesDir)
|
||||
assertNodePtyJobOwnership({ platform, nativeName: 'conpty', native })
|
||||
if (!native.dir.replace(/\\/g, '/').includes('build/Release/')) {
|
||||
throw new Error(`Packaged node-pty resolved to ${native.dir}; expected patched build/Release`)
|
||||
}
|
||||
console.log('[verify-packaged-node-pty] OK — packaged ConPTY owns process trees')
|
||||
}
|
||||
|
||||
module.exports = { verifyPackagedNodePtyJobOwnership }
|
||||
@@ -0,0 +1,51 @@
|
||||
import { createRequire } from 'node:module'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const {
|
||||
verifyPackagedNodePtyJobOwnership
|
||||
} = require('./verify-packaged-node-pty-job-ownership.cjs')
|
||||
|
||||
const PATCHED = {
|
||||
dir: '../build/Release/',
|
||||
module: {
|
||||
listJobProcessIds: () => [],
|
||||
terminateJob: () => true,
|
||||
assignCurrentProcessToJob: () => true
|
||||
}
|
||||
}
|
||||
|
||||
describe('verifyPackagedNodePtyJobOwnership', () => {
|
||||
it('accepts the packaged patched ConPTY binding', () => {
|
||||
expect(() =>
|
||||
verifyPackagedNodePtyJobOwnership('resources', {
|
||||
platform: 'win32',
|
||||
loadNative: () => PATCHED
|
||||
})
|
||||
).not.toThrow()
|
||||
})
|
||||
|
||||
it('rejects a packaged upstream prebuild', () => {
|
||||
expect(() =>
|
||||
verifyPackagedNodePtyJobOwnership('resources', {
|
||||
platform: 'win32',
|
||||
loadNative: () => ({ dir: '../prebuilds/win32-x64/', module: {} })
|
||||
})
|
||||
).toThrow(/missing listJobProcessIds, terminateJob, assignCurrentProcessToJob/)
|
||||
})
|
||||
|
||||
it('requires the patched source-build directory', () => {
|
||||
expect(() =>
|
||||
verifyPackagedNodePtyJobOwnership('resources', {
|
||||
platform: 'win32',
|
||||
loadNative: () => ({ ...PATCHED, dir: '../prebuilds/win32-x64/' })
|
||||
})
|
||||
).toThrow(/expected patched build\/Release/)
|
||||
})
|
||||
|
||||
it('does not load Windows natives for other targets', () => {
|
||||
const loadNative = vi.fn()
|
||||
verifyPackagedNodePtyJobOwnership('resources', { platform: 'linux', loadNative })
|
||||
expect(loadNative).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -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 |
@@ -33,13 +33,14 @@ authority.
|
||||
|
||||
## Current Capabilities
|
||||
|
||||
| Capability | Preferred behavior | Compatibility behavior |
|
||||
| ----------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------- |
|
||||
| `worktree-list-z` | NUL-delimited worktree paths with `prunable` marks | Line-block parser for Git before `worktree list -z` (2.36); the `prunable`/`locked` annotations still parse on Git 2.31–2.35, and a path-existence probe restores `prunable` detection for Git before 2.31 |
|
||||
| `rev-parse-path-format` | Absolute repo metadata paths | Resolve legacy relative output against the scanned repo |
|
||||
| `for-each-ref-exclude` | Exclude remote HEAD before the output limit | Request extra refs, then filter remote HEAD in Orca |
|
||||
| `merge-tree-write-tree` | Derive real-merge conflicts and no-op tree proofs | Omit the conflict summary and keep conservative branch cleanup behavior before Git 2.38 |
|
||||
| `merge-tree-merge-base` | Supply the already-resolved merge base | Use the older two-commit `merge-tree --write-tree` form |
|
||||
| Capability | Preferred behavior | Compatibility behavior |
|
||||
| --------------------------- | ----------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `fetch-no-write-fetch-head` | Fetch a private rebase ref without changing worktree-local `FETCH_HEAD` | Serialize all Orca fetch/pull operations per worktree Git directory before Git 2.29 |
|
||||
| `worktree-list-z` | NUL-delimited worktree paths with `prunable` marks | Line-block parser for Git before `worktree list -z` (2.36); the `prunable`/`locked` annotations still parse on Git 2.31–2.35, and a path-existence probe restores `prunable` detection for Git before 2.31 |
|
||||
| `rev-parse-path-format` | Absolute repo metadata paths | Resolve legacy relative output against the scanned repo |
|
||||
| `for-each-ref-exclude` | Exclude remote HEAD before the output limit | Request extra refs, then filter remote HEAD in Orca |
|
||||
| `merge-tree-write-tree` | Derive real-merge conflicts and no-op tree proofs | Omit the conflict summary and keep conservative branch cleanup behavior before Git 2.38 |
|
||||
| `merge-tree-merge-base` | Supply the already-resolved merge base | Use the older two-commit `merge-tree --write-tree` form |
|
||||
|
||||
## Why Not `simple-git`
|
||||
|
||||
@@ -54,7 +55,7 @@ capability problem.
|
||||
## CI Contract
|
||||
|
||||
PR checks run the capability contract against real Git 2.25.5, 2.38.1, and
|
||||
2.49.1 binaries. This spans the core-workflow baseline, the transitional
|
||||
2.49.1 binaries. This spans the pre-2.29 serialized `FETCH_HEAD` fallback, the transitional
|
||||
`merge-tree --write-tree` behavior before `--merge-base`, and current Git.
|
||||
|
||||
Keep the unit tests alongside that matrix. They cover concurrent probes,
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { Radio } from 'lucide-react-native'
|
||||
import { Animated, Easing, StyleSheet, View } from 'react-native'
|
||||
import type { AgentWorkingMode } from '../../../src/shared/agent-status-types'
|
||||
|
||||
type WorktreeStatus = 'working' | 'active' | 'permission' | 'done' | 'inactive'
|
||||
|
||||
@@ -17,11 +19,18 @@ const STATUS_COLORS: Record<WorktreeStatus, string> = {
|
||||
inactive: 'rgba(115,115,115,0.4)'
|
||||
}
|
||||
|
||||
export function AgentSpinner({ status }: { status: WorktreeStatus }) {
|
||||
export function AgentSpinner({
|
||||
status,
|
||||
workingMode
|
||||
}: {
|
||||
status: WorktreeStatus
|
||||
workingMode?: AgentWorkingMode
|
||||
}) {
|
||||
const spinValue = useRef(new Animated.Value(0)).current
|
||||
const monitoring = status === 'working' && workingMode === 'monitoring'
|
||||
|
||||
useEffect(() => {
|
||||
if (status === 'working') {
|
||||
if (status === 'working' && !monitoring) {
|
||||
const animation = Animated.loop(
|
||||
Animated.timing(spinValue, {
|
||||
toValue: 1,
|
||||
@@ -34,10 +43,18 @@ export function AgentSpinner({ status }: { status: WorktreeStatus }) {
|
||||
return () => animation.stop()
|
||||
}
|
||||
spinValue.setValue(0)
|
||||
}, [status, spinValue])
|
||||
}, [monitoring, status, spinValue])
|
||||
|
||||
const color = STATUS_COLORS[status] ?? STATUS_COLORS.inactive
|
||||
|
||||
if (monitoring) {
|
||||
return (
|
||||
<View style={styles.wrapper} accessibilityLabel="Monitoring background tasks">
|
||||
<Radio size={12} color={STATUS_COLORS.working} />
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
if (status === 'working') {
|
||||
const rotate = spinValue.interpolate({
|
||||
inputRange: [0, 1],
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { Radio } from 'lucide-react-native'
|
||||
import { Animated, Easing, StyleSheet, View } from 'react-native'
|
||||
import type { AgentDotState } from '../worktree/agent-row-display'
|
||||
|
||||
@@ -7,13 +8,14 @@ import type { AgentDotState } from '../worktree/agent-row-display'
|
||||
// emerald for 'done', red for blocked/waiting/interrupted (attention), neutral
|
||||
// for idle. Distinct from the worktree-level AgentSpinner, which collapses the
|
||||
// agent vocabulary into the 5-state rollup the sidebar dot uses.
|
||||
const DOT_COLORS: Record<Exclude<AgentDotState, 'working'>, string> = {
|
||||
const DOT_COLORS: Record<Exclude<AgentDotState, 'working' | 'monitoring'>, string> = {
|
||||
done: '#10b981',
|
||||
blocked: '#ef4444',
|
||||
waiting: '#ef4444',
|
||||
interrupted: '#ef4444',
|
||||
idle: 'rgba(115,115,115,0.4)'
|
||||
}
|
||||
const WORKING_COLOR = '#eab308'
|
||||
|
||||
export function AgentStateDot({ state }: { state: AgentDotState }) {
|
||||
const spinValue = useRef(new Animated.Value(0)).current
|
||||
@@ -44,6 +46,14 @@ export function AgentStateDot({ state }: { state: AgentDotState }) {
|
||||
)
|
||||
}
|
||||
|
||||
if (state === 'monitoring') {
|
||||
return (
|
||||
<View style={styles.wrapper} accessibilityLabel="Monitoring background tasks">
|
||||
<Radio size={10} color={WORKING_COLOR} />
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.wrapper}>
|
||||
<View style={[styles.dot, { backgroundColor: DOT_COLORS[state] }]} />
|
||||
@@ -59,7 +69,7 @@ const styles = StyleSheet.create({
|
||||
height: 6,
|
||||
borderRadius: 3,
|
||||
borderWidth: 1.5,
|
||||
borderColor: '#eab308',
|
||||
borderColor: WORKING_COLOR,
|
||||
borderTopColor: 'transparent'
|
||||
}
|
||||
})
|
||||
|
||||
@@ -199,7 +199,7 @@ describe('memoized worktree rows', () => {
|
||||
await act(async () => {
|
||||
renderer!.update(
|
||||
createElement(WorktreeAgentRow, {
|
||||
agent: agent({ state: 'done', updatedAt: 2_000 }),
|
||||
agent: agent({ state: 'working', workingMode: 'monitoring', updatedAt: 2_000 }),
|
||||
depth: 0,
|
||||
now: 2_000,
|
||||
unvisited: false
|
||||
@@ -207,5 +207,22 @@ describe('memoized worktree rows', () => {
|
||||
)
|
||||
})
|
||||
expect(agentStateDotRender).toHaveBeenCalledTimes(2)
|
||||
expect(agentStateDotRender).toHaveBeenLastCalledWith({ state: 'monitoring' })
|
||||
})
|
||||
|
||||
it('passes workspace monitoring mode to the status indicator', async () => {
|
||||
await act(async () => {
|
||||
renderer = create(
|
||||
createElement(ListRowHarness, {
|
||||
item: { ...baseItem, status: 'working', workingMode: 'monitoring' },
|
||||
now: 2_000
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
expect(agentSpinnerRender).toHaveBeenLastCalledWith({
|
||||
status: 'working',
|
||||
workingMode: 'monitoring'
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,6 +2,7 @@ import { memo } from 'react'
|
||||
import { Bell, ChevronDown, ChevronRight, GitBranch, GitPullRequest } from 'lucide-react-native'
|
||||
import { Pressable, StyleSheet, Text, View } from 'react-native'
|
||||
import type { RepoIcon } from '../../../src/shared/repo-icon'
|
||||
import type { AgentWorkingMode } from '../../../src/shared/agent-status-types'
|
||||
import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types'
|
||||
import { triggerMediumImpact } from '../platform/haptics'
|
||||
import { colors, radii, spacing, typography } from '../theme/mobile-theme'
|
||||
@@ -39,6 +40,7 @@ export type WorktreeListRowItem = {
|
||||
lineageChildCount?: number
|
||||
lineageCollapsed?: boolean
|
||||
agents?: RuntimeWorktreeAgentRow[]
|
||||
workingMode?: AgentWorkingMode
|
||||
}
|
||||
|
||||
type WorktreeRollupStatus = 'working' | 'active' | 'permission' | 'done' | 'inactive'
|
||||
@@ -97,7 +99,7 @@ function WorktreeListRowComponent<T extends WorktreeListRowItem>({
|
||||
delayLongPress={400}
|
||||
>
|
||||
<View style={styles.indicatorCol}>
|
||||
<AgentSpinner status={status} />
|
||||
<AgentSpinner status={status} workingMode={item.workingMode} />
|
||||
{item.unread && (
|
||||
<Bell
|
||||
size={10}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { createElement } from 'react'
|
||||
import { act, create } from 'react-test-renderer'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { AgentSpinner } from './AgentSpinner'
|
||||
import { AgentStateDot } from './AgentStateDot'
|
||||
|
||||
const DESKTOP_WORKING_COLOR = '#eab308'
|
||||
|
||||
type MonitoringTestRenderer = {
|
||||
readonly root: {
|
||||
findByType(type: string): { props: Record<string, unknown> }
|
||||
}
|
||||
unmount(): void
|
||||
}
|
||||
|
||||
const { animationLoop, animationTiming, setValue } = vi.hoisted(() => ({
|
||||
animationLoop: vi.fn(() => ({ start: vi.fn(), stop: vi.fn() })),
|
||||
animationTiming: vi.fn(() => ({})),
|
||||
setValue: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('lucide-react-native', () => ({ Radio: 'Radio' }))
|
||||
vi.mock('react-native', () => ({
|
||||
Animated: {
|
||||
Value: function Value() {
|
||||
return { interpolate: vi.fn(() => 'rotation'), setValue }
|
||||
},
|
||||
View: 'AnimatedView',
|
||||
loop: animationLoop,
|
||||
timing: animationTiming
|
||||
},
|
||||
Easing: { linear: 'linear' },
|
||||
StyleSheet: { create: <T>(styles: T) => styles },
|
||||
View: 'View'
|
||||
}))
|
||||
|
||||
describe('mobile monitoring indicators', () => {
|
||||
let renderer: MonitoringTestRenderer | null = null
|
||||
|
||||
beforeEach(() => {
|
||||
animationLoop.mockClear()
|
||||
animationTiming.mockClear()
|
||||
setValue.mockClear()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => renderer?.unmount())
|
||||
renderer = null
|
||||
})
|
||||
|
||||
it('renders a static Radio for a monitoring agent', async () => {
|
||||
await act(async () => {
|
||||
renderer = create(createElement(AgentStateDot, { state: 'monitoring' }))
|
||||
})
|
||||
|
||||
expect(renderer?.root.findByType('Radio').props).toMatchObject({
|
||||
color: DESKTOP_WORKING_COLOR,
|
||||
size: 10
|
||||
})
|
||||
expect(animationTiming).not.toHaveBeenCalled()
|
||||
expect(animationLoop).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('renders a static Radio for an all-monitoring workspace', async () => {
|
||||
await act(async () => {
|
||||
renderer = create(
|
||||
createElement(AgentSpinner, { status: 'working', workingMode: 'monitoring' })
|
||||
)
|
||||
})
|
||||
|
||||
expect(renderer?.root.findByType('Radio').props).toMatchObject({
|
||||
color: DESKTOP_WORKING_COLOR,
|
||||
size: 12
|
||||
})
|
||||
expect(animationTiming).not.toHaveBeenCalled()
|
||||
expect(animationLoop).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('keeps the spinner fallback when workingMode is absent', async () => {
|
||||
await act(async () => {
|
||||
renderer = create(createElement(AgentSpinner, { status: 'working' }))
|
||||
})
|
||||
|
||||
expect(animationTiming).toHaveBeenCalledOnce()
|
||||
expect(animationLoop).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -697,7 +697,9 @@ describe('useMobileNativeChatController streaming scope', () => {
|
||||
launchAgent: 'claude',
|
||||
agentStatus: {
|
||||
state: 'working',
|
||||
workingMode: undefined as 'monitoring' | undefined,
|
||||
agentType: 'claude',
|
||||
lastAssistantMessage: 'Partial reply',
|
||||
providerSession: { id: 'session-1' }
|
||||
},
|
||||
isActive: true
|
||||
@@ -723,6 +725,7 @@ describe('useMobileNativeChatController streaming scope', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
viewMode.isTabChatView = () => true
|
||||
workingTab.agentStatus.workingMode = undefined
|
||||
act(() => {
|
||||
renderer = create(createElement(Harness))
|
||||
})
|
||||
@@ -737,6 +740,7 @@ describe('useMobileNativeChatController streaming scope', () => {
|
||||
|
||||
it('holds the stream scope and liveness while the user peeks at the terminal', () => {
|
||||
expect(controller?.showNativeChat).toBe(true)
|
||||
expect(controller?.nativeChatAgentWorking).toBe(true)
|
||||
const scopeKey = controller?.nativeChatStreamScopeKey
|
||||
expect(scopeKey).toContain('session-1')
|
||||
expect(controller?.nativeChatStreamLive).toBe(true)
|
||||
@@ -750,6 +754,16 @@ describe('useMobileNativeChatController streaming scope', () => {
|
||||
expect(controller?.nativeChatStreamLive).toBe(true)
|
||||
})
|
||||
|
||||
it('treats passive monitoring as outside the foreground turn', () => {
|
||||
workingTab.agentStatus.workingMode = 'monitoring'
|
||||
act(() => renderer?.update(createElement(Harness)))
|
||||
|
||||
expect(controller?.nativeChatAgentWorking).toBe(false)
|
||||
expect(controller?.nativeChatStreamLive).toBe(false)
|
||||
expect(controller?.nativeChatStreamingText).toBeUndefined()
|
||||
expect(controller?.nativeChatSessionOptions?.isWorking).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps the delayed-send route guard view-gated, unlike the stream scope', () => {
|
||||
const before = answerSendArgs.at(-1)?.streamIdentity
|
||||
expect(before).toBe(controller?.nativeChatStreamScopeKey)
|
||||
|
||||
@@ -115,11 +115,14 @@ export function useMobileNativeChatController(args: {
|
||||
transcriptSettled: nativeChatSession.status === 'ready'
|
||||
})
|
||||
|
||||
const nativeChatStatus = activeChatResolution ? activeSessionTab?.agentStatus : null
|
||||
const nativeChatAgentWorking = nativeChatStatus?.state === 'working'
|
||||
const activeTabStatus = activeSessionTab?.agentStatus
|
||||
const activeTabAgentWorking =
|
||||
activeTabStatus?.state === 'working' && activeTabStatus.workingMode !== 'monitoring'
|
||||
const nativeChatStatus = activeChatResolution ? activeTabStatus : null
|
||||
const nativeChatAgentWorking = activeChatResolution != null && activeTabAgentWorking
|
||||
// Deliberately not gated on the chat view being visible: the streaming gate
|
||||
// has to tell "hidden mid-turn" from "the turn ended".
|
||||
const nativeChatStreamLive = activeSessionTab?.agentStatus?.state === 'working'
|
||||
const nativeChatStreamLive = activeTabAgentWorking
|
||||
// Throttle the streaming bubble: OpenCode emits a status frame per streamed
|
||||
// part, and each one re-renders and re-parses the whole accumulated markdown.
|
||||
const nativeChatStreamingText = useThrottledLatestValue(
|
||||
|
||||
@@ -28,6 +28,9 @@ function row(overrides: Partial<RuntimeWorktreeAgentRow> = {}): RuntimeWorktreeA
|
||||
describe('agentDotState', () => {
|
||||
it('maps known states through and unknown to idle', () => {
|
||||
expect(agentDotState(row({ state: 'working', updatedAt: 0 }), 0)).toBe('working')
|
||||
expect(
|
||||
agentDotState(row({ state: 'working', workingMode: 'monitoring', updatedAt: 0 }), 0)
|
||||
).toBe('monitoring')
|
||||
expect(agentDotState(row({ state: 'blocked', updatedAt: 0 }), 0)).toBe('blocked')
|
||||
expect(agentDotState(row({ state: 'waiting', updatedAt: 0 }), 0)).toBe('waiting')
|
||||
expect(agentDotState(row({ state: 'done', updatedAt: 0 }), 0)).toBe('done')
|
||||
@@ -65,6 +68,12 @@ describe('agentDisplayLabel', () => {
|
||||
expect(agentDisplayLabel(row({ state: 'working', prompt: '', updatedAt: 0 }), 0)).toBe(
|
||||
'Working'
|
||||
)
|
||||
expect(
|
||||
agentDisplayLabel(
|
||||
row({ state: 'working', workingMode: 'monitoring', prompt: '', updatedAt: 0 }),
|
||||
0
|
||||
)
|
||||
).toBe('Monitoring background tasks')
|
||||
})
|
||||
|
||||
it('falls back to the decayed state label when stale', () => {
|
||||
|
||||
@@ -9,23 +9,34 @@ export const AGENT_STATUS_STALE_AFTER_MS = 30 * 60 * 1000
|
||||
// Mirrors the desktop AgentStateDot vocabulary. The wire `state` is the agent
|
||||
// status state; 'blocked'/'waiting' read as attention states, 'done' as
|
||||
// complete, everything else idle.
|
||||
export type AgentDotState = 'working' | 'blocked' | 'waiting' | 'done' | 'idle' | 'interrupted'
|
||||
export type AgentDotState =
|
||||
| 'working'
|
||||
| 'monitoring'
|
||||
| 'blocked'
|
||||
| 'waiting'
|
||||
| 'done'
|
||||
| 'idle'
|
||||
| 'interrupted'
|
||||
|
||||
export function agentDotState(
|
||||
row: Pick<RuntimeWorktreeAgentRow, 'state' | 'interrupted' | 'updatedAt'>,
|
||||
row: Pick<RuntimeWorktreeAgentRow, 'state' | 'workingMode' | 'interrupted' | 'updatedAt'>,
|
||||
now: number
|
||||
): AgentDotState {
|
||||
if (row.interrupted) {
|
||||
return 'interrupted'
|
||||
}
|
||||
switch (row.state) {
|
||||
case 'working':
|
||||
case 'blocked':
|
||||
case 'waiting':
|
||||
// Why: an agent that exits without a final report would otherwise read as
|
||||
// active forever. Decay a stale active state to idle, matching desktop's
|
||||
// renderer-side staleness decay (worktree-agent-rows.ts).
|
||||
return now - row.updatedAt > AGENT_STATUS_STALE_AFTER_MS ? 'idle' : row.state
|
||||
case 'working':
|
||||
if (now - row.updatedAt > AGENT_STATUS_STALE_AFTER_MS) {
|
||||
return 'idle'
|
||||
}
|
||||
return row.workingMode === 'monitoring' ? 'monitoring' : 'working'
|
||||
case 'done':
|
||||
return 'done'
|
||||
}
|
||||
@@ -37,6 +48,8 @@ export function agentStateLabel(state: AgentDotState): string {
|
||||
switch (state) {
|
||||
case 'working':
|
||||
return 'Working'
|
||||
case 'monitoring':
|
||||
return 'Monitoring background tasks'
|
||||
case 'blocked':
|
||||
return 'Blocked'
|
||||
case 'waiting':
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ExecutionHostId } from '../../../src/shared/execution-host'
|
||||
import type { AgentWorkingMode } from '../../../src/shared/agent-status-types'
|
||||
import type { RuntimeWorktreeAgentRow } from '../../../src/shared/runtime-types'
|
||||
|
||||
export type Worktree = {
|
||||
@@ -45,6 +46,7 @@ export type Worktree = {
|
||||
linkedGitLabIssue?: number | null
|
||||
comment?: string
|
||||
status?: 'working' | 'active' | 'permission' | 'done' | 'inactive'
|
||||
workingMode?: AgentWorkingMode
|
||||
agents?: RuntimeWorktreeAgentRow[]
|
||||
}
|
||||
|
||||
|
||||
@@ -160,6 +160,20 @@ describe('areWorktreeListsEqual', () => {
|
||||
expect(areWorktreeListsEqual(first, second)).toBe(false)
|
||||
})
|
||||
|
||||
it('detects monitoring mode changes within working', () => {
|
||||
const first = [worktree({ agents: [agent({ state: 'working' })] })]
|
||||
const second = [worktree({ agents: [agent({ state: 'working', workingMode: 'monitoring' })] })]
|
||||
|
||||
expect(areWorktreeListsEqual(first, second)).toBe(false)
|
||||
})
|
||||
|
||||
it('detects workspace monitoring mode changes within working', () => {
|
||||
const first = [worktree({ status: 'working' })]
|
||||
const second = [worktree({ status: 'working', workingMode: 'monitoring' })]
|
||||
|
||||
expect(areWorktreeListsEqual(first, second)).toBe(false)
|
||||
})
|
||||
|
||||
it('treats missing and empty agent arrays as equivalent for rendering', () => {
|
||||
const first = [worktree({ agents: undefined })]
|
||||
const second = [worktree({ agents: [] })]
|
||||
|
||||
@@ -55,6 +55,7 @@ function areWorktreesEqual(left: Worktree, right: Worktree): boolean {
|
||||
(left.linkedGitLabIssue ?? null) === (right.linkedGitLabIssue ?? null) &&
|
||||
(left.comment ?? '') === (right.comment ?? '') &&
|
||||
(left.status ?? null) === (right.status ?? null) &&
|
||||
(left.workingMode ?? null) === (right.workingMode ?? null) &&
|
||||
arePullRequestsEqual(left.linkedPR, right.linkedPR) &&
|
||||
areAgentRowsEqual(left.agents ?? [], right.agents ?? [])
|
||||
)
|
||||
@@ -102,6 +103,7 @@ function areAgentRowsEqual(
|
||||
a.paneKey !== b.paneKey ||
|
||||
a.parentPaneKey !== b.parentPaneKey ||
|
||||
a.state !== b.state ||
|
||||
a.workingMode !== b.workingMode ||
|
||||
a.agentType !== b.agentType ||
|
||||
a.prompt !== b.prompt ||
|
||||
a.lastAssistantMessage !== b.lastAssistantMessage ||
|
||||
|
||||
@@ -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",
|
||||
|
||||
Generated
+3
-3
@@ -27,7 +27,7 @@ patchedDependencies:
|
||||
hash: 7333b3837f80a7fbd045964db6d76ba4fc118e49134bdbabb00585b6b7b60673
|
||||
path: config/patches/lint-staged@16.4.0.patch
|
||||
node-pty@1.1.0:
|
||||
hash: 710d5c74d1b738c41316e997e7cb860b61147604f98380ccf4f5bb20b6ed0ac5
|
||||
hash: 9c665d9e41571341cb8986607d531b953a7f32c0dd60e1e74e633c098d80f2c1
|
||||
path: config/patches/node-pty@1.1.0.patch
|
||||
|
||||
importers:
|
||||
@@ -69,7 +69,7 @@ importers:
|
||||
version: 3.3.1
|
||||
node-pty:
|
||||
specifier: ^1.1.0
|
||||
version: 1.1.0(patch_hash=710d5c74d1b738c41316e997e7cb860b61147604f98380ccf4f5bb20b6ed0ac5)
|
||||
version: 1.1.0(patch_hash=9c665d9e41571341cb8986607d531b953a7f32c0dd60e1e74e633c098d80f2c1)
|
||||
posthog-node:
|
||||
specifier: ^5.33.3
|
||||
version: 5.33.3
|
||||
@@ -12046,7 +12046,7 @@ snapshots:
|
||||
|
||||
node-int64@0.4.0: {}
|
||||
|
||||
node-pty@1.1.0(patch_hash=710d5c74d1b738c41316e997e7cb860b61147604f98380ccf4f5bb20b6ed0ac5):
|
||||
node-pty@1.1.0(patch_hash=9c665d9e41571341cb8986607d531b953a7f32c0dd60e1e74e633c098d80f2c1):
|
||||
dependencies:
|
||||
node-addon-api: 7.1.1
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ const {
|
||||
resolveCliCommandMock,
|
||||
rmSyncMock,
|
||||
spawnMock,
|
||||
stdioForWindowsInteractiveChildMock,
|
||||
writeKeychainMock
|
||||
} = vi.hoisted(() => ({
|
||||
deleteKeychainMock: vi.fn(),
|
||||
@@ -20,6 +21,7 @@ const {
|
||||
resolveCliCommandMock: vi.fn(),
|
||||
rmSyncMock: vi.fn(),
|
||||
spawnMock: vi.fn(),
|
||||
stdioForWindowsInteractiveChildMock: vi.fn(),
|
||||
writeKeychainMock: vi.fn()
|
||||
}))
|
||||
|
||||
@@ -45,6 +47,9 @@ vi.mock('../../shared/node-cli-command-resolution', () => ({
|
||||
getVersionManagerBinPaths: getVersionManagerBinPathsMock,
|
||||
resolveCliCommand: resolveCliCommandMock
|
||||
}))
|
||||
vi.mock('../../shared/windows-console-input', () => ({
|
||||
stdioForWindowsInteractiveChild: stdioForWindowsInteractiveChildMock
|
||||
}))
|
||||
|
||||
import { ACCOUNT_HANDLERS } from './account'
|
||||
import type { HandlerContext } from '../dispatch'
|
||||
@@ -105,6 +110,10 @@ describe('account CLI handlers', () => {
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(process, 'platform', originalPlatform)
|
||||
spawnMock.mockReset().mockImplementation(() => successfulChild())
|
||||
stdioForWindowsInteractiveChildMock.mockReset().mockImplementation((json: boolean) => ({
|
||||
stdio: ['inherit', json ? process.stderr : 'inherit', 'inherit'],
|
||||
dispose: vi.fn()
|
||||
}))
|
||||
resolveCliCommandMock.mockReset().mockImplementation((command: string) => command)
|
||||
getVersionManagerBinPathsMock.mockReset().mockReturnValue([])
|
||||
readKeychainMock.mockReset().mockResolvedValue(null)
|
||||
@@ -159,6 +168,56 @@ describe('account CLI handlers', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('passes Windows console device handles to the login child instead of inheriting Electron stdio', async () => {
|
||||
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
|
||||
const dispose = vi.fn()
|
||||
stdioForWindowsInteractiveChildMock.mockReturnValue({
|
||||
stdio: [11, 'inherit', 'inherit'],
|
||||
dispose
|
||||
})
|
||||
|
||||
await ACCOUNT_HANDLERS['account add'](context('codex'))
|
||||
|
||||
expect(spawnMock).toHaveBeenCalledWith(
|
||||
'codex',
|
||||
['login', '--device-auth'],
|
||||
expect.objectContaining({ stdio: [11, 'inherit', 'inherit'] })
|
||||
)
|
||||
expect(dispose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('disposes the Windows console input fd when spawn throws synchronously', async () => {
|
||||
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
|
||||
const dispose = vi.fn()
|
||||
stdioForWindowsInteractiveChildMock.mockReturnValue({
|
||||
stdio: [11, 'inherit', 'inherit'],
|
||||
dispose
|
||||
})
|
||||
spawnMock.mockImplementationOnce(() => {
|
||||
throw new Error('invalid stdio')
|
||||
})
|
||||
|
||||
await expect(ACCOUNT_HANDLERS['account add'](context('codex'))).rejects.toThrow('invalid stdio')
|
||||
|
||||
expect(dispose).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('keeps JSON login prompts off the CLI stdout envelope when console fds are attached', async () => {
|
||||
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
|
||||
stdioForWindowsInteractiveChildMock.mockReturnValue({
|
||||
stdio: [11, process.stderr, 'inherit'],
|
||||
dispose: vi.fn()
|
||||
})
|
||||
|
||||
await ACCOUNT_HANDLERS['account add'](context('codex', true))
|
||||
|
||||
expect(spawnMock).toHaveBeenCalledWith(
|
||||
'codex',
|
||||
['login', '--device-auth'],
|
||||
expect.objectContaining({ stdio: [11, process.stderr, 'inherit'] })
|
||||
)
|
||||
})
|
||||
|
||||
it('routes Windows package-manager shims through the safe cmd launcher', async () => {
|
||||
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
|
||||
resolveCliCommandMock.mockReturnValue('C:\\tools\\codex.cmd')
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
UnsafeWindowsBatchArgumentsError,
|
||||
WINDOWS_BATCH_UNSAFE_CHARACTERS_LABEL
|
||||
} from '../../shared/windows-batch-spawn'
|
||||
import { stdioForWindowsInteractiveChild } from '../../shared/windows-console-input'
|
||||
import { ACCOUNT_IMPORT_RUNTIME_CAPABILITY } from '../../shared/protocol-version'
|
||||
import type { RuntimeStatus } from '../../shared/runtime-types'
|
||||
import type {
|
||||
@@ -113,12 +114,18 @@ async function runAgentLoginInTerminal(
|
||||
return
|
||||
}
|
||||
const env = addAgentNodePaths({ ...stripElectronRunAsNode(process.env), ...extraEnv })
|
||||
const child = spawn(spawnCmd, spawnArgs, {
|
||||
// Why: JSON mode reserves stdout for the response envelope while keeping
|
||||
// the interactive login attached to the user's terminal via stderr.
|
||||
stdio: ['inherit', json ? process.stderr : 'inherit', 'inherit'],
|
||||
env
|
||||
})
|
||||
const consoleStdio = stdioForWindowsInteractiveChild(json)
|
||||
let child: ReturnType<typeof spawn>
|
||||
try {
|
||||
child = spawn(spawnCmd, spawnArgs, {
|
||||
// Why: JSON mode reserves stdout for the response envelope while keeping
|
||||
// the interactive login attached to the user's terminal via stderr.
|
||||
stdio: consoleStdio.stdio,
|
||||
env
|
||||
})
|
||||
} finally {
|
||||
consoleStdio.dispose()
|
||||
}
|
||||
session.child = child
|
||||
child.once('error', (error) =>
|
||||
rejectPromise(
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('../format', () => ({ printResult: vi.fn() }))
|
||||
|
||||
import { printResult } from '../format'
|
||||
import { HANDLER_GROUPS } from '../handler-group-manifest'
|
||||
import { ORCHESTRATION_HANDLERS } from './orchestration'
|
||||
import {
|
||||
ORCHESTRATION_DISPATCH_HANDLER,
|
||||
ORCHESTRATION_DISPATCH_INSPECTION_HANDLERS
|
||||
} from './orchestration/dispatch-handlers'
|
||||
import { getOptionalStructuredMessagePayload } from './orchestration/message-payload'
|
||||
import { getOptionalPositiveIntegerValueFlag } from './orchestration/numeric-flags'
|
||||
import { formatWorkerRead, formatWorkerRelease } from './orchestration/worker-output'
|
||||
|
||||
describe('extracted orchestration flag parsing', () => {
|
||||
it('serializes phase and omits empty CSV entries', () => {
|
||||
const payload = getOptionalStructuredMessagePayload(
|
||||
new Map([
|
||||
['phase', 'verification'],
|
||||
['files-modified', ' src/a.ts, ,src/b.ts, ']
|
||||
])
|
||||
)
|
||||
|
||||
expect(JSON.parse(payload ?? '')).toEqual({
|
||||
filesModified: ['src/a.ts', 'src/b.ts'],
|
||||
phase: 'verification'
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects unsafe positive integers before dispatch', () => {
|
||||
expect(() =>
|
||||
getOptionalPositiveIntegerValueFlag(
|
||||
new Map([['timeout-ms', '9007199254740992']]),
|
||||
'timeout-ms'
|
||||
)
|
||||
).toThrow('Invalid positive safe integer for --timeout-ms')
|
||||
})
|
||||
})
|
||||
|
||||
it('composes handlers in the canonical command order', () => {
|
||||
const declared = HANDLER_GROUPS.find((group) => group.name === 'orchestration')?.keys
|
||||
expect(Object.keys(ORCHESTRATION_HANDLERS)).toEqual(declared)
|
||||
})
|
||||
|
||||
describe('extracted orchestration worker formatting', () => {
|
||||
it('renders terminal tails without changing line boundaries', () => {
|
||||
expect(
|
||||
formatWorkerRead({
|
||||
dispatchId: 'dispatch_1',
|
||||
terminal: { tail: ['first', '', 'third'] }
|
||||
} as never)
|
||||
).toBe('first\n\nthird')
|
||||
})
|
||||
|
||||
it('renders transcript blocks and survives unserializable tool input', () => {
|
||||
const circular: { self?: unknown } = {}
|
||||
circular.self = circular
|
||||
|
||||
expect(
|
||||
formatWorkerRead({
|
||||
source: 'transcript',
|
||||
transcript: {
|
||||
messages: [
|
||||
{
|
||||
id: 'message_1',
|
||||
role: 'assistant',
|
||||
blocks: [
|
||||
{ type: 'text', text: 'working' },
|
||||
{ type: 'tool-call', name: 'inspect', input: circular },
|
||||
{ type: 'tool-result', output: 'failed', isError: true },
|
||||
{ type: 'image-ref', url: 'https://example.test/proof.png' }
|
||||
],
|
||||
timestamp: null,
|
||||
source: 'transcript'
|
||||
}
|
||||
]
|
||||
}
|
||||
} as never)
|
||||
).toBe(
|
||||
'[assistant] working\n[tool inspect] [unserializable input]\n[tool result error] failed\n[image] https://example.test/proof.png'
|
||||
)
|
||||
})
|
||||
|
||||
it('renders release evidence in receipt order', () => {
|
||||
expect(
|
||||
formatWorkerRelease({
|
||||
dispatchId: 'dispatch_1',
|
||||
state: 'release_unknown',
|
||||
reason: 'host_unreachable',
|
||||
processAction: 'unverifiable',
|
||||
archive: { source: 'transcript', status: 'saved' },
|
||||
lastError: 'transport closed',
|
||||
recovery: 'Reconnect and retry.'
|
||||
})
|
||||
).toBe(
|
||||
'Worker dispatch_1 terminal [release_unknown] reason=host_unreachable process=unverifiable\n' +
|
||||
'archive transcript [saved]\ntransport closed\nReconnect and retry.'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('extracted orchestration dispatch handlers', () => {
|
||||
const call = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
call.mockReset()
|
||||
vi.mocked(printResult).mockReset()
|
||||
})
|
||||
|
||||
it('allows a dry run without a recipient and returns only its preamble', async () => {
|
||||
call.mockResolvedValue({
|
||||
result: { dispatch: null, dryRun: true, preamble: 'preview preamble' }
|
||||
})
|
||||
|
||||
await ORCHESTRATION_DISPATCH_HANDLER['orchestration dispatch']({
|
||||
flags: new Map<string, string | boolean>([
|
||||
['task', 'task_1'],
|
||||
['from', 'terminal_coordinator'],
|
||||
['dry-run', true],
|
||||
['return-preamble', true]
|
||||
]),
|
||||
client: { call },
|
||||
cwd: '/repo',
|
||||
json: false
|
||||
} as never)
|
||||
|
||||
expect(call).toHaveBeenCalledWith('orchestration.dispatch', {
|
||||
task: 'task_1',
|
||||
run: undefined,
|
||||
to: undefined,
|
||||
from: 'terminal_coordinator',
|
||||
inject: undefined,
|
||||
dryRun: true,
|
||||
returnPreamble: true,
|
||||
devMode: false
|
||||
})
|
||||
expect(renderedValue({ dispatch: null, dryRun: true, preamble: 'preview preamble' })).toBe(
|
||||
'preview preamble'
|
||||
)
|
||||
})
|
||||
|
||||
it('does not resolve coordinator identity for a non-preamble dispatch lookup', async () => {
|
||||
call.mockResolvedValue({ result: { dispatch: null } })
|
||||
|
||||
await ORCHESTRATION_DISPATCH_INSPECTION_HANDLERS['orchestration dispatch-show']({
|
||||
flags: new Map([['task', 'task_1']]),
|
||||
client: { call },
|
||||
cwd: '/repo',
|
||||
json: false
|
||||
} as never)
|
||||
|
||||
expect(call).toHaveBeenCalledWith('orchestration.dispatchShow', {
|
||||
task: 'task_1',
|
||||
preamble: undefined,
|
||||
from: undefined,
|
||||
devMode: false
|
||||
})
|
||||
expect(renderedValue({ dispatch: null })).toBe('No dispatch context found.')
|
||||
})
|
||||
})
|
||||
|
||||
function renderedValue(value: unknown): string {
|
||||
const formatter = vi.mocked(printResult).mock.calls[0]?.[2] as (result: unknown) => string
|
||||
return formatter(value)
|
||||
}
|
||||
+27
-1322
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,32 @@
|
||||
const DEFAULT_KEEPALIVE_INTERVAL_MS = 15_000
|
||||
|
||||
// Why: test-only escape hatch so subprocess tests avoid the full 15 s window; bogus values fall back to the default.
|
||||
function resolveKeepaliveIntervalMs(): number {
|
||||
const raw = process.env.ORCA_KEEPALIVE_INTERVAL_MS ?? process.env.ORCA_HEARTBEAT_INTERVAL_MS
|
||||
if (!raw) {
|
||||
return DEFAULT_KEEPALIVE_INTERVAL_MS
|
||||
}
|
||||
const parsed = Number(raw)
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) {
|
||||
return DEFAULT_KEEPALIVE_INTERVAL_MS
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
export function startCheckKeepalive(deadlineMs: number | undefined): () => void {
|
||||
const startedAt = Date.now()
|
||||
const interval = setInterval(() => {
|
||||
const payload = {
|
||||
_keepalive: true,
|
||||
// Why: retain the old marker for scripts still filtering it while callers migrate to _keepalive.
|
||||
_heartbeat: true,
|
||||
elapsedMs: Date.now() - startedAt,
|
||||
deadlineMs: deadlineMs ?? null
|
||||
}
|
||||
process.stderr.write(`${JSON.stringify(payload)}\n`)
|
||||
}, resolveKeepaliveIntervalMs())
|
||||
if (typeof interval.unref === 'function') {
|
||||
interval.unref()
|
||||
}
|
||||
return () => clearInterval(interval)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import type { CommandHandler } from '../../dispatch'
|
||||
import { printResult } from '../../format'
|
||||
import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags'
|
||||
import { RuntimeClientError } from '../../runtime-client'
|
||||
import { orchestrationMigrationData } from '../../../shared/orchestration-rpc-contract'
|
||||
import { callOrchestrationMutation } from './mutation-request'
|
||||
import { isDevCliInvocation } from './runtime-compatibility'
|
||||
import { resolveCoordinatorTerminalHandle } from './terminal-identity'
|
||||
|
||||
export const ORCHESTRATION_DISPATCH_HANDLER: Record<string, CommandHandler> = {
|
||||
'orchestration dispatch': async ({ flags, client, cwd, json }) => {
|
||||
const from = await resolveCoordinatorTerminalHandle(flags, cwd, client)
|
||||
const dryRun = flags.has('dry-run') ? true : undefined
|
||||
const returnPreamble = flags.has('return-preamble') ? true : undefined
|
||||
// Why: --to is only required for non-dry-run; the RPC handler re-enforces.
|
||||
const to = dryRun ? getOptionalStringFlag(flags, 'to') : getRequiredStringFlag(flags, 'to')
|
||||
const result = await callOrchestrationMutation<{
|
||||
dispatch: { id: string; task_id: string; status: string } | null
|
||||
injected?: boolean
|
||||
dryRun?: boolean
|
||||
preamble?: string
|
||||
}>(client, flags, 'orchestration.dispatch', {
|
||||
task: getRequiredStringFlag(flags, 'task'),
|
||||
run: getOptionalStringFlag(flags, 'run'),
|
||||
to,
|
||||
from,
|
||||
inject: flags.has('inject') ? true : undefined,
|
||||
dryRun,
|
||||
returnPreamble,
|
||||
devMode: isDevCliInvocation()
|
||||
})
|
||||
printResult(result, json, (value) => {
|
||||
if (value.dryRun) {
|
||||
return value.preamble ?? ''
|
||||
}
|
||||
const base = `Dispatched ${value.dispatch?.task_id} -> ${value.dispatch?.id} [${value.dispatch?.status}]`
|
||||
return value.preamble ? `${base}\n\n--- Preamble ---\n${value.preamble}` : base
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export const ORCHESTRATION_DISPATCH_INSPECTION_HANDLERS: Record<string, CommandHandler> = {
|
||||
'orchestration dispatch-show': async ({ flags, client, cwd, json }) => {
|
||||
const showPreamble = flags.has('preamble') ? true : undefined
|
||||
// Why: a preview must embed the same real coordinator handle as an actual dispatch.
|
||||
const from = showPreamble
|
||||
? await resolveCoordinatorTerminalHandle(flags, cwd, client)
|
||||
: undefined
|
||||
const result = await client.call<{
|
||||
dispatch: { id: string; task_id: string; status: string } | null
|
||||
preamble?: string
|
||||
}>('orchestration.dispatchShow', {
|
||||
task: getRequiredStringFlag(flags, 'task'),
|
||||
preamble: showPreamble,
|
||||
from,
|
||||
devMode: isDevCliInvocation()
|
||||
})
|
||||
printResult(result, json, (value) => {
|
||||
if (value.preamble && showPreamble) {
|
||||
return value.preamble
|
||||
}
|
||||
if (!value.dispatch) {
|
||||
return 'No dispatch context found.'
|
||||
}
|
||||
return `${value.dispatch.id} task=${value.dispatch.task_id} [${value.dispatch.status}]`
|
||||
})
|
||||
},
|
||||
|
||||
'orchestration coordinator-start': async () => {
|
||||
throw new RuntimeClientError(
|
||||
'orchestration_migration_required',
|
||||
'The legacy automatic coordinator command is retired. No effects were applied.',
|
||||
orchestrationMigrationData('command_retired')
|
||||
)
|
||||
},
|
||||
|
||||
'orchestration coordinator-stop': async () => {
|
||||
throw new RuntimeClientError(
|
||||
'orchestration_migration_required',
|
||||
'The legacy automatic coordinator command is retired. No effects were applied.',
|
||||
orchestrationMigrationData('command_retired')
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import type { CommandHandler } from '../../dispatch'
|
||||
import { printResult } from '../../format'
|
||||
import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags'
|
||||
import { callOrchestrationMutation } from './mutation-request'
|
||||
import { resolveCoordinatorTerminalHandle } from './terminal-identity'
|
||||
|
||||
export const ORCHESTRATION_GATE_HANDLERS: Record<string, CommandHandler> = {
|
||||
'orchestration gate-create': async ({ flags, client, cwd, json }) => {
|
||||
const result = await callOrchestrationMutation<{
|
||||
gate: { id: string; task_id: string; status: string }
|
||||
}>(client, flags, 'orchestration.gateCreate', {
|
||||
task: getRequiredStringFlag(flags, 'task'),
|
||||
question: getRequiredStringFlag(flags, 'question'),
|
||||
options: getOptionalStringFlag(flags, 'options'),
|
||||
// Why: gates are Run-scoped, so the coordinator handle is the authorized caller identity.
|
||||
from: await resolveCoordinatorTerminalHandle(flags, cwd, client)
|
||||
})
|
||||
printResult(
|
||||
result,
|
||||
json,
|
||||
(value) =>
|
||||
`Gate ${value.gate.id} created for task ${value.gate.task_id} [${value.gate.status}]`
|
||||
)
|
||||
},
|
||||
|
||||
'orchestration gate-resolve': async ({ flags, client, cwd, json }) => {
|
||||
const result = await callOrchestrationMutation<{
|
||||
gate: { id: string; task_id: string; status: string; resolution: string }
|
||||
}>(client, flags, 'orchestration.gateResolve', {
|
||||
id: getRequiredStringFlag(flags, 'id'),
|
||||
resolution: getRequiredStringFlag(flags, 'resolution'),
|
||||
from: await resolveCoordinatorTerminalHandle(flags, cwd, client)
|
||||
})
|
||||
printResult(result, json, (value) => `Gate ${value.gate.id} resolved: ${value.gate.resolution}`)
|
||||
},
|
||||
|
||||
'orchestration gate-list': async ({ flags, client, cwd, json }) => {
|
||||
const run = getOptionalStringFlag(flags, 'run')
|
||||
// Why: named runs remain inspectable without a pane; only implicit runs resolve identity.
|
||||
const from = run ? undefined : await resolveCoordinatorTerminalHandle(flags, cwd, client)
|
||||
const result = await client.call<{
|
||||
gates: { id: string; task_id: string; question: string; status: string }[]
|
||||
count: number
|
||||
runId?: string
|
||||
}>('orchestration.gateList', {
|
||||
task: getOptionalStringFlag(flags, 'task'),
|
||||
status: getOptionalStringFlag(flags, 'status'),
|
||||
run,
|
||||
from
|
||||
})
|
||||
printResult(result, json, (value) => {
|
||||
if (value.gates.length === 0) {
|
||||
return 'No gates found.'
|
||||
}
|
||||
return value.gates
|
||||
.map((gate) => `${gate.id} task=${gate.task_id} [${gate.status}] "${gate.question}"`)
|
||||
.join('\n')
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import type { CommandHandler } from '../../dispatch'
|
||||
import { printResult } from '../../format'
|
||||
import { getOptionalStringFlag } from '../../flags'
|
||||
import { RuntimeClientError } from '../../runtime-client'
|
||||
import type { RuntimeRpcSuccess } from '../../runtime-client'
|
||||
import {
|
||||
formatOrchestrationCheckText,
|
||||
prepareOrchestrationCheckOutput,
|
||||
type LegacyCompatibilityResult,
|
||||
type OrchestrationMessageSummary as MessageSummary
|
||||
} from '../../../shared/orchestration-check-output'
|
||||
import { startCheckKeepalive } from './check-keepalive'
|
||||
import { callOrchestrationMutation } from './mutation-request'
|
||||
import { getOptionalPositiveIntegerValueFlag } from './numeric-flags'
|
||||
import { flushOrchestrationStdout, resolveCompatibilityCliCommand } from './runtime-compatibility'
|
||||
import { resolveOrchestrationTerminalHandle } from './terminal-identity'
|
||||
|
||||
type CheckResult = {
|
||||
messages: MessageSummary[]
|
||||
count: number
|
||||
formatted?: string
|
||||
deliveryId?: string | null
|
||||
runId?: string
|
||||
timedOut?: boolean
|
||||
cancelled?: boolean
|
||||
connectionLost?: boolean
|
||||
legacyCompatibility?: LegacyCompatibilityResult
|
||||
}
|
||||
|
||||
export const ORCHESTRATION_CHECK_HANDLER: Record<string, CommandHandler> = {
|
||||
'orchestration check': async ({ flags, client, cwd, json }) => {
|
||||
const wait = flags.has('wait')
|
||||
const peek = flags.has('peek')
|
||||
// Why: older runtimes strip unknown peek and run --unread --peek as destructive mark-read.
|
||||
if ([flags.has('unread'), peek, flags.has('all')].filter(Boolean).length > 1) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'Choose at most one message read mode: --unread, --peek, or --all.'
|
||||
)
|
||||
}
|
||||
const timeoutMs = getOptionalPositiveIntegerValueFlag(flags, 'timeout-ms')
|
||||
const explicitTerminal = getOptionalStringFlag(flags, 'terminal')
|
||||
const terminal = await resolveOrchestrationTerminalHandle(flags, cwd, client, 'terminal')
|
||||
const stopKeepalive = wait ? startCheckKeepalive(timeoutMs) : null
|
||||
let result: Awaited<ReturnType<typeof client.call<CheckResult>>>
|
||||
try {
|
||||
result = await callOrchestrationMutation<CheckResult>(client, flags, 'orchestration.check', {
|
||||
terminal,
|
||||
terminalPaneKey: explicitTerminal ? undefined : process.env.ORCA_PANE_KEY || undefined,
|
||||
// Why: old runtimes degrade peek to non-consuming all mode instead of destructive mark-read.
|
||||
unread: flags.has('unread') ? true : peek ? false : undefined,
|
||||
peek: peek ? true : undefined,
|
||||
all: flags.has('all') ? true : undefined,
|
||||
types: getOptionalStringFlag(flags, 'types'),
|
||||
format: flags.has('format') ? true : undefined,
|
||||
inject: flags.has('inject') ? true : undefined,
|
||||
compatibilityCliCommand: resolveCompatibilityCliCommand(),
|
||||
run: getOptionalStringFlag(flags, 'run'),
|
||||
ack: getOptionalStringFlag(flags, 'ack'),
|
||||
wait: wait ? true : undefined,
|
||||
timeoutMs
|
||||
})
|
||||
} finally {
|
||||
stopKeepalive?.()
|
||||
}
|
||||
if (peek) {
|
||||
result = filterLegacyPeekResult(result, wait)
|
||||
}
|
||||
result = {
|
||||
...result,
|
||||
result: prepareOrchestrationCheckOutput(result.result, terminal, flags.has('format'))
|
||||
}
|
||||
printResult(result, json, (value) => formatOrchestrationCheckText(value, terminal))
|
||||
const compatibilityAck = result.result.legacyCompatibility?.ackMessageIds
|
||||
if (compatibilityAck && compatibilityAck.length > 0) {
|
||||
await flushOrchestrationStdout()
|
||||
await client.call('orchestration.check', {
|
||||
terminal,
|
||||
compatibilityAck: JSON.stringify({
|
||||
messageIds: compatibilityAck,
|
||||
types: getOptionalStringFlag(flags, 'types')
|
||||
?.split(',')
|
||||
.map((type) => type.trim())
|
||||
.filter(Boolean)
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function filterLegacyPeekResult(
|
||||
result: RuntimeRpcSuccess<CheckResult>,
|
||||
wait: boolean
|
||||
): RuntimeRpcSuccess<CheckResult> {
|
||||
const rawRowCount = result.result.messages.length
|
||||
const unreadOnly = result.result.messages.filter((message) => message.read !== 1)
|
||||
const removedReadRows = unreadOnly.length !== rawRowCount
|
||||
// Why: read rows prove a pre-peek runtime cannot honor wait, so fail instead of returning early.
|
||||
if (wait && removedReadRows && unreadOnly.length === 0) {
|
||||
throw new RuntimeClientError(
|
||||
'peek_wait_unsupported',
|
||||
'The connected runtime does not support --peek with --wait; upgrade the runtime or use --wait without --peek.'
|
||||
)
|
||||
}
|
||||
if (removedReadRows && rawRowCount >= 100) {
|
||||
console.error(
|
||||
'Warning: this runtime returned only its newest 100 messages for --peek; older unread messages may be missing. Upgrade the runtime for exact peek results.'
|
||||
)
|
||||
}
|
||||
return {
|
||||
...result,
|
||||
result: {
|
||||
...result.result,
|
||||
// Why: a pre-peek runtime formats all rows, which no longer matches the filtered set.
|
||||
...(removedReadRows ? { formatted: undefined } : {}),
|
||||
messages: unreadOnly,
|
||||
count: unreadOnly.length
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { CommandHandler } from '../../dispatch'
|
||||
import { printResult } from '../../format'
|
||||
import {
|
||||
getOptionalPositiveIntegerFlag,
|
||||
getOptionalStringFlag,
|
||||
getRequiredStringFlag
|
||||
} from '../../flags'
|
||||
import {
|
||||
formatMessageReadOnlyTag,
|
||||
type OrchestrationMessageSummary as MessageSummary
|
||||
} from '../../../shared/orchestration-check-output'
|
||||
import { callOrchestrationMutation } from './mutation-request'
|
||||
import { resolveOrchestrationTerminalHandle } from './terminal-identity'
|
||||
|
||||
export const ORCHESTRATION_INBOX_HANDLERS: Record<string, CommandHandler> = {
|
||||
'orchestration reply': async ({ flags, client, cwd, json }) => {
|
||||
const from = await resolveOrchestrationTerminalHandle(flags, cwd, client, 'from')
|
||||
const result = await callOrchestrationMutation<{ message: { id: string } }>(
|
||||
client,
|
||||
flags,
|
||||
'orchestration.reply',
|
||||
{
|
||||
id: getRequiredStringFlag(flags, 'id'),
|
||||
body: getRequiredStringFlag(flags, 'body'),
|
||||
run: getOptionalStringFlag(flags, 'run'),
|
||||
from
|
||||
}
|
||||
)
|
||||
printResult(result, json, (value) => `Replied ${value.message.id}`)
|
||||
},
|
||||
|
||||
'orchestration inbox': async ({ flags, client, json }) => {
|
||||
const full = flags.has('full')
|
||||
const result = await client.call<{
|
||||
messages: MessageSummary[]
|
||||
count: number
|
||||
}>('orchestration.inbox', {
|
||||
limit: getOptionalPositiveIntegerFlag(flags, 'limit'),
|
||||
terminal: getOptionalStringFlag(flags, 'terminal')
|
||||
})
|
||||
printResult(result, json, (value) => {
|
||||
if (value.count === 0) {
|
||||
return 'No messages.'
|
||||
}
|
||||
// Why: default output omits body/payload for at-a-glance sweeps; --full prints them for auditing.
|
||||
return value.messages
|
||||
.map((message) => {
|
||||
const head = `${message.id}${formatMessageReadOnlyTag(message)} ${message.from_handle} -> ${message.to_handle ?? '?'}: "${message.subject}"`
|
||||
if (!full) {
|
||||
return head
|
||||
}
|
||||
const parts = [head]
|
||||
if (message.body && message.body.length > 0) {
|
||||
parts.push(message.body)
|
||||
}
|
||||
if (message.payload) {
|
||||
parts.push(`[payload] ${message.payload}`)
|
||||
}
|
||||
return parts.join('\n')
|
||||
})
|
||||
.join(full ? '\n\n' : '\n')
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { getOptionalStringFlag } from '../../flags'
|
||||
import { RuntimeClientError } from '../../runtime-client'
|
||||
|
||||
export function getOptionalStructuredMessagePayload(
|
||||
flags: Map<string, string | boolean>
|
||||
): string | undefined {
|
||||
const rawPayload = getOptionalStringFlag(flags, 'payload')
|
||||
const taskId = getOptionalStringFlag(flags, 'task-id')
|
||||
const dispatchId = getOptionalStringFlag(flags, 'dispatch-id')
|
||||
const outcome = getOptionalStringFlag(flags, 'outcome')
|
||||
const filesModified = getOptionalStringFlag(flags, 'files-modified')
|
||||
const reportPath = getOptionalStringFlag(flags, 'report-path')
|
||||
const phase = getOptionalStringFlag(flags, 'phase')
|
||||
const hasStructuredPayload =
|
||||
taskId !== undefined ||
|
||||
dispatchId !== undefined ||
|
||||
outcome !== undefined ||
|
||||
filesModified !== undefined ||
|
||||
reportPath !== undefined ||
|
||||
phase !== undefined
|
||||
if (!hasStructuredPayload) {
|
||||
return rawPayload
|
||||
}
|
||||
if (rawPayload !== undefined) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'Use either --payload or structured payload flags, not both.'
|
||||
)
|
||||
}
|
||||
// Why: raw JSON args are fragile in Windows PowerShell; these flags avoid shell-specific quoting.
|
||||
const payload: Record<string, string | string[]> = {}
|
||||
if (taskId) {
|
||||
payload.taskId = taskId
|
||||
}
|
||||
if (dispatchId) {
|
||||
payload.dispatchId = dispatchId
|
||||
}
|
||||
if (outcome) {
|
||||
if (outcome !== 'succeeded' && outcome !== 'failed') {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'Invalid --outcome. Expected succeeded or failed.'
|
||||
)
|
||||
}
|
||||
payload.outcome = outcome
|
||||
}
|
||||
if (filesModified) {
|
||||
payload.filesModified = filesModified
|
||||
.split(',')
|
||||
.map((file) => file.trim())
|
||||
.filter(Boolean)
|
||||
}
|
||||
if (reportPath) {
|
||||
payload.reportPath = reportPath
|
||||
}
|
||||
if (phase) {
|
||||
payload.phase = phase
|
||||
}
|
||||
return JSON.stringify(payload)
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import type { CommandHandler } from '../../dispatch'
|
||||
import { printResult } from '../../format'
|
||||
import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags'
|
||||
import { RuntimeClientError } from '../../runtime-client'
|
||||
import { requireWorkerDoneSettlement } from '../orchestration-worker-settlement'
|
||||
import { getOptionalStructuredMessagePayload } from './message-payload'
|
||||
import { callOrchestrationMutation } from './mutation-request'
|
||||
import { isDevCliInvocation } from './runtime-compatibility'
|
||||
import {
|
||||
resolveOrchestrationTerminalHandle,
|
||||
throwNoActiveSenderTerminal
|
||||
} from './terminal-identity'
|
||||
|
||||
type LifecycleSendResult =
|
||||
| {
|
||||
action: 'completed' | 'failed'
|
||||
authority?: 'run_home' | 'worker_server_legacy'
|
||||
}
|
||||
| { action: 'settled'; outcome: 'succeeded' | 'failed'; duplicate?: boolean }
|
||||
| { action: 'rejected'; code: string; reason: string }
|
||||
|
||||
type SendRecipientWarning = {
|
||||
code: string
|
||||
recipient: string
|
||||
message: string
|
||||
}
|
||||
|
||||
type OrchestrationSendResult =
|
||||
| {
|
||||
message: { id: string; run_id?: string }
|
||||
lifecycle?: LifecycleSendResult
|
||||
warnings?: SendRecipientWarning[]
|
||||
}
|
||||
| {
|
||||
messages: { id: string }[]
|
||||
recipients: number
|
||||
warnings?: SendRecipientWarning[]
|
||||
}
|
||||
| {
|
||||
relay: {
|
||||
messageId: string
|
||||
sequence: number
|
||||
dispatchId: string
|
||||
destination?: 'run_home' | 'worker'
|
||||
accepted: true
|
||||
}
|
||||
lifecycle?: LifecycleSendResult
|
||||
warnings?: SendRecipientWarning[]
|
||||
}
|
||||
|
||||
function getLifecycleGroupRecipientError(type: 'worker_done' | 'heartbeat'): string {
|
||||
return `${type} messages belong to one exact Dispatch and cannot target a group address.`
|
||||
}
|
||||
|
||||
function rejectLifecycleGroupRecipient(type: string | undefined, to: string): void {
|
||||
if ((type === 'worker_done' || type === 'heartbeat') && to.startsWith('@')) {
|
||||
throw new RuntimeClientError('invalid_argument', getLifecycleGroupRecipientError(type))
|
||||
}
|
||||
}
|
||||
|
||||
export const ORCHESTRATION_SEND_HANDLER: Record<string, CommandHandler> = {
|
||||
'orchestration send': async ({ flags, client, cwd, json }) => {
|
||||
const to = getOptionalStringFlag(flags, 'to')
|
||||
const type = getOptionalStringFlag(flags, 'type')
|
||||
if (to) {
|
||||
rejectLifecycleGroupRecipient(type, to)
|
||||
}
|
||||
const outcome = getOptionalStringFlag(flags, 'outcome')
|
||||
if (type !== 'worker_done' && outcome !== undefined) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'--outcome is only valid with --type worker_done.'
|
||||
)
|
||||
}
|
||||
if (
|
||||
(type === 'worker_done' || type === 'heartbeat') &&
|
||||
!getOptionalStringFlag(flags, 'from') &&
|
||||
!process.env.ORCA_TERMINAL_HANDLE
|
||||
) {
|
||||
// Why: focus isn't lifecycle authority — an identity-less subprocess must fail closed rather than guess the worker.
|
||||
throwNoActiveSenderTerminal()
|
||||
}
|
||||
|
||||
// Why: lifecycle senders preserve ORCA_TERMINAL_HANDLE across restarts for older runtimes.
|
||||
const from = await resolveOrchestrationTerminalHandle(flags, cwd, client, 'from')
|
||||
const sendParams = {
|
||||
from,
|
||||
to,
|
||||
run: getOptionalStringFlag(flags, 'run'),
|
||||
subject: getRequiredStringFlag(flags, 'subject'),
|
||||
body: getOptionalStringFlag(flags, 'body'),
|
||||
type,
|
||||
priority: getOptionalStringFlag(flags, 'priority'),
|
||||
threadId: getOptionalStringFlag(flags, 'thread-id'),
|
||||
payload: getOptionalStructuredMessagePayload(flags),
|
||||
// Why: pane key is the remint-stable sender identity the runtime verifies lifecycle ownership against; older runtimes strip it.
|
||||
senderPaneKey: process.env.ORCA_PANE_KEY || undefined,
|
||||
waitForLifecycleSettlement: type === 'worker_done' ? true : undefined,
|
||||
devMode: isDevCliInvocation()
|
||||
}
|
||||
const dispatchCapability = getOptionalStringFlag(flags, 'dispatch-capability')
|
||||
const result = await callOrchestrationMutation<OrchestrationSendResult>(
|
||||
client,
|
||||
flags,
|
||||
'orchestration.send',
|
||||
sendParams,
|
||||
dispatchCapability ? { orchestrationCapability: dispatchCapability } : undefined
|
||||
)
|
||||
await requireWorkerDoneSettlement(client, type, sendParams.payload, result.result)
|
||||
if ('lifecycle' in result.result && result.result.lifecycle?.action === 'rejected') {
|
||||
throw new RuntimeClientError(result.result.lifecycle.code, result.result.lifecycle.reason)
|
||||
}
|
||||
printResult(result, json, (value) => {
|
||||
const warnings = 'warnings' in value ? (value.warnings ?? []) : []
|
||||
const withWarnings = (line: string): string =>
|
||||
warnings.length > 0
|
||||
? [line, ...warnings.map((warning) => `Warning: ${warning.message}`)].join('\n')
|
||||
: line
|
||||
if ('message' in value) {
|
||||
return withWarnings(`Sent ${value.message.id}`)
|
||||
}
|
||||
if ('relay' in value) {
|
||||
if (value.relay.destination === 'worker') {
|
||||
return withWarnings(
|
||||
`Queued ${value.relay.messageId} for worker Dispatch ${value.relay.dispatchId}`
|
||||
)
|
||||
}
|
||||
return withWarnings(
|
||||
`Queued ${value.relay.messageId} for Run home (Dispatch ${value.relay.dispatchId})`
|
||||
)
|
||||
}
|
||||
return withWarnings(
|
||||
`Sent ${value.messages.length} messages to ${value.recipients} recipients`
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import type { RuntimeClient } from '../../runtime-client'
|
||||
import { getOptionalStringFlag } from '../../flags'
|
||||
import { orchestrationMutationRecoveryError } from '../../orchestration-mutation-recovery'
|
||||
|
||||
export function callOrchestrationMutation<TResult>(
|
||||
client: RuntimeClient,
|
||||
flags: Map<string, string | boolean>,
|
||||
method: string,
|
||||
params: unknown,
|
||||
options?: { timeoutMs?: number; orchestrationCapability?: string }
|
||||
) {
|
||||
const requestId = getOptionalStringFlag(flags, 'retry-request')
|
||||
const result = requestId
|
||||
? client.call<TResult>(method, params, { ...options, orchestrationRequestId: requestId })
|
||||
: options
|
||||
? client.call<TResult>(method, params, options)
|
||||
: client.call<TResult>(method, params)
|
||||
return result.catch((error) => {
|
||||
throw orchestrationMutationRecoveryError(error)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { parsePositiveSafeIntegerText } from '../../../shared/timer-delay'
|
||||
import { RuntimeClientError } from '../../runtime-client'
|
||||
|
||||
export function getOptionalPositiveIntegerValueFlag(
|
||||
flags: Map<string, string | boolean>,
|
||||
name: string
|
||||
): number | undefined {
|
||||
if (!flags.has(name)) {
|
||||
return undefined
|
||||
}
|
||||
const raw = flags.get(name)
|
||||
if (typeof raw !== 'string' || raw.length === 0) {
|
||||
throw new RuntimeClientError('invalid_argument', `Missing value for --${name}.`)
|
||||
}
|
||||
const value = parsePositiveSafeIntegerText(raw)
|
||||
if (value === null) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
`Invalid positive safe integer for --${name}: ${raw}`
|
||||
)
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import type { CommandHandler } from '../../dispatch'
|
||||
import { getOptionalStringFlag } from '../../flags'
|
||||
import { RuntimeClientError } from '../../runtime-client'
|
||||
import {
|
||||
clampOrchestrationAskTimeoutMs,
|
||||
resolveOrchestrationAskClientTimeoutMs
|
||||
} from '../../../shared/orchestration-ask-timeout'
|
||||
import type { LegacyCompatibilityResult } from '../../../shared/orchestration-check-output'
|
||||
import { callOrchestrationMutation } from './mutation-request'
|
||||
import { getOptionalPositiveIntegerValueFlag } from './numeric-flags'
|
||||
import {
|
||||
flushOrchestrationStdout,
|
||||
resolveCompatibilityCliCommand,
|
||||
resolvePackagedWindowsCompatibilityCommand
|
||||
} from './runtime-compatibility'
|
||||
import { resolveOrchestrationTerminalHandle } from './terminal-identity'
|
||||
|
||||
export const ORCHESTRATION_QUESTION_HANDLER: Record<string, CommandHandler> = {
|
||||
'orchestration ask': async ({ flags, client, cwd, json }) => {
|
||||
const parsedTimeoutMs = getOptionalPositiveIntegerValueFlag(flags, 'timeout-ms')
|
||||
const timeoutMs = clampOrchestrationAskTimeoutMs(parsedTimeoutMs)
|
||||
const from = await resolveOrchestrationTerminalHandle(flags, cwd, client, 'from')
|
||||
const question = getOptionalStringFlag(flags, 'question')
|
||||
const resume = getOptionalStringFlag(flags, 'resume')
|
||||
if ((question ? 1 : 0) + (resume ? 1 : 0) !== 1) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'Choose exactly one of --question or --resume.'
|
||||
)
|
||||
}
|
||||
if (resume && flags.has('options')) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'--options is only valid when creating a new question.'
|
||||
)
|
||||
}
|
||||
const result = await callOrchestrationMutation<{
|
||||
answer: string | null
|
||||
messageId: string | null
|
||||
threadId: string
|
||||
timedOut: boolean
|
||||
timeoutMs?: number
|
||||
cancelled?: boolean
|
||||
connectionLost?: boolean
|
||||
answerMessageId?: string | null
|
||||
legacyCompatibility?: LegacyCompatibilityResult
|
||||
}>(
|
||||
client,
|
||||
flags,
|
||||
'orchestration.ask',
|
||||
{
|
||||
to: getOptionalStringFlag(flags, 'to'),
|
||||
run: getOptionalStringFlag(flags, 'run'),
|
||||
question,
|
||||
resume,
|
||||
options: getOptionalStringFlag(flags, 'options'),
|
||||
timeoutMs: parsedTimeoutMs === undefined ? undefined : timeoutMs,
|
||||
from,
|
||||
compatibilityCliCommand: resolveCompatibilityCliCommand(),
|
||||
compatibilityWindowsCommand: resolvePackagedWindowsCompatibilityCommand()
|
||||
},
|
||||
// Why: extend past timeoutMs so transport does not abort before the runtime resolves its timeout.
|
||||
{
|
||||
timeoutMs: resolveOrchestrationAskClientTimeoutMs(parsedTimeoutMs),
|
||||
orchestrationCapability: getOptionalStringFlag(flags, 'dispatch-capability')
|
||||
}
|
||||
)
|
||||
// Why: ask JSON is intentionally a bare object for `jq -r .answer`, unlike other verbs.
|
||||
if (json) {
|
||||
console.log(JSON.stringify(result.result))
|
||||
} else if (result.result.legacyCompatibility?.resumeRequired) {
|
||||
console.log(`Question ${result.result.messageId} committed.`)
|
||||
console.log(`Resume with: ${result.result.legacyCompatibility.resumeCommand}`)
|
||||
} else if (result.result.answer !== null) {
|
||||
console.log(result.result.answer)
|
||||
}
|
||||
if (result.result.legacyCompatibility?.resumeRequired) {
|
||||
await flushOrchestrationStdout()
|
||||
process.exitCode = 75
|
||||
return
|
||||
}
|
||||
const answerAck = result.result.legacyCompatibility?.answerAcknowledgement
|
||||
if (answerAck && result.result.answer !== null) {
|
||||
await flushOrchestrationStdout()
|
||||
await client.call('orchestration.check', {
|
||||
terminal: from,
|
||||
compatibilityQuestionAck: JSON.stringify(answerAck)
|
||||
})
|
||||
}
|
||||
if (result.result.timedOut) {
|
||||
if (!json) {
|
||||
// Why: report the server's clamped effective budget rather than overstating the wait.
|
||||
const waitedMs = result.result.timeoutMs ?? timeoutMs
|
||||
console.error(`ask timeout after ${waitedMs}ms (thread ${result.result.threadId})`)
|
||||
}
|
||||
process.exitCode = 1
|
||||
}
|
||||
if (result.result.cancelled) {
|
||||
if (!json) {
|
||||
console.error(
|
||||
result.result.connectionLost
|
||||
? `ask connection closed (question ${result.result.messageId})`
|
||||
: `ask cancelled (question ${result.result.messageId})`
|
||||
)
|
||||
}
|
||||
process.exitCode = 1
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { CommandHandler } from '../../dispatch'
|
||||
import { printResult } from '../../format'
|
||||
import { RuntimeClientError } from '../../runtime-client'
|
||||
import { callOrchestrationMutation } from './mutation-request'
|
||||
|
||||
export const ORCHESTRATION_RESET_HANDLER: Record<string, CommandHandler> = {
|
||||
'orchestration reset': async ({ flags, client, json }) => {
|
||||
const scopeCount = [flags.has('all'), flags.has('tasks'), flags.has('messages')].filter(
|
||||
Boolean
|
||||
).length
|
||||
if (scopeCount !== 1) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'Choose exactly one reset scope: --all, --tasks, or --messages.'
|
||||
)
|
||||
}
|
||||
const result = await callOrchestrationMutation<{ reset: string }>(
|
||||
client,
|
||||
flags,
|
||||
'orchestration.reset',
|
||||
{
|
||||
all: flags.has('all') ? true : undefined,
|
||||
tasks: flags.has('tasks') ? true : undefined,
|
||||
messages: flags.has('messages') ? true : undefined
|
||||
}
|
||||
)
|
||||
printResult(result, json, (value) => `Reset: ${value.reset}`)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { CommandHandler } from '../../dispatch'
|
||||
import { printResult } from '../../format'
|
||||
import {
|
||||
getOptionalPositiveIntegerFlag,
|
||||
getOptionalStringFlag,
|
||||
getRequiredStringFlag
|
||||
} from '../../flags'
|
||||
import { ORCHESTRATION_RUN_PAGE_LIMIT } from '../../../shared/orchestration-run-pagination'
|
||||
import { callOrchestrationMutation } from './mutation-request'
|
||||
import { resolveCoordinatorTerminalHandle } from './terminal-identity'
|
||||
|
||||
export const ORCHESTRATION_RUN_HANDLERS: Record<string, CommandHandler> = {
|
||||
'orchestration run-create': async ({ flags, client, cwd, json }) => {
|
||||
const from = await resolveCoordinatorTerminalHandle(flags, cwd, client)
|
||||
const result = await callOrchestrationMutation<{
|
||||
run: { id: string; objective: string; consumer_generation: number }
|
||||
}>(client, flags, 'orchestration.runCreate', {
|
||||
objective: getRequiredStringFlag(flags, 'objective'),
|
||||
from
|
||||
})
|
||||
printResult(result, json, (r) => `Run ${r.run.id} created and bound: ${r.run.objective}`)
|
||||
},
|
||||
|
||||
'orchestration run-use': async ({ flags, client, cwd, json }) => {
|
||||
const from = await resolveCoordinatorTerminalHandle(flags, cwd, client)
|
||||
const result = await callOrchestrationMutation<{
|
||||
run: { id: string; objective: string; consumer_generation: number }
|
||||
}>(client, flags, 'orchestration.runUse', {
|
||||
id: getRequiredStringFlag(flags, 'id'),
|
||||
from,
|
||||
...(flags.has('takeover-legacy') ? { takeoverLegacy: true } : {})
|
||||
})
|
||||
printResult(result, json, (r) => `Using Run ${r.run.id}: ${r.run.objective}`)
|
||||
},
|
||||
|
||||
'orchestration run-current': async ({ flags, client, cwd, json }) => {
|
||||
const from = await resolveCoordinatorTerminalHandle(flags, cwd, client)
|
||||
const result = await client.call<{
|
||||
run: { id: string; objective: string } | null
|
||||
}>('orchestration.runCurrent', { from })
|
||||
printResult(result, json, (r) =>
|
||||
r.run ? `${r.run.id} ${r.run.objective}` : 'No Run is bound to this terminal.'
|
||||
)
|
||||
},
|
||||
|
||||
'orchestration run-list': async ({ flags, client, json }) => {
|
||||
const result = await client.call<{
|
||||
runs: { id: string; objective: string; legacy: number }[]
|
||||
nextCursor: string | null
|
||||
}>('orchestration.runList', {
|
||||
limit: getOptionalPositiveIntegerFlag(flags, 'limit') ?? ORCHESTRATION_RUN_PAGE_LIMIT,
|
||||
cursor: getOptionalStringFlag(flags, 'cursor')
|
||||
})
|
||||
printResult(result, json, (r) => {
|
||||
const rows =
|
||||
r.runs.length === 0
|
||||
? 'No Runs found.'
|
||||
: r.runs
|
||||
.map(
|
||||
(run) => `${run.id}${run.legacy ? ' [legacy, inspect only]' : ''} ${run.objective}`
|
||||
)
|
||||
.join('\n')
|
||||
return r.nextCursor ? `${rows}\nMore Runs: --cursor ${r.nextCursor}` : rows
|
||||
})
|
||||
},
|
||||
|
||||
'orchestration run-show': async ({ flags, client, json }) => {
|
||||
const result = await client.call<{
|
||||
run: {
|
||||
id: string
|
||||
objective: string
|
||||
consumer_generation: number
|
||||
legacy: number
|
||||
created_at: string
|
||||
}
|
||||
}>('orchestration.runShow', { id: getRequiredStringFlag(flags, 'id') })
|
||||
printResult(
|
||||
result,
|
||||
json,
|
||||
(r) =>
|
||||
`${r.run.id}${r.run.legacy ? ' [legacy, inspect only]' : ''} ${r.run.objective}\n` +
|
||||
`consumer generation ${r.run.consumer_generation}; created ${r.run.created_at}`
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { RuntimeClientError } from '../../runtime-client'
|
||||
|
||||
export function resolveCompatibilityCliCommand(): 'orca' | 'orca-ide' | 'orca-dev' {
|
||||
const configured = process.env.ORCA_CLI_COMMAND
|
||||
if (configured === 'orca' || configured === 'orca-ide' || configured === 'orca-dev') {
|
||||
return configured
|
||||
}
|
||||
return process.platform === 'linux' ? 'orca-ide' : 'orca'
|
||||
}
|
||||
|
||||
export function resolvePackagedWindowsCompatibilityCommand(): 'orca' | 'orca-ide' | undefined {
|
||||
if (process.env.ORCA_WINDOWS_PACKAGED_CLI_LAUNCHER !== '1') {
|
||||
return undefined
|
||||
}
|
||||
const command = process.env.ORCA_CLI_COMMAND
|
||||
if (command === 'orca' || command === 'orca-ide') {
|
||||
return command
|
||||
}
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'The packaged Orca launcher did not provide a valid resume command. No question was created.'
|
||||
)
|
||||
}
|
||||
|
||||
export async function flushOrchestrationStdout(): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
process.stdout.write('', (error) => {
|
||||
if (error) {
|
||||
reject(error)
|
||||
} else {
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export function isDevCliInvocation(): boolean {
|
||||
return (
|
||||
process.env.ORCA_DEV_CLI_INVOCATION === '1' ||
|
||||
(process.env.ORCA_USER_DATA_PATH?.includes('orca-dev') ?? false)
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import type { CommandHandler } from '../../dispatch'
|
||||
import { printResult } from '../../format'
|
||||
import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags'
|
||||
import { RuntimeClientError } from '../../runtime-client'
|
||||
import { abbreviateOrchestrationTasks } from '../../../shared/orchestration-task-summary'
|
||||
import { callOrchestrationMutation } from './mutation-request'
|
||||
import { resolveCoordinatorTerminalHandle } from './terminal-identity'
|
||||
|
||||
const TASK_STATUS_VALUES = [
|
||||
'pending',
|
||||
'ready',
|
||||
'dispatched',
|
||||
'completed',
|
||||
'failed',
|
||||
'blocked'
|
||||
] as const
|
||||
|
||||
export const ORCHESTRATION_TASK_HANDLERS: Record<string, CommandHandler> = {
|
||||
'orchestration task-create': async ({ flags, client, cwd, json }) => {
|
||||
const callerTerminalHandle = await resolveCoordinatorTerminalHandle(flags, cwd, client)
|
||||
const result = await callOrchestrationMutation<{ task: { id: string; status: string } }>(
|
||||
client,
|
||||
flags,
|
||||
'orchestration.taskCreate',
|
||||
{
|
||||
spec: getRequiredStringFlag(flags, 'spec'),
|
||||
taskTitle: getOptionalStringFlag(flags, 'task-title'),
|
||||
displayName: getOptionalStringFlag(flags, 'display-name'),
|
||||
deps: getOptionalStringFlag(flags, 'deps'),
|
||||
parent: getOptionalStringFlag(flags, 'parent'),
|
||||
run: getOptionalStringFlag(flags, 'run'),
|
||||
callerTerminalHandle
|
||||
}
|
||||
)
|
||||
printResult(result, json, (r) => `Created ${r.task.id} [${r.task.status}]`)
|
||||
},
|
||||
|
||||
'orchestration task-list': async ({ flags, client, cwd, json }) => {
|
||||
const brief = flags.has('brief')
|
||||
const run = getOptionalStringFlag(flags, 'run')
|
||||
const callerTerminalHandle = run
|
||||
? undefined
|
||||
: await resolveCoordinatorTerminalHandle(flags, cwd, client)
|
||||
const result = await client.call<{
|
||||
tasks: {
|
||||
id: string
|
||||
spec: string
|
||||
task_title?: string | null
|
||||
display_name?: string | null
|
||||
status: string
|
||||
assignee_handle?: string | null
|
||||
dispatch_id?: string | null
|
||||
spec_truncated?: boolean
|
||||
}[]
|
||||
count: number
|
||||
runId?: string
|
||||
legacyReadOnly?: boolean
|
||||
}>('orchestration.taskList', {
|
||||
status: getOptionalStringFlag(flags, 'status'),
|
||||
ready: flags.has('ready') ? true : undefined,
|
||||
brief: brief ? true : undefined,
|
||||
run,
|
||||
callerTerminalHandle
|
||||
})
|
||||
// Why: only older runtimes (no spec_truncated) skip server-side abbreviation and need this client-side fallback.
|
||||
const needsClientAbbreviation =
|
||||
brief && result.result.tasks.some((task) => task.spec_truncated === undefined)
|
||||
const output = needsClientAbbreviation
|
||||
? {
|
||||
...result,
|
||||
result: { ...result.result, tasks: abbreviateOrchestrationTasks(result.result.tasks) }
|
||||
}
|
||||
: result
|
||||
printResult(output, json, (r) => {
|
||||
if (r.count === 0) {
|
||||
return r.legacyReadOnly ? 'No legacy tasks (read-only).' : 'No tasks.'
|
||||
}
|
||||
const tasks = r.tasks
|
||||
.map((task) => {
|
||||
const label = task.display_name ?? task.task_title ?? task.spec
|
||||
const head = `${task.id} [${task.status}] ${label.slice(0, 60)}`
|
||||
if (task.status === 'dispatched' && task.assignee_handle) {
|
||||
return `${head} -> ${task.assignee_handle} (${task.dispatch_id ?? '?'})`
|
||||
}
|
||||
return head
|
||||
})
|
||||
.join('\n')
|
||||
return r.legacyReadOnly ? `Legacy Run ${r.runId} (read-only)\n${tasks}` : tasks
|
||||
})
|
||||
},
|
||||
|
||||
'orchestration task-update': async ({ flags, client, cwd, json }) => {
|
||||
const status = getRequiredStringFlag(flags, 'status')
|
||||
if (!TASK_STATUS_VALUES.includes(status as (typeof TASK_STATUS_VALUES)[number])) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
`invalid status '${status}', expected one of: ${TASK_STATUS_VALUES.join(', ')}`
|
||||
)
|
||||
}
|
||||
const result = await callOrchestrationMutation<{ task: { id: string; status: string } }>(
|
||||
client,
|
||||
flags,
|
||||
'orchestration.taskUpdate',
|
||||
{
|
||||
id: getRequiredStringFlag(flags, 'id'),
|
||||
status,
|
||||
result: getOptionalStringFlag(flags, 'result'),
|
||||
run: getOptionalStringFlag(flags, 'run'),
|
||||
callerTerminalHandle: await resolveCoordinatorTerminalHandle(flags, cwd, client)
|
||||
}
|
||||
)
|
||||
printResult(result, json, (r) => `Updated ${r.task.id} -> ${r.task.status}`)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import type { RuntimeClient } from '../../runtime-client'
|
||||
import { getOptionalStringFlag } from '../../flags'
|
||||
import { RuntimeClientError } from '../../runtime-client'
|
||||
import { getTerminalHandle } from '../../selectors'
|
||||
|
||||
export async function resolveOrchestrationTerminalHandle(
|
||||
flags: Map<string, string | boolean>,
|
||||
cwd: string,
|
||||
client: RuntimeClient,
|
||||
flagName: 'from' | 'terminal',
|
||||
options: { validateEnvHandle?: boolean } = {}
|
||||
): Promise<string> {
|
||||
const explicit = getOptionalStringFlag(flags, flagName)
|
||||
if (explicit) {
|
||||
return explicit
|
||||
}
|
||||
const envHandle = process.env.ORCA_TERMINAL_HANDLE
|
||||
if (envHandle && envHandle.length > 0) {
|
||||
if (flagName === 'from' && options.validateEnvHandle) {
|
||||
// Why: long-lived shells can retain a stale ORCA_TERMINAL_HANDLE after remint; don't bake it into coordinator preambles.
|
||||
const live = await isLiveTerminalHandle(envHandle, client)
|
||||
if (!live) {
|
||||
const reminted = await resolveOrchestrationPaneTerminalHandle(client)
|
||||
if (reminted) {
|
||||
return reminted
|
||||
}
|
||||
throwNoActiveSenderTerminal()
|
||||
}
|
||||
}
|
||||
return envHandle
|
||||
}
|
||||
if (flagName === 'from') {
|
||||
return await resolveImplicitOrchestrationSender(flags, cwd, client)
|
||||
}
|
||||
return await getTerminalHandle(flags, cwd, client)
|
||||
}
|
||||
|
||||
async function isLiveTerminalHandle(handle: string, client: RuntimeClient): Promise<boolean> {
|
||||
try {
|
||||
await client.call('terminal.show', { terminal: handle })
|
||||
return true
|
||||
} catch (err) {
|
||||
if (isStaleTerminalIdentityError(err)) {
|
||||
return false
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
function getClientErrorCode(err: unknown): string | undefined {
|
||||
if (!err || typeof err !== 'object') {
|
||||
return undefined
|
||||
}
|
||||
const code = (err as { code?: unknown }).code
|
||||
return typeof code === 'string' ? code : undefined
|
||||
}
|
||||
|
||||
function isStaleTerminalIdentityError(err: unknown): boolean {
|
||||
const code = getClientErrorCode(err)
|
||||
return code === 'terminal_handle_stale' || code === 'terminal_gone'
|
||||
}
|
||||
|
||||
function isNoActiveTerminalError(err: unknown): boolean {
|
||||
return getClientErrorCode(err) === 'no_active_terminal'
|
||||
}
|
||||
|
||||
async function resolveOrchestrationPaneTerminalHandle(
|
||||
client: RuntimeClient,
|
||||
options: { optional?: boolean } = {}
|
||||
): Promise<string | undefined> {
|
||||
const paneKey = process.env.ORCA_PANE_KEY
|
||||
if (!paneKey || paneKey.length === 0) {
|
||||
return undefined
|
||||
}
|
||||
try {
|
||||
// Why: pane-key reminting preserves caller identity; focus-based active-terminal fallback can point at a different pane.
|
||||
const response = await client.call<{ terminal: { handle: string } }>('terminal.resolvePane', {
|
||||
paneKey
|
||||
})
|
||||
return response.result.terminal.handle
|
||||
} catch (err) {
|
||||
if (
|
||||
isPaneRemintUnavailableError(err) ||
|
||||
(options.optional === true && isOptionalPaneRemintUnavailableError(err))
|
||||
) {
|
||||
return undefined
|
||||
}
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
function isPaneRemintUnavailableError(err: unknown): boolean {
|
||||
const code = getClientErrorCode(err)
|
||||
const message = getClientErrorMessage(err)
|
||||
return (
|
||||
code === 'terminal_not_found' ||
|
||||
code === 'terminal_handle_stale' ||
|
||||
code === 'terminal_gone' ||
|
||||
message === 'terminal_not_found' ||
|
||||
message === 'terminal_handle_stale' ||
|
||||
message === 'terminal_gone'
|
||||
)
|
||||
}
|
||||
|
||||
function isOptionalPaneRemintUnavailableError(err: unknown): boolean {
|
||||
return getClientErrorCode(err) === 'runtime_unavailable'
|
||||
}
|
||||
|
||||
function getClientErrorMessage(err: unknown): string | undefined {
|
||||
if (err instanceof Error) {
|
||||
return err.message
|
||||
}
|
||||
if (!err || typeof err !== 'object') {
|
||||
return undefined
|
||||
}
|
||||
const message = (err as { message?: unknown }).message
|
||||
return typeof message === 'string' ? message : undefined
|
||||
}
|
||||
|
||||
export async function resolveCoordinatorTerminalHandle(
|
||||
flags: Map<string, string | boolean>,
|
||||
cwd: string,
|
||||
client: RuntimeClient
|
||||
): Promise<string> {
|
||||
return await resolveOrchestrationTerminalHandle(flags, cwd, client, 'from', {
|
||||
validateEnvHandle: true
|
||||
})
|
||||
}
|
||||
|
||||
async function resolveImplicitOrchestrationSender(
|
||||
flags: Map<string, string | boolean>,
|
||||
cwd: string,
|
||||
client: RuntimeClient
|
||||
): Promise<string> {
|
||||
try {
|
||||
return await getTerminalHandle(flags, cwd, client)
|
||||
} catch (err) {
|
||||
if (!isNoActiveTerminalError(err)) {
|
||||
throw err
|
||||
}
|
||||
throwNoActiveSenderTerminal()
|
||||
}
|
||||
}
|
||||
|
||||
export function throwNoActiveSenderTerminal(): never {
|
||||
throw new RuntimeClientError(
|
||||
'no_active_sender_terminal',
|
||||
'Could not determine the sender terminal for this orchestration command. ' +
|
||||
'Pass --from <terminal-handle> or run the command inside a live Orca terminal with ORCA_TERMINAL_HANDLE set.'
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import type { CommandHandler } from '../../dispatch'
|
||||
import { printResult } from '../../format'
|
||||
import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags'
|
||||
import { RuntimeClientError } from '../../runtime-client'
|
||||
import type { RuntimeStatus } from '../../../shared/runtime-types'
|
||||
import { ORCHESTRATION_WORKER_LAUNCH_PREFERENCES_RUNTIME_CAPABILITY } from '../../../shared/protocol-version'
|
||||
import { callOrchestrationMutation } from './mutation-request'
|
||||
import { getOptionalPositiveIntegerValueFlag } from './numeric-flags'
|
||||
import { isDevCliInvocation } from './runtime-compatibility'
|
||||
import { resolveCoordinatorTerminalHandle } from './terminal-identity'
|
||||
|
||||
export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record<string, CommandHandler> = {
|
||||
'orchestration worker-start': async ({ flags, client, cwd, json }) => {
|
||||
const model = getOptionalStringFlag(flags, 'model')
|
||||
const effort = getOptionalStringFlag(flags, 'effort')
|
||||
if (model || effort) {
|
||||
const status = await client.call<RuntimeStatus>('status.get')
|
||||
if (
|
||||
!status.result.capabilities?.includes(
|
||||
ORCHESTRATION_WORKER_LAUNCH_PREFERENCES_RUNTIME_CAPABILITY
|
||||
)
|
||||
) {
|
||||
throw new RuntimeClientError(
|
||||
'incompatible_runtime',
|
||||
'The connected Orca runtime does not support worker model or effort overrides. Update or restart Orca and try again.'
|
||||
)
|
||||
}
|
||||
}
|
||||
const result = await callOrchestrationMutation<{
|
||||
runId: string
|
||||
taskId: string
|
||||
dispatchId: string
|
||||
state: string
|
||||
failedStage?: string
|
||||
lastError?: string
|
||||
warning?: string
|
||||
effects: unknown[]
|
||||
residualResources: unknown[]
|
||||
}>(client, flags, 'orchestration.workerStart', {
|
||||
task: getRequiredStringFlag(flags, 'task'),
|
||||
on: getOptionalStringFlag(flags, 'on'),
|
||||
worktree: getOptionalStringFlag(flags, 'worktree'),
|
||||
name: getOptionalStringFlag(flags, 'name'),
|
||||
repo: getOptionalStringFlag(flags, 'repo'),
|
||||
baseBranch: getOptionalStringFlag(flags, 'base-branch'),
|
||||
displayName: getOptionalStringFlag(flags, 'display-name'),
|
||||
comment: getOptionalStringFlag(flags, 'comment'),
|
||||
setup: getOptionalStringFlag(flags, 'setup'),
|
||||
agent: getOptionalStringFlag(flags, 'agent'),
|
||||
model,
|
||||
effort,
|
||||
terminal: getOptionalStringFlag(flags, 'terminal'),
|
||||
retryOf: getOptionalStringFlag(flags, 'retry-of'),
|
||||
timeoutMs: getOptionalPositiveIntegerValueFlag(flags, 'timeout-ms'),
|
||||
run: getOptionalStringFlag(flags, 'run'),
|
||||
from: await resolveCoordinatorTerminalHandle(flags, cwd, client),
|
||||
devMode: isDevCliInvocation()
|
||||
})
|
||||
if (result.result.state !== 'ready') {
|
||||
process.exitCode = 1
|
||||
}
|
||||
printResult(result, json, (worker) => {
|
||||
const base = `Worker ${worker.dispatchId} [${worker.state}] for ${worker.taskId}`
|
||||
if (worker.lastError) {
|
||||
return `${base}\n${worker.failedStage ?? 'start'}: ${worker.lastError}`
|
||||
}
|
||||
return worker.warning ? `${base}\nWarning: ${worker.warning}` : base
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { CommandHandler } from '../../dispatch'
|
||||
import { printResult } from '../../format'
|
||||
import {
|
||||
getOptionalPositiveIntegerFlag,
|
||||
getOptionalStringFlag,
|
||||
getRequiredStringFlag
|
||||
} from '../../flags'
|
||||
import { RuntimeClientError } from '../../runtime-client'
|
||||
import type {
|
||||
OrchestrationWorkerReadResult,
|
||||
OrchestrationWorkerReadSource
|
||||
} from '../../../shared/orchestration-worker-output'
|
||||
import { formatWorkerRead, type LegacyWorkerReadResult } from './worker-output'
|
||||
|
||||
export const ORCHESTRATION_WORKER_OBSERVATION_HANDLERS: Record<string, CommandHandler> = {
|
||||
'orchestration worker-show': async ({ flags, client, json }) => {
|
||||
const result = await client.call<{
|
||||
dispatch: { id: string; task_id: string; status: string }
|
||||
worker: { state: string; stage: string; agent_terminal_handle: string | null }
|
||||
observation?: { agentWait?: { source: string; reason?: string } | null }
|
||||
}>('orchestration.workerShow', {
|
||||
dispatch: getRequiredStringFlag(flags, 'dispatch')
|
||||
})
|
||||
printResult(result, json, (value) => {
|
||||
const base = `${value.dispatch.id} task=${value.dispatch.task_id} [${value.worker.state}] stage=${value.worker.stage}`
|
||||
// Why: absent means unknown on older runtimes, distinct from an evaluated null wait.
|
||||
if (value.observation === undefined || !('agentWait' in value.observation)) {
|
||||
return `${base}\nInteractive wait: unknown (not evaluated)`
|
||||
}
|
||||
const wait = value.observation.agentWait
|
||||
return wait
|
||||
? `${base}\nWaiting on a human: ${wait.reason ?? 'interactive prompt'} (via ${wait.source})`
|
||||
: `${base}\nInteractive wait: none`
|
||||
})
|
||||
},
|
||||
|
||||
'orchestration worker-read': async ({ flags, client, json }) => {
|
||||
const cursorFlag = getOptionalStringFlag(flags, 'cursor')
|
||||
const cursor =
|
||||
cursorFlag !== undefined && /^\d+$/.test(cursorFlag)
|
||||
? Number.parseInt(cursorFlag, 10)
|
||||
: cursorFlag
|
||||
const source = getOptionalStringFlag(flags, 'source')
|
||||
if (source && !['auto', 'transcript', 'terminal'].includes(source)) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'--source must be auto, transcript, or terminal'
|
||||
)
|
||||
}
|
||||
const result = await client.call<OrchestrationWorkerReadResult | LegacyWorkerReadResult>(
|
||||
'orchestration.workerRead',
|
||||
{
|
||||
dispatch: getRequiredStringFlag(flags, 'dispatch'),
|
||||
cursor,
|
||||
limit: getOptionalPositiveIntegerFlag(flags, 'limit'),
|
||||
source: source as OrchestrationWorkerReadSource | undefined
|
||||
}
|
||||
)
|
||||
printResult(result, json, formatWorkerRead)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import type { NativeChatMessage } from '../../../shared/native-chat-types'
|
||||
import type { RuntimeTerminalRead } from '../../../shared/runtime-types'
|
||||
import type { OrchestrationWorkerReadResult } from '../../../shared/orchestration-worker-output'
|
||||
|
||||
export type LegacyWorkerReadResult = {
|
||||
dispatchId: string
|
||||
terminal: RuntimeTerminalRead
|
||||
}
|
||||
|
||||
export function formatWorkerRead(
|
||||
value: OrchestrationWorkerReadResult | LegacyWorkerReadResult
|
||||
): string {
|
||||
if (!('source' in value) || value.source === 'terminal') {
|
||||
return value.terminal.tail.join('\n')
|
||||
}
|
||||
return value.transcript.messages.map(formatWorkerTranscriptMessage).join('\n\n')
|
||||
}
|
||||
|
||||
function formatWorkerTranscriptMessage(message: NativeChatMessage): string {
|
||||
const blocks = message.blocks.map((block) => {
|
||||
if (block.type === 'text') {
|
||||
return block.text
|
||||
}
|
||||
if (block.type === 'tool-call') {
|
||||
return `[tool ${block.name}] ${safeJson(block.input)}`
|
||||
}
|
||||
if (block.type === 'tool-result') {
|
||||
return `[tool result${block.isError ? ' error' : ''}] ${block.output}`
|
||||
}
|
||||
return block.url ? `[image] ${block.url}` : `[image omitted]`
|
||||
})
|
||||
return `[${message.role}] ${blocks.join('\n')}`.trimEnd()
|
||||
}
|
||||
|
||||
export type WorkerReleaseReceipt = {
|
||||
dispatchId: string
|
||||
state: string
|
||||
reason?: string
|
||||
processAction: string
|
||||
archive: { source: string | null; status: string | null } | null
|
||||
recovery?: string
|
||||
lastError?: string
|
||||
}
|
||||
|
||||
export function formatWorkerRelease(value: WorkerReleaseReceipt): string {
|
||||
const head = `Worker ${value.dispatchId} terminal [${value.state}]`
|
||||
const lines = [
|
||||
`${head}${value.reason ? ` reason=${value.reason}` : ''} process=${value.processAction}`
|
||||
]
|
||||
if (value.archive) {
|
||||
lines.push(`archive ${value.archive.source ?? 'none'} [${value.archive.status ?? 'unknown'}]`)
|
||||
}
|
||||
if (value.lastError) {
|
||||
lines.push(value.lastError)
|
||||
}
|
||||
if (value.recovery) {
|
||||
lines.push(value.recovery)
|
||||
}
|
||||
return lines.join('\n')
|
||||
}
|
||||
|
||||
function safeJson(value: unknown): string {
|
||||
try {
|
||||
return JSON.stringify(value)
|
||||
} catch {
|
||||
return '[unserializable input]'
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import type { CommandHandler } from '../../dispatch'
|
||||
import { printResult } from '../../format'
|
||||
import { getOptionalStringFlag, getRequiredStringFlag } from '../../flags'
|
||||
import { RuntimeClientError } from '../../runtime-client'
|
||||
import { callOrchestrationMutation } from './mutation-request'
|
||||
import { formatWorkerRelease, type WorkerReleaseReceipt } from './worker-output'
|
||||
|
||||
const WORKER_TERMINAL_LIST_STATES = [
|
||||
'active',
|
||||
'reclaimable',
|
||||
'retained',
|
||||
'release_pending',
|
||||
'release_unknown',
|
||||
'released'
|
||||
] as const
|
||||
|
||||
export const ORCHESTRATION_WORKER_TERMINAL_HANDLERS: Record<string, CommandHandler> = {
|
||||
'orchestration worker-stop': async ({ flags, client, json }) => {
|
||||
const result = await callOrchestrationMutation<{
|
||||
dispatchId: string
|
||||
state: string
|
||||
processAction: string
|
||||
lastError?: string
|
||||
warning?: string
|
||||
}>(client, flags, 'orchestration.workerStop', {
|
||||
dispatch: getRequiredStringFlag(flags, 'dispatch')
|
||||
})
|
||||
if (result.result.state === 'stop_unknown') {
|
||||
process.exitCode = 1
|
||||
}
|
||||
printResult(
|
||||
result,
|
||||
json,
|
||||
(value) =>
|
||||
`Worker ${value.dispatchId} [${value.state}] process=${value.processAction}${value.lastError ? `\n${value.lastError}` : ''}${value.warning ? `\nWarning: ${value.warning}` : ''}`
|
||||
)
|
||||
},
|
||||
|
||||
'orchestration worker-abandon': async ({ flags, client, json }) => {
|
||||
const result = await callOrchestrationMutation<{
|
||||
dispatchId: string
|
||||
state: string
|
||||
warning: string
|
||||
}>(client, flags, 'orchestration.workerAbandon', {
|
||||
dispatch: getRequiredStringFlag(flags, 'dispatch')
|
||||
})
|
||||
printResult(
|
||||
result,
|
||||
json,
|
||||
(value) => `Worker ${value.dispatchId} [${value.state}]\nWarning: ${value.warning}`
|
||||
)
|
||||
},
|
||||
|
||||
'orchestration worker-release': async ({ flags, client, json }) => {
|
||||
const result = await callOrchestrationMutation<WorkerReleaseReceipt>(
|
||||
client,
|
||||
flags,
|
||||
'orchestration.workerRelease',
|
||||
{ dispatch: getRequiredStringFlag(flags, 'dispatch') }
|
||||
)
|
||||
// Why: only an unprovable close is a failure; retained/pending/already-released are settled answers.
|
||||
if (result.result.state === 'release_unknown') {
|
||||
process.exitCode = 1
|
||||
}
|
||||
printResult(result, json, formatWorkerRelease)
|
||||
},
|
||||
|
||||
'orchestration worker-retain': async ({ flags, client, json }) => {
|
||||
const result = await callOrchestrationMutation<WorkerReleaseReceipt>(
|
||||
client,
|
||||
flags,
|
||||
'orchestration.workerRetain',
|
||||
{ dispatch: getRequiredStringFlag(flags, 'dispatch') }
|
||||
)
|
||||
if (result.result.state === 'release_unknown') {
|
||||
process.exitCode = 1
|
||||
}
|
||||
printResult(result, json, formatWorkerRelease)
|
||||
},
|
||||
|
||||
'orchestration worker-list': async ({ flags, client, json }) => {
|
||||
const terminalState = getOptionalStringFlag(flags, 'terminal-state')
|
||||
if (
|
||||
terminalState &&
|
||||
!WORKER_TERMINAL_LIST_STATES.includes(
|
||||
terminalState as (typeof WORKER_TERMINAL_LIST_STATES)[number]
|
||||
)
|
||||
) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
`invalid --terminal-state '${terminalState}', expected one of: ${WORKER_TERMINAL_LIST_STATES.join(', ')}`
|
||||
)
|
||||
}
|
||||
const result = await client.call<{
|
||||
workers: {
|
||||
dispatchId: string
|
||||
taskId: string
|
||||
runId: string
|
||||
workerState: string
|
||||
dispatchStatus: string
|
||||
agentTerminalHandle: string | null
|
||||
terminalState: string | null
|
||||
resource: unknown
|
||||
}[]
|
||||
counts: Record<string, number>
|
||||
}>('orchestration.workerList', {
|
||||
run: getOptionalStringFlag(flags, 'run'),
|
||||
terminalState
|
||||
})
|
||||
printResult(result, json, (value) => {
|
||||
if (value.workers.length === 0) {
|
||||
return 'No workers found.'
|
||||
}
|
||||
const rows = value.workers
|
||||
.map(
|
||||
(worker) =>
|
||||
`${worker.dispatchId} task=${worker.taskId} [${worker.workerState}] terminal=${worker.terminalState ?? 'none'}`
|
||||
)
|
||||
.join('\n')
|
||||
const counts = Object.entries(value.counts)
|
||||
.map(([state, count]) => `${state}=${count}`)
|
||||
.join(' ')
|
||||
return counts ? `${rows}\nTerminals: ${counts}` : rows
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -38,6 +38,7 @@ describe('createHookStatusSessionTabsInvalidator', () => {
|
||||
|
||||
it.each([
|
||||
['state', { state: 'waiting' as const }],
|
||||
['workingMode', { workingMode: 'monitoring' as const }],
|
||||
['prompt', { prompt: 'ship it' }],
|
||||
['agentType', { agentType: 'codex' }],
|
||||
['toolName', { toolName: 'Bash' }],
|
||||
|
||||
@@ -33,6 +33,7 @@ export function createHookStatusSessionTabsInvalidator(): {
|
||||
return (
|
||||
!previous ||
|
||||
previous.payload.state !== next.state ||
|
||||
previous.payload.workingMode !== next.workingMode ||
|
||||
previous.payload.prompt !== next.prompt ||
|
||||
(previous.payload.agentType ?? null) !== (next.agentType ?? null) ||
|
||||
(previous.payload.toolName ?? null) !== (next.toolName ?? null) ||
|
||||
|
||||
@@ -4,6 +4,7 @@ import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { RelayAgentHookServer } from '../../relay/agent-hook-server'
|
||||
import { seedClaudeSubagentRosterFromSnapshots } from '../../shared/agent-hook-listener'
|
||||
import type { AgentHookRelayEnvelope } from '../../shared/agent-hook-relay'
|
||||
import { makePaneKey } from '../../shared/stable-pane-id'
|
||||
import { AgentHookServer } from './server'
|
||||
@@ -12,25 +13,11 @@ vi.mock('../telemetry/client', () => ({ track: vi.fn() }))
|
||||
vi.mock('../telemetry/cohort-classifier', () => ({ getCohortAtEmit: vi.fn(() => ({})) }))
|
||||
|
||||
const PANE_KEY = makePaneKey('manual-compact', '11111111-1111-4111-8111-111111111111')
|
||||
const PROMPT_ID_1 = '22222222-2222-4222-8222-222222222222'
|
||||
const PROMPT_ID_2 = '33333333-3333-4333-8333-333333333333'
|
||||
const COMPACT_PROMPT_ID = '22222222-2222-4222-8222-222222222222'
|
||||
const TURN_PROMPT_ID = '33333333-3333-4333-8333-333333333333'
|
||||
const SESSION = { key: 'session_id' as const, id: 'session-a' }
|
||||
|
||||
type ClaudeHook = {
|
||||
hook_event_name: string
|
||||
prompt?: string
|
||||
prompt_id: string
|
||||
session_id: string
|
||||
trigger?: 'manual' | 'auto'
|
||||
agent_id?: string
|
||||
agent_type?: string
|
||||
}
|
||||
|
||||
function claudeHook(
|
||||
hookEventName: string,
|
||||
promptId: string,
|
||||
extra: Partial<ClaudeHook> = {}
|
||||
): ClaudeHook {
|
||||
function claudeHook(hookEventName: string, promptId: string, extra: Record<string, unknown> = {}) {
|
||||
return {
|
||||
hook_event_name: hookEventName,
|
||||
prompt_id: promptId,
|
||||
@@ -39,30 +26,66 @@ function claudeHook(
|
||||
}
|
||||
}
|
||||
|
||||
function manualEnvelope(hookEventName: string, state: 'working' | 'done') {
|
||||
return {
|
||||
source: 'claude' as const,
|
||||
paneKey: PANE_KEY,
|
||||
hasExplicitPrompt: hookEventName === 'UserPromptSubmit' ? true : undefined,
|
||||
hookEventName,
|
||||
providerPromptId: hookEventName === 'UserPromptSubmit' ? PROMPT_ID_2 : PROMPT_ID_1,
|
||||
compactTrigger: hookEventName === 'UserPromptSubmit' ? undefined : ('manual' as const),
|
||||
providerSession: SESSION,
|
||||
payload: { state, prompt: 'work before compact', agentType: 'claude' as const }
|
||||
}
|
||||
}
|
||||
|
||||
function postHook(port: number, token: string, payload: Record<string, unknown>) {
|
||||
return fetch(`http://127.0.0.1:${port}/hook/claude`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Orca-Agent-Hook-Token': token
|
||||
},
|
||||
headers: { 'Content-Type': 'application/json', 'X-Orca-Agent-Hook-Token': token },
|
||||
body: JSON.stringify({ paneKey: PANE_KEY, payload })
|
||||
})
|
||||
}
|
||||
|
||||
function turnEnvelope(): AgentHookRelayEnvelope {
|
||||
return {
|
||||
source: 'claude',
|
||||
paneKey: PANE_KEY,
|
||||
connectionId: null,
|
||||
hasExplicitPrompt: true,
|
||||
hookEventName: 'UserPromptSubmit',
|
||||
providerPromptId: TURN_PROMPT_ID,
|
||||
providerSession: SESSION,
|
||||
payload: { state: 'working', prompt: 'work before compact', agentType: 'claude' }
|
||||
} as AgentHookRelayEnvelope
|
||||
}
|
||||
|
||||
/** What a relay predating this change forwards: it ran its own shipped normalizer, so a manual
|
||||
* compact arrives as a PLAIN `done` (no session boundary) and an auto compact as `working`. */
|
||||
function legacyRelayCompactEnvelope(
|
||||
state: 'done' | 'working',
|
||||
overrides: Partial<AgentHookRelayEnvelope> = {}
|
||||
): AgentHookRelayEnvelope {
|
||||
return {
|
||||
source: 'claude',
|
||||
paneKey: PANE_KEY,
|
||||
connectionId: null,
|
||||
hookEventName: 'PostCompact',
|
||||
providerPromptId: COMPACT_PROMPT_ID,
|
||||
compactTrigger: state === 'done' ? 'manual' : 'auto',
|
||||
providerSession: SESSION,
|
||||
payload: { state, prompt: 'work before compact', agentType: 'claude' },
|
||||
...overrides
|
||||
} as AgentHookRelayEnvelope
|
||||
}
|
||||
|
||||
/** What AgentHookServer.hydrate() rebuilds for a pane that was stuck `working` across a restart:
|
||||
* the previous session's connectionId, the unconfirmed flag, an older receivedAt, and the child
|
||||
* the turn had spawned — restored from disk, so proof of nothing. */
|
||||
function seedHydratedStuckPane(server: AgentHookServer, receivedAt: number) {
|
||||
const state = server._getStateForTests()
|
||||
const subagents = [{ id: 'child-1', state: 'working', startedAt: 0, agentType: 'general' }]
|
||||
state.lastStatusByPaneKey.set(PANE_KEY, {
|
||||
paneKey: PANE_KEY,
|
||||
source: 'claude',
|
||||
connectionId: null,
|
||||
hookEventName: 'UserPromptSubmit',
|
||||
providerPromptId: TURN_PROMPT_ID,
|
||||
providerSession: SESSION,
|
||||
restoredUnconfirmed: true,
|
||||
receivedAt,
|
||||
payload: { state: 'working', prompt: 'work before the restart', agentType: 'claude', subagents }
|
||||
} as never)
|
||||
seedClaudeSubagentRosterFromSnapshots(state, PANE_KEY, subagents as never)
|
||||
}
|
||||
|
||||
describe('manual Claude compact hook stream', () => {
|
||||
const servers: { stop: () => void }[] = []
|
||||
const temporaryPaths: string[] = []
|
||||
@@ -76,75 +99,112 @@ describe('manual Claude compact hook stream', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('settles an exact local HTTP lifecycle and rejects a duplicate completion', async () => {
|
||||
it('settles the measured local lifecycle and rejects a duplicate completion', async () => {
|
||||
const server = new AgentHookServer()
|
||||
servers.push(server)
|
||||
await server.start({ env: 'production' })
|
||||
const env = server.buildPtyEnv()
|
||||
const port = Number(env.ORCA_AGENT_HOOK_PORT)
|
||||
const token = env.ORCA_AGENT_HOOK_TOKEN
|
||||
const events: string[] = []
|
||||
const unsubscribe = server.subscribeEnrichedStatus((event) => {
|
||||
events.push(`${event.hookEventName}:${event.payload.state}`)
|
||||
})
|
||||
|
||||
await postHook(port, token, claudeHook('UserPromptSubmit', TURN_PROMPT_ID, { prompt: 'work' }))
|
||||
// Measured stream for a successful manual /compact. PreCompact is not registered in production
|
||||
// and is rejected here too; the summarizer's start-less SubagentStop only republishes state.
|
||||
await postHook(port, token, claudeHook('PreCompact', COMPACT_PROMPT_ID, { trigger: 'manual' }))
|
||||
await postHook(
|
||||
Number(env.ORCA_AGENT_HOOK_PORT),
|
||||
env.ORCA_AGENT_HOOK_TOKEN,
|
||||
claudeHook('UserPromptSubmit', PROMPT_ID_2, { prompt: 'work before compact' })
|
||||
)
|
||||
await postHook(
|
||||
Number(env.ORCA_AGENT_HOOK_PORT),
|
||||
env.ORCA_AGENT_HOOK_TOKEN,
|
||||
claudeHook('PreCompact', PROMPT_ID_1, { trigger: 'manual' })
|
||||
)
|
||||
await postHook(
|
||||
Number(env.ORCA_AGENT_HOOK_PORT),
|
||||
env.ORCA_AGENT_HOOK_TOKEN,
|
||||
claudeHook('SubagentStart', PROMPT_ID_1, {
|
||||
agent_id: 'compact-agent',
|
||||
agent_type: 'general-purpose'
|
||||
port,
|
||||
token,
|
||||
claudeHook('SubagentStop', COMPACT_PROMPT_ID, {
|
||||
agent_id: 'a75b38b59774e1f31',
|
||||
agent_type: '',
|
||||
background_tasks: [],
|
||||
session_crons: []
|
||||
})
|
||||
)
|
||||
await postHook(
|
||||
Number(env.ORCA_AGENT_HOOK_PORT),
|
||||
env.ORCA_AGENT_HOOK_TOKEN,
|
||||
claudeHook('SubagentStop', PROMPT_ID_1, {
|
||||
agent_id: 'compact-agent',
|
||||
agent_type: 'general-purpose'
|
||||
})
|
||||
)
|
||||
await postHook(
|
||||
Number(env.ORCA_AGENT_HOOK_PORT),
|
||||
env.ORCA_AGENT_HOOK_TOKEN,
|
||||
claudeHook('PostCompact', PROMPT_ID_1, { trigger: 'manual' })
|
||||
)
|
||||
await postHook(
|
||||
Number(env.ORCA_AGENT_HOOK_PORT),
|
||||
env.ORCA_AGENT_HOOK_TOKEN,
|
||||
claudeHook('PostCompact', PROMPT_ID_1, { trigger: 'manual' })
|
||||
port,
|
||||
token,
|
||||
claudeHook('SessionStart', COMPACT_PROMPT_ID, { source: 'compact' })
|
||||
)
|
||||
await postHook(port, token, claudeHook('PostCompact', COMPACT_PROMPT_ID, { trigger: 'manual' }))
|
||||
await postHook(port, token, claudeHook('PostCompact', COMPACT_PROMPT_ID, { trigger: 'manual' }))
|
||||
|
||||
expect(events).toEqual([
|
||||
'UserPromptSubmit:working',
|
||||
'PreCompact:working',
|
||||
'SubagentStart:working',
|
||||
'SubagentStop:working',
|
||||
'PostCompact:done'
|
||||
])
|
||||
expect(events).toEqual(['UserPromptSubmit:working', 'SubagentStop:working', 'PostCompact:done'])
|
||||
expect(server.getStatusSnapshot()).toEqual([
|
||||
expect.objectContaining({
|
||||
state: 'done',
|
||||
prompt: 'work before compact',
|
||||
agentType: 'claude'
|
||||
})
|
||||
expect.objectContaining({ state: 'done', prompt: 'work', agentType: 'claude' })
|
||||
])
|
||||
unsubscribe()
|
||||
})
|
||||
|
||||
it('preserves the manual identity over relay and rejects stale transport identities', async () => {
|
||||
it('clears the restart-stuck pane STA-2915 reports, without resurrecting anything', async () => {
|
||||
const server = new AgentHookServer()
|
||||
servers.push(server)
|
||||
await server.start({ env: 'production' })
|
||||
const env = server.buildPtyEnv()
|
||||
const port = Number(env.ORCA_AGENT_HOOK_PORT)
|
||||
const token = env.ORCA_AGENT_HOOK_TOKEN!
|
||||
seedHydratedStuckPane(server, Date.now() - 60_000)
|
||||
expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'working' })
|
||||
|
||||
await postHook(port, token, claudeHook('PreCompact', COMPACT_PROMPT_ID, { trigger: 'manual' }))
|
||||
await postHook(
|
||||
port,
|
||||
token,
|
||||
claudeHook('SubagentStop', COMPACT_PROMPT_ID, {
|
||||
agent_id: 'a75b38b59774e1f31',
|
||||
agent_type: ''
|
||||
})
|
||||
)
|
||||
await postHook(
|
||||
port,
|
||||
token,
|
||||
claudeHook('SessionStart', COMPACT_PROMPT_ID, { source: 'compact' })
|
||||
)
|
||||
await postHook(port, token, claudeHook('PostCompact', COMPACT_PROMPT_ID, { trigger: 'manual' }))
|
||||
|
||||
const row = server.getStatusSnapshot()[0]
|
||||
expect(row).toMatchObject({ state: 'done', prompt: 'work before the restart' })
|
||||
expect(row?.subagents ?? []).toEqual([])
|
||||
})
|
||||
|
||||
it('does not restate a pane a live child still owns, so the staleness clock keeps running', async () => {
|
||||
const server = new AgentHookServer()
|
||||
servers.push(server)
|
||||
await server.start({ env: 'production' })
|
||||
const env = server.buildPtyEnv()
|
||||
const port = Number(env.ORCA_AGENT_HOOK_PORT)
|
||||
const token = env.ORCA_AGENT_HOOK_TOKEN!
|
||||
seedHydratedStuckPane(server, Date.now() - 60_000)
|
||||
// A child THIS runtime observed: real agent work in flight, which a compact may not retire.
|
||||
await postHook(
|
||||
port,
|
||||
token,
|
||||
claudeHook('SubagentStart', TURN_PROMPT_ID, { agent_id: 'child-live' })
|
||||
)
|
||||
const before = server.getStatusSnapshot()[0]
|
||||
expect(before).toMatchObject({ state: 'working' })
|
||||
|
||||
const emitted: string[] = []
|
||||
const unsubscribe = server.subscribeEnrichedStatus((event) => {
|
||||
emitted.push(`${event.hookEventName}:${event.payload.state}`)
|
||||
})
|
||||
await postHook(port, token, claudeHook('PostCompact', COMPACT_PROMPT_ID, { trigger: 'manual' }))
|
||||
|
||||
// Why: restating the row here is the regression, not the fix — it would refresh receivedAt and
|
||||
// hand the stale sweep a brand-new clock for work the compact never observed.
|
||||
expect(emitted).toEqual([])
|
||||
expect(server.getStatusSnapshot()[0]).toEqual(before)
|
||||
unsubscribe()
|
||||
})
|
||||
|
||||
it('forwards the completion over the relay and preserves its cached compact identity', async () => {
|
||||
const main = new AgentHookServer()
|
||||
const forwarded: AgentHookRelayEnvelope[] = []
|
||||
const emitted: string[] = []
|
||||
const connectionId = 'conn-a'
|
||||
const endpointDir = mkdtempSync(join(tmpdir(), 'orca-compact-relay-'))
|
||||
temporaryPaths.push(endpointDir)
|
||||
const relay = new RelayAgentHookServer({
|
||||
@@ -152,7 +212,7 @@ describe('manual Claude compact hook stream', () => {
|
||||
token: 'manual-compact-token',
|
||||
forward: (envelope) => {
|
||||
forwarded.push(envelope)
|
||||
main.ingestRemote(envelope, connectionId)
|
||||
main.ingestRemote(envelope, 'conn-a')
|
||||
}
|
||||
})
|
||||
servers.push(main, relay)
|
||||
@@ -160,208 +220,253 @@ describe('manual Claude compact hook stream', () => {
|
||||
emitted.push(`${event.hookEventName}:${event.payload.state}`)
|
||||
})
|
||||
await relay.start({ publishEndpoint: false })
|
||||
const coordinates = relay.getCoordinates()
|
||||
const { port, token } = relay.getCoordinates()
|
||||
|
||||
await postHook(
|
||||
coordinates.port,
|
||||
coordinates.token,
|
||||
claudeHook('UserPromptSubmit', PROMPT_ID_2, { prompt: 'work before compact' })
|
||||
)
|
||||
// A restarted relay has no prior listener cache; main still owns the status boundary.
|
||||
relay.clearPaneState(PANE_KEY)
|
||||
await postHook(
|
||||
coordinates.port,
|
||||
coordinates.token,
|
||||
claudeHook('PreCompact', PROMPT_ID_1, { trigger: 'manual' })
|
||||
)
|
||||
const validPost = {
|
||||
...forwarded.at(-1)!,
|
||||
hookEventName: 'PostCompact',
|
||||
payload: {
|
||||
state: 'done' as const,
|
||||
prompt: 'work before compact',
|
||||
agentType: 'claude' as const
|
||||
}
|
||||
}
|
||||
|
||||
main.ingestRemote({ ...validPost, providerPromptId: PROMPT_ID_2 }, 'conn-a')
|
||||
main.ingestRemote({ ...validPost, providerPromptId: undefined }, 'conn-a')
|
||||
main.ingestRemote({ ...validPost, providerSession: undefined }, 'conn-a')
|
||||
main.ingestRemote({ ...validPost, source: 'codex' }, 'conn-a')
|
||||
main.ingestRemote(validPost, 'conn-b')
|
||||
|
||||
expect(emitted).toEqual(['UserPromptSubmit:working', 'PreCompact:working'])
|
||||
expect(main.getStatusSnapshot()[0]).toMatchObject({
|
||||
state: 'working',
|
||||
prompt: 'work before compact'
|
||||
})
|
||||
|
||||
await postHook(
|
||||
coordinates.port,
|
||||
coordinates.token,
|
||||
claudeHook('SubagentStart', PROMPT_ID_1, {
|
||||
agent_id: 'compact-agent',
|
||||
agent_type: 'general-purpose'
|
||||
})
|
||||
)
|
||||
await postHook(
|
||||
coordinates.port,
|
||||
coordinates.token,
|
||||
claudeHook('SubagentStop', PROMPT_ID_1, {
|
||||
agent_id: 'compact-agent',
|
||||
agent_type: 'general-purpose'
|
||||
})
|
||||
)
|
||||
await postHook(
|
||||
coordinates.port,
|
||||
coordinates.token,
|
||||
claudeHook('PostCompact', PROMPT_ID_1, { trigger: 'manual' })
|
||||
)
|
||||
await postHook(port, token, claudeHook('UserPromptSubmit', TURN_PROMPT_ID, { prompt: 'work' }))
|
||||
await postHook(port, token, claudeHook('PostCompact', COMPACT_PROMPT_ID, { trigger: 'manual' }))
|
||||
|
||||
expect(forwarded.at(-1)).toMatchObject({
|
||||
source: 'claude',
|
||||
providerPromptId: PROMPT_ID_1,
|
||||
hookEventName: 'PostCompact',
|
||||
compactTrigger: 'manual',
|
||||
providerSession: SESSION,
|
||||
hookEventName: 'PostCompact'
|
||||
providerPromptId: COMPACT_PROMPT_ID
|
||||
})
|
||||
expect(emitted.at(-1)).toBe('PostCompact:done')
|
||||
expect(emitted.slice(-3)).toEqual([
|
||||
'SubagentStart:working',
|
||||
'SubagentStop:working',
|
||||
'PostCompact:done'
|
||||
])
|
||||
expect(main.getStatusSnapshot()[0]).toMatchObject({
|
||||
state: 'done',
|
||||
prompt: 'work before compact'
|
||||
expect(main.getStatusSnapshot()[0]).toMatchObject({ state: 'done', sessionBoundary: true })
|
||||
|
||||
// Why: a client that was offline during the compact receives the row as a reconnect replay of
|
||||
// this cache. Retaining the compact identity lets the client re-run ownership instead of
|
||||
// treating an unowned completion as an ordinary status row.
|
||||
const replayed = relay.replayCachedPayloadsForPanes()
|
||||
expect(replayed).toBeGreaterThan(0)
|
||||
expect(forwarded.at(-1)).toMatchObject({ isReplay: true, payload: { state: 'done' } })
|
||||
expect(forwarded.at(-1)).toMatchObject({
|
||||
hookEventName: 'PostCompact',
|
||||
compactTrigger: 'manual'
|
||||
})
|
||||
unsubscribe()
|
||||
})
|
||||
|
||||
it('invalidates a compact completion when later provider work owns the pane', () => {
|
||||
const server = new AgentHookServer()
|
||||
servers.push(server)
|
||||
server.ingestRemote(manualEnvelope('UserPromptSubmit', 'working'), 'conn-a')
|
||||
server.ingestRemote(manualEnvelope('PreCompact', 'working'), 'conn-a')
|
||||
server.ingestRemote(
|
||||
{
|
||||
source: 'codex',
|
||||
paneKey: PANE_KEY,
|
||||
hookEventName: 'UserPromptSubmit',
|
||||
hasExplicitPrompt: true,
|
||||
payload: { state: 'working', prompt: 'new work', agentType: 'codex' }
|
||||
},
|
||||
'conn-a'
|
||||
)
|
||||
server.ingestRemote({ ...manualEnvelope('PreCompact', 'working'), isReplay: true }, 'conn-a')
|
||||
server.ingestRemote(manualEnvelope('PostCompact', 'done'), 'conn-a')
|
||||
|
||||
expect(server.getStatusSnapshot()[0]).toMatchObject({
|
||||
state: 'working',
|
||||
prompt: 'new work',
|
||||
agentType: 'claude'
|
||||
})
|
||||
expect(server._getStateForTests().lastStatusByPaneKey.get(PANE_KEY)).toMatchObject({
|
||||
source: 'codex',
|
||||
hookEventName: 'UserPromptSubmit'
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps automatic compact hooks working without settling the turn', async () => {
|
||||
it('forwards the completion from a relay whose cache is cold, and the client still guards it', async () => {
|
||||
const main = new AgentHookServer()
|
||||
const forwarded: AgentHookRelayEnvelope[] = []
|
||||
const endpointDir = mkdtempSync(join(tmpdir(), 'orca-auto-compact-relay-'))
|
||||
const endpointDir = mkdtempSync(join(tmpdir(), 'orca-compact-cold-'))
|
||||
temporaryPaths.push(endpointDir)
|
||||
// A relay that restarted while the agent session kept running: hooks resolve the endpoint file
|
||||
// per invocation, so they reconnect — but the relay's per-process cache is empty, and the
|
||||
// compact completion may be the first event it ever sees for this pane.
|
||||
const relay = new RelayAgentHookServer({
|
||||
endpointDir,
|
||||
token: 'cold-cache-token',
|
||||
forward: (envelope) => {
|
||||
forwarded.push(envelope)
|
||||
main.ingestRemote(envelope, 'conn-auto')
|
||||
main.ingestRemote(envelope, 'conn-a')
|
||||
}
|
||||
})
|
||||
servers.push(main, relay)
|
||||
await relay.start({ publishEndpoint: false })
|
||||
const { port, token } = relay.getCoordinates()
|
||||
|
||||
await postHook(
|
||||
port,
|
||||
token,
|
||||
claudeHook('UserPromptSubmit', PROMPT_ID_1, { prompt: 'continue the task' })
|
||||
)
|
||||
await postHook(port, token, claudeHook('PreCompact', PROMPT_ID_1, { trigger: 'auto' }))
|
||||
await postHook(port, token, claudeHook('PostCompact', PROMPT_ID_1, { trigger: 'auto' }))
|
||||
await postHook(port, token, claudeHook('PostCompact', COMPACT_PROMPT_ID, { trigger: 'manual' }))
|
||||
|
||||
expect(forwarded.map((event) => event.hookEventName)).toEqual([
|
||||
'UserPromptSubmit',
|
||||
'PreCompact',
|
||||
'PostCompact'
|
||||
])
|
||||
expect(main.getStatusSnapshot()[0]).toMatchObject({ state: 'working', agentType: 'claude' })
|
||||
expect(main._getStateForTests().lastStatusByPaneKey.get(PANE_KEY)).toMatchObject({
|
||||
hookEventName: 'PostCompact',
|
||||
compactTrigger: undefined
|
||||
// Why: the relay is a forwarder, not the authority on pane identity. Dropping the event here
|
||||
// is how the one signal that can clear a remote pane goes missing after a restart.
|
||||
expect(forwarded.map((envelope) => envelope.hookEventName)).toEqual(['PostCompact'])
|
||||
expect(forwarded[0]).toMatchObject({
|
||||
compactTrigger: 'manual',
|
||||
providerPromptId: COMPACT_PROMPT_ID
|
||||
})
|
||||
// ...and the client, which DOES own pane identity, still refuses to mint a row it never had.
|
||||
expect(main.getStatusSnapshot()).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects unproven compact sources at the main relay boundary', () => {
|
||||
it('does not resurrect a retired pane when the cold relay replays its completion', async () => {
|
||||
const main = new AgentHookServer()
|
||||
const endpointDir = mkdtempSync(join(tmpdir(), 'orca-compact-cold-replay-'))
|
||||
temporaryPaths.push(endpointDir)
|
||||
const relay = new RelayAgentHookServer({
|
||||
endpointDir,
|
||||
token: 'cold-replay-token',
|
||||
forward: (envelope) => main.ingestRemote(envelope, 'conn-a')
|
||||
})
|
||||
servers.push(main, relay)
|
||||
await relay.start({ publishEndpoint: false })
|
||||
const { port, token } = relay.getCoordinates()
|
||||
|
||||
await postHook(port, token, claudeHook('PostCompact', COMPACT_PROMPT_ID, { trigger: 'manual' }))
|
||||
expect(main.getStatusSnapshot()).toEqual([])
|
||||
|
||||
expect(relay.replayCachedPayloadsForPanes()).toBe(1)
|
||||
expect(main.getStatusSnapshot()).toEqual([])
|
||||
})
|
||||
|
||||
it('stamps the silent boundary on a manual completion from a relay that predates it', () => {
|
||||
const server = new AgentHookServer()
|
||||
servers.push(server)
|
||||
server.ingestRemote(turnEnvelope(), 'conn-a')
|
||||
expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'working' })
|
||||
|
||||
server.ingestRemote(legacyRelayCompactEnvelope('done'), 'conn-a')
|
||||
|
||||
// Why: the old relay built this payload before the flag existed, so it arrives as a plain
|
||||
// `done` that every completion-reactive consumer would read as a finished turn.
|
||||
expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'done', sessionBoundary: true })
|
||||
})
|
||||
|
||||
it('drops an auto compact from a relay that predates it, instead of minting working', () => {
|
||||
const server = new AgentHookServer()
|
||||
servers.push(server)
|
||||
server.ingestRemote(turnEnvelope(), 'conn-a')
|
||||
server.ingestRemote(
|
||||
{
|
||||
...manualEnvelope('PreCompact', 'working'),
|
||||
source: 'kimi',
|
||||
payload: { state: 'working', prompt: '', agentType: 'kimi' }
|
||||
},
|
||||
'conn-kimi'
|
||||
)
|
||||
server.ingestRemote(
|
||||
{ ...manualEnvelope('PreCompact', 'working'), compactTrigger: undefined },
|
||||
'conn-auto'
|
||||
...turnEnvelope(),
|
||||
payload: { state: 'done', prompt: 'work', agentType: 'claude' },
|
||||
hookEventName: 'Stop'
|
||||
} as AgentHookRelayEnvelope,
|
||||
'conn-a'
|
||||
)
|
||||
const before = server.getStatusSnapshot()[0]
|
||||
expect(before).toMatchObject({ state: 'done' })
|
||||
|
||||
expect(server.getStatusSnapshot()).toEqual([])
|
||||
expect(server._getStateForTests().lastStatusByPaneKey.size).toBe(0)
|
||||
server.ingestRemote(legacyRelayCompactEnvelope('working'), 'conn-a')
|
||||
|
||||
expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'done' })
|
||||
})
|
||||
|
||||
it('hydrates a manual PreCompact identity and accepts only its exact local completion', async () => {
|
||||
const userDataPath = mkdtempSync(join(tmpdir(), 'orca-compact-restore-'))
|
||||
temporaryPaths.push(userDataPath)
|
||||
const first = new AgentHookServer()
|
||||
servers.push(first)
|
||||
await first.start({ env: 'production', userDataPath })
|
||||
const firstEnv = first.buildPtyEnv()
|
||||
await postHook(
|
||||
Number(firstEnv.ORCA_AGENT_HOOK_PORT),
|
||||
firstEnv.ORCA_AGENT_HOOK_TOKEN,
|
||||
claudeHook('UserPromptSubmit', PROMPT_ID_2, { prompt: 'work before compact' })
|
||||
)
|
||||
await postHook(
|
||||
Number(firstEnv.ORCA_AGENT_HOOK_PORT),
|
||||
firstEnv.ORCA_AGENT_HOOK_TOKEN,
|
||||
claudeHook('PreCompact', PROMPT_ID_1, { trigger: 'manual' })
|
||||
)
|
||||
first.stop()
|
||||
it('suppresses a duplicate completion arriving twice over the relay', () => {
|
||||
const server = new AgentHookServer()
|
||||
servers.push(server)
|
||||
const emitted: string[] = []
|
||||
const unsubscribe = server.subscribeEnrichedStatus((event) => {
|
||||
emitted.push(`${event.hookEventName}:${event.payload.state}`)
|
||||
})
|
||||
server.ingestRemote(turnEnvelope(), 'conn-a')
|
||||
server.ingestRemote(legacyRelayCompactEnvelope('done'), 'conn-a')
|
||||
const applied = server._getStateForTests().lastStatusByPaneKey.get(PANE_KEY)
|
||||
expect(applied?.payload.state).toBe('done')
|
||||
|
||||
const restored = new AgentHookServer()
|
||||
servers.push(restored)
|
||||
await restored.start({ env: 'production', userDataPath })
|
||||
const restoredEnv = restored.buildPtyEnv()
|
||||
await postHook(
|
||||
Number(restoredEnv.ORCA_AGENT_HOOK_PORT),
|
||||
restoredEnv.ORCA_AGENT_HOOK_TOKEN,
|
||||
claudeHook('PostCompact', PROMPT_ID_2, { trigger: 'manual' })
|
||||
)
|
||||
expect(restored.getStatusSnapshot()[0]).toMatchObject({ state: 'working' })
|
||||
server.ingestRemote(legacyRelayCompactEnvelope('done'), 'conn-a')
|
||||
|
||||
await postHook(
|
||||
Number(restoredEnv.ORCA_AGENT_HOOK_PORT),
|
||||
restoredEnv.ORCA_AGENT_HOOK_TOKEN,
|
||||
claudeHook('PostCompact', PROMPT_ID_1, { trigger: 'manual' })
|
||||
// Why: the deleted ownership cache used to reject a repeat; a same-owner guard alone would
|
||||
// accept it and keep refreshing the row, so suppression is keyed on the consumed compact id.
|
||||
expect(emitted).toEqual(['UserPromptSubmit:working', 'PostCompact:done'])
|
||||
expect(server._getStateForTests().lastStatusByPaneKey.get(PANE_KEY)).toBe(applied)
|
||||
unsubscribe()
|
||||
})
|
||||
|
||||
it('classifies a triggerless replay by payload state and still checks ownership', () => {
|
||||
const done = new AgentHookServer()
|
||||
servers.push(done)
|
||||
done.ingestRemote(turnEnvelope(), 'conn-a')
|
||||
// An older relay strips compactTrigger from its cached PostCompact before replaying it.
|
||||
done.ingestRemote(
|
||||
legacyRelayCompactEnvelope('done', { compactTrigger: undefined, isReplay: true }),
|
||||
'conn-a'
|
||||
)
|
||||
expect(restored.getStatusSnapshot()[0]).toMatchObject({
|
||||
expect(done.getStatusSnapshot()[0]).toMatchObject({ state: 'done', sessionBoundary: true })
|
||||
|
||||
// Why: assert this arm from a pane that already FINISHED. Asserting `working` on a pane that
|
||||
// was already `working` cannot fail — it holds whether the replay was dropped or applied, which
|
||||
// is exactly how a trigger-stripped auto compact could start re-arming the stuck row again.
|
||||
const working = new AgentHookServer()
|
||||
servers.push(working)
|
||||
working.ingestRemote(turnEnvelope(), 'conn-a')
|
||||
working.ingestRemote(
|
||||
{
|
||||
...turnEnvelope(),
|
||||
hookEventName: 'Stop',
|
||||
payload: { state: 'done', prompt: 'work before compact', agentType: 'claude' }
|
||||
} as AgentHookRelayEnvelope,
|
||||
'conn-a'
|
||||
)
|
||||
expect(working.getStatusSnapshot()[0]).toMatchObject({ state: 'done' })
|
||||
working.ingestRemote(
|
||||
legacyRelayCompactEnvelope('working', { compactTrigger: undefined, isReplay: true }),
|
||||
'conn-a'
|
||||
)
|
||||
expect(working.getStatusSnapshot()[0]).toMatchObject({ state: 'done' })
|
||||
|
||||
const foreign = new AgentHookServer()
|
||||
servers.push(foreign)
|
||||
foreign.ingestRemote(turnEnvelope(), 'conn-a')
|
||||
// Payload state substitutes for the missing trigger only — ownership is still enforced.
|
||||
foreign.ingestRemote(
|
||||
legacyRelayCompactEnvelope('done', {
|
||||
compactTrigger: undefined,
|
||||
isReplay: true,
|
||||
providerSession: { key: 'session_id', id: 'a-different-session' }
|
||||
}),
|
||||
'conn-a'
|
||||
)
|
||||
expect(foreign.getStatusSnapshot()[0]).toMatchObject({ state: 'working' })
|
||||
})
|
||||
|
||||
it('keeps the summarized turn as the label, with or without a trigger on the envelope', () => {
|
||||
// The compact's own event carries no prompt of its own, so the row's label can only come from
|
||||
// the turn it summarized. The trigger-stripped replay is the one shape that arrives with no
|
||||
// trigger at all, so the carry-forward must not be keyed on the trigger being present.
|
||||
const blank = { state: 'done' as const, prompt: '', agentType: 'claude' }
|
||||
|
||||
const tagged = new AgentHookServer()
|
||||
servers.push(tagged)
|
||||
tagged.ingestRemote(turnEnvelope(), 'conn-a')
|
||||
tagged.ingestRemote(legacyRelayCompactEnvelope('done', { payload: blank }), 'conn-a')
|
||||
expect(tagged.getStatusSnapshot()[0]).toMatchObject({
|
||||
state: 'done',
|
||||
prompt: 'work before compact',
|
||||
agentType: 'claude'
|
||||
prompt: 'work before compact'
|
||||
})
|
||||
|
||||
const stripped = new AgentHookServer()
|
||||
servers.push(stripped)
|
||||
stripped.ingestRemote(turnEnvelope(), 'conn-a')
|
||||
stripped.ingestRemote(
|
||||
legacyRelayCompactEnvelope('done', {
|
||||
compactTrigger: undefined,
|
||||
isReplay: true,
|
||||
payload: blank
|
||||
}),
|
||||
'conn-a'
|
||||
)
|
||||
expect(stripped.getStatusSnapshot()[0]).toMatchObject({
|
||||
state: 'done',
|
||||
prompt: 'work before compact'
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects a completion with no provider prompt id', () => {
|
||||
const server = new AgentHookServer()
|
||||
servers.push(server)
|
||||
server.ingestRemote(turnEnvelope(), 'conn-a')
|
||||
|
||||
server.ingestRemote(
|
||||
legacyRelayCompactEnvelope('done', { providerPromptId: undefined }),
|
||||
'conn-a'
|
||||
)
|
||||
|
||||
expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'working' })
|
||||
})
|
||||
|
||||
it('never lets a PreCompact envelope drive pane state', () => {
|
||||
const server = new AgentHookServer()
|
||||
servers.push(server)
|
||||
server.ingestRemote(turnEnvelope(), 'conn-a')
|
||||
server.ingestRemote(
|
||||
{
|
||||
...turnEnvelope(),
|
||||
payload: { state: 'done', prompt: 'work', agentType: 'claude' },
|
||||
hookEventName: 'Stop'
|
||||
} as AgentHookRelayEnvelope,
|
||||
'conn-a'
|
||||
)
|
||||
|
||||
server.ingestRemote(
|
||||
legacyRelayCompactEnvelope('working', {
|
||||
hookEventName: 'PreCompact',
|
||||
compactTrigger: 'manual'
|
||||
}),
|
||||
'conn-a'
|
||||
)
|
||||
|
||||
expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'done' })
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -27,6 +27,52 @@ afterEach(() => {
|
||||
})
|
||||
|
||||
describe('AgentHookServer ingestTerminalStatus', () => {
|
||||
it('keeps hook monitoring mode across an equivalent OSC ping until a hook clears it', () => {
|
||||
const server = new AgentHookServer()
|
||||
|
||||
server.ingestRemote(
|
||||
{
|
||||
paneKey: PANE,
|
||||
source: 'claude',
|
||||
hookEventName: 'Stop',
|
||||
payload: {
|
||||
state: 'working',
|
||||
workingMode: 'monitoring',
|
||||
prompt: 'watch the build',
|
||||
agentType: 'claude'
|
||||
}
|
||||
},
|
||||
'conn-1'
|
||||
)
|
||||
server.ingestTerminalStatus({
|
||||
paneKey: PANE,
|
||||
connectionId: 'conn-1',
|
||||
payload: { state: 'working', prompt: 'watch the build', agentType: 'claude' }
|
||||
})
|
||||
|
||||
expect(server.getStatusSnapshot()[0]).toMatchObject({
|
||||
state: 'working',
|
||||
workingMode: 'monitoring'
|
||||
})
|
||||
|
||||
server.ingestRemote(
|
||||
{
|
||||
paneKey: PANE,
|
||||
source: 'claude',
|
||||
hookEventName: 'PreToolUse',
|
||||
payload: {
|
||||
state: 'working',
|
||||
prompt: 'watch the build',
|
||||
agentType: 'claude',
|
||||
toolName: 'Read'
|
||||
}
|
||||
},
|
||||
'conn-1'
|
||||
)
|
||||
|
||||
expect(server.getStatusSnapshot()[0]?.workingMode).toBeUndefined()
|
||||
})
|
||||
|
||||
it('preserves a hook turn stamp when an OSC repaint omits hook-only completion text', () => {
|
||||
const server = new AgentHookServer()
|
||||
const listener = vi.fn()
|
||||
|
||||
@@ -228,6 +228,7 @@ describe('AgentHookServer listener replay', () => {
|
||||
const baseline = server.getStatusSnapshot()[0]
|
||||
|
||||
expect(baseline).not.toHaveProperty('claudeRunningNonAgentTask')
|
||||
expect(baseline).toMatchObject({ state: 'working', workingMode: 'monitoring' })
|
||||
expect(
|
||||
server.inferInterrupt({
|
||||
paneKey: PANE,
|
||||
|
||||
@@ -77,7 +77,11 @@ describe('Last-status persistence', () => {
|
||||
worktreeId: 'wt-1',
|
||||
receivedAt: expect.any(Number),
|
||||
stateStartedAt: expect.any(Number),
|
||||
payload: expect.objectContaining({ state: 'working', prompt: 'persist me' })
|
||||
payload: expect.objectContaining({
|
||||
state: 'working',
|
||||
workingMode: 'monitoring',
|
||||
prompt: 'persist me'
|
||||
})
|
||||
})
|
||||
expect(file.entries[PANE].launchToken).toBeUndefined()
|
||||
expect(file.entries[PANE].launchTokenHash).toBe(
|
||||
|
||||
+148
-61
@@ -12,6 +12,7 @@ import { ORCA_HOOK_PROTOCOL_VERSION } from '../../shared/agent-hook-types'
|
||||
import {
|
||||
clearAllListenerCaches,
|
||||
clearPaneCacheState,
|
||||
paneHasStateClaims,
|
||||
clearClaudeAnsweredQuestionWait,
|
||||
createHookListenerState,
|
||||
getEndpointFileName,
|
||||
@@ -23,14 +24,12 @@ import {
|
||||
markCodexLeadTurnInterrupted,
|
||||
MAX_PANE_KEY_LEN,
|
||||
movePaneCacheState,
|
||||
canAcceptClaudeCompactTransition,
|
||||
normalizeClaudePromptId,
|
||||
normalizeHookPayload,
|
||||
parseFormEncodedBody,
|
||||
readRequestBody,
|
||||
reapRestoredClaudeSubagentsForDeadPane,
|
||||
reconcileRemoteCodexState,
|
||||
resolveCachedClaudeCompactOwnership,
|
||||
resolveHookSource,
|
||||
preparePendingGrokResultDiscovery,
|
||||
seedClaudeLeadTurnFromPersistedStatus,
|
||||
@@ -41,6 +40,12 @@ import {
|
||||
type AgentHookEventPayload,
|
||||
type HookListenerState
|
||||
} from '../../shared/agent-hook-listener'
|
||||
import {
|
||||
canAcceptClaudeCompactCompletion,
|
||||
isClaudeCompactCompletionConsumed,
|
||||
markClaudeCompactCompletionConsumed,
|
||||
resolveLegacyCompactTrigger
|
||||
} from '../../shared/claude-compact-completion'
|
||||
import {
|
||||
createHookTransportInterferenceTracker,
|
||||
describeHookTransportInterference,
|
||||
@@ -72,6 +77,7 @@ import {
|
||||
type ParsedAgentStatusPayload,
|
||||
normalizeAgentStatusPayload
|
||||
} from '../../shared/agent-status-types'
|
||||
import { terminalStatusPayloadMatchesHook } from '../../shared/agent-terminal-status-equivalence'
|
||||
import {
|
||||
AgentStatusObservationSequencer,
|
||||
createAgentStatusAuthorityId,
|
||||
@@ -448,30 +454,6 @@ function toAgentStatusIpcPayload(entry: EnrichedAgentHookEventPayload): AgentSta
|
||||
}
|
||||
}
|
||||
|
||||
// Why: OSC never carries model/children; omit both so an equivalent OSC ping preserves the hook-cached identity graph.
|
||||
function equivalentParsedAgentStatusPayload(
|
||||
a: ParsedAgentStatusPayload,
|
||||
b: ParsedAgentStatusPayload,
|
||||
preserveActiveTurnStamp = false
|
||||
): boolean {
|
||||
return (
|
||||
a.state === b.state &&
|
||||
a.prompt === b.prompt &&
|
||||
a.agentType === b.agentType &&
|
||||
a.toolName === b.toolName &&
|
||||
a.toolInput === b.toolInput &&
|
||||
a.interactivePrompt === b.interactivePrompt &&
|
||||
(a.lastAssistantMessage === b.lastAssistantMessage ||
|
||||
(preserveActiveTurnStamp && b.lastAssistantMessage === undefined)) &&
|
||||
a.interrupted === b.interrupted &&
|
||||
// Why: a session-boundary done must never be deduped against a cached real done —
|
||||
// the flag has to reach receivers deterministically (STA-3386).
|
||||
a.sessionBoundary === b.sessionBoundary &&
|
||||
(a.turnCompletedAt === b.turnCompletedAt ||
|
||||
(preserveActiveTurnStamp && b.turnCompletedAt === undefined))
|
||||
)
|
||||
}
|
||||
|
||||
function trackEmptyPaneKeyHook(body: unknown): void {
|
||||
if (typeof body !== 'object' || body === null) {
|
||||
return
|
||||
@@ -1039,6 +1021,7 @@ export class AgentHookServer {
|
||||
providerSession: existing.providerSession,
|
||||
payload: {
|
||||
state: restored.state,
|
||||
...(restored.workingMode ? { workingMode: restored.workingMode } : {}),
|
||||
prompt: payload.prompt,
|
||||
agentType: payload.agentType,
|
||||
...(restored.state === 'done' && restored.interrupted ? { interrupted: true } : {}),
|
||||
@@ -1541,10 +1524,9 @@ export class AgentHookServer {
|
||||
if (!identity.inheritedFromActivePane) {
|
||||
this.maybeTrackAgentPromptSent(effectivePayload, previous)
|
||||
}
|
||||
const cachedPayload = resolveCachedClaudeCompactOwnership(previous, boundaryAwarePayload)
|
||||
const enriched = {
|
||||
...this.attachStatusTiming(cachedPayload, now),
|
||||
observation: this.stampObservation(cachedPayload, origin, now)
|
||||
...this.attachStatusTiming(boundaryAwarePayload, now),
|
||||
observation: this.stampObservation(boundaryAwarePayload, origin, now)
|
||||
}
|
||||
if (
|
||||
typeof enriched.payload.turnCompletedAt === 'number' &&
|
||||
@@ -2201,7 +2183,7 @@ export class AgentHookServer {
|
||||
previous?.connectionId === connectionId &&
|
||||
previous.tabId === tabId &&
|
||||
previous.worktreeId === worktreeId &&
|
||||
equivalentParsedAgentStatusPayload(previous.payload, event.payload, preserveActiveTurnStamp)
|
||||
terminalStatusPayloadMatchesHook(previous.payload, event.payload, preserveActiveTurnStamp)
|
||||
) {
|
||||
return
|
||||
}
|
||||
@@ -2378,39 +2360,59 @@ export class AgentHookServer {
|
||||
this.state.lastStatusByPaneKey.get(paneKey)?.payload
|
||||
)
|
||||
const previousStatus = this.state.lastStatusByPaneKey.get(paneKey)
|
||||
let acceptedCompactCompletion = false
|
||||
if (hookEventName === 'PreCompact' || hookEventName === 'PostCompact') {
|
||||
if (
|
||||
source !== 'claude' ||
|
||||
compactTrigger === undefined ||
|
||||
normalizedPayload.agentType !== source
|
||||
) {
|
||||
// Why: PreCompact is never registered and proves nothing (an aborted compact emits it alone);
|
||||
// reject it here too so a host on any version cannot drive pane state from it.
|
||||
if (hookEventName === 'PreCompact' || source !== 'claude') {
|
||||
return
|
||||
}
|
||||
// Why: a relay predating this change strips `compactTrigger` from its cached PostCompact
|
||||
// before replaying it, so the replay has no manual/auto discriminator. That relay's mapping is
|
||||
// fixed and known — manual produced `done`, auto produced `working` — so the payload state
|
||||
// stands in for the missing trigger. Trigger substitution only; ownership is still checked.
|
||||
const effectiveTrigger = resolveLegacyCompactTrigger(compactTrigger, normalizedPayload.state)
|
||||
// Why: an auto compact happens inside a turn that resumes and emits its own Stop. An older
|
||||
// relay maps it to `working`, and this ingest applies the relay's payload verbatim — so
|
||||
// without this drop, every auto compact on such a host mints exactly the stuck `working` this
|
||||
// change removes.
|
||||
if (effectiveTrigger !== 'manual' || normalizedPayload.agentType !== source) {
|
||||
return
|
||||
}
|
||||
if (
|
||||
hookEventName === 'PreCompact' &&
|
||||
envelope.isReplay === true &&
|
||||
(previousStatus?.hookEventName !== 'PreCompact' ||
|
||||
previousStatus.compactTrigger !== compactTrigger ||
|
||||
previousStatus.providerPromptId !== providerPromptId)
|
||||
) {
|
||||
return
|
||||
}
|
||||
if (
|
||||
!canAcceptClaudeCompactTransition(previousStatus, {
|
||||
isClaudeCompactCompletionConsumed(
|
||||
this.state.claudeConsumedCompactPromptIdByPaneKey,
|
||||
paneKey,
|
||||
providerPromptId
|
||||
) ||
|
||||
!canAcceptClaudeCompactCompletion(previousStatus, {
|
||||
source,
|
||||
connectionId: trimmedConnectionId,
|
||||
hookEventName,
|
||||
providerPromptId,
|
||||
compactTrigger,
|
||||
providerSession
|
||||
})
|
||||
) {
|
||||
return
|
||||
}
|
||||
markClaudeCompactCompletionConsumed(
|
||||
this.state.claudeConsumedCompactPromptIdByPaneKey,
|
||||
paneKey,
|
||||
providerPromptId
|
||||
)
|
||||
// Why: an older relay built this payload before the boundary flag existed, so it arrives as a
|
||||
// plain `done` — which every completion-reactive consumer reads as a finished turn. Stamp the
|
||||
// boundary here so a compact stays silent regardless of which relay normalized it.
|
||||
if (normalizedPayload.sessionBoundary !== true) {
|
||||
normalizedPayload = { ...normalizedPayload, sessionBoundary: true }
|
||||
}
|
||||
acceptedCompactCompletion = true
|
||||
}
|
||||
// Why: keyed on "did we accept a completion", not on the trigger surviving the wire — the
|
||||
// trigger-stripped replay is exactly the shape that arrives without one, and it is still the
|
||||
// compact's own promptless event, so it still needs the summarized turn's label.
|
||||
if (
|
||||
source === 'claude' &&
|
||||
compactTrigger !== undefined &&
|
||||
(compactTrigger !== undefined || acceptedCompactCompletion) &&
|
||||
normalizedPayload.prompt.length === 0 &&
|
||||
previousStatus?.payload.prompt
|
||||
) {
|
||||
@@ -2652,28 +2654,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 +2765,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 +2956,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 +2992,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
|
||||
@@ -2949,7 +3031,12 @@ export class AgentHookServer {
|
||||
...(state !== 'done' && restoredUnconfirmed ? { restoredUnconfirmed: true } : {}),
|
||||
receivedAt: reconciledAt,
|
||||
stateStartedAt: stateChanged ? reconciledAt : enriched.stateStartedAt,
|
||||
payload: { ...enriched.payload, state, subagents }
|
||||
payload: {
|
||||
...enriched.payload,
|
||||
state,
|
||||
workingMode: state === 'working' ? enriched.payload.workingMode : undefined,
|
||||
subagents
|
||||
}
|
||||
}
|
||||
this.state.lastStatusByPaneKey.set(paneKey, reconciled)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { join } from 'node:path'
|
||||
import {
|
||||
clearAiVaultBackgroundRestartCircuit,
|
||||
resetAiVaultScannerBackgroundForTests,
|
||||
scanAiVaultSessionsInBackground
|
||||
} from './session-scanner-background'
|
||||
@@ -56,6 +57,9 @@ export async function listAiVaultSessions(
|
||||
const depth = requestedAiVaultSessionDepth(args)
|
||||
const scanKey = JSON.stringify({ key, depth })
|
||||
const now = Date.now()
|
||||
if (args?.force === true) {
|
||||
clearAiVaultBackgroundRestartCircuit()
|
||||
}
|
||||
// Why: opening this panel repeatedly should not re-parse hundreds of JSONL
|
||||
// transcripts; explicit refreshes bypass the cache and preempt stale scans.
|
||||
if (
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
type ReadAiVaultFirstUserPromptResult
|
||||
} from './session-first-user-prompt-read'
|
||||
import {
|
||||
clearAiVaultServiceRestartCircuit,
|
||||
invalidateAiVaultServiceCache,
|
||||
listAiVaultSubagentSessionsInService,
|
||||
readAiVaultFirstUserPromptInService,
|
||||
@@ -36,6 +37,13 @@ export function shouldUseAiVaultServiceProcess(): boolean {
|
||||
return process.env.NODE_ENV !== 'test'
|
||||
}
|
||||
|
||||
// Let forced refreshes retry after a local service circuit opens.
|
||||
export function clearAiVaultBackgroundRestartCircuit(): void {
|
||||
if (shouldUseAiVaultServiceProcess()) {
|
||||
clearAiVaultServiceRestartCircuit()
|
||||
}
|
||||
}
|
||||
|
||||
export function scanAiVaultSessionsInBackground(
|
||||
options: AiVaultWorkerScanOptions,
|
||||
signal?: AbortSignal
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import type { ChildProcess } from 'node:child_process'
|
||||
import type {
|
||||
AiVaultServiceInit,
|
||||
AiVaultServiceLane,
|
||||
AiVaultServiceRequest
|
||||
import {
|
||||
AI_VAULT_SERVICE_PROTOCOL_VERSION,
|
||||
type AiVaultServiceInit,
|
||||
type AiVaultServiceLane,
|
||||
type AiVaultServiceRequest
|
||||
} from './session-scanner-service-protocol'
|
||||
|
||||
export const AI_VAULT_SERVICE_READY_TIMEOUT_MS = 5_000
|
||||
@@ -110,6 +111,28 @@ export function armAiVaultServiceCancellationTimeout(
|
||||
* A cold start that faults before the request reached the child self-heals on
|
||||
* the scheduled respawn. Requeue once; the caller rejects when this returns false.
|
||||
*/
|
||||
/** Wires a freshly forked child to the client's callbacks and hands it the init frame. */
|
||||
export function attachAiVaultServiceChild(
|
||||
child: ChildProcess,
|
||||
init: AiVaultServiceClientOptions['init'],
|
||||
handlers: {
|
||||
onMessage: (message: unknown) => void
|
||||
onFault: (error: Error) => void
|
||||
onStderr?: (text: string) => void
|
||||
}
|
||||
): void {
|
||||
child.on('message', handlers.onMessage)
|
||||
child.on('error', handlers.onFault)
|
||||
child.on('disconnect', () => handlers.onFault(new Error('AI Vault service disconnected.')))
|
||||
child.on('exit', (code) => handlers.onFault(new Error(`AI Vault service exited (${code}).`)))
|
||||
child.stderr?.on('data', (chunk: Buffer) => handlers.onStderr?.(String(chunk)))
|
||||
child.send({
|
||||
type: 'init',
|
||||
protocol: AI_VAULT_SERVICE_PROTOCOL_VERSION,
|
||||
...init
|
||||
} satisfies AiVaultServiceInit)
|
||||
}
|
||||
|
||||
export function requeueAiVaultServiceStart(
|
||||
call: AiVaultServicePendingCall,
|
||||
queue: AiVaultServicePendingCall[]
|
||||
|
||||
@@ -181,6 +181,87 @@ describe('AiVaultScannerServiceClient', () => {
|
||||
client.dispose()
|
||||
})
|
||||
|
||||
it('starts a queued retry immediately when a forced refresh clears backoff', async () => {
|
||||
vi.useFakeTimers()
|
||||
const children: AiVaultServiceTestChild[] = []
|
||||
const client = new AiVaultScannerServiceClient({
|
||||
processFactory: () => {
|
||||
const child = new AiVaultServiceTestChild(18_345 + children.length)
|
||||
children.push(child)
|
||||
return child.asChildProcess()
|
||||
},
|
||||
init: { sessionParseCache: null }
|
||||
})
|
||||
const titles = client.request({ type: 'request', operation: 'titles', requests: [] })
|
||||
|
||||
vi.advanceTimersByTime(AI_VAULT_SERVICE_READY_TIMEOUT_MS)
|
||||
await Promise.resolve()
|
||||
expect(children).toHaveLength(1)
|
||||
|
||||
client.clearRestartCircuit()
|
||||
expect(children).toHaveLength(2)
|
||||
|
||||
readyAiVaultServiceChild(children[1]!)
|
||||
await vi.waitFor(() =>
|
||||
expect(children[1]!.sent).toContainEqual(expect.objectContaining({ operation: 'titles' }))
|
||||
)
|
||||
children[1]!.emit('message', {
|
||||
type: 'result',
|
||||
id: aiVaultServiceRequestId(children[1]!, 'titles'),
|
||||
operation: 'titles',
|
||||
value: { titles: [] }
|
||||
})
|
||||
await expect(titles).resolves.toEqual({ titles: [] })
|
||||
client.dispose()
|
||||
})
|
||||
|
||||
it('lets a forced refresh reopen the circuit instead of waiting out the window', async () => {
|
||||
vi.useFakeTimers()
|
||||
const children: AiVaultServiceTestChild[] = []
|
||||
const client = new AiVaultScannerServiceClient({
|
||||
processFactory: () => {
|
||||
const child = new AiVaultServiceTestChild(22_345 + children.length)
|
||||
children.push(child)
|
||||
return child.asChildProcess()
|
||||
},
|
||||
init: { sessionParseCache: null }
|
||||
})
|
||||
// Each request retries its cold start once, so two requests spend the three
|
||||
// faults the circuit breaker needs.
|
||||
const first = client.request({ type: 'request', operation: 'titles', requests: [] })
|
||||
vi.advanceTimersByTime(AI_VAULT_SERVICE_READY_TIMEOUT_MS)
|
||||
await Promise.resolve()
|
||||
vi.advanceTimersByTime(250)
|
||||
await Promise.resolve()
|
||||
vi.advanceTimersByTime(AI_VAULT_SERVICE_READY_TIMEOUT_MS)
|
||||
await expect(first).rejects.toThrow('did not become ready')
|
||||
vi.advanceTimersByTime(1_000)
|
||||
await Promise.resolve()
|
||||
|
||||
const blocked = client.request({ type: 'request', operation: 'titles', requests: [] })
|
||||
vi.advanceTimersByTime(AI_VAULT_SERVICE_READY_TIMEOUT_MS)
|
||||
await Promise.resolve()
|
||||
vi.advanceTimersByTime(5_000)
|
||||
await expect(blocked).rejects.toThrow('circuit is open')
|
||||
expect(children).toHaveLength(3)
|
||||
|
||||
client.clearRestartCircuit()
|
||||
const retried = client.request({ type: 'request', operation: 'titles', requests: [] })
|
||||
await vi.waitFor(() => expect(children).toHaveLength(4))
|
||||
readyAiVaultServiceChild(children[3]!)
|
||||
await vi.waitFor(() =>
|
||||
expect(children[3]!.sent).toContainEqual(expect.objectContaining({ operation: 'titles' }))
|
||||
)
|
||||
children[3]!.emit('message', {
|
||||
type: 'result',
|
||||
id: aiVaultServiceRequestId(children[3]!, 'titles'),
|
||||
operation: 'titles',
|
||||
value: { titles: [] }
|
||||
})
|
||||
await expect(retried).resolves.toEqual({ titles: [] })
|
||||
client.dispose()
|
||||
})
|
||||
|
||||
it('acknowledges cache invalidation through the running child', async () => {
|
||||
const { child, client } = setup()
|
||||
const invalidation = client.invalidate(['/tmp/deleted.jsonl'])
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
AiVaultServiceIdleRetirement,
|
||||
AiVaultServiceInvalidations,
|
||||
armAiVaultServiceCancellationTimeout,
|
||||
attachAiVaultServiceChild,
|
||||
clearAiVaultServiceCall,
|
||||
createAiVaultServiceReadyWaiter,
|
||||
rejectAiVaultServiceCall,
|
||||
@@ -20,11 +21,9 @@ import {
|
||||
} from './session-scanner-service-client-state'
|
||||
import { AiVaultServiceRestartPolicy } from './session-scanner-service-restart-policy'
|
||||
import {
|
||||
AI_VAULT_SERVICE_PROTOCOL_VERSION,
|
||||
aiVaultServiceLane,
|
||||
isAiVaultServiceChildMessage,
|
||||
type AiVaultServiceChildMessage,
|
||||
type AiVaultServiceInit,
|
||||
type AiVaultServiceRequest,
|
||||
type AiVaultServiceRequestBody,
|
||||
type AiVaultServiceResultValue
|
||||
@@ -77,6 +76,11 @@ export class AiVaultScannerServiceClient {
|
||||
})
|
||||
}
|
||||
|
||||
clearRestartCircuit(): void {
|
||||
this.restartPolicy.clearCircuit()
|
||||
this.pump()
|
||||
}
|
||||
|
||||
async invalidate(paths: string[]): Promise<void> {
|
||||
if (paths.length === 0 || this.disposed) {
|
||||
return
|
||||
@@ -199,16 +203,11 @@ export class AiVaultScannerServiceClient {
|
||||
this.onFault(new Error('AI Vault service did not become ready.'))
|
||||
)
|
||||
this.readyWaiter = waiter
|
||||
child.on('message', (message) => this.onMessage(message))
|
||||
child.on('error', (error) => this.onFault(error))
|
||||
child.on('disconnect', () => this.onFault(new Error('AI Vault service disconnected.')))
|
||||
child.on('exit', (code) => this.onFault(new Error(`AI Vault service exited (${code}).`)))
|
||||
child.stderr?.on('data', (chunk: Buffer) => this.options.onStderr?.(String(chunk)))
|
||||
child.send({
|
||||
type: 'init',
|
||||
protocol: AI_VAULT_SERVICE_PROTOCOL_VERSION,
|
||||
...this.options.init
|
||||
} satisfies AiVaultServiceInit)
|
||||
attachAiVaultServiceChild(child, this.options.init, {
|
||||
onMessage: (message) => this.onMessage(message),
|
||||
onFault: (error) => this.onFault(error),
|
||||
onStderr: this.options.onStderr
|
||||
})
|
||||
return waiter.promise
|
||||
}
|
||||
|
||||
|
||||
@@ -30,6 +30,22 @@ describe('AiVaultServiceRestartPolicy', () => {
|
||||
expect(policy.restartScheduled).toBe(false)
|
||||
})
|
||||
|
||||
it('clears the pending backoff and fault history for a forced retry', () => {
|
||||
vi.useFakeTimers()
|
||||
const policy = new AiVaultServiceRestartPolicy()
|
||||
const restart = vi.fn()
|
||||
|
||||
policy.recordFault(restart)
|
||||
policy.clearCircuit()
|
||||
vi.advanceTimersByTime(10_000)
|
||||
|
||||
expect(restart).not.toHaveBeenCalled()
|
||||
policy.recordFault(restart)
|
||||
policy.recordFault(restart)
|
||||
expect(policy.startError()).toBeNull()
|
||||
policy.dispose()
|
||||
})
|
||||
|
||||
it('opens the circuit after three faults inside the window', () => {
|
||||
let now = 0
|
||||
const policy = new AiVaultServiceRestartPolicy(() => now)
|
||||
|
||||
@@ -12,6 +12,16 @@ export class AiVaultServiceRestartPolicy {
|
||||
return this.timer !== null
|
||||
}
|
||||
|
||||
/** A forced refresh starts a fresh retry window immediately. */
|
||||
clearCircuit(): void {
|
||||
this.circuitUntil = 0
|
||||
this.faults = []
|
||||
if (this.timer) {
|
||||
clearTimeout(this.timer)
|
||||
this.timer = null
|
||||
}
|
||||
}
|
||||
|
||||
startError(): Error | null {
|
||||
return this.now() < this.circuitUntil
|
||||
? new Error('AI Vault service restart circuit is open.')
|
||||
|
||||
@@ -85,6 +85,11 @@ export function invalidateAiVaultServiceCache(paths: string[]): Promise<void> {
|
||||
return sharedClient?.invalidate(paths) ?? Promise.resolve()
|
||||
}
|
||||
|
||||
/** A forced refresh is a deliberate user action, so it reopens the restart circuit. */
|
||||
export function clearAiVaultServiceRestartCircuit(): void {
|
||||
sharedClient?.clearRestartCircuit()
|
||||
}
|
||||
|
||||
export function resetAiVaultScannerServiceForTests(): void {
|
||||
sharedClient?.dispose()
|
||||
sharedClient = null
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { appRelaunchMock, recordDurableCrashBreadcrumbMock } = vi.hoisted(() => ({
|
||||
appRelaunchMock: vi.fn(),
|
||||
@@ -11,12 +11,24 @@ vi.mock('./crash-reporting/durable-crash-breadcrumb', () => ({
|
||||
}))
|
||||
|
||||
import { relaunchApp } from './app-relaunch'
|
||||
import { _resetHydrateShellPathCache, _setLaunchPathForTests } from './startup/hydrate-shell-path'
|
||||
|
||||
beforeEach(() => {
|
||||
appRelaunchMock.mockReset()
|
||||
recordDurableCrashBreadcrumbMock.mockReset()
|
||||
})
|
||||
|
||||
const originalPath = process.env.PATH
|
||||
|
||||
afterEach(() => {
|
||||
_resetHydrateShellPathCache()
|
||||
if (originalPath === undefined) {
|
||||
delete process.env.PATH
|
||||
} else {
|
||||
process.env.PATH = originalPath
|
||||
}
|
||||
})
|
||||
|
||||
describe('relaunchApp', () => {
|
||||
it('durably records the reason before scheduling the replacement process', () => {
|
||||
relaunchApp('gpu-fallback', { processReason: 'crashed', exitCode: 5 })
|
||||
@@ -32,4 +44,18 @@ describe('relaunchApp', () => {
|
||||
appRelaunchMock.mock.invocationCallOrder[0]
|
||||
)
|
||||
})
|
||||
|
||||
it('does not carry Orca PATH seeds into the replacement process', () => {
|
||||
process.env.PATH = '/seeded/newest-nvm/bin:/usr/bin'
|
||||
_setLaunchPathForTests('/usr/bin')
|
||||
let inheritedPath: string | undefined
|
||||
appRelaunchMock.mockImplementation(() => {
|
||||
inheritedPath = process.env.PATH
|
||||
})
|
||||
|
||||
relaunchApp('renderer-request')
|
||||
|
||||
expect(inheritedPath).toBe('/usr/bin')
|
||||
expect(process.env.PATH).toBe('/seeded/newest-nvm/bin:/usr/bin')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { app } from 'electron'
|
||||
import type { CrashReportBreadcrumbData } from '../shared/crash-reporting'
|
||||
import { recordDurableCrashBreadcrumb } from './crash-reporting/durable-crash-breadcrumb'
|
||||
import { runWithLaunchPath } from './startup/hydrate-shell-path'
|
||||
|
||||
export type AppRelaunchReason =
|
||||
| 'admin-restart'
|
||||
@@ -13,5 +14,5 @@ export function relaunchApp(reason: AppRelaunchReason, data?: CrashReportBreadcr
|
||||
// Why: the current process can exit immediately after app.relaunch(), so
|
||||
// persist the cause before Electron schedules the replacement process.
|
||||
recordDurableCrashBreadcrumb('app_relaunch_requested', { ...data, reason })
|
||||
app.relaunch()
|
||||
runWithLaunchPath(() => app.relaunch())
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -6,6 +6,7 @@ import { join } from 'node:path'
|
||||
import { PassThrough } from 'node:stream'
|
||||
import type { ClaudeManagedAccount } from '../../shared/managed-account-types'
|
||||
import { readActiveClaudeKeychainCredentials } from './keychain'
|
||||
import { getCmdExePath } from '../../shared/windows-batch-spawn'
|
||||
import {
|
||||
createService,
|
||||
resetClaudeKeychainMocks,
|
||||
@@ -516,7 +517,24 @@ describe('ClaudeAccountService credential capture', () => {
|
||||
const destroyStdin = vi.spyOn(child.stdin, 'destroy')
|
||||
const taskkill = new EventEmitter()
|
||||
const spawnMock = vi.fn((command: string) => (command === 'taskkill.exe' ? taskkill : child))
|
||||
const cleanupInteractiveLogin = vi.fn()
|
||||
let publishTerminationPid: (pid: number) => void = () => {}
|
||||
const buildInteractiveLoginSpawn = vi.fn(() => ({
|
||||
command: getCmdExePath(),
|
||||
args: ['/d', '/c', 'start', '', '/wait', 'claude', 'auth', 'login', '--claudeai'],
|
||||
stdio: 'ignore' as const,
|
||||
windowsHide: true,
|
||||
cleanup: cleanupInteractiveLogin,
|
||||
getTerminationPid: () => null,
|
||||
waitForTerminationPid: () =>
|
||||
new Promise<number>((resolve) => {
|
||||
publishTerminationPid = resolve
|
||||
})
|
||||
}))
|
||||
vi.doMock('node:child_process', () => ({ spawn: spawnMock }))
|
||||
vi.doMock('../../shared/windows-interactive-login-spawn', () => ({
|
||||
buildWindowsHostInteractiveLoginSpawn: buildInteractiveLoginSpawn
|
||||
}))
|
||||
|
||||
try {
|
||||
const { ClaudeAccountService } = await import('./service')
|
||||
@@ -548,28 +566,43 @@ describe('ClaudeAccountService credential capture', () => {
|
||||
|
||||
const addPromise = service.addAccount()
|
||||
await vi.waitFor(() => {
|
||||
expect(buildInteractiveLoginSpawn).toHaveBeenCalledWith('claude', [
|
||||
'auth',
|
||||
'login',
|
||||
'--claudeai'
|
||||
])
|
||||
expect(spawnMock).toHaveBeenCalledWith(
|
||||
process.env.ComSpec ?? 'cmd.exe',
|
||||
['/d', '/v:off', '/s', '/c', '""claude" "auth" "login" "--claudeai""'],
|
||||
expect.objectContaining({ shell: false, windowsVerbatimArguments: true })
|
||||
getCmdExePath(),
|
||||
['/d', '/c', 'start', '', '/wait', 'claude', 'auth', 'login', '--claudeai'],
|
||||
expect.objectContaining({ stdio: 'ignore', windowsHide: true })
|
||||
)
|
||||
})
|
||||
|
||||
expect(service.cancelPendingLogin()).toBe(true)
|
||||
const rejection = expect(addPromise).rejects.toThrow('Claude sign-in was cancelled.')
|
||||
expect(child.kill).not.toHaveBeenCalled()
|
||||
expect(spawnMock).toHaveBeenCalledWith(
|
||||
expect(spawnMock).not.toHaveBeenCalledWith(
|
||||
'taskkill.exe',
|
||||
['/pid', '1234', '/t', '/f'],
|
||||
expect.objectContaining({ stdio: 'ignore', windowsHide: true })
|
||||
expect.anything(),
|
||||
expect.anything()
|
||||
)
|
||||
publishTerminationPid(9876)
|
||||
await vi.waitFor(() => {
|
||||
expect(spawnMock).toHaveBeenCalledWith(
|
||||
'taskkill.exe',
|
||||
['/pid', '9876', '/t', '/f'],
|
||||
expect.objectContaining({ stdio: 'ignore', windowsHide: true })
|
||||
)
|
||||
})
|
||||
expect(destroyStdin).not.toHaveBeenCalled()
|
||||
taskkill.emit('close', 0)
|
||||
await rejection
|
||||
expect(destroyStdin).toHaveBeenCalledTimes(1)
|
||||
expect(cleanupInteractiveLogin).toHaveBeenCalledTimes(1)
|
||||
expect(service.cancelPendingLogin()).toBe(false)
|
||||
} finally {
|
||||
vi.doUnmock('node:child_process')
|
||||
vi.doUnmock('../../shared/windows-interactive-login-spawn')
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { EventEmitter } from 'node:events'
|
||||
import { getCmdExePath } from '../../shared/windows-batch-spawn'
|
||||
import { createService, restorePlatform, setPlatform } from './claude-account-service-test-harness'
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: {
|
||||
getPath: () => '/tmp/orca-claude-windows-login-test'
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('../codex-cli/command', () => ({
|
||||
resolveClaudeCommand: vi.fn(() => 'C:\\Tools\\claude.cmd')
|
||||
}))
|
||||
|
||||
describe('Claude Windows host interactive login', () => {
|
||||
afterEach(() => {
|
||||
restorePlatform()
|
||||
})
|
||||
|
||||
it('resolves a Windows auth login whose child has no piped streams', async () => {
|
||||
setPlatform('win32')
|
||||
vi.resetModules()
|
||||
const child = new EventEmitter() as EventEmitter & {
|
||||
stdout: null
|
||||
stderr: null
|
||||
kill: ReturnType<typeof vi.fn>
|
||||
pid: number
|
||||
}
|
||||
child.stdout = null
|
||||
child.stderr = null
|
||||
child.kill = vi.fn()
|
||||
child.pid = 4242
|
||||
const spawnMock = vi.fn(() => {
|
||||
queueMicrotask(() => child.emit('exit', 0))
|
||||
return child
|
||||
})
|
||||
const buildInteractiveLoginSpawn = vi.fn(() => ({
|
||||
command: getCmdExePath(),
|
||||
args: [
|
||||
'/d',
|
||||
'/c',
|
||||
'start',
|
||||
'',
|
||||
'/wait',
|
||||
'C:\\Tools\\claude.cmd',
|
||||
'auth',
|
||||
'login',
|
||||
'--claudeai'
|
||||
],
|
||||
stdio: 'ignore' as const,
|
||||
windowsHide: true
|
||||
}))
|
||||
vi.doMock('node:child_process', () => ({ spawn: spawnMock }))
|
||||
vi.doMock('../../shared/windows-interactive-login-spawn', () => ({
|
||||
buildWindowsHostInteractiveLoginSpawn: buildInteractiveLoginSpawn
|
||||
}))
|
||||
|
||||
try {
|
||||
const { ClaudeAccountService } = await import('./service')
|
||||
const service = new ClaudeAccountService(
|
||||
createService() as never,
|
||||
createService() as never,
|
||||
createService() as never
|
||||
)
|
||||
await (
|
||||
service as unknown as {
|
||||
runClaudeCommand(
|
||||
args: string[],
|
||||
configDir: { windowsPath: string; linuxPath: string | null; wslDistro: string | null },
|
||||
timeoutMs: number
|
||||
): Promise<string>
|
||||
}
|
||||
).runClaudeCommand(
|
||||
['auth', 'login', '--claudeai'],
|
||||
{ windowsPath: 'C:\\tmp\\claude-auth', linuxPath: null, wslDistro: null },
|
||||
1000
|
||||
)
|
||||
|
||||
expect(buildInteractiveLoginSpawn).toHaveBeenCalledWith('C:\\Tools\\claude.cmd', [
|
||||
'auth',
|
||||
'login',
|
||||
'--claudeai'
|
||||
])
|
||||
expect(spawnMock).toHaveBeenCalledWith(
|
||||
getCmdExePath(),
|
||||
expect.arrayContaining(['start', '', '/wait']),
|
||||
expect.objectContaining({
|
||||
stdio: 'ignore',
|
||||
windowsHide: true
|
||||
})
|
||||
)
|
||||
expect(child.kill).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
vi.doUnmock('node:child_process')
|
||||
vi.doUnmock('../../shared/windows-interactive-login-spawn')
|
||||
}
|
||||
})
|
||||
|
||||
it('times out a denied Windows login that stays alive without piped output', async () => {
|
||||
setPlatform('win32')
|
||||
vi.resetModules()
|
||||
vi.useFakeTimers()
|
||||
const child = new EventEmitter() as EventEmitter & {
|
||||
stdout: null
|
||||
stderr: null
|
||||
kill: ReturnType<typeof vi.fn>
|
||||
pid: number
|
||||
}
|
||||
child.stdout = null
|
||||
child.stderr = null
|
||||
child.kill = vi.fn()
|
||||
child.pid = 0
|
||||
const spawnMock = vi.fn(() => child)
|
||||
vi.doMock('node:child_process', () => ({ spawn: spawnMock }))
|
||||
|
||||
try {
|
||||
const { ClaudeAccountService } = await import('./service')
|
||||
const service = new ClaudeAccountService(
|
||||
createService() as never,
|
||||
createService() as never,
|
||||
createService() as never
|
||||
)
|
||||
const login = (
|
||||
service as unknown as {
|
||||
runClaudeCommand(
|
||||
args: string[],
|
||||
configDir: { windowsPath: string; linuxPath: string | null; wslDistro: string | null },
|
||||
timeoutMs: number
|
||||
): Promise<string>
|
||||
}
|
||||
).runClaudeCommand(
|
||||
['auth', 'login', '--claudeai'],
|
||||
{ windowsPath: 'C:\\tmp\\claude-auth', linuxPath: null, wslDistro: null },
|
||||
1000
|
||||
)
|
||||
const rejection = expect(login).rejects.toThrow('Claude sign-in took too long to finish.')
|
||||
|
||||
await vi.advanceTimersByTimeAsync(3_000)
|
||||
|
||||
await rejection
|
||||
expect(child.kill).toHaveBeenCalledOnce()
|
||||
} finally {
|
||||
vi.useRealTimers()
|
||||
vi.doUnmock('node:child_process')
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -35,6 +35,7 @@ import { parseWslUncPath } from '../../shared/wsl-paths'
|
||||
import { toWindowsWslPath } from '../wsl'
|
||||
import { runWslProcess } from '../wsl/wsl-runner'
|
||||
import { buildWindowsCommandInvocation } from './windows-command-invocation'
|
||||
import { buildWindowsHostInteractiveLoginSpawn } from '../../shared/windows-interactive-login-spawn'
|
||||
import {
|
||||
getClaudeSelectionTargetForAccount,
|
||||
getSelectedClaudeAccountIdForTarget,
|
||||
@@ -1043,8 +1044,27 @@ export class ClaudeAccountService {
|
||||
options?: { allowFailure?: boolean; signal?: AbortSignal; keepStdinOpen?: boolean }
|
||||
): Promise<string> {
|
||||
return new Promise((resolvePromise, rejectPromise) => {
|
||||
const spawnConfig =
|
||||
configDir.linuxPath && configDir.wslDistro
|
||||
const isWindowsHostInteractiveLogin =
|
||||
process.platform === 'win32' &&
|
||||
configDir.linuxPath === null &&
|
||||
configDir.wslDistro === null &&
|
||||
args[0] === 'auth' &&
|
||||
args[1] === 'login'
|
||||
const interactiveLogin = isWindowsHostInteractiveLogin
|
||||
? buildWindowsHostInteractiveLoginSpawn(resolveClaudeCommand(), args)
|
||||
: null
|
||||
const spawnConfig = interactiveLogin
|
||||
? {
|
||||
command: interactiveLogin.command,
|
||||
args: interactiveLogin.args,
|
||||
env: {
|
||||
...process.env,
|
||||
CLAUDE_CONFIG_DIR: configDir.windowsPath
|
||||
},
|
||||
shell: false,
|
||||
windowsVerbatimArguments: false
|
||||
}
|
||||
: configDir.linuxPath && configDir.wslDistro
|
||||
? {
|
||||
command: 'wsl.exe',
|
||||
args: [
|
||||
@@ -1082,10 +1102,11 @@ export class ClaudeAccountService {
|
||||
// Why: Claude's browser auth can bind its callback lifetime to stdin.
|
||||
// Keeping stdin open prevents hidden managed-login runs from tearing down
|
||||
// the local callback server before the browser returns.
|
||||
stdio: [options?.keepStdinOpen ? 'pipe' : 'ignore', 'pipe', 'pipe'],
|
||||
stdio: interactiveLogin
|
||||
? interactiveLogin.stdio
|
||||
: [options?.keepStdinOpen ? 'pipe' : 'ignore', 'pipe', 'pipe'],
|
||||
shell: spawnConfig.shell,
|
||||
// On Windows this is wsl.exe or a cmd invocation; without the flag it
|
||||
// opens a console and steals foreground on every managed login (#10488).
|
||||
// Why: hide only the outer wrapper; start creates the visible login console.
|
||||
windowsHide: true,
|
||||
windowsVerbatimArguments: spawnConfig.windowsVerbatimArguments,
|
||||
env: spawnConfig.env,
|
||||
@@ -1095,7 +1116,7 @@ export class ClaudeAccountService {
|
||||
})
|
||||
const stdout = child.stdout
|
||||
const stderr = child.stderr
|
||||
if (!stdout || !stderr) {
|
||||
if (!interactiveLogin && (!stdout || !stderr)) {
|
||||
if (options?.keepStdinOpen) {
|
||||
child.stdin?.destroy()
|
||||
}
|
||||
@@ -1130,17 +1151,18 @@ export class ClaudeAccountService {
|
||||
clearTimeout(timeout)
|
||||
timeout = null
|
||||
}
|
||||
stdout.off('data', appendOutput)
|
||||
stderr.off('data', appendOutput)
|
||||
stdout?.off('data', appendOutput)
|
||||
stderr?.off('data', appendOutput)
|
||||
child.off('error', onError)
|
||||
child.off(completionEvent, onDone)
|
||||
options?.signal?.removeEventListener('abort', onAbort)
|
||||
interactiveLogin?.cleanup?.()
|
||||
if (options?.keepStdinOpen) {
|
||||
child.stdin?.destroy()
|
||||
}
|
||||
if (completesOnExit) {
|
||||
stdout.destroy()
|
||||
stderr.destroy()
|
||||
stdout?.destroy()
|
||||
stderr?.destroy()
|
||||
}
|
||||
}
|
||||
const settle = (callback: () => void): void => {
|
||||
@@ -1159,11 +1181,15 @@ export class ClaudeAccountService {
|
||||
return
|
||||
}
|
||||
terminationPending = true
|
||||
if (process.platform === 'win32' && child.pid) {
|
||||
const taskkill = spawn('taskkill.exe', ['/pid', String(child.pid), '/t', '/f'], {
|
||||
stdio: 'ignore',
|
||||
windowsHide: true
|
||||
})
|
||||
const killWindowsTree = (windowsTerminationPid: number): void => {
|
||||
const taskkill = spawn(
|
||||
'taskkill.exe',
|
||||
['/pid', String(windowsTerminationPid), '/t', '/f'],
|
||||
{
|
||||
stdio: 'ignore',
|
||||
windowsHide: true
|
||||
}
|
||||
)
|
||||
let taskkillFinished = false
|
||||
const finishTaskkill = (succeeded: boolean): void => {
|
||||
if (taskkillFinished) {
|
||||
@@ -1182,9 +1208,27 @@ export class ClaudeAccountService {
|
||||
}, WINDOWS_TASKKILL_TIMEOUT_MS)
|
||||
taskkill.once('error', () => finishTaskkill(false))
|
||||
taskkill.once('close', (code) => finishTaskkill(code === 0))
|
||||
}
|
||||
if (process.platform === 'win32') {
|
||||
const resolveTerminationPid = interactiveLogin?.waitForTerminationPid
|
||||
? interactiveLogin.waitForTerminationPid()
|
||||
: Promise.resolve(interactiveLogin?.getTerminationPid?.() ?? child.pid ?? null)
|
||||
void resolveTerminationPid
|
||||
.then((windowsTerminationPid) => {
|
||||
if (windowsTerminationPid) {
|
||||
killWindowsTree(windowsTerminationPid)
|
||||
return
|
||||
}
|
||||
child.kill()
|
||||
afterKill()
|
||||
})
|
||||
.catch(() => {
|
||||
child.kill()
|
||||
afterKill()
|
||||
})
|
||||
return
|
||||
}
|
||||
if (process.platform !== 'win32' && child.pid) {
|
||||
if (child.pid) {
|
||||
try {
|
||||
process.kill(-child.pid)
|
||||
afterKill()
|
||||
@@ -1229,8 +1273,8 @@ export class ClaudeAccountService {
|
||||
})
|
||||
}
|
||||
|
||||
stdout.on('data', appendOutput)
|
||||
stderr.on('data', appendOutput)
|
||||
stdout?.on('data', appendOutput)
|
||||
stderr?.on('data', appendOutput)
|
||||
child.on('error', onError)
|
||||
// Native Windows browsers can inherit these pipes and indefinitely delay close.
|
||||
child.on(completionEvent, onDone)
|
||||
|
||||
@@ -0,0 +1,413 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
clearAllListenerCaches,
|
||||
clearPaneCacheState,
|
||||
createHookListenerState,
|
||||
movePaneCacheState,
|
||||
normalizeHookPayload,
|
||||
seedClaudeSubagentRosterFromSnapshots,
|
||||
type AgentHookEventPayload,
|
||||
type HookListenerState
|
||||
} from '../../shared/agent-hook-listener'
|
||||
import { makePaneKey } from '../../shared/stable-pane-id'
|
||||
import { applyManagedHooks, CLAUDE_EVENTS } from './hook-settings'
|
||||
|
||||
const PANE_KEY = makePaneKey('compact-registration', '11111111-1111-4111-8111-111111111111')
|
||||
const TURN_PROMPT_ID = '22222222-2222-4222-8222-222222222222'
|
||||
const COMPACT_PROMPT_ID = '33333333-3333-4333-8333-333333333333'
|
||||
|
||||
const REGISTERED_EVENT_NAMES = new Set<string>(CLAUDE_EVENTS.map((event) => event.eventName))
|
||||
|
||||
/** Deliver a hook event the way production does: only if the event is actually REGISTERED with
|
||||
* Claude. Feeding the normalizer directly is what let a whole compact-correlation feature ship
|
||||
* green while being unreachable — every behavior assertion here goes through this gate. */
|
||||
function deliverIfRegistered(
|
||||
state: HookListenerState,
|
||||
payload: Record<string, unknown>
|
||||
): AgentHookEventPayload | null {
|
||||
if (!REGISTERED_EVENT_NAMES.has(payload.hook_event_name as string)) {
|
||||
return null
|
||||
}
|
||||
const event = normalizeHookPayload(state, 'claude', { paneKey: PANE_KEY, payload }, 'production')
|
||||
if (event) {
|
||||
state.lastStatusByPaneKey.set(PANE_KEY, event)
|
||||
}
|
||||
return event
|
||||
}
|
||||
|
||||
function hook(name: string, promptId: string, extra: Record<string, unknown> = {}) {
|
||||
return { hook_event_name: name, prompt_id: promptId, session_id: 'session-a', ...extra }
|
||||
}
|
||||
|
||||
/** The exact sequence Claude Code emits for a successful manual /compact, measured from a PTY-driven
|
||||
* interactive session (2.1.227). PreCompact and the summarizer's start-less SubagentStop are part
|
||||
* of the real stream, so they are delivered here even though only PostCompact is registered. */
|
||||
function successfulManualCompact(state: HookListenerState) {
|
||||
deliverIfRegistered(state, hook('PreCompact', COMPACT_PROMPT_ID, { trigger: 'manual' }))
|
||||
deliverIfRegistered(
|
||||
state,
|
||||
hook('SubagentStop', COMPACT_PROMPT_ID, {
|
||||
agent_id: 'a75b38b59774e1f31',
|
||||
agent_type: '',
|
||||
background_tasks: [],
|
||||
session_crons: []
|
||||
})
|
||||
)
|
||||
deliverIfRegistered(state, hook('SessionStart', COMPACT_PROMPT_ID, { source: 'compact' }))
|
||||
return deliverIfRegistered(state, hook('PostCompact', COMPACT_PROMPT_ID, { trigger: 'manual' }))
|
||||
}
|
||||
|
||||
function startTurn(state: HookListenerState) {
|
||||
deliverIfRegistered(state, hook('UserPromptSubmit', TURN_PROMPT_ID, { prompt: 'do the thing' }))
|
||||
}
|
||||
|
||||
/** The row AgentHookServer.hydrate() rebuilds for a pane that was stuck `working` when Orca last
|
||||
* exited: the previous session's connectionId, the unconfirmed flag, and — when the turn had
|
||||
* spawned one — a child that exists only as a disk snapshot. */
|
||||
function hydrateStuckRow(
|
||||
state: HookListenerState,
|
||||
options: { withRestoredChild?: boolean; providerSession?: boolean } = {}
|
||||
): void {
|
||||
const subagents = options.withRestoredChild
|
||||
? [{ id: 'child-1', state: 'working' as const, startedAt: 0, agentType: 'general' }]
|
||||
: undefined
|
||||
const hydrated = {
|
||||
paneKey: PANE_KEY,
|
||||
source: 'claude',
|
||||
connectionId: 'a-previous-connection',
|
||||
hookEventName: 'UserPromptSubmit',
|
||||
providerPromptId: TURN_PROMPT_ID,
|
||||
...(options.providerSession === false
|
||||
? {}
|
||||
: { providerSession: { key: 'session_id', id: 'session-a' } }),
|
||||
restoredUnconfirmed: true,
|
||||
payload: {
|
||||
state: 'working',
|
||||
prompt: 'work before the restart',
|
||||
agentType: 'claude',
|
||||
...(subagents ? { subagents } : {})
|
||||
}
|
||||
} as unknown as AgentHookEventPayload
|
||||
state.lastStatusByPaneKey.set(PANE_KEY, hydrated)
|
||||
if (subagents) {
|
||||
seedClaudeSubagentRosterFromSnapshots(state, PANE_KEY, subagents)
|
||||
}
|
||||
}
|
||||
|
||||
describe('Claude compact hook registration', () => {
|
||||
it('registers PostCompact and deliberately does not register PreCompact', () => {
|
||||
expect(REGISTERED_EVENT_NAMES.has('PostCompact')).toBe(true)
|
||||
// Why: PreCompact fires BEFORE the compact is validated and an aborted compact emits it alone,
|
||||
// so subscribing to it at all is what strands the pane. This assertion is the guard.
|
||||
expect(REGISTERED_EVENT_NAMES.has('PreCompact')).toBe(false)
|
||||
})
|
||||
|
||||
it('writes PostCompact, and no PreCompact, into the settings Claude actually reads', () => {
|
||||
const written = applyManagedHooks(
|
||||
{ hooks: {} },
|
||||
{ type: 'command', command: 'orca-claude-hook' },
|
||||
'claude-hook.sh'
|
||||
)
|
||||
const postCompact = written.hooks?.PostCompact ?? []
|
||||
expect(
|
||||
postCompact.some((definition) =>
|
||||
(definition.hooks ?? []).some((entry) => entry.command === 'orca-claude-hook')
|
||||
)
|
||||
).toBe(true)
|
||||
expect(written.hooks?.PreCompact).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('STA-2915: a manual compact clears the pane', () => {
|
||||
it('ends a stuck working row as a silent done', () => {
|
||||
const state = createHookListenerState()
|
||||
startTurn(state)
|
||||
expect(state.lastStatusByPaneKey.get(PANE_KEY)?.payload.state).toBe('working')
|
||||
|
||||
const completion = successfulManualCompact(state)
|
||||
|
||||
expect(completion?.payload.state).toBe('done')
|
||||
// Why: a finished compact is a session-shaped boundary, not a completed turn — consumers that
|
||||
// react to completion (automation runs, unread counts, notifications) must stay out of it.
|
||||
expect(completion?.payload.sessionBoundary).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps the summarizer SubagentStop from being the thing that resolves the pane', () => {
|
||||
const state = createHookListenerState()
|
||||
startTurn(state)
|
||||
// The start-less SubagentStop re-emits the cached lead state; it can only republish `working`,
|
||||
// never clear it. Only PostCompact resolves the pane.
|
||||
const republished = deliverIfRegistered(
|
||||
state,
|
||||
hook('SubagentStop', COMPACT_PROMPT_ID, {
|
||||
agent_id: 'a75b38b59774e1f31',
|
||||
agent_type: '',
|
||||
background_tasks: [],
|
||||
session_crons: []
|
||||
})
|
||||
)
|
||||
expect(republished?.payload.state).toBe('working')
|
||||
})
|
||||
})
|
||||
|
||||
describe('STA-4613: an aborted compact must not strand the pane', () => {
|
||||
it('leaves an idle pane idle when PreCompact arrives alone', () => {
|
||||
const state = createHookListenerState()
|
||||
startTurn(state)
|
||||
deliverIfRegistered(state, hook('Stop', TURN_PROMPT_ID))
|
||||
expect(state.lastStatusByPaneKey.get(PANE_KEY)?.payload.state).toBe('done')
|
||||
|
||||
// Measured: "Not enough messages to compact" emits PreCompact and nothing else.
|
||||
deliverIfRegistered(state, hook('PreCompact', COMPACT_PROMPT_ID, { trigger: 'manual' }))
|
||||
|
||||
expect(state.lastStatusByPaneKey.get(PANE_KEY)?.payload.state).toBe('done')
|
||||
})
|
||||
|
||||
it('leaves a working pane working when PreCompact arrives alone', () => {
|
||||
const state = createHookListenerState()
|
||||
startTurn(state)
|
||||
|
||||
deliverIfRegistered(state, hook('PreCompact', COMPACT_PROMPT_ID, { trigger: 'manual' }))
|
||||
|
||||
expect(state.lastStatusByPaneKey.get(PANE_KEY)?.payload.state).toBe('working')
|
||||
})
|
||||
|
||||
it('does not map PreCompact even when it is delivered past the registration gate', () => {
|
||||
const state = createHookListenerState()
|
||||
startTurn(state)
|
||||
deliverIfRegistered(state, hook('Stop', TURN_PROMPT_ID))
|
||||
|
||||
const event = normalizeHookPayload(
|
||||
state,
|
||||
'claude',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
payload: hook('PreCompact', COMPACT_PROMPT_ID, { trigger: 'manual' })
|
||||
},
|
||||
'production'
|
||||
)
|
||||
|
||||
expect(event).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('an auto compact claims nothing', () => {
|
||||
it('leaves the in-flight turn alone and lets its own Stop close it', () => {
|
||||
const state = createHookListenerState()
|
||||
startTurn(state)
|
||||
|
||||
const autoCompact = deliverIfRegistered(
|
||||
state,
|
||||
hook('PostCompact', COMPACT_PROMPT_ID, { trigger: 'auto' })
|
||||
)
|
||||
|
||||
expect(autoCompact).toBeNull()
|
||||
expect(state.lastStatusByPaneKey.get(PANE_KEY)?.payload.state).toBe('working')
|
||||
|
||||
deliverIfRegistered(state, hook('Stop', TURN_PROMPT_ID))
|
||||
expect(state.lastStatusByPaneKey.get(PANE_KEY)?.payload.state).toBe('done')
|
||||
})
|
||||
|
||||
it("writes no compact-scoped state, so it cannot spend the pane's consumed-compact slot", () => {
|
||||
const state = createHookListenerState()
|
||||
startTurn(state)
|
||||
|
||||
deliverIfRegistered(state, hook('PostCompact', COMPACT_PROMPT_ID, { trigger: 'auto' }))
|
||||
|
||||
// Why: only a manual completion claims anything. Running the ownership guard for an auto
|
||||
// compact would mark its prompt id consumed for an event that maps to no state at all.
|
||||
expect(state.claudeConsumedCompactPromptIdByPaneKey.has(PANE_KEY)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('STA-2915: the pane the ticket actually reports', () => {
|
||||
it('clears a row stuck behind a child that exists only as a disk snapshot', () => {
|
||||
const state = createHookListenerState()
|
||||
hydrateStuckRow(state, { withRestoredChild: true })
|
||||
|
||||
deliverIfRegistered(state, hook('PreCompact', COMPACT_PROMPT_ID, { trigger: 'manual' }))
|
||||
// Why: assert the summarizer stays silent rather than assuming it. With a restored roster it
|
||||
// publishes nothing, which is what leaves the hydrated row in place for the completion — if
|
||||
// that ever changes, this test must fail loudly instead of quietly testing something else.
|
||||
const summarizer = deliverIfRegistered(
|
||||
state,
|
||||
hook('SubagentStop', COMPACT_PROMPT_ID, { agent_id: 'a75b38b59774e1f31', agent_type: '' })
|
||||
)
|
||||
expect(summarizer).toBeNull()
|
||||
deliverIfRegistered(state, hook('SessionStart', COMPACT_PROMPT_ID, { source: 'compact' }))
|
||||
|
||||
const completion = deliverIfRegistered(
|
||||
state,
|
||||
hook('PostCompact', COMPACT_PROMPT_ID, { trigger: 'manual' })
|
||||
)
|
||||
|
||||
// A restored child is a disk snapshot, not evidence of live work, and a manual /compact only
|
||||
// completes at an idle prompt — so it may not keep the pane spinning.
|
||||
expect(completion?.payload.state).toBe('done')
|
||||
expect(completion?.payload.sessionBoundary).toBe(true)
|
||||
expect(completion?.payload.subagents ?? []).toEqual([])
|
||||
})
|
||||
|
||||
it('leaves a pane held by a RUNTIME child at working, and republishes nothing', () => {
|
||||
const state = createHookListenerState()
|
||||
startTurn(state)
|
||||
deliverIfRegistered(state, hook('SubagentStart', TURN_PROMPT_ID, { agent_id: 'child-live' }))
|
||||
const before = state.lastStatusByPaneKey.get(PANE_KEY)
|
||||
|
||||
const completion = deliverIfRegistered(
|
||||
state,
|
||||
hook('PostCompact', COMPACT_PROMPT_ID, { trigger: 'manual' })
|
||||
)
|
||||
|
||||
// Why: a child observed in this runtime IS live agent work. The compact must not retire it —
|
||||
// and it must not restate the row either, because a restated row loses `restoredUnconfirmed`
|
||||
// and restarts the staleness clock for work the compact never observed.
|
||||
expect(completion).toBeNull()
|
||||
expect(state.lastStatusByPaneKey.get(PANE_KEY)).toBe(before)
|
||||
expect(before?.payload.state).toBe('working')
|
||||
})
|
||||
|
||||
it('leaves a pane held by an active session cron at working, and republishes nothing', () => {
|
||||
const state = createHookListenerState()
|
||||
startTurn(state)
|
||||
deliverIfRegistered(state, hook('Stop', TURN_PROMPT_ID, { session_crons: [{ id: 'cron-1' }] }))
|
||||
const before = state.lastStatusByPaneKey.get(PANE_KEY)
|
||||
expect(before?.payload.state).toBe('working')
|
||||
|
||||
expect(
|
||||
deliverIfRegistered(state, hook('PostCompact', COMPACT_PROMPT_ID, { trigger: 'manual' }))
|
||||
).toBeNull()
|
||||
expect(state.lastStatusByPaneKey.get(PANE_KEY)).toBe(before)
|
||||
})
|
||||
})
|
||||
|
||||
describe('compact completion guards', () => {
|
||||
it('does not resurrect a pane that was retired before the completion arrived', () => {
|
||||
const state = createHookListenerState()
|
||||
// No cached status: the pane was closed/cleared. A compact clears a row, it never creates one.
|
||||
expect(successfulManualCompact(state)).toBeNull()
|
||||
expect(state.lastStatusByPaneKey.get(PANE_KEY)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('clears a stuck row restored from disk after a restart, despite a stale connection id', () => {
|
||||
const state = createHookListenerState()
|
||||
hydrateStuckRow(state)
|
||||
// Why: the completion must land while the HYDRATED row is still the cached owner, or the
|
||||
// restored-row branch is never the one under test. Deliver it alone — an intervening
|
||||
// summarizer would replace the row with a live one and the assertion would pass through the
|
||||
// strict branch instead, which is exactly how this test used to be vacuous.
|
||||
const completion = deliverIfRegistered(
|
||||
state,
|
||||
hook('PostCompact', COMPACT_PROMPT_ID, { trigger: 'manual' })
|
||||
)
|
||||
|
||||
expect(completion?.payload.state).toBe('done')
|
||||
expect(completion?.payload.sessionBoundary).toBe(true)
|
||||
})
|
||||
|
||||
it('clears a restored row that predates provider-session persistence', () => {
|
||||
const state = createHookListenerState()
|
||||
hydrateStuckRow(state, { providerSession: false })
|
||||
expect(state.lastStatusByPaneKey.get(PANE_KEY)?.providerSession).toBeUndefined()
|
||||
|
||||
const completion = deliverIfRegistered(
|
||||
state,
|
||||
hook('PostCompact', COMPACT_PROMPT_ID, { trigger: 'manual' })
|
||||
)
|
||||
|
||||
expect(completion?.payload.state).toBe('done')
|
||||
})
|
||||
|
||||
it('does not clear a live turn owned by a different Claude session', () => {
|
||||
const state = createHookListenerState()
|
||||
startTurn(state)
|
||||
|
||||
const foreign = normalizeHookPayload(
|
||||
state,
|
||||
'claude',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
payload: {
|
||||
hook_event_name: 'PostCompact',
|
||||
prompt_id: COMPACT_PROMPT_ID,
|
||||
session_id: 'a-different-session',
|
||||
trigger: 'manual'
|
||||
}
|
||||
},
|
||||
'production'
|
||||
)
|
||||
|
||||
expect(foreign).toBeNull()
|
||||
expect(state.lastStatusByPaneKey.get(PANE_KEY)?.payload.state).toBe('working')
|
||||
})
|
||||
|
||||
it('rejects a compact completion with no provider prompt id', () => {
|
||||
const state = createHookListenerState()
|
||||
startTurn(state)
|
||||
|
||||
const event = normalizeHookPayload(
|
||||
state,
|
||||
'claude',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
payload: { hook_event_name: 'PostCompact', session_id: 'session-a', trigger: 'manual' }
|
||||
},
|
||||
'production'
|
||||
)
|
||||
|
||||
expect(event).toBeNull()
|
||||
})
|
||||
|
||||
it('applies a compact completion once, so a duplicate cannot refresh the row', () => {
|
||||
const state = createHookListenerState()
|
||||
startTurn(state)
|
||||
expect(successfulManualCompact(state)?.payload.state).toBe('done')
|
||||
|
||||
const duplicate = normalizeHookPayload(
|
||||
state,
|
||||
'claude',
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
payload: hook('PostCompact', COMPACT_PROMPT_ID, { trigger: 'manual' })
|
||||
},
|
||||
'production'
|
||||
)
|
||||
|
||||
expect(duplicate).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('the consumed-compact record is torn down with its pane', () => {
|
||||
const OTHER_PANE = makePaneKey('compact-registration', '44444444-4444-4444-8444-444444444444')
|
||||
|
||||
function paneWithConsumedCompact(): HookListenerState {
|
||||
const state = createHookListenerState()
|
||||
startTurn(state)
|
||||
expect(successfulManualCompact(state)?.payload.state).toBe('done')
|
||||
expect(state.claudeConsumedCompactPromptIdByPaneKey.get(PANE_KEY)).toBe(COMPACT_PROMPT_ID)
|
||||
return state
|
||||
}
|
||||
|
||||
// Why: this codebase keeps growing a new per-pane store that lands in ONE teardown path and is
|
||||
// missed by the siblings, which leaks the map and leaves stale reads behind a pane that is gone.
|
||||
// Every route that tears pane state down has to take this map with it.
|
||||
it('clearPaneCacheState drops it', () => {
|
||||
const state = paneWithConsumedCompact()
|
||||
clearPaneCacheState(state, PANE_KEY)
|
||||
expect(state.claudeConsumedCompactPromptIdByPaneKey.has(PANE_KEY)).toBe(false)
|
||||
})
|
||||
|
||||
it('movePaneCacheState carries it to the new pane key', () => {
|
||||
const state = paneWithConsumedCompact()
|
||||
movePaneCacheState(state, PANE_KEY, OTHER_PANE)
|
||||
expect(state.claudeConsumedCompactPromptIdByPaneKey.has(PANE_KEY)).toBe(false)
|
||||
expect(state.claudeConsumedCompactPromptIdByPaneKey.get(OTHER_PANE)).toBe(COMPACT_PROMPT_ID)
|
||||
})
|
||||
|
||||
it('clearAllListenerCaches empties it', () => {
|
||||
const state = paneWithConsumedCompact()
|
||||
clearAllListenerCaches(state)
|
||||
expect(state.claudeConsumedCompactPromptIdByPaneKey.size).toBe(0)
|
||||
})
|
||||
})
|
||||
@@ -88,6 +88,14 @@ export const CLAUDE_EVENTS = [
|
||||
{
|
||||
eventName: 'PermissionRequest',
|
||||
definition: { matcher: '*', hooks: [{ type: 'command', command: '' }] }
|
||||
},
|
||||
// Why: a manual /compact ends at an idle prompt without emitting Stop, so PostCompact is the only
|
||||
// signal that can clear the pane (STA-2915). PreCompact is deliberately NOT registered: it fires
|
||||
// before the compact is validated, and an aborted compact emits it alone — mapping it to 'working'
|
||||
// would strand the pane exactly as this registration is meant to prevent (STA-4613).
|
||||
{
|
||||
eventName: 'PostCompact',
|
||||
definition: { hooks: [{ type: 'command', command: '' }] }
|
||||
}
|
||||
] as const
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { EventEmitter } from 'node:events'
|
||||
import type * as NodeOs from 'node:os'
|
||||
import { getCmdExePath } from '../../shared/windows-batch-spawn'
|
||||
import {
|
||||
createRateLimits,
|
||||
createRuntimeHome,
|
||||
createSettings,
|
||||
createStore,
|
||||
registerCodexAccountsTestHomes,
|
||||
testState
|
||||
} from './service-test-harness'
|
||||
|
||||
vi.mock('electron', () => ({
|
||||
app: {
|
||||
getPath: () => testState.userDataDir
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('node:os', async () => {
|
||||
const actual = await vi.importActual<typeof NodeOs>('node:os')
|
||||
return {
|
||||
...actual,
|
||||
homedir: () => testState.fakeHomeDir
|
||||
}
|
||||
})
|
||||
|
||||
describe('Codex Windows host interactive login', () => {
|
||||
registerCodexAccountsTestHomes()
|
||||
|
||||
it('resolves a Windows login whose child has no piped streams', async () => {
|
||||
vi.resetModules()
|
||||
const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')!
|
||||
Object.defineProperty(process, 'platform', { value: 'win32', configurable: true })
|
||||
const child = new EventEmitter() as EventEmitter & {
|
||||
stdout: null
|
||||
stderr: null
|
||||
kill: ReturnType<typeof vi.fn>
|
||||
pid: number
|
||||
}
|
||||
child.stdout = null
|
||||
child.stderr = null
|
||||
child.kill = vi.fn()
|
||||
child.pid = 4242
|
||||
const spawnMock = vi.fn(() => {
|
||||
queueMicrotask(() => child.emit('close', 0))
|
||||
return child
|
||||
})
|
||||
const buildInteractiveLoginSpawn = vi.fn(() => ({
|
||||
command: getCmdExePath(),
|
||||
args: ['/d', '/c', 'start', '', '/wait', 'C:\\Tools\\codex.cmd', 'login'],
|
||||
stdio: 'ignore' as const,
|
||||
windowsHide: true
|
||||
}))
|
||||
vi.doMock('node:child_process', () => ({
|
||||
execFileSync: vi.fn(),
|
||||
spawn: spawnMock
|
||||
}))
|
||||
vi.doMock('../codex-cli/command', () => ({
|
||||
resolveCodexCommand: () => 'C:\\Tools\\codex.cmd'
|
||||
}))
|
||||
vi.doMock('../../shared/windows-interactive-login-spawn', () => ({
|
||||
buildWindowsHostInteractiveLoginSpawn: buildInteractiveLoginSpawn
|
||||
}))
|
||||
|
||||
try {
|
||||
const { CodexAccountService } = await import('./service')
|
||||
const service = new CodexAccountService(
|
||||
createStore(createSettings()) as never,
|
||||
createRateLimits() as never,
|
||||
createRuntimeHome() as never
|
||||
)
|
||||
await (
|
||||
service as unknown as {
|
||||
runCodexLogin(managedHomePath: string): Promise<void>
|
||||
}
|
||||
).runCodexLogin(testState.fakeHomeDir)
|
||||
|
||||
expect(buildInteractiveLoginSpawn).toHaveBeenCalledWith('C:\\Tools\\codex.cmd', ['login'])
|
||||
expect(spawnMock).toHaveBeenCalledWith(
|
||||
getCmdExePath(),
|
||||
expect.arrayContaining(['start', '', '/wait']),
|
||||
expect.objectContaining({
|
||||
stdio: 'ignore',
|
||||
windowsHide: true
|
||||
})
|
||||
)
|
||||
expect(child.kill).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
Object.defineProperty(process, 'platform', originalPlatform)
|
||||
vi.doUnmock('node:child_process')
|
||||
vi.doUnmock('../codex-cli/command')
|
||||
vi.doUnmock('../../shared/windows-interactive-login-spawn')
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -6,6 +6,10 @@ import { dirname, join, resolve, sep } from 'node:path'
|
||||
import { homedir } from 'node:os'
|
||||
import { app } from 'electron'
|
||||
import { getSpawnArgsForWindows } from '../win32-utils'
|
||||
import {
|
||||
buildWindowsHostInteractiveLoginSpawn,
|
||||
type WindowsHostInteractiveLoginSpawn
|
||||
} from '../../shared/windows-interactive-login-spawn'
|
||||
import type {
|
||||
CodexManagedAccount,
|
||||
CodexManagedAccountSummary,
|
||||
@@ -211,10 +215,14 @@ function removeManagedHomeTreeSync(targetPath: string): void {
|
||||
})
|
||||
}
|
||||
|
||||
function killLoginProcessTree(child: ChildProcess): void {
|
||||
function killLoginProcessTree(
|
||||
child: ChildProcess,
|
||||
interactiveLogin?: WindowsHostInteractiveLoginSpawn | null
|
||||
): void {
|
||||
const terminationPid = interactiveLogin?.getTerminationPid?.() ?? child.pid
|
||||
if (
|
||||
process.platform === 'win32' &&
|
||||
typeof child.pid === 'number' &&
|
||||
typeof terminationPid === 'number' &&
|
||||
child.exitCode === null &&
|
||||
child.signalCode === null
|
||||
) {
|
||||
@@ -222,7 +230,7 @@ function killLoginProcessTree(child: ChildProcess): void {
|
||||
// Why: child.kill() only reaches the direct child (cmd.exe for npm .cmd
|
||||
// shims); taskkill /t also ends codex descendants whose open handles on
|
||||
// the managed home make post-login file operations fail with ENOTEMPTY.
|
||||
execFileSync('taskkill', ['/pid', String(child.pid), '/t', '/f'], {
|
||||
execFileSync('taskkill', ['/pid', String(terminationPid), '/t', '/f'], {
|
||||
windowsHide: true,
|
||||
timeout: WINDOWS_LOGIN_TREE_KILL_TIMEOUT_MS,
|
||||
stdio: 'ignore'
|
||||
@@ -1711,12 +1719,20 @@ export class CodexAccountService {
|
||||
command: 'wsl.exe',
|
||||
args: buildWslCodexLoginArgs(wslInfo.distro, wslInfo.linuxPath),
|
||||
env: process.env,
|
||||
codexCommand: 'codex'
|
||||
codexCommand: 'codex',
|
||||
interactiveLogin: null
|
||||
}
|
||||
: (() => {
|
||||
const codexCommand = resolveCodexCommand()
|
||||
// Why: Windows codex may be a .cmd/.bat; spawn+shell:true would trigger DEP0190, so invoke cmd.exe /c explicitly.
|
||||
const { spawnCmd, spawnArgs } = getSpawnArgsForWindows(codexCommand, ['login'])
|
||||
// Why: Windows host login needs a real console; otherwise inherit/hide
|
||||
// leaves the child unable to read a paste-code / device-auth prompt.
|
||||
const interactiveLogin =
|
||||
process.platform === 'win32'
|
||||
? buildWindowsHostInteractiveLoginSpawn(codexCommand, ['login'])
|
||||
: null
|
||||
const { spawnCmd, spawnArgs } = interactiveLogin
|
||||
? { spawnCmd: interactiveLogin.command, spawnArgs: interactiveLogin.args }
|
||||
: getSpawnArgsForWindows(codexCommand, ['login'])
|
||||
return {
|
||||
command: spawnCmd,
|
||||
args: spawnArgs,
|
||||
@@ -1724,12 +1740,15 @@ export class CodexAccountService {
|
||||
...process.env,
|
||||
CODEX_HOME: managedHomePath
|
||||
},
|
||||
codexCommand
|
||||
codexCommand,
|
||||
interactiveLogin
|
||||
}
|
||||
})()
|
||||
const child = spawn(spawnConfig.command, spawnConfig.args, {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
// Why: prevents a console window flash for .cmd/.bat entrypoints routed through cmd.exe on Windows.
|
||||
stdio: spawnConfig.interactiveLogin
|
||||
? spawnConfig.interactiveLogin.stdio
|
||||
: ['ignore', 'pipe', 'pipe'],
|
||||
// Why: hide the outer wrapper only. A dedicated login console stays visible.
|
||||
windowsHide: true,
|
||||
env: spawnConfig.env
|
||||
})
|
||||
@@ -1761,10 +1780,11 @@ export class CodexAccountService {
|
||||
clearTimeout(postAuthExitTimeout)
|
||||
postAuthExitTimeout = null
|
||||
}
|
||||
child.stdout.off('data', appendOutput)
|
||||
child.stderr.off('data', appendOutput)
|
||||
child.stdout?.off('data', appendOutput)
|
||||
child.stderr?.off('data', appendOutput)
|
||||
child.off('error', onError)
|
||||
child.off('close', onClose)
|
||||
spawnConfig.interactiveLogin?.cleanup?.()
|
||||
}
|
||||
|
||||
const settle = (callback: () => void): void => {
|
||||
@@ -1778,7 +1798,7 @@ export class CodexAccountService {
|
||||
|
||||
const timeoutError = new Error('Codex sign-in took too long to finish. Please try again.')
|
||||
timeout = setTimeout(() => {
|
||||
killLoginProcessTree(child)
|
||||
killLoginProcessTree(child, spawnConfig.interactiveLogin)
|
||||
settle(() => {
|
||||
rejectPromise(timeoutError)
|
||||
})
|
||||
@@ -1799,7 +1819,7 @@ export class CodexAccountService {
|
||||
}
|
||||
postAuthExitTimeout = setTimeout(() => {
|
||||
loginTreeKilledAfterAuth = true
|
||||
killLoginProcessTree(child)
|
||||
killLoginProcessTree(child, spawnConfig.interactiveLogin)
|
||||
}, WINDOWS_LOGIN_POST_AUTH_EXIT_GRACE_MS)
|
||||
}, WINDOWS_LOGIN_AUTH_POLL_INTERVAL_MS)
|
||||
}
|
||||
@@ -1845,8 +1865,8 @@ export class CodexAccountService {
|
||||
})
|
||||
}
|
||||
|
||||
child.stdout.on('data', appendOutput)
|
||||
child.stderr.on('data', appendOutput)
|
||||
child.stdout?.on('data', appendOutput)
|
||||
child.stderr?.on('data', appendOutput)
|
||||
child.on('error', onError)
|
||||
child.on('close', onClose)
|
||||
})
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import { beforeEach, describe, expect, it } from 'vitest'
|
||||
|
||||
import {
|
||||
clearCrashBreadcrumbsForTest,
|
||||
getCrashBreadcrumbSnapshot,
|
||||
recordCoalescedCrashBreadcrumb,
|
||||
recordCrashBreadcrumb
|
||||
} from './crash-breadcrumb-store'
|
||||
|
||||
describe('renderer crash breadcrumb attribution', () => {
|
||||
beforeEach(() => {
|
||||
clearCrashBreadcrumbsForTest()
|
||||
})
|
||||
|
||||
it('filters a renderer report to its own breadcrumbs while retaining global evidence', () => {
|
||||
recordCrashBreadcrumb('app_started', { packaged: true })
|
||||
recordCrashBreadcrumb('renderer_a_event', undefined, 'renderer:11')
|
||||
recordCrashBreadcrumb('renderer_b_event', undefined, 'renderer:22')
|
||||
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:11').map((entry) => entry.name)).toEqual([
|
||||
'app_started',
|
||||
'renderer_a_event'
|
||||
])
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:22').map((entry) => entry.name)).toEqual([
|
||||
'app_started',
|
||||
'renderer_b_event'
|
||||
])
|
||||
expect(getCrashBreadcrumbSnapshot().map((entry) => entry.name)).toEqual([
|
||||
'app_started',
|
||||
'renderer_a_event',
|
||||
'renderer_b_event'
|
||||
])
|
||||
})
|
||||
|
||||
it('does not merge identical coalesced storms from sibling renderers', () => {
|
||||
recordCoalescedCrashBreadcrumb({
|
||||
name: 'renderer_error',
|
||||
data: { message: 'boom' },
|
||||
coalesceKey: 'renderer:11\u0000renderer_error:boom',
|
||||
minIntervalMs: 30_000,
|
||||
origin: 'renderer:11'
|
||||
})
|
||||
recordCoalescedCrashBreadcrumb({
|
||||
name: 'renderer_error',
|
||||
data: { message: 'boom' },
|
||||
coalesceKey: 'renderer:22\u0000renderer_error:boom',
|
||||
minIntervalMs: 30_000,
|
||||
origin: 'renderer:22'
|
||||
})
|
||||
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:11')).toHaveLength(1)
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:22')).toHaveLength(1)
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:11')[0]?.origin).toBe('renderer:11')
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:22')[0]?.origin).toBe('renderer:22')
|
||||
})
|
||||
|
||||
it('retains identical high-water profiles independently per renderer', () => {
|
||||
const profile = { rendererSurface: 'main', thresholdPct: 80, usedHeapMB: 512 }
|
||||
recordCrashBreadcrumb('renderer_memory_highwater', profile, 'renderer:11')
|
||||
recordCrashBreadcrumb('renderer_memory_highwater', profile, 'renderer:22')
|
||||
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:11')[0]?.origin).toBe('renderer:11')
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:22')[0]?.origin).toBe('renderer:22')
|
||||
})
|
||||
|
||||
it('preserves the reporter trail when sibling renderer traffic fills the ring', () => {
|
||||
for (let index = 0; index < 4; index += 1) {
|
||||
recordCrashBreadcrumb('renderer_memory_highwater', {
|
||||
rendererSurface: `surface-${index}`,
|
||||
thresholdPct: 80
|
||||
})
|
||||
}
|
||||
recordCrashBreadcrumb('renderer_a_event', undefined, 'renderer:11')
|
||||
for (let index = 0; index < 26; index += 1) {
|
||||
recordCrashBreadcrumb(`renderer_b_event_${index}`, undefined, 'renderer:22')
|
||||
}
|
||||
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:11').map((entry) => entry.name)).toContain(
|
||||
'renderer_a_event'
|
||||
)
|
||||
})
|
||||
|
||||
it('folds pending repeats using the reporter-specific evidence window', () => {
|
||||
recordCoalescedCrashBreadcrumb({
|
||||
name: 'renderer_error',
|
||||
data: { message: 'boom' },
|
||||
coalesceKey: 'renderer:11\u0000renderer_error:boom',
|
||||
minIntervalMs: 30_000,
|
||||
origin: 'renderer:11'
|
||||
})
|
||||
recordCoalescedCrashBreadcrumb({
|
||||
name: 'renderer_error',
|
||||
data: { message: 'boom' },
|
||||
coalesceKey: 'renderer:22\u0000renderer_error:boom',
|
||||
minIntervalMs: 30_000,
|
||||
origin: 'renderer:22'
|
||||
})
|
||||
recordCoalescedCrashBreadcrumb({
|
||||
name: 'renderer_error',
|
||||
data: { message: 'boom' },
|
||||
coalesceKey: 'renderer:22\u0000renderer_error:boom',
|
||||
minIntervalMs: 30_000,
|
||||
origin: 'renderer:22'
|
||||
})
|
||||
recordCoalescedCrashBreadcrumb({
|
||||
name: 'renderer_error',
|
||||
data: { message: 'boom' },
|
||||
coalesceKey: 'renderer:11\u0000renderer_error:boom',
|
||||
minIntervalMs: 30_000,
|
||||
origin: 'renderer:11'
|
||||
})
|
||||
for (let index = 0; index < 4; index += 1) {
|
||||
recordCrashBreadcrumb(
|
||||
'renderer_memory_highwater',
|
||||
{ rendererSurface: `surface-${index}`, thresholdPct: 80 },
|
||||
'renderer:22'
|
||||
)
|
||||
}
|
||||
for (let index = 0; index < 25; index += 1) {
|
||||
recordCrashBreadcrumb(`renderer_b_event_${index}`, undefined, 'renderer:22')
|
||||
}
|
||||
|
||||
const snapshot = getCrashBreadcrumbSnapshot('renderer:11')
|
||||
|
||||
expect(snapshot).toHaveLength(1)
|
||||
expect(snapshot[0]?.data).toEqual({ message: 'boom', suppressedSinceLast: 1 })
|
||||
|
||||
const siblingSnapshot = getCrashBreadcrumbSnapshot('renderer:22')
|
||||
expect(siblingSnapshot.find((entry) => entry.name === 'renderer_error')?.data).toEqual({
|
||||
message: 'boom',
|
||||
suppressedSinceLast: 1
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -30,6 +30,7 @@ type CoalescedBreadcrumbState = {
|
||||
emitted?: CrashReportBreadcrumb
|
||||
/** Newest suppressed payload, sanitized only if a snapshot actually asks for it. */
|
||||
pending?: CrashReportBreadcrumbData
|
||||
origin?: string
|
||||
}
|
||||
|
||||
let breadcrumbs: CrashReportBreadcrumb[] = []
|
||||
@@ -42,19 +43,21 @@ function retainedBreadcrumbKey(breadcrumb: CrashReportBreadcrumb): string | null
|
||||
}
|
||||
const surface = breadcrumb.data?.rendererSurface
|
||||
const threshold = breadcrumb.data?.thresholdPct
|
||||
return `${breadcrumb.name}:${String(surface)}:${String(threshold)}`
|
||||
return `${breadcrumb.name}:${String(surface)}:${String(threshold)}:${breadcrumb.origin ?? 'global'}`
|
||||
}
|
||||
|
||||
/** Returns the stored breadcrumb so coalescing can refresh the entry it owns. */
|
||||
export function recordCrashBreadcrumb(
|
||||
name: string,
|
||||
data?: CrashReportBreadcrumbData
|
||||
data?: CrashReportBreadcrumbData,
|
||||
origin?: string
|
||||
): CrashReportBreadcrumb | undefined {
|
||||
const sanitized = sanitizeCrashReportBreadcrumbs([
|
||||
{
|
||||
createdAt: new Date().toISOString(),
|
||||
name,
|
||||
data
|
||||
data,
|
||||
...(origin ? { origin } : {})
|
||||
}
|
||||
])
|
||||
const breadcrumb = sanitized?.[0]
|
||||
@@ -85,12 +88,14 @@ export function recordCoalescedCrashBreadcrumb({
|
||||
name,
|
||||
data,
|
||||
coalesceKey,
|
||||
minIntervalMs
|
||||
minIntervalMs,
|
||||
origin
|
||||
}: {
|
||||
name: string
|
||||
data?: CrashReportBreadcrumbData
|
||||
coalesceKey: string
|
||||
minIntervalMs: number
|
||||
origin?: string
|
||||
}): { suppressedSinceLast: number } | undefined {
|
||||
const now = monotonicNow()
|
||||
const previous = coalescedBreadcrumbs.get(coalesceKey)
|
||||
@@ -136,7 +141,8 @@ export function recordCoalescedCrashBreadcrumb({
|
||||
windowStartedAtMs: now,
|
||||
suppressed: 0,
|
||||
carried: suppressedSinceLast,
|
||||
resolved: 0
|
||||
resolved: 0,
|
||||
...(origin ? { origin } : {})
|
||||
}
|
||||
coalescedBreadcrumbs.set(coalesceKey, state)
|
||||
while (coalescedBreadcrumbs.size > MAX_COALESCE_KEYS) {
|
||||
@@ -149,7 +155,8 @@ export function recordCoalescedCrashBreadcrumb({
|
||||
}
|
||||
state.emitted = recordCrashBreadcrumb(
|
||||
name,
|
||||
suppressedSinceLast > 0 ? { ...data, suppressedSinceLast } : data
|
||||
suppressedSinceLast > 0 ? { ...data, suppressedSinceLast } : data,
|
||||
origin
|
||||
)
|
||||
return { suppressedSinceLast }
|
||||
}
|
||||
@@ -157,22 +164,29 @@ export function recordCoalescedCrashBreadcrumb({
|
||||
/** Whether any future snapshot can still include this crumb. The ring only
|
||||
* appends and the retained map only grows toward its cap, so an entry pushed
|
||||
* past the snapshot budget is invisible forever, not just for now. */
|
||||
function isCoalescedCrumbStillInEvidence(crumb: CrashReportBreadcrumb): boolean {
|
||||
const visibleFrom = breadcrumbs.length - (MAX_BREADCRUMBS - retainedBreadcrumbs.size)
|
||||
const index = breadcrumbs.indexOf(crumb)
|
||||
if (index !== -1 && index >= visibleFrom) {
|
||||
function isCoalescedCrumbStillInEvidence(
|
||||
crumb: CrashReportBreadcrumb,
|
||||
reporterOrigin?: string
|
||||
): boolean {
|
||||
const retained = [...retainedBreadcrumbs.values()].filter((breadcrumb) =>
|
||||
isVisibleToReporter(breadcrumb, reporterOrigin)
|
||||
)
|
||||
if (retained.some((retainedBreadcrumb) => retainedBreadcrumb === crumb)) {
|
||||
return true
|
||||
}
|
||||
for (const retained of retainedBreadcrumbs.values()) {
|
||||
if (retained === crumb) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
const visibleRecent = breadcrumbs.filter((breadcrumb) =>
|
||||
isVisibleToReporter(breadcrumb, reporterOrigin)
|
||||
)
|
||||
return visibleRecent
|
||||
.slice(-(MAX_BREADCRUMBS - retained.length))
|
||||
.some((recentBreadcrumb) => recentBreadcrumb === crumb)
|
||||
}
|
||||
|
||||
/** Fold a key's newest suppressed payload into the ring entry it owns. */
|
||||
function resolvePendingCoalescedBreadcrumb(state: CoalescedBreadcrumbState): void {
|
||||
function resolvePendingCoalescedBreadcrumb(
|
||||
state: CoalescedBreadcrumbState,
|
||||
reporterOrigin?: string
|
||||
): void {
|
||||
// `data` is optional, so the count—not pending payload presence—marks unresolved work.
|
||||
if (!state.emitted || state.suppressed <= state.resolved) {
|
||||
return
|
||||
@@ -182,7 +196,7 @@ function resolvePendingCoalescedBreadcrumb(state: CoalescedBreadcrumbState): voi
|
||||
// then claim nothing — the burst vanishes from the record entirely. Drop the
|
||||
// handle (keeping `resolved` for folds that landed while it was live) so a
|
||||
// later emit or bounded cleanup can materialize the unclaimed repeats.
|
||||
if (!isCoalescedCrumbStillInEvidence(state.emitted)) {
|
||||
if (!isCoalescedCrumbStillInEvidence(state.emitted, reporterOrigin)) {
|
||||
state.emitted = undefined
|
||||
return
|
||||
}
|
||||
@@ -201,30 +215,46 @@ function resolvePendingCoalescedBreadcrumb(state: CoalescedBreadcrumbState): voi
|
||||
/** Resolve into the owned crumb, or emit the unclaimed repeats before bounded
|
||||
* cleanup drops an orphan's last accounting state. */
|
||||
function preservePendingCoalescedBreadcrumb(state: CoalescedBreadcrumbState): void {
|
||||
resolvePendingCoalescedBreadcrumb(state)
|
||||
resolvePendingCoalescedBreadcrumb(state, state.origin)
|
||||
const unresolved = state.suppressed - state.resolved
|
||||
if (state.emitted || unresolved <= 0) {
|
||||
return
|
||||
}
|
||||
recordCrashBreadcrumb(state.name, {
|
||||
...state.pending,
|
||||
suppressedSinceLast: unresolved
|
||||
})
|
||||
recordCrashBreadcrumb(
|
||||
state.name,
|
||||
{ ...state.pending, suppressedSinceLast: unresolved },
|
||||
state.origin
|
||||
)
|
||||
state.resolved = state.suppressed
|
||||
state.pending = undefined
|
||||
}
|
||||
|
||||
function resolveAllPendingCoalescedBreadcrumbs(): void {
|
||||
function resolveAllPendingCoalescedBreadcrumbs(reporterOrigin?: string): void {
|
||||
for (const state of coalescedBreadcrumbs.values()) {
|
||||
resolvePendingCoalescedBreadcrumb(state)
|
||||
if (reporterOrigin && state.origin && state.origin !== reporterOrigin) {
|
||||
continue
|
||||
}
|
||||
resolvePendingCoalescedBreadcrumb(state, reporterOrigin)
|
||||
}
|
||||
}
|
||||
|
||||
export function getCrashBreadcrumbSnapshot(): CrashReportBreadcrumb[] {
|
||||
resolveAllPendingCoalescedBreadcrumbs()
|
||||
function isVisibleToReporter(
|
||||
breadcrumb: CrashReportBreadcrumb,
|
||||
reporterOrigin: string | undefined
|
||||
): boolean {
|
||||
return !reporterOrigin || !breadcrumb.origin || breadcrumb.origin === reporterOrigin
|
||||
}
|
||||
|
||||
export function getCrashBreadcrumbSnapshot(reporterOrigin?: string): CrashReportBreadcrumb[] {
|
||||
resolveAllPendingCoalescedBreadcrumbs(reporterOrigin)
|
||||
// Why: long sessions must retain threshold profiles without growing the 30-entry budget.
|
||||
const retained = [...retainedBreadcrumbs.values()]
|
||||
const recent = breadcrumbs.slice(-(MAX_BREADCRUMBS - retained.length))
|
||||
const retained = [...retainedBreadcrumbs.values()].filter((breadcrumb) =>
|
||||
isVisibleToReporter(breadcrumb, reporterOrigin)
|
||||
)
|
||||
const visibleRecent = breadcrumbs.filter((breadcrumb) =>
|
||||
isVisibleToReporter(breadcrumb, reporterOrigin)
|
||||
)
|
||||
const recent = visibleRecent.slice(-(MAX_BREADCRUMBS - retained.length))
|
||||
return [...retained, ...recent]
|
||||
.sort((left, right) => left.createdAt.localeCompare(right.createdAt))
|
||||
.map((breadcrumb) => ({
|
||||
|
||||
@@ -41,7 +41,8 @@ function input(reason = 'crashed'): CrashReportCreateInput {
|
||||
{
|
||||
createdAt: '2026-05-16T01:00:00.000Z',
|
||||
name: 'workspace_opened',
|
||||
data: { path: '/Users/alice/project', ssh: false }
|
||||
data: { path: '/Users/alice/project', ssh: false },
|
||||
origin: 'renderer:42'
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -96,7 +96,9 @@ export class CrashReportStore {
|
||||
createdAt: new Date().toISOString(),
|
||||
status: 'pending',
|
||||
details: sanitizeCrashReportDetails(input.details),
|
||||
breadcrumbs: sanitizeCrashReportBreadcrumbs(input.breadcrumbs)
|
||||
breadcrumbs: sanitizeCrashReportBreadcrumbs(input.breadcrumbs)?.map(
|
||||
({ origin: _origin, ...breadcrumb }) => breadcrumb
|
||||
)
|
||||
}
|
||||
return {
|
||||
reports: [report, ...reports].slice(0, MAX_REPORTS),
|
||||
|
||||
@@ -41,11 +41,12 @@ function traceDurableBreadcrumb(
|
||||
export function recordDurableCrashBreadcrumb(
|
||||
name: string,
|
||||
data?: CrashReportBreadcrumbData,
|
||||
failureCause?: string
|
||||
failureCause?: string,
|
||||
origin?: string
|
||||
): void {
|
||||
const sanitizedName = sanitizeCrashReportString(name)
|
||||
const lifecycleData = buildLifecycleData(data)
|
||||
recordCrashBreadcrumb(sanitizedName, lifecycleData)
|
||||
recordCrashBreadcrumb(sanitizedName, lifecycleData, origin)
|
||||
traceDurableBreadcrumb(sanitizedName, lifecycleData, failureCause)
|
||||
}
|
||||
|
||||
@@ -56,12 +57,14 @@ export function recordCoalescedDurableCrashBreadcrumb({
|
||||
name,
|
||||
data,
|
||||
coalesceKey,
|
||||
minIntervalMs
|
||||
minIntervalMs,
|
||||
origin
|
||||
}: {
|
||||
name: string
|
||||
data?: CrashReportBreadcrumbData
|
||||
coalesceKey: string
|
||||
minIntervalMs: number
|
||||
origin?: string
|
||||
}): void {
|
||||
const sanitizedName = sanitizeCrashReportString(name)
|
||||
const lifecycleData = buildLifecycleData(data)
|
||||
@@ -69,7 +72,8 @@ export function recordCoalescedDurableCrashBreadcrumb({
|
||||
name: sanitizedName,
|
||||
data: lifecycleData,
|
||||
coalesceKey,
|
||||
minIntervalMs
|
||||
minIntervalMs,
|
||||
...(origin ? { origin } : {})
|
||||
})
|
||||
if (!coalesced) {
|
||||
return
|
||||
|
||||
@@ -77,6 +77,23 @@ describe('ProcessGoneDedupe', () => {
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('does not suppress simultaneous crashes from different renderers', () => {
|
||||
const dedupe = new ProcessGoneDedupe({ windowMs: 2_000 })
|
||||
|
||||
expect(
|
||||
dedupe.shouldRecord(getProcessGoneDedupeKey('renderer', 'renderer', 'crashed', 5, 11), 1_000)
|
||||
).toBe(true)
|
||||
expect(
|
||||
dedupe.shouldRecord(getProcessGoneDedupeKey('renderer', 'renderer', 'crashed', 5, 22), 1_001)
|
||||
).toBe(true)
|
||||
expect(
|
||||
dedupe.shouldRecord(
|
||||
getProcessGoneDedupeKey('renderer', 'renderer', 'oom', -536870904, 11),
|
||||
1_002
|
||||
)
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps child process crash tuples distinct inside renderer burst windows', () => {
|
||||
const dedupe = new ProcessGoneDedupe({ windowMs: 2_000 })
|
||||
|
||||
|
||||
@@ -80,12 +80,14 @@ export function getProcessGoneDedupeKey(
|
||||
source: 'renderer' | 'child',
|
||||
processType: string,
|
||||
reason: string,
|
||||
exitCode: number | null
|
||||
exitCode: number | null,
|
||||
webContentsId?: number
|
||||
): string {
|
||||
// Why: one renderer death can surface as crashed/oom/launch-failed in a
|
||||
// burst. Coalesce that prompt noise while keeping child identities precise.
|
||||
// burst. Coalesce that prompt noise per renderer while keeping child
|
||||
// identities precise.
|
||||
if (source === 'renderer') {
|
||||
return `${source}:${processType}`
|
||||
return `${source}:${processType}:${webContentsId ?? 'global'}`
|
||||
}
|
||||
return `${source}:${processType}:${reason}:${exitCode ?? 'null'}`
|
||||
}
|
||||
|
||||
@@ -114,6 +114,22 @@ describe('recordProcessGoneCrash', () => {
|
||||
expect(sink.flushMock).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('keeps suppressed renderer evidence scoped to its renderer', () => {
|
||||
const dedupe = new ProcessGoneDedupe()
|
||||
const suppressed = (webContentsId: number) =>
|
||||
event({ reason: 'killed', exitCode: 1, expectedTeardown: 'renderer-reload', webContentsId })
|
||||
|
||||
recordProcessGoneCrash({ record: vi.fn() } as never, suppressed(11), dedupe)
|
||||
recordProcessGoneCrash({ record: vi.fn() } as never, suppressed(22), dedupe)
|
||||
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:11')).toEqual([
|
||||
expect.objectContaining({ origin: 'renderer:11' })
|
||||
])
|
||||
expect(getCrashBreadcrumbSnapshot('renderer:22')).toEqual([
|
||||
expect.objectContaining({ origin: 'renderer:22' })
|
||||
])
|
||||
})
|
||||
|
||||
it('coalesces a recoverable-service crash loop instead of flushing every event', () => {
|
||||
const record = vi.fn()
|
||||
const dedupe = new ProcessGoneDedupe()
|
||||
@@ -314,6 +330,26 @@ describe('recordProcessGoneCrash', () => {
|
||||
expect(sink.flushMock).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('keeps simultaneous renderer reports distinct by webContents identity', async () => {
|
||||
const record = vi.fn().mockResolvedValue({ id: 'report-1' })
|
||||
const dedupe = new ProcessGoneDedupe()
|
||||
|
||||
recordProcessGoneCrash(
|
||||
{ record, attachDetails } as never,
|
||||
event({ webContentsId: 11 }),
|
||||
dedupe,
|
||||
noMinidump
|
||||
)
|
||||
recordProcessGoneCrash(
|
||||
{ record, attachDetails } as never,
|
||||
event({ webContentsId: 22 }),
|
||||
dedupe,
|
||||
noMinidump
|
||||
)
|
||||
|
||||
await vi.waitFor(() => expect(record).toHaveBeenCalledTimes(2))
|
||||
})
|
||||
|
||||
it('still persists the report when the forced trace flush fails', async () => {
|
||||
const record = vi.fn().mockResolvedValue({ id: 'report-1' })
|
||||
sink.flushMock.mockImplementation(() => {
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type CrashReportBreadcrumbData
|
||||
} from '../../shared/crash-reporting'
|
||||
import { decodePosixWaitStatus, describePosixWaitStatus } from '../../shared/posix-wait-status'
|
||||
import { rendererCrashBreadcrumbOrigin } from '../../shared/crash-breadcrumb-origin'
|
||||
import type { CrashReportStore } from './crash-report-store'
|
||||
import { getCrashBreadcrumbSnapshot } from './crash-breadcrumb-store'
|
||||
import {
|
||||
@@ -41,6 +42,7 @@ export type ProcessGoneCrashEvent = {
|
||||
exitCode: number | null
|
||||
expectedTeardown: ExpectedTeardownScope
|
||||
details: Record<string, unknown>
|
||||
webContentsId?: number
|
||||
}
|
||||
|
||||
type CrashReportRecorderStore = Pick<CrashReportStore, 'record' | 'attachDetails'>
|
||||
@@ -74,6 +76,12 @@ function processGoneBreadcrumbData(event: ProcessGoneCrashEvent) {
|
||||
return buildSuppressedProcessGoneBreadcrumbData(event)
|
||||
}
|
||||
|
||||
function processGoneRendererOrigin(event: ProcessGoneCrashEvent): string | undefined {
|
||||
return event.webContentsId === undefined
|
||||
? undefined
|
||||
: rendererCrashBreadcrumbOrigin(event.webContentsId)
|
||||
}
|
||||
|
||||
// Why: key off the emitted breadcrumb, not the crash-report dedupe key, so two
|
||||
// different recoverable services can never suppress each other's evidence.
|
||||
function suppressedProcessGoneCoalesceKey(data: CrashReportBreadcrumbData): string {
|
||||
@@ -179,11 +187,15 @@ export function recordProcessGoneCrash(
|
||||
// 1459/min) and each suppressed event costs a span plus a forced disk flush,
|
||||
// which both floods the 30-entry ring and evicts the real pre-crash trail.
|
||||
const suppressedData = processGoneBreadcrumbData(event)
|
||||
const origin = processGoneRendererOrigin(event)
|
||||
recordCoalescedDurableCrashBreadcrumb({
|
||||
name: 'process_gone_suppressed',
|
||||
data: suppressedData,
|
||||
coalesceKey: suppressedProcessGoneCoalesceKey(suppressedData),
|
||||
minIntervalMs: SUPPRESSED_PROCESS_GONE_COALESCE_MS
|
||||
coalesceKey: origin
|
||||
? `${origin}\u0000${suppressedProcessGoneCoalesceKey(suppressedData)}`
|
||||
: suppressedProcessGoneCoalesceKey(suppressedData),
|
||||
minIntervalMs: SUPPRESSED_PROCESS_GONE_COALESCE_MS,
|
||||
...(origin ? { origin } : {})
|
||||
})
|
||||
return
|
||||
}
|
||||
@@ -191,12 +203,19 @@ export function recordProcessGoneCrash(
|
||||
recordDurableCrashBreadcrumb(
|
||||
'crash_report_store_unavailable',
|
||||
processGoneBreadcrumbData(event),
|
||||
'Crash report store unavailable'
|
||||
'Crash report store unavailable',
|
||||
processGoneRendererOrigin(event)
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
const key = getProcessGoneDedupeKey(event.source, event.processType, event.reason, event.exitCode)
|
||||
const key = getProcessGoneDedupeKey(
|
||||
event.source,
|
||||
event.processType,
|
||||
event.reason,
|
||||
event.exitCode,
|
||||
event.webContentsId
|
||||
)
|
||||
const claim = dedupe.tryClaim(key)
|
||||
if (!claim) {
|
||||
return
|
||||
@@ -209,7 +228,8 @@ export function recordProcessGoneCrash(
|
||||
},
|
||||
event.processType
|
||||
)
|
||||
const breadcrumbs = getCrashBreadcrumbSnapshot()
|
||||
const breadcrumbs = getCrashBreadcrumbSnapshot(processGoneRendererOrigin(event))
|
||||
const reportBreadcrumbs = breadcrumbs?.map(({ origin: _origin, ...breadcrumb }) => breadcrumb)
|
||||
const span = startSpan('electron.process_gone', {
|
||||
attributes: {
|
||||
'crash.source': event.source,
|
||||
@@ -227,7 +247,7 @@ export function recordProcessGoneCrash(
|
||||
'app.main_process.launch_id': mainProcessLifecycle.mainProcessLaunchId,
|
||||
'app.main_process.started_at': mainProcessLifecycle.mainProcessStartedAt,
|
||||
details: crashDetails,
|
||||
breadcrumbs
|
||||
breadcrumbs: reportBreadcrumbs
|
||||
}
|
||||
})
|
||||
// Why: a renderer crash can be followed by another process exit before the
|
||||
@@ -252,7 +272,7 @@ export function recordProcessGoneCrash(
|
||||
electronVersion: process.versions.electron ?? 'unknown',
|
||||
chromeVersion: process.versions.chrome ?? 'unknown',
|
||||
details: crashDetails,
|
||||
breadcrumbs
|
||||
breadcrumbs: reportBreadcrumbs
|
||||
})
|
||||
.then((report) => {
|
||||
// Why: kept off the returned chain so a minidump failure can never reach
|
||||
@@ -268,7 +288,8 @@ export function recordProcessGoneCrash(
|
||||
recordDurableCrashBreadcrumb(
|
||||
'minidump_signature_attach_failed',
|
||||
processGoneBreadcrumbData(event),
|
||||
error instanceof Error ? error.message : String(error)
|
||||
error instanceof Error ? error.message : String(error),
|
||||
processGoneRendererOrigin(event)
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -279,7 +300,8 @@ export function recordProcessGoneCrash(
|
||||
recordDurableCrashBreadcrumb(
|
||||
'crash_report_persist_failed',
|
||||
data,
|
||||
`${String(data.errorName)}: ${String(data.errorMessage)}`
|
||||
`${String(data.errorName)}: ${String(data.errorMessage)}`,
|
||||
processGoneRendererOrigin(event)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { normalizeGitErrorMessage } from '../../shared/git-remote-error'
|
||||
import { isNoWriteFetchHeadUnsupportedError } from '../../shared/git-fetch-head-capability'
|
||||
import { runWithGitWorktreeOperationLock } from '../../shared/git-worktree-operation-lock'
|
||||
import {
|
||||
REBASE_SOURCE_FETCH_TIMEOUT_MS,
|
||||
resolveGitRemoteRebaseSource
|
||||
} from '../../shared/git-rebase-source'
|
||||
import type { GitRuntimeOptions } from './git-runtime-options'
|
||||
import { gitOptionsForWorktree } from './git-runtime-options'
|
||||
import { withLocalGitCapabilityCacheForExecution } from './git-capability-state'
|
||||
import { gitExecFileAsync } from './runner'
|
||||
import { runWithGitReadCacheInvalidation } from './status'
|
||||
|
||||
export async function gitPullRebaseFromBase(
|
||||
worktreePath: string,
|
||||
baseRef: string,
|
||||
options: GitRuntimeOptions = {}
|
||||
): Promise<void> {
|
||||
await runWithGitWorktreeOperationLock(worktreePath, options.signal, () =>
|
||||
gitPullRebaseFromBaseUnlocked(worktreePath, baseRef, options)
|
||||
)
|
||||
}
|
||||
|
||||
async function gitPullRebaseFromBaseUnlocked(
|
||||
worktreePath: string,
|
||||
baseRef: string,
|
||||
options: GitRuntimeOptions
|
||||
): Promise<void> {
|
||||
await runWithGitReadCacheInvalidation(async () => {
|
||||
const operationOptions = {
|
||||
...gitOptionsForWorktree(worktreePath, options),
|
||||
terminationBarrier: true,
|
||||
captureWslLoginShellOutput: true
|
||||
}
|
||||
let rebaseRef: string | null = null
|
||||
try {
|
||||
const source = await resolveGitRemoteRebaseSource(
|
||||
(args) => gitExecFileAsync(args, operationOptions),
|
||||
baseRef
|
||||
)
|
||||
let forkPoint: string | null = null
|
||||
let hasHead = true
|
||||
try {
|
||||
const { stdout } = await gitExecFileAsync(
|
||||
['merge-base', '--fork-point', `refs/remotes/${source.displayName}`, 'HEAD'],
|
||||
operationOptions
|
||||
)
|
||||
forkPoint = stdout.trim() || null
|
||||
} catch {
|
||||
// A first fetch or an unhelpful reflog falls back to Git's merge-base behavior.
|
||||
try {
|
||||
await gitExecFileAsync(['rev-parse', '--verify', 'HEAD'], operationOptions)
|
||||
} catch {
|
||||
hasHead = false
|
||||
}
|
||||
}
|
||||
// Why: concurrent fetches can replace FETCH_HEAD and remote-tracking refs between fetch and rebase.
|
||||
rebaseRef = `refs/orca/rebase/${randomUUID()}`
|
||||
const fetchArgs = [
|
||||
source.remoteName,
|
||||
`+refs/heads/${source.branchName}:${rebaseRef}`,
|
||||
`+refs/heads/${source.branchName}:refs/remotes/${source.displayName}`
|
||||
]
|
||||
await withLocalGitCapabilityCacheForExecution(
|
||||
{ cwd: worktreePath, ...options },
|
||||
(capabilities) =>
|
||||
capabilities.runWithFallback(
|
||||
'fetch-no-write-fetch-head',
|
||||
() =>
|
||||
gitExecFileAsync(['fetch', '--no-write-fetch-head', ...fetchArgs], {
|
||||
...operationOptions,
|
||||
timeout: REBASE_SOURCE_FETCH_TIMEOUT_MS
|
||||
}),
|
||||
() =>
|
||||
gitExecFileAsync(['fetch', ...fetchArgs], {
|
||||
...operationOptions,
|
||||
timeout: REBASE_SOURCE_FETCH_TIMEOUT_MS
|
||||
}),
|
||||
isNoWriteFetchHeadUnsupportedError
|
||||
)
|
||||
)
|
||||
await gitExecFileAsync(
|
||||
hasHead
|
||||
? forkPoint
|
||||
? ['rebase', '--onto', rebaseRef, forkPoint]
|
||||
: ['rebase', rebaseRef]
|
||||
: ['merge', '--ff-only', rebaseRef],
|
||||
operationOptions
|
||||
)
|
||||
} catch (error) {
|
||||
throw new Error(normalizeGitErrorMessage(error, 'pull'))
|
||||
} finally {
|
||||
if (rebaseRef) {
|
||||
try {
|
||||
const { signal: _abortedSignal, ...cleanupOptions } = gitOptionsForWorktree(
|
||||
worktreePath,
|
||||
options
|
||||
)
|
||||
await gitExecFileAsync(['update-ref', '-d', rebaseRef], cleanupOptions)
|
||||
} catch {
|
||||
// Cleanup must not hide the fetch or rebase result.
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
+138
-7
@@ -8,11 +8,20 @@ vi.mock('./runner', () => ({
|
||||
gitExecFileAsync: gitExecFileAsyncMock
|
||||
}))
|
||||
|
||||
import { REBASE_SOURCE_FETCH_TIMEOUT_MS } from '../../shared/git-rebase-source'
|
||||
import { clearGitCapabilityStateForTests } from './git-capability-state'
|
||||
import { gitFastForward, gitFetch, gitPull, gitPullRebaseFromBase, gitPush } from './remote'
|
||||
|
||||
const REBASE_OPERATION_OPTIONS = {
|
||||
cwd: '/repo',
|
||||
terminationBarrier: true,
|
||||
captureWslLoginShellOutput: true
|
||||
}
|
||||
|
||||
describe('git remote operations', () => {
|
||||
beforeEach(() => {
|
||||
gitExecFileAsyncMock.mockReset()
|
||||
clearGitCapabilityStateForTests()
|
||||
})
|
||||
|
||||
it('pushes to origin when no upstream is configured', async () => {
|
||||
@@ -511,32 +520,154 @@ describe('git remote operations', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it('rebases from the selected remote base ref', async () => {
|
||||
it('fetches to a private ref then rebases from the selected remote base ref', async () => {
|
||||
gitExecFileAsyncMock
|
||||
.mockResolvedValueOnce({ stdout: 'origin\nupstream\n', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: 'fork-point\n', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
|
||||
await gitPullRebaseFromBase('/repo', 'upstream/main')
|
||||
|
||||
expect(gitExecFileAsyncMock.mock.calls).toEqual([
|
||||
[['remote'], { cwd: '/repo' }],
|
||||
[['check-ref-format', '--branch', 'main'], { cwd: '/repo' }],
|
||||
[['pull', '--rebase', 'upstream', 'main'], { cwd: '/repo' }]
|
||||
[['remote'], REBASE_OPERATION_OPTIONS],
|
||||
[['check-ref-format', '--branch', 'main'], REBASE_OPERATION_OPTIONS],
|
||||
[
|
||||
['merge-base', '--fork-point', 'refs/remotes/upstream/main', 'HEAD'],
|
||||
REBASE_OPERATION_OPTIONS
|
||||
],
|
||||
[
|
||||
[
|
||||
'fetch',
|
||||
'--no-write-fetch-head',
|
||||
'upstream',
|
||||
expect.stringMatching(/^\+refs\/heads\/main:refs\/orca\/rebase\//),
|
||||
'+refs/heads/main:refs/remotes/upstream/main'
|
||||
],
|
||||
{ ...REBASE_OPERATION_OPTIONS, timeout: REBASE_SOURCE_FETCH_TIMEOUT_MS }
|
||||
],
|
||||
[
|
||||
['rebase', '--onto', expect.stringMatching(/^refs\/orca\/rebase\//), 'fork-point'],
|
||||
REBASE_OPERATION_OPTIONS
|
||||
],
|
||||
[['update-ref', '-d', expect.stringMatching(/^refs\/orca\/rebase\//)], { cwd: '/repo' }]
|
||||
])
|
||||
|
||||
const fetchRefspec = gitExecFileAsyncMock.mock.calls[3][0][3]
|
||||
const rebasedRef = gitExecFileAsyncMock.mock.calls[4][0][2]
|
||||
const deletedRef = gitExecFileAsyncMock.mock.calls[5][0][2]
|
||||
expect(fetchRefspec).toBe(`+refs/heads/main:${rebasedRef}`)
|
||||
expect(gitExecFileAsyncMock.mock.calls[3][0][4]).toBe(
|
||||
'+refs/heads/main:refs/remotes/upstream/main'
|
||||
)
|
||||
expect(deletedRef).toBe(rebasedRef)
|
||||
})
|
||||
|
||||
it('uses the longest configured remote name when rebasing from a base ref', async () => {
|
||||
gitExecFileAsyncMock
|
||||
.mockResolvedValueOnce({ stdout: 'fork\nfork/team\n', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: 'fork-point\n', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
|
||||
await gitPullRebaseFromBase('/repo', 'fork/team/feature/base')
|
||||
|
||||
expect(gitExecFileAsyncMock).toHaveBeenLastCalledWith(
|
||||
['pull', '--rebase', 'fork/team', 'feature/base'],
|
||||
{ cwd: '/repo' }
|
||||
expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
5,
|
||||
['rebase', '--onto', expect.stringMatching(/^refs\/orca\/rebase\//), 'fork-point'],
|
||||
REBASE_OPERATION_OPTIONS
|
||||
)
|
||||
})
|
||||
|
||||
it('rebases when the selected remote has not been fetched before', async () => {
|
||||
gitExecFileAsyncMock
|
||||
.mockResolvedValueOnce({ stdout: 'upstream\n', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockRejectedValueOnce(new Error('missing remote-tracking ref'))
|
||||
.mockResolvedValueOnce({ stdout: 'head\n', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
|
||||
await expect(gitPullRebaseFromBase('/repo', 'upstream/main')).resolves.toBeUndefined()
|
||||
|
||||
expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
5,
|
||||
[
|
||||
'fetch',
|
||||
'--no-write-fetch-head',
|
||||
'upstream',
|
||||
expect.stringMatching(/^\+refs\/heads\/main:refs\/orca\/rebase\//),
|
||||
'+refs/heads/main:refs/remotes/upstream/main'
|
||||
],
|
||||
{ ...REBASE_OPERATION_OPTIONS, timeout: REBASE_SOURCE_FETCH_TIMEOUT_MS }
|
||||
)
|
||||
})
|
||||
|
||||
it('fast-forwards an unborn branch from the fetched private ref', async () => {
|
||||
gitExecFileAsyncMock
|
||||
.mockResolvedValueOnce({ stdout: 'upstream\n', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockRejectedValueOnce(new Error('unborn HEAD'))
|
||||
.mockRejectedValueOnce(new Error('unborn HEAD'))
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
|
||||
await gitPullRebaseFromBase('/repo', 'upstream/main')
|
||||
|
||||
const fetchedRef = gitExecFileAsyncMock.mock.calls[4][0][3]
|
||||
expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
6,
|
||||
['merge', '--ff-only', fetchedRef.slice(fetchedRef.indexOf(':') + 1)],
|
||||
REBASE_OPERATION_OPTIONS
|
||||
)
|
||||
})
|
||||
|
||||
it('removes the private ref when rebase fails', async () => {
|
||||
const controller = new AbortController()
|
||||
gitExecFileAsyncMock
|
||||
.mockResolvedValueOnce({ stdout: 'upstream\n', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: 'fork-point\n', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockImplementationOnce(async () => {
|
||||
controller.abort()
|
||||
throw new Error('fatal: rebase conflict')
|
||||
})
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
|
||||
await expect(
|
||||
gitPullRebaseFromBase('/repo', 'upstream/main', { signal: controller.signal })
|
||||
).rejects.toThrow('fatal: rebase conflict')
|
||||
|
||||
const rebasedRef = gitExecFileAsyncMock.mock.calls[4][0][2]
|
||||
expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(6, ['update-ref', '-d', rebasedRef], {
|
||||
cwd: '/repo'
|
||||
})
|
||||
})
|
||||
|
||||
it('serializes the private fetch when Git cannot avoid writing FETCH_HEAD', async () => {
|
||||
gitExecFileAsyncMock
|
||||
.mockResolvedValueOnce({ stdout: 'upstream\n', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: 'fork-point\n', stderr: '' })
|
||||
.mockRejectedValueOnce(new Error("error: unknown option `no-write-fetch-head'"))
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: '' })
|
||||
|
||||
await gitPullRebaseFromBase('/repo', 'upstream/main')
|
||||
|
||||
const preferredRefspecs = gitExecFileAsyncMock.mock.calls[3][0].slice(3)
|
||||
expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(
|
||||
5,
|
||||
['fetch', 'upstream', ...preferredRefspecs],
|
||||
{ ...REBASE_OPERATION_OPTIONS, timeout: REBASE_SOURCE_FETCH_TIMEOUT_MS }
|
||||
)
|
||||
})
|
||||
|
||||
|
||||
+9
-26
@@ -4,13 +4,15 @@ import {
|
||||
} from '../../shared/git-remote-error'
|
||||
import { resolveEffectiveGitUpstream } from '../../shared/git-effective-upstream'
|
||||
import { gitRefTargetsBranchOnRemote } from '../../shared/git-remote-branch-name'
|
||||
import { resolveGitRemoteRebaseSource } from '../../shared/git-rebase-source'
|
||||
import type { GitPushTarget } from '../../shared/worktree/types'
|
||||
import type { GitRuntimeOptions } from './git-runtime-options'
|
||||
import { gitOptionsForWorktree } from './git-runtime-options'
|
||||
import { validateGitPushTarget } from './push-target-validation'
|
||||
import { gitExecFileAsync } from './runner'
|
||||
import { runWithGitReadCacheInvalidation } from './status'
|
||||
import { runWithGitWorktreeOperationLock } from '../../shared/git-worktree-operation-lock'
|
||||
|
||||
export { gitPullRebaseFromBase } from './remote-rebase'
|
||||
|
||||
async function getConfiguredPushTarget(
|
||||
worktreePath: string,
|
||||
@@ -257,8 +259,8 @@ export async function gitPull(
|
||||
// Why: plain `git pull` uses the user's configured pull strategy (merge by
|
||||
// default) so diverged branches reconcile instead of erroring out. Conflicts
|
||||
// surface through the existing conflict-resolution flow.
|
||||
await runWithGitReadCacheInvalidation(() =>
|
||||
gitPullWithArgs(worktreePath, [], pushTarget, options)
|
||||
await runWithGitWorktreeOperationLock(worktreePath, options.signal, () =>
|
||||
runWithGitReadCacheInvalidation(() => gitPullWithArgs(worktreePath, [], pushTarget, options))
|
||||
)
|
||||
}
|
||||
|
||||
@@ -267,32 +269,13 @@ export async function gitFastForward(
|
||||
pushTarget?: GitPushTarget,
|
||||
options: GitRuntimeOptions = {}
|
||||
): Promise<void> {
|
||||
await runWithGitReadCacheInvalidation(() =>
|
||||
gitPullWithArgs(worktreePath, ['--ff-only'], pushTarget, options)
|
||||
await runWithGitWorktreeOperationLock(worktreePath, options.signal, () =>
|
||||
runWithGitReadCacheInvalidation(() =>
|
||||
gitPullWithArgs(worktreePath, ['--ff-only'], pushTarget, options)
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
export async function gitPullRebaseFromBase(
|
||||
worktreePath: string,
|
||||
baseRef: string,
|
||||
options: GitRuntimeOptions = {}
|
||||
): Promise<void> {
|
||||
await runWithGitReadCacheInvalidation(async () => {
|
||||
try {
|
||||
const source = await resolveGitRemoteRebaseSource(
|
||||
(args) => gitExecFileAsync(args, gitOptionsForWorktree(worktreePath, options)),
|
||||
baseRef
|
||||
)
|
||||
await gitExecFileAsync(
|
||||
['pull', '--rebase', source.remoteName, source.branchName],
|
||||
gitOptionsForWorktree(worktreePath, options)
|
||||
)
|
||||
} catch (error) {
|
||||
throw new Error(normalizeGitErrorMessage(error, 'pull'))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
export async function gitFetch(
|
||||
worktreePath: string,
|
||||
pushTarget?: GitPushTarget,
|
||||
|
||||
@@ -218,6 +218,50 @@ describe('runner execFile timeout handling', () => {
|
||||
expect(child.kill).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')(
|
||||
'keeps a barrier Git abort pending until the process group closes',
|
||||
async () => {
|
||||
const child = createMockChildProcess(1234)
|
||||
spawnMock.mockImplementation((command: string) => {
|
||||
if (command !== 'ps') {
|
||||
return child
|
||||
}
|
||||
const probe = createMockChildProcess(4321)
|
||||
queueMicrotask(() => probe.emit('close', 0, null))
|
||||
return probe
|
||||
})
|
||||
const processKill = vi.spyOn(process, 'kill').mockImplementation(() => true)
|
||||
const controller = new AbortController()
|
||||
try {
|
||||
const pending = gitExecFileAsync(['status'], {
|
||||
cwd: '/repo',
|
||||
signal: controller.signal,
|
||||
terminationBarrier: true
|
||||
})
|
||||
let settled = false
|
||||
void pending.then(
|
||||
() => {
|
||||
settled = true
|
||||
},
|
||||
() => {
|
||||
settled = true
|
||||
}
|
||||
)
|
||||
|
||||
controller.abort()
|
||||
child.emit('close', 0, null)
|
||||
await vi.advanceTimersByTimeAsync(1_999)
|
||||
expect(settled).toBe(false)
|
||||
await vi.advanceTimersByTimeAsync(1)
|
||||
expect(processKill).toHaveBeenCalledWith(-1234, 'SIGKILL')
|
||||
|
||||
await expect(pending).rejects.toMatchObject({ name: 'AbortError' })
|
||||
} finally {
|
||||
processKill.mockRestore()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it('rejects gh executions that never call back using the default timeout', async () => {
|
||||
const child = createMockChildProcess(1234)
|
||||
execFileMock.mockReturnValue(child)
|
||||
|
||||
@@ -253,6 +253,76 @@ describe('WSL direct Git reads', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('fences parsed output from a barrier Git login-shell fallback', async () => {
|
||||
await withPlatform('win32', async () => {
|
||||
seedWslGitReadEnvironmentForTests(DISTRO, LOGIN_ENVIRONMENT)
|
||||
spawnMock.mockImplementation((_command, args) => {
|
||||
const child = createMockChild()
|
||||
queueMicrotask(() => {
|
||||
const capturedCommand = args?.find((arg) =>
|
||||
String(arg).includes('__ORCA_WSL_CAPTURE_BEGIN_')
|
||||
)
|
||||
const fenced = fencedProbeStdout(capturedCommand, 'fork-point\n')
|
||||
const echoedMarker = fenced.match(/__ORCA_WSL_CAPTURE_BEGIN_[^_]+__/)?.[0] ?? ''
|
||||
child.stdout.emit('data', Buffer.from(`${echoedMarker}shell trace\n${fenced}`))
|
||||
child.emit('close', 0, null)
|
||||
})
|
||||
return child
|
||||
})
|
||||
|
||||
await expect(
|
||||
gitExecFileAsync(['merge-base', '--fork-point', 'upstream/main', 'HEAD'], {
|
||||
cwd: String.raw`C:\repo`,
|
||||
env: { GIT_CONFIG_GLOBAL: '/home/user/custom.gitconfig' },
|
||||
wslDistro: DISTRO,
|
||||
captureWslLoginShellOutput: true,
|
||||
terminationBarrier: true
|
||||
})
|
||||
).resolves.toEqual({ stdout: 'fork-point\n', stderr: '' })
|
||||
|
||||
expect(spawnMock.mock.calls[0]?.[1]?.join(' ')).toContain('setsid --wait')
|
||||
expect(spawnMock.mock.calls[0]?.[1]?.join(' ')).toContain('__ORCA_WSL_CAPTURE_BEGIN_')
|
||||
})
|
||||
})
|
||||
|
||||
it('verifies the WSL guest process group before settling an abort', async () => {
|
||||
await withPlatform('win32', async () => {
|
||||
seedWslGitReadEnvironmentForTests(DISTRO, LOGIN_ENVIRONMENT)
|
||||
const command = createMockChild()
|
||||
spawnMock.mockImplementation((_program, args) => {
|
||||
if (spawnMock.mock.calls.length === 1) {
|
||||
queueMicrotask(() => {
|
||||
const marker = String(args?.join(' ')).match(
|
||||
/(__ORCA_WSL_PROCESS_GROUP_[0-9a-f-]+__=)/
|
||||
)?.[1]
|
||||
command.stderr.emit('data', Buffer.from(`${marker}4321\n`))
|
||||
})
|
||||
return command
|
||||
}
|
||||
const terminator = createMockChild()
|
||||
queueMicrotask(() => terminator.emit('close', 0, null))
|
||||
return terminator
|
||||
})
|
||||
const controller = new AbortController()
|
||||
const pending = gitExecFileAsync(['status'], {
|
||||
cwd: String.raw`C:\repo`,
|
||||
env: { GIT_CONFIG_GLOBAL: '/home/user/custom.gitconfig' },
|
||||
wslDistro: DISTRO,
|
||||
signal: controller.signal,
|
||||
terminationBarrier: true
|
||||
})
|
||||
await vi.waitFor(() => expect(spawnMock).toHaveBeenCalledTimes(1))
|
||||
await Promise.resolve()
|
||||
|
||||
controller.abort()
|
||||
|
||||
await expect(pending).rejects.toMatchObject({ name: 'AbortError' })
|
||||
expect(command.kill).not.toHaveBeenCalled()
|
||||
expect(spawnMock.mock.calls[1]?.[1]?.join(' ')).toContain('kill -TERM')
|
||||
expect(spawnMock.mock.calls[1]?.[1]).toContain('4321')
|
||||
})
|
||||
})
|
||||
|
||||
it('ignores unchanged ambient host Git variables when selecting the direct path', async () => {
|
||||
await withPlatform('win32', async () => {
|
||||
const originalAskpass = process.env.GIT_ASKPASS
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user