diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index c2b597fafbf..2ab1ed44421 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -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 diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 03405d4fd13..f34ac31839f 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -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", diff --git a/config/scripts/orchestration-skill-guidance.test.mjs b/config/scripts/orchestration-skill-guidance.test.mjs index 74d14a9a9a1..849fe784b46 100644 --- a/config/scripts/orchestration-skill-guidance.test.mjs +++ b/config/scripts/orchestration-skill-guidance.test.mjs @@ -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 ') + expect(migration).toContain('task-list --run ') + expect(migration).toContain('Legacy inspection remains available without consuming mail') + expect(migration).toContain('run-use --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', () => { diff --git a/config/scripts/run-ssh-docker-terminal-parking-e2e.mjs b/config/scripts/run-ssh-docker-terminal-parking-e2e.mjs new file mode 100644 index 00000000000..8d4183b4515 --- /dev/null +++ b/config/scripts/run-ssh-docker-terminal-parking-e2e.mjs @@ -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) diff --git a/docs/reference/plans/2026-07-27-sta-2694-alt-screen-reveal-artifacts-handoff.md b/docs/reference/plans/2026-07-27-sta-2694-alt-screen-reveal-artifacts-handoff.md deleted file mode 100644 index 5b68ea02916..00000000000 --- a/docs/reference/plans/2026-07-27-sta-2694-alt-screen-reveal-artifacts-handoff.md +++ /dev/null @@ -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 `/terminal-render-desync-evidence//`, 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` diff --git a/docs/reference/plans/2026-07-28-orchestration-seamless-update-migration.md b/docs/reference/plans/2026-07-28-orchestration-seamless-update-migration.md new file mode 100644 index 00000000000..18ceea5bff2 --- /dev/null +++ b/docs/reference/plans/2026-07-28-orchestration-seamless-update-migration.md @@ -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. diff --git a/mobile/package.json b/mobile/package.json index 41ddf3f2f3b..1041b422a34 100644 --- a/mobile/package.json +++ b/mobile/package.json @@ -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", diff --git a/mobile/pnpm-lock.yaml b/mobile/pnpm-lock.yaml index 6ca7573778f..9788413f925 100644 --- a/mobile/pnpm-lock.yaml +++ b/mobile/pnpm-lock.yaml @@ -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 diff --git a/mobile/src/components/BottomDrawer.tsx b/mobile/src/components/BottomDrawer.tsx index 030e38bcd3f..9d27c2c0c4e 100644 --- a/mobile/src/components/BottomDrawer.tsx +++ b/mobile/src/components/BottomDrawer.tsx @@ -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({ { - setMounted(false) - onAfterClose?.() - }} + onHidden={handleHidden} dragContentToDismiss={dragContentToDismiss} contentScrollable={contentScrollable} fillAvailable={fillAvailable} diff --git a/mobile/src/components/bottom-drawer-close-lifecycle.test.ts b/mobile/src/components/bottom-drawer-close-lifecycle.test.ts new file mode 100644 index 00000000000..b4362412db7 --- /dev/null +++ b/mobile/src/components/bottom-drawer-close-lifecycle.test.ts @@ -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() + }) +}) diff --git a/mobile/src/terminal/terminal-webview-html.ts b/mobile/src/terminal/terminal-webview-html.ts index 767b2cc6b6c..11579955926 100644 --- a/mobile/src/terminal/terminal-webview-html.ts +++ b/mobile/src/terminal/terminal-webview-html.ts @@ -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) { diff --git a/mobile/src/terminal/terminal-webview-wheel-scroll-injected.ts b/mobile/src/terminal/terminal-webview-wheel-scroll-injected.ts new file mode 100644 index 00000000000..8d2321e7c25 --- /dev/null +++ b/mobile/src/terminal/terminal-webview-wheel-scroll-injected.ts @@ -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 }); + } +` diff --git a/mobile/src/terminal/terminal-webview-wheel-scroll.test.ts b/mobile/src/terminal/terminal-webview-wheel-scroll.test.ts new file mode 100644 index 00000000000..463b6218bbf --- /dev/null +++ b/mobile/src/terminal/terminal-webview-wheel-scroll.test.ts @@ -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('') + ''.length + const end = XTERM_HTML.indexOf('