mirror of
https://github.com/stablyai/orca.git
synced 2026-10-19 16:03:26 +00:00
Merge remote-tracking branch 'origin/main' into ssh-relay-pty-backpressure-2
# Conflicts: # config/reliability-gates.jsonc # src/main/ssh/ssh-relay-session-reconnect-incarnation.test.ts # src/main/ssh/ssh-relay-session.ts # src/relay/relay.ts
This commit is contained in:
@@ -184,7 +184,9 @@ jobs:
|
||||
name: ssh docker watcher isolation
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
# Why 35: the terminal parking + retention specs below add two more
|
||||
# docker-rig tests capped at 240s each on top of the watcher isolation pair.
|
||||
timeout-minutes: 35
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -227,6 +229,13 @@ jobs:
|
||||
- name: Run Docker SSH watcher isolation E2E
|
||||
run: xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:ssh-docker-watcher-isolation
|
||||
|
||||
# Why always(): these specs gate the C1 terminal parking/retention budget
|
||||
# over a real SSH host and run in no other lane, so a watcher-isolation
|
||||
# failure above must not silently skip them.
|
||||
- name: Run Docker SSH terminal parking + retention E2E
|
||||
if: always()
|
||||
run: xvfb-run --auto-servernum env SKIP_BUILD=1 ORCA_E2E_FORWARD_APP_LOGS=1 pnpm run test:e2e:ssh-docker-terminal-parking
|
||||
|
||||
- name: Upload watcher isolation traces
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
|
||||
+170
-19
@@ -10,6 +10,86 @@
|
||||
}
|
||||
},
|
||||
"gates": [
|
||||
{
|
||||
"id": "mobile-ui.drawer-close-continuity",
|
||||
"title": "Mobile drawers finish closing despite parent rerenders",
|
||||
"maturity": "experimental",
|
||||
"protection": "partial",
|
||||
"owner": "mobile-ui",
|
||||
"layer": "react-native-modal-lifecycle",
|
||||
"surfaces": [
|
||||
"host action sheet",
|
||||
"host rename navigation",
|
||||
"host removal confirmation",
|
||||
"shared mobile bottom drawers"
|
||||
],
|
||||
"platforms": ["ios", "android", "macos"],
|
||||
"providers": ["provider-independent"],
|
||||
"coveredPlatforms": ["ios", "macos"],
|
||||
"coveredProviders": ["provider-independent"],
|
||||
"coverageNotes": "A deterministic React lifecycle test proves callback churn cannot restart an in-flight drawer close, and an iOS 26.5 simulator run covers Edit Host plus confirmed host removal. Android native-modal behavior remains a live-test gap.",
|
||||
"motivatingLinks": ["https://github.com/stablyai/orca/issues/8791"],
|
||||
"invariant": "Once a bottom drawer begins closing, unrelated parent rerenders must not replace its completion callback or restart the native hide animation. The drawer must unmount once and deliver the latest after-close action exactly once.",
|
||||
"oracle": "Render one drawer, begin closing it, rerender with new parent callbacks before completion, and require every MountedBottomDrawer frame to retain one onHidden identity. Trigger that completion barrier repeatedly, then require the drawer's null render to commit before only the latest after-close callback runs exactly once.",
|
||||
"commands": [
|
||||
"pnpm --dir mobile exec vitest run --root .. mobile/src/components/bottom-drawer-close-lifecycle.test.ts",
|
||||
"Manual iOS 26.5 simulator: long-press paired host; open Edit host; return; long-press host; Remove; confirm Remove; assert host disappears"
|
||||
],
|
||||
"testFiles": ["mobile/src/components/bottom-drawer-close-lifecycle.test.ts"],
|
||||
"assertionRefs": [
|
||||
{
|
||||
"file": "mobile/src/components/bottom-drawer-close-lifecycle.test.ts",
|
||||
"assertions": ["keeps close stable and delivers the latest action once after unmount"]
|
||||
}
|
||||
],
|
||||
"evidenceRuns": [
|
||||
{
|
||||
"date": "2026-07-28",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "pnpm --dir mobile exec vitest run --root .. mobile/src/components/bottom-drawer-close-lifecycle.test.ts",
|
||||
"result": "passed",
|
||||
"durationSeconds": 0.18,
|
||||
"summary": "The focused lifecycle harness passed with stable completion identity, latest-callback delivery, and drawer unmount assertions."
|
||||
},
|
||||
{
|
||||
"date": "2026-07-28",
|
||||
"runner": "manual",
|
||||
"platform": "ios",
|
||||
"command": "Manual iOS 26.5 simulator: long-press paired host; open Edit host; return; long-press host; Remove; confirm Remove; assert host disappears",
|
||||
"result": "passed",
|
||||
"durationSeconds": 37,
|
||||
"summary": "Edit host opened responsively after the drawer closed; returning and confirming Remove deleted the host without freezing."
|
||||
}
|
||||
],
|
||||
"runtimeBudget": {
|
||||
"p95Seconds": 5,
|
||||
"scope": "focused React lifecycle contract test"
|
||||
},
|
||||
"flakeHistory": {
|
||||
"status": "unknown",
|
||||
"evidence": "One deterministic local contract run and one iOS simulator flow exist; CI and soak history are not yet available."
|
||||
},
|
||||
"redGreenEvidence": {
|
||||
"status": "complete",
|
||||
"evidence": "On current main, the harness failed because each parent render created a different onHidden callback. The stable completion callback fix passes the byte-identical oracle; restoring the inline callback reproduces the failure."
|
||||
},
|
||||
"performanceBudget": {
|
||||
"required": true,
|
||||
"evidence": "Any number of parent rerenders retains one close-completion identity, so they add zero hide-animation restarts, timers, listeners, or after-close deliveries."
|
||||
},
|
||||
"promotionCriteria": [
|
||||
"Collect 100 consecutive CI passes or 14 days of soak history.",
|
||||
"Run the host Edit and Remove flows on a physical iOS device and an Android emulator or device.",
|
||||
"Keep the callback-identity and exactly-once delivery assertions intact for every shared drawer lifecycle change."
|
||||
],
|
||||
"knownGaps": [
|
||||
"Android native-modal behavior has no live evidence.",
|
||||
"The simulator run used an unreachable stored host rather than a connected multi-worktree host.",
|
||||
"The contract test injects the hide-completion barrier instead of running Reanimated."
|
||||
],
|
||||
"demotionRule": "Keep experimental or demote if parent rerenders can restart drawer hiding, after-close delivery duplicates or goes stale, the focused contract flakes, or either mobile platform retains a touch-blocking modal."
|
||||
},
|
||||
{
|
||||
"id": "mobile-relay.endpoint-recovery",
|
||||
"title": "Mobile relay recovery retries offline hosts and races direct endpoints",
|
||||
@@ -5196,7 +5276,7 @@
|
||||
},
|
||||
{
|
||||
"id": "orchestration.worker-terminal-delivery",
|
||||
"title": "Started workers are visible without stealing focus and retain mailbox identity",
|
||||
"title": "Workers remain visible and observable across workspace entry and app restart",
|
||||
"maturity": "experimental",
|
||||
"protection": "partial",
|
||||
"owner": "orchestration",
|
||||
@@ -5206,29 +5286,63 @@
|
||||
"worker-start",
|
||||
"terminal creation",
|
||||
"terminal tab materialization",
|
||||
"workspace re-entry"
|
||||
"workspace re-entry",
|
||||
"app restart with retained daemon PTYs",
|
||||
"legacy update resume fencing"
|
||||
],
|
||||
"platforms": ["macos", "linux", "windows"],
|
||||
"providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"],
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["local", "daemon", "ssh"],
|
||||
"coverageNotes": "Deterministic units cover local worker presentation, reveal-failure warnings, stable-pane Run/Dispatch routing, and the SSH in-process CLI fallback. An isolated macOS Electron journey launches a fake Codex worker through the real RPC path, tolerates spawn-time handle reminting, asserts the inactive tab in the DOM before navigation, checks Run delivery by pane identity, and proves workspace re-entry keeps one worker tab by both original tab ID and visible title. SSH, WSL, remote-runtime, Linux, and Windows remain live-test gaps; federated workers retain explicit background presentation.",
|
||||
"coverageNotes": "Deterministic units cover authority-aware legacy formatting, exact legacy worker identity planning, local worker presentation, retained-output reads after adoption, reveal-failure warnings, stable-pane Run/Dispatch routing, the SSH in-process CLI fallback, and federated non-reveal. Two isolated macOS Electron journeys launch fake Codex workers through the real RPC path and record append-only spawn/interruption ledgers. They assert immediate inactive presentation, one live agent PID, stable PTY/incarnation/tab/leaf/worktree/Task/Dispatch identity, and no interruption after workspace re-entry; the restart journey additionally removes renderer ownership, marks the Dispatch legacy, retains the daemon process across an app restart, and proves exact background adoption with readable ACK output and no resume replay. Distinct A/B artifacts plus live SSH, WSL, folder, remote-runtime, Linux, and Windows cutover journeys remain explicit gaps.",
|
||||
"motivatingLinks": ["https://github.com/stablyai/orca/pull/11107#discussion_r3663321387"],
|
||||
"invariant": "Starting a worker in the coordinator's current workspace must materialize one inactive terminal tab before worker-start returns, preserve coordinator focus, and remain exactly once after workspace re-entry. An exact existing target workspace must receive a discoverable tab without stealing coordinator focus; if renderer reveal fails, worker-start must expose that the live worker remains background-only. Run and Dispatch checks must resolve through the caller's stable pane identity when a terminal handle is reminted, while a live handle outranks mismatched pane metadata, explicit legacy terminal inspection remains handle-scoped, and remote or headless worker presentation remains background-only.",
|
||||
"oracle": "Drive Run create, Task create, and worker-start through a production Electron runtime with a deterministic Codex fixture. Require the worker tab to be visible in the DOM with data-active=false while the coordinator tab stays active, send ACK to the Run, read it with a deliberately stale coordinator handle plus its stable pane key, switch workspaces away and back, and require exactly one worker tab by original ID and visible title. Unit tests separately assert local worker-start omits background presentation, reveal failures return an actionable warning without discarding the worker, reminted coordinators and workers retain mailbox routing, live handles outrank mismatched pane metadata, and explicit legacy terminal checks do not inherit the caller pane key locally or through the SSH fallback.",
|
||||
"invariant": "Starting a worker in the coordinator's current workspace must materialize one inactive terminal tab before worker-start returns, preserve coordinator focus, and remain exactly once after workspace re-entry. After an app update or restart, an exact live legacy worker must fence automatic provider resume, adopt its original PTY into its original background pane, retain readable output, and clear the resume record without spawning, writing, signalling, interrupting, replacing, or focusing the worker. An exact existing target workspace must receive a discoverable tab without stealing coordinator focus; if renderer reveal fails, worker-start must expose that the live worker remains background-only. Run and Dispatch checks must resolve through the caller's stable pane identity when a terminal handle is reminted, while a live handle outranks mismatched pane metadata, explicit legacy terminal inspection remains handle-scoped, and remote or headless worker presentation remains background-only.",
|
||||
"oracle": "Drive Run create, Task create, and worker-start through production Electron runtimes with a deterministic Codex fixture. Require append-only ledgers with one still-live PID and no interruption, a visible inactive worker tab while the coordinator stays active, Run delivery through stable pane identity, and stable PTY/incarnation, tab, leaf, worktree, Task, and Dispatch across workspace re-entry. In a restart journey, retain the original daemon PTY and PID, remove renderer ownership, retain sleeping-session evidence, mark the Dispatch legacy, relaunch, and require exact inactive tab adoption, readable ACK output, cleared resume state, one spawn, and no resume argv or Conversation interrupted text after another workspace round trip. Unit tests separately assert authority-specific legacy affordances, exact identity and owner matching, retained-output fallback, pane-stable routing, federated non-activation, and SSH fallback parity.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/cli/handlers/orchestration.test.ts src/cli/handlers/orchestration-check-identity.test.ts src/cli/handlers/orchestration-worker-cli.test.ts src/main/runtime/rpc/methods/orchestration.test.ts src/main/ssh/ssh-remote-orca-cli.test.ts",
|
||||
"pnpm run test:e2e -- tests/e2e/orchestration-worker-terminal-visibility.spec.ts --workers=1"
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/formatter.test.ts src/main/runtime/rpc/methods/orchestration-federation.test.ts",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.test.ts",
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orca-runtime.test.ts",
|
||||
"pnpm run test:e2e -- tests/e2e/orchestration-worker-terminal-visibility.spec.ts --workers=1",
|
||||
"pnpm run test:e2e -- tests/e2e/orchestration-legacy-worker-restart-recovery.spec.ts --workers=1"
|
||||
],
|
||||
"testFiles": [
|
||||
"src/main/runtime/orchestration/formatter.test.ts",
|
||||
"src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.test.ts",
|
||||
"src/main/runtime/orca-runtime.test.ts",
|
||||
"src/cli/handlers/orchestration.test.ts",
|
||||
"src/cli/handlers/orchestration-check-identity.test.ts",
|
||||
"src/cli/handlers/orchestration-worker-cli.test.ts",
|
||||
"src/main/runtime/rpc/methods/orchestration.test.ts",
|
||||
"src/main/runtime/rpc/methods/orchestration-federation.test.ts",
|
||||
"src/main/ssh/ssh-remote-orca-cli.test.ts",
|
||||
"tests/e2e/orchestration-worker-terminal-visibility.spec.ts"
|
||||
"tests/e2e/orchestration-worker-terminal-visibility.spec.ts",
|
||||
"tests/e2e/orchestration-legacy-worker-restart-recovery.spec.ts"
|
||||
],
|
||||
"assertionRefs": [
|
||||
{
|
||||
"file": "src/main/runtime/orchestration/orchestration-legacy-worker-terminal-recovery.test.ts",
|
||||
"assertions": [
|
||||
"only exact unique terminal, pane, process-incarnation, and worktree evidence becomes recoverable",
|
||||
"ambiguous, incomplete, or mismatched legacy identities remain fenced and deferred"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/main/runtime/orca-runtime.test.ts",
|
||||
"assertions": [
|
||||
"one exact live legacy worker is adopted into its original background pane without input or signals",
|
||||
"automatic provider resume stays fenced until exact adoption is persisted",
|
||||
"retained renderer output remains readable through the recovered terminal"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/main/runtime/orchestration/formatter.test.ts",
|
||||
"assertions": [
|
||||
"legacy compatibility and recovery replay show only runtime-supplied supported actions",
|
||||
"legacy provenance without live authority stays read-only",
|
||||
"current formatting remains unchanged"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/cli/handlers/orchestration-check-identity.test.ts",
|
||||
"assertions": [
|
||||
@@ -5252,6 +5366,10 @@
|
||||
"a live handle cannot be retargeted by mismatched pane metadata"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "src/main/runtime/rpc/methods/orchestration-federation.test.ts",
|
||||
"assertions": ["federated worker placement explicitly sets activate=false"]
|
||||
},
|
||||
{
|
||||
"file": "src/main/ssh/ssh-remote-orca-cli.test.ts",
|
||||
"assertions": [
|
||||
@@ -5265,7 +5383,18 @@
|
||||
"worker-start exposes one inactive worker tab before workspace navigation",
|
||||
"the coordinator tab remains active",
|
||||
"ACK delivery reaches a stable coordinator pane through a stale handle",
|
||||
"workspace re-entry does not duplicate the worker tab under the same or a new tab ID"
|
||||
"one spawn remains live with no interruption event",
|
||||
"PTY/incarnation, tab, leaf, worktree, Task, and Dispatch identities remain stable",
|
||||
"workspace re-entry does not duplicate the worker tab or print Conversation interrupted"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "tests/e2e/orchestration-legacy-worker-restart-recovery.spec.ts",
|
||||
"assertions": [
|
||||
"the original daemon PTY, process incarnation, PID, pane, Task, and Dispatch survive app restart",
|
||||
"the legacy worker tab is restored once in the background with retained ACK output",
|
||||
"sleeping-session, resume-claim, and pending-startup state are cleared after adoption",
|
||||
"no second spawn, resume argv, input, signal, interruption, or duplicate tab occurs after workspace re-entry"
|
||||
]
|
||||
}
|
||||
],
|
||||
@@ -5279,43 +5408,65 @@
|
||||
"durationSeconds": 5.27,
|
||||
"summary": "Five focused files passed with 216 tests, covering visible inactive local worker creation, reveal-failure warnings, stable-pane mailbox routing, live-handle precedence, and SSH fallback parity."
|
||||
},
|
||||
{
|
||||
"date": "2026-07-28",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/orchestration/formatter.test.ts src/main/runtime/rpc/methods/orchestration-federation.test.ts",
|
||||
"result": "passed",
|
||||
"durationSeconds": 2.72,
|
||||
"summary": "Two focused files passed with 34 tests, covering authority-aware legacy affordances and federated non-reveal."
|
||||
},
|
||||
{
|
||||
"date": "2026-07-28",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "pnpm run test:e2e -- tests/e2e/orchestration-worker-terminal-visibility.spec.ts --workers=1",
|
||||
"result": "passed",
|
||||
"durationSeconds": 11.5,
|
||||
"summary": "The isolated Electron journey passed with a real Run and Task, deterministic Codex PTY, immediate inactive DOM tab, ACK delivery through a stale coordinator handle, and exactly one worker tab by original ID and management title after workspace re-entry."
|
||||
"durationSeconds": 8.3,
|
||||
"summary": "The isolated Electron journey passed with one live fake-agent spawn, no interruption events, stable PTY/incarnation/tab/leaf/worktree/Task/Dispatch identity, immediate inactive presentation, pane-stable ACK delivery, and exactly one tab after workspace re-entry."
|
||||
},
|
||||
{
|
||||
"date": "2026-07-28",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "pnpm run test:e2e -- tests/e2e/orchestration-legacy-worker-restart-recovery.spec.ts --workers=1",
|
||||
"result": "passed",
|
||||
"durationSeconds": 12.6,
|
||||
"summary": "The restart journey retained one daemon PTY and PID, adopted its exact original background pane, preserved readable ACK output and Task/Dispatch authority, cleared all resume state, and recorded no second spawn, resume argv, input, signal, interruption, or duplicate after workspace re-entry."
|
||||
}
|
||||
],
|
||||
"runtimeBudget": {
|
||||
"p95Seconds": 45,
|
||||
"scope": "focused CLI/runtime units plus one isolated Electron worker-start journey"
|
||||
"p95Seconds": 75,
|
||||
"scope": "focused CLI/runtime units plus isolated worker-start and app-restart Electron journeys"
|
||||
},
|
||||
"flakeHistory": {
|
||||
"status": "unknown",
|
||||
"evidence": "The deterministic units and isolated Electron journey pass locally; CI and soak history are not yet available."
|
||||
"evidence": "The deterministic units and two isolated Electron journeys pass locally; CI and soak history are not yet available."
|
||||
},
|
||||
"redGreenEvidence": {
|
||||
"status": "partial",
|
||||
"evidence": "The focused presentation and stale-handle tests failed against the pre-fix implementation, and the live incident plus Electron topology showed the worker PTY existed without an immediate tab. Saved intentional-break and CI artifacts are still needed."
|
||||
"evidence": "The focused presentation and stale-handle tests failed against the pre-fix implementation. The restart journey additionally failed first on empty retained output while the original PTY/PID remained live, then passed after the scoped recovered-worker snapshot fallback. The live incident and pre-fix Electron topology showed workspace re-entry replaying provider resume against a worker whose tab binding was missing. Saved intentional-break and CI artifacts are still needed."
|
||||
},
|
||||
"performanceBudget": {
|
||||
"required": true,
|
||||
"evidence": "Worker-start reuses the existing one-shot renderer reveal and adds no polling, provider listing, or output work. Check adds one optional pane-key field and reuses the existing Run scan or bounded active-Dispatch lookup; it adds no extra RPC, subprocess, timer, or renderer update. Federated and explicitly background terminals are unchanged."
|
||||
"evidence": "Worker-start reuses the existing one-shot renderer reveal and adds no polling, provider listing, or output work. Startup recovery performs one bounded controller inventory per legacy candidate, exact owner/identity checks, one background reveal, and a provider/renderer snapshot only when an adopted worker's in-memory tail is empty and terminal.read is explicitly requested. Check adds one optional pane-key field and reuses the existing Run scan or bounded active-Dispatch lookup. Federated and explicitly background terminals are unchanged."
|
||||
},
|
||||
"promotionCriteria": [
|
||||
"Collect 100 consecutive passes or 14 days of stable CI history on macOS, Linux, and Windows.",
|
||||
"Add live SSH and WSL exact-workspace worker-start evidence and a paired remote-runtime control.",
|
||||
"Run distinct installed A/B artifacts through separate headed and headless paired-runtime cutover journeys, plus a git-independent folder workspace parameter.",
|
||||
"Add Docker SSH restart/reconnect proof and physical Windows WSL correct-distro/wrong-distro proof.",
|
||||
"Attach saved intentional-break artifacts for hidden local presentation and dropped stable-pane delivery."
|
||||
],
|
||||
"knownGaps": [
|
||||
"No live Linux, Windows, SSH, WSL, or paired remote-runtime run is attached.",
|
||||
"No distinct installed A/B headed or headless paired-runtime cutover is attached; the restart journey relaunches the same build while preserving the daemon and agent.",
|
||||
"No Docker SSH restart/reconnect, physical Windows WSL distro-authority, or git-independent folder-workspace cutover journey is attached.",
|
||||
"Packaged Windows updater and uninstaller continuity is owned by separate updater reliability work and is not claimed by this gate.",
|
||||
"The Electron journey uses a deterministic fake Codex CLI rather than a real account.",
|
||||
"The gate does not cover terminal output recovery after app restart; it covers identity, discoverability, focus, and mailbox routing."
|
||||
"The local presentation journey tolerates its existing terminal-handle remint and proves continuity by PTY/incarnation/tab/leaf; byte-stable handle proof across a real A/B cutover awaits the runtime-authority/RPC implementation.",
|
||||
"The local Electron restart proof covers retained visible output from the same-build daemon checkpoint, not transcript recovery after a transport cut or distinct A/B runtime replacement."
|
||||
],
|
||||
"demotionRule": "Keep experimental or demote if the Electron journey flakes without a product or harness defect, if local worker-start can return before tab materialization without an explicit reveal warning, if focus moves to the worker, if workspace re-entry duplicates the tab, or if pane-stable delivery reads the wrong mailbox."
|
||||
"demotionRule": "Keep experimental or demote if either Electron journey flakes without a product or harness defect, if local worker-start can return before tab materialization without an explicit reveal warning, if focus moves to the worker, if restart or workspace re-entry spawns/resumes/duplicates/interferes with the worker, if retained output becomes unreadable, or if pane-stable delivery reads the wrong mailbox."
|
||||
},
|
||||
{
|
||||
"id": "terminal-render.windows-cjk-repaint",
|
||||
|
||||
@@ -51,30 +51,39 @@ describe('orchestration skill guidance', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('teaches the hard cutover without reviving a legacy executor', () => {
|
||||
it('teaches attested adoption without reviving the retired scheduler', () => {
|
||||
const skill = readSkill()
|
||||
const migration = getSection(skill, 'Contract Migration')
|
||||
|
||||
expect(migration).toContain('hard cutover')
|
||||
expect(migration).toContain('effectsApplied')
|
||||
expect(migration).toContain('skills get orchestration --full')
|
||||
expect(migration).toContain('Do not retry the rejected command unchanged')
|
||||
expect(migration).toContain('no longer supervised')
|
||||
expect(migration).toContain('task-list --run run_legacy_local')
|
||||
expect(migration).toContain('Read-only inspection never consumes legacy mail')
|
||||
expect(migration).toContain('does not run a legacy scheduler, translate old writes, or drain')
|
||||
expect(migration).toContain('does not cancel the prior assignment')
|
||||
expect(migration).toContain('invalidate its worktree')
|
||||
expect(migration).toContain('discard filesystem changes')
|
||||
expect(migration).toContain('leave it as the only editor in that worktree')
|
||||
expect(migration).toContain('observe it manually, read-only')
|
||||
expect(migration).toContain('until it reaches a stable handoff point')
|
||||
expect(migration).toContain('visible activity is a reason to keep observing')
|
||||
expect(migration).toContain(
|
||||
'Never launch a replacement editor in the same worktree while the legacy worker may still write there.'
|
||||
'adopts a live pre-update orchestration assignment into an ordinary Run'
|
||||
)
|
||||
expect(migration).toContain('if remaining work needs new lifecycle supervision')
|
||||
expect(migration).not.toContain('restart the work using Run -> Task -> `worker-start`')
|
||||
expect(migration).toContain(
|
||||
'preserves the existing agent process, PTY/session, terminal handle, tab/leaf/pane, worktree or folder workspace, Task, and Dispatch'
|
||||
)
|
||||
expect(migration).toContain('never restarts or replaces the worker')
|
||||
expect(migration).toContain('The retired scheduler is not revived')
|
||||
expect(migration).toContain('[LEGACY COMPATIBILITY]')
|
||||
expect(migration).toContain('[LEGACY READ-ONLY]')
|
||||
expect(migration).toContain(
|
||||
'Loss of lifecycle authority does not invalidate the existing assignment, process, or filesystem work.'
|
||||
)
|
||||
expect(migration).toContain(
|
||||
'It must not spawn, write, signal, stop, switch, focus, split, or inject a terminal.'
|
||||
)
|
||||
expect(migration).not.toContain('task-list --run run_legacy_local')
|
||||
expect(migration).toContain('run_legacy_local is an empty audit tombstone')
|
||||
expect(migration).toContain('Recovered orchestration work from a contract update')
|
||||
expect(migration).toContain('run-show --id <adopted_run_id>')
|
||||
expect(migration).toContain('task-list --run <adopted_run_id>')
|
||||
expect(migration).toContain('Legacy inspection remains available without consuming mail')
|
||||
expect(migration).toContain('run-use --id <adopted_run_id> --takeover-legacy')
|
||||
expect(migration).toContain('Takeover fences only the old coordinator')
|
||||
expect(migration).toContain('Live legacy workers keep their original Tasks, Dispatches')
|
||||
expect(migration).toContain(
|
||||
'keep the original worker as the only editor until it reaches a stable handoff point'
|
||||
)
|
||||
expect(migration).toContain('a conflict-free placement for any remaining work')
|
||||
})
|
||||
|
||||
it('treats long-running worker waits as liveness checkpoints, not failures', () => {
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { spawnSync } from 'node:child_process'
|
||||
|
||||
const rawExtraArgs = process.argv.slice(2)
|
||||
const extraArgs = rawExtraArgs[0] === '--' ? rawExtraArgs.slice(1) : rawExtraArgs
|
||||
const pnpm = process.platform === 'win32' ? 'pnpm.cmd' : 'pnpm'
|
||||
const env = {
|
||||
...process.env,
|
||||
ORCA_E2E_SSH_DOCKER: '1'
|
||||
}
|
||||
|
||||
// Why: Node's CVE-2024-27980 hardening rejects .cmd spawns without shell on Windows.
|
||||
const spawnOptions = {
|
||||
stdio: 'inherit',
|
||||
env,
|
||||
shell: process.platform === 'win32'
|
||||
}
|
||||
|
||||
const runtime = spawnSync(pnpm, ['run', 'ensure:electron-runtime'], spawnOptions)
|
||||
|
||||
if (runtime.status !== 0) {
|
||||
process.exit(runtime.status ?? 1)
|
||||
}
|
||||
|
||||
// Why both specs in one runner: they share the docker SSH rig and the same
|
||||
// ORCA_E2E_SSH_DOCKER gate — the SSH parking spec proves SSH panes park and
|
||||
// restore, the retention spec proves the C1 budget bounds what they retain.
|
||||
const result = spawnSync(
|
||||
pnpm,
|
||||
[
|
||||
'exec',
|
||||
'playwright',
|
||||
'test',
|
||||
'tests/e2e/ssh-terminal-parking.spec.ts',
|
||||
'tests/e2e/terminal-retention-budget.spec.ts',
|
||||
'--config',
|
||||
'tests/playwright.config.ts',
|
||||
'--project',
|
||||
'electron-headless',
|
||||
'--workers=1',
|
||||
...extraArgs
|
||||
],
|
||||
spawnOptions
|
||||
)
|
||||
|
||||
process.exit(result.status ?? 1)
|
||||
@@ -1,213 +0,0 @@
|
||||
# STA-2694 — garbled terminal after switching away from an AI workspace
|
||||
|
||||
Handoff snapshot: 2026-07-27, branch
|
||||
`neil/sta-2694-fix-ui-rendering-artifacts-when-switching-away-from-ai`.
|
||||
|
||||
## The report
|
||||
|
||||
> When I use an AI tool—such as OpenCode—and switch away to the desktop or
|
||||
> another task, the page appears garbled or distorted upon returning; I have to
|
||||
> resize the window to restore the display.
|
||||
|
||||
Reporter hints: related to terminal parking / workspace switching; also happens
|
||||
with Claude Code and probably grok.
|
||||
|
||||
## Status
|
||||
|
||||
**One defect, root-caused and fixed, with a mechanism-level test that fails
|
||||
without the fix.** The garble window is *unbounded*, not the ~1s I originally
|
||||
claimed — see [the correction](#correction-the-window-is-unbounded).
|
||||
|
||||
A second hypothesis was implemented, then **refuted by measurement and
|
||||
reverted**. That refutation is the other half of the value here: it rules out a
|
||||
whole class of "just force a fuller repaint" fixes, and it is pinned by a test so
|
||||
it cannot be reintroduced.
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| Fix | `ed1eaf55f1` — release an abandoned synchronized-output frame on reveal |
|
||||
| Refuted + reverted | `0f7ec4458d`, reverted in `8d5eacecb4` |
|
||||
| Oracle + scope correction | `3ccffc17ec` |
|
||||
| Unit tests | 8 passing across 2 files |
|
||||
| e2e | 5 draw-command oracle + 10 headless convergence + 1 headful |
|
||||
| Teeth-verified | Yes — removing the fix fails the stranded-latch test |
|
||||
|
||||
## The defect
|
||||
|
||||
Alt-screen agent TUIs (OpenCode/OpenTUI, Codex, grok) bracket every repaint in
|
||||
DEC 2026 synchronized output — `\x1b[?2026h … \x1b[?2026l` — many times a second.
|
||||
Hide a pane mid-bracket (a worktree switch, a cold park, or an OS-level occlusion
|
||||
lands there routinely) and xterm keeps
|
||||
`decPrivateModes.synchronizedOutput` latched `true`.
|
||||
|
||||
`RenderService.refreshRows` checks that latch **before** rendering
|
||||
(`RenderService.ts:162`), so while it holds, every repaint Orca owns is a no-op:
|
||||
the forced render-pause repaint, the plain `refresh()` fallback, and the shared
|
||||
glyph-atlas rebuild all render zero rows against a perfectly correct buffer.
|
||||
|
||||
The fix (`terminal-synchronized-output-release.ts`) clears the latch and flushes
|
||||
the handler's buffered row range at both reveal repaint entry points, before the
|
||||
repaint. Both reveal paths reach it:
|
||||
|
||||
- `schedulePaneRevealPresent` (plain refocus / desktop return)
|
||||
- `resetWebglTextureAtlas` (worktree switch, cold park, tab reveal — also reached
|
||||
from `resetAndRefreshAllTerminalWebglAtlases` via the light tab-resume path)
|
||||
|
||||
### Correction: the window is unbounded
|
||||
|
||||
`ed1eaf55f1`'s commit message says this "closes a bounded window rather than the
|
||||
whole STA-2694 report", because xterm arms a 1s watchdog that clears the latch.
|
||||
**That was wrong.** The watchdog is armed only inside
|
||||
`SynchronizedOutputHandler.bufferRows`, and `refreshRows` returns at its
|
||||
`_isPaused` check *first*:
|
||||
|
||||
```ts
|
||||
public refreshRows(start, end, sync = false, isRedrawOnly = false): void {
|
||||
if (this._isPaused) { this._needsFullRefresh = true; return } // ← occluded pane stops here
|
||||
if (this._coreService.decPrivateModes.synchronizedOutput) {
|
||||
this._syncOutputHandler.bufferRows(start, end) // ← only place the watchdog arms
|
||||
return
|
||||
}
|
||||
...
|
||||
```
|
||||
|
||||
While a pane is occluded its `IntersectionObserver` sets `_isPaused`, so nothing
|
||||
ever reaches `bufferRows` and **no timer is ever pending**. A pane hidden
|
||||
mid-frame holds the latch with no watchdog behind it, indefinitely — which is the
|
||||
indefinite garble the report describes. `terminal-reveal-draw-command-probe.spec.ts`
|
||||
asserts exactly this: latch set, `_timeout === undefined`, and a repaint drawing
|
||||
0 instances.
|
||||
|
||||
This also explains the specific workaround: resizing the window makes the TUI
|
||||
repaint via SIGWINCH, and that repaint's closing `?2026l` clears the latch.
|
||||
|
||||
## The refuted hypothesis (do not reimplement)
|
||||
|
||||
The idea: xterm's renderers are diff-based, so a reveal `refresh()` skips cells
|
||||
whose model entry still matches the buffer, leaving an occluded canvas showing
|
||||
pre-hide pixels until a resize rebuilds the model. It is a *plausible* reading —
|
||||
`WebglRenderer._updateModel` really does early-continue per unchanged cell.
|
||||
|
||||
It is wrong, measured on a live pane:
|
||||
|
||||
| Refresh | `updateCell` calls | instances drawn |
|
||||
|---|---|---|
|
||||
| diff-skipped (model matches buffer) | 0 | 562 |
|
||||
| model cleared first | 561 | 562 |
|
||||
|
||||
`GlyphRenderer.render` copies vertices for **every** row up to `lineLengths[y]`
|
||||
into the active buffer and issues **one** full-viewport `drawElementsInstanced`.
|
||||
The diff only decides how much *vertex data* is rewritten, never how much is
|
||||
*drawn*. The DOM renderer likewise `replaceChildren()`s every row
|
||||
unconditionally. So clearing the model cannot change what reaches the screen.
|
||||
|
||||
Worse, it has a cost: `_clearModel(true)` zeroes every glyph vertex, and
|
||||
`RenderService.clear()` fires no repaint of its own — so any paint landing between
|
||||
the clear and the repopulating refresh draws an **empty** viewport (0 instances,
|
||||
also asserted in the spec). On a reveal that refresh is debounced through a RAF
|
||||
and can itself be swallowed, which would turn a merely-stale pane into a blank
|
||||
one. Reverted in `8d5eacecb4`.
|
||||
|
||||
The first test in the oracle spec pins the refutation so this cannot come back as
|
||||
a "fix".
|
||||
|
||||
## Why pixel oracles failed, and what replaced them
|
||||
|
||||
The field defect is "the buffer is correct but the compositor shows pre-hide
|
||||
pixels". Two pixel oracles were built and **both were proven blind** by injecting
|
||||
that exact defect (freeze `RenderService.refreshRows`, then write new content):
|
||||
|
||||
1. **Canvas-vs-buffer ink sampling.** `drawImage` on a
|
||||
non-`preserveDrawingBuffer` WebGL canvas hands back a *re-rendered* copy — it
|
||||
reported 0 missing cells against 5263 cells of text the canvas had never
|
||||
drawn.
|
||||
2. **Screenshot vs. a forced repaint.** Playwright's screenshot drives a fresh
|
||||
compositor frame, which *heals* the stale paint before capture; and the
|
||||
"repair" ran the same code the reveal already ran, so a shared defect cancels
|
||||
out.
|
||||
|
||||
An earlier resize-referenced oracle was also unsound: resizing shifts alt-screen
|
||||
rows, so its 4.4% pixel diff measured legitimate reflow.
|
||||
|
||||
**Pixels are the wrong layer** — anything that reads them can trigger the repaint
|
||||
that hides the bug. `tests/e2e/terminal-reveal-draw-command-probe.spec.ts`
|
||||
instead wraps `GlyphRenderer.updateCell` and `gl.drawElementsInstanced` on the
|
||||
live pane and counts draw commands. A draw command cannot be healed after the
|
||||
fact, so "did the reveal repaint?" is directly observable — and falsifiable,
|
||||
which is how the second hypothesis got refuted.
|
||||
|
||||
Use that spec for **paint** questions;
|
||||
`terminal-opencode-altscreen-reveal-artifacts.spec.ts` for **buffer, geometry and
|
||||
PTY-size convergence** (worktree switch, cold park, idle agent, headful desktop
|
||||
hide). The idle-agent case matters: every earlier test kept the TUI streaming
|
||||
across the reveal, so live frames repainted whatever the reveal got wrong and the
|
||||
defect healed itself before any assertion ran.
|
||||
|
||||
## Leads closed by measurement
|
||||
|
||||
Both were live suspects in the previous handoff; both are now ruled out.
|
||||
|
||||
- **Dimension staleness.** Every dimension-rebuilding path in `WebglRenderer` is
|
||||
behind an unchanged/zero-sized early exit that a hidden pane trips, and
|
||||
`performSafeFit` early-returns at unchanged geometry — so nothing on the reveal
|
||||
path re-runs `handleResize()`. Measured across a real `window.hide()` /
|
||||
`show()`: canvas backing store `1272×1104` matched the renderer's computed
|
||||
dimensions exactly, char metrics stayed `8.65×16`, `_isAttached` stayed true,
|
||||
the screen element stayed connected. No staleness.
|
||||
- **Lagging atlas page bindings.** Right after a reveal the bound texture version
|
||||
*does* lag the atlas page (e.g. 1297 vs 1366) — but bindings are lazy and
|
||||
`GlyphRenderer.render` rebinds any page whose version moved, so one repaint
|
||||
brings them level (1366/1366). Normal, not a defect. Judge bindings only
|
||||
*after* a draw.
|
||||
|
||||
## Residual risk
|
||||
|
||||
The oracle proves the repaint is *issued*; it does not photograph the user's
|
||||
screen. If a report survives this fix, the remaining suspects are below the draw
|
||||
call — GPU-process/compositor-level content loss — where the in-app sentinel on
|
||||
real hardware is the tool:
|
||||
|
||||
```js
|
||||
localStorage.setItem('orca:render-desync-sentinel', '1') // then reload
|
||||
```
|
||||
|
||||
Reproduce, then **⌘-click** (Ctrl-click off Mac) in the garbled pane. That starts
|
||||
a 10s burst at 250ms intervals; a trip needs the same cells missing across 2
|
||||
consecutive samples, ≥200 text cells, ≥8% missing. It writes `corrupt.png` +
|
||||
`corrupt.json` to `<userData>/terminal-render-desync-evidence/<captureId>/`, then
|
||||
runs atlas recovery and captures the healed frame. Armed at import when the flag
|
||||
is set (`terminal-freeze-breadcrumbs.ts:45`).
|
||||
|
||||
## Verification commands
|
||||
|
||||
```bash
|
||||
npx vitest run --config config/vitest.config.ts src/renderer/src/lib/pane-manager/
|
||||
npx tsc --noEmit -p config/tsconfig.tc.web.json
|
||||
npx playwright test tests/e2e/terminal-reveal-draw-command-probe.spec.ts \
|
||||
tests/e2e/terminal-opencode-altscreen-reveal-artifacts.spec.ts \
|
||||
tests/e2e/terminal-inline-tui-reveal-convergence.spec.ts \
|
||||
--config tests/playwright.config.ts --project=electron-headless --workers=1
|
||||
SKIP_BUILD=1 npx playwright test tests/e2e/terminal-opencode-altscreen-reveal-artifacts.spec.ts \
|
||||
--config tests/playwright.config.ts --project=electron-headful --workers=1
|
||||
```
|
||||
|
||||
To confirm the fix still has teeth, delete the
|
||||
`releaseAbandonedSynchronizedOutput(pane.terminal)` line from
|
||||
`schedulePaneRevealPresent` and re-run the oracle: the stranded-latch test fails
|
||||
with "the reveal repaint did not release the stranded latch, so the pane stays
|
||||
frozen".
|
||||
|
||||
## Files
|
||||
|
||||
Production:
|
||||
|
||||
- `src/renderer/src/lib/pane-manager/terminal-synchronized-output-release.ts` (the fix)
|
||||
- `src/renderer/src/lib/pane-manager/pane-reveal-repaint.ts` (`schedulePaneRevealPresent`)
|
||||
- `src/renderer/src/lib/pane-manager/pane-webgl-renderer.ts` (`resetWebglTextureAtlas`)
|
||||
|
||||
Tests:
|
||||
|
||||
- `terminal-synchronized-output-release.test.ts`, `reveal-repaint-synchronized-output.test.ts`
|
||||
- `tests/e2e/terminal-reveal-draw-command-probe.spec.ts` (the oracle)
|
||||
- `tests/e2e/terminal-opencode-altscreen-reveal-artifacts.spec.ts`,
|
||||
`tests/e2e/fixtures/opencode-altscreen-live-fixture.cjs`
|
||||
@@ -0,0 +1,576 @@
|
||||
# Preserve active orchestration work across contract updates
|
||||
|
||||
Status: implementation validation
|
||||
|
||||
Date: 2026-07-28
|
||||
|
||||
## Decision
|
||||
|
||||
Do not block updates, restart active workers, or revive the retired scheduler.
|
||||
|
||||
On first launch after the contract update, atomically adopt the durable
|
||||
pre-Run graph into one ordinary lightweight Run. Preserve every Task,
|
||||
Dispatch, message, gate, terminal, PTY, process, worktree, and prompt
|
||||
identifier. Mark only the pre-update Dispatch attempts as legacy-contract
|
||||
attempts and accept the exact command shapes already pasted into those
|
||||
workers through a narrow adapter.
|
||||
|
||||
This is state migration plus a per-Dispatch protocol adapter. It is not a
|
||||
second scheduler:
|
||||
|
||||
- the migrated Run owns the preserved graph and coordinator inbox;
|
||||
- legacy attempts keep their original protocol until they settle;
|
||||
- every new attempt uses the current protocol, even on a preserved Task; and
|
||||
- no placement, polling, concurrency, or deadline loop is resurrected.
|
||||
|
||||
## User-visible outcome
|
||||
|
||||
- The update installs immediately.
|
||||
- Existing coordinator and worker terminals keep the same process, PTY,
|
||||
worktree, prompt, Task ID, Dispatch ID, and history.
|
||||
- Orca does not inject text, focus a tab, or start a replacement editor.
|
||||
- The legacy graph appears in an automatically adopted, normal Run instead of
|
||||
being stranded in `run_legacy_local`.
|
||||
- An original live worker with retained launch proof can keep using the
|
||||
`heartbeat`, `worker_done`, `escalation`, `ask`, and `check` commands in its
|
||||
existing prompt.
|
||||
- An original live coordinator can keep listing and settling preserved Tasks,
|
||||
dispatch remaining work with current commands, check direct legacy mail, and
|
||||
use the pre-cutover `reply` CLI guidance.
|
||||
- Unprovable, stale, ambiguous, or already-settled rows remain inspectable and
|
||||
unmistakably read-only. They never advertise Reply or Ack actions.
|
||||
- A pre-update WSL process whose older launcher did not propagate the hidden
|
||||
token remains lifecycle read-only. Its assignment, process, terminal, and
|
||||
filesystem work remain valid and inspectable.
|
||||
|
||||
The retired `orchestration run`, `coordinator-start`, and `coordinator-stop`
|
||||
scheduler commands remain retired. Their in-memory loop cannot be reconstructed
|
||||
truthfully. The coordinator agent and all durable work remain accessible; it
|
||||
explicitly dispatches any ready work that was never assigned before the update.
|
||||
|
||||
## Evidence and constraints
|
||||
|
||||
- Schema v7 preserved old `messages`, `tasks`, `dispatch_contexts`, and
|
||||
`decision_gates` by assigning them to `run_legacy_local`.
|
||||
- The exact prompt at `8b154d686` used old `send`, `ask`, and consuming
|
||||
`check` shapes. It omitted `worker_done --outcome`; a subject equal to
|
||||
`Failed` or beginning `Failed:` represented failure. Its escalation carried
|
||||
`taskId` but no `dispatchId`.
|
||||
- `reply` existed in the old CLI and message formatter guidance, not in that
|
||||
pinned worker prompt.
|
||||
- Restored `OrcaRuntime` PTY records currently set `launchToken: null`, and
|
||||
provider `listProcesses()` does not expose the launch token. Handles and
|
||||
pane IDs alone therefore cannot authorize compatibility.
|
||||
- Managed hooks source the owner-only endpoint file on every invocation, so an
|
||||
old process reaches the new hook server after restart. The hook cache retains
|
||||
the prior authenticated pane/launch-token association and distinguishes
|
||||
hydrated rows from events observed by the current runtime.
|
||||
- Older builds did not propagate `ORCA_AGENT_LAUNCH_TOKEN` through `WSLENV`, and
|
||||
a running process cannot acquire it retroactively.
|
||||
- The CLI transport mutation receipt is keyed by rotating runtime
|
||||
authentication. It cannot deduplicate a legacy mutation across restart.
|
||||
- Current invalid-capability lifecycle sends deliberately remain as auditable
|
||||
rejected messages. Compatibility must not silently change that behavior.
|
||||
- PR #11142 fixes background-tab materialization for newly dispatched workers.
|
||||
It does not recover a pre-fix worker whose PTY survived an update after its
|
||||
renderer tab binding was lost; workspace activation can otherwise mistake
|
||||
that worker for a sleeping provider session and launch `codex resume`.
|
||||
- The packaged Windows launcher keeps its Electron-as-Node child alive for the
|
||||
lifetime of a blocking CLI command. A seamless design cannot assume that a
|
||||
bounded RPC wait releases the installed executable.
|
||||
|
||||
## Non-negotiable invariants
|
||||
|
||||
1. Adoption never spawns, writes, signals, stops, focuses, or injects a
|
||||
terminal and never mutates the assigned filesystem. It may restore one
|
||||
persisted background tab/leaf binding for the exact already-live PTY.
|
||||
2. Every durable row and identifier survives adoption; only its owning Run and
|
||||
explicit protocol metadata change.
|
||||
3. Compatibility is write-once per Dispatch. Migration never classifies a
|
||||
current retry as legacy.
|
||||
4. A legacy mutation requires one uniquely resolved legacy attempt or
|
||||
coordinator principal plus current live proof of its original process tree.
|
||||
5. Caller-supplied handles, pane keys, Task IDs, Dispatch IDs, or remote
|
||||
attachments never create authority.
|
||||
6. Current Dispatch behavior remains unchanged, including auditable rejected
|
||||
lifecycle messages, capabilities, process incarnation, Run Delivery, and
|
||||
question semantics.
|
||||
7. Legacy direct mail and current Run Delivery are disjoint, even when their
|
||||
Dispatches share one migrated Task and Run.
|
||||
8. A B-era disconnect may replay accepted work; it may not lose mail or create
|
||||
a second question, reply, completion, or settlement. A cut after an A-era
|
||||
ask was already answered is explicitly ambiguous because A persisted no
|
||||
invocation identity; recovery replays its answer through legacy check before
|
||||
a same-text question is asked again.
|
||||
9. Different reply bodies for the same source and principal conflict instead
|
||||
of creating multiple replies.
|
||||
10. Folder workspaces, SSH, WSL, remote runtimes, macOS, Linux, and Windows
|
||||
follow the same proof rules. Missing proof degrades to inspection without
|
||||
invalidating the retained assignment or filesystem work.
|
||||
|
||||
## Storage and atomic adoption
|
||||
|
||||
Raise the schema version and add:
|
||||
|
||||
```text
|
||||
dispatch_contexts.contract_version INTEGER NOT NULL
|
||||
dispatch_contexts.launch_token_hash TEXT
|
||||
messages.delivery_contract TEXT NOT NULL
|
||||
CHECK(delivery_contract IN ('legacy_direct', 'current_delivery', 'audit_only'))
|
||||
legacy_adoptions(
|
||||
source_run_id PRIMARY KEY,
|
||||
adopted_run_id UNIQUE NOT NULL,
|
||||
scheduler_state_lost INTEGER NOT NULL,
|
||||
adopted_at
|
||||
)
|
||||
legacy_compatibility_principals(
|
||||
id PRIMARY KEY,
|
||||
run_id NOT NULL,
|
||||
dispatch_id,
|
||||
role CHECK(role IN ('worker', 'coordinator')),
|
||||
host_scope NOT NULL,
|
||||
terminal_handle NOT NULL,
|
||||
pane_key NOT NULL,
|
||||
launch_token_hash NOT NULL,
|
||||
process_incarnation,
|
||||
status CHECK(status IN ('committed', 'settled', 'revoked')),
|
||||
UNIQUE(role, run_id, dispatch_id)
|
||||
)
|
||||
legacy_operation_receipts(
|
||||
principal_id,
|
||||
operation_key,
|
||||
method,
|
||||
payload_hash,
|
||||
effect_id,
|
||||
response_json,
|
||||
completed_at,
|
||||
PRIMARY KEY(principal_id, operation_key)
|
||||
)
|
||||
legacy_mail_receipts(
|
||||
principal_id,
|
||||
message_id,
|
||||
acknowledged_at,
|
||||
PRIMARY KEY(principal_id, message_id)
|
||||
)
|
||||
```
|
||||
|
||||
The schema migration runs in one `BEGIN IMMEDIATE` transaction:
|
||||
|
||||
1. create a persisted random Run ID and `legacy_adoptions` marker if one does
|
||||
not already exist;
|
||||
2. create an ordinary `legacy = 0` Run with a recovery objective;
|
||||
3. move all `run_legacy_local` Tasks, Dispatches, decision gates, messages,
|
||||
and question threads to it without changing their IDs, sequence, status, or
|
||||
content;
|
||||
4. mark pre-existing direct mail `legacy_direct` and hard-cutover rejection
|
||||
rows `audit_only`;
|
||||
5. mark a Dispatch legacy only when it predates the contract column and lacks
|
||||
a current dispatch capability; and
|
||||
6. fence any impossible outstanding legacy Delivery, move retained Delivery
|
||||
history to the adopted Run, assert every Task/Dispatch/gate/message/question/
|
||||
Delivery Run ID agrees, and leave `run_legacy_local` as an empty read-only
|
||||
audit tombstone.
|
||||
|
||||
Every new Dispatch and message writes the current contract explicitly.
|
||||
Repeated startup, a partially initialized fixture, and WAL recovery reuse the
|
||||
persisted adoption marker. Reset and fresh-database paths cannot synthesize
|
||||
legacy authority.
|
||||
|
||||
## Durable principals and live authority
|
||||
|
||||
After the hook server and PTY inventory are ready, a one-shot adoption service
|
||||
may commit compatibility principals. It does not mutate terminal processes or
|
||||
input.
|
||||
|
||||
Before renderer hydration, legacy Dispatch evidence also fences automatic
|
||||
provider resume for the exact sleeping pane. Once the relevant local daemon or
|
||||
SSH relay has authoritative inventory, Orca intersects the durable handle,
|
||||
pane, PTY ID, PTY incarnation, workspace, and host owner. A unique live match
|
||||
is adopted into its original tab/leaf as inactive background state while the
|
||||
coordinator tab remains active. Missing, stale, reused, cross-host, or
|
||||
ambiguous evidence stays fenced and inspectable. Ordinary provider resume is
|
||||
unblocked only when authoritative inventory proves that exact PTY exited.
|
||||
|
||||
At hook-server startup, copy the validated hydrated status rows into an
|
||||
immutable main-process-only startup snapshot before the server listens or
|
||||
binds the new listener. Later live events update a separate current-runtime
|
||||
observation map and cannot overwrite the pre-update commitment source. A
|
||||
current event is preferred but is not required before the worker's first
|
||||
post-restart lifecycle command when controller inventory proves the exact
|
||||
original PTY and process incarnation are live.
|
||||
|
||||
For each candidate it resolves the union of:
|
||||
|
||||
- durable Dispatch assignee and pane;
|
||||
- equivalent-pane aliases;
|
||||
- remote attachment and host ownership;
|
||||
- coordinator candidates from active legacy coordinator rows, Task creator
|
||||
handles, Dispatch coordinator/parent provenance, and direct-message
|
||||
sender/recipient history;
|
||||
- the restored terminal inventory and process incarnation; and
|
||||
- the hydrated, previously authenticated hook pane/launch-token association.
|
||||
|
||||
The candidate commits only when that union identifies exactly one role and
|
||||
row. The orchestration database stores a SHA-256 token commitment, never the
|
||||
raw token. The existing owner-only hook status cache is an input to the
|
||||
one-time commitment, but a hydrated status is not enough to mutate.
|
||||
|
||||
Every compatibility call then requires:
|
||||
|
||||
- a hidden launch token and pane inherited by the calling process;
|
||||
- the immutable pre-update hook commitment, plus either a matching
|
||||
current-runtime hook event or exact current controller proof of the original
|
||||
PTY and process incarnation;
|
||||
- a live PTY with the committed handle, host scope, and process incarnation;
|
||||
- the committed principal and exact active legacy Dispatch or adopted Run; and
|
||||
- an operation-specific unique match.
|
||||
|
||||
The current hook event or exact controller inventory proves that the process
|
||||
survived the restart; equality with the pre-update commitment proves it is the
|
||||
same launch. If the hook cache was absent, the provider cannot report the
|
||||
proof, the token changed, or any candidate is ambiguous, the row remains
|
||||
read-only.
|
||||
|
||||
For new Dispatches, persist the launch-token hash at dispatch time so later
|
||||
contract updates do not depend on hook-cache recovery. Never return or log raw
|
||||
tokens. Add explicit RPC-envelope, structured-log, error, and CLI JSON
|
||||
redaction tests.
|
||||
|
||||
Host scope is runtime-owned:
|
||||
|
||||
- local: stable local execution-host identity;
|
||||
- WSL: stable native execution-host identity plus distro;
|
||||
- SSH: saved-host authority plus remote pane/process identity; and
|
||||
- federated runtime: authenticated peer fingerprint plus remote attachment.
|
||||
|
||||
`pickRemoteCliEnv`, SSH relay forwarding, WSLENV, and the legacy in-process SSH
|
||||
fallback must carry the hidden evidence without exposing it in command text or
|
||||
logs. A local runtime never accepts a raw remote token as local authority.
|
||||
Pre-update WSL processes without the token cannot use the lifecycle adapter.
|
||||
|
||||
For SSH, the host passthrough and in-process fallback stamp the saved target,
|
||||
`SshRelaySession` connection incarnation, and attachment provenance from the
|
||||
authenticated runtime channel; caller environment cannot choose them. WSL
|
||||
stamps the runtime-owned native host and distro in both the full bridge and
|
||||
fallback bridge. The verifier intersects those stamps with the committed host
|
||||
scope before considering token or pane evidence.
|
||||
|
||||
## Mixed-contract Run and mail routing
|
||||
|
||||
The adopted Run is a normal current Run. Tasks belong to it, so a current retry
|
||||
of a preserved Task naturally routes to the same Run without a cross-Run Task
|
||||
reference.
|
||||
|
||||
Message delivery is selected by `messages.delivery_contract`, not by Run ID:
|
||||
|
||||
- old and adapter-created direct messages are `legacy_direct`;
|
||||
- current sends are `current_delivery`; and
|
||||
- migration rejections and non-actionable history are `audit_only`.
|
||||
|
||||
Current Run Delivery creation, filtering, waiting, and acknowledgment select
|
||||
only `current_delivery`. Legacy `check` selects only the exact principal's
|
||||
`legacy_direct` address. History and inbox may show all three with explicit
|
||||
labels but never attach actions to `audit_only`. Mixed legacy/current attempts
|
||||
under one Task are covered across send, ask, check, reply, and settlement.
|
||||
|
||||
The original coordinator is automatically associated with the adopted Run
|
||||
after its principal proves live. `run-use` may bind that same principal without
|
||||
converting legacy Dispatches. A different coordinator cannot silently take
|
||||
over while a legacy attempt is active; an explicit recovery takeover is a
|
||||
separate current-contract action and revokes legacy coordinator mutation
|
||||
authority before rebinding.
|
||||
|
||||
When that coordinator uses old direct `check`, the adapter also performs a
|
||||
non-consuming existence check for `current_delivery` mail. It never mixes the
|
||||
messages into legacy output; it prints the exact current Run check command and,
|
||||
after that command creates a Delivery, the exact acknowledgment form. This
|
||||
keeps an unchanged coordinator informed about current retries without
|
||||
weakening current Delivery semantics.
|
||||
|
||||
## Exact legacy adapter
|
||||
|
||||
The CLI keeps accepting the old flags. It sends a hidden compatibility
|
||||
envelope; the runtime, not the CLI, decides whether legacy behavior applies.
|
||||
|
||||
Version B generates a random hidden `compatibilityInvocationId` once per CLI
|
||||
process and reuses it for every transport reconnect by that invocation.
|
||||
`legacy_operation_receipts.operation_key` is this invocation ID for B calls.
|
||||
The method and canonical payload hash must also match.
|
||||
|
||||
Attested compatibility calls bypass the rotating-auth generic mutation ledger
|
||||
after the contract fence routes them to the adapter. Their only dedupe boundary
|
||||
is the compatibility-principal receipt transaction described here; current
|
||||
calls continue through the existing generic ledger unchanged.
|
||||
|
||||
Version A had no invocation ID. Cross-cutover reconstruction is therefore
|
||||
limited to effects with a durable semantic identity: final settlement per
|
||||
Dispatch, still-pending ask per normalized question/options/recipient, reply
|
||||
per source/principal/body, and read recovery per message. Heartbeat and
|
||||
escalation remain at-least-once across an A-to-B manual retry because
|
||||
collapsing identical commands could suppress a legitimate later event. Tests
|
||||
and guidance do not promise cross-cutover exactly-once behavior for those
|
||||
repeatable signals.
|
||||
|
||||
An A-era ask that was already answered before its output was lost is also
|
||||
ambiguous. B does not guess whether the same text means retry or a new
|
||||
question. Its answer is in the durable recovery cohort and the error tells the
|
||||
agent to run the exact legacy check command first. After that answer is printed
|
||||
and acknowledged, a new B invocation with identical text creates a new
|
||||
question. If multiple identical A threads exist, ask fails ambiguous and
|
||||
recovery check drains them by message sequence; no arbitrary thread is chosen.
|
||||
|
||||
### Lifecycle `send`
|
||||
|
||||
- `heartbeat` and `worker_done`: resolve Task + Dispatch from the payload, then
|
||||
intersect them with the verified worker principal.
|
||||
- `escalation`: resolve Task + verified worker principal to exactly one active
|
||||
legacy Dispatch because the old prompt supplied no Dispatch ID.
|
||||
- Preserve the old direct coordinator recipient after verifying it belongs to
|
||||
the adopted Run principal.
|
||||
- Infer missing `worker_done` outcome as `failed` only when the trimmed subject
|
||||
is `Failed` or begins `Failed:`; otherwise infer `succeeded`.
|
||||
- Normalize to the current internal settlement model.
|
||||
|
||||
Compatibility validation happens before message insertion. Current lifecycle
|
||||
handling is not refactored through this prevalidation: its existing
|
||||
invalid-capability audit message behavior remains locked by regression tests.
|
||||
|
||||
The DB commits the direct message, lifecycle effect, and compatibility receipt
|
||||
in one transaction. If a pre-update `worker_done` already settled the Dispatch,
|
||||
the adapter reconstructs the matching semantic receipt from the existing
|
||||
message and settlement. The persisted A settlement is authoritative: the
|
||||
pinned A reconciler recorded even a `Failed:` subject as completed, so B
|
||||
returns that original completed result rather than retroactively changing Task
|
||||
or dependency state. Only a not-yet-accepted B call applies the corrected
|
||||
failure inference. A conflicting retry fails.
|
||||
|
||||
### `check`
|
||||
|
||||
Legacy check is at-least-once:
|
||||
|
||||
1. a read RPC returns the exact unacknowledged `legacy_direct` message IDs
|
||||
without changing them;
|
||||
2. the CLI prints the complete response; and
|
||||
3. a hidden ack atomically records receipts and marks those exact rows read.
|
||||
|
||||
A cut after read and before ack replays the same IDs. `--peek` and `--all`
|
||||
remain read-only.
|
||||
|
||||
Version A could mark a message read before losing its response. On adoption,
|
||||
every eligible read direct message connected to a still-active legacy attempt
|
||||
and lacking a post-adoption receipt is inserted into a durable recovery cohort
|
||||
using `legacy_mail_receipts` with `acknowledged_at = NULL`. Legacy check drains
|
||||
that stable cohort in bounded sequence-ordered pages before ordinary unread
|
||||
mail. Each page is labeled
|
||||
`[LEGACY RECOVERY REPLAY — MAY HAVE BEEN SEEN]`, replays until its post-print
|
||||
ack, and then advances. The cohort never grows after adoption, so every
|
||||
eligible row is covered without an unbounded response. Settled-at-cutover and
|
||||
unrelated historical mail do not enter it.
|
||||
|
||||
### `ask`
|
||||
|
||||
Legacy ask is an idempotent mutation followed by a resumable read:
|
||||
|
||||
1. create or find the direct legacy gate/question by verified Dispatch,
|
||||
normalized question, options, and recipient;
|
||||
2. atomically commit its message/thread plus operation receipt and return the
|
||||
stable question ID;
|
||||
3. wait in bounded read-only slices using that ID; and
|
||||
4. after printing the answer, hidden-ack that exact answer.
|
||||
|
||||
On first adoption, existing pending decision-gate threads are indexed into the
|
||||
same semantic identity. A retry resumes them instead of creating another gate.
|
||||
|
||||
### `reply`
|
||||
|
||||
Legacy reply requires the source thread, the verified coordinator principal,
|
||||
and a unique question owned by the adopted Run. One transaction inserts the
|
||||
reply, resolves the exact gate, marks the exact source, and completes the
|
||||
receipt.
|
||||
|
||||
An existing pre-update reply with the same source, principal, and body is
|
||||
reconstructed as success. A second body for the same source/principal is a
|
||||
conflict, not another reply.
|
||||
|
||||
### Coordinator and Task commands
|
||||
|
||||
After automatic binding, unchanged Task listing, Task settlement, dispatch,
|
||||
and gate inspection use the adopted Run. A new attempt receives a current
|
||||
preamble, capability, launch-token commitment, and current message contract.
|
||||
No unrelated Task can be created until the migrated coordinator binding is
|
||||
proven or explicitly taken over.
|
||||
|
||||
## Windows update behavior
|
||||
|
||||
No compatibility mutation holds a DB transaction while waiting. Windows
|
||||
legacy `ask` commits the question, prints its stable ID and exact resume
|
||||
command, then exits before a long wait whenever the installed launcher cannot
|
||||
prove that the executable is replaceable.
|
||||
|
||||
The native packaged launcher sets an internal
|
||||
`ORCA_WINDOWS_PACKAGED_CLI_LAUNCHER=1` marker for its Electron-as-Node child.
|
||||
After the DB commit, legacy `ask` writes and flushes the stable question ID and
|
||||
the exact resume command, then exits with a documented `75` resume-required
|
||||
status. The command name comes only from the validated inherited
|
||||
`ORCA_CLI_COMMAND` packaged enum: `orca` for native packaged terminals or
|
||||
`orca-ide` for packaged WSL. Arbitrary environment text is rejected rather
|
||||
than rendered. The launcher propagates status 75. No long wait starts on this
|
||||
path.
|
||||
|
||||
This compatibility path makes the accepted question recoverable without
|
||||
claiming Windows updater or uninstaller process ownership. Generic executable
|
||||
drain, replacement, and uninstall behavior remains separate updater
|
||||
reliability work and requires its own Windows artifact proof.
|
||||
|
||||
## Rendering and authoritative guidance
|
||||
|
||||
Formatting is authority-aware:
|
||||
|
||||
- `[LEGACY COMPATIBILITY]`: live and attested; show only supported commands;
|
||||
- `[LEGACY RECOVERY REPLAY — MAY HAVE BEEN SEEN]`: one bounded cutover replay;
|
||||
- `[LEGACY READ-ONLY]`: retained but unactionable; no Reply or Ack hint; and
|
||||
- current messages: unchanged.
|
||||
|
||||
Update `skill-guides/orchestration.md` and regenerate its bundled source. The
|
||||
guide explains automatic adoption, exact continuity, the retired scheduler
|
||||
boundary, proof failures, current retries, and the Windows ask resume fallback.
|
||||
It must not tell agents to restart a worker whose Dispatch was adopted.
|
||||
|
||||
Formatting cannot use database provenance alone; current liveness and
|
||||
attestation are runtime facts. Recovery may reveal the exact already-live PTY
|
||||
once as an inactive background tab. It never creates a PTY or process, writes
|
||||
input, switches workspaces, focuses, splits, or injects a terminal.
|
||||
|
||||
## Deterministic verification
|
||||
|
||||
### Schema and authority
|
||||
|
||||
- Migrate exact pre-v7, hard-cutover, current, partial, WAL, reset, and fresh
|
||||
fixtures; preserve IDs and row counts and reuse one adopted Run.
|
||||
- Assert Task, Dispatch, decision-gate, message, question-thread, and retained
|
||||
Delivery Run ownership agrees; outstanding legacy Deliveries are fenced.
|
||||
- Prove current retries in the adopted Run remain current across repeated
|
||||
migrations.
|
||||
- Test unique worker/coordinator import from prior hook commitment plus current
|
||||
live hook, and every forged, stale, wrong-host, wrong-pane, wrong-process,
|
||||
duplicate-token, duplicate-role, equivalent-pane, and remote-attachment
|
||||
ambiguity.
|
||||
- Race a current-runtime hook before adoption and prove the immutable startup
|
||||
commitment is neither overwritten nor confused with live proof.
|
||||
- Cover manual coordinators with no `coordinator_runs` row and reject
|
||||
conflicting candidates from Task, Dispatch, and message provenance.
|
||||
- Assert all legacy authority failures occur before message/receipt/gate/state
|
||||
effects while current invalid-capability rejection remains unchanged.
|
||||
- Assert tokens are absent from RPC logs, errors, CLI output, and orchestration
|
||||
storage.
|
||||
|
||||
### Exact old behavior and replay
|
||||
|
||||
- Replay the pinned prompt's heartbeat, successful and `Failed:`
|
||||
`worker_done`, task-only escalation, ask, and consuming check.
|
||||
- Replay the old formatter's reply command separately.
|
||||
- Cover every operation once after B and once accepted by A immediately before
|
||||
the cutover where a durable semantic identity exists, including the bounded
|
||||
recovery replay for an A check and preservation of A's persisted settlement.
|
||||
- Prove one B invocation reuses its invocation ID across reconnect, while
|
||||
separate identical heartbeat/escalation invocations remain distinct.
|
||||
- Inject real transport cuts after check read, ask commit, reply commit, and
|
||||
completion commit; prove stable IDs and one receipt/effect.
|
||||
- Page a recovery cohort larger than one response limit across repeated
|
||||
disconnects and prove every eligible row appears until ack, then never again.
|
||||
- Test mixed legacy/current attempts for every send/check/ask/reply route and
|
||||
prove current Delivery cannot consume legacy direct mail and old coordinator
|
||||
check only advertises the exact non-consuming current Delivery command.
|
||||
|
||||
### Live two-launch E2E
|
||||
|
||||
The focused renderer/daemon restart regression reconstructs the rc.3-era
|
||||
orphan artifact in a shared candidate profile: a durable legacy Dispatch,
|
||||
sleeping provider record, and live daemon PTY with its visual binding removed.
|
||||
It proves startup restores the exact PID, PTY/incarnation, handle, tab/leaf,
|
||||
Task, and Dispatch; emits no provider-resume spawn or interruption; preserves
|
||||
coordinator focus; and remains inert after switching away and back. This
|
||||
candidate/candidate fixture covers the renderer regression deterministically
|
||||
but does not replace the distinct installed-A/candidate-B packaged cutover
|
||||
journey below. It does not claim packaged Windows updater behavior.
|
||||
|
||||
Use distinct installed A and B artifacts plus an external append-only fake
|
||||
agent spawn ledger:
|
||||
|
||||
1. launch A with coordinator and worker terminals and record the replaceable A
|
||||
desktop/main PID, runtime ID, version, and artifact hash separately from the
|
||||
durable daemon, coordinator, and worker identities;
|
||||
2. accept one command with durable semantic identity on A—pending ask, reply,
|
||||
completion, or check—cut its response, close A without stopping the daemon
|
||||
or fake agent, install B, and prove B owns the relaunched runtime;
|
||||
3. assert A's desktop/main process and runtime are gone, B has a different
|
||||
desktop/main PID, runtime ID, version, and artifact hash, while the daemon
|
||||
plus coordinator/worker PID and start time, PTY/session, terminal handle,
|
||||
tab/leaf/pane, worktree, Task, and Dispatch remain byte-identical;
|
||||
4. prove that exact pending ask, reply, completion, or check resumes or
|
||||
deduplicates on B; do not use heartbeat, escalation, or an already-answered
|
||||
A ask as an exactly-once oracle;
|
||||
5. run the remaining exact old lifecycle commands and settle the same
|
||||
Dispatch;
|
||||
6. switch away and back and assert no second spawn/tab and no
|
||||
`Conversation interrupted`; and
|
||||
7. create a current attempt on preserved state and prove current grammar.
|
||||
|
||||
The append-only spawn ledger and an append-only interruption ledger, daemon
|
||||
inventory, runtime terminal inventory, and every viewer DOM independently
|
||||
prove one launch, process, handle, tab, and no `Conversation interrupted`.
|
||||
Transport fault injection cuts the real CLI connection after check output but
|
||||
before ack, and after ask, reply, and completion commit. Re-run the byte-exact A
|
||||
argv under B and assert stable IDs plus exactly one message, gate, reply,
|
||||
settlement, and receipt.
|
||||
|
||||
Retain #11142's local visible-inactive test and extend its oracle beyond DOM
|
||||
counting with the ledgers and host inventory.
|
||||
|
||||
Run separate remote journeys:
|
||||
|
||||
- headed paired server A-to-B with a surviving external client;
|
||||
- headless `orca serve` A-to-B with the same surviving-client oracle;
|
||||
- both prove the remote PID/PTy continuity, both viewer states, zero
|
||||
client-local handles/tabs, and wrong-host evidence with zero effects;
|
||||
- Docker SSH restart/reconnect with a remote proof file binding the process,
|
||||
pane, and token commitment;
|
||||
- physical Windows WSL coverage proving the correct distro and rejecting a
|
||||
wrong-distro token; and
|
||||
- a git-independent folder workspace parameter through the same adoption
|
||||
journey.
|
||||
|
||||
Packaged Windows updater continuity is outside this migration gate. A separate
|
||||
updater change must prove candidate-built A/B install, executable release,
|
||||
resume, and normal uninstall behavior on Windows before making that guarantee.
|
||||
|
||||
## Implementation slices
|
||||
|
||||
1. Schema, atomic Run adoption, per-row contract provenance, and mixed mailbox.
|
||||
2. Hook-commitment import, live principal verifier, host scopes, and redaction.
|
||||
3. Atomic compatibility receipts plus lifecycle send/escalation.
|
||||
4. Check read/ack and cutover recovery replay.
|
||||
5. Ask create/resume, reply conflict semantics, and coordinator binding.
|
||||
6. CLI hidden envelope, SSH/WSL forwarding, Windows resume fallback.
|
||||
7. Authority-aware formatting and the version-matched orchestration guide.
|
||||
8. Two-launch, remote, platform, and #11142 regression coverage.
|
||||
9. Focused unit/type/lint/E2E checks and final adversarial review.
|
||||
|
||||
## Definition of done
|
||||
|
||||
- Updates are never blocked.
|
||||
- Every durable legacy Task is owned by an ordinary visible Run.
|
||||
- Every provably original live legacy Dispatch can finish through its existing
|
||||
prompt without changing process or worktree.
|
||||
- New attempts use the current contract and mailbox in that same Run.
|
||||
- No authority comes from IDs or handles alone.
|
||||
- No adoption step starts, stops, writes, signals, focuses, splits, or injects
|
||||
a terminal. Exact live-PTY recovery may restore one inactive background
|
||||
renderer tab/leaf binding.
|
||||
- B-era disconnects replay or deduplicate instead of losing or duplicating
|
||||
work; A-era repeatable signals and already-answered asks follow the explicit
|
||||
ambiguity recovery rules.
|
||||
- Lost scheduler memory is reported precisely without stranding durable state.
|
||||
- Local/background, remote, SSH, WSL, folder, and Windows guarantees have
|
||||
deterministic proof.
|
||||
- The PR contains this plan, focused implementation, and no unrelated changes.
|
||||
@@ -72,6 +72,7 @@
|
||||
"acorn": "8.15.0",
|
||||
"esbuild": "0.25.4",
|
||||
"expo-module-scripts": "^55.0.2",
|
||||
"happy-dom": "^20.9.0",
|
||||
"oxfmt": "^0.52.0",
|
||||
"oxlint": "^1.71.0",
|
||||
"react-test-renderer": "19.2.6",
|
||||
|
||||
Generated
+42
-2
@@ -168,6 +168,9 @@ importers:
|
||||
expo-module-scripts:
|
||||
specifier: ^55.0.2
|
||||
version: 55.0.2(@babel/core@7.29.7)(@babel/runtime@7.29.7)(@jest/types@29.6.3)(babel-jest@29.7.0(@babel/core@7.29.7))(esbuild@0.25.4)(eslint@9.39.4)(expo@55.0.27)(jest@29.7.0(@types/node@26.1.1))(prettier@2.8.8)(react-native@0.83.9(@babel/core@7.29.7)(@react-native/metro-config@0.85.2(@babel/core@7.29.7))(@types/react@19.2.14)(react@19.2.6))(react-refresh@0.14.2)(react-test-renderer@19.2.6(react@19.2.6))(react@19.2.6)
|
||||
happy-dom:
|
||||
specifier: ^20.9.0
|
||||
version: 20.11.1
|
||||
oxfmt:
|
||||
specifier: ^0.52.0
|
||||
version: 0.52.0
|
||||
@@ -188,7 +191,7 @@ importers:
|
||||
version: 8.1.0(@types/node@26.1.1)(esbuild@0.25.4)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0)
|
||||
vitest:
|
||||
specifier: ^4.1.9
|
||||
version: 4.1.9(@types/node@26.1.1)(jsdom@20.0.3)(vite@8.1.0(@types/node@26.1.1)(esbuild@0.25.4)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0))
|
||||
version: 4.1.9(@types/node@26.1.1)(happy-dom@20.11.1)(jsdom@20.0.3)(vite@8.1.0(@types/node@26.1.1)(esbuild@0.25.4)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0))
|
||||
|
||||
packages:
|
||||
|
||||
@@ -2741,6 +2744,9 @@ packages:
|
||||
'@types/unist@3.0.3':
|
||||
resolution: {integrity: sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==}
|
||||
|
||||
'@types/whatwg-mimetype@3.0.2':
|
||||
resolution: {integrity: sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==}
|
||||
|
||||
'@types/ws@8.18.1':
|
||||
resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==}
|
||||
|
||||
@@ -3177,6 +3183,10 @@ packages:
|
||||
buffer-from@1.1.2:
|
||||
resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}
|
||||
|
||||
buffer-image-size@0.6.4:
|
||||
resolution: {integrity: sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==}
|
||||
engines: {node: '>=4.0'}
|
||||
|
||||
buffer@6.0.3:
|
||||
resolution: {integrity: sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==}
|
||||
|
||||
@@ -3556,6 +3566,10 @@ packages:
|
||||
resolution: {integrity: sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==}
|
||||
engines: {node: '>=0.12'}
|
||||
|
||||
entities@7.0.1:
|
||||
resolution: {integrity: sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==}
|
||||
engines: {node: '>=0.12'}
|
||||
|
||||
error-ex@1.3.4:
|
||||
resolution: {integrity: sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ==}
|
||||
|
||||
@@ -4286,6 +4300,10 @@ packages:
|
||||
graceful-fs@4.2.11:
|
||||
resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
|
||||
|
||||
happy-dom@20.11.1:
|
||||
resolution: {integrity: sha512-XSt8tMzbW9ymE7687xztkO1ckR7qJNQ3LywY9vlYGhGi3zXrGBHuUo2Cl1ztZaICW+1eAGdkLbj6iwVqDT33kg==}
|
||||
engines: {node: '>=20.0.0'}
|
||||
|
||||
has-bigints@1.1.0:
|
||||
resolution: {integrity: sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==}
|
||||
engines: {node: '>= 0.4'}
|
||||
@@ -9661,6 +9679,8 @@ snapshots:
|
||||
|
||||
'@types/unist@3.0.3': {}
|
||||
|
||||
'@types/whatwg-mimetype@3.0.2': {}
|
||||
|
||||
'@types/ws@8.18.1':
|
||||
dependencies:
|
||||
'@types/node': 25.6.0
|
||||
@@ -10236,6 +10256,10 @@ snapshots:
|
||||
|
||||
buffer-from@1.1.2: {}
|
||||
|
||||
buffer-image-size@0.6.4:
|
||||
dependencies:
|
||||
'@types/node': 26.1.1
|
||||
|
||||
buffer@6.0.3:
|
||||
dependencies:
|
||||
base64-js: 1.5.1
|
||||
@@ -10611,6 +10635,8 @@ snapshots:
|
||||
|
||||
entities@6.0.1: {}
|
||||
|
||||
entities@7.0.1: {}
|
||||
|
||||
error-ex@1.3.4:
|
||||
dependencies:
|
||||
is-arrayish: 0.2.1
|
||||
@@ -11614,6 +11640,19 @@ snapshots:
|
||||
|
||||
graceful-fs@4.2.11: {}
|
||||
|
||||
happy-dom@20.11.1:
|
||||
dependencies:
|
||||
'@types/node': 26.1.1
|
||||
'@types/whatwg-mimetype': 3.0.2
|
||||
'@types/ws': 8.18.1
|
||||
buffer-image-size: 0.6.4
|
||||
entities: 7.0.1
|
||||
whatwg-mimetype: 3.0.0
|
||||
ws: 8.21.0
|
||||
transitivePeerDependencies:
|
||||
- bufferutil
|
||||
- utf-8-validate
|
||||
|
||||
has-bigints@1.1.0: {}
|
||||
|
||||
has-flag@3.0.0: {}
|
||||
@@ -14235,7 +14274,7 @@ snapshots:
|
||||
tsx: 4.22.4
|
||||
yaml: 2.9.0
|
||||
|
||||
vitest@4.1.9(@types/node@26.1.1)(jsdom@20.0.3)(vite@8.1.0(@types/node@26.1.1)(esbuild@0.25.4)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0)):
|
||||
vitest@4.1.9(@types/node@26.1.1)(happy-dom@20.11.1)(jsdom@20.0.3)(vite@8.1.0(@types/node@26.1.1)(esbuild@0.25.4)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0)):
|
||||
dependencies:
|
||||
'@vitest/expect': 4.1.9
|
||||
'@vitest/mocker': 4.1.9(vite@8.1.0(@types/node@26.1.1)(esbuild@0.25.4)(terser@5.49.0)(tsx@4.22.4)(yaml@2.9.0))
|
||||
@@ -14259,6 +14298,7 @@ snapshots:
|
||||
why-is-node-running: 2.3.0
|
||||
optionalDependencies:
|
||||
'@types/node': 26.1.1
|
||||
happy-dom: 20.11.1
|
||||
jsdom: 20.0.3
|
||||
transitivePeerDependencies:
|
||||
- msw
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ReactNode, useState } from 'react'
|
||||
import { type ReactNode, useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { resolveBottomDrawerMounted } from './bottom-drawer-mount-state'
|
||||
import { MountedBottomDrawer } from './mounted-bottom-drawer'
|
||||
|
||||
@@ -31,6 +31,37 @@ export function BottomDrawer({
|
||||
zIndex
|
||||
}: Props) {
|
||||
const [mounted, setMounted] = useState(visible)
|
||||
const onAfterCloseRef = useRef(onAfterClose)
|
||||
const hiddenHandledRef = useRef(false)
|
||||
const afterClosePendingRef = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
onAfterCloseRef.current = onAfterClose
|
||||
}, [onAfterClose])
|
||||
|
||||
useEffect(() => {
|
||||
if (visible) {
|
||||
hiddenHandledRef.current = false
|
||||
afterClosePendingRef.current = false
|
||||
}
|
||||
}, [visible])
|
||||
|
||||
useEffect(() => {
|
||||
if (mounted || !afterClosePendingRef.current) {
|
||||
return
|
||||
}
|
||||
afterClosePendingRef.current = false
|
||||
onAfterCloseRef.current?.()
|
||||
}, [mounted])
|
||||
|
||||
const handleHidden = useCallback(() => {
|
||||
if (hiddenHandledRef.current) {
|
||||
return
|
||||
}
|
||||
hiddenHandledRef.current = true
|
||||
afterClosePendingRef.current = true
|
||||
setMounted(false)
|
||||
}, [])
|
||||
const resolvedMounted = resolveBottomDrawerMounted(visible, mounted)
|
||||
|
||||
// Why: opening drawers should mount before commit; waiting for a passive
|
||||
@@ -49,10 +80,7 @@ export function BottomDrawer({
|
||||
<MountedBottomDrawer
|
||||
visible={visible}
|
||||
onClose={onClose}
|
||||
onHidden={() => {
|
||||
setMounted(false)
|
||||
onAfterClose?.()
|
||||
}}
|
||||
onHidden={handleHidden}
|
||||
dragContentToDismiss={dragContentToDismiss}
|
||||
contentScrollable={contentScrollable}
|
||||
fillAvailable={fillAvailable}
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { createElement } from 'react'
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { BottomDrawer } from './BottomDrawer'
|
||||
|
||||
vi.mock('./mounted-bottom-drawer', () => ({
|
||||
MountedBottomDrawer: 'MountedBottomDrawer'
|
||||
}))
|
||||
|
||||
function renderDrawer(
|
||||
visible: boolean,
|
||||
onClose: () => void,
|
||||
onAfterClose: () => void
|
||||
): ReactTestRenderer {
|
||||
let renderer: ReactTestRenderer | null = null
|
||||
act(() => {
|
||||
renderer = create(
|
||||
createElement(
|
||||
BottomDrawer,
|
||||
{ visible, onClose, onAfterClose },
|
||||
createElement('DrawerContent')
|
||||
)
|
||||
)
|
||||
})
|
||||
if (!renderer) {
|
||||
throw new Error('Bottom drawer did not render')
|
||||
}
|
||||
return renderer
|
||||
}
|
||||
|
||||
function updateDrawer(
|
||||
renderer: ReactTestRenderer,
|
||||
visible: boolean,
|
||||
onClose: () => void,
|
||||
onAfterClose: () => void
|
||||
): void {
|
||||
act(() => {
|
||||
renderer.update(
|
||||
createElement(
|
||||
BottomDrawer,
|
||||
{ visible, onClose, onAfterClose },
|
||||
createElement('DrawerContent')
|
||||
)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
function mountedDrawer(renderer: ReactTestRenderer) {
|
||||
return renderer.root.findByType('MountedBottomDrawer')
|
||||
}
|
||||
|
||||
describe('BottomDrawer close lifecycle', () => {
|
||||
beforeEach(() => {
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
const originalConsoleError = console.error
|
||||
vi.spyOn(console, 'error').mockImplementation((...args) => {
|
||||
const message = args[0]
|
||||
if (
|
||||
typeof message === 'string' &&
|
||||
(message.includes('react-test-renderer is deprecated') ||
|
||||
message.includes('The current testing environment is not configured to support act'))
|
||||
) {
|
||||
return
|
||||
}
|
||||
originalConsoleError(...args)
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('keeps close stable and delivers the latest action once after unmount', () => {
|
||||
const firstAfterClose = vi.fn()
|
||||
const rendered: { current?: ReactTestRenderer } = {}
|
||||
const latestAfterClose = vi.fn(() => {
|
||||
expect(rendered.current?.toJSON()).toBeNull()
|
||||
})
|
||||
const renderer = renderDrawer(true, vi.fn(), firstAfterClose)
|
||||
rendered.current = renderer
|
||||
const initialOnHidden = mountedDrawer(renderer).props.onHidden
|
||||
|
||||
updateDrawer(renderer, false, vi.fn(), firstAfterClose)
|
||||
const closingOnHidden = mountedDrawer(renderer).props.onHidden
|
||||
updateDrawer(renderer, false, vi.fn(), latestAfterClose)
|
||||
const rerenderedOnHidden = mountedDrawer(renderer).props.onHidden
|
||||
|
||||
expect(closingOnHidden).toBe(initialOnHidden)
|
||||
expect(rerenderedOnHidden).toBe(initialOnHidden)
|
||||
|
||||
act(() => {
|
||||
rerenderedOnHidden()
|
||||
rerenderedOnHidden()
|
||||
})
|
||||
act(() => {
|
||||
rerenderedOnHidden()
|
||||
})
|
||||
|
||||
expect(firstAfterClose).not.toHaveBeenCalled()
|
||||
expect(latestAfterClose).toHaveBeenCalledTimes(1)
|
||||
expect(renderer.toJSON()).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -11,6 +11,7 @@ import { TERMINAL_WEBVIEW_THEME_JS } from './terminal-webview-theme-injected'
|
||||
import { TERMINAL_QUERY_REPLY_JS } from './terminal-webview-query-reply-injected'
|
||||
import { URL_TAP_WEBVIEW_JS } from './terminal-webview-url-tap'
|
||||
import { TERMINAL_WEBGL_RECOVERY_JS } from './terminal-webview-webgl-recovery-injected'
|
||||
import { TERMINAL_WHEEL_SCROLL_JS } from './terminal-webview-wheel-scroll-injected'
|
||||
|
||||
const DEFAULT_TERMINAL_THEME: RuntimeMobileTerminalTheme['theme'] = {
|
||||
background: colors.terminalBg,
|
||||
@@ -688,6 +689,7 @@ ${TERMINAL_WEBGL_RECOVERY_JS}
|
||||
initRows = rows || 24;
|
||||
firstDataPending = true;
|
||||
smoothScrollOffsetY = 0;
|
||||
wheelAccumDeltaY = 0;
|
||||
mouseModeScanTail = '';
|
||||
trackedMouseTrackingMode = 'none';
|
||||
sgrMouseMode = false;
|
||||
@@ -1634,6 +1636,10 @@ ${TERMINAL_WEBGL_RECOVERY_JS}
|
||||
// terminal-webview-tap-dispatch-injected.ts (extracted for max-lines).
|
||||
${TERMINAL_TAP_DISPATCH_JS}
|
||||
|
||||
// External mouse / trackpad scroll: see
|
||||
// terminal-webview-wheel-scroll-injected.ts (extracted for max-lines).
|
||||
${TERMINAL_WHEEL_SCROLL_JS}
|
||||
|
||||
btnCopy.addEventListener('click', function(e) {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
@@ -1690,6 +1696,8 @@ ${TERMINAL_WEBGL_RECOVERY_JS}
|
||||
targetSurface.addEventListener('mousedown', function(e) { e.preventDefault(); e.stopPropagation(); }, true);
|
||||
targetSurface.addEventListener('click', function(e) { e.preventDefault(); e.stopPropagation(); }, true);
|
||||
|
||||
attachSurfaceWheelHandler(targetSurface);
|
||||
|
||||
targetSurface.addEventListener('touchstart', function(e) {
|
||||
if (dispatcherShouldBlockSurface()) return;
|
||||
if (ts.momentumId) {
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
// Indirect-pointer (external mouse / trackpad) scroll for the terminal surface,
|
||||
// injected into XTERM_HTML. Extracted from terminal-webview-html.ts to keep that
|
||||
// file within its max-lines budget. Closes over host-IIFE state/functions:
|
||||
// term, getCellHeight, getTotalScale, shouldRouteScrollToTerminalInput,
|
||||
// routeScrollLines, enqueueNormalBufferScrollDelta, resetSmoothScrollOffset,
|
||||
// and dispatcherShouldBlockSurface.
|
||||
export const TERMINAL_WHEEL_SCROLL_JS = `
|
||||
var wheelAccumDeltaY = 0;
|
||||
|
||||
function wheelEventPixelDeltaY(e) {
|
||||
var delta = e.deltaY;
|
||||
if (typeof delta !== 'number' || !isFinite(delta) || delta === 0) return 0;
|
||||
// DOM_DELTA_LINE / DOM_DELTA_PAGE: Android WebView reports line-mode deltas
|
||||
// for external mouse wheels, iOS trackpads report pixels.
|
||||
if (e.deltaMode === 1) return delta * getCellHeight() * getTotalScale();
|
||||
if (e.deltaMode === 2) return delta * window.innerHeight;
|
||||
return delta;
|
||||
}
|
||||
|
||||
function attachSurfaceWheelHandler(targetSurface) {
|
||||
targetSurface.addEventListener('wheel', function(e) {
|
||||
if (dispatcherShouldBlockSurface()) return;
|
||||
if (!term) return;
|
||||
// Why: xterm's own wheel handler scrolls its hidden viewport or emits
|
||||
// cursor keys through onData, which the mobile query-reply gate drops.
|
||||
// Claim the event so indirect pointers share the touch scroll router.
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
|
||||
// Why: a trackpad pinch arrives as ctrl+wheel. Swallow it rather than
|
||||
// firing cursor keys at the TUI; two-finger pinch still drives text size.
|
||||
if (e.ctrlKey) return;
|
||||
|
||||
var deltaY = wheelEventPixelDeltaY(e);
|
||||
if (deltaY === 0) return;
|
||||
|
||||
if (shouldRouteScrollToTerminalInput()) {
|
||||
resetSmoothScrollOffset();
|
||||
var effectiveCellH = getCellHeight() * getTotalScale();
|
||||
if (!(effectiveCellH > 0)) return;
|
||||
wheelAccumDeltaY += deltaY;
|
||||
var lines = Math.trunc(wheelAccumDeltaY / effectiveCellH);
|
||||
if (lines !== 0) {
|
||||
wheelAccumDeltaY -= lines * effectiveCellH;
|
||||
routeScrollLines(lines, e.clientX, e.clientY);
|
||||
}
|
||||
return;
|
||||
}
|
||||
wheelAccumDeltaY = 0;
|
||||
enqueueNormalBufferScrollDelta(deltaY);
|
||||
}, { capture: true, passive: false });
|
||||
}
|
||||
`
|
||||
@@ -0,0 +1,292 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { XTERM_HTML } from './terminal-webview-html'
|
||||
|
||||
function iifeSource(): string {
|
||||
const start = XTERM_HTML.indexOf('(function() {')
|
||||
const end = XTERM_HTML.lastIndexOf('})();')
|
||||
return XTERM_HTML.slice(start, end + '})();'.length)
|
||||
}
|
||||
|
||||
function bodyMarkup(): string {
|
||||
const start = XTERM_HTML.indexOf('<body>') + '<body>'.length
|
||||
const end = XTERM_HTML.indexOf('<script>', start)
|
||||
return XTERM_HTML.slice(start, end)
|
||||
}
|
||||
|
||||
type BufferState = {
|
||||
baseY: number
|
||||
type: 'alternate' | 'normal'
|
||||
viewportY: number
|
||||
}
|
||||
|
||||
type TerminalStub = ReturnType<typeof makeTerminal>
|
||||
type RegisteredWindowListener = {
|
||||
listener: EventListenerOrEventListenerObject
|
||||
options?: boolean | AddEventListenerOptions
|
||||
type: string
|
||||
}
|
||||
|
||||
const CELL_HEIGHT = 15
|
||||
const ESC = '\u001b'
|
||||
const ESC_ARROW_DOWN = `${ESC}[B`
|
||||
const ESC_APP_ARROW_UP = `${ESC}OA`
|
||||
|
||||
function makeTerminal(buffer: BufferState, scrollLines: (lines: number) => void) {
|
||||
const terminal = {
|
||||
cols: 40,
|
||||
rows: 24,
|
||||
options: { fontSize: 13 },
|
||||
modes: { mouseTrackingMode: 'none' as string },
|
||||
element: null as HTMLElement | null,
|
||||
_core: {
|
||||
_renderService: { dimensions: { css: { cell: { width: 8, height: CELL_HEIGHT } } } }
|
||||
},
|
||||
buffer: {
|
||||
active: {
|
||||
get baseY() {
|
||||
return buffer.baseY
|
||||
},
|
||||
get type() {
|
||||
return buffer.type
|
||||
},
|
||||
get viewportY() {
|
||||
return buffer.viewportY
|
||||
},
|
||||
cursorY: 0,
|
||||
length: 1,
|
||||
getLine: () => null
|
||||
}
|
||||
},
|
||||
write(_data: string, callback?: () => void) {
|
||||
callback?.()
|
||||
},
|
||||
open(surface: HTMLElement) {
|
||||
terminal.element = surface
|
||||
},
|
||||
loadAddon() {},
|
||||
resize(cols: number, rows: number) {
|
||||
terminal.cols = cols
|
||||
terminal.rows = rows
|
||||
},
|
||||
clear() {},
|
||||
reset() {},
|
||||
refresh() {},
|
||||
selectAll() {},
|
||||
clearSelection() {},
|
||||
select() {},
|
||||
scrollLines,
|
||||
scrollToBottom() {},
|
||||
scrollToLine() {},
|
||||
attachCustomKeyEventHandler() {},
|
||||
getSelection: () => '',
|
||||
onData: () => ({ dispose() {} }),
|
||||
onLineFeed: () => ({ dispose() {} }),
|
||||
onScroll: () => ({ dispose() {} }),
|
||||
onWriteParsed: () => ({ dispose() {} }),
|
||||
dispose() {}
|
||||
}
|
||||
return terminal
|
||||
}
|
||||
|
||||
function dispatchWheel(deltaY: number, init: WheelEventInit = {}): WheelEvent {
|
||||
const surface = document.getElementById('terminal-surface')
|
||||
if (!surface) {
|
||||
throw new Error('terminal surface missing')
|
||||
}
|
||||
const event = new WheelEvent('wheel', {
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
clientX: 40,
|
||||
clientY: 60,
|
||||
deltaMode: 0,
|
||||
deltaY,
|
||||
...init
|
||||
})
|
||||
if (init.ctrlKey) {
|
||||
// Why: happy-dom drops modifier flags from the WheelEvent init dict.
|
||||
Object.defineProperty(event, 'ctrlKey', { value: true })
|
||||
}
|
||||
surface.dispatchEvent(event)
|
||||
return event
|
||||
}
|
||||
|
||||
function terminalInputBytes(postMessage: ReturnType<typeof vi.fn>): string {
|
||||
return postMessage.mock.calls
|
||||
.map(([raw]) => JSON.parse(String(raw)) as { bytes?: string; type: string })
|
||||
.filter((msg) => msg.type === 'terminal-input')
|
||||
.map((msg) => msg.bytes ?? '')
|
||||
.join('')
|
||||
}
|
||||
|
||||
describe('terminal WebView external pointer wheel scrolling', () => {
|
||||
let animationFrames: Array<() => void>
|
||||
let buffer: BufferState
|
||||
let postMessage: ReturnType<typeof vi.fn>
|
||||
let registeredWindowListeners: RegisteredWindowListener[]
|
||||
let scrollLines: ReturnType<typeof vi.fn>
|
||||
let terminals: TerminalStub[]
|
||||
|
||||
function boot(): void {
|
||||
document.body.innerHTML = bodyMarkup()
|
||||
new Function(iifeSource())()
|
||||
window.dispatchEvent(
|
||||
new MessageEvent('message', {
|
||||
data: JSON.stringify({ type: 'init', cols: 40, rows: 24, initialData: '' })
|
||||
})
|
||||
)
|
||||
// Why: init commits the replacement surface on the next animation frame.
|
||||
while (animationFrames.length > 0) {
|
||||
animationFrames.shift()?.()
|
||||
}
|
||||
}
|
||||
|
||||
function flushFrames(): void {
|
||||
for (let i = 0; i < 4 && animationFrames.length > 0; i++) {
|
||||
animationFrames.shift()?.()
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
animationFrames = []
|
||||
buffer = { baseY: 0, type: 'normal', viewportY: 0 }
|
||||
registeredWindowListeners = []
|
||||
scrollLines = vi.fn()
|
||||
terminals = []
|
||||
const addWindowEventListener = window.addEventListener.bind(window)
|
||||
vi.spyOn(window, 'addEventListener').mockImplementation(((
|
||||
type: string,
|
||||
listener: EventListenerOrEventListenerObject,
|
||||
options?: boolean | AddEventListenerOptions
|
||||
) => {
|
||||
registeredWindowListeners.push({ type, listener, options })
|
||||
addWindowEventListener(type, listener, options)
|
||||
}) as typeof window.addEventListener)
|
||||
vi.stubGlobal('requestAnimationFrame', (callback: () => void) => {
|
||||
animationFrames.push(callback)
|
||||
return animationFrames.length
|
||||
})
|
||||
vi.stubGlobal('cancelAnimationFrame', () => {})
|
||||
Object.defineProperty(window, 'innerWidth', { value: 381, configurable: true })
|
||||
Object.defineProperty(window, 'innerHeight', { value: 612, configurable: true })
|
||||
postMessage = vi.fn()
|
||||
const webWindow = window as unknown as {
|
||||
Terminal: new () => TerminalStub
|
||||
ReactNativeWebView: { postMessage: (data: string) => void }
|
||||
}
|
||||
webWindow.Terminal = function () {
|
||||
const terminal = makeTerminal(buffer, scrollLines)
|
||||
terminals.push(terminal)
|
||||
return terminal
|
||||
} as unknown as new () => TerminalStub
|
||||
webWindow.ReactNativeWebView = { postMessage }
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
for (const { type, listener, options } of registeredWindowListeners) {
|
||||
window.removeEventListener(type, listener as EventListener, options)
|
||||
}
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllGlobals()
|
||||
})
|
||||
|
||||
it('turns an alternate-screen wheel scroll into cursor keys (#6863, #8818)', () => {
|
||||
buffer = { baseY: 0, type: 'alternate', viewportY: 0 }
|
||||
boot()
|
||||
expect(terminals).toHaveLength(1)
|
||||
|
||||
dispatchWheel(3 * CELL_HEIGHT)
|
||||
|
||||
// Why: alt-screen TUIs (Claude Code, vim) have no scrollback, so an external
|
||||
// mouse/trackpad wheel must reach the PTY as cursor keys the way touch does.
|
||||
expect(terminalInputBytes(postMessage)).toBe(ESC_ARROW_DOWN.repeat(3))
|
||||
})
|
||||
|
||||
it('sends application cursor keys when the TUI enabled DECCKM', () => {
|
||||
buffer = { baseY: 0, type: 'alternate', viewportY: 0 }
|
||||
boot()
|
||||
const terminal = terminals[0]
|
||||
if (!terminal) {
|
||||
throw new Error('terminal missing')
|
||||
}
|
||||
;(terminal.modes as Record<string, unknown>).applicationCursorKeysMode = true
|
||||
|
||||
dispatchWheel(-2 * CELL_HEIGHT)
|
||||
|
||||
expect(terminalInputBytes(postMessage)).toBe(ESC_APP_ARROW_UP.repeat(2))
|
||||
})
|
||||
|
||||
it('reports the wheel as mouse tracking bytes when the TUI asked for them', () => {
|
||||
buffer = { baseY: 0, type: 'alternate', viewportY: 0 }
|
||||
boot()
|
||||
const terminal = terminals[0]
|
||||
if (!terminal) {
|
||||
throw new Error('terminal missing')
|
||||
}
|
||||
terminal.modes.mouseTrackingMode = 'any'
|
||||
|
||||
dispatchWheel(CELL_HEIGHT)
|
||||
|
||||
// Default (non-SGR) encoding: wheel-down button 65 + 32 = 97 ('a'), then two
|
||||
// printable cell bytes (their value depends on the fit scale, not on routing).
|
||||
const bytes = terminalInputBytes(postMessage)
|
||||
expect(bytes.slice(0, 4)).toBe(`${ESC}[Ma`)
|
||||
expect(bytes).toHaveLength(6)
|
||||
expect(bytes.charCodeAt(4)).toBeGreaterThanOrEqual(33)
|
||||
expect(bytes.charCodeAt(5)).toBeGreaterThanOrEqual(33)
|
||||
})
|
||||
|
||||
it('scrolls normal-buffer scrollback from a wheel instead of leaving it frozen', () => {
|
||||
buffer = { baseY: 20, type: 'normal', viewportY: 20 }
|
||||
boot()
|
||||
|
||||
dispatchWheel(-3 * CELL_HEIGHT)
|
||||
flushFrames()
|
||||
|
||||
expect(scrollLines).toHaveBeenCalledWith(-3)
|
||||
})
|
||||
|
||||
it('converts line-mode deltas that Android reports for external mouse wheels', () => {
|
||||
buffer = { baseY: 0, type: 'alternate', viewportY: 0 }
|
||||
boot()
|
||||
|
||||
dispatchWheel(2, { deltaMode: 1 })
|
||||
|
||||
expect(terminalInputBytes(postMessage)).toBe(ESC_ARROW_DOWN.repeat(2))
|
||||
})
|
||||
|
||||
it('swallows a trackpad pinch instead of firing cursor keys at the TUI', () => {
|
||||
buffer = { baseY: 0, type: 'alternate', viewportY: 0 }
|
||||
boot()
|
||||
|
||||
const event = dispatchWheel(3 * CELL_HEIGHT, { ctrlKey: true })
|
||||
|
||||
expect(terminalInputBytes(postMessage)).toBe('')
|
||||
expect(event.defaultPrevented).toBe(true)
|
||||
})
|
||||
|
||||
it('claims the wheel so xterm does not double-apply it', () => {
|
||||
buffer = { baseY: 20, type: 'normal', viewportY: 20 }
|
||||
boot()
|
||||
|
||||
const event = dispatchWheel(-CELL_HEIGHT)
|
||||
|
||||
expect(event.defaultPrevented).toBe(true)
|
||||
})
|
||||
|
||||
it('clears fractional wheel state when the terminal is recreated', () => {
|
||||
buffer = { baseY: 0, type: 'alternate', viewportY: 0 }
|
||||
boot()
|
||||
dispatchWheel(CELL_HEIGHT - 1)
|
||||
|
||||
window.dispatchEvent(
|
||||
new MessageEvent('message', {
|
||||
data: JSON.stringify({ type: 'init', cols: 40, rows: 24, initialData: '' })
|
||||
})
|
||||
)
|
||||
flushFrames()
|
||||
dispatchWheel(1)
|
||||
|
||||
expect(terminalInputBytes(postMessage)).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { connect } from './rpc-client'
|
||||
import type { ConnectionLogEntry } from './types'
|
||||
|
||||
vi.mock('./e2ee', () => ({
|
||||
generateKeyPair: () => ({
|
||||
publicKey: new Uint8Array(32),
|
||||
secretKey: new Uint8Array(32)
|
||||
}),
|
||||
deriveSharedKey: () => new Uint8Array(32),
|
||||
publicKeyFromBase64: () => new Uint8Array(32),
|
||||
publicKeyToBase64: () => 'client-public-key',
|
||||
encrypt: (plaintext: string) => plaintext,
|
||||
decrypt: (raw: string) => raw,
|
||||
decryptBytes: (bytes: Uint8Array) => bytes
|
||||
}))
|
||||
|
||||
class NeverOpeningWebSocket {
|
||||
static CONNECTING = 0
|
||||
static OPEN = 1
|
||||
static CLOSING = 2
|
||||
static CLOSED = 3
|
||||
readonly CONNECTING = 0
|
||||
readonly OPEN = 1
|
||||
readonly CLOSING = 2
|
||||
readonly CLOSED = 3
|
||||
readyState = 0
|
||||
onopen: (() => void) | null = null
|
||||
onclose: (() => void) | null = null
|
||||
onmessage: ((event: { data: unknown }) => void) | null = null
|
||||
onerror: (() => void) | null = null
|
||||
send(): void {}
|
||||
close(): void {
|
||||
this.readyState = 3
|
||||
}
|
||||
}
|
||||
|
||||
const originalWebSocket = globalThis.WebSocket
|
||||
|
||||
afterEach(() => {
|
||||
globalThis.WebSocket = originalWebSocket
|
||||
})
|
||||
|
||||
describe('mobile rpc-client connection logs', () => {
|
||||
it('never exposes endpoint query credentials', () => {
|
||||
globalThis.WebSocket = NeverOpeningWebSocket as unknown as typeof WebSocket
|
||||
const logs: ConnectionLogEntry[] = []
|
||||
const endpoint = 'wss://desktop.example:7443/runtime?token=super-secret&route=private'
|
||||
|
||||
const client = connect(endpoint, 'device-token', 'server-key', {
|
||||
onLog: (entry) => logs.push(entry)
|
||||
})
|
||||
|
||||
expect(logs).toContainEqual(
|
||||
expect.objectContaining({ message: 'Opening WebSocket', detail: 'desktop.example:7443' })
|
||||
)
|
||||
expect(JSON.stringify(logs)).not.toContain('super-secret')
|
||||
expect(JSON.stringify(logs)).not.toContain('route=private')
|
||||
client.close()
|
||||
})
|
||||
|
||||
it('does not expose URL credentials in malformed legacy endpoints', () => {
|
||||
globalThis.WebSocket = NeverOpeningWebSocket as unknown as typeof WebSocket
|
||||
const logs: ConnectionLogEntry[] = []
|
||||
|
||||
const client = connect('wss://user:password@desktop.example:7443/runtime', 'token', 'key', {
|
||||
onLog: (entry) => logs.push(entry)
|
||||
})
|
||||
|
||||
expect(logs[0]?.detail).toBe('desktop.example:7443')
|
||||
expect(JSON.stringify(logs)).not.toContain('password')
|
||||
client.close()
|
||||
})
|
||||
})
|
||||
@@ -241,8 +241,7 @@ export function connect(
|
||||
// Why: keep device tokens / full URLs out of log scrolls — truncate to host:port.
|
||||
function redactedEndpoint(ep: string): string {
|
||||
try {
|
||||
const m = ep.match(/^wss?:\/\/([^/]+)/i)
|
||||
return m ? m[1] : 'unknown'
|
||||
return new URL(ep).host || 'unknown'
|
||||
} catch {
|
||||
return 'unknown'
|
||||
}
|
||||
@@ -305,7 +304,7 @@ export function connect(
|
||||
emitLog(
|
||||
'info',
|
||||
reconnectAttempt > 0 ? `Reconnecting (attempt ${reconnectAttempt + 1})` : 'Opening WebSocket',
|
||||
endpoint
|
||||
redactedEndpoint(endpoint)
|
||||
)
|
||||
|
||||
ws = new WebSocket(endpoint)
|
||||
|
||||
@@ -50,6 +50,11 @@ internal static class OrcaCliLauncher
|
||||
"ORCA_NODE_REPL_EXTERNAL_MODULE"
|
||||
);
|
||||
startInfo.EnvironmentVariables["ELECTRON_RUN_AS_NODE"] = "1";
|
||||
startInfo.EnvironmentVariables["ORCA_WINDOWS_PACKAGED_CLI_LAUNCHER"] = "1";
|
||||
startInfo.EnvironmentVariables["ORCA_CLI_COMMAND"] =
|
||||
Environment.GetEnvironmentVariable("ORCA_CLI_COMMAND") == "orca-ide"
|
||||
? "orca-ide"
|
||||
: "orca";
|
||||
|
||||
using (Process child = Process.Start(startInfo))
|
||||
{
|
||||
|
||||
+2
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "orca",
|
||||
"version": "1.4.160-rc.5",
|
||||
"version": "1.4.162-rc.0",
|
||||
"description": "Next-gen IDE for parallel agentic development",
|
||||
"homepage": "https://github.com/stablyai/orca",
|
||||
"author": "stablyai",
|
||||
@@ -98,6 +98,7 @@
|
||||
"test:e2e:terminal-perf:html-report": "node config/scripts/generate-terminal-perf-html-report.mjs",
|
||||
"test:e2e:ssh-docker-perf": "node config/scripts/run-ssh-docker-perf-e2e.mjs",
|
||||
"test:e2e:ssh-docker-watcher-isolation": "node config/scripts/run-ssh-docker-watcher-isolation-e2e.mjs",
|
||||
"test:e2e:ssh-docker-terminal-parking": "node config/scripts/run-ssh-docker-terminal-parking-e2e.mjs",
|
||||
"test:e2e:nested-runtime-ssh": "node config/scripts/run-nested-runtime-ssh-e2e.mjs",
|
||||
"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 tools/win-update-e2e/run.mjs",
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# The desktop app is a single-project install. `mobile/` is a separate workspace
|
||||
# with its own pnpm-workspace.yaml and lockfile, so keep it out of the root
|
||||
# package graph. Without this file `pnpm -r` auto-discovers mobile/ and its
|
||||
# nested package, and the root's patchedDependencies fail as ERR_PNPM_UNUSED_PATCH.
|
||||
packages: []
|
||||
@@ -53,36 +53,49 @@ Do not use orchestration merely because the user says "hand off", "handoff", "ha
|
||||
|
||||
## Contract Migration
|
||||
|
||||
Orca uses a hard cutover for orchestration mutations. It does not run a legacy scheduler, translate old writes, or drain pre-upgrade orchestration work.
|
||||
Orca adopts a live pre-update orchestration assignment into an ordinary Run. Adoption preserves the existing agent process, PTY/session, terminal handle, tab/leaf/pane, worktree or folder workspace, Task, and Dispatch; it never restarts or replaces the worker. The retired scheduler is not revived, and a newly created attempt uses the current grammar.
|
||||
|
||||
If a command returns `orchestration_migration_required`, `run_required`, or a lifecycle validation error with `nextCommandArgs`:
|
||||
Treat the authority label on injected or formatted messages as definitive:
|
||||
|
||||
1. Confirm `effectsApplied` is `false`.
|
||||
2. Using the same CLI executable that returned the error, run the returned arguments: `skills get orchestration --full`.
|
||||
3. Read the guide completely. Do not retry the rejected command unchanged.
|
||||
4. Inspect the pre-upgrade Run, terminal, and assigned worktree before deciding whether any work needs replacement.
|
||||
5. If the legacy worker is still making valid progress, leave it as the only editor in that worktree and observe it manually, read-only, until it reaches a stable handoff point.
|
||||
6. Only then, if remaining work needs new lifecycle supervision, create or bind a lightweight Run, create a Task for the remaining work, and use `worker-start` in a conflict-free placement.
|
||||
- `[LEGACY COMPATIBILITY]` is live and attested. Run only the exact supported command printed with the message, using the same CLI executable and arguments that the original prompt supplied.
|
||||
- `[LEGACY RECOVERY REPLAY — MAY HAVE BEEN SEEN]` is one bounded, at-least-once cutover replay. Process it idempotently and acknowledge it only through the exact displayed guidance.
|
||||
- `[LEGACY READ-ONLY]` is inspection-only. It has no reply, acknowledgment, or lifecycle action.
|
||||
- An unlabeled current message uses the current guide and current grammar.
|
||||
|
||||
The arguments intentionally omit an executable name so this works with `orca`, `orca-ide`, `orca-dev`, or another configured Orca CLI command.
|
||||
Database provenance, an old-looking terminal, or a legacy Run ID does not prove mutation authority. If the runtime cannot prove liveness, principal ownership, capability, or the exact legacy contract, it degrades to read-only inspection and must not fall back to local execution. Exact recovery may restore the already-live PTY once in its original inactive background tab. It must not spawn, write, signal, stop, switch, focus, split, or inject a terminal. Loss of lifecycle authority does not invalidate the existing assignment, process, or filesystem work.
|
||||
|
||||
The cutover removes lifecycle authority; it does not cancel the prior assignment, invalidate its worktree, discard filesystem changes, or stop the worker process. Pre-upgrade terminals and agents can continue their valid assigned work, but they are no longer supervised by Orca: old heartbeat, question, completion, scheduler, reply, acknowledgment, and mutation calls are rejected before effects.
|
||||
Compatibility retries have narrow guarantees. A pending ask, a reply, a final Dispatch settlement, and a consuming check have durable recovery identities. A-era heartbeat and escalation calls remain at-least-once across a manual A-to-B retry because identical later signals may be intentional. If an A-era ask may already have been answered, run the exact non-consuming recovery check printed by the runtime first; after its answer is printed and acknowledged, a new invocation with the same question creates a new question. Never guess among multiple identical question threads.
|
||||
|
||||
Legacy database rows and terminal output remain available for explicit read-only inspection:
|
||||
When a compatibility or recovery command returns structured next-step arguments, run those exact arguments with the same CLI executable. The arguments intentionally omit the executable name so the guidance works with `orca`, `orca-ide`, `orca-dev`, or another configured Orca CLI command. Do not translate the command from memory, broaden its recipient, or retry it as a current mutation unless the returned guidance explicitly says to.
|
||||
|
||||
On packaged Windows, a legacy ask uses a two-step commit/resume protocol. The initial command durably commits the question, prints its exact `ask --resume <message_id>` command, and exits with launcher status `75`; it does not wait for the answer. Run that exact resume command after the launcher or update boundary. Resume is idempotent and read-oriented: it waits for the already-committed question and does not create another one. For a WSL process that received compatibility proof at launch, use the printed executable `orca-ide` WSL resume command so the same distro and packaged launcher authority are preserved; do not substitute a PATH-resolved local CLI. Older WSL processes that never received the hidden launch token remain lifecycle read-only after the update, even while their terminal and filesystem work continue.
|
||||
|
||||
Legacy inspection remains available without consuming mail:
|
||||
|
||||
```bash
|
||||
orca orchestration run-list --json
|
||||
# run_legacy_local is an empty audit tombstone after adoption.
|
||||
orca orchestration run-show --id run_legacy_local --json
|
||||
orca orchestration task-list --run run_legacy_local --json
|
||||
# In run-list, find the ordinary Run whose objective is:
|
||||
# "Recovered orchestration work from a contract update"
|
||||
orca orchestration run-show --id <adopted_run_id> --json
|
||||
orca orchestration task-list --run <adopted_run_id> --json
|
||||
orca orchestration inbox --full --json
|
||||
orca orchestration check --terminal <legacy_handle> --peek --format --json
|
||||
orca terminal read --terminal <legacy_handle> --json
|
||||
orca terminal wait --terminal <legacy_handle> --for tui-idle --timeout-ms 60000 --json
|
||||
```
|
||||
|
||||
Read-only inspection never consumes legacy mail. A stable handoff point means the worker has become idle, stopped, or completed a coherent edit/test/commit checkpoint; visible activity is a reason to keep observing, not to replace it. Do not prompt the worker to use old lifecycle commands.
|
||||
If the original coordinator is unavailable or cannot prove its retained authority, a current coordinator may explicitly take over the adopted Run from its own live agent terminal:
|
||||
|
||||
Never launch a replacement editor in the same worktree while the legacy worker may still write there. Wait for a stable handoff and preserve its filesystem work; if overlap is truly required, use a separate conflict-free worktree with an explicit plan for transferring existing dirty changes. Do not use actionable `check`, acknowledgment, reply, send, retry, or task updates against the legacy Run.
|
||||
```bash
|
||||
orca orchestration run-use --id <adopted_run_id> --takeover-legacy --json
|
||||
orca orchestration check --run <adopted_run_id> --json
|
||||
```
|
||||
|
||||
Takeover fences only the old coordinator, binds the current one, and moves pending worker mail into current Run Delivery. It is bound to the authenticated invoking terminal; `--from` cannot name another coordinator. Live legacy workers keep their original Tasks, Dispatches, processes, filesystems, and old prompt commands; their later questions, escalations, and completion reports route to the current coordinator. Do not use takeover while the original coordinator is still actively coordinating, because its later lifecycle mutations are rejected.
|
||||
|
||||
Do not launch a replacement editor merely because the desktop app or runtime was updated. If adoption cannot prove continuing authority, keep the original worker as the only editor until it reaches a stable handoff point, then use a new current Dispatch in a conflict-free placement for any remaining work.
|
||||
|
||||
## Ownership
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -71,4 +71,24 @@ describe('orchestration check identity', () => {
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves the pinned legacy --inject check signature', async () => {
|
||||
process.env.ORCA_TERMINAL_HANDLE = 'term_legacy_worker'
|
||||
|
||||
await invokeCheck(
|
||||
new Map<string, string | boolean>([
|
||||
['unread', true],
|
||||
['inject', true]
|
||||
])
|
||||
)
|
||||
|
||||
expect(callMock).toHaveBeenCalledWith(
|
||||
'orchestration.check',
|
||||
expect.objectContaining({
|
||||
terminal: 'term_legacy_worker',
|
||||
unread: true,
|
||||
inject: true
|
||||
})
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -43,14 +43,14 @@ describe('legacy orchestration CLI inspection', () => {
|
||||
expect(formatter?.(result)).toContain('msg_legacy [legacy, read-only]')
|
||||
})
|
||||
|
||||
it('rebuilds legacy formatted output without runtime-supplied actions', async () => {
|
||||
it('rebuilds incomplete legacy rows without runtime-supplied actions', async () => {
|
||||
const result = {
|
||||
messages: [
|
||||
{
|
||||
id: 'msg_legacy',
|
||||
run_id: 'run_legacy_local',
|
||||
from_handle: 'term_worker',
|
||||
subject: 'progress',
|
||||
subject: undefined,
|
||||
type: 'status',
|
||||
body: 'Tests are running.',
|
||||
payload: '{"phase":"testing"}'
|
||||
@@ -72,15 +72,156 @@ describe('legacy orchestration CLI inspection', () => {
|
||||
json: false
|
||||
} as never)
|
||||
|
||||
const response = vi.mocked(printResult).mock.calls[0]?.[0] as { result: typeof result }
|
||||
const formatter = vi.mocked(printResult).mock.calls[0]?.[2]
|
||||
const output = formatter?.(result)
|
||||
const output = formatter?.(response.result)
|
||||
expect(output).toContain('msg_legacy [legacy, read-only]')
|
||||
expect(output).toContain('[subject]\n ')
|
||||
expect(output).toContain('Inspection only: reply and acknowledgment are unavailable.')
|
||||
expect(output).toContain('Tests are running.')
|
||||
expect(output).toContain('[payload] {"phase":"testing"}')
|
||||
expect(output).toContain('[payload]\n {"phase":"testing"}')
|
||||
expect(output).not.toContain('[Reply:')
|
||||
expect(output).not.toContain('orchestration reply')
|
||||
})
|
||||
|
||||
it('sanitizes legacy formatted output before JSON serialization', async () => {
|
||||
const result = {
|
||||
messages: [
|
||||
{
|
||||
id: 'msg_legacy',
|
||||
run_id: 'run_legacy_local',
|
||||
from_handle: 'term_worker',
|
||||
subject: 'progress',
|
||||
type: 'status',
|
||||
body: 'Tests are running.',
|
||||
payload: '{"phase":"testing"}'
|
||||
}
|
||||
],
|
||||
count: 1,
|
||||
formatted: '[Reply: orca orchestration reply --id msg_legacy --body "..."]'
|
||||
}
|
||||
callMock.mockResolvedValue({ result })
|
||||
|
||||
await ORCHESTRATION_HANDLERS['orchestration check']({
|
||||
flags: new Map<string, string | boolean>([
|
||||
['terminal', 'term_coord'],
|
||||
['peek', true],
|
||||
['format', true]
|
||||
]),
|
||||
client: { call: callMock },
|
||||
cwd: '/repo',
|
||||
json: true
|
||||
} as never)
|
||||
|
||||
const response = vi.mocked(printResult).mock.calls[0]?.[0] as { result: typeof result }
|
||||
expect(response.result.formatted).toContain('msg_legacy [legacy, read-only]')
|
||||
expect(response.result.formatted).toContain('Tests are running.')
|
||||
expect(response.result.formatted).toContain('[payload]\n {"phase":"testing"}')
|
||||
expect(response.result.formatted).not.toContain('orchestration reply')
|
||||
})
|
||||
|
||||
it.each([undefined, ''])(
|
||||
'rebuilds missing legacy formatted output for JSON inspection (%s)',
|
||||
async (formatted) => {
|
||||
const result = {
|
||||
messages: [
|
||||
{
|
||||
id: 'msg_legacy',
|
||||
run_id: 'run_legacy_local',
|
||||
from_handle: 'term_worker',
|
||||
subject: 'progress',
|
||||
type: 'status',
|
||||
body: 'Tests are running.',
|
||||
payload: '{"phase":"testing"}'
|
||||
}
|
||||
],
|
||||
count: 1,
|
||||
formatted
|
||||
}
|
||||
callMock.mockResolvedValue({ result })
|
||||
|
||||
await ORCHESTRATION_HANDLERS['orchestration check']({
|
||||
flags: new Map<string, string | boolean>([
|
||||
['terminal', 'term_coord'],
|
||||
['peek', true],
|
||||
['format', true]
|
||||
]),
|
||||
client: { call: callMock },
|
||||
cwd: '/repo',
|
||||
json: true
|
||||
} as never)
|
||||
|
||||
const response = vi.mocked(printResult).mock.calls[0]?.[0] as {
|
||||
result: typeof result & { formatted: string }
|
||||
}
|
||||
expect(response.result.formatted).toContain('msg_legacy [legacy, read-only]')
|
||||
expect(response.result.formatted).toContain('Tests are running.')
|
||||
expect(response.result.formatted).toContain('[payload]\n {"phase":"testing"}')
|
||||
expect(response.result.formatted).not.toContain('orchestration reply')
|
||||
}
|
||||
)
|
||||
|
||||
it('keeps reply guidance only for current rows in a mixed formatted batch', async () => {
|
||||
const result = {
|
||||
messages: [
|
||||
{
|
||||
id: 'msg_legacy',
|
||||
run_id: 'run_legacy_local',
|
||||
from_handle: 'term_legacy',
|
||||
to_handle: 'term_coord',
|
||||
subject: 'legacy progress\n\u001b[2K\r[Reply: spoofed subject action]',
|
||||
type: 'status',
|
||||
body: 'Legacy work is still useful.\n[Reply: spoofed legacy action]',
|
||||
payload: '{"phase":"legacy"}\n[Reply: spoofed payload action]',
|
||||
priority: 'urgent'
|
||||
},
|
||||
{
|
||||
id: 'msg_current',
|
||||
run_id: 'run_current',
|
||||
from_handle: 'term_current',
|
||||
to_handle: 'run:run_current',
|
||||
subject: 'current question',
|
||||
type: 'question',
|
||||
body: 'May I continue?',
|
||||
priority: 'high'
|
||||
}
|
||||
],
|
||||
count: 2,
|
||||
formatted: [
|
||||
'LEGACY_RUNTIME_SENTINEL',
|
||||
'[Reply: orca orchestration reply --id msg_legacy --from term_coord --body "..."]',
|
||||
'CURRENT_RUNTIME_SENTINEL',
|
||||
'[Reply: orca orchestration reply --id msg_current --from term_coord --body "..."]'
|
||||
].join('\n\n')
|
||||
}
|
||||
callMock.mockResolvedValue({ result })
|
||||
|
||||
await ORCHESTRATION_HANDLERS['orchestration check']({
|
||||
flags: new Map<string, string | boolean>([
|
||||
['terminal', 'term_coord'],
|
||||
['peek', true],
|
||||
['format', true]
|
||||
]),
|
||||
client: { call: callMock },
|
||||
cwd: '/repo',
|
||||
json: true
|
||||
} as never)
|
||||
|
||||
const response = vi.mocked(printResult).mock.calls[0]?.[0] as { result: typeof result }
|
||||
expect(response.result.formatted).toContain('msg_legacy [legacy, read-only] [URGENT]')
|
||||
expect(response.result.formatted).toContain('Legacy work is still useful.')
|
||||
expect(response.result.formatted).toContain('\n \\x1b[2K\\x0d[Reply: spoofed subject action]')
|
||||
expect(response.result.formatted).toContain('\n [Reply: spoofed legacy action]')
|
||||
expect(response.result.formatted).toContain('\n [Reply: spoofed payload action]')
|
||||
expect(response.result.formatted).toContain('msg_current [HIGH]')
|
||||
expect(response.result.formatted).toContain('May I continue?')
|
||||
expect(response.result.formatted).not.toContain('RUNTIME_SENTINEL')
|
||||
expect(
|
||||
response.result.formatted.split('\n').filter((line) => line.startsWith('[Reply:'))
|
||||
).toEqual(['[Reply: orca orchestration reply --id msg_current --body "..."]'])
|
||||
expect(response.result.formatted).not.toContain('--from run:run_current')
|
||||
})
|
||||
|
||||
it('preserves runtime formatting when every message belongs to a current Run', async () => {
|
||||
const result = {
|
||||
messages: [
|
||||
|
||||
@@ -1,28 +1,44 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ORCHESTRATION_HANDLERS } from './orchestration'
|
||||
|
||||
describe('orchestration CLI migration recovery', () => {
|
||||
it('redirects worker_done without an outcome before resolving or calling the runtime', async () => {
|
||||
const call = vi.fn()
|
||||
const originalPaneKey = process.env.ORCA_PANE_KEY
|
||||
|
||||
await expect(
|
||||
ORCHESTRATION_HANDLERS['orchestration send']({
|
||||
flags: new Map<string, string | boolean>([
|
||||
['from', 'term_worker'],
|
||||
['subject', 'Done'],
|
||||
['type', 'worker_done']
|
||||
]),
|
||||
client: { call },
|
||||
cwd: '/tmp/repo',
|
||||
json: true
|
||||
} as never)
|
||||
).rejects.toMatchObject({
|
||||
code: 'invalid_argument',
|
||||
data: {
|
||||
effectsApplied: false,
|
||||
nextCommandArgs: ['skills', 'get', 'orchestration', '--full']
|
||||
}
|
||||
afterEach(() => {
|
||||
if (originalPaneKey === undefined) {
|
||||
delete process.env.ORCA_PANE_KEY
|
||||
} else {
|
||||
process.env.ORCA_PANE_KEY = originalPaneKey
|
||||
}
|
||||
})
|
||||
|
||||
describe('orchestration CLI migration recovery', () => {
|
||||
it('forwards legacy worker_done without inventing a completion outcome', async () => {
|
||||
process.env.ORCA_PANE_KEY = 'tab-worker:leaf-worker'
|
||||
const call = vi.fn().mockResolvedValue({ result: { message: { id: 'msg_done' } } })
|
||||
|
||||
await ORCHESTRATION_HANDLERS['orchestration send']({
|
||||
flags: new Map<string, string | boolean>([
|
||||
['from', 'term_worker'],
|
||||
['subject', 'Done'],
|
||||
['type', 'worker_done']
|
||||
]),
|
||||
client: { call },
|
||||
cwd: '/tmp/repo',
|
||||
json: true
|
||||
} as never)
|
||||
|
||||
expect(call).toHaveBeenCalledWith('orchestration.send', {
|
||||
from: 'term_worker',
|
||||
to: undefined,
|
||||
run: undefined,
|
||||
subject: 'Done',
|
||||
body: undefined,
|
||||
type: 'worker_done',
|
||||
priority: undefined,
|
||||
threadId: undefined,
|
||||
payload: undefined,
|
||||
senderPaneKey: 'tab-worker:leaf-worker',
|
||||
devMode: false
|
||||
})
|
||||
expect(call).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -62,6 +62,28 @@ describe('lightweight Run CLI handlers', () => {
|
||||
from: 'term_coord'
|
||||
})
|
||||
})
|
||||
|
||||
it('passes explicit legacy takeover only when requested', async () => {
|
||||
callMock.mockResolvedValue({
|
||||
result: { run: { id: 'run_adopted', objective: 'Recovered work' } }
|
||||
})
|
||||
await ORCHESTRATION_HANDLERS['orchestration run-use']({
|
||||
flags: new Map<string, string | boolean>([
|
||||
['id', 'run_adopted'],
|
||||
['from', 'term_current'],
|
||||
['takeover-legacy', true]
|
||||
]),
|
||||
client: { call: callMock },
|
||||
cwd: '/tmp/repo',
|
||||
json: true
|
||||
} as never)
|
||||
|
||||
expect(callMock).toHaveBeenCalledWith('orchestration.runUse', {
|
||||
id: 'run_adopted',
|
||||
from: 'term_current',
|
||||
takeoverLegacy: true
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('orchestration reset CLI handler', () => {
|
||||
|
||||
@@ -64,11 +64,13 @@ describe('orchestration timeout flag validation', () => {
|
||||
// Why: unread:false makes pre-peek runtimes fall back to non-consuming all mode.
|
||||
expect(callMock).toHaveBeenCalledWith('orchestration.check', {
|
||||
terminal: 'term_worker',
|
||||
terminalPaneKey: undefined,
|
||||
unread: false,
|
||||
peek: true,
|
||||
all: undefined,
|
||||
types: undefined,
|
||||
format: undefined,
|
||||
compatibilityCliCommand: expect.stringMatching(/^orca(?:-ide)?$/),
|
||||
run: undefined,
|
||||
ack: undefined,
|
||||
wait: true,
|
||||
@@ -182,7 +184,9 @@ describe('orchestration timeout flag validation', () => {
|
||||
resume: undefined,
|
||||
options: undefined,
|
||||
timeoutMs: 123,
|
||||
from: 'term_worker'
|
||||
from: 'term_worker',
|
||||
compatibilityCliCommand: expect.stringMatching(/^orca(?:-ide)?$/),
|
||||
compatibilityWindowsCommand: undefined
|
||||
},
|
||||
{ timeoutMs: 5_123, orchestrationCapability: undefined }
|
||||
)
|
||||
@@ -209,7 +213,9 @@ describe('orchestration timeout flag validation', () => {
|
||||
resume: 'msg_question',
|
||||
options: undefined,
|
||||
timeoutMs: undefined,
|
||||
from: 'term_worker'
|
||||
from: 'term_worker',
|
||||
compatibilityCliCommand: expect.stringMatching(/^orca(?:-ide)?$/),
|
||||
compatibilityWindowsCommand: undefined
|
||||
},
|
||||
{ timeoutMs: 605_000, orchestrationCapability: undefined }
|
||||
)
|
||||
|
||||
@@ -86,11 +86,15 @@ describe('orchestration timeout flag validation', () => {
|
||||
|
||||
expect(callMock).toHaveBeenCalledWith('orchestration.check', {
|
||||
terminal: 'term_worker',
|
||||
terminalPaneKey: undefined,
|
||||
unread: false,
|
||||
peek: true,
|
||||
all: undefined,
|
||||
types: undefined,
|
||||
inject: undefined,
|
||||
format: undefined,
|
||||
compatibilityCliCommand: expect.stringMatching(/^orca(?:-ide)?$/),
|
||||
run: undefined,
|
||||
ack: undefined,
|
||||
wait: true,
|
||||
timeoutMs: 250
|
||||
})
|
||||
@@ -273,12 +277,16 @@ describe('orchestration timeout flag validation', () => {
|
||||
'orchestration.ask',
|
||||
{
|
||||
to: 'term_coord',
|
||||
run: undefined,
|
||||
question: 'Proceed?',
|
||||
resume: undefined,
|
||||
options: undefined,
|
||||
timeoutMs: 123,
|
||||
from: 'term_worker'
|
||||
from: 'term_worker',
|
||||
compatibilityCliCommand: expect.stringMatching(/^orca(?:-ide)?$/),
|
||||
compatibilityWindowsCommand: undefined
|
||||
},
|
||||
{ timeoutMs: 5_123 }
|
||||
{ timeoutMs: 5_123, orchestrationCapability: undefined }
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const callMock = vi.fn()
|
||||
const originalCliCommand = process.env.ORCA_CLI_COMMAND
|
||||
const originalPackagedLauncher = process.env.ORCA_WINDOWS_PACKAGED_CLI_LAUNCHER
|
||||
const originalTerminalHandle = process.env.ORCA_TERMINAL_HANDLE
|
||||
const originalExitCode = process.exitCode
|
||||
|
||||
vi.mock('../format', () => ({ printResult: vi.fn() }))
|
||||
vi.mock('../selectors', () => ({ getTerminalHandle: vi.fn() }))
|
||||
|
||||
import { ORCHESTRATION_HANDLERS } from './orchestration'
|
||||
|
||||
describe('packaged Windows legacy ask protocol', () => {
|
||||
beforeEach(() => {
|
||||
callMock.mockReset()
|
||||
process.env.ORCA_WINDOWS_PACKAGED_CLI_LAUNCHER = '1'
|
||||
process.env.ORCA_TERMINAL_HANDLE = 'term_worker'
|
||||
process.exitCode = undefined
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
process.exitCode = originalExitCode
|
||||
restoreEnv('ORCA_CLI_COMMAND', originalCliCommand)
|
||||
restoreEnv('ORCA_WINDOWS_PACKAGED_CLI_LAUNCHER', originalPackagedLauncher)
|
||||
restoreEnv('ORCA_TERMINAL_HANDLE', originalTerminalHandle)
|
||||
})
|
||||
|
||||
it.each(['orca', 'orca-ide'] as const)(
|
||||
'commits with the %s launcher and exits 75 before resume',
|
||||
async (command) => {
|
||||
process.env.ORCA_CLI_COMMAND = command
|
||||
callMock.mockResolvedValue({
|
||||
result: {
|
||||
answer: null,
|
||||
messageId: 'msg_question',
|
||||
threadId: 'msg_question',
|
||||
timedOut: false,
|
||||
legacyCompatibility: {
|
||||
resumeRequired: true,
|
||||
resumeCommand: `${command} orchestration ask --resume msg_question`
|
||||
}
|
||||
}
|
||||
})
|
||||
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
|
||||
await invokeAsk(new Map([['question', 'Proceed?']]))
|
||||
|
||||
expect(callMock).toHaveBeenCalledWith(
|
||||
'orchestration.ask',
|
||||
expect.objectContaining({
|
||||
question: 'Proceed?',
|
||||
resume: undefined,
|
||||
compatibilityWindowsCommand: command
|
||||
}),
|
||||
expect.any(Object)
|
||||
)
|
||||
expect(log.mock.calls.map(([line]) => line)).toEqual([
|
||||
'Question msg_question committed.',
|
||||
`Resume with: ${command} orchestration ask --resume msg_question`
|
||||
])
|
||||
expect(process.exitCode).toBe(75)
|
||||
}
|
||||
)
|
||||
|
||||
it('resumes the committed question without another exit-75 handoff', async () => {
|
||||
process.env.ORCA_CLI_COMMAND = 'orca'
|
||||
callMock.mockResolvedValue({
|
||||
result: {
|
||||
answer: 'yes',
|
||||
messageId: 'msg_question',
|
||||
threadId: 'msg_question',
|
||||
timedOut: false
|
||||
}
|
||||
})
|
||||
const log = vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
|
||||
await invokeAsk(new Map([['resume', 'msg_question']]))
|
||||
|
||||
expect(callMock).toHaveBeenCalledWith(
|
||||
'orchestration.ask',
|
||||
expect.objectContaining({
|
||||
question: undefined,
|
||||
resume: 'msg_question',
|
||||
compatibilityWindowsCommand: 'orca'
|
||||
}),
|
||||
expect.any(Object)
|
||||
)
|
||||
expect(log).toHaveBeenCalledWith('yes')
|
||||
expect(process.exitCode).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
function invokeAsk(flags: Map<string, string | boolean>): Promise<void> {
|
||||
return ORCHESTRATION_HANDLERS['orchestration ask']({
|
||||
flags,
|
||||
client: { call: callMock },
|
||||
cwd: '/tmp/repo',
|
||||
json: false
|
||||
} as never)
|
||||
}
|
||||
|
||||
function restoreEnv(name: string, value: string | undefined): void {
|
||||
if (value === undefined) {
|
||||
delete process.env[name]
|
||||
} else {
|
||||
process.env[name] = value
|
||||
}
|
||||
}
|
||||
@@ -692,6 +692,7 @@ describe('orchestration timeout flag validation', () => {
|
||||
all: undefined,
|
||||
types: undefined,
|
||||
format: undefined,
|
||||
compatibilityCliCommand: expect.stringMatching(/^orca(?:-ide)?$/),
|
||||
run: undefined,
|
||||
ack: undefined,
|
||||
wait: true,
|
||||
@@ -819,7 +820,9 @@ describe('orchestration timeout flag validation', () => {
|
||||
resume: undefined,
|
||||
options: undefined,
|
||||
timeoutMs: 123,
|
||||
from: 'term_worker'
|
||||
from: 'term_worker',
|
||||
compatibilityCliCommand: expect.stringMatching(/^orca(?:-ide)?$/),
|
||||
compatibilityWindowsCommand: undefined
|
||||
},
|
||||
{ timeoutMs: 5_123, orchestrationCapability: undefined }
|
||||
)
|
||||
@@ -848,7 +851,9 @@ describe('orchestration timeout flag validation', () => {
|
||||
resume: 'msg_question',
|
||||
options: undefined,
|
||||
timeoutMs: undefined,
|
||||
from: 'term_worker'
|
||||
from: 'term_worker',
|
||||
compatibilityCliCommand: expect.stringMatching(/^orca(?:-ide)?$/),
|
||||
compatibilityWindowsCommand: undefined
|
||||
},
|
||||
{ timeoutMs: 605_000, orchestrationCapability: undefined }
|
||||
)
|
||||
|
||||
@@ -21,11 +21,14 @@ import type {
|
||||
} from '../../shared/orchestration-worker-output'
|
||||
import type { NativeChatMessage } from '../../shared/native-chat-types'
|
||||
import type { RuntimeTerminalRead } from '../../shared/runtime-types'
|
||||
import { orchestrationMigrationData } from '../../shared/orchestration-rpc-contract'
|
||||
import {
|
||||
ORCHESTRATION_LEGACY_RUN_ID,
|
||||
orchestrationMigrationData,
|
||||
orchestrationSkillRecoveryData
|
||||
} from '../../shared/orchestration-rpc-contract'
|
||||
formatMessageReadOnlyTag,
|
||||
formatOrchestrationCheckText,
|
||||
prepareOrchestrationCheckOutput,
|
||||
type LegacyCompatibilityResult,
|
||||
type OrchestrationMessageSummary as MessageSummary
|
||||
} from '../../shared/orchestration-check-output'
|
||||
|
||||
// Why: 15 s is well under Claude Code's ~2 min Bash-tool silence budget while keeping log volume low. See design doc §3.4.
|
||||
const DEFAULT_KEEPALIVE_INTERVAL_MS = 15_000
|
||||
@@ -75,43 +78,6 @@ const TASK_STATUS_VALUES = [
|
||||
'blocked'
|
||||
] as const
|
||||
|
||||
type MessageSummary = {
|
||||
id: string
|
||||
run_id?: string
|
||||
from_handle: string
|
||||
to_handle?: string
|
||||
subject: string
|
||||
type?: string
|
||||
body?: string
|
||||
payload?: string | null
|
||||
read?: number
|
||||
}
|
||||
|
||||
function formatMessageReadOnlyTag(message: MessageSummary): string {
|
||||
return message.run_id === ORCHESTRATION_LEGACY_RUN_ID ? ' [legacy, read-only]' : ''
|
||||
}
|
||||
|
||||
function isLegacyReadOnlyMessage(message: MessageSummary): boolean {
|
||||
return message.run_id === ORCHESTRATION_LEGACY_RUN_ID
|
||||
}
|
||||
|
||||
function formatLegacyAwareCheckMessages(messages: MessageSummary[]): string {
|
||||
return messages
|
||||
.map((message) => {
|
||||
const lines = [
|
||||
`${message.id}${formatMessageReadOnlyTag(message)} [${message.type ?? 'status'}] from=${message.from_handle} "${message.subject}"`
|
||||
]
|
||||
if (message.body) {
|
||||
lines.push(message.body)
|
||||
}
|
||||
if (message.payload) {
|
||||
lines.push(`[payload] ${message.payload}`)
|
||||
}
|
||||
return lines.join('\n')
|
||||
})
|
||||
.join('\n\n')
|
||||
}
|
||||
|
||||
type LifecycleSendRejection = {
|
||||
action: 'rejected'
|
||||
code: string
|
||||
@@ -132,6 +98,40 @@ type OrchestrationSendResult =
|
||||
lifecycle?: { action: 'completed' | 'failed' }
|
||||
}
|
||||
|
||||
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'
|
||||
}
|
||||
|
||||
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.'
|
||||
)
|
||||
}
|
||||
|
||||
async function flushStdout(): Promise<void> {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
process.stdout.write('', (error) => {
|
||||
if (error) {
|
||||
reject(error)
|
||||
} else {
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function getOptionalStructuredMessagePayload(
|
||||
flags: Map<string, string | boolean>
|
||||
): string | undefined {
|
||||
@@ -447,7 +447,8 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
|
||||
run: { id: string; objective: string; consumer_generation: number }
|
||||
}>(client, flags, 'orchestration.runUse', {
|
||||
id: getRequiredStringFlag(flags, 'id'),
|
||||
from
|
||||
from,
|
||||
...(flags.has('takeover-legacy') ? { takeoverLegacy: true } : {})
|
||||
})
|
||||
printResult(result, json, (r) => `Using Run ${r.run.id}: ${r.run.objective}`)
|
||||
},
|
||||
@@ -503,13 +504,6 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
|
||||
rejectLifecycleGroupRecipient(type, to)
|
||||
}
|
||||
const outcome = getOptionalStringFlag(flags, 'outcome')
|
||||
if (type === 'worker_done' && outcome === undefined && !flags.has('payload')) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'worker_done requires --outcome succeeded or --outcome failed. No effects were applied.',
|
||||
orchestrationSkillRecoveryData()
|
||||
)
|
||||
}
|
||||
if (type !== 'worker_done' && outcome !== undefined) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
@@ -596,6 +590,7 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
|
||||
timedOut?: boolean
|
||||
cancelled?: boolean
|
||||
connectionLost?: boolean
|
||||
legacyCompatibility?: LegacyCompatibilityResult
|
||||
}
|
||||
let result: Awaited<ReturnType<typeof client.call<CheckResult>>>
|
||||
try {
|
||||
@@ -608,6 +603,8 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
|
||||
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,
|
||||
@@ -644,31 +641,25 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
|
||||
}
|
||||
}
|
||||
}
|
||||
printResult(result, json, (r) => {
|
||||
if (r.formatted) {
|
||||
return r.messages.some(isLegacyReadOnlyMessage)
|
||||
? formatLegacyAwareCheckMessages(r.messages)
|
||||
: r.formatted
|
||||
}
|
||||
if (r.count === 0) {
|
||||
if (r.timedOut) {
|
||||
return 'Wait timed out; no messages were consumed.'
|
||||
}
|
||||
if (r.cancelled) {
|
||||
return r.connectionLost
|
||||
? 'Wait cancelled because the connection closed; no messages were consumed.'
|
||||
: 'Wait cancelled; no messages were consumed.'
|
||||
}
|
||||
return 'No messages.'
|
||||
}
|
||||
const rendered = r.messages
|
||||
.map(
|
||||
(m) =>
|
||||
`${m.id}${formatMessageReadOnlyTag(m)} [${m.type ?? 'status'}] from=${m.from_handle} "${m.subject}"`
|
||||
)
|
||||
.join('\n')
|
||||
return r.deliveryId ? `Delivery ${r.deliveryId}\n${rendered}` : rendered
|
||||
})
|
||||
result = {
|
||||
...result,
|
||||
result: prepareOrchestrationCheckOutput(result.result, terminal, flags.has('format'))
|
||||
}
|
||||
printResult(result, json, (r) => formatOrchestrationCheckText(r, terminal))
|
||||
const compatibilityAck = result.result.legacyCompatibility?.ackMessageIds
|
||||
if (compatibilityAck && compatibilityAck.length > 0) {
|
||||
await flushStdout()
|
||||
await client.call('orchestration.check', {
|
||||
terminal,
|
||||
compatibilityAck: JSON.stringify({
|
||||
messageIds: compatibilityAck,
|
||||
types: getOptionalStringFlag(flags, 'types')
|
||||
?.split(',')
|
||||
.map((type) => type.trim())
|
||||
.filter(Boolean)
|
||||
})
|
||||
})
|
||||
}
|
||||
},
|
||||
|
||||
'orchestration reply': async ({ flags, client, cwd, json }) => {
|
||||
@@ -988,6 +979,8 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
|
||||
timeoutMs?: number
|
||||
cancelled?: boolean
|
||||
connectionLost?: boolean
|
||||
answerMessageId?: string | null
|
||||
legacyCompatibility?: LegacyCompatibilityResult
|
||||
}>(
|
||||
client,
|
||||
flags,
|
||||
@@ -999,7 +992,9 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
|
||||
resume,
|
||||
options: getOptionalStringFlag(flags, 'options'),
|
||||
timeoutMs: parsedTimeoutMs === undefined ? undefined : timeoutMs,
|
||||
from
|
||||
from,
|
||||
compatibilityCliCommand: resolveCompatibilityCliCommand(),
|
||||
compatibilityWindowsCommand: resolvePackagedWindowsCompatibilityCommand()
|
||||
},
|
||||
// Why: extend past timeoutMs so the RPC transport's 60s default doesn't abort before the runtime's own timeout resolves.
|
||||
{
|
||||
@@ -1010,9 +1005,25 @@ export const ORCHESTRATION_HANDLERS: Record<string, CommandHandler> = {
|
||||
// Why: bypass printResult so --json emits a bare JSON object (no envelope) pipeable via `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 flushStdout()
|
||||
process.exitCode = 75
|
||||
return
|
||||
}
|
||||
const answerAck = result.result.legacyCompatibility?.answerAcknowledgement
|
||||
if (answerAck && result.result.answer !== null) {
|
||||
await flushStdout()
|
||||
await client.call('orchestration.check', {
|
||||
terminal: from,
|
||||
compatibilityQuestionAck: JSON.stringify(answerAck)
|
||||
})
|
||||
}
|
||||
if (result.result.timedOut) {
|
||||
if (!json) {
|
||||
// Why: report the server's effective budget — it clamps large values, so the requested one would overstate the wait.
|
||||
|
||||
@@ -103,20 +103,40 @@ describe.skipIf(process.platform === 'win32')('RuntimeClient', () => {
|
||||
await new Promise<void>((resolve) => server.listen(endpoint, resolve))
|
||||
writeMetadata(userDataPath, endpoint)
|
||||
|
||||
const priorLaunchToken = process.env.ORCA_AGENT_LAUNCH_TOKEN
|
||||
process.env.ORCA_AGENT_LAUNCH_TOKEN = 'launch-secret'
|
||||
const client = new RuntimeClient(userDataPath, 500)
|
||||
await client.call(
|
||||
'orchestration.send',
|
||||
{ subject: 'hello' },
|
||||
{
|
||||
orchestrationRequestId: 'mutation_explicit'
|
||||
try {
|
||||
await client.call(
|
||||
'orchestration.send',
|
||||
{ subject: 'hello' },
|
||||
{
|
||||
orchestrationRequestId: 'mutation_explicit'
|
||||
}
|
||||
)
|
||||
await client.call('orchestration.taskList', {})
|
||||
const secondClient = new RuntimeClient(userDataPath, 500)
|
||||
await secondClient.call('orchestration.taskList', {})
|
||||
} finally {
|
||||
if (priorLaunchToken === undefined) {
|
||||
delete process.env.ORCA_AGENT_LAUNCH_TOKEN
|
||||
} else {
|
||||
process.env.ORCA_AGENT_LAUNCH_TOKEN = priorLaunchToken
|
||||
}
|
||||
)
|
||||
await client.call('orchestration.taskList', {})
|
||||
}
|
||||
|
||||
expect(requests[0]?.method).toBe('status.get')
|
||||
expect(requests[0]?.compatibilityInvocationId).toBeUndefined()
|
||||
expect(requests[1]?.orchestrationRequestId).toBe('mutation_explicit')
|
||||
expect(requests[1]?.orchestrationContractVersion).toBe(1)
|
||||
expect(requests[1]?.compatibilityInvocationId).toBe('mutation_explicit')
|
||||
expect(requests[1]?.orchestrationCompatibilityEvidence).toMatchObject({
|
||||
launchToken: 'launch-secret'
|
||||
})
|
||||
expect(requests[2]?.orchestrationRequestId).toBeUndefined()
|
||||
expect(requests[2]?.compatibilityInvocationId).not.toBe(requests[1]?.compatibilityInvocationId)
|
||||
expect(requests[3]?.method).toBe('orchestration.taskList')
|
||||
expect(requests[3]?.compatibilityInvocationId).not.toBe(requests[1]?.compatibilityInvocationId)
|
||||
})
|
||||
|
||||
it('rejects an old local runtime before sending an orchestration mutation', async () => {
|
||||
|
||||
+14
-17
@@ -20,6 +20,8 @@ import {
|
||||
ORCHESTRATION_CONTRACT_VERSION,
|
||||
RUNTIME_PROTOCOL_VERSION
|
||||
} from '../../shared/protocol-version'
|
||||
import { createOrchestrationCompatibilityEnvelope } from './orchestration-compatibility-envelope'
|
||||
import { getTimeoutMsParam, isWaitingCheck } from './runtime-request-timeout'
|
||||
|
||||
// Why: for long-poll methods the caller's method-level
|
||||
// `params.timeoutMs` is the inner waiter budget; we extend the client-side
|
||||
@@ -43,6 +45,9 @@ export class RuntimeClient {
|
||||
private readonly environmentSelector: string | null
|
||||
private remoteCompatChecked = false
|
||||
private orchestrationContractCheck: Promise<void> | null = null
|
||||
private readonly orchestrationCompatibility = createOrchestrationCompatibilityEnvelope(
|
||||
process.env
|
||||
)
|
||||
|
||||
// Why: browser commands trigger first-time session init (agent-browser connect +
|
||||
// CDP proxy setup) which can take 15-30s. 60s accommodates cold start without
|
||||
@@ -76,12 +81,20 @@ export class RuntimeClient {
|
||||
const orchestrationRequestId = orchestrationMutation
|
||||
? (options?.orchestrationRequestId ?? randomUUID())
|
||||
: undefined
|
||||
const compatibilityEnvelope = method.startsWith('orchestration.')
|
||||
? {
|
||||
...this.orchestrationCompatibility,
|
||||
compatibilityInvocationId:
|
||||
orchestrationRequestId ?? this.orchestrationCompatibility.compatibilityInvocationId
|
||||
}
|
||||
: {}
|
||||
const envelope = {
|
||||
orchestrationCapability: options?.orchestrationCapability,
|
||||
orchestrationContractVersion: method.startsWith('orchestration.')
|
||||
? ORCHESTRATION_CONTRACT_VERSION
|
||||
: undefined,
|
||||
orchestrationRequestId
|
||||
orchestrationRequestId,
|
||||
...compatibilityEnvelope
|
||||
}
|
||||
if (this.remotePairing) {
|
||||
if (method !== 'status.get') {
|
||||
@@ -327,19 +340,3 @@ function resolveRemotePairing(
|
||||
function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
function isWaitingCheck(params: unknown): boolean {
|
||||
return (
|
||||
typeof params === 'object' &&
|
||||
params !== null &&
|
||||
'wait' in params &&
|
||||
(params as { wait: unknown }).wait === true
|
||||
)
|
||||
}
|
||||
|
||||
function getTimeoutMsParam(params: unknown): unknown {
|
||||
if (typeof params !== 'object' || params === null || !('timeoutMs' in params)) {
|
||||
return undefined
|
||||
}
|
||||
return (params as { timeoutMs?: unknown }).timeoutMs
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { readOrchestrationCompatibilityEvidence } from '../../shared/orchestration-compatibility-evidence'
|
||||
import type { RuntimeOrchestrationEnvelope } from '../../shared/runtime-rpc-envelope'
|
||||
|
||||
export function createOrchestrationCompatibilityEnvelope(
|
||||
env: NodeJS.ProcessEnv
|
||||
): RuntimeOrchestrationEnvelope {
|
||||
return {
|
||||
compatibilityInvocationId: randomUUID(),
|
||||
orchestrationCompatibilityEvidence: readOrchestrationCompatibilityEvidence(env)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
export function isWaitingCheck(params: unknown): boolean {
|
||||
return (
|
||||
typeof params === 'object' &&
|
||||
params !== null &&
|
||||
'wait' in params &&
|
||||
(params as { wait: unknown }).wait === true
|
||||
)
|
||||
}
|
||||
|
||||
export function getTimeoutMsParam(params: unknown): unknown {
|
||||
if (typeof params !== 'object' || params === null || !('timeoutMs' in params)) {
|
||||
return undefined
|
||||
}
|
||||
return (params as { timeoutMs?: unknown }).timeoutMs
|
||||
}
|
||||
@@ -188,7 +188,9 @@ export async function sendRequest<TResult>(
|
||||
params,
|
||||
orchestrationCapability: envelope?.orchestrationCapability,
|
||||
orchestrationContractVersion: envelope?.orchestrationContractVersion,
|
||||
orchestrationRequestId: envelope?.orchestrationRequestId
|
||||
orchestrationRequestId: envelope?.orchestrationRequestId,
|
||||
compatibilityInvocationId: envelope?.compatibilityInvocationId,
|
||||
orchestrationCompatibilityEvidence: envelope?.orchestrationCompatibilityEvidence
|
||||
})}\n`
|
||||
)
|
||||
})
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { RuntimeRpcFailureError } from './types'
|
||||
|
||||
describe('RuntimeRpcFailureError compatibility redaction', () => {
|
||||
it('removes compatibility evidence from CLI JSON errors', () => {
|
||||
const error = new RuntimeRpcFailureError({
|
||||
id: 'request-1',
|
||||
ok: false,
|
||||
error: {
|
||||
code: 'compatibility_rejected',
|
||||
message: 'Rejected',
|
||||
data: {
|
||||
orchestrationCompatibilityEvidence: {
|
||||
launchToken: 'launch-secret'
|
||||
}
|
||||
}
|
||||
},
|
||||
_meta: { runtimeId: 'runtime-1' }
|
||||
})
|
||||
|
||||
expect(error.data).toEqual({
|
||||
orchestrationCompatibilityEvidence: '[redacted]'
|
||||
})
|
||||
expect(JSON.stringify(error.response)).not.toContain('launch-secret')
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { RuntimeRpcFailure } from '../../shared/runtime-rpc-envelope'
|
||||
import { redactOrchestrationCompatibilitySecrets } from '../../shared/orchestration-compatibility-evidence'
|
||||
|
||||
export type {
|
||||
RuntimeRpcFailure,
|
||||
@@ -15,7 +16,7 @@ export class RuntimeClientError extends Error {
|
||||
constructor(code: string, message: string, data?: unknown) {
|
||||
super(message)
|
||||
this.code = code
|
||||
this.data = data
|
||||
this.data = redactOrchestrationCompatibilitySecrets(data)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +26,12 @@ export class RuntimeRpcFailureError extends RuntimeClientError {
|
||||
constructor(response: RuntimeRpcFailure) {
|
||||
// Why: all client errors expose recovery through the same inherited channel.
|
||||
super(response.error.code, response.error.message, response.error.data)
|
||||
this.response = response
|
||||
this.response = {
|
||||
...response,
|
||||
error: {
|
||||
...response.error,
|
||||
...(response.error.data === undefined ? {} : { data: this.data })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,8 +16,12 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [
|
||||
{
|
||||
path: ['orchestration', 'run-use'],
|
||||
summary: 'Bind this coordinator terminal to an existing Run',
|
||||
usage: 'orca orchestration run-use --id <run_id> [--from <handle>] [--json]',
|
||||
allowedFlags: [...GLOBAL_FLAGS, 'id', 'from', 'retry-request']
|
||||
usage:
|
||||
'orca orchestration run-use --id <run_id> [--from <handle>] [--takeover-legacy] [--json]',
|
||||
allowedFlags: [...GLOBAL_FLAGS, 'id', 'from', 'takeover-legacy', 'retry-request'],
|
||||
notes: [
|
||||
'--takeover-legacy must run in the live coordinator agent terminal it binds; it preserves existing worker assignments.'
|
||||
]
|
||||
},
|
||||
{
|
||||
path: ['orchestration', 'run-current'],
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import type { AgentHookEventPayload } from '../../shared/agent-hook-listener'
|
||||
import { makePaneKey } from '../../shared/stable-pane-id'
|
||||
import { AgentHookServer } from './server'
|
||||
|
||||
const PANE_KEY = makePaneKey('tab-authority', '11111111-1111-4111-8111-111111111111')
|
||||
const SECOND_PANE_KEY = makePaneKey('tab-authority-2', '22222222-2222-4222-8222-222222222222')
|
||||
|
||||
describe('AgentHookServer authority evidence', () => {
|
||||
const servers: AgentHookServer[] = []
|
||||
|
||||
afterEach(() => {
|
||||
for (const server of servers) {
|
||||
server.stop()
|
||||
}
|
||||
servers.length = 0
|
||||
})
|
||||
|
||||
it('freezes pre-listen commitments separately from current-runtime observations', async () => {
|
||||
const server = new AgentHookServer()
|
||||
servers.push(server)
|
||||
const hydrated = {
|
||||
paneKey: PANE_KEY,
|
||||
launchToken: 'launch-before-restart',
|
||||
tabId: 'tab-authority',
|
||||
worktreeId: 'repo::before',
|
||||
connectionId: 'ssh-target',
|
||||
payload: { state: 'working', prompt: 'before', agentType: 'codex' },
|
||||
receivedAt: 100,
|
||||
stateStartedAt: 100
|
||||
} satisfies AgentHookEventPayload & { receivedAt: number; stateStartedAt: number }
|
||||
server._getStateForTests().lastStatusByPaneKey.set(PANE_KEY, hydrated)
|
||||
|
||||
await server.start()
|
||||
const commitments = server.getHydratedAuthorityCommitments()
|
||||
|
||||
expect(commitments).toEqual([
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
launchTokenHash: expect.stringMatching(/^[a-f0-9]{64}$/),
|
||||
tabId: 'tab-authority',
|
||||
worktreeId: 'repo::before',
|
||||
connectionId: 'ssh-target',
|
||||
observedAt: 100
|
||||
}
|
||||
])
|
||||
expect(Object.isFrozen(commitments)).toBe(true)
|
||||
expect(Object.isFrozen(commitments[0])).toBe(true)
|
||||
expect(server.getCurrentAuthorityObservations()).toEqual([])
|
||||
expect(
|
||||
server.attestCompatibilityAuthority({
|
||||
paneKey: PANE_KEY,
|
||||
launchTokenHash: createHash('sha256').update('launch-before-restart').digest('hex'),
|
||||
connectionId: 'ssh-target',
|
||||
terminalProvenance: 'restored'
|
||||
})
|
||||
).toEqual({ paneKey: PANE_KEY, source: 'hydrated_commitment' })
|
||||
|
||||
server.ingestRemote(
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
launchToken: 'launch-after-restart',
|
||||
tabId: 'tab-authority',
|
||||
worktreeId: 'repo::after',
|
||||
payload: { state: 'working', prompt: 'after', agentType: 'codex' }
|
||||
},
|
||||
'ssh-target'
|
||||
)
|
||||
|
||||
expect(server.getHydratedAuthorityCommitments()).toBe(commitments)
|
||||
expect(JSON.stringify(commitments)).not.toContain('launch-before-restart')
|
||||
expect(server.getCurrentAuthorityObservations()).toEqual([
|
||||
expect.objectContaining({
|
||||
paneKey: PANE_KEY,
|
||||
launchTokenHash: expect.stringMatching(/^[a-f0-9]{64}$/),
|
||||
connectionId: 'ssh-target',
|
||||
worktreeId: 'repo::after'
|
||||
})
|
||||
])
|
||||
expect(JSON.stringify(server.getCurrentAuthorityObservations())).not.toContain(
|
||||
'launch-after-restart'
|
||||
)
|
||||
expect(
|
||||
server.attestCompatibilityAuthority({
|
||||
paneKey: PANE_KEY,
|
||||
launchTokenHash: createHash('sha256').update('launch-before-restart').digest('hex'),
|
||||
connectionId: 'ssh-target',
|
||||
terminalProvenance: 'restored'
|
||||
})
|
||||
).toBeNull()
|
||||
expect(
|
||||
server.attestCompatibilityAuthority({
|
||||
paneKey: PANE_KEY,
|
||||
launchTokenHash: createHash('sha256').update('launch-before-restart').digest('hex'),
|
||||
connectionId: 'ssh-target',
|
||||
terminalProvenance: 'current_runtime'
|
||||
})
|
||||
).toBeNull()
|
||||
|
||||
expect(
|
||||
server.attestCompatibilityAuthority({
|
||||
paneKey: PANE_KEY,
|
||||
launchTokenHash: createHash('sha256').update('launch-after-restart').digest('hex'),
|
||||
connectionId: 'ssh-target',
|
||||
terminalProvenance: 'restored'
|
||||
})
|
||||
).toBeNull()
|
||||
expect(
|
||||
server.attestCompatibilityAuthority({
|
||||
paneKey: PANE_KEY,
|
||||
launchTokenHash: createHash('sha256').update('launch-after-restart').digest('hex'),
|
||||
connectionId: 'ssh-target',
|
||||
terminalProvenance: 'current_runtime'
|
||||
})
|
||||
).toEqual({ paneKey: PANE_KEY, source: 'current_hook' })
|
||||
|
||||
server.ingestRemote(
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
launchToken: 'launch-before-restart',
|
||||
tabId: 'tab-authority',
|
||||
worktreeId: 'repo::current',
|
||||
payload: { state: 'working', prompt: 'current', agentType: 'codex' }
|
||||
},
|
||||
'ssh-target'
|
||||
)
|
||||
|
||||
expect(
|
||||
server.attestCompatibilityAuthority({
|
||||
paneKey: PANE_KEY,
|
||||
launchTokenHash: createHash('sha256').update('launch-before-restart').digest('hex'),
|
||||
connectionId: 'ssh-target',
|
||||
terminalProvenance: 'restored'
|
||||
})
|
||||
).toEqual({ paneKey: PANE_KEY, source: 'current_hook' })
|
||||
|
||||
server.ingestRemote(
|
||||
{
|
||||
paneKey: SECOND_PANE_KEY,
|
||||
launchToken: 'launch-before-restart',
|
||||
tabId: 'tab-authority-2',
|
||||
payload: { state: 'working', prompt: 'duplicate', agentType: 'codex' }
|
||||
},
|
||||
'ssh-target'
|
||||
)
|
||||
|
||||
expect(
|
||||
server.attestCompatibilityAuthority({
|
||||
paneKey: PANE_KEY,
|
||||
launchTokenHash: createHash('sha256').update('launch-before-restart').digest('hex'),
|
||||
connectionId: 'ssh-target',
|
||||
terminalProvenance: 'restored'
|
||||
})
|
||||
).toBeNull()
|
||||
|
||||
server.clearStatusEntriesForConnection('ssh-target')
|
||||
|
||||
expect(server.getHydratedAuthorityCommitments()).toBe(commitments)
|
||||
expect(server.getCurrentAuthorityObservations()).toEqual([])
|
||||
expect(
|
||||
server.attestCompatibilityAuthority({
|
||||
paneKey: PANE_KEY,
|
||||
launchTokenHash: createHash('sha256').update('launch-before-restart').digest('hex'),
|
||||
connectionId: 'ssh-target',
|
||||
terminalProvenance: 'restored'
|
||||
})
|
||||
).toEqual({ paneKey: PANE_KEY, source: 'hydrated_commitment' })
|
||||
|
||||
server.clearPaneState(PANE_KEY)
|
||||
|
||||
expect(server.getHydratedAuthorityCommitments()).toBe(commitments)
|
||||
expect(
|
||||
server.attestCompatibilityAuthority({
|
||||
paneKey: PANE_KEY,
|
||||
launchTokenHash: createHash('sha256').update('launch-before-restart').digest('hex'),
|
||||
connectionId: 'ssh-target',
|
||||
terminalProvenance: 'restored'
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('preserves hydrated authority when stale alias cleanup does not own the stable pane', async () => {
|
||||
const server = new AgentHookServer()
|
||||
servers.push(server)
|
||||
const launchToken = 'launch-before-restart'
|
||||
const launchTokenHash = createHash('sha256').update(launchToken).digest('hex')
|
||||
const hydrated = {
|
||||
paneKey: PANE_KEY,
|
||||
launchToken,
|
||||
tabId: 'tab-authority',
|
||||
worktreeId: 'repo::before',
|
||||
connectionId: 'ssh-target',
|
||||
payload: { state: 'working', prompt: 'before', agentType: 'codex' },
|
||||
receivedAt: 100,
|
||||
stateStartedAt: 100
|
||||
} satisfies AgentHookEventPayload & { receivedAt: number; stateStartedAt: number }
|
||||
server._getStateForTests().lastStatusByPaneKey.set(PANE_KEY, hydrated)
|
||||
server.registerPaneKeyAlias('tab-authority:0', PANE_KEY, 'old-pty')
|
||||
await server.start()
|
||||
server.ingestRemote(
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
launchToken,
|
||||
tabId: 'tab-authority',
|
||||
worktreeId: 'repo::current',
|
||||
payload: { state: 'working', prompt: 'current', agentType: 'codex' }
|
||||
},
|
||||
'ssh-target'
|
||||
)
|
||||
|
||||
server.clearPaneKeyAliasesForPty('old-pty', { shouldClearStablePaneKey: () => false })
|
||||
|
||||
expect(
|
||||
server.attestCompatibilityAuthority({
|
||||
paneKey: PANE_KEY,
|
||||
launchTokenHash,
|
||||
connectionId: 'ssh-target',
|
||||
terminalProvenance: 'restored'
|
||||
})
|
||||
).toEqual({ paneKey: PANE_KEY, source: 'current_hook' })
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
/* eslint-disable max-lines -- Why: this suite exercises the full hook HTTP surface (Claude/Codex/Gemini parsing, transcript chunked scan, paneKey dispatch) and keeping the scenarios co-located avoids fixture drift across files. */
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { createHash } from 'node:crypto'
|
||||
import {
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
@@ -57,6 +58,7 @@ const TAB_A_PANE = makePaneKey('tab-A', LEAF_5)
|
||||
|
||||
type Body = {
|
||||
paneKey: string
|
||||
launchToken?: string
|
||||
tabId?: string
|
||||
worktreeId?: string
|
||||
env?: string
|
||||
@@ -6254,7 +6256,10 @@ describe('Last-status persistence', () => {
|
||||
try {
|
||||
await postHookEvent(
|
||||
server,
|
||||
buildBody({ hook_event_name: 'UserPromptSubmit', prompt: 'persist me' })
|
||||
buildBody(
|
||||
{ hook_event_name: 'UserPromptSubmit', prompt: 'persist me' },
|
||||
{ launchToken: 'launch-bearer-must-not-persist' }
|
||||
)
|
||||
)
|
||||
// Synchronous flush via stop() captures the trailing-debounced write.
|
||||
server.flushStatusPersistSync()
|
||||
@@ -6269,11 +6274,148 @@ describe('Last-status persistence', () => {
|
||||
stateStartedAt: expect.any(Number),
|
||||
payload: expect.objectContaining({ state: 'working', prompt: 'persist me' })
|
||||
})
|
||||
expect(file.entries[PANE].launchToken).toBeUndefined()
|
||||
expect(file.entries[PANE].launchTokenHash).toBe(
|
||||
createHash('sha256').update('launch-bearer-must-not-persist').digest('hex')
|
||||
)
|
||||
expect(readFileSync(lastStatusPath(), 'utf8')).not.toContain('launch-bearer-must-not-persist')
|
||||
} finally {
|
||||
server.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('scrubs a legacy persisted launch bearer while retaining its authority commitment', async () => {
|
||||
mkdirSync(join(userDataPath, 'agent-hooks'), { recursive: true })
|
||||
const receivedAt = recentTs()
|
||||
const launchToken = 'legacy-launch-bearer'
|
||||
writeFileSync(
|
||||
lastStatusPath(),
|
||||
JSON.stringify({
|
||||
version: 2,
|
||||
entries: {
|
||||
[PANE]: {
|
||||
paneKey: PANE,
|
||||
launchToken,
|
||||
tabId: 'tab-1',
|
||||
worktreeId: 'wt-1',
|
||||
connectionId: null,
|
||||
receivedAt,
|
||||
stateStartedAt: receivedAt,
|
||||
payload: {
|
||||
state: 'working',
|
||||
prompt: 'legacy worker',
|
||||
agentType: 'codex'
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
'utf8'
|
||||
)
|
||||
|
||||
const server = new AgentHookServer()
|
||||
await server.start({ env: 'production', userDataPath })
|
||||
try {
|
||||
const launchTokenHash = createHash('sha256').update(launchToken).digest('hex')
|
||||
expect(server.getHydratedAuthorityCommitments()).toEqual([
|
||||
expect.objectContaining({ paneKey: PANE, launchTokenHash })
|
||||
])
|
||||
expect(server.getStatusSnapshotForPane(PANE)[0]?.launchToken).toBeUndefined()
|
||||
|
||||
const persisted = readFileSync(lastStatusPath(), 'utf8')
|
||||
expect(persisted).not.toContain(launchToken)
|
||||
expect(JSON.parse(persisted).entries[PANE]).toMatchObject({ launchTokenHash })
|
||||
} finally {
|
||||
server.stop()
|
||||
}
|
||||
|
||||
const restartedServer = new AgentHookServer()
|
||||
await restartedServer.start({ env: 'production', userDataPath })
|
||||
try {
|
||||
expect(restartedServer.getHydratedAuthorityCommitments()).toEqual([
|
||||
expect.objectContaining({
|
||||
paneKey: PANE,
|
||||
launchTokenHash: createHash('sha256').update(launchToken).digest('hex')
|
||||
})
|
||||
])
|
||||
expect(restartedServer.getStatusSnapshotForPane(PANE)[0]?.launchToken).toBeUndefined()
|
||||
} finally {
|
||||
restartedServer.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('persists SSH authority through transient clears until explicit retirement', async () => {
|
||||
mkdirSync(join(userDataPath, 'agent-hooks'), { recursive: true })
|
||||
const receivedAt = recentTs()
|
||||
const launchToken = 'retained-ssh-launch-bearer'
|
||||
const launchTokenHash = createHash('sha256').update(launchToken).digest('hex')
|
||||
writeFileSync(
|
||||
lastStatusPath(),
|
||||
JSON.stringify({
|
||||
version: 2,
|
||||
entries: {
|
||||
[PANE]: {
|
||||
paneKey: PANE,
|
||||
launchTokenHash,
|
||||
tabId: 'tab-1',
|
||||
worktreeId: 'wt-1',
|
||||
connectionId: 'ssh-target',
|
||||
receivedAt,
|
||||
stateStartedAt: receivedAt,
|
||||
payload: {
|
||||
state: 'working',
|
||||
prompt: 'retained SSH worker',
|
||||
agentType: 'codex'
|
||||
}
|
||||
}
|
||||
}
|
||||
}),
|
||||
'utf8'
|
||||
)
|
||||
|
||||
const first = new AgentHookServer()
|
||||
await first.start({ env: 'production', userDataPath })
|
||||
first.clearStatusEntriesForConnection('ssh-target')
|
||||
first.flushStatusPersistSync()
|
||||
first.stop()
|
||||
|
||||
const afterClear = JSON.parse(readFileSync(lastStatusPath(), 'utf8'))
|
||||
expect(afterClear.entries).toEqual({})
|
||||
expect(afterClear.authorityCommitments[PANE]).toMatchObject({
|
||||
paneKey: PANE,
|
||||
launchTokenHash,
|
||||
connectionId: 'ssh-target'
|
||||
})
|
||||
|
||||
const restored = new AgentHookServer()
|
||||
await restored.start({ env: 'production', userDataPath })
|
||||
expect(
|
||||
restored.attestCompatibilityAuthority({
|
||||
paneKey: PANE,
|
||||
launchTokenHash,
|
||||
connectionId: 'ssh-target',
|
||||
terminalProvenance: 'restored'
|
||||
})
|
||||
).toEqual({ paneKey: PANE, source: 'hydrated_commitment' })
|
||||
restored.retirePaneAuthority(PANE)
|
||||
restored.flushStatusPersistSync()
|
||||
restored.stop()
|
||||
|
||||
const retired = new AgentHookServer()
|
||||
await retired.start({ env: 'production', userDataPath })
|
||||
try {
|
||||
expect(
|
||||
retired.attestCompatibilityAuthority({
|
||||
paneKey: PANE,
|
||||
launchTokenHash,
|
||||
connectionId: 'ssh-target',
|
||||
terminalProvenance: 'restored'
|
||||
})
|
||||
).toBeNull()
|
||||
} finally {
|
||||
retired.stop()
|
||||
}
|
||||
})
|
||||
|
||||
it('persists and hydrates Pi session identity without creating status telemetry', async () => {
|
||||
const firstServer = new AgentHookServer()
|
||||
const firstRendererListener = vi.fn()
|
||||
@@ -7640,6 +7782,82 @@ describe('AgentHookServer ingestRemote', () => {
|
||||
})
|
||||
|
||||
describe('AgentHookServer ingestTerminalStatus', () => {
|
||||
// Why: the OSC 9999 payload cannot carry a provider session, so letting it overwrite the row
|
||||
// erased the session id from persisted rows and from headless `orca serve` — which serves these
|
||||
// rows straight to mobile — leaving Chat UI with no transcript to subscribe to (#10630).
|
||||
it('keeps the cached provider session when an OSC status completes the turn', () => {
|
||||
const server = new AgentHookServer()
|
||||
const providerSession = { key: 'session_id' as const, id: 'claude-session-1' }
|
||||
|
||||
server.ingestRemote(
|
||||
{
|
||||
paneKey: PANE,
|
||||
providerSession,
|
||||
payload: { state: 'working', prompt: 'summarize the diff', agentType: 'claude' }
|
||||
},
|
||||
'conn-1'
|
||||
)
|
||||
server.ingestTerminalStatus({
|
||||
paneKey: PANE,
|
||||
connectionId: 'conn-1',
|
||||
payload: { state: 'done', prompt: 'summarize the diff', agentType: 'claude' }
|
||||
})
|
||||
|
||||
expect(server.getStatusSnapshot()[0]).toMatchObject({ state: 'done', providerSession })
|
||||
})
|
||||
|
||||
// Why: an OSC ping that names no agent — or the literal 'unknown', which
|
||||
// resolveAgentStatusIdentity treats identically — makes no claim about the pane's identity, so it
|
||||
// must not read as a mismatch. Missing this stripped the session from persisted and headless rows
|
||||
// while the live renderer kept it, blanking mobile chat only after a restart (#10630).
|
||||
it.each([undefined, 'unknown' as const])(
|
||||
'keeps the cached provider session when an OSC status claims agentType %s',
|
||||
(agentType) => {
|
||||
const server = new AgentHookServer()
|
||||
const providerSession = { key: 'session_id' as const, id: 'claude-session-1' }
|
||||
|
||||
server.ingestRemote(
|
||||
{
|
||||
paneKey: PANE,
|
||||
providerSession,
|
||||
payload: { state: 'working', prompt: 'summarize the diff', agentType: 'claude' }
|
||||
},
|
||||
'conn-1'
|
||||
)
|
||||
server.ingestTerminalStatus({
|
||||
paneKey: PANE,
|
||||
connectionId: 'conn-1',
|
||||
payload: {
|
||||
state: 'done',
|
||||
prompt: 'summarize the diff',
|
||||
...(agentType ? { agentType } : {})
|
||||
}
|
||||
})
|
||||
|
||||
expect(server.getStatusSnapshot()[0]).toMatchObject({ providerSession })
|
||||
}
|
||||
)
|
||||
|
||||
it('drops the cached provider session when an OSC status starts a new turn', () => {
|
||||
const server = new AgentHookServer()
|
||||
|
||||
server.ingestRemote(
|
||||
{
|
||||
paneKey: PANE,
|
||||
providerSession: { key: 'session_id' as const, id: 'claude-session-1' },
|
||||
payload: { state: 'done', prompt: 'first', agentType: 'claude' }
|
||||
},
|
||||
'conn-1'
|
||||
)
|
||||
server.ingestTerminalStatus({
|
||||
paneKey: PANE,
|
||||
connectionId: 'conn-1',
|
||||
payload: { state: 'working', prompt: 'second', agentType: 'claude' }
|
||||
})
|
||||
|
||||
expect(server.getStatusSnapshot()[0]?.providerSession).toBeUndefined()
|
||||
})
|
||||
|
||||
it('forwards runtime terminal status through the normal listener and snapshot path', () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(1_000)
|
||||
|
||||
+383
-18
@@ -79,6 +79,22 @@ type EnrichedAgentHookEventPayload = AgentHookEventPayload & {
|
||||
stateStartedAt: number
|
||||
}
|
||||
|
||||
type PersistedAgentHookEventPayload = Omit<
|
||||
EnrichedAgentHookEventPayload,
|
||||
'launchToken' | 'promptInteractionKey'
|
||||
> & {
|
||||
launchTokenHash?: string
|
||||
}
|
||||
|
||||
type PersistedAgentHookAuthorityCommitment = {
|
||||
paneKey: string
|
||||
launchTokenHash: string
|
||||
connectionId: string | null
|
||||
tabId?: string
|
||||
worktreeId?: string
|
||||
observedAt: number
|
||||
}
|
||||
|
||||
export type AgentHookStatusChangeEntry = {
|
||||
state: AgentStatusState
|
||||
receivedAt: number
|
||||
@@ -92,6 +108,20 @@ export type AgentHookProviderSessionIdentity = {
|
||||
worktreeId?: string
|
||||
}
|
||||
|
||||
export type AgentHookAuthorityEvidence = Readonly<{
|
||||
paneKey: string
|
||||
launchTokenHash: string
|
||||
connectionId: string | null
|
||||
tabId?: string
|
||||
worktreeId?: string
|
||||
observedAt: number
|
||||
}>
|
||||
|
||||
export type AgentHookAuthorityAttestation = Readonly<{
|
||||
paneKey: string
|
||||
source: 'current_hook' | 'hydrated_commitment'
|
||||
}>
|
||||
|
||||
type StatusChangeListener = (statuses: AgentHookStatusChangeEntry[]) => void
|
||||
type ProviderSessionChangeListener = (providerSessions: AgentHookProviderSessionIdentity[]) => void
|
||||
type PaneStatusClearListener = (clear: AgentStatusClearIpcPayload) => void
|
||||
@@ -128,7 +158,8 @@ export const PANE_KEY_ALIASES_MAX = 1024
|
||||
|
||||
type LastStatusFile = {
|
||||
version: number
|
||||
entries: Record<string, EnrichedAgentHookEventPayload>
|
||||
entries: Record<string, PersistedAgentHookEventPayload>
|
||||
authorityCommitments?: Record<string, PersistedAgentHookAuthorityCommitment>
|
||||
}
|
||||
|
||||
type AgentPromptSentDedupeEntry = {
|
||||
@@ -251,7 +282,6 @@ function sanitizeHydratedEntry(
|
||||
}
|
||||
return {
|
||||
paneKey,
|
||||
launchToken: typeof record.launchToken === 'string' ? record.launchToken : undefined,
|
||||
tabId: typeof tabId === 'string' ? tabId : undefined,
|
||||
worktreeId: typeof worktreeId === 'string' ? worktreeId : undefined,
|
||||
connectionId,
|
||||
@@ -268,6 +298,63 @@ function sanitizeHydratedEntry(
|
||||
}
|
||||
}
|
||||
|
||||
function readPersistedLaunchTokenHash(rawEntry: unknown): string | null {
|
||||
if (typeof rawEntry !== 'object' || rawEntry === null) {
|
||||
return null
|
||||
}
|
||||
const record = rawEntry as Record<string, unknown>
|
||||
const launchTokenHash =
|
||||
typeof record.launchTokenHash === 'string' ? record.launchTokenHash.trim() : ''
|
||||
if (/^[a-f0-9]{64}$/.test(launchTokenHash)) {
|
||||
return launchTokenHash
|
||||
}
|
||||
const legacyLaunchToken = typeof record.launchToken === 'string' ? record.launchToken.trim() : ''
|
||||
return legacyLaunchToken ? createHash('sha256').update(legacyLaunchToken).digest('hex') : null
|
||||
}
|
||||
|
||||
function sanitizePersistedAuthorityCommitment(
|
||||
paneKey: string,
|
||||
value: unknown
|
||||
): AgentHookAuthorityEvidence | null {
|
||||
if (!isValidPaneKey(paneKey) || typeof value !== 'object' || value === null) {
|
||||
return null
|
||||
}
|
||||
const record = value as Record<string, unknown>
|
||||
const launchTokenHash =
|
||||
typeof record.launchTokenHash === 'string' ? record.launchTokenHash.trim() : ''
|
||||
const connectionId = record.connectionId
|
||||
const observedAt = record.observedAt
|
||||
if (
|
||||
!/^[a-f0-9]{64}$/.test(launchTokenHash) ||
|
||||
(connectionId !== null && typeof connectionId !== 'string') ||
|
||||
typeof observedAt !== 'number' ||
|
||||
!Number.isFinite(observedAt)
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return Object.freeze({
|
||||
paneKey,
|
||||
launchTokenHash,
|
||||
connectionId,
|
||||
...(typeof record.tabId === 'string' ? { tabId: record.tabId } : {}),
|
||||
...(typeof record.worktreeId === 'string' ? { worktreeId: record.worktreeId } : {}),
|
||||
observedAt
|
||||
})
|
||||
}
|
||||
|
||||
function authorityCommitmentsMatch(
|
||||
left: AgentHookAuthorityEvidence,
|
||||
right: AgentHookAuthorityEvidence
|
||||
): boolean {
|
||||
return (
|
||||
left.paneKey === right.paneKey &&
|
||||
left.launchTokenHash === right.launchTokenHash &&
|
||||
left.connectionId === right.connectionId &&
|
||||
left.tabId === right.tabId &&
|
||||
left.worktreeId === right.worktreeId
|
||||
)
|
||||
}
|
||||
|
||||
function toAgentStatusIpcPayload(entry: EnrichedAgentHookEventPayload): AgentStatusIpcPayload {
|
||||
return {
|
||||
paneKey: entry.paneKey,
|
||||
@@ -479,6 +566,11 @@ export class AgentHookServer {
|
||||
private state: HookListenerState = createHookListenerState()
|
||||
// Why: hydrated rows give UI continuity but aren't evidence of live agent work in this runtime.
|
||||
private runtimeObservedStatusPaneKeys = new Set<string>()
|
||||
private hydratedAuthorityCommitments: readonly AgentHookAuthorityEvidence[] = Object.freeze([])
|
||||
private hydratedLaunchTokenHashByPaneKey = new Map<string, string>()
|
||||
private persistedAuthorityCommitmentsByPaneKey = new Map<string, AgentHookAuthorityEvidence>()
|
||||
private revokedHydratedAuthorityCommitments = new WeakSet<AgentHookAuthorityEvidence>()
|
||||
private currentAuthorityObservations = new Map<string, AgentHookAuthorityEvidence>()
|
||||
private legacyPaneKeyAliases = new Map<string, PaneKeyAliasEntry>()
|
||||
private paneKeyAliasPersistenceListener: PaneKeyAliasPersistenceListener | null = null
|
||||
// Why: on-disk last-status cache path; null without a userDataPath (tests), where persistence is a no-op and only in-memory replay applies.
|
||||
@@ -562,6 +654,53 @@ export class AgentHookServer {
|
||||
return entry ? [toAgentStatusIpcPayload(entry as EnrichedAgentHookEventPayload)] : []
|
||||
}
|
||||
|
||||
getHydratedAuthorityCommitments(): readonly AgentHookAuthorityEvidence[] {
|
||||
return this.hydratedAuthorityCommitments
|
||||
}
|
||||
|
||||
getCurrentAuthorityObservations(): readonly AgentHookAuthorityEvidence[] {
|
||||
return Object.freeze(
|
||||
Array.from(this.currentAuthorityObservations.values(), (entry) => Object.freeze({ ...entry }))
|
||||
)
|
||||
}
|
||||
|
||||
attestCompatibilityAuthority(candidate: {
|
||||
paneKey: string
|
||||
launchTokenHash: string
|
||||
connectionId: string | null
|
||||
terminalProvenance: 'current_runtime' | 'restored'
|
||||
}): AgentHookAuthorityAttestation | null {
|
||||
const paneKey = this.resolvePaneKeyAlias(candidate.paneKey)
|
||||
const matchesCandidate = (entry: AgentHookAuthorityEvidence): boolean =>
|
||||
entry.launchTokenHash === candidate.launchTokenHash &&
|
||||
entry.connectionId === candidate.connectionId
|
||||
const commitments = this.hydratedAuthorityCommitments.filter(
|
||||
(entry) => matchesCandidate(entry) && !this.revokedHydratedAuthorityCommitments.has(entry)
|
||||
)
|
||||
const current = Array.from(this.currentAuthorityObservations.values())
|
||||
const observations = current.filter(matchesCandidate)
|
||||
const paneObservations = current.filter(
|
||||
(entry) => this.resolvePaneKeyAlias(entry.paneKey) === paneKey
|
||||
)
|
||||
const hasUniqueCurrentObservation =
|
||||
observations.length === 1 &&
|
||||
paneObservations.length === 1 &&
|
||||
this.resolvePaneKeyAlias(observations[0]!.paneKey) === paneKey
|
||||
if (candidate.terminalProvenance === 'current_runtime') {
|
||||
return hasUniqueCurrentObservation ? Object.freeze({ paneKey, source: 'current_hook' }) : null
|
||||
}
|
||||
if (commitments.length !== 1 || this.resolvePaneKeyAlias(commitments[0]!.paneKey) !== paneKey) {
|
||||
return null
|
||||
}
|
||||
if (observations.length === 0 && paneObservations.length === 0) {
|
||||
return Object.freeze({ paneKey, source: 'hydrated_commitment' })
|
||||
}
|
||||
if (!hasUniqueCurrentObservation) {
|
||||
return null
|
||||
}
|
||||
return Object.freeze({ paneKey, source: 'current_hook' })
|
||||
}
|
||||
|
||||
inferInterrupt(request: AgentInterruptInferenceRequest): boolean {
|
||||
if (!isValidPaneKey(request.paneKey)) {
|
||||
return false
|
||||
@@ -1301,9 +1440,40 @@ export class AgentHookServer {
|
||||
tabId: owner?.tabId
|
||||
})
|
||||
}
|
||||
const hydratedLaunchTokenHash = this.hydratedLaunchTokenHashByPaneKey.get(previousOwnerPaneKey)
|
||||
if (hydratedLaunchTokenHash) {
|
||||
this.hydratedLaunchTokenHashByPaneKey.delete(previousOwnerPaneKey)
|
||||
this.hydratedLaunchTokenHashByPaneKey.set(toPaneKey, hydratedLaunchTokenHash)
|
||||
}
|
||||
const persistedAuthority = this.persistedAuthorityCommitmentsByPaneKey.get(previousOwnerPaneKey)
|
||||
if (persistedAuthority) {
|
||||
const owner = parsePaneKey(toPaneKey)
|
||||
this.persistedAuthorityCommitmentsByPaneKey.delete(previousOwnerPaneKey)
|
||||
this.persistedAuthorityCommitmentsByPaneKey.set(
|
||||
toPaneKey,
|
||||
Object.freeze({
|
||||
...persistedAuthority,
|
||||
paneKey: toPaneKey,
|
||||
...(owner?.tabId ? { tabId: owner.tabId } : {})
|
||||
})
|
||||
)
|
||||
}
|
||||
if (this.runtimeObservedStatusPaneKeys.delete(previousOwnerPaneKey)) {
|
||||
this.runtimeObservedStatusPaneKeys.add(toPaneKey)
|
||||
}
|
||||
const authorityObservation = this.currentAuthorityObservations.get(previousOwnerPaneKey)
|
||||
if (authorityObservation) {
|
||||
const owner = parsePaneKey(toPaneKey)
|
||||
this.currentAuthorityObservations.delete(previousOwnerPaneKey)
|
||||
this.currentAuthorityObservations.set(
|
||||
toPaneKey,
|
||||
Object.freeze({
|
||||
...authorityObservation,
|
||||
paneKey: toPaneKey,
|
||||
tabId: owner?.tabId
|
||||
})
|
||||
)
|
||||
}
|
||||
const promptDedupe = this.promptSentDedupeByPaneKey.get(previousOwnerPaneKey)
|
||||
if (promptDedupe !== undefined) {
|
||||
this.promptSentDedupeByPaneKey.delete(previousOwnerPaneKey)
|
||||
@@ -1321,7 +1491,7 @@ export class AgentHookServer {
|
||||
this.boundPaneKeyAliases()
|
||||
this.closedAgentStatusPaneKeys.delete(toPaneKey)
|
||||
this.notifyPaneKeyAliasPersistenceListener()
|
||||
if (hadStatus) {
|
||||
if (hadStatus || persistedAuthority) {
|
||||
this.scheduleStatusPersist()
|
||||
this.notifyStatusChangeListeners()
|
||||
}
|
||||
@@ -1339,6 +1509,7 @@ export class AgentHookServer {
|
||||
aliasChanged = true
|
||||
}
|
||||
}
|
||||
const authorityChanged = this.revokeHydratedAuthorityForPaneKeys(paneKeys)
|
||||
const hadStatus = [...paneKeys].some((key) => this.state.lastStatusByPaneKey.has(key))
|
||||
for (const key of paneKeys) {
|
||||
this.markPaneClosedForAgentStatus(key)
|
||||
@@ -1346,12 +1517,13 @@ export class AgentHookServer {
|
||||
this.clearCodexSubagentPoll(key)
|
||||
clearPaneCacheState(this.state, key)
|
||||
this.runtimeObservedStatusPaneKeys.delete(key)
|
||||
this.currentAuthorityObservations.delete(key)
|
||||
this.promptSentDedupeByPaneKey.delete(key)
|
||||
}
|
||||
if (aliasChanged) {
|
||||
this.notifyPaneKeyAliasPersistenceListener()
|
||||
}
|
||||
if (hadStatus) {
|
||||
if (hadStatus || authorityChanged) {
|
||||
this.scheduleStatusPersist()
|
||||
this.notifyStatusChangeListeners()
|
||||
}
|
||||
@@ -1366,11 +1538,19 @@ export class AgentHookServer {
|
||||
const clearedStatusPaneKeys = new Set<string>()
|
||||
for (const [legacyPaneKey, entry] of this.legacyPaneKeyAliases) {
|
||||
if (entry.ptyId === ptyId) {
|
||||
this.legacyPaneKeyAliases.delete(legacyPaneKey)
|
||||
clearPaneCacheState(this.state, legacyPaneKey)
|
||||
this.promptSentDedupeByPaneKey.delete(legacyPaneKey)
|
||||
const shouldClearStablePaneKey =
|
||||
options?.shouldClearStablePaneKey?.(entry.stablePaneKey) ?? true
|
||||
const revokedPaneKeys = new Set([legacyPaneKey])
|
||||
if (shouldClearStablePaneKey) {
|
||||
revokedPaneKeys.add(entry.stablePaneKey)
|
||||
}
|
||||
if (this.revokeHydratedAuthorityForPaneKeys(revokedPaneKeys)) {
|
||||
statusChanged = true
|
||||
}
|
||||
this.legacyPaneKeyAliases.delete(legacyPaneKey)
|
||||
clearPaneCacheState(this.state, legacyPaneKey)
|
||||
this.currentAuthorityObservations.delete(legacyPaneKey)
|
||||
this.promptSentDedupeByPaneKey.delete(legacyPaneKey)
|
||||
if (shouldClearStablePaneKey && this.state.lastStatusByPaneKey.has(entry.stablePaneKey)) {
|
||||
statusChanged = true
|
||||
clearedStatusPaneKeys.add(entry.stablePaneKey)
|
||||
@@ -1379,6 +1559,7 @@ export class AgentHookServer {
|
||||
// Why: hydrated rows live under the stable key; if this PTY dies before ptyPaneKey rebuilds, alias cleanup is the only evictor.
|
||||
clearPaneCacheState(this.state, entry.stablePaneKey)
|
||||
this.runtimeObservedStatusPaneKeys.delete(entry.stablePaneKey)
|
||||
this.currentAuthorityObservations.delete(entry.stablePaneKey)
|
||||
this.promptSentDedupeByPaneKey.delete(entry.stablePaneKey)
|
||||
}
|
||||
aliasChanged = true
|
||||
@@ -1400,6 +1581,27 @@ export class AgentHookServer {
|
||||
return this.legacyPaneKeyAliases.get(paneKey)?.stablePaneKey ?? paneKey
|
||||
}
|
||||
|
||||
private revokeHydratedAuthorityForPaneKeys(paneKeys: ReadonlySet<string>): boolean {
|
||||
let changed = false
|
||||
for (const commitment of this.hydratedAuthorityCommitments) {
|
||||
if (
|
||||
paneKeys.has(commitment.paneKey) ||
|
||||
paneKeys.has(this.resolvePaneKeyAlias(commitment.paneKey))
|
||||
) {
|
||||
this.revokedHydratedAuthorityCommitments.add(commitment)
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
for (const paneKey of paneKeys) {
|
||||
const resolvedPaneKey = this.resolvePaneKeyAlias(paneKey)
|
||||
changed = this.hydratedLaunchTokenHashByPaneKey.delete(paneKey) || changed
|
||||
changed = this.hydratedLaunchTokenHashByPaneKey.delete(resolvedPaneKey) || changed
|
||||
changed = this.persistedAuthorityCommitmentsByPaneKey.delete(paneKey) || changed
|
||||
changed = this.persistedAuthorityCommitmentsByPaneKey.delete(resolvedPaneKey) || changed
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
private normalizeHookBodyPaneKeyAlias(body: unknown): unknown {
|
||||
if (typeof body !== 'object' || body === null) {
|
||||
return body
|
||||
@@ -1463,12 +1665,31 @@ export class AgentHookServer {
|
||||
) {
|
||||
return
|
||||
}
|
||||
// Why: the OSC 9999 wire payload has no providerSession field at all, so an OSC observation is
|
||||
// never evidence that the session ended — yet overwriting the row dropped the cached identity.
|
||||
// That erased it from persisted rows (lost across restart) and from headless `orca serve`, which
|
||||
// serves these rows to mobile directly instead of the renderer store, blanking Chat UI (#10630).
|
||||
// A new turn after `done` still starts clean so a reused pane cannot inherit a finished session.
|
||||
// Why: mirror resolveAgentStatusIdentity, which treats a literal 'unknown' exactly like an
|
||||
// omitted type — an OSC ping that names no agent makes no claim about the pane's identity, so
|
||||
// it must not be read as a mismatch and strip the session the renderer would have kept.
|
||||
const claimedAgentType =
|
||||
event.payload.agentType && event.payload.agentType !== 'unknown'
|
||||
? event.payload.agentType
|
||||
: undefined
|
||||
const preservedProviderSession =
|
||||
previous?.providerSession &&
|
||||
(claimedAgentType === undefined || claimedAgentType === previous.payload.agentType) &&
|
||||
(previous.payload.state !== 'done' || event.payload.state === 'done')
|
||||
? previous.providerSession
|
||||
: undefined
|
||||
// Why: OSC status is a runtime observation, not a prompt boundary; keep prompt-sent telemetry tied to native hooks.
|
||||
this.applyNormalizedStatus({
|
||||
paneKey,
|
||||
tabId,
|
||||
worktreeId,
|
||||
connectionId,
|
||||
...(preservedProviderSession ? { providerSession: preservedProviderSession } : {}),
|
||||
payload: event.payload
|
||||
})
|
||||
}
|
||||
@@ -1602,6 +1823,7 @@ export class AgentHookServer {
|
||||
isReplay: envelope.isReplay === true ? true : undefined,
|
||||
payload: normalizedPayload
|
||||
}
|
||||
this.recordCurrentAuthorityObservation(event)
|
||||
this.applyNormalizedStatus(event)
|
||||
}
|
||||
|
||||
@@ -1632,6 +1854,7 @@ export class AgentHookServer {
|
||||
if (this.lastStatusFilePath) {
|
||||
this.hydrateLastStatusFromDisk()
|
||||
}
|
||||
this.captureHydratedAuthorityCommitments()
|
||||
const handleRequest = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
|
||||
if (req.method !== 'POST') {
|
||||
res.writeHead(404)
|
||||
@@ -1673,6 +1896,7 @@ export class AgentHookServer {
|
||||
const aliasedBody = this.normalizeHookBodyPaneKeyAlias(body)
|
||||
const normalized = normalizeHookPayload(this.state, source, aliasedBody, this.env)
|
||||
if (normalized && !this.shouldSuppressClosedTabStatus(normalized.paneKey)) {
|
||||
this.recordCurrentAuthorityObservation(normalized)
|
||||
const enriched = this.applyNormalizedStatus(normalized)
|
||||
this.scheduleAssistantMessageRetry(source, aliasedBody, enriched)
|
||||
this.scheduleCodexSubagentPoll(source, aliasedBody, enriched)
|
||||
@@ -1739,6 +1963,11 @@ export class AgentHookServer {
|
||||
this.lastStatusFilePath = null
|
||||
this.lastWrittenJson = null
|
||||
this.runtimeObservedStatusPaneKeys.clear()
|
||||
this.hydratedAuthorityCommitments = Object.freeze([])
|
||||
this.hydratedLaunchTokenHashByPaneKey.clear()
|
||||
this.persistedAuthorityCommitmentsByPaneKey.clear()
|
||||
this.revokedHydratedAuthorityCommitments = new WeakSet()
|
||||
this.currentAuthorityObservations.clear()
|
||||
this.promptSentDedupeByPaneKey.clear()
|
||||
this.closedAgentStatusTabIds.clear()
|
||||
this.closedAgentStatusPaneKeys.clear()
|
||||
@@ -1750,7 +1979,7 @@ export class AgentHookServer {
|
||||
|
||||
/** 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 {
|
||||
if (!this.deleteStatusEntry(paneKey)) {
|
||||
if (!this.deleteStatusEntry(paneKey, { preserveAuthority: true })) {
|
||||
return
|
||||
}
|
||||
this.scheduleStatusPersist()
|
||||
@@ -1775,7 +2004,7 @@ export class AgentHookServer {
|
||||
if (entry.connectionId !== normalizedConnectionId) {
|
||||
continue
|
||||
}
|
||||
const deleted = this.deleteStatusEntry(paneKey)
|
||||
const deleted = this.deleteStatusEntry(paneKey, { preserveAuthority: true })
|
||||
if (deleted) {
|
||||
statusChanged = true
|
||||
if (deleted.payload.agentType === 'codex') {
|
||||
@@ -1785,6 +2014,11 @@ export class AgentHookServer {
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const [paneKey, evidence] of this.currentAuthorityObservations) {
|
||||
if (evidence.connectionId === normalizedConnectionId) {
|
||||
this.currentAuthorityObservations.delete(paneKey)
|
||||
}
|
||||
}
|
||||
if (statusChanged) {
|
||||
// Why: persist/notify once — one disconnect can own many panes.
|
||||
this.scheduleStatusPersist()
|
||||
@@ -1798,7 +2032,10 @@ export class AgentHookServer {
|
||||
})
|
||||
}
|
||||
|
||||
private deleteStatusEntry(paneKey: string): EnrichedAgentHookEventPayload | null {
|
||||
private deleteStatusEntry(
|
||||
paneKey: string,
|
||||
options?: { preserveAuthority?: boolean }
|
||||
): EnrichedAgentHookEventPayload | null {
|
||||
const resolvedPaneKey = this.resolvePaneKeyAlias(paneKey)
|
||||
const existing = this.state.lastStatusByPaneKey.get(resolvedPaneKey) as
|
||||
| EnrichedAgentHookEventPayload
|
||||
@@ -1807,9 +2044,14 @@ export class AgentHookServer {
|
||||
return null
|
||||
}
|
||||
this.state.lastStatusByPaneKey.delete(resolvedPaneKey)
|
||||
if (!options?.preserveAuthority) {
|
||||
this.hydratedLaunchTokenHashByPaneKey.delete(resolvedPaneKey)
|
||||
this.persistedAuthorityCommitmentsByPaneKey.delete(resolvedPaneKey)
|
||||
}
|
||||
this.clearAssistantMessageRetry(resolvedPaneKey)
|
||||
this.clearCodexSubagentPoll(resolvedPaneKey)
|
||||
this.runtimeObservedStatusPaneKeys.delete(resolvedPaneKey)
|
||||
this.currentAuthorityObservations.delete(resolvedPaneKey)
|
||||
if (existing.payload.state === 'done') {
|
||||
this.promptSentDedupeByPaneKey.delete(resolvedPaneKey)
|
||||
}
|
||||
@@ -1854,6 +2096,11 @@ export class AgentHookServer {
|
||||
paneKeysToClear.add(paneKey)
|
||||
}
|
||||
}
|
||||
for (const commitment of this.hydratedAuthorityCommitments) {
|
||||
if (paneCacheKeyMatchesTab(commitment.paneKey, tabId)) {
|
||||
paneKeysToClear.add(commitment.paneKey)
|
||||
}
|
||||
}
|
||||
|
||||
let aliasChanged = false
|
||||
for (const [legacyPaneKey, entry] of this.legacyPaneKeyAliases) {
|
||||
@@ -1867,6 +2114,7 @@ export class AgentHookServer {
|
||||
aliasChanged = true
|
||||
}
|
||||
}
|
||||
const authorityChanged = this.revokeHydratedAuthorityForPaneKeys(paneKeysToClear)
|
||||
|
||||
let statusChanged = false
|
||||
for (const paneKey of paneKeysToClear) {
|
||||
@@ -1877,12 +2125,13 @@ export class AgentHookServer {
|
||||
this.clearCodexSubagentPoll(paneKey)
|
||||
clearPaneCacheState(this.state, paneKey)
|
||||
this.runtimeObservedStatusPaneKeys.delete(paneKey)
|
||||
this.currentAuthorityObservations.delete(paneKey)
|
||||
this.promptSentDedupeByPaneKey.delete(paneKey)
|
||||
}
|
||||
if (aliasChanged) {
|
||||
this.notifyPaneKeyAliasPersistenceListener()
|
||||
}
|
||||
if (statusChanged) {
|
||||
if (statusChanged || authorityChanged) {
|
||||
this.scheduleStatusPersist()
|
||||
this.notifyStatusChangeListeners()
|
||||
}
|
||||
@@ -1890,25 +2139,31 @@ export class AgentHookServer {
|
||||
|
||||
clearPaneState(paneKey: string): void {
|
||||
const resolvedPaneKey = this.resolvePaneKeyAlias(paneKey)
|
||||
const paneKeys = new Set([paneKey, resolvedPaneKey])
|
||||
// Why: only persist when a status entry was actually evicted; dropping prompt/tool caches doesn't change the file.
|
||||
const hadStatus = this.state.lastStatusByPaneKey.has(resolvedPaneKey)
|
||||
this.clearAssistantMessageRetry(resolvedPaneKey)
|
||||
this.clearCodexSubagentPoll(resolvedPaneKey)
|
||||
clearPaneCacheState(this.state, resolvedPaneKey)
|
||||
this.currentAuthorityObservations.delete(resolvedPaneKey)
|
||||
this.promptSentDedupeByPaneKey.delete(resolvedPaneKey)
|
||||
let clearedAlias = false
|
||||
for (const [legacyPaneKey, stablePaneKey] of this.legacyPaneKeyAliases) {
|
||||
if (stablePaneKey.stablePaneKey === resolvedPaneKey) {
|
||||
this.legacyPaneKeyAliases.delete(legacyPaneKey)
|
||||
paneKeys.add(legacyPaneKey)
|
||||
paneKeys.add(stablePaneKey.stablePaneKey)
|
||||
clearPaneCacheState(this.state, legacyPaneKey)
|
||||
this.currentAuthorityObservations.delete(legacyPaneKey)
|
||||
this.promptSentDedupeByPaneKey.delete(legacyPaneKey)
|
||||
clearedAlias = true
|
||||
}
|
||||
}
|
||||
const authorityChanged = this.revokeHydratedAuthorityForPaneKeys(paneKeys)
|
||||
if (clearedAlias) {
|
||||
this.notifyPaneKeyAliasPersistenceListener()
|
||||
}
|
||||
if (hadStatus) {
|
||||
if (hadStatus || authorityChanged) {
|
||||
this.runtimeObservedStatusPaneKeys.delete(resolvedPaneKey)
|
||||
this.scheduleStatusPersist()
|
||||
this.notifyStatusChangeListeners()
|
||||
@@ -1963,6 +2218,8 @@ export class AgentHookServer {
|
||||
}
|
||||
// Why: keep hydrate idempotent so a future re-start path can't merge prior-session state.
|
||||
this.state.lastStatusByPaneKey.clear()
|
||||
this.hydratedLaunchTokenHashByPaneKey.clear()
|
||||
this.persistedAuthorityCommitmentsByPaneKey.clear()
|
||||
let raw: string
|
||||
try {
|
||||
raw = readFileSync(this.lastStatusFilePath, 'utf8')
|
||||
@@ -2001,6 +2258,7 @@ export class AgentHookServer {
|
||||
let hydrated = 0
|
||||
let dropped = 0
|
||||
let prunedLegacyClaudeSubagents = 0
|
||||
let scrubbedLegacyLaunchTokens = 0
|
||||
// Why: drop entries older than HYDRATE_MAX_AGE_MS to bound disk growth (one Date.now() for a consistent cutoff).
|
||||
const ttlCutoff = Date.now() - HYDRATE_MAX_AGE_MS
|
||||
for (const [paneKey, rawEntry] of Object.entries(entries)) {
|
||||
@@ -2011,6 +2269,21 @@ export class AgentHookServer {
|
||||
: { ...(rawEntry as Record<string, unknown>), paneKey: resolvedPaneKey }
|
||||
const entry = sanitizeHydratedEntry(resolvedPaneKey, rawResolvedEntry)
|
||||
if (entry && entry.receivedAt >= ttlCutoff) {
|
||||
const launchTokenHash = readPersistedLaunchTokenHash(rawResolvedEntry)
|
||||
if (launchTokenHash) {
|
||||
this.hydratedLaunchTokenHashByPaneKey.set(resolvedPaneKey, launchTokenHash)
|
||||
const evidence = this.toAuthorityEvidence(entry, launchTokenHash)
|
||||
if (evidence) {
|
||||
this.persistedAuthorityCommitmentsByPaneKey.set(resolvedPaneKey, evidence)
|
||||
}
|
||||
}
|
||||
if (
|
||||
typeof rawResolvedEntry === 'object' &&
|
||||
rawResolvedEntry !== null &&
|
||||
typeof (rawResolvedEntry as Record<string, unknown>).launchToken === 'string'
|
||||
) {
|
||||
scrubbedLegacyLaunchTokens += 1
|
||||
}
|
||||
const hydratedPayload = dropHydratedIdleClaudeSubagents(entry.payload)
|
||||
if (hydratedPayload !== entry.payload) {
|
||||
prunedLegacyClaudeSubagents +=
|
||||
@@ -2041,13 +2314,30 @@ export class AgentHookServer {
|
||||
dropped += 1
|
||||
}
|
||||
}
|
||||
for (const [paneKey, rawCommitment] of Object.entries(file.authorityCommitments ?? {})) {
|
||||
const resolvedPaneKey = this.resolvePaneKeyAlias(paneKey)
|
||||
const commitment = sanitizePersistedAuthorityCommitment(resolvedPaneKey, rawCommitment)
|
||||
if (!commitment || commitment.observedAt < ttlCutoff) {
|
||||
dropped += 1
|
||||
continue
|
||||
}
|
||||
const existing = this.persistedAuthorityCommitmentsByPaneKey.get(resolvedPaneKey)
|
||||
if (existing && !authorityCommitmentsMatch(existing, commitment)) {
|
||||
this.persistedAuthorityCommitmentsByPaneKey.delete(resolvedPaneKey)
|
||||
this.hydratedLaunchTokenHashByPaneKey.delete(resolvedPaneKey)
|
||||
dropped += 1
|
||||
continue
|
||||
}
|
||||
this.persistedAuthorityCommitmentsByPaneKey.set(resolvedPaneKey, commitment)
|
||||
this.hydratedLaunchTokenHashByPaneKey.set(resolvedPaneKey, commitment.launchTokenHash)
|
||||
}
|
||||
if (dropped > 0) {
|
||||
console.warn(
|
||||
`[agent-hooks] last-status hydrate dropped ${dropped} entries (kept ${hydrated})`
|
||||
)
|
||||
}
|
||||
if (dropped > 0 || prunedLegacyClaudeSubagents > 0) {
|
||||
// Why: persist load-time pruning once so legacy idle rows aren't re-parsed every launch.
|
||||
if (dropped > 0 || prunedLegacyClaudeSubagents > 0 || scrubbedLegacyLaunchTokens > 0) {
|
||||
// Why: persist load-time pruning and bearer scrubbing once.
|
||||
this.runStatusPersist()
|
||||
} else if (hydrated > 0) {
|
||||
// Why: prime dedup from raw bytes (not re-serialized) only when hydration was lossless.
|
||||
@@ -2055,17 +2345,92 @@ export class AgentHookServer {
|
||||
}
|
||||
}
|
||||
|
||||
private captureHydratedAuthorityCommitments(): void {
|
||||
this.revokedHydratedAuthorityCommitments = new WeakSet()
|
||||
for (const entry of this.state.lastStatusByPaneKey.values()) {
|
||||
const evidence = this.toAuthorityEvidence(
|
||||
entry as EnrichedAgentHookEventPayload,
|
||||
this.hydratedLaunchTokenHashByPaneKey.get(entry.paneKey)
|
||||
)
|
||||
if (evidence && !this.persistedAuthorityCommitmentsByPaneKey.has(entry.paneKey)) {
|
||||
this.persistedAuthorityCommitmentsByPaneKey.set(entry.paneKey, evidence)
|
||||
}
|
||||
}
|
||||
this.hydratedAuthorityCommitments = Object.freeze(
|
||||
Array.from(this.persistedAuthorityCommitmentsByPaneKey.values())
|
||||
)
|
||||
}
|
||||
|
||||
private recordCurrentAuthorityObservation(payload: AgentHookEventPayload): void {
|
||||
const evidence = this.toAuthorityEvidence(payload)
|
||||
if (evidence) {
|
||||
this.currentAuthorityObservations.set(evidence.paneKey, evidence)
|
||||
this.persistedAuthorityCommitmentsByPaneKey.set(evidence.paneKey, evidence)
|
||||
this.hydratedLaunchTokenHashByPaneKey.set(evidence.paneKey, evidence.launchTokenHash)
|
||||
}
|
||||
}
|
||||
|
||||
private toAuthorityEvidence(
|
||||
payload: AgentHookEventPayload | EnrichedAgentHookEventPayload,
|
||||
launchTokenHashOverride?: string
|
||||
): AgentHookAuthorityEvidence | null {
|
||||
const launchToken = payload.launchToken?.trim()
|
||||
const launchTokenHash =
|
||||
launchTokenHashOverride ??
|
||||
(launchToken ? createHash('sha256').update(launchToken).digest('hex') : null)
|
||||
if (!launchTokenHash) {
|
||||
return null
|
||||
}
|
||||
return Object.freeze({
|
||||
paneKey: payload.paneKey,
|
||||
launchTokenHash,
|
||||
connectionId: payload.connectionId,
|
||||
...(payload.tabId ? { tabId: payload.tabId } : {}),
|
||||
...(payload.worktreeId ? { worktreeId: payload.worktreeId } : {}),
|
||||
observedAt: 'receivedAt' in payload ? payload.receivedAt : Date.now()
|
||||
})
|
||||
}
|
||||
|
||||
private serializeStatusFile(): string {
|
||||
const entries: Record<string, EnrichedAgentHookEventPayload> = {}
|
||||
const entries: Record<string, PersistedAgentHookEventPayload> = {}
|
||||
const authorityCommitments: Record<string, PersistedAgentHookAuthorityCommitment> = {}
|
||||
const conflictedCommitments = new Set<string>()
|
||||
for (const [paneKey, commitment] of this.persistedAuthorityCommitmentsByPaneKey) {
|
||||
authorityCommitments[paneKey] = { ...commitment }
|
||||
}
|
||||
for (const [paneKey, payload] of this.state.lastStatusByPaneKey) {
|
||||
// Why: never persist invalid keys (matches the hydrate-path invariant).
|
||||
if (!isValidPaneKey(paneKey)) {
|
||||
continue
|
||||
}
|
||||
const { promptInteractionKey: _promptInteractionKey, ...persistedPayload } = payload
|
||||
entries[paneKey] = persistedPayload as EnrichedAgentHookEventPayload
|
||||
const {
|
||||
promptInteractionKey: _promptInteractionKey,
|
||||
launchToken,
|
||||
...persistedPayload
|
||||
} = payload as EnrichedAgentHookEventPayload
|
||||
const launchTokenHash = launchToken?.trim()
|
||||
? createHash('sha256').update(launchToken.trim()).digest('hex')
|
||||
: this.hydratedLaunchTokenHashByPaneKey.get(paneKey)
|
||||
entries[paneKey] = {
|
||||
...persistedPayload,
|
||||
...(launchTokenHash ? { launchTokenHash } : {})
|
||||
}
|
||||
const commitment = this.toAuthorityEvidence(payload, launchTokenHash)
|
||||
if (commitment && !conflictedCommitments.has(paneKey)) {
|
||||
const existing = authorityCommitments[paneKey]
|
||||
if (existing && !authorityCommitmentsMatch(existing, commitment)) {
|
||||
delete authorityCommitments[paneKey]
|
||||
conflictedCommitments.add(paneKey)
|
||||
} else {
|
||||
authorityCommitments[paneKey] = { ...commitment }
|
||||
}
|
||||
}
|
||||
}
|
||||
const file: LastStatusFile = {
|
||||
version: LAST_STATUS_FILE_VERSION,
|
||||
entries,
|
||||
authorityCommitments
|
||||
}
|
||||
const file: LastStatusFile = { version: LAST_STATUS_FILE_VERSION, entries }
|
||||
return JSON.stringify(file)
|
||||
}
|
||||
|
||||
|
||||
@@ -11,4 +11,18 @@ describe('packaged Windows CLI launcher asset', () => {
|
||||
expect(launcher).toContain('orca.cmd cannot safely forward orchestration message bodies')
|
||||
expect(launcher).not.toContain('"%ELECTRON%" "%CLI%" %*')
|
||||
})
|
||||
|
||||
it('marks the packaged child and propagates its exact exit status', () => {
|
||||
const sourcePath = join(process.cwd(), 'native', 'windows-cli-launcher', 'OrcaCliLauncher.cs')
|
||||
const source = readFileSync(sourcePath, 'utf8')
|
||||
|
||||
expect(source).toContain(
|
||||
'startInfo.EnvironmentVariables["ORCA_WINDOWS_PACKAGED_CLI_LAUNCHER"] = "1";'
|
||||
)
|
||||
expect(source).toContain('Environment.GetEnvironmentVariable("ORCA_CLI_COMMAND") == "orca-ide"')
|
||||
expect(source).toContain('? "orca-ide"')
|
||||
expect(source).toContain(': "orca";')
|
||||
expect(source).toContain('child.WaitForExit();')
|
||||
expect(source).toContain('return child.ExitCode;')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -299,6 +299,16 @@ export class HeadlessEmulator {
|
||||
return lines
|
||||
}
|
||||
|
||||
getBufferTailLines(limit: number): string[] {
|
||||
const buffer = this.terminal.buffer.active
|
||||
const start = Math.max(0, buffer.length - Math.max(0, Math.floor(limit)))
|
||||
const lines: string[] = []
|
||||
for (let row = start; row < buffer.length; row += 1) {
|
||||
lines.push(buffer.getLine(row)?.translateToString(true) ?? '')
|
||||
}
|
||||
return lines
|
||||
}
|
||||
|
||||
getCwd(): string | null {
|
||||
return this.oscText.cwd
|
||||
}
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as WslModule from '../wsl'
|
||||
|
||||
vi.mock('../wsl', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof WslModule>()),
|
||||
getDefaultWslDistro: () => 'Ubuntu'
|
||||
}))
|
||||
|
||||
import { TerminalHost } from './terminal-host'
|
||||
import type { SubprocessHandle } from './session'
|
||||
import { resolveWslSessionContext } from './wsl-session-context'
|
||||
@@ -60,6 +67,40 @@ describe('TerminalHost WSL context', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('persists the resolved default distro across daemon attaches', async () => {
|
||||
const spawnSubprocess = vi.fn(() => createSubprocess())
|
||||
host = new TerminalHost({ spawnSubprocess })
|
||||
const platform = Object.getOwnPropertyDescriptor(process, 'platform')
|
||||
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
|
||||
try {
|
||||
const created = await host.createOrAttach({
|
||||
sessionId: 'session-default-wsl',
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
cwd: 'C:\\Users\\jin\\repo',
|
||||
shellOverride: 'wsl.exe',
|
||||
terminalWindowsWslDistro: null,
|
||||
streamClient: { onData: vi.fn(), onExit: vi.fn() }
|
||||
})
|
||||
const attached = await host.createOrAttach({
|
||||
sessionId: 'session-default-wsl',
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
shellOverride: 'wsl.exe',
|
||||
terminalWindowsWslDistro: 'Debian',
|
||||
streamClient: { onData: vi.fn(), onExit: vi.fn() }
|
||||
})
|
||||
|
||||
expect(created.wslDistro).toBe('Ubuntu')
|
||||
expect(attached.wslDistro).toBe('Ubuntu')
|
||||
expect(spawnSubprocess).toHaveBeenCalledOnce()
|
||||
} finally {
|
||||
if (platform) {
|
||||
Object.defineProperty(process, 'platform', platform)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('returns authoritative null when a native session is attached with a WSL preference', async () => {
|
||||
const spawnSubprocess = vi.fn(() => createSubprocess())
|
||||
host = new TerminalHost({ spawnSubprocess })
|
||||
@@ -118,6 +159,13 @@ describe('TerminalHost WSL context', () => {
|
||||
terminalWindowsWslDistro: ' Ubuntu '
|
||||
})
|
||||
).toEqual({ distro: 'Ubuntu', treatPosixCwdAsWsl: true })
|
||||
expect(
|
||||
resolveWslSessionContext({
|
||||
cwd: 'C:\\Users\\jin\\repo',
|
||||
shellOverride: 'wsl.exe',
|
||||
terminalWindowsWslDistro: null
|
||||
})
|
||||
).toEqual({ distro: 'Ubuntu', treatPosixCwdAsWsl: true })
|
||||
} finally {
|
||||
if (platform) {
|
||||
Object.defineProperty(process, 'platform', platform)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { splitWorktreeIdForFilesystem } from '../../shared/worktree-id'
|
||||
import { isWslShellName } from '../../shared/local-windows-terminal-runtime'
|
||||
import { parseWslPath } from '../wsl'
|
||||
import { getDefaultWslDistro, parseWslPath } from '../wsl'
|
||||
import { parsePtySessionId } from './pty-session-id'
|
||||
import { parseWslUncPath } from '../../shared/wsl-paths'
|
||||
|
||||
@@ -41,7 +41,8 @@ export function resolveWslSessionContext(args: {
|
||||
return (
|
||||
(args.sessionId ? getWslContextFromSessionId(args.sessionId) : undefined) ??
|
||||
(isWslShellName(args.shellOverride)
|
||||
? getWslContextFromPreferredDistro(args.terminalWindowsWslDistro)
|
||||
? (getWslContextFromPreferredDistro(args.terminalWindowsWslDistro) ??
|
||||
getWslContextFromPreferredDistro(getDefaultWslDistro()))
|
||||
: undefined)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -65,6 +65,7 @@ import {
|
||||
updateMRReviewers
|
||||
} from './client'
|
||||
import { __resetRepoDefaultBranchCacheForTests } from '../source-control/repo-default-branch'
|
||||
import { _resetKnownHostsCache } from './gitlab-known-host-probe'
|
||||
|
||||
/** Answer the real default-branch resolver probes (#9171 guard). */
|
||||
function primeGitDefaultBranch(defaultRef = 'refs/remotes/origin/main'): void {
|
||||
@@ -92,6 +93,7 @@ describe('gitlab client — MR operations', () => {
|
||||
gitExecFileAsyncMock.mockReset()
|
||||
primeGitDefaultBranch()
|
||||
__resetRepoDefaultBranchCacheForTests()
|
||||
_resetKnownHostsCache()
|
||||
_resetGitLabRateLimitCache()
|
||||
getGlabKnownHostsMock.mockResolvedValue(['gitlab.com'])
|
||||
resolveIssueSourceMock.mockResolvedValue({
|
||||
@@ -288,6 +290,39 @@ describe('gitlab client — MR operations', () => {
|
||||
allowDefaultWslFallback: false
|
||||
})
|
||||
})
|
||||
|
||||
it('merges many authenticated hosts with one cache scan', async () => {
|
||||
const hostCount = 256
|
||||
glabExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: Array.from(
|
||||
{ length: hostCount },
|
||||
(_, index) => `Logged in to gitlab-${index}.example.test as user`
|
||||
).join('\n'),
|
||||
stderr: ''
|
||||
})
|
||||
const originalMap = Array.prototype.map
|
||||
let knownHostCacheScans = 0
|
||||
const mapSpy = vi.spyOn(Array.prototype, 'map').mockImplementation(function (
|
||||
this: unknown[],
|
||||
callback: (value: unknown, index: number, array: unknown[]) => unknown,
|
||||
thisArg?: unknown
|
||||
): unknown[] {
|
||||
if (this[0] === 'gitlab.com' && this.every((value) => typeof value === 'string')) {
|
||||
knownHostCacheScans += 1
|
||||
}
|
||||
return Reflect.apply(originalMap, this, [callback, thisArg])
|
||||
})
|
||||
|
||||
try {
|
||||
await expect(diagnoseAuth()).resolves.toMatchObject({
|
||||
authenticated: true,
|
||||
hosts: expect.any(Array)
|
||||
})
|
||||
} finally {
|
||||
mapSpy.mockRestore()
|
||||
}
|
||||
expect(knownHostCacheScans).toBe(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getRateLimit', () => {
|
||||
|
||||
@@ -39,6 +39,7 @@ import {
|
||||
type LocalGitExecOptions,
|
||||
type ProjectRef
|
||||
} from './gl-utils'
|
||||
import { rememberGlabKnownHosts } from './gitlab-known-host-probe'
|
||||
import type { IssueListState } from './issues'
|
||||
import {
|
||||
hasHostedReviewLocalGitOptions,
|
||||
@@ -100,6 +101,8 @@ export async function diagnoseAuth(): Promise<GitLabAuthDiagnostic> {
|
||||
})
|
||||
const output = `${stdout}\n${stderr}`
|
||||
const hosts = parseGlabAuthStatusHosts(output)
|
||||
// Why: refreshing auth must advance the provider cache key past a stale null result.
|
||||
rememberGlabKnownHosts(hosts)
|
||||
return {
|
||||
glabAvailable: true,
|
||||
authenticated:
|
||||
|
||||
@@ -32,13 +32,30 @@ export function rememberGlabKnownHost(
|
||||
connectionId?: string | null,
|
||||
localGitOptions: LocalGitExecOptions = {}
|
||||
): void {
|
||||
const normalizedHost = normalizeGitLabHost(host)
|
||||
rememberGlabKnownHosts([host], connectionId, localGitOptions)
|
||||
}
|
||||
|
||||
export function rememberGlabKnownHosts(
|
||||
hosts: readonly string[],
|
||||
connectionId?: string | null,
|
||||
localGitOptions: LocalGitExecOptions = {}
|
||||
): void {
|
||||
const key = knownHostsExecutionKey(connectionId, localGitOptions)
|
||||
const cached = knownHostsCacheByExecutionContext.get(key)
|
||||
if (!cached || cached.map(normalizeGitLabHost).includes(normalizedHost)) {
|
||||
const cached = knownHostsCacheByExecutionContext.get(key) ?? DEFAULT_GITLAB_HOSTS
|
||||
const seen = new Set(cached.map(normalizeGitLabHost))
|
||||
const additions: string[] = []
|
||||
for (const host of hosts) {
|
||||
const normalizedHost = normalizeGitLabHost(host)
|
||||
if (seen.has(normalizedHost)) {
|
||||
continue
|
||||
}
|
||||
seen.add(normalizedHost)
|
||||
additions.push(normalizedHost)
|
||||
}
|
||||
if (additions.length === 0) {
|
||||
return
|
||||
}
|
||||
knownHostsCacheByExecutionContext.set(key, [...cached, normalizedHost])
|
||||
knownHostsCacheByExecutionContext.set(key, [...cached, ...additions])
|
||||
}
|
||||
|
||||
export async function getGlabKnownHosts(
|
||||
@@ -80,12 +97,13 @@ async function probeGlabKnownHosts(
|
||||
: {})
|
||||
})
|
||||
const hosts = parseGlabAuthStatusHosts(`${stdout}\n${stderr}`)
|
||||
const merged = Array.from(new Set([...DEFAULT_GITLAB_HOSTS, ...hosts]))
|
||||
const remembered = knownHostsCacheByExecutionContext.get(key) ?? []
|
||||
const merged = Array.from(new Set([...DEFAULT_GITLAB_HOSTS, ...remembered, ...hosts]))
|
||||
knownHostsCacheByExecutionContext.set(key, merged)
|
||||
return merged
|
||||
} catch {
|
||||
// Keep failures uncached so auth or tunnel recovery is discovered later.
|
||||
return [...DEFAULT_GITLAB_HOSTS]
|
||||
return knownHostsCacheByExecutionContext.get(key) ?? [...DEFAULT_GITLAB_HOSTS]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
parseGlabAuthStatusHosts,
|
||||
resolveIssueSource
|
||||
} from './gl-utils'
|
||||
import { rememberGlabKnownHost, rememberGlabKnownHosts } from './gitlab-known-host-probe'
|
||||
import { registerSshGitProvider, unregisterSshGitProvider } from '../providers/ssh-git-dispatch'
|
||||
|
||||
describe('gitlab project ref resolution', () => {
|
||||
@@ -503,6 +504,90 @@ describe('getGlabKnownHosts', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves a native auth refresh while an older native probe is in flight', async () => {
|
||||
let resolveProbe!: (value: { stdout: string; stderr: string }) => void
|
||||
glabExecFileAsyncMock.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
resolveProbe = resolve
|
||||
})
|
||||
)
|
||||
|
||||
const staleProbe = getGlabKnownHosts()
|
||||
rememberGlabKnownHost('gitlab.refreshed.test')
|
||||
resolveProbe({ stdout: 'Logged in to gitlab.com as user\n', stderr: '' })
|
||||
|
||||
await expect(staleProbe).resolves.toEqual(['gitlab.com', 'gitlab.refreshed.test'])
|
||||
await expect(getGlabKnownHosts()).resolves.toEqual(['gitlab.com', 'gitlab.refreshed.test'])
|
||||
})
|
||||
|
||||
it('preserves a native auth refresh when an older native probe fails', async () => {
|
||||
let rejectProbe!: (error: Error) => void
|
||||
glabExecFileAsyncMock.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((_resolve, reject) => {
|
||||
rejectProbe = reject
|
||||
})
|
||||
)
|
||||
|
||||
const staleProbe = getGlabKnownHosts()
|
||||
rememberGlabKnownHost('gitlab.refreshed.test')
|
||||
rejectProbe(new Error('stale auth probe failed'))
|
||||
|
||||
await expect(staleProbe).resolves.toEqual(['gitlab.com', 'gitlab.refreshed.test'])
|
||||
await expect(getGlabKnownHosts()).resolves.toEqual(['gitlab.com', 'gitlab.refreshed.test'])
|
||||
})
|
||||
|
||||
it('keeps a remembered native host out of WSL and SSH caches', async () => {
|
||||
glabExecFileAsyncMock
|
||||
.mockResolvedValueOnce({ stdout: 'Logged in to native.test as user\n', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: 'Logged in to wsl.test as user\n', stderr: '' })
|
||||
.mockResolvedValueOnce({ stdout: 'Logged in to ssh.test as user\n', stderr: '' })
|
||||
|
||||
await Promise.all([
|
||||
getGlabKnownHosts(),
|
||||
getGlabKnownHosts(undefined, { wslDistro: 'Ubuntu' }),
|
||||
getGlabKnownHosts('conn-1')
|
||||
])
|
||||
rememberGlabKnownHost('gitlab.refreshed.test')
|
||||
|
||||
await expect(getGlabKnownHosts()).resolves.toEqual([
|
||||
'gitlab.com',
|
||||
'native.test',
|
||||
'gitlab.refreshed.test'
|
||||
])
|
||||
await expect(getGlabKnownHosts(undefined, { wslDistro: 'Ubuntu' })).resolves.toEqual([
|
||||
'gitlab.com',
|
||||
'wsl.test'
|
||||
])
|
||||
await expect(getGlabKnownHosts('conn-1')).resolves.toEqual(['gitlab.com', 'ssh.test'])
|
||||
})
|
||||
|
||||
it('batch-normalizes and deduplicates hosts in first-seen order per execution context', async () => {
|
||||
rememberGlabKnownHosts([' Native-B.test ', 'native-a.test', 'NATIVE-B.TEST'])
|
||||
rememberGlabKnownHosts(['WSL-B.test', ' wsl-a.test ', 'wsl-b.test'], undefined, {
|
||||
wslDistro: 'Ubuntu'
|
||||
})
|
||||
rememberGlabKnownHosts(['SSH-B.test', 'ssh-a.test', ' ssh-b.test '], 'conn-batch')
|
||||
|
||||
await expect(getGlabKnownHosts()).resolves.toEqual([
|
||||
'gitlab.com',
|
||||
'native-b.test',
|
||||
'native-a.test'
|
||||
])
|
||||
await expect(getGlabKnownHosts(undefined, { wslDistro: 'Ubuntu' })).resolves.toEqual([
|
||||
'gitlab.com',
|
||||
'wsl-b.test',
|
||||
'wsl-a.test'
|
||||
])
|
||||
await expect(getGlabKnownHosts('conn-batch')).resolves.toEqual([
|
||||
'gitlab.com',
|
||||
'ssh-b.test',
|
||||
'ssh-a.test'
|
||||
])
|
||||
expect(glabExecFileAsyncMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('recognizes a self-hosted host on a non-default port', async () => {
|
||||
glabExecFileAsyncMock.mockResolvedValueOnce({
|
||||
stdout: '✓ Logged in to gitlab.example.com:8080 as user\n',
|
||||
|
||||
+30
-2
@@ -30,7 +30,12 @@ import {
|
||||
getSshPtyProvider,
|
||||
registerHeadlessPtyRuntime
|
||||
} from './ipc/pty'
|
||||
import { initDaemonPtyProvider, disconnectDaemon, shutdownDaemon } from './daemon/daemon-init'
|
||||
import {
|
||||
initDaemonPtyProvider,
|
||||
disconnectDaemon,
|
||||
getDaemonProvider,
|
||||
shutdownDaemon
|
||||
} from './daemon/daemon-init'
|
||||
import { closeAllWatchers } from './ipc/filesystem-watcher'
|
||||
import { disposeWorktreeBaseDirectoryWatchers } from './ipc/worktree-base-directory-watcher'
|
||||
import { registerCoreHandlers } from './ipc/register-core-handlers'
|
||||
@@ -132,6 +137,7 @@ import {
|
||||
import { maybeRedirectAppImageCliLaunch } from './startup/appimage-cli-redirect'
|
||||
import { maybeRedirectPackagedCliEntryLaunch } from './startup/packaged-cli-entry-redirect'
|
||||
import { startFirstWindowStartupServices } from './startup/first-window-startup-services'
|
||||
import { recoverLegacyWorkerTerminalsForRendererStartup } from './startup/legacy-worker-renderer-recovery'
|
||||
import { createWslCliReconciliationStartupBarrier } from './startup/wsl-cli-reconciliation-startup-barrier'
|
||||
import { getDevInstanceIdentity } from './startup/dev-instance-identity'
|
||||
import { hydrateShellPath, mergePathSegments } from './startup/hydrate-shell-path'
|
||||
@@ -724,10 +730,24 @@ if (hasSingleInstanceLock) {
|
||||
}
|
||||
|
||||
ipcMain.handle('app:awaitFirstWindowStartupServices', async () => {
|
||||
// Why: restored WSL terminals get a bounded chance to receive launcher repairs before window rendering proceeds.
|
||||
await Promise.all([firstWindowStartupServicesReady, managedWslCliStartupBarrierReady])
|
||||
})
|
||||
|
||||
ipcMain.handle('app:recoverLegacyWorkerTerminalsForRendererStartup', () =>
|
||||
recoverLegacyWorkerTerminalsForRendererStartup({
|
||||
firstWindowStartupServicesReady,
|
||||
managedWslCliStartupBarrierReady,
|
||||
localPtyProviderStartupReady,
|
||||
reconcile: async () => {
|
||||
await runtime?.refreshRestoredOrchestrationAuthority()
|
||||
return runtime?.reconcileLegacyWorkerTerminals({ materializeRenderer: true })
|
||||
},
|
||||
onDeferredRecoveryError: (error) => {
|
||||
console.warn('[orchestration] legacy worker provider-ready recovery failed', error)
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
// Why: the renderer pulls this once its ui:openSettings listener attaches, so a Settings request queued before mount isn't lost.
|
||||
ipcMain.handle('ui:consumePendingOpenSettings', (event) =>
|
||||
pendingOpenSettings.matches(event.sender.id, { consume: true })
|
||||
@@ -2207,6 +2227,11 @@ void app.whenReady().then(async () => {
|
||||
getAgentProviderSessionSnapshot: () => agentHookServer.getStatusSnapshot(),
|
||||
getAgentProviderSessionRowsForPane: (paneKey) =>
|
||||
agentHookServer.getStatusSnapshotForPane(paneKey),
|
||||
attestAgentHookCompatibilityAuthority: (candidate) =>
|
||||
agentHookServer.attestCompatibilityAuthority(candidate),
|
||||
retireAgentHookCompatibilityAuthority: (paneKey) =>
|
||||
agentHookServer.retirePaneAuthority(paneKey),
|
||||
canRecoverPersistentLocalPtys: () => getDaemonProvider() !== null,
|
||||
// Why: source codex-home here (runs in window AND serve) so aiVault.listSessions includes managed-Codex sessions; registerCoreHandlers is window-only.
|
||||
getAdditionalAiVaultCodexHomePaths: () =>
|
||||
codexRuntimeHome ? codexRuntimeHome.getHostCodexHomePathsForSessionDiscovery() : [],
|
||||
@@ -2222,6 +2247,7 @@ void app.whenReady().then(async () => {
|
||||
orchestrationEnvironmentTransport
|
||||
})
|
||||
runtime = runtimeService
|
||||
runtimeService.prepareLegacyWorkerTerminalRecovery()
|
||||
publishProviderSessionChanges(agentHookServer.getProviderSessionIdentities())
|
||||
browserManager.setBrowserGuestStateChangedListener((worktreeId) => {
|
||||
runtimeService.notifyMobileSessionTabsChanged(worktreeId)
|
||||
@@ -2664,6 +2690,8 @@ void app.whenReady().then(async () => {
|
||||
store,
|
||||
prepareCodexSessionResumeForLaunch
|
||||
)
|
||||
await runtime.refreshRestoredOrchestrationAuthority()
|
||||
await runtime.reconcileLegacyWorkerTerminals()
|
||||
// Why: headless servers can't mount <webview> panes; use offscreen WebContents, gated on a real display so browser.headless.v1 stays honest.
|
||||
if (headlessBrowserDisplayAvailable) {
|
||||
runtime.setOffscreenBrowserBackend(new OffscreenBrowserBackend(browserManager))
|
||||
|
||||
@@ -177,6 +177,57 @@ describe('dashboard payload validation', () => {
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('validates the preview terminal input profile', () => {
|
||||
const terminalInput = {
|
||||
hostPlatform: 'win32',
|
||||
localWindowsConpty: true,
|
||||
osRelease: '10.0.22631',
|
||||
windowsShiftEnterEncoding: 'alt-enter',
|
||||
kittyKeyboardAdvertised: false
|
||||
}
|
||||
expect(
|
||||
isDashboardSnapshot({
|
||||
...SNAPSHOT,
|
||||
cards: [{ ...SNAPSHOT.cards[0], terminalInput }]
|
||||
})
|
||||
).toBe(true)
|
||||
for (const invalid of [
|
||||
{ ...terminalInput, hostPlatform: 'windows' },
|
||||
{ ...terminalInput, localWindowsConpty: 'true' },
|
||||
{ ...terminalInput, osRelease: 'x'.repeat(1_025) },
|
||||
{ ...terminalInput, windowsShiftEnterEncoding: 'enter' },
|
||||
{ ...terminalInput, kittyKeyboardAdvertised: 1 }
|
||||
]) {
|
||||
expect(
|
||||
isDashboardSnapshot({
|
||||
...SNAPSHOT,
|
||||
cards: [{ ...SNAPSHOT.cards[0], terminalInput: invalid }]
|
||||
})
|
||||
).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
// Why: terminalInput is per-card, so a host profile this validator does not
|
||||
// know must cost that preview its card, never the whole board.
|
||||
it('drops only the card whose terminal input profile is unusable', () => {
|
||||
const good = SNAPSHOT.cards[0]
|
||||
const bad = {
|
||||
...good,
|
||||
paneKey: 'tab-2:leaf-2',
|
||||
terminalInput: {
|
||||
hostPlatform: 'plan9',
|
||||
localWindowsConpty: false,
|
||||
windowsShiftEnterEncoding: 'csi-u',
|
||||
kittyKeyboardAdvertised: true
|
||||
}
|
||||
}
|
||||
|
||||
const admitted = admitDashboardSnapshot({ ...SNAPSHOT, cards: [good, bad] })
|
||||
|
||||
expect(admitted?.droppedCardCount).toBe(1)
|
||||
expect(admitted?.snapshot.cards.map((card) => card.paneKey)).toEqual(['tab-1:leaf-1'])
|
||||
})
|
||||
|
||||
// Why: the pop-out replays the last accepted snapshot, so rejecting the whole
|
||||
// board over one card froze every other agent's status until it was renamed.
|
||||
describe('admitDashboardSnapshot', () => {
|
||||
|
||||
@@ -29,6 +29,20 @@ const MAX_LABEL_LENGTH = DASHBOARD_MAX_LABEL_LENGTH
|
||||
const DASHBOARD_BUCKETS = new Set(['attention', 'working', 'done', 'idle'])
|
||||
const DASHBOARD_DOT_STATES = new Set(['working', 'blocked', 'waiting', 'done', 'idle'])
|
||||
const DASHBOARD_REVIEW_STATES = new Set(['open', 'closed', 'merged', 'draft'])
|
||||
const DASHBOARD_HOST_PLATFORMS = new Set([
|
||||
'aix',
|
||||
'android',
|
||||
'cygwin',
|
||||
'darwin',
|
||||
'freebsd',
|
||||
'haiku',
|
||||
'linux',
|
||||
'netbsd',
|
||||
'openbsd',
|
||||
'sunos',
|
||||
'win32'
|
||||
])
|
||||
const WINDOWS_SHIFT_ENTER_ENCODINGS = new Set(['alt-enter', 'csi-u'])
|
||||
|
||||
function isBoundedString(value: unknown, maxLength: number, allowEmpty = false): value is string {
|
||||
return typeof value === 'string' && value.length <= maxLength && (allowEmpty || value.length > 0)
|
||||
@@ -263,6 +277,26 @@ function isDashboardCard(value: unknown): boolean {
|
||||
isFiniteNumber(card.stateChangedAt) &&
|
||||
typeof card.unseen === 'boolean' &&
|
||||
isOptionalBoundedString(card.askSummary, AGENT_STATUS_INTERACTIVE_PROMPT_MAX_LENGTH) &&
|
||||
isOptionalBoundedString(card.conversationName, MAX_LABEL_LENGTH)
|
||||
isOptionalBoundedString(card.conversationName, MAX_LABEL_LENGTH) &&
|
||||
isDashboardTerminalInput(card.terminalInput)
|
||||
)
|
||||
}
|
||||
|
||||
function isDashboardTerminalInput(value: unknown): boolean {
|
||||
if (value === undefined) {
|
||||
return true
|
||||
}
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
return false
|
||||
}
|
||||
const input = value as Record<string, unknown>
|
||||
return (
|
||||
typeof input.hostPlatform === 'string' &&
|
||||
DASHBOARD_HOST_PLATFORMS.has(input.hostPlatform) &&
|
||||
typeof input.localWindowsConpty === 'boolean' &&
|
||||
isOptionalBoundedString(input.osRelease, MAX_LABEL_LENGTH) &&
|
||||
typeof input.windowsShiftEnterEncoding === 'string' &&
|
||||
WINDOWS_SHIFT_ENTER_ENCODINGS.has(input.windowsShiftEnterEncoding) &&
|
||||
typeof input.kittyKeyboardAdvertised === 'boolean'
|
||||
)
|
||||
}
|
||||
|
||||
@@ -183,6 +183,32 @@ describe('registerMobileHandlers', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('preserves a copyable pairing URL when QR encoding fails', async () => {
|
||||
const createMobilePairingOffer = vi.fn().mockResolvedValue({
|
||||
available: true,
|
||||
pairingUrl: 'orca://pair?code=copy-me',
|
||||
endpoint: 'wss://pair.example/oversized',
|
||||
deviceId: 'mobile-large',
|
||||
connectionMode: 'local-only'
|
||||
})
|
||||
|
||||
registerMobileHandlers({ createMobilePairingOffer } as never, {
|
||||
encodePairingQr: vi.fn().mockResolvedValue({ ok: false, reason: 'encoding_failed' })
|
||||
})
|
||||
|
||||
await expect(
|
||||
handlers.get('mobile:getPairingQR')?.(null, { address: 'pair.example' })
|
||||
).resolves.toEqual({
|
||||
available: true,
|
||||
qrDataUrl: null,
|
||||
qrError: 'encoding_failed',
|
||||
pairingUrl: 'orca://pair?code=copy-me',
|
||||
endpoint: 'wss://pair.example/oversized',
|
||||
deviceId: 'mobile-large',
|
||||
connectionMode: 'local-only'
|
||||
})
|
||||
})
|
||||
|
||||
it('lists only paired mobile-scoped devices', () => {
|
||||
const rpcServer = {
|
||||
getDeviceRegistry: () => ({
|
||||
|
||||
@@ -6,6 +6,7 @@ import { isTailnetIPv4Address } from '../../shared/tailnet-address'
|
||||
import type { DeviceEntry } from '../runtime/device-registry'
|
||||
import type { OrcaRuntimeRpcServer } from '../runtime/runtime-rpc'
|
||||
import type { RelayBrokerStatus } from '../runtime/relay/relay-session-broker'
|
||||
import { encodeMobilePairingQr, type MobilePairingQrResult } from '../runtime/mobile-pairing-qr'
|
||||
import {
|
||||
getWebSocketPort,
|
||||
inspectWindowsMobileFirewall,
|
||||
@@ -93,6 +94,7 @@ export type MobileHandlerDependencies = {
|
||||
openWindowsNetworkSettings?: () => Promise<void>
|
||||
getRelayStatus?: () => RelayBrokerStatus
|
||||
consumePendingUnpairedDeviceAuthFailure?: (webContentsId: number) => boolean
|
||||
encodePairingQr?: (pairingUrl: string) => Promise<MobilePairingQrResult>
|
||||
}
|
||||
|
||||
export function registerMobileHandlers(
|
||||
@@ -144,18 +146,12 @@ export function registerMobileHandlers(
|
||||
return { available: false as const }
|
||||
}
|
||||
|
||||
// Why dynamic: pairing is the only consumer, so launch should not parse
|
||||
// the qrcode bundle for users who never pair a device.
|
||||
const { default: QRCode } = await import('qrcode')
|
||||
const qrDataUrl = await QRCode.toDataURL(offer.pairingUrl, {
|
||||
errorCorrectionLevel: 'M',
|
||||
margin: 2,
|
||||
width: 256
|
||||
})
|
||||
const qr = await (dependencies.encodePairingQr ?? encodeMobilePairingQr)(offer.pairingUrl)
|
||||
|
||||
return {
|
||||
available: true as const,
|
||||
qrDataUrl,
|
||||
qrDataUrl: qr.ok ? qr.qrDataUrl : null,
|
||||
...(!qr.ok ? { qrError: qr.reason } : {}),
|
||||
pairingUrl: offer.pairingUrl,
|
||||
endpoint: offer.endpoint,
|
||||
deviceId: offer.deviceId,
|
||||
|
||||
@@ -3605,6 +3605,64 @@ describe('registerPtyHandlers', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('resolves default WSL authority before daemon host env and spawn metadata', async () => {
|
||||
await withWin32Platform(async () => {
|
||||
_setWslCachesForTests({ available: true, distros: ['Ubuntu'] })
|
||||
const daemonSpawn = setupDaemonAdapter()
|
||||
const runtime = {
|
||||
setPtyController: vi.fn(),
|
||||
registerPty: vi.fn(),
|
||||
onPtySpawned: vi.fn(),
|
||||
onPtyExit: vi.fn(),
|
||||
onPtyData: vi.fn(),
|
||||
preparePtyExecutionContext: vi.fn().mockReturnValue(true),
|
||||
getOrchestrationCompatibilityHostId: vi.fn(() => 'compat-host')
|
||||
}
|
||||
const settings = {
|
||||
terminalWindowsShell: 'wsl.exe',
|
||||
terminalWindowsWslDistro: null,
|
||||
terminalWindowsPowerShellImplementation: 'auto'
|
||||
}
|
||||
handlers.clear()
|
||||
registerPtyHandlers(
|
||||
mainWindow as never,
|
||||
runtime as never,
|
||||
undefined,
|
||||
(() => settings) as never
|
||||
)
|
||||
const controller = runtime.setPtyController.mock.calls[0]?.[0] as {
|
||||
spawn(args: {
|
||||
cols: number
|
||||
rows: number
|
||||
cwd?: string
|
||||
worktreeId?: string
|
||||
env?: Record<string, string>
|
||||
}): Promise<{ id: string }>
|
||||
}
|
||||
|
||||
await controller.spawn({
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
cwd: 'C:\\repo',
|
||||
worktreeId: 'repo-1::C:\\repo',
|
||||
env: {}
|
||||
})
|
||||
|
||||
const spawnOptions = daemonSpawn.mock.calls.at(-1)?.[0] as DaemonSpawnCall
|
||||
expect(spawnOptions.terminalWindowsWslDistro).toBe('Ubuntu')
|
||||
expect(spawnOptions.env).toMatchObject({
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_HOST_KIND: 'wsl',
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_HOST_ID: 'compat-host',
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION: 'Ubuntu'
|
||||
})
|
||||
expect(runtime.preparePtyExecutionContext).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
'Ubuntu',
|
||||
expect.objectContaining({ resetIncarnation: true })
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('distinguishes an attached native context from an older daemon fallback', async () => {
|
||||
await withWin32Platform(async () => {
|
||||
_setWslCachesForTests({ available: true, distros: ['Ubuntu'] })
|
||||
@@ -5380,6 +5438,37 @@ describe('registerPtyHandlers', () => {
|
||||
expect(listProcesses).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('scopes runtime inventories to the requested provider', async () => {
|
||||
const localList = vi
|
||||
.spyOn(getLocalPtyProvider(), 'listProcesses')
|
||||
.mockResolvedValue([{ id: 'local-pty', title: 'Local', cwd: '/local' }])
|
||||
const sshAList = vi.fn(async () => [{ id: 'ssh-a-pty' }])
|
||||
const sshBList = vi.fn(async () => {
|
||||
throw new Error('ssh-b unavailable')
|
||||
})
|
||||
registerSshPtyProvider('ssh-a', { listProcesses: sshAList } as never)
|
||||
registerSshPtyProvider('ssh-b', { listProcesses: sshBList } as never)
|
||||
const runtime = { setPtyController: vi.fn() }
|
||||
handlers.clear()
|
||||
registerPtyHandlers(mainWindow as never, runtime as never)
|
||||
const controller = runtime.setPtyController.mock.calls[0]?.[0] as {
|
||||
listProcesses(connectionId?: string | null): Promise<{ id: string }[]>
|
||||
}
|
||||
|
||||
await expect(controller.listProcesses(null)).resolves.toEqual([
|
||||
{ id: 'local-pty', title: 'Local', cwd: '/local' }
|
||||
])
|
||||
expect(localList).toHaveBeenCalledOnce()
|
||||
expect(sshAList).not.toHaveBeenCalled()
|
||||
expect(sshBList).not.toHaveBeenCalled()
|
||||
|
||||
await expect(controller.listProcesses('ssh-a')).resolves.toEqual([{ id: 'ssh-a-pty' }])
|
||||
expect(sshAList).toHaveBeenCalledOnce()
|
||||
expect(sshBList).not.toHaveBeenCalled()
|
||||
|
||||
await expect(controller.listProcesses()).rejects.toThrow('ssh-b unavailable')
|
||||
})
|
||||
|
||||
it('returns unavailable runtime confirmation for unsupported or missing providers', async () => {
|
||||
registerSshPtyProvider('ssh-1', {} as never)
|
||||
setPtyOwnership('unsupported-pty', 'ssh-1')
|
||||
@@ -14658,6 +14747,45 @@ describe('registerPtyHandlers', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('seeds the headless emulator from an SSH relay reattach replay', async () => {
|
||||
setLocalPtyProvider({
|
||||
spawn: vi.fn(async () => ({
|
||||
id: 'pty-ssh-reattach',
|
||||
isReattach: true,
|
||||
replay: 'relay history\r\n'
|
||||
})),
|
||||
write: vi.fn(),
|
||||
resize: vi.fn(),
|
||||
kill: vi.fn(),
|
||||
shutdown: vi.fn(),
|
||||
onData: vi.fn(() => vi.fn()),
|
||||
onExit: vi.fn(() => vi.fn()),
|
||||
listProcesses: vi.fn(async () => []),
|
||||
getForegroundProcess: vi.fn(async () => null)
|
||||
} as never)
|
||||
const runtime = {
|
||||
setPtyController: vi.fn(),
|
||||
noteTerminalSpawnCommand: vi.fn(),
|
||||
seedHeadlessTerminal: vi.fn(),
|
||||
onPtySpawned: vi.fn(),
|
||||
onPtyData: vi.fn(),
|
||||
onPtyExit: vi.fn(),
|
||||
createPreAllocatedTerminalHandle: vi.fn(() => 'handle-ssh-reattach'),
|
||||
registerPreAllocatedHandleForPty: vi.fn(),
|
||||
preAllocateHandleForPty: vi.fn()
|
||||
}
|
||||
registerPtyHandlers(mainWindow as never, runtime as never)
|
||||
|
||||
await handlers.get('pty:spawn')!(null, { cols: 80, rows: 24 })
|
||||
|
||||
// Why: without this seed main's model would be a strict suffix of what the renderer painted, and a later park-reveal would restore the fragment.
|
||||
expect(runtime.seedHeadlessTerminal).toHaveBeenCalledTimes(1)
|
||||
expect(runtime.seedHeadlessTerminal).toHaveBeenCalledWith(
|
||||
'pty-ssh-reattach',
|
||||
'relay history\r\n'
|
||||
)
|
||||
})
|
||||
|
||||
it('upgrades legacy numeric pane keys when the spawn metadata proves the stable leaf', async () => {
|
||||
registerPtyHandlers(mainWindow as never)
|
||||
const leafId = '11111111-1111-4111-8111-111111111111'
|
||||
|
||||
+77
-54
@@ -140,7 +140,7 @@ import {
|
||||
} from '../agent-hooks/migration-unsupported-pty-state'
|
||||
import { parseWslPath } from '../wsl'
|
||||
import { mergePersistedWindowsPath } from '../pty/windows-environment-path'
|
||||
import { addOrcaWslInteropEnv } from '../pty/wsl-orca-env'
|
||||
import { addOrcaWslInteropEnv, stampWslOrchestrationCompatibilityHost } from '../pty/wsl-orca-env'
|
||||
import { PtyProducerFlowController } from './pty-producer-flow-control'
|
||||
import { beginTerminalInstall } from './watcher-removal-gate'
|
||||
import {
|
||||
@@ -1811,6 +1811,11 @@ export function registerPtyHandlers(
|
||||
if (preAllocatedHandle) {
|
||||
env.ORCA_TERMINAL_HANDLE = preAllocatedHandle
|
||||
}
|
||||
stampWslOrchestrationCompatibilityHost(
|
||||
env,
|
||||
runtime?.getOrchestrationCompatibilityHostId?.(),
|
||||
ctx?.isWsl === true ? ctx.wslDistro : null
|
||||
)
|
||||
if (ctx?.isWsl === true) {
|
||||
addOrcaWslInteropEnv(env)
|
||||
}
|
||||
@@ -3662,10 +3667,35 @@ export function registerPtyHandlers(
|
||||
})
|
||||
: { shellOverride: undefined, terminalWindowsWslDistro: null }
|
||||
const daemonShellOverride = terminalRuntimeOptions.shellOverride
|
||||
const isDaemonHostSpawn =
|
||||
!args.connectionId &&
|
||||
!(provider instanceof LocalPtyProvider) &&
|
||||
!routesFreshSpawnsToLocalProvider(provider)
|
||||
const callerRequestedSessionId = args.sessionId?.trim()
|
||||
const requestedSessionId =
|
||||
callerRequestedSessionId ??
|
||||
(isDaemonHostSpawn && args.agentSessionCreateOperationId
|
||||
? ptySessionIdForAgentCreateOperation(args.worktreeId, args.agentSessionCreateOperationId)
|
||||
: undefined)
|
||||
const sessionId =
|
||||
requestedSessionId ?? (isDaemonHostSpawn ? mintPtySessionId(args.worktreeId) : undefined)
|
||||
const effectiveSessionRelayId =
|
||||
sessionId !== undefined ? getRelayPtyId(args.connectionId, sessionId) : undefined
|
||||
const effectiveSessionAppId =
|
||||
sessionId !== undefined ? getAppPtyId(args.connectionId, sessionId) : undefined
|
||||
const isMintedSessionId = callerRequestedSessionId === undefined && isDaemonHostSpawn
|
||||
const expectedWslDistro = !args.connectionId
|
||||
? (resolveWslSessionContext({
|
||||
cwd,
|
||||
sessionId,
|
||||
shellOverride: terminalRuntimeOptions.shellOverride,
|
||||
terminalWindowsWslDistro: terminalRuntimeOptions.terminalWindowsWslDistro
|
||||
})?.distro ?? null)
|
||||
: null
|
||||
const codexSelectionTarget = getCodexSelectionTargetForPty(
|
||||
daemonShellOverride,
|
||||
cwd,
|
||||
terminalRuntimeOptions.terminalWindowsWslDistro ?? null
|
||||
expectedWslDistro
|
||||
)
|
||||
const codexResumePreparation = prepareCodexResumeHome({
|
||||
connectionId: args.connectionId,
|
||||
@@ -3693,31 +3723,6 @@ export function registerPtyHandlers(
|
||||
)
|
||||
}
|
||||
|
||||
const isDaemonHostSpawn =
|
||||
!args.connectionId &&
|
||||
!(provider instanceof LocalPtyProvider) &&
|
||||
!routesFreshSpawnsToLocalProvider(provider)
|
||||
const callerRequestedSessionId = args.sessionId?.trim()
|
||||
const requestedSessionId =
|
||||
callerRequestedSessionId ??
|
||||
(isDaemonHostSpawn && args.agentSessionCreateOperationId
|
||||
? ptySessionIdForAgentCreateOperation(args.worktreeId, args.agentSessionCreateOperationId)
|
||||
: undefined)
|
||||
const sessionId =
|
||||
requestedSessionId ?? (isDaemonHostSpawn ? mintPtySessionId(args.worktreeId) : undefined)
|
||||
const effectiveSessionRelayId =
|
||||
sessionId !== undefined ? getRelayPtyId(args.connectionId, sessionId) : undefined
|
||||
const effectiveSessionAppId =
|
||||
sessionId !== undefined ? getAppPtyId(args.connectionId, sessionId) : undefined
|
||||
const isMintedSessionId = callerRequestedSessionId === undefined && isDaemonHostSpawn
|
||||
const expectedWslDistro = !args.connectionId
|
||||
? (resolveWslSessionContext({
|
||||
cwd,
|
||||
sessionId,
|
||||
shellOverride: terminalRuntimeOptions.shellOverride,
|
||||
terminalWindowsWslDistro: terminalRuntimeOptions.terminalWindowsWslDistro
|
||||
})?.distro ?? null)
|
||||
: null
|
||||
const shouldPersistHostSessionBinding = args.persistHostSessionBinding === true
|
||||
let hostSessionBinding: {
|
||||
store: NonNullable<typeof store>
|
||||
@@ -3792,11 +3797,16 @@ export function registerPtyHandlers(
|
||||
launchAgent: isTuiAgent(args.launchAgent) ? args.launchAgent : undefined,
|
||||
shellPath: daemonShellOverride ?? process.env.COMSPEC,
|
||||
isWsl: shouldSkipCodexHomeEnvForWindowsShell(daemonShellOverride, cwd),
|
||||
wslDistro: codexSelectionTarget.runtime === 'wsl' ? codexSelectionTarget.wslDistro : null,
|
||||
wslDistro: codexSelectionTarget.runtime === 'wsl' ? expectedWslDistro : null,
|
||||
agentStatusHooksEnabled: isAgentStatusHooksEnabled(getSettings?.()),
|
||||
networkProxySettings: getSettings?.(),
|
||||
deferGitConfigGuardToDaemon: provider.supportsGitCredentialGuardHost?.(sessionId) === true
|
||||
})
|
||||
stampWslOrchestrationCompatibilityHost(
|
||||
env,
|
||||
runtime?.getOrchestrationCompatibilityHostId?.(),
|
||||
codexSelectionTarget.runtime === 'wsl' ? expectedWslDistro : null
|
||||
)
|
||||
promoteAgentTeamsShimPath(env, requestedAgentTeamsPath)
|
||||
}
|
||||
|
||||
@@ -3896,8 +3906,7 @@ export function registerPtyHandlers(
|
||||
}
|
||||
if (process.platform === 'win32' && !args.connectionId) {
|
||||
spawnOptions.shellOverride = terminalRuntimeOptions.shellOverride
|
||||
spawnOptions.terminalWindowsWslDistro =
|
||||
terminalRuntimeOptions.terminalWindowsWslDistro ?? null
|
||||
spawnOptions.terminalWindowsWslDistro = expectedWslDistro
|
||||
spawnOptions.terminalWindowsPowerShellImplementation = getSettings
|
||||
? (getSettings()?.terminalWindowsPowerShellImplementation ?? 'auto')
|
||||
: undefined
|
||||
@@ -4543,7 +4552,13 @@ export function registerPtyHandlers(
|
||||
return null
|
||||
}
|
||||
},
|
||||
listProcesses: async () => {
|
||||
listProcesses: async (connectionId) => {
|
||||
if (connectionId === null) {
|
||||
return localProvider.listProcesses()
|
||||
}
|
||||
if (connectionId !== undefined) {
|
||||
return getProvider(connectionId).listProcesses()
|
||||
}
|
||||
const providerSessions = await Promise.all([
|
||||
localProvider.listProcesses(),
|
||||
...Array.from(sshProviders.values(), (provider) => provider.listProcesses())
|
||||
@@ -4750,24 +4765,6 @@ export function registerPtyHandlers(
|
||||
})
|
||||
: { shellOverride: args.shellOverride, terminalWindowsWslDistro: null }
|
||||
const initialShellOverride = terminalRuntimeOptions.shellOverride
|
||||
const initialSelectionTarget = getCodexSelectionTargetForPty(
|
||||
initialShellOverride,
|
||||
cwd,
|
||||
terminalRuntimeOptions.terminalWindowsWslDistro ?? null
|
||||
)
|
||||
const claudeAuth =
|
||||
isClaudeLaunch && prepareClaudeAuth ? await prepareClaudeAuth(initialSelectionTarget) : null
|
||||
spawnTiming.mark('auth')
|
||||
if (isClaudeLaunch && isClaudeAuthSwitchInProgress()) {
|
||||
throw new Error('A Claude account switch is in progress. Try again after it finishes.')
|
||||
}
|
||||
if (claudeAuth?.stripAuthEnv && hasClaudeAuthEnvConflict(args.env)) {
|
||||
throw new Error(
|
||||
'This Claude launch defines explicit Anthropic auth environment variables. Remove those overrides before using a managed Claude account.'
|
||||
)
|
||||
}
|
||||
// Why: the daemon-backed provider skips LocalPtyProvider's buildSpawnEnv, so assemble the same host-local env here for parity.
|
||||
// Safety: skip entirely for SSH — every injection is a loopback secret or a local path that leaks or misleads on the remote host.
|
||||
const isDaemonHostSpawn =
|
||||
!args.connectionId &&
|
||||
!(provider instanceof LocalPtyProvider) &&
|
||||
@@ -4794,6 +4791,24 @@ export function registerPtyHandlers(
|
||||
terminalWindowsWslDistro: terminalRuntimeOptions.terminalWindowsWslDistro
|
||||
})?.distro ?? null)
|
||||
: null
|
||||
const initialSelectionTarget = getCodexSelectionTargetForPty(
|
||||
initialShellOverride,
|
||||
cwd,
|
||||
expectedWslDistro
|
||||
)
|
||||
const claudeAuth =
|
||||
isClaudeLaunch && prepareClaudeAuth ? await prepareClaudeAuth(initialSelectionTarget) : null
|
||||
spawnTiming.mark('auth')
|
||||
if (isClaudeLaunch && isClaudeAuthSwitchInProgress()) {
|
||||
throw new Error('A Claude account switch is in progress. Try again after it finishes.')
|
||||
}
|
||||
if (claudeAuth?.stripAuthEnv && hasClaudeAuthEnvConflict(args.env)) {
|
||||
throw new Error(
|
||||
'This Claude launch defines explicit Anthropic auth environment variables. Remove those overrides before using a managed Claude account.'
|
||||
)
|
||||
}
|
||||
// Why: the daemon-backed provider skips LocalPtyProvider's buildSpawnEnv, so assemble the same host-local env here for parity.
|
||||
// Safety: skip entirely for SSH — every injection is a loopback secret or a local path that leaks or misleads on the remote host.
|
||||
const startupTerminalColorQueryReplyColors = getStartupTerminalColorQueryReplyColors(args)
|
||||
// Why: forward pane env to SSH only when the relay hook path is enabled, or a newer relay could emit statuses this build can't route.
|
||||
const sshSourceEnv = stripRemotePaneEnvWhenHooksDisabled(args.connectionId, args.env)
|
||||
@@ -4903,7 +4918,7 @@ export function registerPtyHandlers(
|
||||
const codexSelectionTarget = getCodexSelectionTargetForPty(
|
||||
effectiveShellOverride,
|
||||
cwd,
|
||||
terminalRuntimeOptions.terminalWindowsWslDistro ?? null
|
||||
expectedWslDistro
|
||||
)
|
||||
const codexResumePreparation = prepareCodexResumeHome({
|
||||
connectionId: args.connectionId,
|
||||
@@ -4969,13 +4984,17 @@ export function registerPtyHandlers(
|
||||
launchAgent: isTuiAgent(args.launchAgent) ? args.launchAgent : undefined,
|
||||
shellPath: effectiveShellOverride ?? process.env.COMSPEC,
|
||||
isWsl: shouldSkipCodexHomeEnvForWindowsShell(effectiveShellOverride, cwd),
|
||||
wslDistro:
|
||||
codexSelectionTarget.runtime === 'wsl' ? codexSelectionTarget.wslDistro : null,
|
||||
wslDistro: codexSelectionTarget.runtime === 'wsl' ? expectedWslDistro : null,
|
||||
agentStatusHooksEnabled: isAgentStatusHooksEnabled(getSettings?.()),
|
||||
networkProxySettings: getSettings?.(),
|
||||
deferGitConfigGuardToDaemon:
|
||||
provider.supportsGitCredentialGuardHost?.(effectiveSessionId) === true
|
||||
})
|
||||
stampWslOrchestrationCompatibilityHost(
|
||||
env,
|
||||
runtime?.getOrchestrationCompatibilityHostId?.(),
|
||||
codexSelectionTarget.runtime === 'wsl' ? expectedWslDistro : null
|
||||
)
|
||||
promoteAgentTeamsShimPath(env, requestedAgentTeamsPath)
|
||||
} catch (err) {
|
||||
// Why: buildPtyHostEnv has fs side-effects (Pi/OMP install); clear per-PTY state on throw, but only minted ids — caller ids may name existing PTYs.
|
||||
@@ -5062,8 +5081,7 @@ export function registerPtyHandlers(
|
||||
}
|
||||
if (process.platform === 'win32' && !args.connectionId) {
|
||||
// Why: the renderer models PowerShell as one shell family; thread the implementation choice so both PTY paths resolve the same executable.
|
||||
spawnOptions.terminalWindowsWslDistro =
|
||||
terminalRuntimeOptions.terminalWindowsWslDistro ?? null
|
||||
spawnOptions.terminalWindowsWslDistro = expectedWslDistro
|
||||
spawnOptions.terminalWindowsPowerShellImplementation = getSettings
|
||||
? (getSettings()?.terminalWindowsPowerShellImplementation ?? 'auto')
|
||||
: undefined
|
||||
@@ -5369,6 +5387,11 @@ export function registerPtyHandlers(
|
||||
preferProviderIfExisting: true
|
||||
}
|
||||
)
|
||||
} else if (typeof result.replay === 'string' && result.replay.length > 0) {
|
||||
// Why: the relay reattach replay is the one restore main never ingests, so without
|
||||
// this seed its model is a mere suffix of what the renderer painted — and a later
|
||||
// park-reveal would outrank the fuller relay replay with that fragment.
|
||||
runtime.seedHeadlessTerminal(result.id, result.replay)
|
||||
}
|
||||
}
|
||||
if (
|
||||
|
||||
@@ -62,6 +62,7 @@ describe('registerSshBrowseHandler', () => {
|
||||
|
||||
await expect(resultPromise).resolves.toEqual({
|
||||
resolvedPath: '/home/user',
|
||||
pathFlavor: 'posix',
|
||||
entries: [
|
||||
{ name: 'src', isDirectory: true },
|
||||
{ name: 'notes file.txt', isDirectory: false },
|
||||
@@ -93,6 +94,7 @@ describe('registerSshBrowseHandler', () => {
|
||||
|
||||
await expect(resultPromise).resolves.toEqual({
|
||||
resolvedPath: "/tmp/it's here",
|
||||
pathFlavor: 'posix',
|
||||
entries: []
|
||||
})
|
||||
expect(exec).toHaveBeenCalledWith("cd '/tmp/it'\\''s here' && pwd && command ls -1Ap")
|
||||
@@ -128,6 +130,7 @@ describe('registerSshBrowseHandler', () => {
|
||||
|
||||
await expect(resultPromise).resolves.toEqual({
|
||||
resolvedPath: 'C:/Users/alice',
|
||||
pathFlavor: 'win32',
|
||||
entries: [
|
||||
{ name: 'Desktop', isDirectory: true },
|
||||
{ name: 'notes.txt', isDirectory: false }
|
||||
@@ -150,6 +153,40 @@ describe('registerSshBrowseHandler', () => {
|
||||
expect(script).toContain("Write-Output ($resolved -replace '\\\\', '/')")
|
||||
})
|
||||
|
||||
it('lists Windows drive roots when an SSH picker browses the host root', async () => {
|
||||
const posixChannel = createMockChannel()
|
||||
const windowsChannel = createMockChannel()
|
||||
const exec = vi.fn().mockResolvedValueOnce(posixChannel).mockResolvedValueOnce(windowsChannel)
|
||||
const getConnectionManager = () => ({
|
||||
getConnection: () => ({ exec })
|
||||
})
|
||||
registerSshBrowseHandler(getConnectionManager as never)
|
||||
|
||||
const resultPromise = handler(null, { targetId: 'ssh-1', dirPath: '/' })
|
||||
await Promise.resolve()
|
||||
posixChannel.stderr.emit('data', Buffer.from('"exec" is not recognized'))
|
||||
posixChannel.emit('exit', 1)
|
||||
posixChannel.emit('close')
|
||||
await vi.waitFor(() => {
|
||||
expect(windowsChannel.listenerCount('close')).toBe(1)
|
||||
})
|
||||
windowsChannel.emit('data', Buffer.from('/\r\nC:\\/\r\nM:\\/\r\n'))
|
||||
windowsChannel.emit('exit', 0)
|
||||
windowsChannel.emit('close')
|
||||
|
||||
await expect(resultPromise).resolves.toEqual({
|
||||
resolvedPath: '/',
|
||||
pathFlavor: 'win32',
|
||||
entries: [
|
||||
{ name: 'C:\\', isDirectory: true },
|
||||
{ name: 'M:\\', isDirectory: true }
|
||||
]
|
||||
})
|
||||
const script = decodeEncodedCommand(exec.mock.calls[1]?.[0] ?? '')
|
||||
expect(script).toContain('Get-PSDrive -PSProvider FileSystem')
|
||||
expect(script).not.toContain('Set-Location')
|
||||
})
|
||||
|
||||
it('falls back for a non-English cmd.exe reject (exit 1, localized stderr)', async () => {
|
||||
// Regression: real Windows OpenSSH + cmd.exe forwards exit 1 (not 9009) with
|
||||
// localized stderr. The old 9009/English-string trigger silently missed this,
|
||||
@@ -182,6 +219,7 @@ describe('registerSshBrowseHandler', () => {
|
||||
|
||||
await expect(resultPromise).resolves.toEqual({
|
||||
resolvedPath: 'C:/Users',
|
||||
pathFlavor: 'win32',
|
||||
entries: [{ name: 'Admin', isDirectory: true }]
|
||||
})
|
||||
expect(exec).toHaveBeenCalledTimes(2)
|
||||
@@ -213,6 +251,7 @@ describe('registerSshBrowseHandler', () => {
|
||||
|
||||
await expect(resultPromise).resolves.toEqual({
|
||||
resolvedPath: "C:/O'Brien",
|
||||
pathFlavor: 'win32',
|
||||
entries: []
|
||||
})
|
||||
const script = decodeEncodedCommand(exec.mock.calls[1]?.[0] ?? '')
|
||||
@@ -241,7 +280,11 @@ describe('registerSshBrowseHandler', () => {
|
||||
windowsChannel.emit('exit', 0)
|
||||
windowsChannel.emit('close')
|
||||
|
||||
await expect(resultPromise).resolves.toEqual({ resolvedPath: 'C:/Users/alice', entries: [] })
|
||||
await expect(resultPromise).resolves.toEqual({
|
||||
resolvedPath: 'C:/Users/alice',
|
||||
entries: [],
|
||||
pathFlavor: 'win32'
|
||||
})
|
||||
const script = decodeEncodedCommand(exec.mock.calls[1]?.[0] ?? '')
|
||||
// ~ must expand to $HOME, not be passed literally to Set-Location.
|
||||
expect(script).toContain('$dir = $HOME')
|
||||
@@ -279,7 +322,11 @@ describe('registerSshBrowseHandler', () => {
|
||||
windowsChannel.emit('exit', 0)
|
||||
windowsChannel.emit('close')
|
||||
|
||||
await expect(resultPromise).resolves.toEqual({ resolvedPath: 'C:/Users', entries: [] })
|
||||
await expect(resultPromise).resolves.toEqual({
|
||||
resolvedPath: 'C:/Users',
|
||||
entries: [],
|
||||
pathFlavor: 'win32'
|
||||
})
|
||||
const script = decodeEncodedCommand(exec.mock.calls[1]?.[0] ?? '')
|
||||
expect(script).toContain(expected)
|
||||
}
|
||||
|
||||
+26
-11
@@ -2,12 +2,19 @@ import { ipcMain } from 'electron'
|
||||
import type { SshConnectionManager } from '../ssh/ssh-connection-manager'
|
||||
import type { SshExecOptions } from '../ssh/ssh-connection-utils'
|
||||
import { powerShellCommand, powerShellLiteral } from '../ssh/ssh-remote-powershell'
|
||||
import type { FilesystemPathFlavor } from '../../shared/types'
|
||||
|
||||
export type RemoteDirEntry = {
|
||||
name: string
|
||||
isDirectory: boolean
|
||||
}
|
||||
|
||||
type RemoteBrowseResult = {
|
||||
entries: RemoteDirEntry[]
|
||||
resolvedPath: string
|
||||
pathFlavor: FilesystemPathFlavor
|
||||
}
|
||||
|
||||
const SSH_BROWSE_TIMEOUT_MS = 15_000
|
||||
|
||||
// Why: 127 = POSIX "command not found" (locale-independent) — the Windows fallback never ran, so the original POSIX error is the real one.
|
||||
@@ -32,10 +39,7 @@ export function registerSshBrowseHandler(
|
||||
|
||||
ipcMain.handle(
|
||||
'ssh:browseDir',
|
||||
async (
|
||||
_event,
|
||||
args: { targetId: string; dirPath: string }
|
||||
): Promise<{ entries: RemoteDirEntry[]; resolvedPath: string }> => {
|
||||
async (_event, args: { targetId: string; dirPath: string }): Promise<RemoteBrowseResult> => {
|
||||
const mgr = getConnectionManager()
|
||||
if (!mgr) {
|
||||
throw new Error('SSH connection manager not initialized')
|
||||
@@ -68,15 +72,25 @@ type SshBrowseConnection = NonNullable<ReturnType<SshConnectionManager['getConne
|
||||
function browseWithPosixShell(
|
||||
conn: SshBrowseConnection,
|
||||
dirPath: string
|
||||
): Promise<{ entries: RemoteDirEntry[]; resolvedPath: string }> {
|
||||
): Promise<RemoteBrowseResult> {
|
||||
// Why: `command ls` skips aliases; `&&` makes a failing ls exit non-zero (not look empty); -1Ap = one-per-line + trailing / on dirs.
|
||||
return runBrowseCommand(conn, `cd ${shellEscape(dirPath)} && pwd && command ls -1Ap`)
|
||||
return runBrowseCommand(conn, `cd ${shellEscape(dirPath)} && pwd && command ls -1Ap`, 'posix')
|
||||
}
|
||||
|
||||
function browseWithWindowsPowerShell(
|
||||
conn: SshBrowseConnection,
|
||||
dirPath: string
|
||||
): Promise<{ entries: RemoteDirEntry[]; resolvedPath: string }> {
|
||||
): Promise<RemoteBrowseResult> {
|
||||
if (/^[\\/]+$/.test(dirPath.trim())) {
|
||||
const script = [
|
||||
"$ErrorActionPreference = 'Stop'",
|
||||
'[Console]::OutputEncoding = [System.Text.Encoding]::UTF8',
|
||||
"Write-Output '/'",
|
||||
"Get-PSDrive -PSProvider FileSystem | Where-Object { $_.Name -match '^[A-Za-z]$' } | Sort-Object Name | ForEach-Object { Write-Output (($_.Name.ToUpperInvariant() + ':\\') + '/') }"
|
||||
].join('; ')
|
||||
return runBrowseCommand(conn, powerShellCommand(script), 'win32', { wrapCommand: false })
|
||||
}
|
||||
|
||||
const script = [
|
||||
"$ErrorActionPreference = 'Stop'",
|
||||
// Why: PowerShell 5.1 emits redirected stdout in the OEM code page; pin UTF-8 so non-ASCII names aren't mojibake.
|
||||
@@ -91,14 +105,15 @@ function browseWithWindowsPowerShell(
|
||||
'}'
|
||||
].join('; ')
|
||||
|
||||
return runBrowseCommand(conn, powerShellCommand(script), { wrapCommand: false })
|
||||
return runBrowseCommand(conn, powerShellCommand(script), 'win32', { wrapCommand: false })
|
||||
}
|
||||
|
||||
async function runBrowseCommand(
|
||||
conn: SshBrowseConnection,
|
||||
command: string,
|
||||
pathFlavor: FilesystemPathFlavor,
|
||||
options?: SshExecOptions
|
||||
): Promise<{ entries: RemoteDirEntry[]; resolvedPath: string }> {
|
||||
): Promise<RemoteBrowseResult> {
|
||||
const channel = options ? await conn.exec(command, options) : await conn.exec(command)
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -145,7 +160,7 @@ async function runBrowseCommand(
|
||||
rejectOnce(new Error('Remote directory listing timed out'))
|
||||
closeChannel()
|
||||
}
|
||||
const resolveOnce = (result: { entries: RemoteDirEntry[]; resolvedPath: string }): void => {
|
||||
const resolveOnce = (result: RemoteBrowseResult): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
@@ -213,7 +228,7 @@ async function runBrowseCommand(
|
||||
return a.name.localeCompare(b.name)
|
||||
})
|
||||
|
||||
resolveOnce({ entries, resolvedPath })
|
||||
resolveOnce({ entries, resolvedPath, pathFlavor })
|
||||
}
|
||||
|
||||
channel.on('data', onStdoutData)
|
||||
|
||||
@@ -3710,6 +3710,21 @@ describe('Store', () => {
|
||||
expect(hostSession.lastVisitedAtByWorktreeId?.['r1::/path/wt1']).toBeUndefined()
|
||||
})
|
||||
|
||||
it('lists only persisted workspace-session host partitions', async () => {
|
||||
const store = await createStore()
|
||||
expect(store.getWorkspaceSessionHostIds()).toEqual(['local'])
|
||||
|
||||
store.getWorkspaceSession('ssh:not-persisted')
|
||||
store.setWorkspaceSession(getDefaultWorkspaceSession(), 'ssh:ssh-a')
|
||||
store.setWorkspaceSession(getDefaultWorkspaceSession(), 'runtime:environment-a')
|
||||
|
||||
expect(store.getWorkspaceSessionHostIds()).toEqual([
|
||||
'local',
|
||||
'ssh:ssh-a',
|
||||
'runtime:environment-a'
|
||||
])
|
||||
})
|
||||
|
||||
it('removeProject removes the derived project host setup compatibility record', async () => {
|
||||
const store = await createStore()
|
||||
store.addRepo(makeRepo({ id: 'r1' }))
|
||||
|
||||
@@ -5771,6 +5771,17 @@ export class Store {
|
||||
return this.state.workspaceSessionsByHostId?.[resolved] ?? getDefaultWorkspaceSession()
|
||||
}
|
||||
|
||||
getWorkspaceSessionHostIds(): ExecutionHostId[] {
|
||||
const hostIds = new Set<ExecutionHostId>([LOCAL_EXECUTION_HOST_ID])
|
||||
for (const key of Object.keys(this.state.workspaceSessionsByHostId ?? {})) {
|
||||
const hostId = normalizeExecutionHostId(key)
|
||||
if (hostId) {
|
||||
hostIds.add(hostId)
|
||||
}
|
||||
}
|
||||
return [...hostIds]
|
||||
}
|
||||
|
||||
readTerminalScrollbackSnapshot(ref: string): string | null {
|
||||
return readTerminalScrollbackSnapshotSync(ref, this.terminalScrollbackSnapshotStorage)
|
||||
}
|
||||
|
||||
@@ -96,6 +96,7 @@ vi.mock('../wsl', () => ({
|
||||
toLinuxPath: (path: string) => path.replace(/^C:\\/i, '/mnt/c/').replace(/\\/g, '/'),
|
||||
toWindowsWslPath: (path: string, distro: string) =>
|
||||
`\\\\wsl.localhost\\${distro}${path.replace(/\//g, '\\')}`,
|
||||
getDefaultWslDistro: () => 'Ubuntu',
|
||||
isWslAvailable: () => true,
|
||||
// Why: WSL worktree validation now asks the distro; these tests use WSL UNC
|
||||
// cwds that are meant to exist, so report them present without spawning wsl.exe.
|
||||
@@ -880,6 +881,45 @@ describe('LocalPtyProvider', () => {
|
||||
expect(spawnCall[2].env.HISTFILE).toContain('terminal-history-wsl/Debian')
|
||||
})
|
||||
|
||||
it('resolves and persists the default distro for Windows cwd WSL terminals', async () => {
|
||||
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
|
||||
const buildSpawnEnv = vi.fn(
|
||||
(
|
||||
_id: string,
|
||||
env: Record<string, string>,
|
||||
_ctx?: { isWsl?: boolean; wslDistro?: string | null }
|
||||
) => env
|
||||
)
|
||||
provider.configure({ buildSpawnEnv })
|
||||
|
||||
const result = await provider.spawn({
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
worktreeId: 'repo-1::C:\\Users\\jin\\repo',
|
||||
cwd: 'C:\\Users\\jin\\repo',
|
||||
shellOverride: 'wsl.exe',
|
||||
terminalWindowsWslDistro: null
|
||||
})
|
||||
|
||||
const spawnCall = spawnMock.mock.calls.at(-1)!
|
||||
expect(spawnCall[1]).toEqual([
|
||||
'-d',
|
||||
'Ubuntu',
|
||||
'--',
|
||||
'sh',
|
||||
'-c',
|
||||
expect.stringContaining("cd '/mnt/c/Users/jin/repo'")
|
||||
])
|
||||
expect(buildSpawnEnv.mock.calls[0]?.[2]).toMatchObject({
|
||||
isWsl: true,
|
||||
wslDistro: 'Ubuntu'
|
||||
})
|
||||
expect(result.wslDistro).toBe('Ubuntu')
|
||||
expect(
|
||||
(await provider.listProcesses()).find((entry) => entry.id === result.id)?.wslDistro
|
||||
).toBe('Ubuntu')
|
||||
})
|
||||
|
||||
it('repro: keeps explicit PowerShell 7 selection when the pwsh probe is cold-false', async () => {
|
||||
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
|
||||
const pwshAvailable = vi.fn(() => false)
|
||||
|
||||
@@ -11,7 +11,7 @@ import { buildWindowsPowerShellSpawnAttempts } from './windows-shell-fallback-ch
|
||||
import { resolveProcessCwd } from './process-cwd'
|
||||
import { existsSync } from 'node:fs'
|
||||
import * as pty from 'node-pty'
|
||||
import { parseWslPath, isWslAvailable } from '../wsl'
|
||||
import { getDefaultWslDistro, parseWslPath, isWslAvailable } from '../wsl'
|
||||
import { splitWorktreeIdForFilesystem } from '../../shared/worktree-id'
|
||||
import {
|
||||
injectHistoryEnv,
|
||||
@@ -547,6 +547,10 @@ export class LocalPtyProvider implements IPtyProvider {
|
||||
process.platform === 'win32'
|
||||
? getWslContextFromPreferredDistro(args.terminalWindowsWslDistro)
|
||||
: undefined
|
||||
let launchWslContext =
|
||||
wslInfo !== null
|
||||
? getWslContextFromPreferredDistro(wslInfo.distro)
|
||||
: (worktreeWslContext ?? preferredWslContext)
|
||||
|
||||
let shellPath: string
|
||||
let shellArgs: string[]
|
||||
@@ -572,6 +576,9 @@ export class LocalPtyProvider implements IPtyProvider {
|
||||
process.env.COMSPEC ||
|
||||
'powershell.exe'
|
||||
const shellFamily = worktreeWslContext ? 'wsl.exe' : requestedShellFamily
|
||||
if (!launchWslContext && pathWin32.basename(shellFamily).toLowerCase() === 'wsl.exe') {
|
||||
launchWslContext = getWslContextFromPreferredDistro(getDefaultWslDistro())
|
||||
}
|
||||
const normalizedShellFamily = pathWin32.basename(shellFamily).toLowerCase()
|
||||
const resolvedGitBashPath = resolveWindowsGitBashShellPath(shellFamily)
|
||||
// Why: normalize setting-value and path forms to the PowerShell family so the resolver can fall back to inbox powershell.exe.
|
||||
@@ -606,7 +613,7 @@ export class LocalPtyProvider implements IPtyProvider {
|
||||
shellPath,
|
||||
cwd,
|
||||
defaultCwd,
|
||||
wslContext: worktreeWslContext ?? preferredWslContext,
|
||||
wslContext: launchWslContext,
|
||||
startupCommand: args.command
|
||||
})
|
||||
const primaryAttempt = windowsFallbackAttempts[0]
|
||||
@@ -621,7 +628,7 @@ export class LocalPtyProvider implements IPtyProvider {
|
||||
shellPath,
|
||||
cwd,
|
||||
defaultCwd,
|
||||
worktreeWslContext ?? preferredWslContext,
|
||||
launchWslContext,
|
||||
args.command
|
||||
)
|
||||
shellArgs = resolved.shellArgs
|
||||
@@ -672,8 +679,7 @@ export class LocalPtyProvider implements IPtyProvider {
|
||||
}
|
||||
|
||||
const isWslShell = Boolean(wslInfo) || pathWin32.basename(shellPath).toLowerCase() === 'wsl.exe'
|
||||
const launchWslDistro =
|
||||
wslInfo?.distro ?? worktreeWslContext?.distro ?? preferredWslContext?.distro ?? null
|
||||
const launchWslDistro = isWslShell ? (launchWslContext?.distro ?? null) : null
|
||||
const finalEnv = this.opts.buildSpawnEnv
|
||||
? this.opts.buildSpawnEnv(id, spawnEnv, {
|
||||
command: args.command,
|
||||
@@ -796,7 +802,7 @@ export class LocalPtyProvider implements IPtyProvider {
|
||||
let historyResult: ReturnType<typeof injectHistoryEnv> | null = null
|
||||
if (historyEnabled) {
|
||||
historyResult = injectHistoryEnv(finalEnv, worktreeId, effectiveShellPath, cwd, {
|
||||
wslDistro: preferredWslContext?.distro ?? worktreeWslContext?.distro ?? null
|
||||
wslDistro: launchWslDistro
|
||||
})
|
||||
logHistoryInjection(worktreeId, historyResult)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { addOrcaWslInteropEnv, addWorktreeSetupWslInteropEnv } from './wsl-orca-env'
|
||||
import {
|
||||
addOrcaWslInteropEnv,
|
||||
addWorktreeSetupWslInteropEnv,
|
||||
stampWslOrchestrationCompatibilityHost
|
||||
} from './wsl-orca-env'
|
||||
|
||||
describe('addOrcaWslInteropEnv', () => {
|
||||
it('marks the Orca terminal handle for Windows to WSL env import', () => {
|
||||
@@ -29,10 +33,14 @@ describe('addOrcaWslInteropEnv', () => {
|
||||
ORCA_PANE_KEY: 'tab-1:leaf-1',
|
||||
ORCA_TAB_ID: 'tab-1',
|
||||
ORCA_WORKTREE_ID: 'repo::\\\\wsl.localhost\\Ubuntu\\home\\jin\\repo',
|
||||
ORCA_AGENT_LAUNCH_TOKEN: 'launch-secret',
|
||||
ORCA_AGENT_HOOK_PORT: '4567',
|
||||
ORCA_AGENT_HOOK_TOKEN: 'token',
|
||||
ORCA_AGENT_HOOK_ENV: 'dev',
|
||||
ORCA_AGENT_HOOK_VERSION: '1'
|
||||
ORCA_AGENT_HOOK_VERSION: '1',
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_HOST_KIND: 'wsl',
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_HOST_ID: 'local',
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION: 'Ubuntu'
|
||||
}
|
||||
|
||||
addOrcaWslInteropEnv(env)
|
||||
@@ -44,10 +52,44 @@ describe('addOrcaWslInteropEnv', () => {
|
||||
expect(env.WSLENV).toContain('ORCA_PANE_KEY/u')
|
||||
expect(env.WSLENV).toContain('ORCA_TAB_ID/u')
|
||||
expect(env.WSLENV).toContain('ORCA_WORKTREE_ID/u')
|
||||
expect(env.WSLENV).toContain('ORCA_AGENT_LAUNCH_TOKEN/u')
|
||||
expect(env.WSLENV).toContain('ORCA_AGENT_HOOK_PORT/u')
|
||||
expect(env.WSLENV).toContain('ORCA_AGENT_HOOK_TOKEN/u')
|
||||
expect(env.WSLENV).toContain('ORCA_AGENT_HOOK_ENV/u')
|
||||
expect(env.WSLENV).toContain('ORCA_AGENT_HOOK_VERSION/u')
|
||||
expect(env.WSLENV).toContain('ORCA_ORCHESTRATION_COMPATIBILITY_HOST_KIND/u')
|
||||
expect(env.WSLENV).toContain('ORCA_ORCHESTRATION_COMPATIBILITY_HOST_ID/u')
|
||||
expect(env.WSLENV).toContain('ORCA_ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION/u')
|
||||
})
|
||||
|
||||
it('overwrites caller host evidence with native runtime WSL authority', () => {
|
||||
const env = {
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_HOST_KIND: 'ssh',
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_HOST_ID: 'caller-host',
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION: 'caller-incarnation',
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_ATTACHMENT: 'caller-attachment'
|
||||
}
|
||||
|
||||
stampWslOrchestrationCompatibilityHost(env, 'local', 'Ubuntu')
|
||||
|
||||
expect(env).toEqual({
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_HOST_KIND: 'wsl',
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_HOST_ID: 'local',
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION: 'Ubuntu'
|
||||
})
|
||||
})
|
||||
|
||||
it('clears inherited host evidence outside a runtime-owned WSL scope', () => {
|
||||
const env = {
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_HOST_KIND: 'ssh',
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_HOST_ID: 'caller-host',
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION: 'caller-incarnation',
|
||||
ORCA_ORCHESTRATION_COMPATIBILITY_ATTACHMENT: 'caller-attachment'
|
||||
}
|
||||
|
||||
stampWslOrchestrationCompatibilityHost(env, 'local', null)
|
||||
|
||||
expect(env).toEqual({})
|
||||
})
|
||||
|
||||
it('path-translates a Windows hook endpoint but passes a guest-side one untouched', () => {
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
import {
|
||||
ORCHESTRATION_COMPATIBILITY_ATTACHMENT_ENV,
|
||||
ORCHESTRATION_COMPATIBILITY_HOST_ID_ENV,
|
||||
ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION_ENV,
|
||||
ORCHESTRATION_COMPATIBILITY_HOST_KIND_ENV
|
||||
} from '../../shared/orchestration-compatibility-evidence'
|
||||
|
||||
const WSLENV_ENTRY_SEPARATOR = ':'
|
||||
|
||||
function parseWslenvEntries(value: string | undefined): string[] {
|
||||
@@ -70,6 +77,9 @@ export function addOrcaWslInteropEnv(env: Record<string, string>): void {
|
||||
'ORCA_TAB_ID/u',
|
||||
'ORCA_WORKTREE_ID/u',
|
||||
'ORCA_AGENT_LAUNCH_TOKEN/u',
|
||||
'ORCA_ORCHESTRATION_COMPATIBILITY_HOST_KIND/u',
|
||||
'ORCA_ORCHESTRATION_COMPATIBILITY_HOST_ID/u',
|
||||
'ORCA_ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION/u',
|
||||
'ORCA_AGENT_HOOK_PORT/u',
|
||||
'ORCA_AGENT_HOOK_TOKEN/u',
|
||||
'ORCA_AGENT_HOOK_ENV/u',
|
||||
@@ -84,3 +94,22 @@ export function addOrcaWslInteropEnv(env: Record<string, string>): void {
|
||||
]
|
||||
applyWslenvPassthrough(env, passthroughEntries)
|
||||
}
|
||||
|
||||
export function stampWslOrchestrationCompatibilityHost(
|
||||
env: Record<string, string>,
|
||||
hostId: string | null | undefined,
|
||||
distro: string | null | undefined
|
||||
): void {
|
||||
delete env[ORCHESTRATION_COMPATIBILITY_HOST_KIND_ENV]
|
||||
delete env[ORCHESTRATION_COMPATIBILITY_HOST_ID_ENV]
|
||||
delete env[ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION_ENV]
|
||||
delete env[ORCHESTRATION_COMPATIBILITY_ATTACHMENT_ENV]
|
||||
const normalizedHostId = hostId?.trim()
|
||||
const normalizedDistro = distro?.trim()
|
||||
if (!normalizedHostId || !normalizedDistro) {
|
||||
return
|
||||
}
|
||||
env[ORCHESTRATION_COMPATIBILITY_HOST_KIND_ENV] = 'wsl'
|
||||
env[ORCHESTRATION_COMPATIBILITY_HOST_ID_ENV] = normalizedHostId
|
||||
env[ORCHESTRATION_COMPATIBILITY_HOST_INCARNATION_ENV] = normalizedDistro
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { encodePairingOffer } from '../../shared/pairing'
|
||||
import type { PairingOffer } from '../../shared/mobile-relay-pairing-offer'
|
||||
import { encodeMobilePairingQr } from './mobile-pairing-qr'
|
||||
|
||||
function pairingUrl(endpointLength: number, relay: boolean): string {
|
||||
const prefix = 'wss://pair.example/'
|
||||
const offer: PairingOffer = {
|
||||
v: 2,
|
||||
endpoint: `${prefix}${'a'.repeat(Math.max(0, endpointLength - prefix.length))}`,
|
||||
deviceToken: 'd'.repeat(43),
|
||||
publicKeyB64: Buffer.alloc(32, 7).toString('base64'),
|
||||
scope: 'mobile',
|
||||
...(relay
|
||||
? {
|
||||
relay: {
|
||||
v: 1,
|
||||
directorUrl: 'https://director.example',
|
||||
cellUrl: 'https://cell.example',
|
||||
assignmentEpoch: 1,
|
||||
relayHostId: 'a'.repeat(16),
|
||||
inviteToken: 'b'.repeat(43),
|
||||
inviteExpiresAt: Date.now() + 60_000,
|
||||
e2eeFraming: 2
|
||||
}
|
||||
}
|
||||
: {})
|
||||
}
|
||||
return encodePairingOffer(offer)
|
||||
}
|
||||
|
||||
async function discoverEndpointBoundary(relay: boolean): Promise<number> {
|
||||
let passing = 1
|
||||
let failing = 4_000
|
||||
expect((await encodeMobilePairingQr(pairingUrl(passing, relay))).ok).toBe(true)
|
||||
expect((await encodeMobilePairingQr(pairingUrl(failing, relay))).ok).toBe(false)
|
||||
while (failing - passing > 1) {
|
||||
const candidate = Math.floor((passing + failing) / 2)
|
||||
if ((await encodeMobilePairingQr(pairingUrl(candidate, relay))).ok) {
|
||||
passing = candidate
|
||||
} else {
|
||||
failing = candidate
|
||||
}
|
||||
}
|
||||
return passing
|
||||
}
|
||||
|
||||
describe('encodeMobilePairingQr', () => {
|
||||
it.each([
|
||||
['direct', false],
|
||||
['relay', true]
|
||||
] as const)(
|
||||
'uses the real encoder at the adjacent %s-offer capacity boundary',
|
||||
async (_, relay) => {
|
||||
const boundary = await discoverEndpointBoundary(relay)
|
||||
|
||||
await expect(encodeMobilePairingQr(pairingUrl(boundary, relay))).resolves.toMatchObject({
|
||||
ok: true
|
||||
})
|
||||
await expect(encodeMobilePairingQr(pairingUrl(boundary + 1, relay))).resolves.toEqual({
|
||||
ok: false,
|
||||
reason: 'encoding_failed'
|
||||
})
|
||||
}
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
export type MobilePairingQrResult =
|
||||
| { ok: true; qrDataUrl: string }
|
||||
| { ok: false; reason: 'encoding_failed' }
|
||||
|
||||
export async function encodeMobilePairingQr(pairingUrl: string): Promise<MobilePairingQrResult> {
|
||||
try {
|
||||
const { default: QRCode } = await import('qrcode')
|
||||
const qrDataUrl = await QRCode.toDataURL(pairingUrl, {
|
||||
errorCorrectionLevel: 'M',
|
||||
margin: 2,
|
||||
width: 256
|
||||
})
|
||||
return { ok: true, qrDataUrl }
|
||||
} catch {
|
||||
return { ok: false, reason: 'encoding_failed' }
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+1409
-103
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,350 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { AgentHookServer } from '../agent-hooks/server'
|
||||
import { OrcaRuntimeService } from './orca-runtime'
|
||||
|
||||
const PANE_KEY = '11111111-1111-4111-8111-111111111111:22222222-2222-4222-8222-222222222222'
|
||||
const TOKEN = 'launch-secret'
|
||||
const TOKEN_HASH = createHash('sha256').update(TOKEN).digest('hex')
|
||||
|
||||
type TerminalAuthorityResolver = {
|
||||
getOrchestrationDispatchAuthority: (terminalHandle: string) => unknown
|
||||
restoredOrchestrationAuthorityByPtyId: Map<string, Record<string, unknown>>
|
||||
}
|
||||
|
||||
function createRuntime(
|
||||
hostScope:
|
||||
| { kind: 'local'; hostId: 'local' }
|
||||
| { kind: 'wsl'; hostId: 'local'; distro: string }
|
||||
| { kind: 'ssh'; targetId: string },
|
||||
launchTokenHash: string | null = TOKEN_HASH
|
||||
) {
|
||||
const runtime = new OrcaRuntimeService(null, undefined, {
|
||||
attestAgentHookCompatibilityAuthority: ({ paneKey, launchTokenHash, connectionId }) =>
|
||||
paneKey === PANE_KEY &&
|
||||
launchTokenHash === TOKEN_HASH &&
|
||||
connectionId === (hostScope.kind === 'ssh' ? hostScope.targetId : null)
|
||||
? { paneKey, source: 'hydrated_commitment' }
|
||||
: null
|
||||
})
|
||||
const resolveTerminal = vi.fn(() => ({
|
||||
runtimeId: 'runtime-1',
|
||||
terminalHandle: 'term-1',
|
||||
ptyId: 'pty-1',
|
||||
worktreeId: 'repo-1::/worktree',
|
||||
processIncarnation: 'incarnation-1',
|
||||
paneKey: PANE_KEY,
|
||||
launchTokenHash,
|
||||
hostScope
|
||||
}))
|
||||
;(runtime as unknown as TerminalAuthorityResolver).getOrchestrationDispatchAuthority =
|
||||
resolveTerminal
|
||||
if (launchTokenHash === null) {
|
||||
;(runtime as unknown as TerminalAuthorityResolver).restoredOrchestrationAuthorityByPtyId.set(
|
||||
'pty-1',
|
||||
{
|
||||
ptyId: 'pty-1',
|
||||
worktreeId: 'repo-1::/worktree',
|
||||
terminalHandle: 'term-1',
|
||||
paneKey: PANE_KEY,
|
||||
processIncarnation: 'incarnation-1',
|
||||
hostScope
|
||||
}
|
||||
)
|
||||
}
|
||||
return runtime
|
||||
}
|
||||
|
||||
describe('orchestration compatibility runtime authority', () => {
|
||||
it('returns only attested local identity and its token hash', () => {
|
||||
const runtime = createRuntime({ kind: 'local', hostId: 'local' })
|
||||
|
||||
const authority = runtime.verifyOrchestrationCompatibilityCaller({
|
||||
terminalHandle: 'term-1',
|
||||
paneKey: PANE_KEY,
|
||||
launchToken: TOKEN
|
||||
})
|
||||
|
||||
expect(authority).toEqual({
|
||||
hostScope: { kind: 'local', hostId: 'local' },
|
||||
paneKey: PANE_KEY,
|
||||
terminalHandle: 'term-1',
|
||||
processIncarnation: 'incarnation-1',
|
||||
launchTokenHash: TOKEN_HASH
|
||||
})
|
||||
expect(JSON.stringify(authority)).not.toContain(TOKEN)
|
||||
expect(
|
||||
runtime.verifyOrchestrationCompatibilityCaller({
|
||||
terminalHandle: 'term-1',
|
||||
paneKey: PANE_KEY,
|
||||
launchToken: 'wrong'
|
||||
})
|
||||
).toBeNull()
|
||||
expect(
|
||||
runtime.verifyOrchestrationCompatibilityCaller({
|
||||
terminalHandle: 'term-1',
|
||||
paneKey: PANE_KEY,
|
||||
launchToken: TOKEN_HASH
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps local and WSL authority stable across app runtime generations', () => {
|
||||
const firstLocal = createRuntime({ kind: 'local', hostId: 'local' })
|
||||
const secondLocal = createRuntime({ kind: 'local', hostId: 'local' })
|
||||
const wsl = createRuntime({ kind: 'wsl', hostId: 'local', distro: 'Ubuntu' })
|
||||
const localEvidence = {
|
||||
terminalHandle: 'term-1',
|
||||
paneKey: PANE_KEY,
|
||||
launchToken: TOKEN
|
||||
}
|
||||
const wslEvidence = {
|
||||
...localEvidence,
|
||||
host: { kind: 'wsl', hostId: 'local', distro: 'Ubuntu' }
|
||||
} as const
|
||||
|
||||
expect(firstLocal.verifyOrchestrationCompatibilityCaller(localEvidence)?.hostScope).toEqual(
|
||||
secondLocal.verifyOrchestrationCompatibilityCaller(localEvidence)?.hostScope
|
||||
)
|
||||
expect(wsl.verifyOrchestrationCompatibilityCaller(wslEvidence)?.hostScope).toEqual({
|
||||
kind: 'wsl',
|
||||
hostId: 'local',
|
||||
distro: 'Ubuntu'
|
||||
})
|
||||
expect(wsl.verifyOrchestrationCompatibilityCaller(localEvidence)).toBeNull()
|
||||
expect(
|
||||
wsl.verifyOrchestrationCompatibilityCaller({
|
||||
...wslEvidence,
|
||||
host: { kind: 'wsl', hostId: 'runtime-before-restart', distro: 'Ubuntu' }
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('requires a live exact terminal even when the hook proof is hydrated', () => {
|
||||
const runtime = createRuntime({ kind: 'local', hostId: 'local' })
|
||||
;(runtime as unknown as TerminalAuthorityResolver).getOrchestrationDispatchAuthority = () =>
|
||||
null
|
||||
|
||||
expect(
|
||||
runtime.verifyOrchestrationCompatibilityCaller({
|
||||
terminalHandle: 'term-1',
|
||||
paneKey: PANE_KEY,
|
||||
launchToken: TOKEN
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('uses the hydrated hook commitment for a restored exact PTY', () => {
|
||||
const restored = createRuntime({ kind: 'local', hostId: 'local' }, null)
|
||||
const uncommitted = new OrcaRuntimeService()
|
||||
;(uncommitted as unknown as TerminalAuthorityResolver).getOrchestrationDispatchAuthority =
|
||||
() => ({
|
||||
runtimeId: 'runtime-1',
|
||||
terminalHandle: 'term-1',
|
||||
ptyId: 'pty-1',
|
||||
worktreeId: 'repo-1::/worktree',
|
||||
processIncarnation: 'incarnation-1',
|
||||
paneKey: PANE_KEY,
|
||||
launchTokenHash: null,
|
||||
hostScope: { kind: 'local', hostId: 'local' }
|
||||
})
|
||||
const evidence = {
|
||||
terminalHandle: 'term-1',
|
||||
paneKey: PANE_KEY,
|
||||
launchToken: TOKEN
|
||||
}
|
||||
|
||||
expect(restored.verifyOrchestrationCompatibilityCaller(evidence)).toMatchObject({
|
||||
processIncarnation: 'incarnation-1',
|
||||
launchTokenHash: TOKEN_HASH
|
||||
})
|
||||
expect(uncommitted.verifyOrchestrationCompatibilityCaller(evidence)).toBeNull()
|
||||
expect(
|
||||
restored.verifyOrchestrationCompatibilityCaller({
|
||||
...evidence,
|
||||
launchToken: 'wrong'
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it.each([
|
||||
['PTY', { ptyId: 'pty-other' }],
|
||||
['worktree', { worktreeId: 'repo-1::/other' }],
|
||||
['terminal handle', { terminalHandle: 'term-other' }],
|
||||
[
|
||||
'pane',
|
||||
{ paneKey: '33333333-3333-4333-8333-333333333333:44444444-4444-4444-8444-444444444444' }
|
||||
],
|
||||
['process incarnation', { processIncarnation: 'incarnation-other' }]
|
||||
])('rejects a restored receipt with mismatched %s identity', (_field, mismatch) => {
|
||||
const runtime = createRuntime({ kind: 'local', hostId: 'local' }, null)
|
||||
const internals = runtime as unknown as TerminalAuthorityResolver
|
||||
const receipt = internals.restoredOrchestrationAuthorityByPtyId.get('pty-1')!
|
||||
internals.restoredOrchestrationAuthorityByPtyId.set('pty-1', { ...receipt, ...mismatch })
|
||||
|
||||
expect(
|
||||
runtime.verifyOrchestrationCompatibilityCaller({
|
||||
terminalHandle: 'term-1',
|
||||
paneKey: PANE_KEY,
|
||||
launchToken: TOKEN
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects restored receipts from a different WSL distro or SSH target', () => {
|
||||
const wsl = createRuntime({ kind: 'wsl', hostId: 'local', distro: 'Ubuntu' }, null)
|
||||
const wslInternals = wsl as unknown as TerminalAuthorityResolver
|
||||
const wslReceipt = wslInternals.restoredOrchestrationAuthorityByPtyId.get('pty-1')!
|
||||
wslInternals.restoredOrchestrationAuthorityByPtyId.set('pty-1', {
|
||||
...wslReceipt,
|
||||
hostScope: { kind: 'wsl', hostId: 'local', distro: 'Debian' }
|
||||
})
|
||||
expect(
|
||||
wsl.verifyOrchestrationCompatibilityCaller({
|
||||
terminalHandle: 'term-1',
|
||||
paneKey: PANE_KEY,
|
||||
launchToken: TOKEN,
|
||||
host: { kind: 'wsl', hostId: 'local', distro: 'Ubuntu' }
|
||||
})
|
||||
).toBeNull()
|
||||
|
||||
const ssh = createRuntime({ kind: 'ssh', targetId: 'saved-target' }, null)
|
||||
const sshInternals = ssh as unknown as TerminalAuthorityResolver
|
||||
const sshReceipt = sshInternals.restoredOrchestrationAuthorityByPtyId.get('pty-1')!
|
||||
sshInternals.restoredOrchestrationAuthorityByPtyId.set('pty-1', {
|
||||
...sshReceipt,
|
||||
hostScope: { kind: 'ssh', targetId: 'other-target' }
|
||||
})
|
||||
const host = ssh.registerOrchestrationCompatibilitySshAttachment('saved-target', 'connection-1')
|
||||
expect(
|
||||
ssh.verifyOrchestrationCompatibilityCaller({
|
||||
terminalHandle: 'term-1',
|
||||
paneKey: PANE_KEY,
|
||||
launchToken: TOKEN,
|
||||
host
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('does not fall back to a restored receipt when a fresh launch token mismatches', () => {
|
||||
const runtime = createRuntime({ kind: 'local', hostId: 'local' })
|
||||
;(runtime as unknown as TerminalAuthorityResolver).restoredOrchestrationAuthorityByPtyId.set(
|
||||
'pty-1',
|
||||
{
|
||||
ptyId: 'pty-1',
|
||||
worktreeId: 'repo-1::/worktree',
|
||||
terminalHandle: 'term-1',
|
||||
paneKey: PANE_KEY,
|
||||
processIncarnation: 'incarnation-1',
|
||||
hostScope: { kind: 'local', hostId: 'local' }
|
||||
}
|
||||
)
|
||||
|
||||
expect(
|
||||
runtime.verifyOrchestrationCompatibilityCaller({
|
||||
terminalHandle: 'term-1',
|
||||
paneKey: PANE_KEY,
|
||||
launchToken: 'wrong'
|
||||
})
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('attests current coordinators immediately without upgrading restored legacy callers', () => {
|
||||
const server = new AgentHookServer()
|
||||
server.ingestRemote(
|
||||
{
|
||||
paneKey: PANE_KEY,
|
||||
launchToken: TOKEN,
|
||||
payload: { state: 'working', prompt: 'coordinate', agentType: 'codex' }
|
||||
},
|
||||
'saved-target'
|
||||
)
|
||||
const createIntegratedRuntime = (launchTokenHash: string | null): OrcaRuntimeService => {
|
||||
const runtime = new OrcaRuntimeService(null, undefined, {
|
||||
attestAgentHookCompatibilityAuthority: (candidate) =>
|
||||
server.attestCompatibilityAuthority(candidate)
|
||||
})
|
||||
;(runtime as unknown as TerminalAuthorityResolver).getOrchestrationDispatchAuthority = vi.fn(
|
||||
() => ({
|
||||
runtimeId: 'runtime-1',
|
||||
terminalHandle: 'term-1',
|
||||
ptyId: 'pty-1',
|
||||
worktreeId: 'repo-1::/worktree',
|
||||
processIncarnation: 'incarnation-1',
|
||||
paneKey: PANE_KEY,
|
||||
launchTokenHash,
|
||||
hostScope: { kind: 'ssh', targetId: 'saved-target' }
|
||||
})
|
||||
)
|
||||
if (launchTokenHash === null) {
|
||||
;(
|
||||
runtime as unknown as TerminalAuthorityResolver
|
||||
).restoredOrchestrationAuthorityByPtyId.set('pty-1', {
|
||||
ptyId: 'pty-1',
|
||||
worktreeId: 'repo-1::/worktree',
|
||||
terminalHandle: 'term-1',
|
||||
paneKey: PANE_KEY,
|
||||
processIncarnation: 'incarnation-1',
|
||||
hostScope: { kind: 'ssh', targetId: 'saved-target' }
|
||||
})
|
||||
}
|
||||
return runtime
|
||||
}
|
||||
const evidenceFor = (runtime: OrcaRuntimeService, launchToken = TOKEN) => ({
|
||||
terminalHandle: 'term-1',
|
||||
paneKey: PANE_KEY,
|
||||
launchToken,
|
||||
host: runtime.registerOrchestrationCompatibilitySshAttachment('saved-target', 'connection-1')
|
||||
})
|
||||
|
||||
const current = createIntegratedRuntime(TOKEN_HASH)
|
||||
expect(current.verifyOrchestrationCompatibilityCaller(evidenceFor(current))).not.toBeNull()
|
||||
|
||||
const restored = createIntegratedRuntime(null)
|
||||
expect(restored.verifyOrchestrationCompatibilityCaller(evidenceFor(restored))).toBeNull()
|
||||
|
||||
server.ingestRemote(
|
||||
{
|
||||
paneKey: '33333333-3333-4333-8333-333333333333:44444444-4444-4444-8444-444444444444',
|
||||
launchToken: TOKEN,
|
||||
payload: { state: 'working', prompt: 'duplicate', agentType: 'codex' }
|
||||
},
|
||||
'saved-target'
|
||||
)
|
||||
expect(current.verifyOrchestrationCompatibilityCaller(evidenceFor(current))).toBeNull()
|
||||
|
||||
const mismatchedToken = 'different-launch-secret'
|
||||
const mismatched = createIntegratedRuntime(
|
||||
createHash('sha256').update(mismatchedToken).digest('hex')
|
||||
)
|
||||
expect(
|
||||
mismatched.verifyOrchestrationCompatibilityCaller(evidenceFor(mismatched, mismatchedToken))
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts only a live runtime-issued SSH attachment', () => {
|
||||
const runtime = createRuntime({ kind: 'ssh', targetId: 'saved-target' })
|
||||
const host = runtime.registerOrchestrationCompatibilitySshAttachment(
|
||||
'saved-target',
|
||||
'connection-1'
|
||||
)
|
||||
const evidence = {
|
||||
terminalHandle: 'term-1',
|
||||
paneKey: PANE_KEY,
|
||||
launchToken: TOKEN,
|
||||
host
|
||||
} as const
|
||||
|
||||
expect(runtime.verifyOrchestrationCompatibilityCaller(evidence)).not.toBeNull()
|
||||
expect(
|
||||
runtime.verifyOrchestrationCompatibilityCaller({
|
||||
...evidence,
|
||||
host: { ...host, attachmentId: 'caller-chosen' }
|
||||
})
|
||||
).toBeNull()
|
||||
|
||||
runtime.releaseOrchestrationCompatibilitySshAttachment(host.attachmentId)
|
||||
|
||||
expect(runtime.verifyOrchestrationCompatibilityCaller(evidence)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -942,7 +942,7 @@ describe('OrchestrationDb', () => {
|
||||
|
||||
// v1 data preserved
|
||||
expect(d.getMessageById('msg_v1')?.subject).toBe('pre-migration')
|
||||
expect(d.getMessageById('msg_v1')?.run_id).toBe(LEGACY_RUN_ID)
|
||||
expect(d.getMessageById('msg_v1')?.run_id).toBe(d.getLegacyAdoption()?.adopted_run_id)
|
||||
expect(d.getRun(LEGACY_RUN_ID)).toMatchObject({ legacy: 1 })
|
||||
})
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -77,6 +77,14 @@ describe('formatMessageBanner', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('lets the CLI resolve the live sender for Run and Dispatch addresses', () => {
|
||||
for (const to_handle of ['run:run_test', 'dispatch:dispatch_test']) {
|
||||
const banner = formatMessageBanner(makeMessage({ to_handle }))
|
||||
expect(banner).toContain('[Reply: orca orchestration reply --id msg_test1 --body "..."]')
|
||||
expect(banner).not.toContain(`--from ${to_handle}`)
|
||||
}
|
||||
})
|
||||
|
||||
it('marks legacy messages read-only without reply or acknowledgment affordances', () => {
|
||||
const banner = formatMessageBanner(
|
||||
makeMessage({ id: 'msg_legacy', run_id: 'run_legacy_local' })
|
||||
@@ -88,6 +96,63 @@ describe('formatMessageBanner', () => {
|
||||
expect(banner).not.toContain('orchestration reply')
|
||||
})
|
||||
|
||||
it('renders only attested actions for legacy compatibility authority', () => {
|
||||
const banner = formatMessageBanner(makeMessage({ id: 'msg_legacy' }), {
|
||||
authority: 'legacy_compatibility',
|
||||
supportedActionHints: [
|
||||
'orca orchestration reply --id msg_legacy --from term_coord --body "..."'
|
||||
]
|
||||
})
|
||||
|
||||
expect(banner).toContain('[LEGACY COMPATIBILITY]')
|
||||
expect(banner).toContain(
|
||||
'[Supported action: orca orchestration reply --id msg_legacy --from term_coord --body "..."]'
|
||||
)
|
||||
expect(banner).not.toContain('[Reply:')
|
||||
expect(banner).not.toContain('acknowledgment')
|
||||
})
|
||||
|
||||
it('warns that a bounded legacy recovery replay may already have been seen', () => {
|
||||
const banner = formatMessageBanner(makeMessage(), {
|
||||
authority: 'legacy_recovery_replay',
|
||||
supportedActionHints: ['orca orchestration check --ack delivery_legacy']
|
||||
})
|
||||
|
||||
expect(banner).toContain('[LEGACY RECOVERY REPLAY — MAY HAVE BEEN SEEN]')
|
||||
expect(banner).toContain('bounded recovery replay may already have been seen')
|
||||
expect(banner).toContain('[Supported action: orca orchestration check --ack delivery_legacy]')
|
||||
expect(banner).not.toContain('[Reply:')
|
||||
})
|
||||
|
||||
it('does not infer live compatibility from legacy database provenance', () => {
|
||||
const banner = formatMessageBanner(makeMessage({ run_id: 'run_legacy_local' }), {
|
||||
supportedActionHints: ['orca orchestration check --ack delivery_legacy']
|
||||
})
|
||||
|
||||
expect(banner).toContain('[LEGACY READ-ONLY]')
|
||||
expect(banner).not.toContain('Supported action:')
|
||||
expect(banner).not.toContain('check --ack')
|
||||
})
|
||||
|
||||
it('keeps adopted legacy and audit messages read-only without runtime authority', () => {
|
||||
for (const deliveryContract of ['legacy_direct', 'audit_only'] as const) {
|
||||
const banner = formatMessageBanner(
|
||||
makeMessage({ run_id: 'run_adopted', delivery_contract: deliveryContract })
|
||||
)
|
||||
|
||||
expect(banner).toContain('[LEGACY READ-ONLY]')
|
||||
expect(banner).not.toContain('[Reply:')
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps current formatting unchanged when authority is explicit', () => {
|
||||
const message = makeMessage({ id: 'msg_current' })
|
||||
|
||||
expect(formatMessageBanner(message, { authority: 'current' })).toBe(
|
||||
formatMessageBanner(message)
|
||||
)
|
||||
})
|
||||
|
||||
it('ends with a separator line', () => {
|
||||
const banner = formatMessageBanner(makeMessage())
|
||||
const lines = banner.split('\n')
|
||||
|
||||
@@ -4,19 +4,77 @@ import { ORCHESTRATION_LEGACY_RUN_ID } from '../../../shared/orchestration-rpc-c
|
||||
const BANNER_WIDTH = 60
|
||||
const SEPARATOR = '─'.repeat(BANNER_WIDTH)
|
||||
|
||||
export function formatMessageBanner(msg: MessageRow): string {
|
||||
export type MessageFormattingAuthority =
|
||||
| 'current'
|
||||
| 'legacy_compatibility'
|
||||
| 'legacy_recovery_replay'
|
||||
| 'legacy_read_only'
|
||||
|
||||
export type MessageFormattingOptions = {
|
||||
authority?: MessageFormattingAuthority
|
||||
supportedActionHints?: readonly string[]
|
||||
}
|
||||
|
||||
function resolveAuthority(
|
||||
msg: MessageRow,
|
||||
authority: MessageFormattingAuthority | undefined
|
||||
): MessageFormattingAuthority {
|
||||
if (authority) {
|
||||
return authority
|
||||
}
|
||||
return msg.run_id === ORCHESTRATION_LEGACY_RUN_ID ||
|
||||
msg.delivery_contract === 'legacy_direct' ||
|
||||
msg.delivery_contract === 'audit_only'
|
||||
? 'legacy_read_only'
|
||||
: 'current'
|
||||
}
|
||||
|
||||
function appendLegacyGuidance(
|
||||
lines: string[],
|
||||
authority: MessageFormattingAuthority,
|
||||
supportedActionHints: readonly string[]
|
||||
): void {
|
||||
if (authority === 'legacy_read_only') {
|
||||
lines.push('[Inspection only: reply and acknowledgment are unavailable.]')
|
||||
return
|
||||
}
|
||||
if (authority === 'legacy_compatibility') {
|
||||
lines.push('[Use only the supported legacy action shown below.]')
|
||||
} else if (authority === 'legacy_recovery_replay') {
|
||||
lines.push(
|
||||
'[This bounded recovery replay may already have been seen. Use only the action shown below.]'
|
||||
)
|
||||
}
|
||||
for (const hint of supportedActionHints) {
|
||||
lines.push(`[Supported action: ${hint}]`)
|
||||
}
|
||||
}
|
||||
|
||||
export function formatMessageBanner(msg: MessageRow, options: MessageFormattingOptions): string
|
||||
export function formatMessageBanner(msg: MessageRow): string
|
||||
export function formatMessageBanner(
|
||||
msg: MessageRow,
|
||||
options: MessageFormattingOptions = {}
|
||||
): string {
|
||||
const priorityTag =
|
||||
msg.priority === 'urgent' ? ' [URGENT]' : msg.priority === 'high' ? ' [HIGH]' : ''
|
||||
const legacyReadOnly = msg.run_id === ORCHESTRATION_LEGACY_RUN_ID
|
||||
const authorityTag = legacyReadOnly ? ' [LEGACY READ-ONLY]' : ''
|
||||
const authority = resolveAuthority(msg, options.authority)
|
||||
const authorityTag =
|
||||
authority === 'legacy_compatibility'
|
||||
? ' [LEGACY COMPATIBILITY]'
|
||||
: authority === 'legacy_recovery_replay'
|
||||
? ' [LEGACY RECOVERY REPLAY — MAY HAVE BEEN SEEN]'
|
||||
: authority === 'legacy_read_only'
|
||||
? ' [LEGACY READ-ONLY]'
|
||||
: ''
|
||||
const senderName = msg.from_handle.toUpperCase()
|
||||
|
||||
const header = `──── From: ${senderName} (${msg.from_handle})${priorityTag}${authorityTag} (${msg.type}) ────`
|
||||
|
||||
const lines: string[] = [header]
|
||||
lines.push(`Subject: ${msg.subject}`)
|
||||
if (legacyReadOnly) {
|
||||
lines.push('[Inspection only: reply and acknowledgment are unavailable.]')
|
||||
if (authority !== 'current') {
|
||||
appendLegacyGuidance(lines, authority, options.supportedActionHints ?? [])
|
||||
}
|
||||
|
||||
if (msg.body) {
|
||||
@@ -27,11 +85,12 @@ export function formatMessageBanner(msg: MessageRow): string {
|
||||
lines.push(`[Payload: ${msg.payload}]`)
|
||||
}
|
||||
|
||||
if (!legacyReadOnly) {
|
||||
// Why: older shells can lack Orca's terminal identity environment.
|
||||
lines.push(
|
||||
`[Reply: orca orchestration reply --id ${msg.id} --from ${msg.to_handle} --body "..."]`
|
||||
)
|
||||
if (authority === 'current') {
|
||||
const explicitFrom =
|
||||
msg.to_handle.startsWith('run:') || msg.to_handle.startsWith('dispatch:')
|
||||
? ''
|
||||
: ` --from ${msg.to_handle}`
|
||||
lines.push(`[Reply: orca orchestration reply --id ${msg.id}${explicitFrom} --body "..."]`)
|
||||
}
|
||||
lines.push(SEPARATOR)
|
||||
|
||||
|
||||
@@ -0,0 +1,381 @@
|
||||
import { rmSync } from 'node:fs'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import Database from '../../sqlite/sync-database'
|
||||
import { LEGACY_RUN_ID, OrchestrationDb } from './db'
|
||||
import {
|
||||
createLegacyStorageCutoverFixture,
|
||||
type LegacyStorageCutoverFixture
|
||||
} from './orchestration-legacy-storage-test-fixture'
|
||||
|
||||
describe('OrchestrationDb legacy coordinator authority', () => {
|
||||
let db: OrchestrationDb | undefined
|
||||
let tempDir: string | undefined
|
||||
|
||||
afterEach(() => {
|
||||
db?.close()
|
||||
db = undefined
|
||||
if (tempDir) {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
tempDir = undefined
|
||||
}
|
||||
})
|
||||
|
||||
function createCutoverFixture(): LegacyStorageCutoverFixture {
|
||||
const created = createLegacyStorageCutoverFixture()
|
||||
tempDir = created.tempDir
|
||||
return created.fixture
|
||||
}
|
||||
|
||||
function openAdoptedFixture(): {
|
||||
fixture: LegacyStorageCutoverFixture
|
||||
adoptedRunId: string
|
||||
workerPrincipalId: string
|
||||
} {
|
||||
const fixture = createCutoverFixture()
|
||||
db = new OrchestrationDb(fixture.dbPath)
|
||||
const adoptedRunId = db.getLegacyAdoption()?.adopted_run_id as string
|
||||
const worker = db.commitLegacyCompatibilityPrincipal({
|
||||
runId: adoptedRunId,
|
||||
dispatchId: fixture.legacyDispatchId,
|
||||
role: 'worker',
|
||||
hostScope: 'local:runtime_1',
|
||||
terminalHandle: 'term_legacy_worker',
|
||||
paneKey: 'tab_legacy:33333333-3333-4333-8333-333333333333',
|
||||
launchTokenHash: 'legacy_launch_hash',
|
||||
processIncarnation: 'process_1'
|
||||
})
|
||||
return {
|
||||
fixture,
|
||||
adoptedRunId,
|
||||
workerPrincipalId: worker.principal.id
|
||||
}
|
||||
}
|
||||
|
||||
it('records exact scheduler loss without admitting naturally settled coordinators', () => {
|
||||
const fixture = createCutoverFixture()
|
||||
const raw = new Database(fixture.dbPath)
|
||||
raw.exec(`
|
||||
UPDATE tasks
|
||||
SET created_by_terminal_handle = 'term_manual_coord'
|
||||
WHERE run_id = '${LEGACY_RUN_ID}';
|
||||
UPDATE messages
|
||||
SET from_handle = CASE
|
||||
WHEN from_handle = 'term_legacy_coord' THEN 'term_manual_coord'
|
||||
ELSE from_handle
|
||||
END,
|
||||
to_handle = CASE
|
||||
WHEN to_handle = 'term_legacy_coord' THEN 'term_manual_coord'
|
||||
ELSE to_handle
|
||||
END
|
||||
WHERE run_id = '${LEGACY_RUN_ID}';
|
||||
INSERT INTO coordinator_runs (
|
||||
id, spec, status, coordinator_handle, created_at
|
||||
) VALUES (
|
||||
'coordinator_manual', 'manual legacy coordinator', 'running',
|
||||
'term_manual_coord', datetime('now', '-1 minute')
|
||||
);
|
||||
INSERT INTO coordinator_runs (
|
||||
id, spec, status, coordinator_handle, created_at, completed_at
|
||||
) VALUES (
|
||||
'coordinator_natural', 'naturally completed coordinator', 'completed',
|
||||
'term_natural_coord', datetime('now', '-2 minutes'),
|
||||
'2099-01-01T00:00:00.000Z'
|
||||
);
|
||||
`)
|
||||
raw.close()
|
||||
|
||||
db = new OrchestrationDb(fixture.dbPath)
|
||||
const adoptedRunId = db.getLegacyAdoption()?.adopted_run_id as string
|
||||
expect(db.getActiveCoordinatorRun()).toBeUndefined()
|
||||
const adoption = db.getLegacyAdoption()!
|
||||
const migratedCoordinator = db.getCoordinatorRun('coordinator_manual')!
|
||||
expect(migratedCoordinator).toMatchObject({
|
||||
status: 'failed',
|
||||
completed_at: adoption.adopted_at,
|
||||
scheduler_lost_at: adoption.adopted_at
|
||||
})
|
||||
expect(db.getCoordinatorRun('coordinator_natural')).toMatchObject({
|
||||
status: 'completed',
|
||||
completed_at: '2099-01-01T00:00:00.000Z',
|
||||
scheduler_lost_at: null
|
||||
})
|
||||
expect(
|
||||
db.resolveLegacyCoordinatorCandidate({
|
||||
runId: adoptedRunId,
|
||||
terminalHandle: 'term_manual_coord',
|
||||
paneKey: 'tab_manual:44444444-4444-4444-8444-444444444444'
|
||||
})
|
||||
).toMatchObject({ terminalHandle: 'term_manual_coord' })
|
||||
expect(db.isLegacyCoordinatorHandle(adoptedRunId, 'term_natural_coord')).toBe(false)
|
||||
|
||||
db.close()
|
||||
db = new OrchestrationDb(fixture.dbPath)
|
||||
expect(db.getLegacyAdoption()).toEqual(adoption)
|
||||
expect(db.getCoordinatorRun('coordinator_manual')).toEqual(migratedCoordinator)
|
||||
expect(
|
||||
db.resolveLegacyCoordinatorCandidate({
|
||||
runId: adoptedRunId,
|
||||
terminalHandle: 'term_manual_coord',
|
||||
paneKey: 'tab_manual:44444444-4444-4444-8444-444444444444'
|
||||
})
|
||||
).toMatchObject({ terminalHandle: 'term_manual_coord' })
|
||||
})
|
||||
|
||||
it('fails closed when multiple pre-cutover schedulers lose authority', () => {
|
||||
const fixture = createCutoverFixture()
|
||||
const raw = new Database(fixture.dbPath)
|
||||
raw.exec(`
|
||||
INSERT INTO coordinator_runs (
|
||||
id, spec, status, coordinator_handle, created_at
|
||||
) VALUES
|
||||
('coordinator_first', 'first', 'running', 'term_first_coord', datetime('now', '-2 minutes')),
|
||||
('coordinator_second', 'second', 'running', 'term_second_coord', datetime('now', '-1 minute'));
|
||||
`)
|
||||
raw.close()
|
||||
|
||||
db = new OrchestrationDb(fixture.dbPath)
|
||||
const adoption = db.getLegacyAdoption()!
|
||||
const adoptedRunId = adoption.adopted_run_id
|
||||
expect(db.getActiveCoordinatorRun()).toBeUndefined()
|
||||
expect(db.getCoordinatorRun('coordinator_first')).toMatchObject({
|
||||
status: 'failed',
|
||||
scheduler_lost_at: adoption.adopted_at
|
||||
})
|
||||
expect(db.getCoordinatorRun('coordinator_second')).toMatchObject({
|
||||
status: 'failed',
|
||||
scheduler_lost_at: adoption.adopted_at
|
||||
})
|
||||
expect(
|
||||
db.resolveLegacyCoordinatorCandidate({
|
||||
runId: adoptedRunId,
|
||||
terminalHandle: 'term_legacy_coord',
|
||||
paneKey: 'tab_manual:44444444-4444-4444-8444-444444444444'
|
||||
})
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not infer a coordinator from worker-to-worker legacy mail', () => {
|
||||
const fixture = createCutoverFixture()
|
||||
const raw = new Database(fixture.dbPath)
|
||||
raw.exec(`
|
||||
INSERT INTO tasks (
|
||||
id, run_id, spec, status, created_by_terminal_handle
|
||||
) VALUES (
|
||||
'task_second_worker', '${LEGACY_RUN_ID}', 'second worker',
|
||||
'dispatched', 'term_legacy_coord'
|
||||
);
|
||||
INSERT INTO dispatch_contexts (
|
||||
id, run_id, task_id, contract_version, assignee_handle,
|
||||
assignee_pane_key, status, dispatched_at
|
||||
) VALUES (
|
||||
'dispatch_second_worker', '${LEGACY_RUN_ID}', 'task_second_worker', 0,
|
||||
'term_second_worker', 'tab_second:55555555-5555-4555-8555-555555555555',
|
||||
'dispatched', datetime('now')
|
||||
);
|
||||
INSERT INTO messages (
|
||||
id, run_id, from_handle, to_handle, subject
|
||||
) VALUES (
|
||||
'message_worker_to_worker', '${LEGACY_RUN_ID}', 'term_legacy_worker',
|
||||
'term_second_worker', 'peer coordination'
|
||||
);
|
||||
`)
|
||||
raw.close()
|
||||
|
||||
db = new OrchestrationDb(fixture.dbPath)
|
||||
const adoptedRunId = db.getLegacyAdoption()?.adopted_run_id as string
|
||||
expect(db.isLegacyCoordinatorHandle(adoptedRunId, 'term_second_worker')).toBe(false)
|
||||
expect(db.isLegacyCoordinatorHandle(adoptedRunId, 'term_legacy_worker')).toBe(false)
|
||||
expect(db.isLegacyCoordinatorHandle(adoptedRunId, 'term_legacy_coord')).toBe(true)
|
||||
})
|
||||
|
||||
it('promotes only the unacknowledged coordinator recovery cohort during takeover', () => {
|
||||
const fixture = createCutoverFixture()
|
||||
db = new OrchestrationDb(fixture.dbPath)
|
||||
const adoptedRunId = db.getLegacyAdoption()?.adopted_run_id as string
|
||||
const unacknowledged = db.insertMessage({
|
||||
runId: adoptedRunId,
|
||||
deliveryContract: 'legacy_direct',
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'second recovered coordinator outcome'
|
||||
})
|
||||
db.markAsRead([unacknowledged.id])
|
||||
const coordinator = db.commitLegacyCompatibilityPrincipal({
|
||||
runId: adoptedRunId,
|
||||
role: 'coordinator',
|
||||
hostScope: 'local:runtime_1',
|
||||
terminalHandle: 'term_legacy_coord',
|
||||
paneKey: 'tab_coord:44444444-4444-4444-8444-444444444444',
|
||||
launchTokenHash: 'coord_launch_hash',
|
||||
processIncarnation: 'process_coord'
|
||||
}).principal
|
||||
const firstPage = db.getLegacyMailPage({ principalId: coordinator.id, limit: 1 })
|
||||
expect(firstPage.recovery).toBe(true)
|
||||
db.acknowledgeLegacyMail({
|
||||
principalId: coordinator.id,
|
||||
messageIds: firstPage.messages.map((message) => message.id)
|
||||
})
|
||||
const acknowledgedId = firstPage.messages[0].id
|
||||
|
||||
db.bindRun({
|
||||
runId: adoptedRunId,
|
||||
coordinatorHandle: 'term_current_coord',
|
||||
coordinatorPaneKey: 'tab_current:11111111-1111-4111-8111-111111111111',
|
||||
takeoverLegacy: true
|
||||
})
|
||||
|
||||
expect(db.getMessageById(acknowledgedId)).toMatchObject({
|
||||
to_handle: 'term_legacy_coord',
|
||||
delivery_contract: 'legacy_direct',
|
||||
read: 1
|
||||
})
|
||||
expect(db.getMessageById(unacknowledged.id)).toMatchObject({
|
||||
to_handle: `run:${adoptedRunId}`,
|
||||
delivery_contract: 'current_delivery',
|
||||
read: 0
|
||||
})
|
||||
})
|
||||
|
||||
it('promotes a pre-cutover read recovery message when takeover precedes attestation', () => {
|
||||
const fixture = createCutoverFixture()
|
||||
db = new OrchestrationDb(fixture.dbPath)
|
||||
const adoptedRunId = db.getLegacyAdoption()?.adopted_run_id as string
|
||||
const recoveryMessageId = fixture.legacyMessageIds[1]
|
||||
expect(db.getLegacyCoordinatorPrincipal(adoptedRunId)).toBeUndefined()
|
||||
expect(db.getMessageById(recoveryMessageId)).toMatchObject({
|
||||
to_handle: 'term_legacy_coord',
|
||||
delivery_contract: 'legacy_direct',
|
||||
read: 1
|
||||
})
|
||||
|
||||
const run = db.bindRun({
|
||||
runId: adoptedRunId,
|
||||
coordinatorHandle: 'term_current_coord',
|
||||
coordinatorPaneKey: 'tab_current:11111111-1111-4111-8111-111111111111',
|
||||
takeoverLegacy: true
|
||||
})!
|
||||
expect(db.getMessageById(recoveryMessageId)).toMatchObject({
|
||||
to_handle: `run:${adoptedRunId}`,
|
||||
delivery_contract: 'current_delivery',
|
||||
read: 0
|
||||
})
|
||||
|
||||
const first = db.getOrCreateRunDelivery({
|
||||
runId: adoptedRunId,
|
||||
consumerGeneration: run.consumer_generation
|
||||
})!
|
||||
const replay = db.getOrCreateRunDelivery({
|
||||
runId: adoptedRunId,
|
||||
consumerGeneration: run.consumer_generation
|
||||
})!
|
||||
expect(first.messages.map((message) => message.id)).toContain(recoveryMessageId)
|
||||
expect(replay).toMatchObject({ replayed: true, delivery: { id: first.delivery.id } })
|
||||
|
||||
db.acknowledgeRunDelivery({
|
||||
runId: adoptedRunId,
|
||||
consumerGeneration: run.consumer_generation,
|
||||
deliveryId: first.delivery.id
|
||||
})
|
||||
expect(
|
||||
db
|
||||
.getOrCreateRunDelivery({
|
||||
runId: adoptedRunId,
|
||||
consumerGeneration: run.consumer_generation
|
||||
})
|
||||
?.messages.map((message) => message.id) ?? []
|
||||
).not.toContain(recoveryMessageId)
|
||||
})
|
||||
|
||||
it('promotes retained mail on an ordinary post-settlement coordinator replacement', () => {
|
||||
const state = openAdoptedFixture()
|
||||
const coordinator = db!.commitLegacyCompatibilityPrincipal({
|
||||
runId: state.adoptedRunId,
|
||||
role: 'coordinator',
|
||||
hostScope: 'local:runtime_1',
|
||||
terminalHandle: 'term_legacy_coord',
|
||||
paneKey: 'tab_coord:44444444-4444-4444-8444-444444444444',
|
||||
launchTokenHash: 'coord_launch_hash',
|
||||
processIncarnation: 'process_coord'
|
||||
}).principal
|
||||
const completion = db!.insertMessage({
|
||||
runId: state.adoptedRunId,
|
||||
deliveryContract: 'legacy_direct',
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'Completed before ordinary run-use',
|
||||
type: 'worker_done'
|
||||
})
|
||||
db!.settleWorkerReport({
|
||||
taskId: state.fixture.legacyTaskId,
|
||||
dispatchId: state.fixture.legacyDispatchId,
|
||||
outcome: 'succeeded',
|
||||
result: 'done'
|
||||
})
|
||||
|
||||
const run = db!.bindRun({
|
||||
runId: state.adoptedRunId,
|
||||
coordinatorHandle: 'term_current_coord',
|
||||
coordinatorPaneKey: 'tab_current:11111111-1111-4111-8111-111111111111'
|
||||
})!
|
||||
|
||||
expect(db!.getLegacyCompatibilityPrincipal(coordinator.id)?.status).toBe('revoked')
|
||||
expect(db!.getMessageById(completion.id)).toMatchObject({
|
||||
to_handle: `run:${state.adoptedRunId}`,
|
||||
delivery_contract: 'current_delivery',
|
||||
read: 0
|
||||
})
|
||||
expect(
|
||||
db!
|
||||
.getOrCreateRunDelivery({
|
||||
runId: state.adoptedRunId,
|
||||
consumerGeneration: run.consumer_generation
|
||||
})
|
||||
?.messages.map((message) => message.id)
|
||||
).toContain(completion.id)
|
||||
})
|
||||
|
||||
it('acknowledges the exact current Run answer to a legacy ask after takeover', () => {
|
||||
const state = openAdoptedFixture()
|
||||
const ask = db!.commitLegacyAskOperation({
|
||||
principalId: state.workerPrincipalId,
|
||||
operationKey: 'ask_before_takeover',
|
||||
method: 'orchestration.ask',
|
||||
payloadHash: 'ask_before_takeover_payload',
|
||||
question: 'Continue after takeover?',
|
||||
recipientHandle: 'term_legacy_coord'
|
||||
})
|
||||
const run = db!.bindRun({
|
||||
runId: state.adoptedRunId,
|
||||
coordinatorHandle: 'term_current_coord',
|
||||
coordinatorPaneKey: 'tab_current:11111111-1111-4111-8111-111111111111',
|
||||
takeoverLegacy: true
|
||||
})!
|
||||
const answered = db!.answerQuestion({
|
||||
messageId: ask.question.message_id,
|
||||
runId: state.adoptedRunId,
|
||||
consumerGeneration: run.consumer_generation,
|
||||
body: 'continue'
|
||||
})
|
||||
expect(answered.message).toMatchObject({
|
||||
from_handle: `run:${state.adoptedRunId}`,
|
||||
to_handle: `dispatch:${state.fixture.legacyDispatchId}`,
|
||||
delivery_contract: 'current_delivery'
|
||||
})
|
||||
|
||||
const acknowledged = db!.acknowledgeLegacyQuestionAnswer({
|
||||
principalId: state.workerPrincipalId,
|
||||
questionId: ask.question.message_id,
|
||||
answerMessageId: answered.message.id
|
||||
})
|
||||
|
||||
expect(acknowledged.duplicate).toBe(false)
|
||||
expect(db!.getMessageById(answered.message.id)?.read).toBe(1)
|
||||
expect(
|
||||
db!.acknowledgeLegacyQuestionAnswer({
|
||||
principalId: state.workerPrincipalId,
|
||||
questionId: ask.question.message_id,
|
||||
answerMessageId: answered.message.id
|
||||
}).duplicate
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,255 @@
|
||||
import { rmSync } from 'node:fs'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import Database from '../../sqlite/sync-database'
|
||||
import { LEGACY_RUN_ID, OrchestrationDb } from './db'
|
||||
import { createLegacyStorageCutoverFixture } from './orchestration-legacy-storage-test-fixture'
|
||||
|
||||
describe('OrchestrationDb legacy question migration', () => {
|
||||
let db: OrchestrationDb | undefined
|
||||
let tempDir: string | undefined
|
||||
|
||||
afterEach(() => {
|
||||
db?.close()
|
||||
if (tempDir) {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
function prepareTakenOverSchema19Question(readAndAcknowledge: boolean): {
|
||||
dbPath: string
|
||||
adoptedRunId: string
|
||||
questionId: string
|
||||
} {
|
||||
const created = createLegacyStorageCutoverFixture()
|
||||
tempDir = created.tempDir
|
||||
db = new OrchestrationDb(created.fixture.dbPath)
|
||||
const adoptedRunId = db.getLegacyAdoption()?.adopted_run_id as string
|
||||
const questionId = readAndAcknowledge ? 'msg_schema19_acknowledged' : 'msg_schema19_unread'
|
||||
db.insertMessage({
|
||||
id: questionId,
|
||||
runId: adoptedRunId,
|
||||
deliveryContract: 'legacy_direct',
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'Question',
|
||||
body: 'Continue after takeover?',
|
||||
type: 'decision_gate',
|
||||
threadId: questionId,
|
||||
payload: JSON.stringify({
|
||||
taskId: created.fixture.legacyTaskId,
|
||||
dispatchId: created.fixture.legacyDispatchId
|
||||
})
|
||||
})
|
||||
if (readAndAcknowledge) {
|
||||
db.markAsRead([questionId])
|
||||
}
|
||||
const coordinator = db.commitLegacyCompatibilityPrincipal({
|
||||
runId: adoptedRunId,
|
||||
role: 'coordinator',
|
||||
hostScope: 'local:runtime_1',
|
||||
terminalHandle: 'term_legacy_coord',
|
||||
paneKey: 'tab_coord:44444444-4444-4444-8444-444444444444',
|
||||
launchTokenHash: 'coord_launch_hash',
|
||||
processIncarnation: 'process_coord'
|
||||
}).principal
|
||||
if (readAndAcknowledge) {
|
||||
const recovery = db.getLegacyMailPage({ principalId: coordinator.id })
|
||||
expect(recovery.messages.map((message) => message.id)).toContain(questionId)
|
||||
db.acknowledgeLegacyMail({
|
||||
principalId: coordinator.id,
|
||||
messageIds: recovery.messages.map((message) => message.id)
|
||||
})
|
||||
}
|
||||
db.bindRun({
|
||||
runId: adoptedRunId,
|
||||
coordinatorHandle: 'term_current_coord',
|
||||
coordinatorPaneKey: 'tab_current:11111111-1111-4111-8111-111111111111',
|
||||
takeoverLegacy: true
|
||||
})
|
||||
expect(db.getMessageById(questionId)).toMatchObject(
|
||||
readAndAcknowledge
|
||||
? { delivery_contract: 'legacy_direct', read: 1 }
|
||||
: { delivery_contract: 'current_delivery', read: 0 }
|
||||
)
|
||||
db.close()
|
||||
db = undefined
|
||||
|
||||
const raw = new Database(created.fixture.dbPath)
|
||||
raw.exec('DROP TABLE question_threads')
|
||||
raw.pragma('user_version = 19')
|
||||
raw.close()
|
||||
return { dbPath: created.fixture.dbPath, adoptedRunId, questionId }
|
||||
}
|
||||
|
||||
it('backfills a pre-question-thread ask and its accepted answer', () => {
|
||||
const created = createLegacyStorageCutoverFixture()
|
||||
tempDir = created.tempDir
|
||||
db = new OrchestrationDb(created.fixture.dbPath)
|
||||
const adoptedRunId = db.getLegacyAdoption()?.adopted_run_id as string
|
||||
db.close()
|
||||
db = undefined
|
||||
|
||||
const raw = new Database(created.fixture.dbPath)
|
||||
raw.exec(`
|
||||
DROP TABLE question_threads;
|
||||
INSERT INTO messages (
|
||||
id, run_id, delivery_contract, from_handle, to_handle,
|
||||
subject, body, type, thread_id, payload
|
||||
) VALUES (
|
||||
'msg_cutover', '${adoptedRunId}', 'legacy_direct',
|
||||
'term_legacy_worker', 'term_legacy_coord', 'Question',
|
||||
'Continue?', 'decision_gate', 'msg_cutover',
|
||||
'{"taskId":"${created.fixture.legacyTaskId}","dispatchId":"${created.fixture.legacyDispatchId}"}'
|
||||
);
|
||||
INSERT INTO messages (
|
||||
id, run_id, delivery_contract, from_handle, to_handle,
|
||||
subject, body, thread_id
|
||||
) VALUES
|
||||
(
|
||||
'msg_cross_run_decoy', 'run_decoy', 'legacy_direct',
|
||||
'term_legacy_coord', 'term_legacy_worker',
|
||||
'Re: Question', 'cross-run decoy', 'msg_cutover'
|
||||
),
|
||||
(
|
||||
'msg_self_sent_decoy', '${adoptedRunId}', 'legacy_direct',
|
||||
'term_legacy_worker', 'term_legacy_worker',
|
||||
'Re: Question', 'self-sent decoy', 'msg_cutover'
|
||||
),
|
||||
(
|
||||
'msg_cutover_answer', '${adoptedRunId}', 'legacy_direct',
|
||||
'term_legacy_coord', 'term_legacy_worker',
|
||||
'Re: Question', 'yes', 'msg_cutover'
|
||||
);
|
||||
`)
|
||||
raw.pragma('user_version = 19')
|
||||
raw.close()
|
||||
|
||||
db = new OrchestrationDb(created.fixture.dbPath)
|
||||
expect(db.getQuestion('msg_cutover')).toMatchObject({
|
||||
run_id: adoptedRunId,
|
||||
dispatch_id: created.fixture.legacyDispatchId,
|
||||
asker_handle: 'term_legacy_worker',
|
||||
status: 'answered',
|
||||
answer_message_id: 'msg_cutover_answer',
|
||||
answer_body: 'yes'
|
||||
})
|
||||
})
|
||||
|
||||
it('leaves a question pending when only cross-run and self-sent decoys exist', () => {
|
||||
const created = createLegacyStorageCutoverFixture()
|
||||
tempDir = created.tempDir
|
||||
db = new OrchestrationDb(created.fixture.dbPath)
|
||||
const adoptedRunId = db.getLegacyAdoption()?.adopted_run_id as string
|
||||
db.close()
|
||||
db = undefined
|
||||
|
||||
const raw = new Database(created.fixture.dbPath)
|
||||
raw.exec(`
|
||||
DROP TABLE question_threads;
|
||||
INSERT INTO messages (
|
||||
id, run_id, delivery_contract, from_handle, to_handle,
|
||||
subject, body, type, thread_id, payload
|
||||
) VALUES (
|
||||
'msg_pending_cutover', '${adoptedRunId}', 'legacy_direct',
|
||||
'term_legacy_worker', 'term_legacy_coord', 'Question',
|
||||
'Continue?', 'decision_gate', 'msg_pending_cutover',
|
||||
'{"taskId":"${created.fixture.legacyTaskId}","dispatchId":"${created.fixture.legacyDispatchId}"}'
|
||||
);
|
||||
INSERT INTO messages (
|
||||
id, run_id, delivery_contract, from_handle, to_handle,
|
||||
subject, body, thread_id
|
||||
) VALUES
|
||||
(
|
||||
'msg_pending_cross_run_decoy', 'run_decoy', 'legacy_direct',
|
||||
'term_legacy_coord', 'term_legacy_worker',
|
||||
'Re: Question', 'cross-run decoy', 'msg_pending_cutover'
|
||||
),
|
||||
(
|
||||
'msg_pending_self_sent_decoy', '${adoptedRunId}', 'legacy_direct',
|
||||
'term_legacy_worker', 'term_legacy_worker',
|
||||
'Re: Question', 'self-sent decoy', 'msg_pending_cutover'
|
||||
);
|
||||
`)
|
||||
raw.pragma('user_version = 19')
|
||||
raw.close()
|
||||
|
||||
db = new OrchestrationDb(created.fixture.dbPath)
|
||||
expect(db.getQuestion('msg_pending_cutover')).toMatchObject({
|
||||
run_id: adoptedRunId,
|
||||
dispatch_id: created.fixture.legacyDispatchId,
|
||||
asker_handle: 'term_legacy_worker',
|
||||
status: 'pending',
|
||||
answer_message_id: null,
|
||||
answer_body: null
|
||||
})
|
||||
})
|
||||
|
||||
it('uses task provenance to disambiguate same-handle same-second asks', () => {
|
||||
const created = createLegacyStorageCutoverFixture()
|
||||
tempDir = created.tempDir
|
||||
const raw = new Database(created.fixture.dbPath)
|
||||
raw.exec(`
|
||||
INSERT INTO tasks (
|
||||
id, run_id, spec, status, created_by_terminal_handle, created_at
|
||||
) VALUES
|
||||
('task_question_target', '${LEGACY_RUN_ID}', 'target', 'dispatched',
|
||||
'term_legacy_coord', '2026-01-01 00:00:00'),
|
||||
('task_question_other', '${LEGACY_RUN_ID}', 'other', 'dispatched',
|
||||
'term_legacy_coord', '2026-01-01 00:00:00');
|
||||
INSERT INTO dispatch_contexts (
|
||||
id, run_id, task_id, contract_version, assignee_handle,
|
||||
assignee_pane_key, status, dispatched_at, created_at
|
||||
) VALUES
|
||||
('dispatch_question_target', '${LEGACY_RUN_ID}', 'task_question_target', 0,
|
||||
'term_legacy_worker', 'tab_target:11111111-1111-4111-8111-111111111111',
|
||||
'dispatched', '2026-01-01 00:00:00', '2026-01-01 00:00:00'),
|
||||
('dispatch_question_other', '${LEGACY_RUN_ID}', 'task_question_other', 0,
|
||||
'term_legacy_worker', 'tab_other:22222222-2222-4222-8222-222222222222',
|
||||
'dispatched', '2026-01-01 00:00:00', '2026-01-01 00:00:00');
|
||||
INSERT INTO messages (
|
||||
id, run_id, delivery_contract, from_handle, to_handle,
|
||||
subject, body, type, payload, created_at
|
||||
) VALUES (
|
||||
'msg_question_task_only', '${LEGACY_RUN_ID}', 'legacy_direct',
|
||||
'term_legacy_worker', 'term_legacy_coord', 'Question', 'Continue?',
|
||||
'decision_gate', '{"taskId":"task_question_target","question":"Continue?","options":[]}',
|
||||
'2026-01-01 00:00:00'
|
||||
);
|
||||
`)
|
||||
raw.close()
|
||||
|
||||
db = new OrchestrationDb(created.fixture.dbPath)
|
||||
expect(db.getQuestion('msg_question_task_only')).toMatchObject({
|
||||
dispatch_id: 'dispatch_question_target',
|
||||
asker_handle: 'term_legacy_worker',
|
||||
status: 'pending'
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
['promoted unread', false],
|
||||
['acknowledged recovery', true]
|
||||
] as const)('backfills and routes a %s v19 question after takeover', (_label, acknowledged) => {
|
||||
const state = prepareTakenOverSchema19Question(acknowledged)
|
||||
|
||||
db = new OrchestrationDb(state.dbPath)
|
||||
expect(db.getQuestion(state.questionId)).toMatchObject({
|
||||
run_id: state.adoptedRunId,
|
||||
status: 'pending'
|
||||
})
|
||||
expect(db.getMessageById(state.questionId)).toMatchObject({
|
||||
to_handle: `run:${state.adoptedRunId}`,
|
||||
delivery_contract: 'current_delivery',
|
||||
read: 0
|
||||
})
|
||||
const run = db.getRun(state.adoptedRunId)!
|
||||
expect(
|
||||
db
|
||||
.getOrCreateRunDelivery({
|
||||
runId: state.adoptedRunId,
|
||||
consumerGeneration: run.consumer_generation
|
||||
})
|
||||
?.messages.map((message) => message.id)
|
||||
).toContain(state.questionId)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,751 @@
|
||||
import { rmSync } from 'node:fs'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import Database from '../../sqlite/sync-database'
|
||||
import {
|
||||
CURRENT_CONTRACT_VERSION,
|
||||
LEGACY_CONTRACT_VERSION,
|
||||
LEGACY_RUN_ID,
|
||||
OrchestrationDb
|
||||
} from './db'
|
||||
import {
|
||||
createLegacyStorageCutoverFixture,
|
||||
type LegacyStorageCutoverFixture
|
||||
} from './orchestration-legacy-storage-test-fixture'
|
||||
|
||||
describe('OrchestrationDb legacy contract storage', () => {
|
||||
let db: OrchestrationDb | undefined
|
||||
let tempDir: string | undefined
|
||||
|
||||
afterEach(() => {
|
||||
db?.close()
|
||||
db = undefined
|
||||
if (tempDir) {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
tempDir = undefined
|
||||
}
|
||||
})
|
||||
|
||||
function createCutoverFixture(): LegacyStorageCutoverFixture {
|
||||
const created = createLegacyStorageCutoverFixture()
|
||||
tempDir = created.tempDir
|
||||
return created.fixture
|
||||
}
|
||||
|
||||
function openAdoptedFixture(): {
|
||||
fixture: LegacyStorageCutoverFixture
|
||||
adoptedRunId: string
|
||||
workerPrincipalId: string
|
||||
coordinatorPrincipalId: string
|
||||
} {
|
||||
const fixture = createCutoverFixture()
|
||||
db = new OrchestrationDb(fixture.dbPath)
|
||||
const adoptedRunId = db.getLegacyAdoption()?.adopted_run_id as string
|
||||
const worker = db.commitLegacyCompatibilityPrincipal({
|
||||
runId: adoptedRunId,
|
||||
dispatchId: fixture.legacyDispatchId,
|
||||
role: 'worker',
|
||||
hostScope: 'local:runtime_1',
|
||||
terminalHandle: 'term_legacy_worker',
|
||||
paneKey: 'tab_legacy:33333333-3333-4333-8333-333333333333',
|
||||
launchTokenHash: 'legacy_launch_hash',
|
||||
processIncarnation: 'process_1'
|
||||
})
|
||||
const coordinator = db.commitLegacyCompatibilityPrincipal({
|
||||
runId: adoptedRunId,
|
||||
role: 'coordinator',
|
||||
hostScope: 'local:runtime_1',
|
||||
terminalHandle: 'term_legacy_coord',
|
||||
paneKey: 'tab_coord:44444444-4444-4444-8444-444444444444',
|
||||
launchTokenHash: 'coord_launch_hash',
|
||||
processIncarnation: 'process_coord'
|
||||
})
|
||||
return {
|
||||
fixture,
|
||||
adoptedRunId,
|
||||
workerPrincipalId: worker.principal.id,
|
||||
coordinatorPrincipalId: coordinator.principal.id
|
||||
}
|
||||
}
|
||||
|
||||
it('atomically rehomes the full graph, fences legacy Delivery, and preserves current rows', () => {
|
||||
const fixture = createCutoverFixture()
|
||||
db = new OrchestrationDb(fixture.dbPath)
|
||||
const adoption = db.getLegacyAdoption()
|
||||
const adoptedRunId = adoption?.adopted_run_id as string
|
||||
const sqlite = (db as unknown as { db: Database.Database }).db
|
||||
|
||||
expect(adoption).toMatchObject({
|
||||
source_run_id: LEGACY_RUN_ID,
|
||||
scheduler_state_lost: 1
|
||||
})
|
||||
expect(db.getRun(adoptedRunId)).toMatchObject({ legacy: 0, consumer_generation: 0 })
|
||||
expect(db.listTasks({ runId: LEGACY_RUN_ID })).toEqual([])
|
||||
expect(db.getDispatchContextById(fixture.legacyDispatchId)).toMatchObject({
|
||||
run_id: adoptedRunId,
|
||||
contract_version: LEGACY_CONTRACT_VERSION,
|
||||
launch_token_hash: null
|
||||
})
|
||||
expect(db.getGate(fixture.legacyGateId)).toMatchObject({ run_id: adoptedRunId })
|
||||
expect(db.getQuestion(fixture.legacyQuestionId)).toMatchObject({ run_id: adoptedRunId })
|
||||
expect(db.getMessageById(fixture.legacyMessageIds[0])).toMatchObject({
|
||||
run_id: adoptedRunId,
|
||||
delivery_contract: 'legacy_direct'
|
||||
})
|
||||
expect(db.getMessageById(fixture.rejectionMessageId)).toMatchObject({
|
||||
run_id: adoptedRunId,
|
||||
delivery_contract: 'audit_only'
|
||||
})
|
||||
expect(db.getMessageById(fixture.lookalikeMessageId)).toMatchObject({
|
||||
run_id: adoptedRunId,
|
||||
delivery_contract: 'legacy_direct'
|
||||
})
|
||||
for (const messageId of fixture.malformedRejectionMessageIds) {
|
||||
expect(db.getMessageById(messageId)).toMatchObject({
|
||||
run_id: adoptedRunId,
|
||||
delivery_contract: 'legacy_direct'
|
||||
})
|
||||
}
|
||||
expect(
|
||||
sqlite.prepare('SELECT * FROM deliveries WHERE id = ?').get(fixture.legacyDeliveryId)
|
||||
).toMatchObject({ run_id: adoptedRunId, status: 'fenced' })
|
||||
expect(db.getDispatchContextById(fixture.currentDispatchId)).toMatchObject({
|
||||
run_id: fixture.currentRunId,
|
||||
contract_version: CURRENT_CONTRACT_VERSION,
|
||||
launch_token_hash: 'current_launch_hash'
|
||||
})
|
||||
|
||||
db.close()
|
||||
const partial = new Database(fixture.dbPath)
|
||||
partial
|
||||
.prepare('UPDATE tasks SET run_id = ? WHERE id = ?')
|
||||
.run(LEGACY_RUN_ID, fixture.legacyTaskId)
|
||||
partial.pragma('user_version = 19')
|
||||
partial.close()
|
||||
db = new OrchestrationDb(fixture.dbPath)
|
||||
expect(db.getLegacyAdoption()?.adopted_run_id).toBe(adoptedRunId)
|
||||
expect(db.getTask(fixture.legacyTaskId)?.run_id).toBe(adoptedRunId)
|
||||
expect(db.getDispatchContextById(fixture.currentDispatchId)?.contract_version).toBe(
|
||||
CURRENT_CONTRACT_VERSION
|
||||
)
|
||||
expect(db.listTasks({ runId: LEGACY_RUN_ID })).toEqual([])
|
||||
})
|
||||
|
||||
it('ignores unrelated cross-Run anomalies while validating adopted rows', () => {
|
||||
const fixture = createCutoverFixture()
|
||||
const raw = new Database(fixture.dbPath)
|
||||
raw
|
||||
.prepare('UPDATE dispatch_contexts SET run_id = ? WHERE id = ?')
|
||||
.run(fixture.unrelatedRunId, fixture.currentDispatchId)
|
||||
raw.close()
|
||||
|
||||
db = new OrchestrationDb(fixture.dbPath)
|
||||
|
||||
expect(db.getLegacyAdoption()).toBeDefined()
|
||||
expect(db.getDispatchContextById(fixture.currentDispatchId)?.run_id).toBe(
|
||||
fixture.unrelatedRunId
|
||||
)
|
||||
})
|
||||
|
||||
it('does not synthesize an adopted Run or compatibility authority for a fresh database', () => {
|
||||
db = new OrchestrationDb(':memory:')
|
||||
|
||||
expect(db.getLegacyAdoption()).toBeUndefined()
|
||||
expect(db.listLegacyCompatibilityPrincipals(LEGACY_RUN_ID)).toEqual([])
|
||||
expect(db.listRuns()).toEqual([expect.objectContaining({ id: LEGACY_RUN_ID, legacy: 1 })])
|
||||
})
|
||||
|
||||
it('keeps current Delivery disjoint from adopted direct and audit-only mail', () => {
|
||||
const state = openAdoptedFixture()
|
||||
const run = db!.getRun(state.adoptedRunId) as NonNullable<ReturnType<OrchestrationDb['getRun']>>
|
||||
db!.insertMessage({
|
||||
runId: state.adoptedRunId,
|
||||
from: 'current_worker',
|
||||
to: `run:${state.adoptedRunId}`,
|
||||
subject: 'current retry mail'
|
||||
})
|
||||
|
||||
const delivery = db!.getOrCreateRunDelivery({
|
||||
runId: state.adoptedRunId,
|
||||
consumerGeneration: run.consumer_generation
|
||||
})
|
||||
|
||||
expect(delivery?.messages.map((message) => message.subject)).toEqual(['current retry mail'])
|
||||
})
|
||||
|
||||
it('drains a durable recovery cohort in bounded replaying pages before unread mail', () => {
|
||||
const state = openAdoptedFixture()
|
||||
const first = db!.getLegacyMailPage({ principalId: state.workerPrincipalId, limit: 1 })
|
||||
const replay = db!.getLegacyMailPage({ principalId: state.workerPrincipalId, limit: 1 })
|
||||
|
||||
expect(first.recovery).toBe(true)
|
||||
expect(replay.messages.map((message) => message.id)).toEqual(
|
||||
first.messages.map((message) => message.id)
|
||||
)
|
||||
expect(() =>
|
||||
db!.acknowledgeLegacyMail({
|
||||
principalId: state.workerPrincipalId,
|
||||
messageIds: [state.fixture.legacyMessageIds[2]]
|
||||
})
|
||||
).toThrow(/current replay page/)
|
||||
db!.acknowledgeLegacyMail({
|
||||
principalId: state.workerPrincipalId,
|
||||
messageIds: first.messages.map((message) => message.id)
|
||||
})
|
||||
const second = db!.getLegacyMailPage({ principalId: state.workerPrincipalId, limit: 1 })
|
||||
expect(second.recovery).toBe(true)
|
||||
expect(second.messages[0].id).not.toBe(first.messages[0].id)
|
||||
db!.acknowledgeLegacyMail({
|
||||
principalId: state.workerPrincipalId,
|
||||
messageIds: second.messages.map((message) => message.id)
|
||||
})
|
||||
expect(db!.getLegacyMailPage({ principalId: state.workerPrincipalId, limit: 1 }).recovery).toBe(
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
it('returns complete addressed legacy history without changing read state', () => {
|
||||
const state = openAdoptedFixture()
|
||||
const unread = db!.insertMessage({
|
||||
runId: state.adoptedRunId,
|
||||
deliveryContract: 'legacy_direct',
|
||||
from: 'term_legacy_coord',
|
||||
to: 'term_legacy_worker',
|
||||
subject: 'unread history'
|
||||
})
|
||||
db!.insertMessage({
|
||||
runId: state.adoptedRunId,
|
||||
deliveryContract: 'legacy_direct',
|
||||
from: 'other',
|
||||
to: 'other',
|
||||
subject: 'not addressed'
|
||||
})
|
||||
|
||||
const history = db!.getLegacyMailHistory({ principalId: state.workerPrincipalId })
|
||||
|
||||
expect(history.recovery).toBe(false)
|
||||
expect(history.messages.map((message) => message.subject)).toEqual([
|
||||
'read worker mail',
|
||||
'second worker page',
|
||||
'unread history'
|
||||
])
|
||||
expect(db!.getMessageById(unread.id)?.read).toBe(0)
|
||||
})
|
||||
|
||||
it('resolves legacy principals and completion evidence only within exact assignments', () => {
|
||||
const state = openAdoptedFixture()
|
||||
const taskId = db!.getDispatchContextById(state.fixture.legacyDispatchId)!.task_id
|
||||
const payload = JSON.stringify({ taskId, dispatchId: state.fixture.legacyDispatchId })
|
||||
const completion = db!.insertMessage({
|
||||
runId: state.adoptedRunId,
|
||||
deliveryContract: 'legacy_direct',
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'Completed',
|
||||
body: 'done',
|
||||
type: 'worker_done',
|
||||
payload
|
||||
})
|
||||
|
||||
expect(
|
||||
db!.resolveLegacyWorkerCandidate({
|
||||
runId: state.adoptedRunId,
|
||||
terminalHandle: 'term_legacy_worker',
|
||||
paneKey: 'tab_reminted:33333333-3333-4333-8333-333333333333',
|
||||
taskId
|
||||
})
|
||||
).toMatchObject({ dispatch: { id: state.fixture.legacyDispatchId } })
|
||||
expect(
|
||||
db!.resolveLegacyWorkerCandidate({
|
||||
runId: state.adoptedRunId,
|
||||
terminalHandle: 'term_legacy_worker',
|
||||
paneKey: 'tab_wrong:99999999-9999-4999-8999-999999999999',
|
||||
taskId
|
||||
})
|
||||
).toBeUndefined()
|
||||
expect(
|
||||
db!.resolveLegacyCoordinatorCandidate({
|
||||
runId: state.adoptedRunId,
|
||||
terminalHandle: 'term_legacy_coord',
|
||||
paneKey: 'tab_coord:44444444-4444-4444-8444-444444444444'
|
||||
})
|
||||
).toMatchObject({ terminalHandle: 'term_legacy_coord' })
|
||||
expect(
|
||||
db!.findLegacyWorkerCompletion({
|
||||
principalId: state.workerPrincipalId,
|
||||
taskId,
|
||||
recipientHandle: 'term_legacy_coord',
|
||||
subject: 'Completed',
|
||||
body: 'done',
|
||||
payload
|
||||
})
|
||||
).toMatchObject({ id: completion.id })
|
||||
})
|
||||
|
||||
it('prevents an unproven coordinator from taking over an active adopted Run', () => {
|
||||
const state = openAdoptedFixture()
|
||||
expect(() =>
|
||||
db!.bindRun({
|
||||
runId: state.adoptedRunId,
|
||||
coordinatorHandle: 'term_other',
|
||||
coordinatorPaneKey: 'tab_other:55555555-5555-4555-8555-555555555555'
|
||||
})
|
||||
).toThrow(/attested coordinator may rebind/)
|
||||
|
||||
const bound = db!.bindRun({
|
||||
runId: state.adoptedRunId,
|
||||
coordinatorHandle: 'term_legacy_coord',
|
||||
coordinatorPaneKey: 'tab_coord:44444444-4444-4444-8444-444444444444',
|
||||
legacyCoordinatorAuthority: {
|
||||
runId: state.adoptedRunId,
|
||||
principalId: state.coordinatorPrincipalId,
|
||||
terminalHandle: 'term_legacy_coord',
|
||||
paneKey: 'tab_coord:44444444-4444-4444-8444-444444444444',
|
||||
consumerGeneration: 0
|
||||
}
|
||||
})
|
||||
expect(bound).toMatchObject({ coordinator_handle: 'term_legacy_coord' })
|
||||
expect(
|
||||
db!.bindRun({
|
||||
runId: state.adoptedRunId,
|
||||
coordinatorHandle: 'term_legacy_coord',
|
||||
coordinatorPaneKey: 'tab_coord:44444444-4444-4444-8444-444444444444'
|
||||
})
|
||||
).toMatchObject({ coordinator_handle: 'term_legacy_coord' })
|
||||
})
|
||||
|
||||
it.each([
|
||||
['generation', { consumerGeneration: 1 }],
|
||||
['principal', { principalId: 'legacy_principal_wrong' }],
|
||||
['handle', { terminalHandle: 'term_wrong' }],
|
||||
['pane', { paneKey: 'tab_wrong:99999999-9999-4999-8999-999999999999' }]
|
||||
] as const)('rejects stale legacy coordinator %s proof inside Run binding', (_label, patch) => {
|
||||
const state = openAdoptedFixture()
|
||||
const before = db!.getRun(state.adoptedRunId)
|
||||
|
||||
expect(() =>
|
||||
db!.bindRun({
|
||||
runId: state.adoptedRunId,
|
||||
coordinatorHandle: 'term_legacy_coord',
|
||||
coordinatorPaneKey: 'tab_coord:44444444-4444-4444-8444-444444444444',
|
||||
legacyCoordinatorAuthority: {
|
||||
runId: state.adoptedRunId,
|
||||
principalId: state.coordinatorPrincipalId,
|
||||
terminalHandle: 'term_legacy_coord',
|
||||
paneKey: 'tab_coord:44444444-4444-4444-8444-444444444444',
|
||||
consumerGeneration: 0,
|
||||
...patch
|
||||
}
|
||||
})
|
||||
).toThrow(/no longer has lifecycle authority/)
|
||||
expect(db!.getRun(state.adoptedRunId)).toEqual(before)
|
||||
})
|
||||
|
||||
it('revokes the legacy coordinator when a current coordinator takes over after settlement', () => {
|
||||
const state = openAdoptedFixture()
|
||||
db!.settleWorkerReport({
|
||||
taskId: state.fixture.legacyTaskId,
|
||||
dispatchId: state.fixture.legacyDispatchId,
|
||||
outcome: 'succeeded',
|
||||
result: 'done'
|
||||
})
|
||||
|
||||
expect(
|
||||
db!.bindRun({
|
||||
runId: state.adoptedRunId,
|
||||
coordinatorHandle: 'term_current_coord',
|
||||
coordinatorPaneKey: 'tab_current:11111111-1111-4111-8111-111111111111'
|
||||
})
|
||||
).toMatchObject({ coordinator_handle: 'term_current_coord' })
|
||||
expect(db!.getLegacyCompatibilityPrincipal(state.coordinatorPrincipalId)?.status).toBe(
|
||||
'revoked'
|
||||
)
|
||||
expect(() =>
|
||||
db!.commitLegacyCompatibilityPrincipal({
|
||||
runId: state.adoptedRunId,
|
||||
role: 'coordinator',
|
||||
hostScope: 'local:runtime_1',
|
||||
terminalHandle: 'term_legacy_coord',
|
||||
paneKey: 'tab_coord:44444444-4444-4444-8444-444444444444',
|
||||
launchTokenHash: 'coord_launch_hash',
|
||||
processIncarnation: 'process_coord'
|
||||
})
|
||||
).toThrow(/revoked/)
|
||||
})
|
||||
|
||||
it('promotes only mail addressed to the replaced legacy coordinator', () => {
|
||||
const state = openAdoptedFixture()
|
||||
const coordinatorMail = db!.insertMessage({
|
||||
runId: state.adoptedRunId,
|
||||
deliveryContract: 'legacy_direct',
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'coordinator outcome'
|
||||
})
|
||||
const workerMail = db!.insertMessage({
|
||||
runId: state.adoptedRunId,
|
||||
deliveryContract: 'legacy_direct',
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_other_worker',
|
||||
subject: 'worker-only guidance'
|
||||
})
|
||||
|
||||
db!.bindRun({
|
||||
runId: state.adoptedRunId,
|
||||
coordinatorHandle: 'term_current_coord',
|
||||
coordinatorPaneKey: 'tab_current:11111111-1111-4111-8111-111111111111',
|
||||
takeoverLegacy: true
|
||||
})
|
||||
|
||||
expect(db!.getMessageById(coordinatorMail.id)).toMatchObject({
|
||||
to_handle: `run:${state.adoptedRunId}`,
|
||||
delivery_contract: 'current_delivery'
|
||||
})
|
||||
expect(db!.getMessageById(workerMail.id)).toMatchObject({
|
||||
to_handle: 'term_other_worker',
|
||||
delivery_contract: 'legacy_direct'
|
||||
})
|
||||
})
|
||||
|
||||
it('commits legacy messages, lifecycle effects, and invocation receipts exactly once', () => {
|
||||
const state = openAdoptedFixture()
|
||||
const params = {
|
||||
principalId: state.workerPrincipalId,
|
||||
operationKey: 'invocation_1',
|
||||
method: 'orchestration.send',
|
||||
payloadHash: 'payload_1',
|
||||
message: {
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'alive',
|
||||
type: 'heartbeat' as const
|
||||
},
|
||||
lifecycle: { kind: 'heartbeat' as const, at: '2026-07-28T12:00:00.000Z' }
|
||||
}
|
||||
|
||||
const first = db!.commitLegacyLifecycleOperation(params)
|
||||
const replay = db!.commitLegacyLifecycleOperation(params)
|
||||
|
||||
expect(replay).toMatchObject({
|
||||
duplicate: true,
|
||||
message: { id: first.message.id },
|
||||
receipt: { effect_id: first.message.id }
|
||||
})
|
||||
expect(db!.getDispatchContextById(state.fixture.legacyDispatchId)?.last_heartbeat_at).toBe(
|
||||
'2026-07-28T12:00:00.000Z'
|
||||
)
|
||||
expect(db!.getUnreadMessages('term_legacy_coord')).toEqual([])
|
||||
expect(db!.getUndeliveredUnreadMessages('term_legacy_coord')).toEqual([])
|
||||
expect(() =>
|
||||
db!.commitLegacyLifecycleOperation({ ...params, payloadHash: 'different' })
|
||||
).toThrow(/different input/)
|
||||
})
|
||||
|
||||
it('reconstructs a matching pre-receipt settlement without changing its persisted outcome', () => {
|
||||
const state = openAdoptedFixture()
|
||||
const accepted = db!.insertMessage({
|
||||
runId: state.adoptedRunId,
|
||||
deliveryContract: 'legacy_direct',
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'Completed',
|
||||
type: 'worker_done'
|
||||
})
|
||||
expect(
|
||||
db!.settleWorkerReport({
|
||||
taskId: db!.getDispatchContextById(state.fixture.legacyDispatchId)!.task_id,
|
||||
dispatchId: state.fixture.legacyDispatchId,
|
||||
outcome: 'succeeded',
|
||||
result: 'accepted by A'
|
||||
})
|
||||
).toMatchObject({ action: 'settled', duplicate: false })
|
||||
|
||||
const reconstructed = db!.commitLegacyLifecycleOperation({
|
||||
principalId: state.workerPrincipalId,
|
||||
operationKey: `settlement:${state.fixture.legacyDispatchId}`,
|
||||
method: 'orchestration.send',
|
||||
payloadHash: 'settlement_payload',
|
||||
message: {
|
||||
existingId: accepted.id,
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'Completed',
|
||||
type: 'worker_done'
|
||||
},
|
||||
lifecycle: {
|
||||
kind: 'worker_report',
|
||||
taskId: db!.getDispatchContextById(state.fixture.legacyDispatchId)!.task_id,
|
||||
outcome: 'succeeded',
|
||||
result: 'accepted by A'
|
||||
}
|
||||
})
|
||||
|
||||
expect(reconstructed).toMatchObject({
|
||||
duplicate: false,
|
||||
message: { id: accepted.id },
|
||||
settlement: { action: 'settled', outcome: 'succeeded', duplicate: true }
|
||||
})
|
||||
expect(db!.getLegacyCompatibilityPrincipal(state.workerPrincipalId)?.status).toBe('settled')
|
||||
})
|
||||
|
||||
it('reconstructs a read pre-takeover completion through its original legacy route', () => {
|
||||
const state = openAdoptedFixture()
|
||||
const taskId = db!.getDispatchContextById(state.fixture.legacyDispatchId)!.task_id
|
||||
const accepted = db!.insertMessage({
|
||||
runId: state.adoptedRunId,
|
||||
deliveryContract: 'legacy_direct',
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'Completed',
|
||||
body: 'accepted before takeover',
|
||||
type: 'worker_done'
|
||||
})
|
||||
db!.markAsRead([accepted.id])
|
||||
db!.settleWorkerReport({
|
||||
taskId,
|
||||
dispatchId: state.fixture.legacyDispatchId,
|
||||
outcome: 'succeeded',
|
||||
result: 'accepted before takeover'
|
||||
})
|
||||
db!.bindRun({
|
||||
runId: state.adoptedRunId,
|
||||
coordinatorHandle: 'term_current_coord',
|
||||
coordinatorPaneKey: 'tab_current:11111111-1111-4111-8111-111111111111',
|
||||
takeoverLegacy: true
|
||||
})
|
||||
const beforeIds = db!.getInbox(100).map((message) => message.id)
|
||||
|
||||
const reconstructed = db!.commitLegacyLifecycleOperation({
|
||||
principalId: state.workerPrincipalId,
|
||||
operationKey: 'read_completion_after_takeover',
|
||||
method: 'orchestration.send',
|
||||
payloadHash: 'read_completion_after_takeover_payload',
|
||||
message: {
|
||||
existingId: accepted.id,
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'Completed',
|
||||
body: 'accepted before takeover',
|
||||
type: 'worker_done'
|
||||
},
|
||||
lifecycle: {
|
||||
kind: 'worker_report',
|
||||
taskId,
|
||||
outcome: 'succeeded',
|
||||
result: 'accepted before takeover'
|
||||
}
|
||||
})
|
||||
|
||||
expect(reconstructed).toMatchObject({
|
||||
duplicate: false,
|
||||
message: {
|
||||
id: accepted.id,
|
||||
to_handle: 'term_legacy_coord',
|
||||
delivery_contract: 'legacy_direct'
|
||||
},
|
||||
settlement: { action: 'settled', outcome: 'succeeded', duplicate: true }
|
||||
})
|
||||
expect(db!.getInbox(100).map((message) => message.id)).toEqual(beforeIds)
|
||||
})
|
||||
|
||||
it('rejects cross-cutover completion reconstruction for another recipient', () => {
|
||||
const state = openAdoptedFixture()
|
||||
const taskId = db!.getDispatchContextById(state.fixture.legacyDispatchId)!.task_id
|
||||
const payload = JSON.stringify({ taskId, dispatchId: state.fixture.legacyDispatchId })
|
||||
const foreign = db!.insertMessage({
|
||||
runId: state.adoptedRunId,
|
||||
deliveryContract: 'legacy_direct',
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_other_coord',
|
||||
subject: 'Completed',
|
||||
body: 'accepted elsewhere',
|
||||
type: 'worker_done',
|
||||
payload
|
||||
})
|
||||
db!.settleWorkerReport({
|
||||
taskId,
|
||||
dispatchId: state.fixture.legacyDispatchId,
|
||||
outcome: 'succeeded',
|
||||
result: 'accepted elsewhere'
|
||||
})
|
||||
const beforeIds = db!.getInbox(100).map((message) => message.id)
|
||||
|
||||
expect(
|
||||
db!.findLegacyWorkerCompletion({
|
||||
principalId: state.workerPrincipalId,
|
||||
taskId,
|
||||
recipientHandle: 'term_legacy_coord',
|
||||
subject: 'Completed',
|
||||
body: 'accepted elsewhere',
|
||||
payload
|
||||
})
|
||||
).toBeUndefined()
|
||||
expect(() =>
|
||||
db!.commitLegacyLifecycleOperation({
|
||||
principalId: state.workerPrincipalId,
|
||||
operationKey: 'wrong_recipient_retry',
|
||||
method: 'orchestration.send',
|
||||
payloadHash: 'wrong_recipient_retry_payload',
|
||||
message: {
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'Completed',
|
||||
body: 'accepted elsewhere',
|
||||
type: 'worker_done',
|
||||
payload
|
||||
},
|
||||
lifecycle: {
|
||||
kind: 'worker_report',
|
||||
taskId,
|
||||
outcome: 'succeeded',
|
||||
result: 'accepted elsewhere'
|
||||
}
|
||||
})
|
||||
).toThrow(/settled/)
|
||||
expect(() =>
|
||||
db!.commitLegacyLifecycleOperation({
|
||||
principalId: state.workerPrincipalId,
|
||||
operationKey: 'wrong_recipient_reconstruction',
|
||||
method: 'orchestration.send',
|
||||
payloadHash: 'wrong_recipient_payload',
|
||||
message: {
|
||||
existingId: foreign.id,
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'Completed',
|
||||
body: 'accepted elsewhere',
|
||||
type: 'worker_done',
|
||||
payload
|
||||
},
|
||||
lifecycle: {
|
||||
kind: 'worker_report',
|
||||
taskId,
|
||||
outcome: 'succeeded',
|
||||
result: 'accepted elsewhere'
|
||||
}
|
||||
})
|
||||
).toThrow(/does not match this principal/)
|
||||
expect(db!.getInbox(100).map((message) => message.id)).toEqual(beforeIds)
|
||||
expect(
|
||||
db!.getLegacyOperationReceipt(state.workerPrincipalId, 'wrong_recipient_reconstruction')
|
||||
).toBeUndefined()
|
||||
expect(
|
||||
db!.getLegacyOperationReceipt(state.workerPrincipalId, 'wrong_recipient_retry')
|
||||
).toBeUndefined()
|
||||
expect(db!.getTask(taskId)).toMatchObject({
|
||||
status: 'completed',
|
||||
result: 'accepted elsewhere'
|
||||
})
|
||||
})
|
||||
|
||||
it('uses invocation identity for repeated asks and atomically conflicts divergent replies', () => {
|
||||
const state = openAdoptedFixture()
|
||||
const ask = {
|
||||
principalId: state.workerPrincipalId,
|
||||
operationKey: 'ask_invocation_1',
|
||||
method: 'orchestration.ask',
|
||||
payloadHash: 'ask_payload',
|
||||
question: 'Same text?',
|
||||
options: ['yes', 'no'],
|
||||
recipientHandle: 'term_legacy_coord'
|
||||
}
|
||||
const first = db!.commitLegacyAskOperation(ask)
|
||||
const replay = db!.commitLegacyAskOperation(ask)
|
||||
const repeated = db!.commitLegacyAskOperation({
|
||||
...ask,
|
||||
operationKey: 'ask_invocation_2'
|
||||
})
|
||||
|
||||
expect(replay).toMatchObject({ duplicate: true, question: { message_id: first.message.id } })
|
||||
expect(repeated.message.id).not.toBe(first.message.id)
|
||||
expect(db!.findPendingLegacyQuestions(ask)).toHaveLength(2)
|
||||
expect(
|
||||
db!.findPendingLegacyQuestions({
|
||||
...ask,
|
||||
question: ' Same text?\r\n',
|
||||
options: ['yes ', ' no']
|
||||
})
|
||||
).toHaveLength(2)
|
||||
|
||||
const inherited = db!.createQuestion({
|
||||
runId: state.adoptedRunId,
|
||||
dispatchId: state.fixture.legacyDispatchId,
|
||||
askerHandle: 'term_legacy_worker',
|
||||
question: 'Inherited?'
|
||||
})
|
||||
const sqlite = (db as unknown as { db: Database.Database }).db
|
||||
sqlite
|
||||
.prepare(
|
||||
`UPDATE messages
|
||||
SET from_handle = 'term_legacy_worker', to_handle = 'term_legacy_coord',
|
||||
delivery_contract = 'legacy_direct'
|
||||
WHERE id = ?`
|
||||
)
|
||||
.run(inherited.message.id)
|
||||
const inheritedAsk = {
|
||||
...ask,
|
||||
operationKey: 'ask_inherited_1',
|
||||
payloadHash: 'ask_inherited_payload_1',
|
||||
question: 'Inherited?',
|
||||
options: [],
|
||||
existingQuestionId: inherited.message.id
|
||||
}
|
||||
const adopted = db!.commitLegacyAskOperation(inheritedAsk)
|
||||
const distinct = db!.commitLegacyAskOperation({
|
||||
...inheritedAsk,
|
||||
operationKey: 'ask_inherited_2',
|
||||
payloadHash: 'ask_inherited_payload_2'
|
||||
})
|
||||
expect(adopted.message.id).toBe(inherited.message.id)
|
||||
expect(distinct.message.id).not.toBe(inherited.message.id)
|
||||
|
||||
const reply = {
|
||||
principalId: state.coordinatorPrincipalId,
|
||||
operationKey: 'reply_invocation_1',
|
||||
method: 'orchestration.reply',
|
||||
payloadHash: 'reply_payload',
|
||||
questionId: first.message.id,
|
||||
body: 'yes'
|
||||
}
|
||||
const answered = db!.commitLegacyReplyOperation(reply)
|
||||
const answerReplay = db!.commitLegacyReplyOperation(reply)
|
||||
expect(answerReplay).toMatchObject({
|
||||
duplicate: true,
|
||||
message: { id: answered.message.id }
|
||||
})
|
||||
expect(
|
||||
db!
|
||||
.findLegacyQuestionsBySemanticIdentity(ask)
|
||||
.find((row) => row.question.message_id === first.message.id)
|
||||
).toMatchObject({ question: { status: 'answered' }, answerAcknowledged: false })
|
||||
db!.acknowledgeLegacyQuestionAnswer({
|
||||
principalId: state.workerPrincipalId,
|
||||
questionId: first.message.id,
|
||||
answerMessageId: answered.message.id
|
||||
})
|
||||
expect(
|
||||
db!
|
||||
.findLegacyQuestionsBySemanticIdentity(ask)
|
||||
.find((row) => row.question.message_id === first.message.id)
|
||||
).toMatchObject({ answerAcknowledged: true })
|
||||
expect(() =>
|
||||
db!.commitLegacyReplyOperation({
|
||||
...reply,
|
||||
operationKey: 'reply_invocation_2',
|
||||
payloadHash: 'different_reply',
|
||||
body: 'no'
|
||||
})
|
||||
).toThrow(/different answer/)
|
||||
|
||||
const currentTask = db!.createTask({ runId: state.adoptedRunId, spec: 'current retry' })
|
||||
const currentDispatch = db!.createDispatchContext(currentTask.id, 'term_current_retry')
|
||||
const currentQuestion = db!.createQuestion({
|
||||
runId: state.adoptedRunId,
|
||||
dispatchId: currentDispatch.id,
|
||||
askerHandle: 'term_current_retry',
|
||||
question: 'Current question?'
|
||||
})
|
||||
expect(() =>
|
||||
db!.commitLegacyReplyOperation({
|
||||
...reply,
|
||||
operationKey: 'reply_current_question',
|
||||
payloadHash: 'current_question',
|
||||
questionId: currentQuestion.message.id
|
||||
})
|
||||
).toThrow(/not actionable/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,206 @@
|
||||
import { mkdtempSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import Database from '../../sqlite/sync-database'
|
||||
import { LEGACY_RUN_ID, OrchestrationDb } from './db'
|
||||
|
||||
export type LegacyStorageCutoverFixture = {
|
||||
dbPath: string
|
||||
currentRunId: string
|
||||
unrelatedRunId: string
|
||||
currentDispatchId: string
|
||||
legacyTaskId: string
|
||||
legacyDispatchId: string
|
||||
legacyGateId: string
|
||||
legacyMessageIds: string[]
|
||||
legacyQuestionId: string
|
||||
legacyDeliveryId: string
|
||||
rejectionMessageId: string
|
||||
lookalikeMessageId: string
|
||||
malformedRejectionMessageIds: string[]
|
||||
}
|
||||
|
||||
export function createLegacyStorageCutoverFixture(): {
|
||||
fixture: LegacyStorageCutoverFixture
|
||||
tempDir: string
|
||||
} {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), 'orca-legacy-storage-'))
|
||||
const dbPath = join(tempDir, 'orchestration.db')
|
||||
const first = new OrchestrationDb(dbPath)
|
||||
const currentRun = first.createRun({
|
||||
objective: 'Current work',
|
||||
coordinatorHandle: 'term_current_coord',
|
||||
coordinatorPaneKey: 'tab_current:11111111-1111-4111-8111-111111111111'
|
||||
})
|
||||
const currentTask = first.createTask({ spec: 'current', runId: currentRun.id })
|
||||
const unrelatedRun = first.createRun({
|
||||
objective: 'Unrelated current work',
|
||||
coordinatorHandle: 'term_unrelated_coord',
|
||||
coordinatorPaneKey: 'tab_unrelated:55555555-5555-4555-8555-555555555555'
|
||||
})
|
||||
const currentDispatch = first.createDispatchContext(
|
||||
currentTask.id,
|
||||
'term_current_worker',
|
||||
'tab_current:22222222-2222-4222-9222-222222222222',
|
||||
'current_launch_hash'
|
||||
)
|
||||
first.insertMessage({
|
||||
runId: currentRun.id,
|
||||
from: 'term_current_worker',
|
||||
to: `run:${currentRun.id}`,
|
||||
subject: 'current mail'
|
||||
})
|
||||
|
||||
const legacyTask = first.createTask({
|
||||
spec: 'legacy',
|
||||
createdByTerminalHandle: 'term_legacy_coord'
|
||||
})
|
||||
first.createDispatchContext(
|
||||
legacyTask.id,
|
||||
'term_legacy_worker',
|
||||
'tab_legacy:33333333-3333-4333-8333-333333333333'
|
||||
)
|
||||
const legacyGate = first.createGate({
|
||||
taskId: legacyTask.id,
|
||||
question: 'Retained gate?'
|
||||
})
|
||||
first.resolveGate(legacyGate.id, 'continue')
|
||||
const retryDispatch = first.createDispatchContext(
|
||||
legacyTask.id,
|
||||
'term_legacy_worker',
|
||||
'tab_legacy:33333333-3333-4333-8333-333333333333'
|
||||
)
|
||||
const legacyMessages = [
|
||||
first.insertMessage({
|
||||
from: 'term_legacy_coord',
|
||||
to: 'term_legacy_worker',
|
||||
subject: 'read worker mail'
|
||||
}),
|
||||
first.insertMessage({
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'read coordinator mail'
|
||||
}),
|
||||
first.insertMessage({
|
||||
from: 'term_legacy_coord',
|
||||
to: 'term_legacy_worker',
|
||||
subject: 'second worker page'
|
||||
})
|
||||
]
|
||||
first.markAsRead(legacyMessages.map((message) => message.id))
|
||||
const question = first.createQuestion({
|
||||
runId: LEGACY_RUN_ID,
|
||||
dispatchId: retryDispatch.id,
|
||||
askerHandle: 'term_legacy_worker',
|
||||
question: 'Retained question?'
|
||||
})
|
||||
const rejection = first.insertMessage({
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'Rejected heartbeat',
|
||||
type: 'heartbeat',
|
||||
payload: JSON.stringify({ _orcaLifecycleRejection: { code: 'migration', reason: 'cutover' } })
|
||||
})
|
||||
const lookalike = first.insertMessage({
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'Ordinary legacy mail',
|
||||
payload: JSON.stringify({
|
||||
userData: { _orcaLifecycleRejection: { code: 'not-a-top-level-audit-marker' } }
|
||||
})
|
||||
})
|
||||
const malformedRejections = [
|
||||
first.insertMessage({
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'Invalid JSON marker',
|
||||
payload: '{"_orcaLifecycleRejection":'
|
||||
}),
|
||||
first.insertMessage({
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'Array marker',
|
||||
payload: JSON.stringify({ _orcaLifecycleRejection: [] })
|
||||
}),
|
||||
first.insertMessage({
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'String marker',
|
||||
payload: JSON.stringify({ _orcaLifecycleRejection: 'migration' })
|
||||
}),
|
||||
first.insertMessage({
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'Incomplete marker',
|
||||
payload: JSON.stringify({ _orcaLifecycleRejection: { code: 'migration' } })
|
||||
}),
|
||||
first.insertMessage({
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'Non-string marker fields',
|
||||
payload: JSON.stringify({ _orcaLifecycleRejection: { code: 19, reason: false } })
|
||||
}),
|
||||
first.insertMessage({
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'Array root',
|
||||
payload: JSON.stringify([
|
||||
{ _orcaLifecycleRejection: { code: 'migration', reason: 'nested' } }
|
||||
])
|
||||
}),
|
||||
first.insertMessage({
|
||||
from: 'term_legacy_worker',
|
||||
to: 'term_legacy_coord',
|
||||
subject: 'String root',
|
||||
payload: JSON.stringify('_orcaLifecycleRejection')
|
||||
})
|
||||
]
|
||||
first.close()
|
||||
|
||||
const raw = new Database(dbPath)
|
||||
const legacyDeliveryId = 'delivery_legacy_outstanding'
|
||||
raw
|
||||
.prepare(
|
||||
`INSERT INTO deliveries (
|
||||
id, run_id, consumer_generation, message_ids, status
|
||||
) VALUES (?, ?, 0, ?, 'outstanding')`
|
||||
)
|
||||
.run(legacyDeliveryId, LEGACY_RUN_ID, JSON.stringify([legacyMessages[0].id]))
|
||||
raw
|
||||
.prepare("UPDATE messages SET delivery_contract = 'legacy_direct' WHERE id = ?")
|
||||
.run(rejection.id)
|
||||
const seedAuditOnly = raw.prepare(
|
||||
"UPDATE messages SET delivery_contract = 'audit_only' WHERE id = ?"
|
||||
)
|
||||
for (const message of [lookalike, ...malformedRejections]) {
|
||||
seedAuditOnly.run(message.id)
|
||||
}
|
||||
raw.exec(`
|
||||
DROP INDEX IF EXISTS idx_messages_delivery_contract;
|
||||
DROP TABLE legacy_mail_receipts;
|
||||
DROP TABLE legacy_operation_receipts;
|
||||
DROP TABLE legacy_compatibility_principals;
|
||||
DROP TABLE legacy_adoptions;
|
||||
`)
|
||||
raw.pragma('user_version = 18')
|
||||
raw.close()
|
||||
|
||||
return {
|
||||
tempDir,
|
||||
fixture: {
|
||||
dbPath,
|
||||
currentRunId: currentRun.id,
|
||||
unrelatedRunId: unrelatedRun.id,
|
||||
currentDispatchId: currentDispatch.id,
|
||||
legacyTaskId: legacyTask.id,
|
||||
legacyDispatchId: retryDispatch.id,
|
||||
legacyGateId: legacyGate.id,
|
||||
legacyMessageIds: legacyMessages.map((message) => message.id),
|
||||
legacyQuestionId: question.message.id,
|
||||
legacyDeliveryId,
|
||||
rejectionMessageId: rejection.id,
|
||||
lookalikeMessageId: lookalike.id,
|
||||
malformedRejectionMessageIds: malformedRejections.map((message) => message.id)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { LegacyWorkerTerminalRecoveryRow } from './types'
|
||||
import { planLegacyWorkerTerminalRecovery } from './orchestration-legacy-worker-terminal-recovery'
|
||||
|
||||
const LEAF_ID = '11111111-1111-4111-8111-111111111111'
|
||||
const INCARNATION_ID = '22222222-2222-4222-8222-222222222222'
|
||||
|
||||
function recoveryRow(
|
||||
overrides: Partial<LegacyWorkerTerminalRecoveryRow> = {}
|
||||
): LegacyWorkerTerminalRecoveryRow {
|
||||
return {
|
||||
dispatch_id: 'dispatch-1',
|
||||
task_id: 'task-1',
|
||||
dispatch_status: 'completed',
|
||||
contract_version: 0,
|
||||
assignee_handle: 'term-worker',
|
||||
assignee_pane_key: `tab-worker:${LEAF_ID}`,
|
||||
process_incarnation: `ssh:ssh-1@@pty-worker:${INCARNATION_ID}`,
|
||||
worker_state: 'ready',
|
||||
worktree_id: 'repo::/workspace',
|
||||
agent_terminal_handle: 'term-worker',
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('legacy worker terminal recovery planning', () => {
|
||||
it('retains completed Dispatches when the worker process row is still live', () => {
|
||||
expect(planLegacyWorkerTerminalRecovery([recoveryRow()])).toEqual({
|
||||
blockedPanes: [
|
||||
{
|
||||
worktreeId: 'repo::/workspace',
|
||||
paneKey: `tab-worker:${LEAF_ID}`,
|
||||
contractVersion: 0
|
||||
}
|
||||
],
|
||||
candidates: [
|
||||
expect.objectContaining({
|
||||
dispatchId: 'dispatch-1',
|
||||
ptyId: 'ssh:ssh-1@@pty-worker',
|
||||
incarnationId: INCARNATION_ID
|
||||
})
|
||||
],
|
||||
ambiguousDispatchIds: []
|
||||
})
|
||||
})
|
||||
|
||||
it('blocks resume but refuses recovery when durable handles disagree', () => {
|
||||
expect(
|
||||
planLegacyWorkerTerminalRecovery([recoveryRow({ agent_terminal_handle: 'term-replacement' })])
|
||||
).toEqual({
|
||||
blockedPanes: [
|
||||
{
|
||||
worktreeId: 'repo::/workspace',
|
||||
paneKey: `tab-worker:${LEAF_ID}`,
|
||||
contractVersion: 0
|
||||
}
|
||||
],
|
||||
candidates: [],
|
||||
ambiguousDispatchIds: []
|
||||
})
|
||||
})
|
||||
|
||||
it('fails closed when two Dispatches claim one terminal identity', () => {
|
||||
const plan = planLegacyWorkerTerminalRecovery([
|
||||
recoveryRow(),
|
||||
recoveryRow({ dispatch_id: 'dispatch-2', task_id: 'task-2' })
|
||||
])
|
||||
|
||||
expect(plan.candidates).toEqual([])
|
||||
expect(plan.ambiguousDispatchIds).toEqual(['dispatch-1', 'dispatch-2'])
|
||||
expect(plan.blockedPanes).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('does not trust malformed pane or process identities', () => {
|
||||
const plan = planLegacyWorkerTerminalRecovery([
|
||||
recoveryRow({
|
||||
assignee_pane_key: 'tab-worker:1',
|
||||
process_incarnation: 'runtime:pty:generation'
|
||||
})
|
||||
])
|
||||
|
||||
expect(plan).toEqual({
|
||||
blockedPanes: [],
|
||||
candidates: [],
|
||||
ambiguousDispatchIds: []
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,119 @@
|
||||
import { isPtyIncarnationId, type PtyIncarnationId } from '../../../shared/pty-incarnation'
|
||||
import { parsePaneKey } from '../../../shared/stable-pane-id'
|
||||
import type { LegacyWorkerTerminalRecoveryRow } from './types'
|
||||
|
||||
export type LegacyWorkerTerminalRecoveryCandidate = {
|
||||
dispatchId: string
|
||||
dispatchStatus: LegacyWorkerTerminalRecoveryRow['dispatch_status']
|
||||
contractVersion: number
|
||||
taskId: string
|
||||
worktreeId: string
|
||||
terminalHandle: string
|
||||
paneKey: string
|
||||
tabId: string
|
||||
leafId: string
|
||||
processIncarnation: string
|
||||
ptyId: string
|
||||
incarnationId: PtyIncarnationId
|
||||
}
|
||||
|
||||
export type LegacyWorkerTerminalRecoveryPlan = {
|
||||
blockedPanes: { worktreeId: string; paneKey: string; contractVersion: number }[]
|
||||
candidates: LegacyWorkerTerminalRecoveryCandidate[]
|
||||
ambiguousDispatchIds: string[]
|
||||
}
|
||||
|
||||
function parseProcessIncarnation(
|
||||
value: string
|
||||
): { ptyId: string; incarnationId: PtyIncarnationId } | null {
|
||||
const separator = value.lastIndexOf(':')
|
||||
if (separator <= 0) {
|
||||
return null
|
||||
}
|
||||
const ptyId = value.slice(0, separator)
|
||||
const incarnationId = value.slice(separator + 1)
|
||||
return ptyId && isPtyIncarnationId(incarnationId) ? { ptyId, incarnationId } : null
|
||||
}
|
||||
|
||||
function countCandidateKeys(
|
||||
candidates: readonly LegacyWorkerTerminalRecoveryCandidate[],
|
||||
select: (candidate: LegacyWorkerTerminalRecoveryCandidate) => string
|
||||
): Map<string, number> {
|
||||
const counts = new Map<string, number>()
|
||||
for (const candidate of candidates) {
|
||||
const key = select(candidate)
|
||||
counts.set(key, (counts.get(key) ?? 0) + 1)
|
||||
}
|
||||
return counts
|
||||
}
|
||||
|
||||
export function planLegacyWorkerTerminalRecovery(
|
||||
rows: readonly LegacyWorkerTerminalRecoveryRow[]
|
||||
): LegacyWorkerTerminalRecoveryPlan {
|
||||
const blockedPanes = new Map<
|
||||
string,
|
||||
{ worktreeId: string; paneKey: string; contractVersion: number }
|
||||
>()
|
||||
const parsedCandidates: LegacyWorkerTerminalRecoveryCandidate[] = []
|
||||
for (const row of rows) {
|
||||
const worktreeId = row.worktree_id?.trim()
|
||||
const paneKey = row.assignee_pane_key?.trim()
|
||||
const pane = paneKey ? parsePaneKey(paneKey) : null
|
||||
if (worktreeId && paneKey && pane) {
|
||||
blockedPanes.set(`${worktreeId}\0${paneKey}`, {
|
||||
worktreeId,
|
||||
paneKey,
|
||||
contractVersion: row.contract_version
|
||||
})
|
||||
}
|
||||
const terminalHandle = row.assignee_handle?.trim()
|
||||
const workerHandle = row.agent_terminal_handle?.trim()
|
||||
const processIncarnation = row.process_incarnation?.trim()
|
||||
const process = processIncarnation ? parseProcessIncarnation(processIncarnation) : null
|
||||
if (
|
||||
!worktreeId ||
|
||||
!paneKey ||
|
||||
!pane ||
|
||||
!terminalHandle ||
|
||||
terminalHandle !== workerHandle ||
|
||||
!processIncarnation ||
|
||||
!process
|
||||
) {
|
||||
continue
|
||||
}
|
||||
parsedCandidates.push({
|
||||
dispatchId: row.dispatch_id,
|
||||
dispatchStatus: row.dispatch_status,
|
||||
contractVersion: row.contract_version,
|
||||
taskId: row.task_id,
|
||||
worktreeId,
|
||||
terminalHandle,
|
||||
paneKey,
|
||||
tabId: pane.tabId,
|
||||
leafId: pane.leafId,
|
||||
processIncarnation,
|
||||
ptyId: process.ptyId,
|
||||
incarnationId: process.incarnationId
|
||||
})
|
||||
}
|
||||
|
||||
const identityCounts = [
|
||||
countCandidateKeys(parsedCandidates, (candidate) => candidate.terminalHandle),
|
||||
countCandidateKeys(parsedCandidates, (candidate) => candidate.paneKey),
|
||||
countCandidateKeys(parsedCandidates, (candidate) => candidate.processIncarnation)
|
||||
]
|
||||
const ambiguousDispatchIds = new Set<string>()
|
||||
const candidates = parsedCandidates.filter((candidate) => {
|
||||
const keys = [candidate.terminalHandle, candidate.paneKey, candidate.processIncarnation]
|
||||
const ambiguous = keys.some((key, index) => (identityCounts[index]?.get(key) ?? 0) !== 1)
|
||||
if (ambiguous) {
|
||||
ambiguousDispatchIds.add(candidate.dispatchId)
|
||||
}
|
||||
return !ambiguous
|
||||
})
|
||||
return {
|
||||
blockedPanes: [...blockedPanes.values()],
|
||||
candidates,
|
||||
ambiguousDispatchIds: [...ambiguousDispatchIds]
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,12 @@ import type Database from '../../sqlite/sync-database'
|
||||
|
||||
const POST_V6_COLUMNS = [
|
||||
['messages', 'run_id'],
|
||||
['messages', 'delivery_contract'],
|
||||
['coordinator_runs', 'scheduler_lost_at'],
|
||||
['tasks', 'run_id'],
|
||||
['dispatch_contexts', 'run_id'],
|
||||
['dispatch_contexts', 'contract_version'],
|
||||
['dispatch_contexts', 'launch_token_hash'],
|
||||
['dispatch_contexts', 'capability_hash'],
|
||||
['dispatch_contexts', 'process_incarnation'],
|
||||
['dispatch_contexts', 'capability_revoked_at'],
|
||||
@@ -14,11 +18,16 @@ const POST_V6_COLUMNS = [
|
||||
['remote_dispatch_attachments', 'to_worker_imported_sequence'],
|
||||
['remote_dispatch_attachments', 'protocol_version'],
|
||||
['federation_relay_items', 'dispatch_id'],
|
||||
['remote_questions', 'message_id']
|
||||
['remote_questions', 'message_id'],
|
||||
['legacy_adoptions', 'source_run_id'],
|
||||
['legacy_compatibility_principals', 'id'],
|
||||
['legacy_operation_receipts', 'principal_id'],
|
||||
['legacy_mail_receipts', 'principal_id']
|
||||
] as const
|
||||
|
||||
const POST_V6_INDEXES = [
|
||||
'idx_messages_run_sequence',
|
||||
'idx_messages_delivery_contract',
|
||||
'idx_tasks_run_status',
|
||||
'idx_dispatch_run_status',
|
||||
'idx_gates_run_status',
|
||||
@@ -46,11 +55,39 @@ function messagesAllowQuestions(db: Database.Database): boolean {
|
||||
return !!row && row.sql.includes("'question'")
|
||||
}
|
||||
|
||||
function hasConsistentLegacyAdoption(db: Database.Database): boolean {
|
||||
const sourceRunId = 'run_legacy_local'
|
||||
const sourceGraph = db
|
||||
.prepare(
|
||||
`SELECT 1
|
||||
WHERE EXISTS(SELECT 1 FROM tasks WHERE run_id = ?)
|
||||
OR EXISTS(SELECT 1 FROM dispatch_contexts WHERE run_id = ?)
|
||||
OR EXISTS(SELECT 1 FROM decision_gates WHERE run_id = ?)
|
||||
OR EXISTS(SELECT 1 FROM messages WHERE run_id = ?)
|
||||
OR EXISTS(SELECT 1 FROM question_threads WHERE run_id = ?)
|
||||
OR EXISTS(SELECT 1 FROM deliveries WHERE run_id = ?)`
|
||||
)
|
||||
.get(sourceRunId, sourceRunId, sourceRunId, sourceRunId, sourceRunId, sourceRunId)
|
||||
const adoption = db
|
||||
.prepare('SELECT adopted_run_id FROM legacy_adoptions WHERE source_run_id = ?')
|
||||
.get(sourceRunId) as { adopted_run_id: string } | undefined
|
||||
if (sourceGraph) {
|
||||
return false
|
||||
}
|
||||
if (adoption) {
|
||||
return Boolean(
|
||||
db.prepare('SELECT 1 FROM runs WHERE id = ? AND legacy = 0').get(adoption.adopted_run_id)
|
||||
)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function hasCompletePostV6Schema(db: Database.Database): boolean {
|
||||
return (
|
||||
POST_V6_COLUMNS.every(([table, column]) => hasOrchestrationColumn(db, table, column)) &&
|
||||
POST_V6_INDEXES.every((index) => hasOrchestrationIndex(db, index)) &&
|
||||
messagesAllowQuestions(db)
|
||||
messagesAllowQuestions(db) &&
|
||||
hasConsistentLegacyAdoption(db)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -59,9 +96,12 @@ export function resolveOrchestrationMigrationStartVersion(
|
||||
storedVersion: number,
|
||||
schemaVersion: number
|
||||
): number {
|
||||
if (storedVersion >= schemaVersion || hasCompletePostV6Schema(db)) {
|
||||
if (storedVersion > schemaVersion) {
|
||||
return storedVersion
|
||||
}
|
||||
if (hasCompletePostV6Schema(db)) {
|
||||
return storedVersion
|
||||
}
|
||||
// Why: version-skewed pre-Run databases can claim the post-v6 range while retaining v6 tables.
|
||||
return Math.min(storedVersion, 6)
|
||||
return Math.min(storedVersion, schemaVersion, 6)
|
||||
}
|
||||
|
||||
@@ -3,7 +3,8 @@ import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import Database from '../../sqlite/sync-database'
|
||||
import { LEGACY_RUN_ID, OrchestrationDb } from './db'
|
||||
import { LEGACY_CONTRACT_VERSION, LEGACY_RUN_ID, OrchestrationDb } from './db'
|
||||
import { resolveOrchestrationMigrationStartVersion } from './orchestration-schema-version-skew'
|
||||
|
||||
describe('OrchestrationDb version-skew migration', () => {
|
||||
let db: OrchestrationDb | undefined
|
||||
@@ -11,12 +12,14 @@ describe('OrchestrationDb version-skew migration', () => {
|
||||
|
||||
afterEach(() => {
|
||||
db?.close()
|
||||
db = undefined
|
||||
if (tempDir) {
|
||||
rmSync(tempDir, { recursive: true, force: true })
|
||||
tempDir = undefined
|
||||
}
|
||||
})
|
||||
|
||||
function createLegacySchemaClaimingVersion17(): string {
|
||||
function createLegacySchemaClaimingVersion(claimedVersion = 17): string {
|
||||
tempDir = mkdtempSync(join(tmpdir(), 'orca-db-version-skew-'))
|
||||
const dbPath = join(tempDir, 'orchestration.db')
|
||||
const raw = new Database(dbPath)
|
||||
@@ -126,20 +129,28 @@ describe('OrchestrationDb version-skew migration', () => {
|
||||
'gate_legacy', 'task_legacy', 'retained gate'
|
||||
);
|
||||
`)
|
||||
raw.pragma('user_version = 17')
|
||||
raw.pragma(`user_version = ${claimedVersion}`)
|
||||
raw.close()
|
||||
return dbPath
|
||||
}
|
||||
|
||||
it('repairs retained v6 rows when the database already claims v17', () => {
|
||||
const dbPath = createLegacySchemaClaimingVersion17()
|
||||
const dbPath = createLegacySchemaClaimingVersion()
|
||||
db = new OrchestrationDb(dbPath)
|
||||
|
||||
const adoptedRunId = db.getLegacyAdoption()?.adopted_run_id
|
||||
expect(adoptedRunId).toBeTruthy()
|
||||
expect(db.getRun(LEGACY_RUN_ID)).toMatchObject({ legacy: 1 })
|
||||
expect(db.getMessageById('msg_legacy')).toMatchObject({ run_id: LEGACY_RUN_ID })
|
||||
expect(db.getTask('task_legacy')).toMatchObject({ run_id: LEGACY_RUN_ID })
|
||||
expect(db.getDispatchContextById('ctx_legacy')).toMatchObject({ run_id: LEGACY_RUN_ID })
|
||||
expect(db.getGate('gate_legacy')).toMatchObject({ run_id: LEGACY_RUN_ID })
|
||||
expect(db.getMessageById('msg_legacy')).toMatchObject({
|
||||
run_id: adoptedRunId,
|
||||
delivery_contract: 'legacy_direct'
|
||||
})
|
||||
expect(db.getTask('task_legacy')).toMatchObject({ run_id: adoptedRunId })
|
||||
expect(db.getDispatchContextById('ctx_legacy')).toMatchObject({
|
||||
run_id: adoptedRunId,
|
||||
contract_version: LEGACY_CONTRACT_VERSION
|
||||
})
|
||||
expect(db.getGate('gate_legacy')).toMatchObject({ run_id: adoptedRunId })
|
||||
|
||||
const run = db.createRun({
|
||||
objective: 'verify repaired orchestration',
|
||||
@@ -164,8 +175,18 @@ describe('OrchestrationDb version-skew migration', () => {
|
||||
db.close()
|
||||
db = undefined
|
||||
db = new OrchestrationDb(dbPath)
|
||||
expect(db.listTasks({ runId: LEGACY_RUN_ID }).map((row) => row.id)).toEqual(['task_legacy'])
|
||||
expect(db.listTasks({ runId: adoptedRunId }).map((row) => row.id)).toEqual(['task_legacy'])
|
||||
expect(db.getRun(run.id)).toBeDefined()
|
||||
expect(db.getQuestion(question.message.id)).toMatchObject({ status: 'pending' })
|
||||
})
|
||||
|
||||
it('does not repair an incomplete schema written by a future binary', () => {
|
||||
const dbPath = createLegacySchemaClaimingVersion(20)
|
||||
const raw = new Database(dbPath)
|
||||
|
||||
expect(resolveOrchestrationMigrationStartVersion(raw, 20, 19)).toBe(20)
|
||||
expect(raw.pragma('user_version', { simple: true })).toBe(20)
|
||||
|
||||
raw.close()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { OrchestrationDb } from './db'
|
||||
import { CURRENT_CONTRACT_VERSION, OrchestrationDb } from './db'
|
||||
|
||||
describe('OrchestrationDb worker Dispatch state', () => {
|
||||
let db: OrchestrationDb | undefined
|
||||
@@ -44,6 +44,51 @@ describe('OrchestrationDb worker Dispatch state', () => {
|
||||
status: 'dispatched',
|
||||
assignee_handle: 'term_worker'
|
||||
})
|
||||
expect(d.listLegacyWorkerTerminalRecoveryRows()).toEqual([
|
||||
expect.objectContaining({
|
||||
dispatch_id: started.dispatch.id,
|
||||
contract_version: CURRENT_CONTRACT_VERSION,
|
||||
worker_state: 'ready',
|
||||
agent_terminal_handle: 'term_worker'
|
||||
})
|
||||
])
|
||||
})
|
||||
|
||||
it('requeues an active Task before settling a worker whose terminal is missing', () => {
|
||||
const d = createDb()
|
||||
const task = d.createTask({ spec: 'recover missing worker' })
|
||||
const started = d.createStartingWorkerDispatch({
|
||||
taskId: task.id,
|
||||
startOptions: { topology: 'current', agent: 'codex' }
|
||||
})
|
||||
d.prepareStartingWorkerAuthority({
|
||||
dispatchId: started.dispatch.id,
|
||||
handle: 'term_missing',
|
||||
paneKey: 'tab_missing:11111111-1111-4111-8111-111111111111',
|
||||
processIncarnation: 'pty-missing:22222222-2222-4222-8222-222222222222',
|
||||
worktreeId: 'repo::worktree',
|
||||
setupState: 'not_applicable',
|
||||
effects: []
|
||||
})
|
||||
d.markWorkerDispatchReady(started.dispatch.id)
|
||||
|
||||
expect(
|
||||
d.reconcileMissingWorkerTerminal(started.dispatch.id, 'worker terminal is no longer live')
|
||||
).toMatchObject({
|
||||
state: 'abandoned',
|
||||
stage: 'terminal_missing',
|
||||
last_error: 'worker terminal is no longer live'
|
||||
})
|
||||
expect(d.getDispatchContextById(started.dispatch.id)).toMatchObject({
|
||||
status: 'failed',
|
||||
failure_count: 1,
|
||||
last_failure: 'worker terminal is no longer live'
|
||||
})
|
||||
expect(d.getTask(task.id)?.status).toBe('ready')
|
||||
|
||||
d.reconcileMissingWorkerTerminal(started.dispatch.id, 'duplicate recovery')
|
||||
expect(d.getDispatchContextById(started.dispatch.id)?.failure_count).toBe(1)
|
||||
expect(d.getTask(task.id)?.status).toBe('ready')
|
||||
})
|
||||
|
||||
it('commits worker-start mutation acceptance with the starting Dispatch', () => {
|
||||
|
||||
@@ -14,6 +14,8 @@ export type MessageType = (typeof MESSAGE_TYPES)[number]
|
||||
|
||||
export type MessagePriority = 'normal' | 'high' | 'urgent'
|
||||
|
||||
export type MessageDeliveryContract = 'legacy_direct' | 'current_delivery' | 'audit_only'
|
||||
|
||||
export type TaskStatus = 'pending' | 'ready' | 'dispatched' | 'completed' | 'failed' | 'blocked'
|
||||
|
||||
export type DispatchStatus = 'pending' | 'dispatched' | 'completed' | 'failed' | 'circuit_broken'
|
||||
@@ -61,6 +63,46 @@ export type DeliveryRow = {
|
||||
acknowledged_at: string | null
|
||||
}
|
||||
|
||||
export type LegacyAdoptionRow = {
|
||||
source_run_id: string
|
||||
adopted_run_id: string
|
||||
scheduler_state_lost: number
|
||||
adopted_at: string
|
||||
}
|
||||
|
||||
export type LegacyPrincipalRole = 'worker' | 'coordinator'
|
||||
|
||||
export type LegacyPrincipalStatus = 'committed' | 'settled' | 'revoked'
|
||||
|
||||
export type LegacyCompatibilityPrincipalRow = {
|
||||
id: string
|
||||
run_id: string
|
||||
dispatch_id: string | null
|
||||
role: LegacyPrincipalRole
|
||||
host_scope: string
|
||||
terminal_handle: string
|
||||
pane_key: string
|
||||
launch_token_hash: string
|
||||
process_incarnation: string | null
|
||||
status: LegacyPrincipalStatus
|
||||
}
|
||||
|
||||
export type LegacyOperationReceiptRow = {
|
||||
principal_id: string
|
||||
operation_key: string
|
||||
method: string
|
||||
payload_hash: string
|
||||
effect_id: string
|
||||
response_json: string
|
||||
completed_at: string
|
||||
}
|
||||
|
||||
export type LegacyMailReceiptRow = {
|
||||
principal_id: string
|
||||
message_id: string
|
||||
acknowledged_at: string | null
|
||||
}
|
||||
|
||||
export type QuestionStatus = 'pending' | 'answered' | 'closed'
|
||||
|
||||
export type QuestionRow = {
|
||||
@@ -117,6 +159,19 @@ export type WorkerDispatchRow = {
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
export type LegacyWorkerTerminalRecoveryRow = {
|
||||
dispatch_id: string
|
||||
task_id: string
|
||||
dispatch_status: DispatchStatus
|
||||
contract_version: number
|
||||
assignee_handle: string | null
|
||||
assignee_pane_key: string | null
|
||||
process_incarnation: string | null
|
||||
worker_state: WorkerDispatchState
|
||||
worktree_id: string | null
|
||||
agent_terminal_handle: string | null
|
||||
}
|
||||
|
||||
export type FederatedDispatchRow = {
|
||||
dispatch_id: string
|
||||
environment_id: string
|
||||
@@ -170,6 +225,7 @@ export type FederationRelayItemRow = {
|
||||
export type MessageRow = {
|
||||
id: string
|
||||
run_id: string
|
||||
delivery_contract?: MessageDeliveryContract
|
||||
from_handle: string
|
||||
to_handle: string
|
||||
subject: string
|
||||
@@ -204,6 +260,8 @@ export type DispatchContextRow = {
|
||||
id: string
|
||||
run_id: string
|
||||
task_id: string
|
||||
contract_version: number
|
||||
launch_token_hash: string | null
|
||||
assignee_handle: string | null
|
||||
assignee_pane_key: string | null
|
||||
capability_hash: string | null
|
||||
@@ -238,4 +296,5 @@ export type CoordinatorRun = {
|
||||
poll_interval_ms: number
|
||||
created_at: string
|
||||
completed_at: string | null
|
||||
scheduler_lost_at: string | null
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { resolveAdvertisedPairingEndpoint } from './pairing-endpoint'
|
||||
import { PAIRING_OFFER_VERSION, PairingOfferSchema } from '../../shared/mobile-relay-pairing-offer'
|
||||
import { PAIRING_ENDPOINT_MAX_CHARACTERS } from '../../shared/mobile-pairing-protocol-limits'
|
||||
import { parseManualNetworkAddress } from '../../shared/network/manual-address'
|
||||
|
||||
describe('resolveAdvertisedPairingEndpoint', () => {
|
||||
const bound = 'ws://0.0.0.0:6768'
|
||||
@@ -17,8 +20,10 @@ describe('resolveAdvertisedPairingEndpoint', () => {
|
||||
['proxy.example.test:80', 'ws://proxy.example.test'],
|
||||
['lan-host:7443', 'ws://lan-host:7443'],
|
||||
['::1', 'ws://[::1]:6768'],
|
||||
['0:0:0:0:0:0:0:1', 'ws://[::1]:6768'],
|
||||
['2001:db8::0', 'ws://[2001:db8::]:6768'],
|
||||
['[2001:db8::4]:7443', 'ws://[2001:db8::4]:7443'],
|
||||
['[0:0:0:0:0:0:0:1]:7443', 'ws://[::1]:7443'],
|
||||
['http://proxy.example.test/orca', 'ws://proxy.example.test/orca'],
|
||||
['https://proxy.example.test/orca', 'wss://proxy.example.test/orca'],
|
||||
[
|
||||
@@ -36,6 +41,12 @@ describe('resolveAdvertisedPairingEndpoint', () => {
|
||||
'*',
|
||||
'0.0.0.0',
|
||||
'::',
|
||||
'0:0:0:0:0:0:0:0',
|
||||
'[0:0:0:0:0:0:0:0]:8080',
|
||||
'ws://[0:0:0:0:0:0:0:0]:8080',
|
||||
'::ffff:0.0.0.0',
|
||||
'[::ffff:0.0.0.0]:8080',
|
||||
'ws://[::ffff:0.0.0.0]:8080',
|
||||
'ftp://proxy.example.test',
|
||||
'ws://user:secret@proxy.example.test',
|
||||
'ws://proxy.example.test/#fragment',
|
||||
@@ -50,4 +61,42 @@ describe('resolveAdvertisedPairingEndpoint', () => {
|
||||
reason: 'invalid_advertised_endpoint'
|
||||
})
|
||||
})
|
||||
|
||||
it.each([
|
||||
['::ffff:192.168.1.24', 'ws://[::ffff:c0a8:118]:6768'],
|
||||
['[::ffff:192.168.1.24]:8080', 'ws://[::ffff:c0a8:118]:8080'],
|
||||
['2001:db8::24', 'ws://[2001:db8::24]:6768']
|
||||
])('accepts reachable mapped/native IPv6 control %s', (input, endpoint) => {
|
||||
expect(resolveAdvertisedPairingEndpoint(bound, input)).toEqual({ ok: true, endpoint })
|
||||
})
|
||||
|
||||
it.each([
|
||||
['ws://host.example.test.', true],
|
||||
['ws://0x7f.1:6768', true],
|
||||
['\u0000ws://host.example.test', false],
|
||||
['ws://host.example.test/path\u0001', false]
|
||||
])('keeps full-URL renderer/main acceptance aligned for %j', (input, accepted) => {
|
||||
expect(parseManualNetworkAddress(input).ok).toBe(accepted)
|
||||
expect(resolveAdvertisedPairingEndpoint(bound, input).ok).toBe(accepted)
|
||||
})
|
||||
|
||||
it('matches the pairing-offer endpoint length boundary', () => {
|
||||
const prefix = 'wss://example.test/'
|
||||
const atLimit = `${prefix}${'a'.repeat(PAIRING_ENDPOINT_MAX_CHARACTERS - prefix.length)}`
|
||||
const aboveLimit = `${atLimit}a`
|
||||
const offer = (endpoint: string) => ({
|
||||
v: PAIRING_OFFER_VERSION,
|
||||
endpoint,
|
||||
deviceToken: 'token',
|
||||
publicKeyB64: 'key'
|
||||
})
|
||||
|
||||
expect(resolveAdvertisedPairingEndpoint(bound, atLimit)).toEqual({
|
||||
ok: true,
|
||||
endpoint: atLimit
|
||||
})
|
||||
expect(PairingOfferSchema.safeParse(offer(atLimit)).success).toBe(true)
|
||||
expect(resolveAdvertisedPairingEndpoint(bound, aboveLimit).ok).toBe(false)
|
||||
expect(PairingOfferSchema.safeParse(offer(aboveLimit)).success).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { isIP } from 'node:net'
|
||||
import { PAIRING_ENDPOINT_MAX_CHARACTERS } from '../../shared/mobile-pairing-protocol-limits'
|
||||
import { isPairingWildcardHostname, normalizePairingUrl } from '../../shared/network/pairing-url'
|
||||
|
||||
export const INVALID_PAIRING_ENDPOINT_GUIDANCE =
|
||||
'Use a reachable hostname, host:port, IPv4/IPv6 literal, or ws(s):// URL. HTTP(S) URLs are normalized to WebSocket URLs.'
|
||||
@@ -39,29 +41,8 @@ export function resolveAdvertisedPairingEndpoint(
|
||||
}
|
||||
|
||||
function resolveFullUrl(value: string): PairingEndpointResolution {
|
||||
let endpoint: URL
|
||||
try {
|
||||
endpoint = new URL(value)
|
||||
} catch {
|
||||
return invalid()
|
||||
}
|
||||
if (endpoint.protocol === 'http:') {
|
||||
endpoint.protocol = 'ws:'
|
||||
} else if (endpoint.protocol === 'https:') {
|
||||
endpoint.protocol = 'wss:'
|
||||
}
|
||||
if (
|
||||
(endpoint.protocol !== 'ws:' && endpoint.protocol !== 'wss:') ||
|
||||
!endpoint.hostname ||
|
||||
endpoint.username ||
|
||||
endpoint.password ||
|
||||
endpoint.hash ||
|
||||
endpoint.port === '0' ||
|
||||
isWildcardHost(endpoint.hostname)
|
||||
) {
|
||||
return invalid()
|
||||
}
|
||||
return valid(formatWebSocketUrl(endpoint))
|
||||
const endpoint = normalizePairingUrl(value)
|
||||
return endpoint ? valid(endpoint) : invalid()
|
||||
}
|
||||
|
||||
function parseHostOverride(value: string): { hostname: string; port: string } | null {
|
||||
@@ -98,9 +79,7 @@ function getExplicitPort(value: string): string | null {
|
||||
}
|
||||
|
||||
function isWildcardHost(hostname: string): boolean {
|
||||
const normalized = unbracketIpv6(hostname).toLowerCase()
|
||||
// Why: wildcard bind addresses identify local interfaces, not a route a client can connect to.
|
||||
return normalized === '*' || normalized === '0.0.0.0' || normalized === '::'
|
||||
return isPairingWildcardHostname(hostname)
|
||||
}
|
||||
|
||||
function bracketIpv6(hostname: string): string {
|
||||
@@ -118,6 +97,9 @@ function formatWebSocketUrl(url: URL): string {
|
||||
}
|
||||
|
||||
function valid(endpoint: string): PairingEndpointResolution {
|
||||
if (endpoint.length > PAIRING_ENDPOINT_MAX_CHARACTERS) {
|
||||
return invalid()
|
||||
}
|
||||
return { ok: true, endpoint }
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Why: single boundary between raw RPC frames and OrcaRuntimeService; keeps schema, handler, and result type on one object.
|
||||
import { ZodError, type ZodType } from 'zod'
|
||||
import type { TerminalStreamFrame } from '../../../shared/terminal-stream-protocol'
|
||||
import type { OrcaRuntimeService } from '../orca-runtime'
|
||||
import type { OrcaRuntimeService, OrchestrationCompatibilityCallerAuthority } from '../orca-runtime'
|
||||
import type {
|
||||
DeviceCredentialInstalled,
|
||||
PairingGetEndpointsParams,
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
PairingProvisionRelayParams
|
||||
} from '../../../shared/mobile-relay-credential-contract'
|
||||
import type { RuntimeCapability } from '../../../shared/protocol-version'
|
||||
import type { OrchestrationCompatibilityEvidence } from '../../../shared/orchestration-compatibility-evidence'
|
||||
|
||||
export type PairingRpcContext = {
|
||||
getEndpoints(params: PairingGetEndpointsParams): Promise<PairingGetEndpointsResult>
|
||||
@@ -48,8 +49,18 @@ export type RpcRequest = {
|
||||
orchestrationCapability?: string
|
||||
orchestrationContractVersion?: number
|
||||
orchestrationRequestId?: string
|
||||
compatibilityInvocationId?: string
|
||||
orchestrationCompatibilityEvidence?: OrchestrationCompatibilityEvidence
|
||||
}
|
||||
|
||||
export type LegacyCoordinatorAuthorityProof = Readonly<{
|
||||
runId: string
|
||||
principalId: string | null
|
||||
terminalHandle: string
|
||||
paneKey: string
|
||||
consumerGeneration: number
|
||||
}>
|
||||
|
||||
export type RpcContext = {
|
||||
runtime: OrcaRuntimeService
|
||||
// Why: lets long-poll handlers release immediately on client disconnect instead of running down timeoutMs. See design doc §3.1.
|
||||
@@ -77,6 +88,11 @@ export type RpcContext = {
|
||||
method: string
|
||||
payloadHash: string
|
||||
}
|
||||
// Why: only the compatibility authority router can set this trusted scope; user params cannot bypass Run consumer binding.
|
||||
legacyCoordinatorRunId?: string
|
||||
legacyCoordinatorAuthority?: LegacyCoordinatorAuthorityProof
|
||||
revalidateLegacyCoordinator?: () => string
|
||||
orchestrationCompatibilityCallerAuthority?: OrchestrationCompatibilityCallerAuthority
|
||||
// Why: federation pins the authenticated saved-environment caller without exposing its token to handlers or storage.
|
||||
authenticatedCallerFingerprint?: string
|
||||
pairing?: PairingRpcContext
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { InvalidArgumentError, ZodError, formatZodError } from './core'
|
||||
import type { RpcEnvelopeMeta, RpcRequest, RpcResponse } from './core'
|
||||
import {
|
||||
computerErrorData,
|
||||
errorResponse,
|
||||
mapBrowserError,
|
||||
mapEmulatorError,
|
||||
mapRuntimeError
|
||||
} from './errors'
|
||||
|
||||
export function invalidArgumentResponse(
|
||||
request: RpcRequest,
|
||||
meta: RpcEnvelopeMeta,
|
||||
message: string
|
||||
): RpcResponse {
|
||||
return errorResponse(
|
||||
request.id,
|
||||
meta,
|
||||
'invalid_argument',
|
||||
message,
|
||||
request.method.startsWith('computer.') ? computerErrorData('invalid_argument') : undefined
|
||||
)
|
||||
}
|
||||
|
||||
export function mapDispatcherError(
|
||||
request: RpcRequest,
|
||||
meta: RpcEnvelopeMeta,
|
||||
error: unknown
|
||||
): RpcResponse {
|
||||
if (error instanceof ZodError) {
|
||||
return invalidArgumentResponse(request, meta, formatZodError(error))
|
||||
}
|
||||
if (error instanceof InvalidArgumentError) {
|
||||
return invalidArgumentResponse(request, meta, error.message)
|
||||
}
|
||||
if (request.method.startsWith('browser.')) {
|
||||
return mapBrowserError(request.id, meta, error)
|
||||
}
|
||||
if (request.method.startsWith('emulator.')) {
|
||||
return mapEmulatorError(request.id, meta, error)
|
||||
}
|
||||
return mapRuntimeError(request.id, meta, error)
|
||||
}
|
||||
@@ -46,6 +46,10 @@ function makeRuntime(ui: PersistedUIState = getDefaultUIState()): OrcaRuntimeSer
|
||||
updateUIState: vi.fn((updates: Partial<PersistedUIState>) => {
|
||||
currentUI = { ...currentUI, ...updates }
|
||||
return currentUI
|
||||
}),
|
||||
getOrchestrationDb: () => ({
|
||||
getLegacyAdoption: () => undefined,
|
||||
resolveLegacyWorkerCandidate: () => undefined
|
||||
})
|
||||
} as unknown as OrcaRuntimeService
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { RuntimeCapability } from '../../../shared/protocol-version'
|
||||
import type { TerminalStreamFrame } from '../../../shared/terminal-stream-protocol'
|
||||
import type { PairingRpcContext } from './core'
|
||||
|
||||
export type RpcDispatchStreamingOptions = {
|
||||
connectionId?: string
|
||||
signal?: AbortSignal
|
||||
clientId?: string
|
||||
pairedDeviceId?: string
|
||||
clientKind?: 'mobile' | 'runtime'
|
||||
clientCapabilities?: readonly RuntimeCapability[]
|
||||
pairing?: PairingRpcContext
|
||||
sendBinary?: (bytes: Uint8Array<ArrayBufferLike>) => boolean | void
|
||||
registerBinaryStreamHandler?: (
|
||||
streamId: number,
|
||||
handler: (frame: TerminalStreamFrame) => void
|
||||
) => () => void
|
||||
}
|
||||
+100
-118
@@ -1,57 +1,44 @@
|
||||
// Why: the dispatcher is the one place that knows how to turn a validated
|
||||
// RPC request into a response envelope. Splitting it from the transport
|
||||
// makes it unit-testable without spinning up a socket, and keeps
|
||||
// runtime-rpc.ts focused on framing/auth/connection bookkeeping.
|
||||
import {
|
||||
ZodError,
|
||||
InvalidArgumentError,
|
||||
buildRegistry,
|
||||
formatZodError,
|
||||
isStreamingMethod,
|
||||
type RpcAnyMethod,
|
||||
type RpcEnvelopeMeta,
|
||||
type PairingRpcContext,
|
||||
type RpcRegistry,
|
||||
type RpcRequest,
|
||||
type RpcResponse
|
||||
} from './core'
|
||||
|
||||
import type { TerminalStreamFrame } from '../../../shared/terminal-stream-protocol'
|
||||
import type { FeatureInteractionId } from '../../../shared/feature-interactions'
|
||||
import {
|
||||
computerErrorData,
|
||||
errorResponse,
|
||||
mapBrowserError,
|
||||
mapEmulatorError,
|
||||
mapRuntimeError,
|
||||
successResponse
|
||||
} from './errors'
|
||||
import { errorResponse, successResponse } from './errors'
|
||||
import { ALL_RPC_METHODS } from './methods'
|
||||
import { emulatorProbe, emulatorProbeError } from '../../emulator/emulator-probe'
|
||||
import type { OrcaRuntimeService } from '../orca-runtime'
|
||||
import type { RuntimeCapability } from '../../../shared/protocol-version'
|
||||
import {
|
||||
OrchestrationMutationExecutor,
|
||||
authenticatedCallerFingerprint,
|
||||
getOrchestrationMutationExecutor,
|
||||
type OrchestrationMutationExecutor,
|
||||
type DurableMutationInvocation
|
||||
} from './orchestration-mutation-executor'
|
||||
import { orchestrationMigrationFence } from './orchestration-contract-fence'
|
||||
import { getRuntimeFeatureInteractionId } from './runtime-feature-interaction'
|
||||
import { recordRuntimeFeatureInteraction } from './runtime-feature-interaction'
|
||||
import { OrchestrationLegacyCompatibility } from './orchestration-legacy-compatibility'
|
||||
import type { RpcDispatchStreamingOptions } from './dispatcher-stream-options'
|
||||
import { invalidArgumentResponse, mapDispatcherError } from './dispatcher-error-response'
|
||||
|
||||
export type DispatcherOptions = {
|
||||
runtime: OrcaRuntimeService
|
||||
methods?: readonly RpcAnyMethod[]
|
||||
}
|
||||
export type DispatcherOptions = { runtime: OrcaRuntimeService; methods?: readonly RpcAnyMethod[] }
|
||||
|
||||
export class RpcDispatcher {
|
||||
private readonly runtime: OrcaRuntimeService
|
||||
private readonly registry: RpcRegistry
|
||||
private readonly orchestrationMutations: OrchestrationMutationExecutor
|
||||
private readonly legacyOrchestration: OrchestrationLegacyCompatibility
|
||||
|
||||
constructor({ runtime, methods = ALL_RPC_METHODS }: DispatcherOptions) {
|
||||
this.runtime = runtime
|
||||
this.registry = buildRegistry(methods)
|
||||
this.orchestrationMutations = new OrchestrationMutationExecutor(runtime)
|
||||
this.orchestrationMutations = getOrchestrationMutationExecutor(runtime)
|
||||
this.legacyOrchestration = new OrchestrationLegacyCompatibility(runtime)
|
||||
}
|
||||
|
||||
async dispatch(request: RpcRequest, options?: { signal?: AbortSignal }): Promise<RpcResponse> {
|
||||
@@ -76,9 +63,6 @@ export class RpcDispatcher {
|
||||
return parsedParams.error
|
||||
}
|
||||
|
||||
// Why: streaming methods are not supported over one-shot transports like
|
||||
// Unix sockets. They require a reply function that can be called multiple
|
||||
// times, which is only available via dispatchStreaming.
|
||||
if (isStreamingMethod(method)) {
|
||||
return errorResponse(
|
||||
request.id,
|
||||
@@ -88,29 +72,60 @@ export class RpcDispatcher {
|
||||
)
|
||||
}
|
||||
|
||||
const isEmulator = request.method.startsWith('emulator.')
|
||||
if (isEmulator) {
|
||||
if (request.method.startsWith('emulator.')) {
|
||||
emulatorProbe(`rpc ${request.method}`, request.params)
|
||||
}
|
||||
try {
|
||||
const invoke = (mutation?: DurableMutationInvocation) =>
|
||||
method.handler(parsedParams.value, {
|
||||
const compatibility = await this.legacyOrchestration.tryHandle(
|
||||
request,
|
||||
parsedParams.value,
|
||||
options?.signal
|
||||
)
|
||||
if (compatibility.handled) {
|
||||
return successResponse(request.id, meta, compatibility.result)
|
||||
}
|
||||
const effectiveParams = compatibility.params ?? parsedParams.value
|
||||
const legacyCoordinator = this.legacyOrchestration.createCoordinatorInvocation(
|
||||
request,
|
||||
compatibility.legacyCoordinatorAuthority
|
||||
)
|
||||
const invoke = (mutation?: DurableMutationInvocation) => {
|
||||
const legacyCoordinatorRunId = legacyCoordinator?.revalidate()
|
||||
return method.handler(effectiveParams, {
|
||||
runtime: this.runtime,
|
||||
signal: options?.signal,
|
||||
requestId: request.id,
|
||||
orchestrationCapability: request.orchestrationCapability,
|
||||
authenticatedCallerFingerprint: authenticatedCallerFingerprint(request),
|
||||
authenticatedCallerFingerprint:
|
||||
mutation?.identity.callerFingerprint ?? authenticatedCallerFingerprint(request),
|
||||
recordMutationReceipt: mutation?.recordReceipt,
|
||||
orchestrationMutation: mutation?.identity
|
||||
orchestrationMutation: mutation?.identity,
|
||||
legacyCoordinatorRunId,
|
||||
legacyCoordinatorAuthority: legacyCoordinator?.authority,
|
||||
revalidateLegacyCoordinator: legacyCoordinator?.revalidate,
|
||||
orchestrationCompatibilityCallerAuthority:
|
||||
compatibility.orchestrationCompatibilityCallerAuthority
|
||||
})
|
||||
const result = await this.orchestrationMutations.run(request, parsedParams.value, invoke)
|
||||
this.recordRuntimeFeatureInteraction(request.method, result, undefined, request.params)
|
||||
}
|
||||
const result = await this.orchestrationMutations.run(
|
||||
request,
|
||||
effectiveParams,
|
||||
invoke,
|
||||
legacyCoordinator?.mutationCallerFingerprint
|
||||
)
|
||||
recordRuntimeFeatureInteraction(
|
||||
this.runtime,
|
||||
request.method,
|
||||
result,
|
||||
undefined,
|
||||
request.params
|
||||
)
|
||||
return successResponse(request.id, meta, result)
|
||||
} catch (error) {
|
||||
if (isEmulator) {
|
||||
if (request.method.startsWith('emulator.')) {
|
||||
emulatorProbeError(`rpc ${request.method}`, error, { params: request.params })
|
||||
}
|
||||
return this.mapError(request, meta, error)
|
||||
return mapDispatcherError(request, meta, error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -120,20 +135,7 @@ export class RpcDispatcher {
|
||||
async dispatchStreaming(
|
||||
request: RpcRequest,
|
||||
reply: (response: string) => void,
|
||||
options?: {
|
||||
connectionId?: string
|
||||
signal?: AbortSignal
|
||||
clientId?: string
|
||||
pairedDeviceId?: string
|
||||
clientKind?: 'mobile' | 'runtime'
|
||||
clientCapabilities?: readonly RuntimeCapability[]
|
||||
pairing?: PairingRpcContext
|
||||
sendBinary?: (bytes: Uint8Array<ArrayBufferLike>) => boolean | void
|
||||
registerBinaryStreamHandler?: (
|
||||
streamId: number,
|
||||
handler: (frame: TerminalStreamFrame) => void
|
||||
) => () => void
|
||||
}
|
||||
options?: RpcDispatchStreamingOptions
|
||||
): Promise<void> {
|
||||
const meta = this.meta()
|
||||
const method = this.registry.get(request.method)
|
||||
@@ -160,8 +162,23 @@ export class RpcDispatcher {
|
||||
|
||||
if (!isStreamingMethod(method)) {
|
||||
try {
|
||||
const invoke = (mutation?: DurableMutationInvocation) =>
|
||||
method.handler(parsedParams.value, {
|
||||
const compatibility = await this.legacyOrchestration.tryHandle(
|
||||
request,
|
||||
parsedParams.value,
|
||||
options?.signal
|
||||
)
|
||||
if (compatibility.handled) {
|
||||
reply(JSON.stringify(successResponse(request.id, meta, compatibility.result)))
|
||||
return
|
||||
}
|
||||
const effectiveParams = compatibility.params ?? parsedParams.value
|
||||
const legacyCoordinator = this.legacyOrchestration.createCoordinatorInvocation(
|
||||
request,
|
||||
compatibility.legacyCoordinatorAuthority
|
||||
)
|
||||
const invoke = (mutation?: DurableMutationInvocation) => {
|
||||
const legacyCoordinatorRunId = legacyCoordinator?.revalidate()
|
||||
return method.handler(effectiveParams, {
|
||||
runtime: this.runtime,
|
||||
signal: options?.signal,
|
||||
requestId: request.id,
|
||||
@@ -171,25 +188,44 @@ export class RpcDispatcher {
|
||||
clientKind: options?.clientKind,
|
||||
clientCapabilities: options?.clientCapabilities,
|
||||
orchestrationCapability: request.orchestrationCapability,
|
||||
authenticatedCallerFingerprint: authenticatedCallerFingerprint(request),
|
||||
authenticatedCallerFingerprint:
|
||||
mutation?.identity.callerFingerprint ?? authenticatedCallerFingerprint(request),
|
||||
recordMutationReceipt: mutation?.recordReceipt,
|
||||
orchestrationMutation: mutation?.identity,
|
||||
pairing: options?.pairing,
|
||||
sendBinary: options?.sendBinary,
|
||||
registerBinaryStreamHandler: options?.registerBinaryStreamHandler
|
||||
registerBinaryStreamHandler: options?.registerBinaryStreamHandler,
|
||||
legacyCoordinatorRunId,
|
||||
legacyCoordinatorAuthority: legacyCoordinator?.authority,
|
||||
revalidateLegacyCoordinator: legacyCoordinator?.revalidate,
|
||||
orchestrationCompatibilityCallerAuthority:
|
||||
compatibility.orchestrationCompatibilityCallerAuthority
|
||||
})
|
||||
const result = await this.orchestrationMutations.run(request, parsedParams.value, invoke)
|
||||
this.recordRuntimeFeatureInteraction(request.method, result, undefined, request.params)
|
||||
}
|
||||
const result = await this.orchestrationMutations.run(
|
||||
request,
|
||||
effectiveParams,
|
||||
invoke,
|
||||
legacyCoordinator?.mutationCallerFingerprint
|
||||
)
|
||||
recordRuntimeFeatureInteraction(
|
||||
this.runtime,
|
||||
request.method,
|
||||
result,
|
||||
undefined,
|
||||
request.params
|
||||
)
|
||||
reply(JSON.stringify(successResponse(request.id, meta, result)))
|
||||
} catch (error) {
|
||||
reply(JSON.stringify(this.mapError(request, meta, error)))
|
||||
reply(JSON.stringify(mapDispatcherError(request, meta, error)))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const recordedStreamingFeatureInteractions = new Set<FeatureInteractionId>()
|
||||
const emit = (result: unknown): void => {
|
||||
this.recordRuntimeFeatureInteraction(
|
||||
recordRuntimeFeatureInteraction(
|
||||
this.runtime,
|
||||
request.method,
|
||||
result,
|
||||
recordedStreamingFeatureInteractions,
|
||||
@@ -212,20 +248,22 @@ export class RpcDispatcher {
|
||||
pairedDeviceId: options?.pairedDeviceId,
|
||||
clientKind: options?.clientKind,
|
||||
clientCapabilities: options?.clientCapabilities,
|
||||
orchestrationCapability: request.orchestrationCapability,
|
||||
pairing: options?.pairing,
|
||||
sendBinary: options?.sendBinary,
|
||||
registerBinaryStreamHandler: options?.registerBinaryStreamHandler
|
||||
},
|
||||
emit
|
||||
)
|
||||
this.recordRuntimeFeatureInteraction(
|
||||
recordRuntimeFeatureInteraction(
|
||||
this.runtime,
|
||||
request.method,
|
||||
result,
|
||||
recordedStreamingFeatureInteractions,
|
||||
request.params
|
||||
)
|
||||
} catch (error) {
|
||||
reply(JSON.stringify(this.mapError(request, meta, error)))
|
||||
reply(JSON.stringify(mapDispatcherError(request, meta, error)))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,69 +279,13 @@ export class RpcDispatcher {
|
||||
const result = method.params.safeParse(rawParams)
|
||||
if (!result.success) {
|
||||
return {
|
||||
error: this.invalidArgumentResponse(request, meta, formatZodError(result.error))
|
||||
error: invalidArgumentResponse(request, meta, formatZodError(result.error))
|
||||
}
|
||||
}
|
||||
return { value: result.data }
|
||||
}
|
||||
|
||||
private mapError(request: RpcRequest, meta: RpcEnvelopeMeta, error: unknown): RpcResponse {
|
||||
if (error instanceof ZodError) {
|
||||
return this.invalidArgumentResponse(request, meta, formatZodError(error))
|
||||
}
|
||||
if (error instanceof InvalidArgumentError) {
|
||||
return this.invalidArgumentResponse(request, meta, error.message)
|
||||
}
|
||||
|
||||
// Why: browser methods throw BrowserError with a structured `code`;
|
||||
// every other runtime error has a plain-message code. Routing by method
|
||||
// prefix keeps the mapping a single decision rather than a per-method
|
||||
// flag callers must remember to set.
|
||||
if (request.method.startsWith('browser.')) {
|
||||
return mapBrowserError(request.id, meta, error)
|
||||
}
|
||||
if (request.method.startsWith('emulator.')) {
|
||||
return mapEmulatorError(request.id, meta, error)
|
||||
}
|
||||
return mapRuntimeError(request.id, meta, error)
|
||||
}
|
||||
|
||||
private invalidArgumentResponse(
|
||||
request: RpcRequest,
|
||||
meta: RpcEnvelopeMeta,
|
||||
message: string
|
||||
): RpcResponse {
|
||||
return errorResponse(
|
||||
request.id,
|
||||
meta,
|
||||
'invalid_argument',
|
||||
message,
|
||||
request.method.startsWith('computer.') ? computerErrorData('invalid_argument') : undefined
|
||||
)
|
||||
}
|
||||
|
||||
private meta(): RpcEnvelopeMeta {
|
||||
return { runtimeId: this.runtime.getRuntimeId() }
|
||||
}
|
||||
|
||||
private recordRuntimeFeatureInteraction(
|
||||
method: string,
|
||||
result: unknown,
|
||||
alreadyRecorded?: Set<FeatureInteractionId>,
|
||||
rawParams?: unknown
|
||||
): void {
|
||||
const id = getRuntimeFeatureInteractionId(method, result, rawParams)
|
||||
if (!id) {
|
||||
return
|
||||
}
|
||||
if (alreadyRecorded?.has(id)) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
this.runtime.recordFeatureInteraction(id)
|
||||
alreadyRecorded?.add(id)
|
||||
} catch {
|
||||
// Best-effort education state must not break runtime tools.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,6 +88,7 @@ const STRUCTURED_RUNTIME_PASSTHROUGH_CODES: ReadonlySet<string> = new Set([
|
||||
'agent_unconfigured',
|
||||
'terminal_worktree_mismatch',
|
||||
'request_mismatch',
|
||||
'legacy_read_only',
|
||||
'orchestration_migration_required',
|
||||
'operation_unknown',
|
||||
'question_not_found',
|
||||
|
||||
@@ -265,7 +265,7 @@ describe('orchestration federation control mail', () => {
|
||||
})
|
||||
await expect(waiting).resolves.toMatchObject({
|
||||
ok: true,
|
||||
result: { count: 0, timedOut: true }
|
||||
result: { count: 0 }
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -224,6 +224,7 @@ describe('orchestration federation', () => {
|
||||
])
|
||||
)
|
||||
expect(workerDb.listTasks()).toHaveLength(0)
|
||||
expect(vi.mocked(workerRuntime.createManagedWorktree).mock.calls[0]?.[0].activate).toBe(false)
|
||||
expect(workerRuntime.sendTerminalAgentPrompt).toHaveBeenCalledWith(
|
||||
'term_windows_worker',
|
||||
expect.stringContaining(`Your task ID is: ${task.id}`)
|
||||
|
||||
@@ -103,8 +103,12 @@ export const ORCHESTRATION_GATE_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.gateCreate',
|
||||
params: GateCreateParams,
|
||||
handler: (params, { runtime }) => {
|
||||
handler: (params, { runtime, legacyCoordinatorRunId }) => {
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const task = db.getTask(params.task)
|
||||
if (legacyCoordinatorRunId && task?.run_id !== legacyCoordinatorRunId) {
|
||||
throw new Error(`Task not found: ${params.task}`)
|
||||
}
|
||||
let options: string[] | undefined
|
||||
if (params.options) {
|
||||
try {
|
||||
@@ -129,8 +133,12 @@ export const ORCHESTRATION_GATE_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.gateResolve',
|
||||
params: GateResolveParams,
|
||||
handler: (params, { runtime }) => {
|
||||
handler: (params, { runtime, legacyCoordinatorRunId }) => {
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const existing = db.getGate(params.id)
|
||||
if (legacyCoordinatorRunId && existing?.run_id !== legacyCoordinatorRunId) {
|
||||
throw new Error(`Gate not found: ${params.id}`)
|
||||
}
|
||||
const gate = db.resolveGate(params.id, params.resolution)
|
||||
if (!gate) {
|
||||
throw new Error(`Gate not found: ${params.id}`)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { z } from 'zod'
|
||||
import { defineMethod, type RpcMethod } from '../core'
|
||||
import { OptionalString, requiredString } from '../schemas'
|
||||
import { OptionalBoolean, OptionalString, requiredString } from '../schemas'
|
||||
import type { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { OrchestrationError } from '../../orchestration/orchestration-error'
|
||||
|
||||
@@ -11,7 +11,8 @@ const RunCreateParams = z.object({
|
||||
|
||||
const RunUseParams = z.object({
|
||||
id: requiredString('Missing --id'),
|
||||
from: requiredString('Missing coordinator terminal')
|
||||
from: requiredString('Missing coordinator terminal'),
|
||||
takeoverLegacy: OptionalBoolean
|
||||
})
|
||||
|
||||
const RunCurrentParams = z.object({ from: requiredString('Missing coordinator terminal') })
|
||||
@@ -51,14 +52,33 @@ export const ORCHESTRATION_RUN_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.runUse',
|
||||
params: RunUseParams,
|
||||
handler: (params, { runtime }) => {
|
||||
handler: (
|
||||
params,
|
||||
{
|
||||
runtime,
|
||||
legacyCoordinatorAuthority,
|
||||
orchestrationCompatibilityCallerAuthority: callerAuthority
|
||||
}
|
||||
) => {
|
||||
const paneKey = requireCallerPane(runtime, params.from)
|
||||
if (
|
||||
params.takeoverLegacy &&
|
||||
(callerAuthority?.terminalHandle !== params.from || callerAuthority.paneKey !== paneKey)
|
||||
) {
|
||||
throw new OrchestrationError(
|
||||
'legacy_read_only',
|
||||
'Legacy takeover must be invoked by the live coordinator agent terminal it will bind. No effects were applied.',
|
||||
{ effectsApplied: false }
|
||||
)
|
||||
}
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const priorRun = db.getCurrentRunForPane(paneKey)
|
||||
const run = db.bindRun({
|
||||
runId: params.id,
|
||||
coordinatorHandle: params.from,
|
||||
coordinatorPaneKey: paneKey
|
||||
coordinatorPaneKey: paneKey,
|
||||
takeoverLegacy: params.takeoverLegacy,
|
||||
legacyCoordinatorAuthority
|
||||
})
|
||||
if (!run) {
|
||||
throw new OrchestrationError(
|
||||
|
||||
@@ -36,6 +36,21 @@ export type WorkerSetupReceipt = {
|
||||
| 'not_applicable'
|
||||
}
|
||||
|
||||
export function requireWorkerAuthority(runtime: OrcaRuntimeService, terminalHandle: string) {
|
||||
const authority = runtime.getOrchestrationDispatchAuthority(terminalHandle)
|
||||
const paneKey = authority?.paneKey ?? runtime.getTerminalPaneKey(terminalHandle)
|
||||
const processIncarnation =
|
||||
authority?.processIncarnation ?? runtime.getTerminalProcessIncarnation(terminalHandle)
|
||||
if (!paneKey || !processIncarnation) {
|
||||
throw new Error('stable_pane_required')
|
||||
}
|
||||
return {
|
||||
paneKey,
|
||||
processIncarnation,
|
||||
...(authority?.launchTokenHash ? { launchTokenHash: authority.launchTokenHash } : {})
|
||||
}
|
||||
}
|
||||
|
||||
export async function createExistingWorktreeWorkerTerminal(args: {
|
||||
runtime: OrcaRuntimeService
|
||||
worktreeId: string
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
createExistingWorktreeWorkerTerminal,
|
||||
createWorkerWorktree,
|
||||
monitorWorkerSetup,
|
||||
requireWorkerAuthority,
|
||||
type WorkerEffect,
|
||||
type WorkerSetupReceipt
|
||||
} from './orchestration-worker-topology'
|
||||
@@ -235,16 +236,11 @@ export const ORCHESTRATION_WORKER_START_METHODS: RpcMethod[] = [
|
||||
: `Agent did not become ready (${wait.status}).`
|
||||
)
|
||||
}
|
||||
const paneKey = runtime.getTerminalPaneKey(terminalHandle)
|
||||
const processIncarnation = runtime.getTerminalProcessIncarnation(terminalHandle)
|
||||
if (!paneKey || !processIncarnation) {
|
||||
throw new Error('stable_pane_required')
|
||||
}
|
||||
const terminalAuthority = requireWorkerAuthority(runtime, terminalHandle)
|
||||
const capability = db.prepareStartingWorkerAuthority({
|
||||
dispatchId: started.dispatch.id,
|
||||
handle: terminalHandle,
|
||||
paneKey,
|
||||
processIncarnation,
|
||||
...terminalAuthority,
|
||||
worktreeId: resolvedWorktree.id,
|
||||
effects,
|
||||
setupState: setupReceipt.state
|
||||
|
||||
@@ -1918,6 +1918,30 @@ describe('orchestration RPC methods', () => {
|
||||
expect(db.getDispatchContextById(result.dispatch.id)?.assignee_pane_key).toBe('tab_w:leaf_w')
|
||||
})
|
||||
|
||||
it('commits the target process launch token on a manual dispatch', async () => {
|
||||
setup()
|
||||
vi.spyOn(runtime, 'getOrchestrationDispatchAuthority').mockReturnValue({
|
||||
runtimeId: runtime.getRuntimeId(),
|
||||
terminalHandle: 'term_a',
|
||||
ptyId: 'pty_a',
|
||||
worktreeId: 'repo::worktree',
|
||||
paneKey: 'tab_w:leaf_w',
|
||||
processIncarnation: 'runtime_test:term_a:1',
|
||||
launchTokenHash: 'launch-token-hash',
|
||||
hostScope: { kind: 'local', hostId: 'local' }
|
||||
})
|
||||
const task = db.createTask({ spec: 'work' })
|
||||
|
||||
const result = (await call('orchestration.dispatch', {
|
||||
task: task.id,
|
||||
to: 'term_a'
|
||||
})) as { dispatch: { id: string } }
|
||||
|
||||
expect(db.getDispatchContextById(result.dispatch.id)?.launch_token_hash).toBe(
|
||||
'launch-token-hash'
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects dispatch for a pending task', async () => {
|
||||
setup()
|
||||
const parent = db.createTask({ spec: 'parent' })
|
||||
@@ -2162,6 +2186,32 @@ describe('orchestration RPC methods', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('commits the launched worker token with its durable authority', async () => {
|
||||
setup()
|
||||
mockCurrentWorkerStart()
|
||||
vi.spyOn(runtime, 'getOrchestrationDispatchAuthority').mockReturnValue({
|
||||
runtimeId: runtime.getRuntimeId(),
|
||||
terminalHandle: 'term_worker',
|
||||
ptyId: 'pty_worker',
|
||||
worktreeId: 'repo::worktree',
|
||||
paneKey: 'tab_worker:leaf_worker',
|
||||
processIncarnation: 'runtime_test:term_worker:1',
|
||||
launchTokenHash: 'worker-launch-token-hash',
|
||||
hostScope: { kind: 'local', hostId: 'local' }
|
||||
})
|
||||
const task = db.createTask({ spec: 'persist worker identity' })
|
||||
|
||||
const result = (await call('orchestration.workerStart', {
|
||||
task: task.id,
|
||||
from: 'term_coord',
|
||||
agent: 'codex'
|
||||
})) as { dispatchId: string }
|
||||
|
||||
expect(db.getDispatchContextById(result.dispatchId)?.launch_token_hash).toBe(
|
||||
'worker-launch-token-hash'
|
||||
)
|
||||
})
|
||||
|
||||
it('surfaces a worker terminal reveal failure without discarding the live worker', async () => {
|
||||
setup()
|
||||
mockCurrentWorkerStart()
|
||||
|
||||
@@ -2,7 +2,12 @@
|
||||
import { z } from 'zod'
|
||||
import { defineMethod, type RpcMethod } from '../core'
|
||||
import { OptionalFiniteNumber, OptionalString, OptionalBoolean, requiredString } from '../schemas'
|
||||
import type { MessageType, MessagePriority, TaskStatus } from '../../orchestration/db'
|
||||
import {
|
||||
LEGACY_CONTRACT_VERSION,
|
||||
type MessageType,
|
||||
type MessagePriority,
|
||||
type TaskStatus
|
||||
} from '../../orchestration/db'
|
||||
import { MESSAGE_TYPES } from '../../orchestration/types'
|
||||
import { buildDispatchPreamble } from '../../orchestration/preamble'
|
||||
import { formatMessageBanner } from '../../orchestration/formatter'
|
||||
@@ -51,6 +56,10 @@ function parseRemoteWorkerPayload(payload: string | undefined): Record<string, u
|
||||
}
|
||||
}
|
||||
|
||||
function isWorkerReportOutcome(value: unknown): value is 'succeeded' | 'failed' {
|
||||
return value === 'succeeded' || value === 'failed'
|
||||
}
|
||||
|
||||
const SendParams = z
|
||||
.object({
|
||||
to: OptionalString,
|
||||
@@ -107,6 +116,9 @@ const CheckParams = z
|
||||
// Why: one-release RPC compatibility only; the public CLI uses --format because no terminal input is injected.
|
||||
inject: OptionalBoolean,
|
||||
ack: OptionalString,
|
||||
compatibilityAck: OptionalString,
|
||||
compatibilityQuestionAck: OptionalString,
|
||||
compatibilityCliCommand: z.enum(['orca', 'orca-ide', 'orca-dev']).optional(),
|
||||
run: OptionalString,
|
||||
wait: OptionalBoolean,
|
||||
timeoutMs: OptionalFiniteNumber
|
||||
@@ -205,7 +217,9 @@ const AskParams = z
|
||||
options: OptionalString,
|
||||
timeoutMs: OptionalFiniteNumber,
|
||||
from: OptionalString,
|
||||
run: OptionalString
|
||||
run: OptionalString,
|
||||
compatibilityCliCommand: z.enum(['orca', 'orca-ide', 'orca-dev']).optional(),
|
||||
compatibilityWindowsCommand: z.enum(['orca', 'orca-ide']).optional()
|
||||
})
|
||||
.superRefine((params, ctx) => {
|
||||
if ((params.question ? 1 : 0) + (params.resume ? 1 : 0) !== 1) {
|
||||
@@ -241,6 +255,7 @@ function resolveRunScope(
|
||||
callerTerminalHandle?: string
|
||||
callerPaneKey?: string
|
||||
requireCurrentConsumer: boolean
|
||||
legacyCoordinatorRunId?: string
|
||||
}
|
||||
): RunRow {
|
||||
const db = runtime.getOrchestrationDb()
|
||||
@@ -252,6 +267,9 @@ function resolveRunScope(
|
||||
if (!params.requireCurrentConsumer && explicit) {
|
||||
return explicit
|
||||
}
|
||||
if (explicit && params.legacyCoordinatorRunId === explicit.id) {
|
||||
return explicit
|
||||
}
|
||||
if (!params.callerTerminalHandle) {
|
||||
throw new OrchestrationError(
|
||||
'run_required',
|
||||
@@ -366,6 +384,49 @@ function resolveMessageRun(
|
||||
return { run, dispatchId: dispatch?.id ?? dispatchId }
|
||||
}
|
||||
|
||||
function legacyWorkerDeliveryContract(
|
||||
runtime: OrcaRuntimeService,
|
||||
runId: string | undefined,
|
||||
recipient: string
|
||||
): 'legacy_direct' | undefined {
|
||||
if (!runId) {
|
||||
return undefined
|
||||
}
|
||||
if (!recipient.startsWith('dispatch:')) {
|
||||
return runtime
|
||||
.getOrchestrationDb()
|
||||
.resolveLegacyWorkerCandidate({ runId, terminalHandle: recipient })
|
||||
? 'legacy_direct'
|
||||
: undefined
|
||||
}
|
||||
const dispatch = runtime
|
||||
.getOrchestrationDb()
|
||||
.getDispatchContextById(recipient.slice('dispatch:'.length))
|
||||
return dispatch?.run_id === runId &&
|
||||
dispatch.contract_version === LEGACY_CONTRACT_VERSION &&
|
||||
(dispatch.status === 'pending' || dispatch.status === 'dispatched')
|
||||
? 'legacy_direct'
|
||||
: undefined
|
||||
}
|
||||
|
||||
function interruptedAcknowledgedCheck(
|
||||
runId: string,
|
||||
acknowledged: string,
|
||||
reason: 'consumer_fenced' | 'outcome_unknown' | 'waiter_exists'
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
runId,
|
||||
deliveryId: null,
|
||||
messages: [],
|
||||
count: 0,
|
||||
acknowledged,
|
||||
timedOut: false,
|
||||
cancelled: false,
|
||||
connectionLost: false,
|
||||
waitInterrupted: reason
|
||||
}
|
||||
}
|
||||
|
||||
function rejectFederatedExplicitTarget(params: { to?: string; run?: string }): void {
|
||||
if (params.to || params.run) {
|
||||
throw new OrchestrationError(
|
||||
@@ -382,7 +443,10 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.send',
|
||||
params: SendParams,
|
||||
handler: async (params, { runtime, orchestrationCapability }) => {
|
||||
handler: async (
|
||||
params,
|
||||
{ runtime, orchestrationCapability, legacyCoordinatorRunId, revalidateLegacyCoordinator }
|
||||
) => {
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const from = params.from ?? 'unknown'
|
||||
// Why: caller-supplied pane fields are only compatibility metadata; lifecycle authority uses the runtime-observed pane plus capability.
|
||||
@@ -463,6 +527,15 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
runId: params.run,
|
||||
payload: params.payload
|
||||
})
|
||||
if (
|
||||
params.type === 'worker_done' &&
|
||||
!isWorkerReportOutcome(parseRemoteWorkerPayload(params.payload).outcome)
|
||||
) {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
'worker_done requires outcome=succeeded|failed for a current Dispatch.'
|
||||
)
|
||||
}
|
||||
if (params.to?.startsWith('task:')) {
|
||||
throw new OrchestrationError(
|
||||
'invalid_argument',
|
||||
@@ -514,6 +587,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
'Coordinator-to-worker control mail cannot report worker lifecycle.'
|
||||
)
|
||||
}
|
||||
revalidateLegacyCoordinator?.()
|
||||
const relay = db.enqueueFederationRelay({
|
||||
dispatchId,
|
||||
direction: 'to_worker',
|
||||
@@ -540,6 +614,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
}
|
||||
}
|
||||
// Point-to-point — existing single-recipient behavior
|
||||
revalidateLegacyCoordinator?.()
|
||||
const msg = db.insertMessage({
|
||||
from,
|
||||
to,
|
||||
@@ -550,7 +625,12 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
threadId: params.threadId,
|
||||
payload: params.payload,
|
||||
senderPaneKey,
|
||||
runId: routing.run?.id
|
||||
runId: routing.run?.id,
|
||||
deliveryContract: legacyWorkerDeliveryContract(
|
||||
runtime,
|
||||
routing.run?.id ?? legacyCoordinatorRunId,
|
||||
to
|
||||
)
|
||||
})
|
||||
const dispatch = routing.dispatchId
|
||||
? db.getDispatchContextById(routing.dispatchId)
|
||||
@@ -607,6 +687,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
throw new Error(`No recipients resolved for group address: ${to}`)
|
||||
}
|
||||
|
||||
revalidateLegacyCoordinator?.()
|
||||
const threadId = params.threadId ?? `thread_${Date.now()}`
|
||||
const messages = handles.map((handle) =>
|
||||
db.insertMessage({
|
||||
@@ -619,7 +700,12 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
threadId,
|
||||
payload: params.payload,
|
||||
senderPaneKey,
|
||||
runId: routing.run?.id
|
||||
runId: routing.run?.id,
|
||||
deliveryContract: legacyWorkerDeliveryContract(
|
||||
runtime,
|
||||
routing.run?.id ?? legacyCoordinatorRunId,
|
||||
handle
|
||||
)
|
||||
})
|
||||
)
|
||||
for (const message of messages) {
|
||||
@@ -633,7 +719,16 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.check',
|
||||
params: CheckParams,
|
||||
handler: async (params, { runtime, signal }) => {
|
||||
handler: async (
|
||||
params,
|
||||
{
|
||||
runtime,
|
||||
signal,
|
||||
legacyCoordinatorRunId,
|
||||
revalidateLegacyCoordinator,
|
||||
recordMutationReceipt
|
||||
}
|
||||
) => {
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const handle = params.terminal ?? 'unknown'
|
||||
const typeFilter = parseMessageTypes(params.types)
|
||||
@@ -646,7 +741,8 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
runId: params.run,
|
||||
callerTerminalHandle: handle,
|
||||
callerPaneKey: paneKey ?? undefined,
|
||||
requireCurrentConsumer: true
|
||||
requireCurrentConsumer: true,
|
||||
legacyCoordinatorRunId
|
||||
})
|
||||
const generation = run.consumer_generation
|
||||
const address = `run:${run.id}`
|
||||
@@ -659,6 +755,11 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
deliveryId: params.ack
|
||||
})
|
||||
: undefined
|
||||
if (acknowledged) {
|
||||
recordMutationReceipt?.(
|
||||
interruptedAcknowledgedCheck(run.id, acknowledged.delivery.id, 'outcome_unknown')
|
||||
)
|
||||
}
|
||||
if (params.peek || params.all || params.unread === false) {
|
||||
const history = db.getRunMailboxHistory(run.id, 100, typeFilter)
|
||||
const messages =
|
||||
@@ -722,14 +823,28 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
signal,
|
||||
exclusive: true
|
||||
})
|
||||
try {
|
||||
revalidateLegacyCoordinator?.()
|
||||
} catch (error) {
|
||||
if (!acknowledged) {
|
||||
throw error
|
||||
}
|
||||
return interruptedAcknowledgedCheck(run.id, acknowledged.delivery.id, 'consumer_fenced')
|
||||
}
|
||||
const latestRun = db.getRun(run.id)
|
||||
if (!latestRun || latestRun.consumer_generation !== generation) {
|
||||
if (acknowledged) {
|
||||
return interruptedAcknowledgedCheck(run.id, acknowledged.delivery.id, 'consumer_fenced')
|
||||
}
|
||||
throw new OrchestrationError(
|
||||
'consumer_fenced',
|
||||
'This mailbox consumer was replaced while waiting.'
|
||||
)
|
||||
}
|
||||
if (waitResult === 'waiter_exists') {
|
||||
if (acknowledged) {
|
||||
return interruptedAcknowledgedCheck(run.id, acknowledged.delivery.id, 'waiter_exists')
|
||||
}
|
||||
throw new OrchestrationError(
|
||||
'waiter_exists',
|
||||
`Run ${run.id} already has an active actionable waiter.`
|
||||
@@ -911,13 +1026,28 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.reply',
|
||||
params: ReplyParams,
|
||||
handler: async (params, { runtime }) => {
|
||||
handler: async (params, { runtime, legacyCoordinatorRunId }) => {
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const original = db.getMessageById(params.id)
|
||||
if (!original) {
|
||||
throw new Error(`Message not found: ${params.id}`)
|
||||
}
|
||||
if (original.run_id === ORCHESTRATION_LEGACY_RUN_ID) {
|
||||
if (
|
||||
legacyCoordinatorRunId &&
|
||||
(original.run_id !== legacyCoordinatorRunId ||
|
||||
(params.run !== undefined && params.run !== legacyCoordinatorRunId))
|
||||
) {
|
||||
throw new OrchestrationError(
|
||||
'request_mismatch',
|
||||
`Message ${params.id} does not belong to this adopted Run.`,
|
||||
{ effectsApplied: false }
|
||||
)
|
||||
}
|
||||
if (
|
||||
original.run_id === ORCHESTRATION_LEGACY_RUN_ID ||
|
||||
original.delivery_contract === 'legacy_direct' ||
|
||||
original.delivery_contract === 'audit_only'
|
||||
) {
|
||||
throw new OrchestrationError(
|
||||
'legacy_read_only',
|
||||
'Legacy orchestration messages are inspect-only; no reply was applied.',
|
||||
@@ -930,7 +1060,8 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
const run = resolveRunScope(runtime, {
|
||||
runId: params.run ?? question.run_id,
|
||||
callerTerminalHandle: params.from,
|
||||
requireCurrentConsumer: true
|
||||
requireCurrentConsumer: true,
|
||||
legacyCoordinatorRunId
|
||||
})
|
||||
const answered = db.answerQuestion({
|
||||
messageId: question.message_id,
|
||||
@@ -993,7 +1124,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.taskCreate',
|
||||
params: TaskCreateParams,
|
||||
handler: (params, { runtime }) => {
|
||||
handler: (params, { runtime, legacyCoordinatorRunId }) => {
|
||||
const db = runtime.getOrchestrationDb()
|
||||
let deps: string[] | undefined
|
||||
if (params.deps) {
|
||||
@@ -1017,7 +1148,8 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
runId: resolveRunScope(runtime, {
|
||||
runId: params.run,
|
||||
callerTerminalHandle: params.callerTerminalHandle,
|
||||
requireCurrentConsumer: true
|
||||
requireCurrentConsumer: true,
|
||||
legacyCoordinatorRunId
|
||||
}).id
|
||||
})
|
||||
return { task }
|
||||
@@ -1027,7 +1159,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.taskList',
|
||||
params: TaskListParams,
|
||||
handler: (params, { runtime }) => {
|
||||
handler: (params, { runtime, legacyCoordinatorRunId }) => {
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const explicitRun = params.run ? db.getRun(params.run) : undefined
|
||||
const run =
|
||||
@@ -1036,7 +1168,8 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
: resolveRunScope(runtime, {
|
||||
runId: params.run,
|
||||
callerTerminalHandle: params.callerTerminalHandle,
|
||||
requireCurrentConsumer: params.run === undefined
|
||||
requireCurrentConsumer: params.run === undefined,
|
||||
legacyCoordinatorRunId
|
||||
})
|
||||
// Why: listTasksWithDispatch adds assignee_handle + dispatch_id (NULL for non-dispatched), so legacy-shape consumers are unaffected.
|
||||
const joined = db.listTasksWithDispatch({
|
||||
@@ -1063,12 +1196,13 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.taskUpdate',
|
||||
params: TaskUpdateParams,
|
||||
handler: (params, { runtime }) => {
|
||||
handler: (params, { runtime, legacyCoordinatorRunId }) => {
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const run = resolveRunScope(runtime, {
|
||||
runId: params.run,
|
||||
callerTerminalHandle: params.callerTerminalHandle,
|
||||
requireCurrentConsumer: true
|
||||
requireCurrentConsumer: true,
|
||||
legacyCoordinatorRunId
|
||||
})
|
||||
const existing = db.getTask(params.id)
|
||||
if (!existing || existing.run_id !== run.id) {
|
||||
@@ -1088,7 +1222,7 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
defineMethod({
|
||||
name: 'orchestration.dispatch',
|
||||
params: DispatchParams,
|
||||
handler: async (params, { runtime }) => {
|
||||
handler: async (params, { runtime, legacyCoordinatorRunId, revalidateLegacyCoordinator }) => {
|
||||
const db = runtime.getOrchestrationDb()
|
||||
const task = db.getTask(params.task)
|
||||
if (!task) {
|
||||
@@ -1097,7 +1231,8 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
const run = resolveRunScope(runtime, {
|
||||
runId: params.run,
|
||||
callerTerminalHandle: params.from,
|
||||
requireCurrentConsumer: true
|
||||
requireCurrentConsumer: true,
|
||||
legacyCoordinatorRunId
|
||||
})
|
||||
if (task.run_id !== run.id) {
|
||||
throw new OrchestrationError(
|
||||
@@ -1143,8 +1278,13 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
}
|
||||
}
|
||||
|
||||
const assigneePaneKey = runtime.getTerminalPaneKey(to) ?? undefined
|
||||
const processIncarnation = runtime.getTerminalProcessIncarnation(to) ?? undefined
|
||||
const dispatchAuthority = runtime.getOrchestrationDispatchAuthority(to)
|
||||
const assigneePaneKey =
|
||||
dispatchAuthority?.paneKey ?? runtime.getTerminalPaneKey(to) ?? undefined
|
||||
const processIncarnation =
|
||||
dispatchAuthority?.processIncarnation ??
|
||||
runtime.getTerminalProcessIncarnation(to) ??
|
||||
undefined
|
||||
if (params.inject && (!assigneePaneKey || !processIncarnation)) {
|
||||
throw new OrchestrationError(
|
||||
'stable_pane_required',
|
||||
@@ -1152,7 +1292,13 @@ export const ORCHESTRATION_METHODS: RpcMethod[] = [
|
||||
)
|
||||
}
|
||||
|
||||
const ctx = db.createDispatchContext(params.task, to, assigneePaneKey)
|
||||
revalidateLegacyCoordinator?.()
|
||||
const ctx = db.createDispatchContext(
|
||||
params.task,
|
||||
to,
|
||||
assigneePaneKey,
|
||||
dispatchAuthority?.launchTokenHash ?? undefined
|
||||
)
|
||||
const dispatchCapability = params.inject
|
||||
? db.mintDispatchCapability({
|
||||
dispatchId: ctx.id,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { WorktreeActivate, WorktreeCreate } from './worktree-schemas'
|
||||
import { WorktreeActivate, WorktreeCreate, WorktreeSet } from './worktree-schemas'
|
||||
|
||||
describe('worktree RPC schemas', () => {
|
||||
it('validates additive navigation intent', () => {
|
||||
@@ -31,4 +31,27 @@ describe('worktree RPC schemas', () => {
|
||||
|
||||
expect(parsed.success).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps a blanked display name on remote hosts instead of dropping the clear', () => {
|
||||
// Blanking sends displayName:'' meaning "fall back to the branch/folder name".
|
||||
// Coercing it to undefined made updateManagedWorktreeMeta's omitUndefinedProperties
|
||||
// drop the key, so an SSH/paired-web rename-to-blank silently kept the old name.
|
||||
const parsed = WorktreeSet.parse({ worktree: 'id:r1::/repos/wt', displayName: '' })
|
||||
|
||||
expect(parsed.displayName).toBe('')
|
||||
expect(Object.prototype.hasOwnProperty.call(parsed, 'displayName')).toBe(true)
|
||||
})
|
||||
|
||||
it('still omits a display name that was never sent', () => {
|
||||
const parsed = WorktreeSet.parse({ worktree: 'id:r1::/repos/wt', comment: 'note' })
|
||||
|
||||
expect(parsed.displayName).toBeUndefined()
|
||||
expect(Object.prototype.hasOwnProperty.call(parsed, 'displayName')).toBe(false)
|
||||
})
|
||||
|
||||
it('ignores a non-string display name rather than persisting it', () => {
|
||||
const parsed = WorktreeSet.parse({ worktree: 'id:r1::/repos/wt', displayName: 42 })
|
||||
|
||||
expect(parsed.displayName).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -189,7 +189,10 @@ export const WorktreePrefetchCreateBase = z.object({
|
||||
})
|
||||
|
||||
export const WorktreeSet = WorktreeSelector.extend({
|
||||
displayName: OptionalString,
|
||||
// Why: '' is the blanking contract — "fall back to the branch/folder name".
|
||||
// OptionalString coerced it to undefined, so on remote/SSH hosts clearing the
|
||||
// name was dropped here and the old name came back on the next refresh.
|
||||
displayName: OptionalPlainString,
|
||||
// Why: empty comments are meaningful metadata updates, so use the plain
|
||||
// string parser instead of OptionalString's empty-as-undefined behavior.
|
||||
comment: OptionalPlainString,
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user