mirror of
https://github.com/stablyai/orca.git
synced 2026-10-20 00:03:45 +00:00
Merge branch 'main' of https://github.com/stablyai/orca into P0
This commit is contained in:
+1
-1
@@ -2,4 +2,4 @@
|
||||
/src/renderer/src/i18n/locales/ @brennanb2025
|
||||
/config/scripts/*localization*.mjs @brennanb2025
|
||||
/config/scripts/*locale*.mjs @brennanb2025
|
||||
/i18next.config.ts @brennanb2025
|
||||
/config/i18next.config.ts @brennanb2025
|
||||
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
if [[ $# -ne 2 ]]; then
|
||||
echo "Usage: $0 <base-sha> <head-sha>" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
base_sha=$1
|
||||
head_sha=$2
|
||||
git rev-parse --verify "${base_sha}^{tree}" >/dev/null
|
||||
git rev-parse --verify "${head_sha}^{tree}" >/dev/null
|
||||
|
||||
declare -A base_entries=()
|
||||
while IFS= read -r -d '' entry; do
|
||||
base_entries["$entry"]=1
|
||||
done < <(git ls-tree -z --name-only "$base_sha")
|
||||
|
||||
blocked_entries=()
|
||||
while IFS= read -r -d '' entry; do
|
||||
if [[ -z "${base_entries[$entry]+present}" ]]; then
|
||||
blocked_entries+=("$entry")
|
||||
fi
|
||||
done < <(git ls-tree -z --name-only "$head_sha")
|
||||
|
||||
if (( ${#blocked_entries[@]} == 0 )); then
|
||||
echo "Root directory guard passed: no new root-level files or folders."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "::error title=Root-level additions blocked::New root-level files or folders bloat the GitHub landing page."
|
||||
echo "Root directory guard failed."
|
||||
echo "New root-level files or folders are not allowed because they bloat the GitHub landing page."
|
||||
echo "Move each new entry under an existing top-level directory."
|
||||
printf 'Blocked entries:\n'
|
||||
printf ' %s\n' "${blocked_entries[@]}"
|
||||
exit 1
|
||||
@@ -13,7 +13,7 @@ on:
|
||||
branches:
|
||||
- Jinwoo-H/windows-update-survival
|
||||
paths:
|
||||
- 'tools/daemon-relocation-spike/**'
|
||||
- 'tests/tools/daemon-relocation-spike/**'
|
||||
- '.github/workflows/daemon-relocation-spike.yml'
|
||||
workflow_dispatch: {}
|
||||
|
||||
@@ -76,7 +76,7 @@ jobs:
|
||||
# --keep-work-dir so the per-tier daemon stdout/stderr logs survive
|
||||
# for the artifact upload (the spike otherwise removes work-dir),
|
||||
# which is what diagnoses a tier that fails to reach ready.
|
||||
node tools/daemon-relocation-spike/spike.mjs `
|
||||
node tests/tools/daemon-relocation-spike/spike.mjs `
|
||||
--app-dir dist/win-unpacked `
|
||||
--work-dir "$work" `
|
||||
--tier $tier `
|
||||
|
||||
@@ -93,6 +93,23 @@ jobs:
|
||||
- name: Verify macOS entitlements
|
||||
run: pnpm verify:macos-entitlements
|
||||
|
||||
root_directory_guard:
|
||||
name: root directory guard
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Reject new root-level files and folders
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha }}
|
||||
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
|
||||
run: bash .github/scripts/check-root-directory-entries.sh "$BASE_SHA" "$HEAD_SHA"
|
||||
|
||||
typecheck:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
@@ -377,6 +394,7 @@ jobs:
|
||||
if: always()
|
||||
needs:
|
||||
- static_analysis
|
||||
- root_directory_guard
|
||||
- typecheck
|
||||
- git_compatibility
|
||||
- shell_contracts
|
||||
@@ -397,6 +415,7 @@ jobs:
|
||||
- name: Require successful checks
|
||||
env:
|
||||
STATIC_ANALYSIS: ${{ needs.static_analysis.result }}
|
||||
ROOT_DIRECTORY_GUARD: ${{ needs.root_directory_guard.result }}
|
||||
TYPECHECK: ${{ needs.typecheck.result }}
|
||||
GIT_COMPATIBILITY: ${{ needs.git_compatibility.result }}
|
||||
SHELL_CONTRACTS: ${{ needs.shell_contracts.result }}
|
||||
@@ -406,6 +425,7 @@ jobs:
|
||||
run: |
|
||||
for result in \
|
||||
"$STATIC_ANALYSIS" \
|
||||
"$ROOT_DIRECTORY_GUARD" \
|
||||
"$TYPECHECK" \
|
||||
"$GIT_COMPATIBILITY" \
|
||||
"$SHELL_CONTRACTS" \
|
||||
|
||||
@@ -135,7 +135,7 @@ jobs:
|
||||
run: |
|
||||
New-Item -ItemType Directory -Force artifacts | Out-Null
|
||||
$log = "artifacts/crash-survival-output.log"
|
||||
node tools/win-crash-survival-e2e/run.mjs `
|
||||
node tests/tools/win-crash-survival-e2e/run.mjs `
|
||||
--expect "$env:EXPECT" `
|
||||
--exe-path "$env:ORCA_EXE" `
|
||||
--soak-seconds 8 2>&1 | Tee-Object -FilePath $log
|
||||
|
||||
@@ -20,7 +20,7 @@ on:
|
||||
branches:
|
||||
- Jinwoo-H/windows-update-survival
|
||||
paths:
|
||||
- 'tools/win-update-e2e/**'
|
||||
- 'tests/tools/win-update-e2e/**'
|
||||
- '.github/workflows/win-update-e2e.yml'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
@@ -125,7 +125,7 @@ jobs:
|
||||
ORCA_E2E_DIAG_DIR: artifacts/diag
|
||||
run: |
|
||||
$log = "artifacts/harness-output.log"
|
||||
node tools/win-update-e2e/run.mjs `
|
||||
node tests/tools/win-update-e2e/run.mjs `
|
||||
--from "$env:FROM_EXE" `
|
||||
--to "$env:TO_EXE" `
|
||||
--expect "$env:EXPECT" `
|
||||
|
||||
@@ -16,7 +16,7 @@ on:
|
||||
paths:
|
||||
- 'src/main/daemon/**'
|
||||
- 'src/main/pty/**'
|
||||
- 'tools/win-update-e2e/**'
|
||||
- 'tests/tools/win-update-e2e/**'
|
||||
- 'config/electron-builder.config.cjs'
|
||||
- '.github/workflows/win-update-survival-e2e.yml'
|
||||
workflow_dispatch:
|
||||
@@ -97,7 +97,7 @@ jobs:
|
||||
$exe = "dist/orca-windows-setup.exe"
|
||||
if (-not (Test-Path $exe)) { throw "Installer not found at $exe" }
|
||||
$log = "artifacts/survival-output.log"
|
||||
node tools/win-update-e2e/run.mjs `
|
||||
node tests/tools/win-update-e2e/run.mjs `
|
||||
--from "$exe" `
|
||||
--to "$exe" `
|
||||
--expect "$env:EXPECT" `
|
||||
|
||||
+3
-2
@@ -70,7 +70,7 @@ coverage/
|
||||
prod-release-scan-*.md
|
||||
|
||||
# Benchmark run output
|
||||
/tools/benchmarks/results/*.json
|
||||
/tests/tools/benchmarks/results/*.json
|
||||
/.bench-fixtures/
|
||||
|
||||
# Temp
|
||||
@@ -99,6 +99,7 @@ docs/**
|
||||
!docs/reference/git-compatibility.md
|
||||
!docs/reference/headless-linux-server.md
|
||||
!docs/reference/linux-glibc-compatibility.md
|
||||
!docs/reference/relay-grace-time-reconfiguration.md
|
||||
|
||||
# Stably CLI (only docs/ are tracked)
|
||||
.stably/*
|
||||
@@ -132,4 +133,4 @@ src/renderer/src/i18n/locales/.ja-catalog-cache.json
|
||||
src/renderer/src/i18n/locales/.es-catalog-cache.json
|
||||
|
||||
# Bench result JSONs are working artifacts
|
||||
tools/benchmarks/results/terminal-pipeline-*.json
|
||||
tests/tools/benchmarks/results/terminal-pipeline-*.json
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"updatedAt": "2026-07-31",
|
||||
"updatedAt": "2026-08-01",
|
||||
"policy": {
|
||||
"maturityLevels": ["experimental", "soak", "blocking", "accepted-gap", "deprecated"],
|
||||
"blockingPromotion": {
|
||||
@@ -10,6 +10,86 @@
|
||||
}
|
||||
},
|
||||
"gates": [
|
||||
{
|
||||
"id": "terminal-provider.login-session-retirement",
|
||||
"title": "macOS login-session retirement preserves live daemons through transient rejection bursts",
|
||||
"maturity": "experimental",
|
||||
"protection": "partial",
|
||||
"owner": "daemon-terminal",
|
||||
"layer": "macos-daemon-lifecycle",
|
||||
"surfaces": [
|
||||
"GUI-spawned macOS daemon",
|
||||
"local PTY survival",
|
||||
"daemon reconnect and replacement"
|
||||
],
|
||||
"platforms": ["macos"],
|
||||
"providers": ["local-daemon"],
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["local-daemon"],
|
||||
"coverageNotes": "A deterministic fake clock covers short-burst recovery, sustained session death, pending-timer and in-flight-probe suspension, event-trigger preemption, resolver corroboration, and shutdown cancellation. The production-only watch remains behind the macOS GUI launch flag; SSH/headless, WSL, Linux, Windows, mobile, and relay paths are unaffected.",
|
||||
"motivatingLinks": [
|
||||
"https://github.com/stablyai/orca/issues/11749",
|
||||
"https://github.com/stablyai/orca/issues/7936"
|
||||
],
|
||||
"invariant": "A GUI-spawned macOS daemon may retire for PAM rejections only after it previously accepted login wrapping, receives three conclusive rejections spanning at least one uninterrupted 120-second observation window, and observes explicitly unhealthy in-process resolver state. A conclusive acceptance or a sleep/App Nap-sized gap before or during a probe resets the rejection window to the periodic cadence, and client or PTY activity cannot shorten its scheduled backoff.",
|
||||
"oracle": "Arm the watch with an accepted probe, inject three rejections over 20 seconds plus unhealthy resolver state, then inject client and PTY activity and require zero resolver reads, zero retirement calls, and exactly four probes until the 120-second boundary. Return acceptance at that boundary and require the daemon to survive. Jump wall time by one hour while a timer is pending and while a PAM probe promise is unresolved; require rejection evidence to restart after wake, zero probes for the next 119,999 milliseconds, and recovery without retirement in both cases. Repeatedly delay timers beyond the suspension threshold for one hour and require the periodic probe bound, one live timer, and zero resolver or retirement calls. Separately keep rejecting through an uninterrupted boundary and require one retirement, while healthy or unknown resolver state suppresses it and stop aborts an in-flight resolver check.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/macos-login-session-death-watch.test.ts --reporter=dot"
|
||||
],
|
||||
"testFiles": ["src/main/daemon/macos-login-session-death-watch.test.ts"],
|
||||
"assertionRefs": [
|
||||
{
|
||||
"file": "src/main/daemon/macos-login-session-death-watch.test.ts",
|
||||
"assertions": [
|
||||
"preserves the daemon when a short PAM rejection burst recovers after wake",
|
||||
"does not count a suspended timer gap as rejection evidence",
|
||||
"does not count suspension during an in-flight probe as rejection evidence",
|
||||
"backs off repeated timer lateness to the periodic probe cadence",
|
||||
"retires only after sustained conclusive rejections with a degraded resolver",
|
||||
"suppresses retirement while resolver health is healthy or unknown, then retires on explicit degradation",
|
||||
"stop prevents an in-flight resolver check from retiring the daemon"
|
||||
]
|
||||
}
|
||||
],
|
||||
"evidenceRuns": [
|
||||
{
|
||||
"date": "2026-08-01",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/macos-login-session-death-watch.test.ts --reporter=dot",
|
||||
"result": "passed",
|
||||
"durationSeconds": 0.1,
|
||||
"summary": "The focused state-machine suite passed 21 tests, including the field-shaped 20-second rejection burst, pending-timer and in-flight-probe suspension rebaselining, repeated-lateness backoff, bounded recovery retry, sustained-death convergence, resolver suppression, trigger coalescing, and shutdown cancellation."
|
||||
}
|
||||
],
|
||||
"runtimeBudget": {
|
||||
"p95Seconds": 2,
|
||||
"scope": "deterministic login-session death-watch state-machine suite"
|
||||
},
|
||||
"flakeHistory": {
|
||||
"status": "unknown",
|
||||
"evidence": "The deterministic suite passes locally; focused CI and soak history are not yet available."
|
||||
},
|
||||
"redGreenEvidence": {
|
||||
"status": "complete",
|
||||
"evidence": "On origin/main, the field-shaped accepted then three-rejection sequence calls onRetire after 20 seconds and fails the recovery oracle. With the minimum observation window and non-preemptible rejection schedule, the identical oracle preserves the daemon and recovers at the boundary."
|
||||
},
|
||||
"performanceBudget": {
|
||||
"required": true,
|
||||
"evidence": "The watch retains one timer and one in-flight probe. A rejection burst runs the existing two 10-second confirmation probes, then one recovery probe at the 120-second boundary; client and PTY activity cannot pull that deadline earlier. Timer lateness and in-flight probe suspension both rebaseline evidence to the periodic cadence, preventing an App Nap retry loop, and resolver work is skipped until the time floor. No polling loop, startup await, session scan, renderer work, provider fanout, listener, or retained payload was added."
|
||||
},
|
||||
"promotionCriteria": [
|
||||
"Collect 100 consecutive focused CI passes or 14 days of soak history.",
|
||||
"Capture field evidence from macOS sleep/wake and a full GUI logout without a false retirement or missed stale-session recovery.",
|
||||
"Keep the exact probe-count, no-early-resolver, trigger-preemption, acceptance-reset, and shutdown-abort assertions green."
|
||||
],
|
||||
"knownGaps": [
|
||||
"A real dead macOS GUI login session cannot be fabricated without ending the runner's login session; sustained-death coverage uses deterministic PAM and resolver oracles.",
|
||||
"The two-minute production window and one-hour pending/in-flight suspension cases are covered by fake-clock tests rather than a real sleep/wake run.",
|
||||
"No multi-process aggregate throttle is added; each stale daemon independently obeys the same non-preemptible observation window."
|
||||
],
|
||||
"demotionRule": "Keep experimental or demote if any activity trigger shortens the rejection window, a transient burst reaches resolver retirement authority, sustained dead-session evidence no longer converges, shutdown permits late retirement, or the focused gate flakes without an identified product or harness fault."
|
||||
},
|
||||
{
|
||||
"id": "ssh-relay.staged-upload-recovery",
|
||||
"title": "SSH relay uploads remain retryable before the shared install lock",
|
||||
@@ -2970,6 +3050,105 @@
|
||||
],
|
||||
"demotionRule": "Demote or quarantine if the unit gate flakes without a product bug or harness bug filed to the owner."
|
||||
},
|
||||
{
|
||||
"id": "terminal-scroll.streaming-refocus-intent",
|
||||
"title": "Streaming refocus preserves follow-output viewport intent",
|
||||
"maturity": "experimental",
|
||||
"protection": "partial",
|
||||
"owner": "terminal-rendering",
|
||||
"layer": "renderer-unit-and-electron-e2e",
|
||||
"surfaces": [
|
||||
"terminal lifecycle",
|
||||
"window focus recovery",
|
||||
"hidden-to-visible resume",
|
||||
"xterm write backlog",
|
||||
"scrollback"
|
||||
],
|
||||
"platforms": ["macos", "linux", "windows"],
|
||||
"providers": ["local", "daemon", "ssh", "wsl", "remote-runtime"],
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["local", "daemon"],
|
||||
"coverageNotes": "Unit coverage proves provider-independent ordering for any PaneManager. Live Electron coverage exercises a local PTY through the daemon on macOS; SSH, WSL, remote-runtime, Linux, and Windows remain unproved for this exact race.",
|
||||
"motivatingLinks": [
|
||||
"https://github.com/stablyai/orca/issues/11753",
|
||||
"https://github.com/stablyai/orca/pull/11915"
|
||||
],
|
||||
"invariant": "When output is queued during a focus or visibility transition, Orca records the pre-flush viewport intent before xterm parses backlog writes, so a follow-output terminal stays at the bottom and a pinned terminal keeps its prior position.",
|
||||
"oracle": "Unit tests require exactly one intent sync before each queued-output flush. The Electron test injects a transient top-of-buffer xterm wobble during refocus and requires every presented scrollbar frame, including the final rendered output, to remain at the bottom.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts",
|
||||
"pnpm exec electron-vite build --mode e2e",
|
||||
"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-streaming-refocus-viewport.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=5"
|
||||
],
|
||||
"testFiles": [
|
||||
"src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts",
|
||||
"tests/e2e/terminal-streaming-refocus-viewport.spec.ts"
|
||||
],
|
||||
"assertionRefs": [
|
||||
{
|
||||
"file": "src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts",
|
||||
"assertions": [
|
||||
"window-wake recovery synchronizes viewport intent exactly once before flushing queued output",
|
||||
"heavy visibility resume synchronizes intent exactly once before flushing queued output"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "tests/e2e/terminal-streaming-refocus-viewport.spec.ts",
|
||||
"assertions": [
|
||||
"phase-one scrollback is visibly ready at the bottom without a fixed sleep",
|
||||
"no presented animation frame moves the scrollbar thumb away from the bottom during refocus",
|
||||
"the final streamed marker renders with the visible scrollbar still at the bottom"
|
||||
]
|
||||
}
|
||||
],
|
||||
"evidenceRuns": [
|
||||
{
|
||||
"date": "2026-08-01",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/terminal-visibility-resume.test.ts",
|
||||
"result": "passed",
|
||||
"durationSeconds": 0.096,
|
||||
"summary": "14 tests passed, including exact sync count and pre-flush ordering for wake and heavy visibility resume."
|
||||
},
|
||||
{
|
||||
"date": "2026-08-01",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-streaming-refocus-viewport.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=5",
|
||||
"result": "passed",
|
||||
"durationSeconds": 35.2,
|
||||
"summary": "Five consecutive Electron iterations passed after replacing fixed-time readiness and stale tab capture with deterministic viewport and pane-identity oracles."
|
||||
}
|
||||
],
|
||||
"runtimeBudget": {
|
||||
"p95Seconds": 30,
|
||||
"scope": "focused renderer unit test or one Electron E2E iteration"
|
||||
},
|
||||
"flakeHistory": {
|
||||
"status": "soaking",
|
||||
"evidence": "Five consecutive local Electron iterations passed; CI soak history is still required before promotion."
|
||||
},
|
||||
"redGreenEvidence": {
|
||||
"status": "complete",
|
||||
"evidence": "The controlled xterm viewport wobble reproduces the pinned-top failure with post-flush intent sampling and passes when intent is latched before the queued write flush."
|
||||
},
|
||||
"performanceBudget": {
|
||||
"required": true,
|
||||
"evidence": "Wake recovery keeps one O(panes) intent pass before the existing bounded 64 KiB-per-pane flush. Heavy resume removes its second intent pass and keeps the existing bounded 256 KiB-per-pane flush; no polling, timers, subprocesses, IPC, output parsing, fit, or repaint work is added."
|
||||
},
|
||||
"promotionCriteria": [
|
||||
"Collect stable CI soak history for the Electron race gate.",
|
||||
"Run the live oracle on Linux and Windows terminal backends.",
|
||||
"Add live SSH or remote-runtime coverage for queued output during refocus."
|
||||
],
|
||||
"knownGaps": [
|
||||
"The deterministic wobble uses xterm private buffer state and must be updated if that internal contract changes.",
|
||||
"Live Linux, Windows, SSH, WSL, and remote-runtime execution is not covered for this exact race.",
|
||||
"The Electron gate proves follow-output behavior; adjacent scroll-intent coverage protects pinned viewport behavior."
|
||||
],
|
||||
"demotionRule": "Demote or quarantine if the Electron oracle flakes without a product bug or harness bug filed to terminal-rendering."
|
||||
},
|
||||
{
|
||||
"id": "startup-upgrade.persisted-session-corpus",
|
||||
"title": "Current Orca preserves or recovers old production persisted sessions",
|
||||
@@ -3106,11 +3285,11 @@
|
||||
"oracle": "Resolve the launched instance's real main PID from inside Electron, force-kill only that PID, require it to die, require one command-line-scoped daemon PID and the stamped interactive shell PID to remain live, relaunch with persisted state, require the daemon PID to remain identical, read the exact shell PID and a per-shell environment sentinel back through the exact restored tab, then require a successful Windows Application event-log query with zero matching pwsh FailFast events across the full crash-to-input window.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts config/scripts/win-crash-survival-e2e.test.mjs",
|
||||
"node tools/win-crash-survival-e2e/run.mjs --expect survival --exe-path \"$env:ORCA_EXE\" --soak-seconds 8"
|
||||
"node tests/tools/win-crash-survival-e2e/run.mjs --expect survival --exe-path \"$env:ORCA_EXE\" --soak-seconds 8"
|
||||
],
|
||||
"testFiles": [
|
||||
"config/scripts/win-crash-survival-e2e.test.mjs",
|
||||
"tools/win-crash-survival-e2e/run.mjs"
|
||||
"tests/tools/win-crash-survival-e2e/run.mjs"
|
||||
],
|
||||
"assertionRefs": [
|
||||
{
|
||||
@@ -3124,7 +3303,7 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "tools/win-crash-survival-e2e/run.mjs",
|
||||
"file": "tests/tools/win-crash-survival-e2e/run.mjs",
|
||||
"assertions": [
|
||||
"force-killing only the real Electron main leaves the exact scoped daemon and stamped interactive shell alive",
|
||||
"packaged relaunch adopts the unchanged daemon and reads the survivor shell's environment sentinel through the restored terminal"
|
||||
@@ -3136,7 +3315,7 @@
|
||||
"date": "2026-07-18",
|
||||
"runner": "ci",
|
||||
"platform": "windows",
|
||||
"command": "node tools/win-crash-survival-e2e/run.mjs --expect survival --exe-path \"$env:ORCA_EXE\" --soak-seconds 8",
|
||||
"command": "node tests/tools/win-crash-survival-e2e/run.mjs --expect survival --exe-path \"$env:ORCA_EXE\" --soak-seconds 8",
|
||||
"result": "passed",
|
||||
"durationSeconds": 61,
|
||||
"summary": "The packaged branch build's real main died; the same daemon and shell PIDs survived; the event-log scan found zero FailFast events; relaunch adopted the unchanged daemon; and terminal input read the survivor shell sentinel back."
|
||||
@@ -4621,6 +4800,101 @@
|
||||
],
|
||||
"demotionRule": "Keep experimental or demote if the gate flakes without a product or harness bug, if any local shutdown reaches fallback before startup settles, or if shutdown adds inventory scans or retry loops."
|
||||
},
|
||||
{
|
||||
"id": "terminal-provider.snapshot-capability-renderer-responsiveness",
|
||||
"title": "PTY snapshot capability discovery never blocks renderer JavaScript",
|
||||
"maturity": "experimental",
|
||||
"protection": "partial",
|
||||
"owner": "terminal-provider",
|
||||
"layer": "renderer-ipc",
|
||||
"surfaces": [
|
||||
"renderer startup",
|
||||
"cold terminal restoration",
|
||||
"hidden terminal parking",
|
||||
"SSH terminal restoration"
|
||||
],
|
||||
"platforms": ["macos", "linux", "windows"],
|
||||
"providers": ["daemon", "ssh", "remote-runtime"],
|
||||
"coveredPlatforms": ["macos"],
|
||||
"coveredProviders": ["daemon", "ssh"],
|
||||
"coverageNotes": "A preload contract and Electron main-stall oracle prove capability lookup is asynchronous. Startup prefetch covers restored primary and split-pane PTY identities before cold activation, while unknown providers remain eager. Docker SSH journeys prove remote terminals still remount eagerly and reclaim their authenticated PTY owner after restart.",
|
||||
"motivatingLinks": ["https://stablygroup.slack.com/archives/C0BD60A5J85/p1785524559818629"],
|
||||
"invariant": "PTY snapshot capability discovery must never synchronously block renderer JavaScript. Restored daemon capability must be known before workspace readiness enables cold activation; unknown or legacy capability must remain eager. A healthy SSH provider must return definitive false without polling. One unresponsive capability batch must fail open within one second regardless of PTY count, and stale async responses must not update current bindings.",
|
||||
"oracle": "The preload test rejects sendSync and requires ipcRenderer.invoke. Unit contracts assert 512-ID batching, one-second fail-open, unknown retry, definitive SSH false, and generation-fenced stale responses. During an injected 1.5-second Electron main-thread stall, a renderer-owned 50ms interval must keep a maximum gap below 500ms and each API call must return within 100ms. The production cold-activation journey must still mount at most three of eight daemon tabs after reload, while Docker SSH restoration remains eager.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/preload/pty-snapshot-capability-ipc.test.ts src/main/ipc/pty.test.ts src/main/providers/ssh-pty-provider.test.ts src/renderer/src/components/terminal/terminal-provider-snapshot-capability.test.ts src/renderer/src/components/terminal/use-terminal-provider-snapshot-capability.test.tsx src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.test.ts src/renderer/src/app-startup-routing.test.ts --reporter=dot",
|
||||
"pnpm exec electron-vite build --mode e2e",
|
||||
"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/pty-snapshot-capability-main-stall.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=3",
|
||||
"SKIP_BUILD=1 pnpm exec playwright test tests/e2e/terminal-cold-activation-deferral.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1",
|
||||
"ORCA_E2E_SSH_DOCKER=1 SKIP_BUILD=1 pnpm exec playwright test tests/e2e/ssh-cold-activation-restore.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1"
|
||||
],
|
||||
"testFiles": [
|
||||
"src/preload/pty-snapshot-capability-ipc.test.ts",
|
||||
"src/main/ipc/pty.test.ts",
|
||||
"src/main/providers/ssh-pty-provider.test.ts",
|
||||
"src/renderer/src/components/terminal/terminal-provider-snapshot-capability.test.ts",
|
||||
"src/renderer/src/components/terminal/use-terminal-provider-snapshot-capability.test.tsx",
|
||||
"src/renderer/src/components/terminal/background-terminal-worktree-mount.test.ts",
|
||||
"src/renderer/src/components/terminal-pane/terminal-hidden-view-parking.test.ts",
|
||||
"src/renderer/src/app-startup-routing.test.ts",
|
||||
"tests/e2e/pty-snapshot-capability-main-stall.spec.ts",
|
||||
"tests/e2e/terminal-cold-activation-deferral.spec.ts",
|
||||
"tests/e2e/ssh-cold-activation-restore.spec.ts"
|
||||
],
|
||||
"assertionRefs": [
|
||||
{
|
||||
"file": "tests/e2e/pty-snapshot-capability-main-stall.spec.ts",
|
||||
"assertions": [
|
||||
"a 1.5-second main stall leaves renderer interval gaps below 500ms",
|
||||
"capability calls return to renderer JavaScript within 100ms"
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "tests/e2e/terminal-cold-activation-deferral.spec.ts",
|
||||
"assertions": [
|
||||
"cold reload mounts at most three of eight daemon tabs and parked watchers cover the rest"
|
||||
]
|
||||
}
|
||||
],
|
||||
"evidenceRuns": [
|
||||
{
|
||||
"date": "2026-07-31",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "SKIP_BUILD=1 pnpm exec playwright test tests/e2e/pty-snapshot-capability-main-stall.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1 --repeat-each=3",
|
||||
"result": "passed",
|
||||
"durationSeconds": 16.8,
|
||||
"summary": "Three 1.5-second main stalls produced 32 renderer calls each; maximum interval gaps were 70.3ms, 70.1ms, and 71.6ms, and maximum call-return durations were 0.1ms, 0.1ms, and 0.2ms. The synchronous baseline produced a 1465.1ms interval gap and 1464.2ms call-return duration."
|
||||
}
|
||||
],
|
||||
"runtimeBudget": {
|
||||
"p95Seconds": 30,
|
||||
"scope": "focused Electron responsiveness and cold-restore journeys"
|
||||
},
|
||||
"flakeHistory": {
|
||||
"status": "unknown",
|
||||
"evidence": "The deterministic Electron oracle passed three consecutive local runs; CI soak history is not yet available."
|
||||
},
|
||||
"redGreenEvidence": {
|
||||
"status": "complete",
|
||||
"evidence": "The byte-identical Electron oracle failed with synchronous sendSync at a 1465.1ms renderer interval gap and 1464.2ms call-return duration, then passed three times with async invoke at no more than 71.6ms and 0.2ms respectively. The preload test also fails on the synchronous baseline."
|
||||
},
|
||||
"performanceBudget": {
|
||||
"required": true,
|
||||
"evidence": "Capability requests are deduplicated by PTY ID, sent in bounded 512-ID batches, cached after a definitive result, and retried only for unknown results. SSH now returns definitive false. One unresponsive batch fails open after one second without scanning further batches. No subprocesses or provider inventories are added."
|
||||
},
|
||||
"promotionCriteria": [
|
||||
"Run the Electron main-stall oracle for at least 100 consecutive passes or 14 days across required CI platforms.",
|
||||
"Collect Windows and Linux desktop cold-restore coverage.",
|
||||
"Add a headed paired-desktop cold-restore journey if provider capability semantics move into the remote runtime."
|
||||
],
|
||||
"knownGaps": [
|
||||
"The main-stall and local daemon cold-restore Electron journeys currently run on macOS only.",
|
||||
"Docker SSH proves the Linux relay/provider path but not a Linux desktop renderer.",
|
||||
"This gate proves renderer responsiveness to main stalls; it does not identify the cause of the reported production hard freeze."
|
||||
],
|
||||
"demotionRule": "Demote if capability discovery reintroduces synchronous renderer IPC, cold daemon tabs mount eagerly despite authoritative snapshots, SSH capability polls after a definitive response, or the renderer gap budget flakes without a product or harness bug."
|
||||
},
|
||||
{
|
||||
"id": "terminal-provider.ssh-remote-reattach-contract",
|
||||
"title": "SSH restore and remote-runtime recovery preserve live terminal ownership",
|
||||
@@ -5909,14 +6183,14 @@
|
||||
"oracle": "Runtime tests assert the exact PTY write sequence and failure cleanup; orchestration tests assert dispatch/coordinator use the agent prompt path; the live CLI harness dispatches a 32KB task to a fake Codex-like TUI and requires marker present, bracketed paste present, zero unframed line breaks, and submit observed.",
|
||||
"commands": [
|
||||
"pnpm exec vitest run --config config/vitest.config.ts src/shared/agent-prompt-injection.test.ts src/main/runtime/orca-runtime.test.ts src/main/runtime/rpc/methods/orchestration.test.ts src/main/runtime/orchestration/coordinator.test.ts",
|
||||
"node tools/repro-orchestration-long-prompt.mjs --cli out/bin/orca-dev --mode codex-like --size-kb 32 --timeout-ms 20000"
|
||||
"node tests/tools/repro-orchestration-long-prompt.mjs --cli out/bin/orca-dev --mode codex-like --size-kb 32 --timeout-ms 20000"
|
||||
],
|
||||
"testFiles": [
|
||||
"src/shared/agent-prompt-injection.test.ts",
|
||||
"src/main/runtime/orca-runtime.test.ts",
|
||||
"src/main/runtime/rpc/methods/orchestration.test.ts",
|
||||
"src/main/runtime/orchestration/coordinator.test.ts",
|
||||
"tools/repro-orchestration-long-prompt.mjs"
|
||||
"tests/tools/repro-orchestration-long-prompt.mjs"
|
||||
],
|
||||
"assertionRefs": [
|
||||
{
|
||||
@@ -5952,7 +6226,7 @@
|
||||
]
|
||||
},
|
||||
{
|
||||
"file": "tools/repro-orchestration-long-prompt.mjs",
|
||||
"file": "tests/tools/repro-orchestration-long-prompt.mjs",
|
||||
"assertions": [
|
||||
"fake Codex-like worker observes submit after long orchestration dispatch",
|
||||
"32KB task marker survives before submit",
|
||||
@@ -5974,7 +6248,7 @@
|
||||
"date": "2026-07-07",
|
||||
"runner": "local",
|
||||
"platform": "macos",
|
||||
"command": "node tools/repro-orchestration-long-prompt.mjs --cli out/bin/orca-dev --mode codex-like --size-kb 32 --timeout-ms 20000",
|
||||
"command": "node tests/tools/repro-orchestration-long-prompt.mjs --cli out/bin/orca-dev --mode codex-like --size-kb 32 --timeout-ms 20000",
|
||||
"result": "passed",
|
||||
"durationSeconds": 2.2,
|
||||
"summary": "Live dev-runtime repro passed: expectedSpecBytes=32830, hasSubmit=true, rawContainsMarker=true, hasBracketedPasteFrame=true, unframedLineBreaks=0, contractOk=true."
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import { execFileSync, spawnSync } from 'node:child_process'
|
||||
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { parse } from 'yaml'
|
||||
|
||||
const projectDir = resolve(import.meta.dirname, '../..')
|
||||
const guardScript = join(projectDir, '.github/scripts/check-root-directory-entries.sh')
|
||||
const tempDirs = []
|
||||
|
||||
function git(cwd, args) {
|
||||
return execFileSync('git', args, { cwd, encoding: 'utf8' }).trim()
|
||||
}
|
||||
|
||||
function makeFixture() {
|
||||
const root = mkdtempSync(join(tmpdir(), 'orca-root-directory-guard-'))
|
||||
tempDirs.push(root)
|
||||
git(root, ['init', '--quiet'])
|
||||
git(root, ['config', 'user.email', 'root-directory-guard-test@example.com'])
|
||||
git(root, ['config', 'user.name', 'Root Directory Guard Test'])
|
||||
mkdirSync(join(root, 'config'), { recursive: true })
|
||||
writeFileSync(join(root, 'config', 'base.txt'), 'base\n')
|
||||
git(root, ['add', '-A'])
|
||||
git(root, ['commit', '--quiet', '-m', 'base'])
|
||||
return { root, base: git(root, ['rev-parse', 'HEAD']) }
|
||||
}
|
||||
|
||||
function commitFiles(root, files) {
|
||||
for (const [relativePath, contents] of files) {
|
||||
const target = join(root, relativePath)
|
||||
mkdirSync(dirname(target), { recursive: true })
|
||||
writeFileSync(target, contents)
|
||||
}
|
||||
git(root, ['add', '-A'])
|
||||
git(root, ['commit', '--quiet', '-m', 'head'])
|
||||
return git(root, ['rev-parse', 'HEAD'])
|
||||
}
|
||||
|
||||
function runGuard({ root, base, head }) {
|
||||
return spawnSync('bash', [guardScript, base, head], {
|
||||
cwd: root,
|
||||
encoding: 'utf8'
|
||||
})
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
while (tempDirs.length > 0) {
|
||||
rmSync(tempDirs.pop(), { force: true, recursive: true })
|
||||
}
|
||||
})
|
||||
|
||||
describe('root directory guard', () => {
|
||||
it('allows additions inside an existing top-level directory', () => {
|
||||
const fixture = makeFixture()
|
||||
const head = commitFiles(fixture.root, [['config/new.txt', 'nested\n']])
|
||||
|
||||
const result = runGuard({ ...fixture, head })
|
||||
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stdout).toContain('no new root-level files or folders')
|
||||
})
|
||||
|
||||
it('rejects a new root-level file with the landing-page message', () => {
|
||||
const fixture = makeFixture()
|
||||
const head = commitFiles(fixture.root, [['new-root.md', 'too prominent\n']])
|
||||
|
||||
const result = runGuard({ ...fixture, head })
|
||||
const output = `${result.stdout}\n${result.stderr}`
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output).toContain('bloat the GitHub landing page')
|
||||
expect(output).toContain('new-root.md')
|
||||
})
|
||||
|
||||
it('rejects a new top-level directory', () => {
|
||||
const fixture = makeFixture()
|
||||
const head = commitFiles(fixture.root, [['new-folder/file.txt', 'too prominent\n']])
|
||||
|
||||
const result = runGuard({ ...fixture, head })
|
||||
const output = `${result.stdout}\n${result.stderr}`
|
||||
|
||||
expect(result.status).toBe(1)
|
||||
expect(output).toContain('new-folder')
|
||||
})
|
||||
|
||||
it('is wired into the PR verify gate', () => {
|
||||
const workflow = parse(readFileSync(join(projectDir, '.github/workflows/pr.yml'), 'utf8'))
|
||||
const guardJob = workflow.jobs.root_directory_guard
|
||||
const guardStep = guardJob.steps.find(
|
||||
(step) => step.name === 'Reject new root-level files and folders'
|
||||
)
|
||||
|
||||
expect(guardJob.name).toBe('root directory guard')
|
||||
expect(guardJob.steps[0].with['fetch-depth']).toBe(0)
|
||||
expect(guardStep.run).toContain('.github/scripts/check-root-directory-entries.sh')
|
||||
expect(workflow.jobs.verify.needs).toContain('root_directory_guard')
|
||||
})
|
||||
})
|
||||
@@ -22,7 +22,7 @@ const testFilePatterns = [
|
||||
'config/**/*.{test,spec}.{js,cjs,mjs,ts,tsx}',
|
||||
'src/**/*.{test,spec}.{js,cjs,mjs,ts,tsx}',
|
||||
'tests/**/*.{test,spec}.{js,cjs,mjs,ts,tsx}',
|
||||
'tools/**/*.{test,spec}.{js,cjs,mjs,ts,tsx}'
|
||||
'tests/tools/**/*.{test,spec}.{js,cjs,mjs,ts,tsx}'
|
||||
]
|
||||
const realZshUsage =
|
||||
/(?:spawnSync|execFileSync|spawn)\(\s*['"](?:\/(?:usr\/)?bin\/)?zsh['"]|spawnSync\(\s*['"]which['"]\s*,\s*\[\s*['"]zsh['"]|name:\s*['"]zsh['"]\s*,\s*path:\s*executablePath/
|
||||
@@ -173,6 +173,7 @@ describe('PR workflow parallelism', () => {
|
||||
it('keeps verify as the aggregate required check', () => {
|
||||
expect(workflow.jobs.verify.needs).toEqual([
|
||||
'static_analysis',
|
||||
'root_directory_guard',
|
||||
'typecheck',
|
||||
'git_compatibility',
|
||||
'shell_contracts',
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* pnpm bench:multi-workspace-typing [-- --panes 8 --rate-kbps 512 \
|
||||
* --keys 48 --cadence-ms 250 --cpu-workers 4 --label before-fix]
|
||||
*
|
||||
* Results land in tools/benchmarks/results/multi-workspace-typing-*.json.
|
||||
* Results land in tests/tools/benchmarks/results/multi-workspace-typing-*.json.
|
||||
* Run once per build/config with distinct --label values, then diff the
|
||||
* totalMs/inputHalfMs/echoHalfMs percentiles.
|
||||
*/
|
||||
|
||||
@@ -82,13 +82,17 @@ async function extractToTemporaryCatalog(root, tempDir) {
|
||||
const outputPattern = path.join(tempDir, '{{language}}.json')
|
||||
// Why: extraction output is evidence for this check, not another committed
|
||||
// catalog that feature authors must keep synchronized.
|
||||
await execFileAsync(process.execPath, [cliPath, 'extract', '--sync-primary', '--quiet'], {
|
||||
cwd: root,
|
||||
env: {
|
||||
...process.env,
|
||||
ORCA_I18N_EXTRACTION_OUTPUT: outputPattern.split(path.sep).join('/')
|
||||
await execFileAsync(
|
||||
process.execPath,
|
||||
[cliPath, '--config', 'config/i18next.config.ts', 'extract', '--sync-primary', '--quiet'],
|
||||
{
|
||||
cwd: root,
|
||||
env: {
|
||||
...process.env,
|
||||
ORCA_I18N_EXTRACTION_OUTPUT: outputPattern.split(path.sep).join('/')
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
return JSON.parse(await fs.readFile(path.join(tempDir, 'en.json'), 'utf8'))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { parseArgs } from '../../tools/win-crash-survival-e2e/cli-args.mjs'
|
||||
import { buildCrashAssertions } from '../../tools/win-crash-survival-e2e/crash-assertions.mjs'
|
||||
import { scanPwshFailFast } from '../../tools/win-crash-survival-e2e/crash-step.mjs'
|
||||
import { selectScopedDaemon } from '../../tools/win-crash-survival-e2e/daemon-identity.mjs'
|
||||
import { parseArgs } from '../../tests/tools/win-crash-survival-e2e/cli-args.mjs'
|
||||
import { buildCrashAssertions } from '../../tests/tools/win-crash-survival-e2e/crash-assertions.mjs'
|
||||
import { scanPwshFailFast } from '../../tests/tools/win-crash-survival-e2e/crash-step.mjs'
|
||||
import { selectScopedDaemon } from '../../tests/tools/win-crash-survival-e2e/daemon-identity.mjs'
|
||||
import {
|
||||
reattachSentinelMatches,
|
||||
selectCreatedTabId
|
||||
} from '../../tools/win-crash-survival-e2e/reattach-proof.mjs'
|
||||
import { quotePowerShellLiteral } from '../../tools/win-update-e2e/powershell-runner.mjs'
|
||||
import { closeApp, resolveElectronMainPid } from '../../tools/win-update-e2e/app-driver.mjs'
|
||||
import { isPidAlive } from '../../tools/win-update-e2e/daemon-processes.mjs'
|
||||
} from '../../tests/tools/win-crash-survival-e2e/reattach-proof.mjs'
|
||||
import { quotePowerShellLiteral } from '../../tests/tools/win-update-e2e/powershell-runner.mjs'
|
||||
import { closeApp, resolveElectronMainPid } from '../../tests/tools/win-update-e2e/app-driver.mjs'
|
||||
import { isPidAlive } from '../../tests/tools/win-update-e2e/daemon-processes.mjs'
|
||||
|
||||
describe('win-crash-survival-e2e proof contracts', () => {
|
||||
it('keeps the packaged proof manually dispatchable without a PR trigger', () => {
|
||||
@@ -59,7 +59,7 @@ describe('win-crash-survival-e2e proof contracts', () => {
|
||||
})
|
||||
|
||||
it('scans for FailFast only after the post-crash input probe', () => {
|
||||
const harness = readFileSync('tools/win-crash-survival-e2e/run.mjs', 'utf8')
|
||||
const harness = readFileSync('tests/tools/win-crash-survival-e2e/run.mjs', 'utf8')
|
||||
const scanIndex = harness.indexOf('const { events: failFastEvents }')
|
||||
const probeIndex = harness.indexOf('reattachProven = await proveReattachedShell')
|
||||
expect(scanIndex).not.toBe(-1)
|
||||
@@ -163,7 +163,7 @@ describe('win-crash-survival-e2e proof contracts', () => {
|
||||
})
|
||||
|
||||
it('requires the real packaged main for the crash proof but permits fallback cleanup', async () => {
|
||||
const harness = readFileSync('tools/win-crash-survival-e2e/run.mjs', 'utf8')
|
||||
const harness = readFileSync('tests/tools/win-crash-survival-e2e/run.mjs', 'utf8')
|
||||
expect(harness).toContain(
|
||||
'resolveElectronMainPid(session.app, { allowLauncherFallback: false })'
|
||||
)
|
||||
|
||||
@@ -22,7 +22,7 @@ export default defineConfig({
|
||||
'src/**/*.test.tsx',
|
||||
'config/scripts/**/*.test.ts',
|
||||
'config/scripts/**/*.test.mjs',
|
||||
'tools/**/*.test.mjs',
|
||||
'tests/tools/**/*.test.mjs',
|
||||
'tests/e2e/**/*.unit.test.ts'
|
||||
],
|
||||
// Why: the full suite runs heavy TS transforms plus real git/http fixtures;
|
||||
|
||||
@@ -1,377 +0,0 @@
|
||||
# Agent Status over WSL (STA-1515)
|
||||
|
||||
Status: implemented and rig-validated (2026-07-09 round 3 + 2026-07-10 round-4 re-run
|
||||
pinned to the hardened build, Windows 11 + WSL2 NAT): Claude end-to-end live —
|
||||
provisioning, working→done in the store, completion toast, loopback-only posture, and
|
||||
restart resume over a daemon-surviving PTY with the instance-keyed endpoint dir reused
|
||||
across restarts. The round-4 re-run also proved the `--exec` spawn form live (host
|
||||
process table) and the stale-exit reinstall upgrading the guest to the new bundle
|
||||
version in place. Residual: Codex's done/Stop leg unproven live — env-blocked on the
|
||||
rig (no dev-profile Codex credentials AND the model backend is unreachable from the
|
||||
guest under NAT); everything that fired behaved correctly. Confirm on a credentialed
|
||||
rig with a guest-reachable backend, ideally on a fresh distro to also observe the
|
||||
deferred Codex trust entries landing after config.toml is seeded.
|
||||
Owner: brennanb2025. Linear: STA-1515.
|
||||
Precedent this mirrors: the SSH agent-hook relay (`src/relay/agent-hook-server.ts`,
|
||||
`src/shared/agent-hook-relay.ts`, ingest at `agentHookServer.ingestRemote` in
|
||||
`src/main/agent-hooks/server.ts`).
|
||||
|
||||
## Background — how we got here
|
||||
|
||||
GitHub issue `7565` reported OMP agents in WSL worktrees disappearing from the worktree
|
||||
sidebar after v1.4.124. Diagnosis split it into a regression and a pre-existing class gap:
|
||||
|
||||
- The **regression** was a title-normalization change (PR `7447`) that stopped idle OMP
|
||||
titles from producing the sidebar's title-derived fallback row. Decision: the sidebar is
|
||||
moving to **hook-driven rows only** (fallback removal in flight, separate PR), so the
|
||||
fallback was not restored.
|
||||
- The **class gap** is that agent hooks have never worked from inside WSL for any agent.
|
||||
Two scoped PRs fixed it for OMP alone (merged, live-validated on a Windows+WSL2-NAT rig):
|
||||
- PR `7642` — Orca-managed WSL shells wrap interactive `omp` invocations with
|
||||
`--extension "$ORCA_OMP_STATUS_EXTENSION"` (the env var is WSLENV `/p`-translated so
|
||||
the WSL process reads the extension out of the Windows filesystem via `/mnt/c`).
|
||||
- PR `7641` — when the extension's loopback POST cannot connect, it delivers via
|
||||
Windows-side `/mnt/c/Windows/System32/curl.exe` (a Windows process, so *its*
|
||||
`127.0.0.1` is the loopback Orca actually binds). Fire-and-forget spawn,
|
||||
`--noproxy 127.0.0.1`, memoized WSL/curl probes, load-tolerant timeouts
|
||||
(`--connect-timeout 3 --max-time 10`; 0.5s dropped events under load).
|
||||
|
||||
This document is the full context for the general fix: every other hook client is still
|
||||
dead from WSL, and the hooks-only sidebar change makes this work the gate for the
|
||||
Windows+WSL story.
|
||||
|
||||
## Why hooks don't work on Windows+WSL — two independent gaps
|
||||
|
||||
### Gap A — transport
|
||||
|
||||
The hook listener binds `127.0.0.1` only, deliberately (`src/main/agent-hooks/server.ts`,
|
||||
`listen(0, '127.0.0.1')`; auth via `X-Orca-Agent-Hook-Token`, 403 otherwise). Every hook
|
||||
client POSTs to a hardcoded `http://127.0.0.1:$ORCA_AGENT_HOOK_PORT/hook/<source>`.
|
||||
|
||||
WSL2 under default **NAT** networking is a VM with its own network namespace. Microsoft's
|
||||
localhost forwarding is **one-way (Windows→WSL only)**: `127.0.0.1` inside WSL is WSL's
|
||||
own loopback, so every POST dies `ECONNREFUSED` — silently, because hook clients are
|
||||
deliberately fail-open. Reaching Windows from WSL would require the host vNIC IP (changes
|
||||
per boot) + a non-loopback listener bind + a firewall rule — all three conflict with the
|
||||
loopback-only security posture.
|
||||
|
||||
The env coordinates DO cross correctly (`src/main/pty/wsl-orca-env.ts`
|
||||
`addOrcaWslInteropEnv`: WSLENV `PORT/u TOKEN/u ENV/u VERSION/u` plus
|
||||
`ORCA_AGENT_HOOK_ENDPOINT/p` path-translated; called from `src/main/ipc/pty.ts` and
|
||||
`src/main/daemon/pty-subprocess.ts`). The address is simply unreachable.
|
||||
|
||||
Opt-in **mirrored** networking (Win11, `.wslconfig`) shares loopback and makes plain fetch
|
||||
work — the fix must not fight it. No `wslinfo` probing is needed: under mirrored mode the
|
||||
relay's preferred-port bind collides with the Windows listener and the `EADDRINUSE`
|
||||
fallback (below) handles it, while clients that go straight to the shared loopback reach
|
||||
the Windows listener directly. Both delivery paths stay valid.
|
||||
|
||||
### Gap B — installation
|
||||
|
||||
Hook configs and scripts are written to the **Windows** home by every hook service:
|
||||
Claude `settings.json` + managed scripts, Codex config, Gemini/Cursor/Droid/Devin/Grok/
|
||||
Copilot scripts, Amp/OpenCode plugin files, the Pi/OMP extension file. An agent inside WSL
|
||||
reads the **WSL-side** `$HOME` and sees none of it. There is zero WSL-targeted install
|
||||
code in `src/main/agent-hooks/` or any hook service. SSH remotes have the exact precedent
|
||||
needed: dedicated remote installers (`src/main/ssh/ssh-relay-session.ts` remote
|
||||
settings.json handling; PR `7744` installed Droid/Copilot hooks over SSH).
|
||||
|
||||
Consequence: even mirrored-networking users get no hooks — transport fine, configs absent.
|
||||
OMP escapes Gap B by *pointing across* the boundary (`/mnt/c` path via `/p` translation)
|
||||
rather than installing WSL-side; that trick can carry file *content* for some clients, but
|
||||
shell hooks still execute inside WSL and then hit Gap A regardless.
|
||||
|
||||
## Transport map — every client, how it posts
|
||||
|
||||
Endpoint file contract: `writeEndpointFile` (`src/shared/agent-hook-listener.ts`) emits
|
||||
exactly four keys (`ORCA_AGENT_HOOK_PORT/TOKEN/ENV/VERSION`) to `endpoint.env` (POSIX) /
|
||||
`endpoint.cmd` (Windows) — **no host field**. Shell clients source it to refresh stale
|
||||
coords after an Orca restart; node clients parse it. It is never executed as a delivery
|
||||
script. Clients prefer endpoint-FILE coords over env (restart re-coordination) — any
|
||||
transport change must preserve that property.
|
||||
|
||||
| Client | Mechanism | Runtime that POSTs |
|
||||
| --- | --- | --- |
|
||||
| Claude, Codex, Gemini, Cursor, Droid, Devin, Grok | managed shell script | `curl` (POSIX) / `curl.exe` (Windows), built in `src/main/agent-hooks/installer-utils.ts` |
|
||||
| Copilot | managed script | `curl` (POSIX) / PowerShell `Invoke-WebRequest` (Windows) |
|
||||
| command-code | managed script (parse-not-source hardened) | `curl` |
|
||||
| Amp, OpenCode | in-process node plugin | `fetch` |
|
||||
| Pi / OMP | bundled in-process extension (`src/main/pi/agent-status-extension-source.ts`) | `fetch`, now with the WSL curl.exe fallback |
|
||||
|
||||
All of them target `127.0.0.1`.
|
||||
|
||||
## Status quo + why this gates the hooks-only sidebar
|
||||
|
||||
Today the worktree-card rows still have a title-derived fallback producer
|
||||
(`src/renderer/src/components/sidebar/worktree-title-derived-agent-rows.ts`), so WSL users
|
||||
DO currently see rows for title-rich agents (Claude `✳`/spinner titles, Gemini glyphs) —
|
||||
degraded (generic text, no prompt/last-message preview, no notifications) but present.
|
||||
Title-poor agents are dark (Codex — hence GH `6907`). When the hooks-only change removes
|
||||
that producer, **every non-OMP agent in a WSL worktree loses its card row entirely until
|
||||
this work ships**. Hook fidelity adds: prompt + last-assistant-message previews,
|
||||
waiting/blocked precision, completion notifications, AI Vault / native chat session
|
||||
integration.
|
||||
|
||||
## Solution design — WSL relay + WSL-side installation
|
||||
|
||||
### Transport (Gap A): guest-resident relay, host-owned stdio
|
||||
|
||||
Run a small receiver **inside WSL on WSL's own loopback, listening on the very port the
|
||||
clients were already given** (`$ORCA_AGENT_HOOK_PORT` — free inside WSL, since that port
|
||||
only exists on the Windows side). Unmodified clients then deliver successfully with
|
||||
**zero client changes**; the reporter's diagnostic relay in GH `7565` proved this shape
|
||||
live. Forward each parsed envelope to the Windows host over the relay's **own stdio**
|
||||
(Orca spawns it via `wsl.exe`, so it owns that pipe). Ingest through the existing trust
|
||||
boundary: `agentHookServer.ingestRemote` (`src/main/agent-hooks/server.ts`), envelope
|
||||
shape `src/shared/agent-hook-relay.ts` — identical to the SSH relay, which runs a
|
||||
loopback-only receiver on the remote box and forwards over the SSH control channel.
|
||||
|
||||
**Port binding.** Bind the inherited `$ORCA_AGENT_HOOK_PORT` first — it keeps every
|
||||
already-crossed coordinate (env and the `/p`-translated endpoint file) truthful with zero
|
||||
divergence. On `EADDRINUSE` inside the guest, fall back to the SSH relay's own pattern:
|
||||
bind `127.0.0.1:0`, write a **WSL-side endpoint file**, and point WSL PTYs'
|
||||
`ORCA_AGENT_HOOK_ENDPOINT` at it (clients already prefer endpoint-file coords over env).
|
||||
The relay writes that WSL-side endpoint file in **both** modes so restart re-coordination
|
||||
never depends on `/mnt/c` translation being readable.
|
||||
|
||||
Lifecycle: one relay per distro **per Orca instance** (concurrent instances have distinct
|
||||
ports, so guest listeners never collide); **ensure** — not just start — whenever a WSL PTY
|
||||
exists: first spawn *and* daemon-PTY reattach after an Orca restart (WSL PTYs survive in
|
||||
the daemon; the new instance has a new port + token and must respawn the relay before
|
||||
surviving agents re-coordinate). The relay **exits when its stdin closes**: a lingering
|
||||
guest listener would let WSL's own Windows→WSL forwarder grab the freed Windows-side port
|
||||
and blackhole stale Windows-side hook posts. Restart if WSL restarts; token still
|
||||
validated at the relay's HTTP receiver; harmless under mirrored networking (bind
|
||||
fallback) and inert on non-WSL platforms (ensure only fires from WSL PTY spawns).
|
||||
|
||||
Reliability contract (invariant class `agent-session.hook-transport`): hook clients are
|
||||
fail-open silent, so the relay must not be — spawn failures, `EADDRINUSE` fallback, and
|
||||
forward errors each leave a diagnosable breadcrumb; the `wsl.exe` "Catastrophic failure
|
||||
(E_UNEXPECTED)" retry is **bounded** with backoff, never a spawn loop. Oracle: provider-
|
||||
contract tests with fault injection (stdin close → exit, occupied port → fallback + file
|
||||
rewrite, envelope round-trip to `ingestRemote`) rather than end-to-end flows only.
|
||||
|
||||
Design notes from a survey of comparable WSL-capable tools (kept nameless per policy):
|
||||
- Guest-resident component + host-owned channel + guest-side installation, explicitly
|
||||
reusing the tool's SSH-remote machinery, **is the established pattern**. No surveyed
|
||||
tool makes guest processes dial back to a Windows-localhost listener — the merged OMP
|
||||
curl.exe stopgap is the outlier as a primary path (but see the round-4 revised
|
||||
stance below: it survives as the no-node fallback).
|
||||
- Prefer host-owned **stdio** over Windows→WSL localhost port forwarding (wslhost
|
||||
forwarding is known-flaky under load; one surveyed tool dials the distro vNIC IP just to
|
||||
avoid it — stdio sidesteps the question entirely).
|
||||
- WSL offers no persistent control channel between separate `wsl.exe` invocations —
|
||||
collapse the relay's ensure-installed + launch into **one idempotent script per spawn**.
|
||||
- Install into the guest from inside the guest (download/extract in WSL) or stream the
|
||||
binary through `wsl.exe` stdin — not by copying through `/mnt/c`.
|
||||
|
||||
### Installation (Gap B): WSL-side hook installers
|
||||
|
||||
Write agent hook configs/scripts into the WSL-side home, per agent, analogous to the SSH
|
||||
remote installers — via `wsl.exe`-executed scripts (preferred, mirrors SSH most closely)
|
||||
or `\\wsl.localhost\<distro>\...` writes. Without this half, the relay receives nothing:
|
||||
the hook clients themselves are absent from the WSL filesystem.
|
||||
|
||||
## Alternatives considered (and why not)
|
||||
|
||||
1. **Endpoint-file host/URL field** — the file already crosses into WSL (`/p`-translated),
|
||||
but clients read only PORT/TOKEN and hardcode the host, so all ~13 still need edits;
|
||||
and a WSL-reachable listener bind breaks the loopback-only posture (LAN exposure,
|
||||
firewall prompts).
|
||||
2. **Replicate the curl.exe bridge per client** — the shell clients share ~2 generated
|
||||
builders so it is cheaper than it sounds, but it is N point fixes, requires WSL interop
|
||||
enabled (`/etc/wsl.conf` can disable it), pays a per-event process spawn (load-sensitive,
|
||||
see validation facts), and keeps the ecosystem-outlier direction.
|
||||
3. **Listener-side bind changes / rely on mirrored networking** — posture conflict /
|
||||
opt-in only.
|
||||
4. **OSC 9999 in-band status** (`src/shared/agent-status-osc.ts`, parsed per-pane in
|
||||
`pty-transport.ts` and `orca-runtime.ts`) — zero-network and pane-attributed, but only
|
||||
viable for in-process clients and carries status payloads, not the full hook event
|
||||
vocabulary (prompts, tools, completion) — cannot replace the pipeline.
|
||||
|
||||
## Facts + gotchas from the 2026-07-08 Windows-rig validation
|
||||
|
||||
- curl.exe interop delivery works under NAT (shipped for OMP), but per-event process spawn
|
||||
is load-sensitive: `--connect-timeout 0.5` dropped 3/3 events to a *healthy* listener
|
||||
under load; fine at 3s. A resident relay avoids per-event spawns entirely.
|
||||
- `wslinfo --networking-mode` distinguishes NAT vs mirrored.
|
||||
- Clients prefer endpoint-FILE coords over env. Testing gotcha: unset
|
||||
`ORCA_AGENT_HOOK_ENDPOINT` in synthetic tests or events go to the real running app.
|
||||
- Server ingest silently drops paneKeys that are not `uuid:uuid`-shaped — use real-shaped
|
||||
keys in synthetic validation.
|
||||
- OMP is a Bun single-file binary; Bun's `node:child_process`/`fetch` compat held. Other
|
||||
in-process clients run inside their agents' runtimes — verify per runtime.
|
||||
- Environmental: fresh WSL 2.7.10 intermittently threw "Catastrophic failure
|
||||
(E_UNEXPECTED)" from `wsl.exe -d <distro> -- bash -lc` under concurrent spawn load
|
||||
(cleared by `wsl --terminate`). The relay spawn path should tolerate/retry this.
|
||||
- Fork-PR CI runs sit in `action_required` until approved:
|
||||
`gh api repos/stablyai/orca/actions/runs/<id>/approve -X POST`.
|
||||
|
||||
## Acceptance
|
||||
|
||||
On a default-config Windows 11 + WSL2 **NAT** machine: launch **Codex or Claude**
|
||||
(explicitly not OMP) in a WSL worktree → live hook-driven worktree-card row with status
|
||||
transitions and a completion notification; hook listener still bound to Windows loopback
|
||||
only; zero per-client transport changes; hooks installed WSL-side automatically (no manual
|
||||
config); harmless under mirrored networking and inert on non-WSL platforms. After an Orca
|
||||
restart with the WSL agent still running (daemon-surviving PTY), status events resume
|
||||
without relaunching the agent.
|
||||
|
||||
## 2026-07-09 Windows-rig validation follow-ups
|
||||
|
||||
The first live GUI run proved every mechanism in isolation but failed end-to-end, yielding
|
||||
two fixes:
|
||||
|
||||
1. **Link death must be handled, not just child death.** A mux protocol error or timeout
|
||||
can kill the host↔guest link while the guest process (and its 204-returning receiver)
|
||||
stays alive — the exact observed signature: hooks POST 204, store never populates.
|
||||
`wsl-hook-relay-link.ts` now guarantees exactly-once death handling from either signal;
|
||||
the manager breadcrumbs it, kills the child, and self-restarts after a short cooldown
|
||||
(a live agent session produces no new PTY spawns to re-trigger ensure).
|
||||
`ORCA_WSL_HOOK_RELAY_DEBUG=1` traces every received envelope pre-ingest so a live rig
|
||||
can pinpoint any residual drop. The full host chain is pinned by a live integration
|
||||
test (real bundle over real child stdio through the real manager into a real
|
||||
`ingestRemote`).
|
||||
2. **(Round 2) The renderer's SSH-era ownership gate dropped `wsl:*` events.** With the
|
||||
link fixed, envelopes reached `ingestRemote` and the durable cache, but
|
||||
`useIpcEvents.applyAgentStatus` compares the stamped connectionId against the owning
|
||||
repo's — `"wsl:<distro>" !== null` for a local repo, so every WSL-relayed status died
|
||||
before `setAgentStatus`/notifications. Fix: `wsl:*` ids are transport provenance, not
|
||||
ownership — the gate normalizes them to local (null) via
|
||||
`isWslHookRelayConnectionId`, while still rejecting WSL-stamped events against
|
||||
SSH-owned repos. Provenance stays stamped (it made the drop diagnosable in the first
|
||||
place).
|
||||
3. **Codex reads a redirected home.** Orca launches WSL Codex with `CODEX_HOME` pointed at
|
||||
the managed runtime home (`~/.local/share/orca/codex-runtime-home/home`), so installing
|
||||
hooks to `~/.codex` left Codex dark. The installers now accept an explicit codex home;
|
||||
the trust write into `config.toml` is deferred while that file doesn't exist (the
|
||||
launch path seeds it only-if-absent — creating it first would cancel the seed), and the
|
||||
manager re-runs the idempotent installers on later ensures (throttled) to upsert trust
|
||||
once the seed lands. Consequence: the very first WSL Codex session after a cold relay
|
||||
may miss hooks; the next one has them.
|
||||
|
||||
## 2026-07-09 adversarial-review hardening (pre-rig round 3)
|
||||
|
||||
Four independent review lenses over the full diff; confirmed findings fixed:
|
||||
|
||||
- **Endpoint identity (all 4 reviewers)**: the guest endpoint dir was keyed by the
|
||||
ephemeral Windows hook port, so a daemon-surviving agent kept sourcing the DEAD
|
||||
`port-P1` file after an Orca restart — breaking the restart-resume acceptance criterion
|
||||
and regressing shipped OMP recovery. Now keyed by a restart-stable instance key
|
||||
(hash of the Windows endpoint file path = userData + namespace, crossed via
|
||||
`ORCA_WSL_HOOK_INSTANCE`): the restarted instance's relay REWRITES the same file, which
|
||||
is exactly what re-coordinates survivors.
|
||||
- **Restart policy**: every failure now arms the restart timer (one failed relaunch no
|
||||
longer ends self-recovery), and the timer probes `wsl --list --running` first — `wsl -d`
|
||||
BOOTS a stopped distro, so recovery must never resurrect a VM the user shut down; a
|
||||
stopped distro's state is dropped instead (next WSL terminal re-ensures). Failure
|
||||
counters only reset after 2 min of stable uptime, so connect-then-die loops escalate to
|
||||
the 10-min cap instead of cycling every 10s.
|
||||
- **Install-dir versioning**: the guest install dir is namespaced by bundle version, so
|
||||
concurrent Orca instances with different bundles (dev + prod) never reinstall over each
|
||||
other; tmp files carry the guest PID. The install spawn also gained the 30s timeout it
|
||||
was missing (a wedged wsl.exe could previously pin the state machine at 'starting'
|
||||
forever).
|
||||
- **Guest node resolution**: candidates (PATH, nvm glob, fixed paths) are each
|
||||
version-probed, first pass wins — an apt node 12 on PATH no longer masks an nvm node 20
|
||||
into a false "no node >= 18" 10-minute cooldown.
|
||||
- **wsl.exe text handling**: `WSL_UTF8=1` on all spawns + NUL-stripping on stderr, so the
|
||||
"Catastrophic failure" transient-retry matcher and breadcrumbs survive UTF-16LE output.
|
||||
- Smaller: ordered post-sentinel chunk handoff (frame-decoder desync race), port-fallback
|
||||
breadcrumb now reaches host logs via the home handshake, bad home reply fails the
|
||||
connect (was: silently 'running' without installs), missing-bundle warn-once, distro
|
||||
map keys case-normalized, `disposeAll` wired to app `will-quit`, single-spawn Codex
|
||||
trust catch-up via a one-shot 60s reinstall timer.
|
||||
|
||||
Accepted gaps (reviewed, deliberately not addressed here): old version-namespaced
|
||||
install dirs accrete across upgrades (~200KB each); an outdated running daemon
|
||||
/p-translates the guest endpoint path until it restarts (hook scripts fall back to env
|
||||
coords, which same-port binding keeps correct); default-distro resolution caches the
|
||||
first non-empty answer for the app run.
|
||||
|
||||
`wslDistroCache` no longer caches a transient empty list for the app run — an empty
|
||||
result is re-probed after a short window, so a distro registered mid-session is picked
|
||||
up. `isWslAvailable` likewise re-probes instead of latching a failure.
|
||||
|
||||
## 2026-07-09 round-4 external adversarial review
|
||||
|
||||
A second adversarial sweep (five independent lenses: guest relay + fs bridge, host
|
||||
lifecycle state machine, app integration + renderer gate, design-vs-alternatives, and a
|
||||
platform fact-check of every WSL claim). Design verdict: the guest-resident relay over
|
||||
host-owned stdio is the right architecture — the zero-per-client-change chokepoint is
|
||||
what the curl.exe alternative cannot match, and the lifecycle weight is inherent to any
|
||||
guest-resident helper. Confirmed findings, all fixed on this branch:
|
||||
|
||||
- **`dropState` identity race (major)**: the recovery timer re-checked state identity
|
||||
only BEFORE the async `wsl --list --running` probe; an ensure() landing during the
|
||||
probe could get its fresh state deleted by key — orphaning a live relay child outside
|
||||
the map (unkillable by `disposeAll`, duplicate relay on next ensure). Fixed: identity
|
||||
re-check after the probe await + identity-guarded delete in the manager.
|
||||
- **Distro-running probe failed OPEN**: any probe error (including its 10s timeout)
|
||||
reported "running", so recovery could `wsl -d` — and thereby BOOT — a distro the user
|
||||
shut down, in exactly the wedged-wsl.exe failure mode where the probe errors. Now
|
||||
fails closed: drop the state; the next WSL PTY spawn re-ensures.
|
||||
- **Spawn form hardened to `--exec`**: `wsl.exe -- <cmd>` routes through the distro's
|
||||
default login shell (Microsoft docs: only `--exec` runs "without using the default
|
||||
Linux shell"), so a fish/nushell chsh could mangle the launch; `--exec sh -c`/-`s`
|
||||
bypasses it and passes argv verbatim (no `$`-preprocessing, escaping shim dropped) —
|
||||
same form as the Codex WSL login spawn.
|
||||
- **Post-sentinel handoff microtask**: pending chunks flushed synchronously inside the
|
||||
mux constructor, before the manager could register notification handlers — an
|
||||
envelope arriving in the trailing bytes dispatched to zero handlers (recovered only
|
||||
by the later replay request). Flush now rides a microtask: after the caller's
|
||||
synchronous wiring, still ahead of any subsequent stdout IO event.
|
||||
- **Relay process posture**: the guest relay now mirrors the SSH relay's
|
||||
`uncaughtException` (log + exit → manager respawns) / `unhandledRejection` (log +
|
||||
survive) handlers.
|
||||
- **Replay cache recency cap**: the WSL relay has no per-pane teardown signal, so the
|
||||
per-pane replay cache grew for the relay's lifetime; now capped at 256 panes,
|
||||
evicting longest-idle first (meta map kept in lockstep). Backstop for SSH too.
|
||||
- Smaller: guest launch script derives the stale-exit code from the shared contract
|
||||
constant (was a hardcoded 42 twin); one-shot reinstall timer refuses to arm after
|
||||
dispose; fs-bridge scope comment states the lexical (symlink-following) bound
|
||||
honestly. New oracles: sentinel unit suite (chunk splits, overflow kill, timeout,
|
||||
microtask handoff), fs-bridge scoping suite, 403 + fallback endpoint-file rewrite,
|
||||
cache-cap eviction, and the recovery/manager race regressions.
|
||||
|
||||
**Revised stance on the OMP curl.exe bridge — keep it, do not retire.** The relay
|
||||
requires node ≥ 18 in the distro; a fresh WSL Ubuntu ships none, Codex CLI is a native
|
||||
binary that brings none, and Claude Code's native installer no longer implies a system
|
||||
node. A distro running only Codex would hit the no-node cooldown and stay dark — the
|
||||
exact GH `6907` shape. The interop bridge is the one delivery path with no guest
|
||||
runtime requirement, so it stays as the documented no-node fallback (currently wired
|
||||
for OMP; extending it to the shared shell-script builders is the tracked follow-up if
|
||||
no-node distros show up in telemetry). The relay remains the primary path: resident
|
||||
(no per-event spawn cost) and interop-independent.
|
||||
|
||||
## Implementation map
|
||||
|
||||
- Guest: `src/relay/wsl-agent-hook-relay.ts` (entry; exits on stdin close),
|
||||
`src/relay/wsl-hook-fs-bridge.ts` (home-scoped fs RPCs for installs),
|
||||
`src/relay/agent-hook-server.ts` (`token`/`preferredPort` options + `EADDRINUSE`
|
||||
fallback). Bundled by `config/scripts/build-relay.mjs` → `out/relay/wsl/`.
|
||||
- Host: `src/main/agent-hooks/wsl-hook-relay-manager.ts` (per-distro state machine),
|
||||
`wsl-hook-relay-launch.ts` (bundle resolve, guest launch/install scripts, spawn env,
|
||||
sentinel wait), `wsl-hook-relay-link.ts` (envelope forward + exactly-once link-death
|
||||
handling), `wsl-hook-relay-deps.ts` (DI seam), `wsl-hook-fs-adapter.ts` (SFTP-shaped
|
||||
adapter + `installWslGuestHooks`, which targets Codex's managed runtime home).
|
||||
- Wiring: `buildPtyHostEnv` (`src/main/ipc/pty.ts`) ensures the relay on every WSL spawn
|
||||
and repoints `ORCA_AGENT_HOOK_ENDPOINT` at the guest endpoint file once known;
|
||||
`src/main/pty/wsl-orca-env.ts` picks `/u` vs `/p` by value shape.
|
||||
- Contract shared by both sides: `src/shared/wsl-hook-relay-contract.ts`.
|
||||
- Oracles: `src/relay/wsl-agent-hook-relay.test.ts`,
|
||||
`src/main/agent-hooks/wsl-hook-relay-manager.test.ts` (fault injection: stale-42
|
||||
reinstall, no-node-43 cooldown, bounded E_UNEXPECTED retry, exit re-ensure gating, and a
|
||||
full installer run against an in-memory guest).
|
||||
|
||||
## References
|
||||
|
||||
- GitHub: issues `6907` (Codex/WSL), `7091` + `7565` (OMP, fixed), `7563` (WSL CLI
|
||||
detection, adjacent); PRs `7642` + `7641` (OMP fixes), `7744` (SSH hook installers
|
||||
precedent), `7447` (title-collapse regression).
|
||||
- Linear: STA-1515 (this work; ticket comments carry the same context).
|
||||
- Key files: `src/main/agent-hooks/server.ts`, `src/shared/agent-hook-listener.ts`,
|
||||
`src/shared/agent-hook-relay.ts`, `src/relay/agent-hook-server.ts`, `src/relay/relay.ts`,
|
||||
`src/main/pty/wsl-orca-env.ts`, `src/main/agent-hooks/installer-utils.ts`,
|
||||
`src/main/pi/agent-status-extension-source.ts`, `src/main/ssh/ssh-relay-session.ts`,
|
||||
`src/main/providers/windows-shell-args.ts`, `src/shared/wsl-login-shell-command.ts`.
|
||||
@@ -1,96 +0,0 @@
|
||||
# Android Emulation — Live Pane Streaming
|
||||
|
||||
The Android **control** path (device list, boot, tap/type/buttons/rotate/exec,
|
||||
install/launch/permissions/ax/logcat) is complete and unit-tested. This document
|
||||
covers the **live H.264 video pane** (scrcpy + WebCodecs), which requires the
|
||||
Android SDK, a running AVD, the bundled `scrcpy-server.jar`, and Electron's
|
||||
WebCodecs runtime for end-to-end validation.
|
||||
|
||||
## What is built (committed)
|
||||
|
||||
| Module | Tested | Notes |
|
||||
|---|---|---|
|
||||
| `android/scrcpy-control-protocol.ts` | ✅ unit | Byte-exact control encoders (touch/key/text/back). |
|
||||
| `android/scrcpy-video-frame-parser.ts` | ✅ unit | scrcpy v2.4 codec-meta + frame-header parsing. |
|
||||
| `android/scrcpy-server-deploy.ts` | ✅ unit | push / forward / server-start arg builders. |
|
||||
| `android/scrcpy-stream-session.ts` | live-validated | Owns the server process + video/control sockets. |
|
||||
| `emulator/scrcpy-video-registry.ts` | ✅ unit | Pub/sub bridging a session to renderer subscribers. |
|
||||
| `ipc/emulator-video-stream.ts` | registration tested | `emulator:videoStream*` IPC; registered in `register-core-handlers`. |
|
||||
| `emulator-pane/use-emulator-video-stream.ts` | live-validated | WebCodecs `VideoDecoder` → `<canvas>`. |
|
||||
|
||||
## Current wiring
|
||||
|
||||
### 1. `scrcpy-server.jar`
|
||||
|
||||
The version-pinned server jar must match `SCRCPY_SERVER_VERSION` in
|
||||
`scrcpy-server-deploy.ts`. Runtime resolution checks the packaged resource and a
|
||||
development fallback.
|
||||
|
||||
### 2. `AndroidEmulatorBackend.startSession`
|
||||
|
||||
`startSession` ensures the target is booted, resolves the bundled server jar,
|
||||
starts `ScrcpyStreamSession`, and feeds `scrcpyVideoRegistry`. A
|
||||
`createStreamSession` option lets unit tests inject a fake because the real
|
||||
session does socket I/O.
|
||||
|
||||
```ts
|
||||
async startSession(deviceId: string): Promise<EmulatorSessionInfo> {
|
||||
const serial = await this.ensureBooted(deviceId)
|
||||
const jar = resolveScrcpyServerJar()
|
||||
if (!jar) {
|
||||
throw new EmulatorError('emulator_helper_failed', 'scrcpy-server.jar not bundled (see docs/android-emulation-streaming.md).')
|
||||
}
|
||||
const session = await (this.createStreamSession ?? ScrcpyStreamSession.start)(
|
||||
{ runner: this.runner, sdk: this.requireSdk(), serial, localJarPath: jar, maxSize: 1024 },
|
||||
{
|
||||
onMeta: (meta) => scrcpyVideoRegistry.pushMeta(serial, meta),
|
||||
onFrame: (f) => scrcpyVideoRegistry.pushFrame(serial, { config: f.config, keyFrame: f.keyFrame, pts: String(f.pts), bytes: toArrayBuffer(f.data) }),
|
||||
onError: () => scrcpyVideoRegistry.stop(serial),
|
||||
onClose: () => scrcpyVideoRegistry.stop(serial)
|
||||
}
|
||||
)
|
||||
scrcpyVideoRegistry.register(serial, () => session.close())
|
||||
this.streamSessions.set(serial, session)
|
||||
return { deviceUdid: serial, streamUrl: `scrcpy://${serial}`, wsUrl: '', streamCodec: 'h264' }
|
||||
}
|
||||
```
|
||||
|
||||
`stopHelperForDevice(serial)` stops the registry and closes the stored session.
|
||||
|
||||
### 3. Low-latency input via the scrcpy control socket (optional refinement)
|
||||
|
||||
Input already works via `adb shell input`. For smooth multi-touch, when a live
|
||||
session exists, route `tap`/`gesture` through `session.sendControl(...)` using the
|
||||
encoders in `scrcpy-control-protocol.ts` (convert normalized coords →
|
||||
device pixels with `android-input-mapping`, then `encodeInjectTouchEvent`).
|
||||
|
||||
### 4. Preload + pane
|
||||
|
||||
- **Preload** (`src/preload/...` emulator API): exposes `startVideoStream`,
|
||||
`stopVideoStream`, `onVideoStreamMeta`, `onVideoStreamFrame` wrapping the
|
||||
`emulator:videoStream*` channels (mirror the existing `startFrameStream` etc.).
|
||||
- **Pane** (`emulator-screen-stream-content.tsx`): when
|
||||
`session.streamCodec === 'h264'`, renders the `<canvas>` from
|
||||
`useEmulatorVideoStream(deviceId, enabled)` instead of the MJPEG `<img>`.
|
||||
- **Hardware buttons** (`emulator-phone-hardware-buttons.tsx`): includes Android
|
||||
variants (Back, Home, Recents, Power, Volume) selected by backend kind, per
|
||||
`docs/STYLEGUIDE.md`.
|
||||
|
||||
### 5. Validate on hardware
|
||||
|
||||
```sh
|
||||
pnpm build:cli
|
||||
# boot an AVD (Android Studio or `emulator @<avd>`), then:
|
||||
orca-dev emulator devices --json # see the device
|
||||
orca-dev emulator tap 0.5 0.8 --device <serial> # control works today
|
||||
# after wiring §2/§4: open the emulator pane and confirm the live frame + taps.
|
||||
```
|
||||
|
||||
## Risks to validate first
|
||||
|
||||
- **WebCodecs H.264 in Electron**: confirm `VideoDecoder.isConfigSupported({ codec: 'avc1.640028' })`. If unsupported, fall back to a wasm decoder (Broadway/tinyh264) or a main-process H.264→JPEG transcode into the existing MJPEG channel — neither changes the backend interface (it advertises the codec).
|
||||
- **scrcpy server protocol/version**: the option set + handshake in
|
||||
`scrcpy-server-deploy.ts` / `scrcpy-stream-session.ts` are pinned to v2.4 and
|
||||
must match the bundled jar.
|
||||
- **Annex-B vs avcC**: the renderer configures the decoder without a description
|
||||
(Annex-B). If frames don't decode, extract the avcC from the config packet.
|
||||
@@ -1,376 +0,0 @@
|
||||
# Android Emulation
|
||||
|
||||
## Problem
|
||||
|
||||
Orca ships a built-in mobile emulator surface (live pane + `orca emulator` CLI +
|
||||
agent skill), but it is **iOS Simulator only and macOS only**:
|
||||
|
||||
- `src/main/emulator/emulator-availability.ts:32` hard-returns "unavailable" for
|
||||
any `platform() !== 'darwin'`, so Windows and Linux users get nothing.
|
||||
- The backend (`src/main/emulator/emulator-bridge.ts`) is wired directly to
|
||||
`serve-sim` (`serve-sim-*.ts`) and `xcrun simctl`
|
||||
(`simctl-simulator-devices.ts`), both Apple-only tooling.
|
||||
|
||||
Android emulators run on Windows, Linux, and macOS via the Android SDK that
|
||||
Android Studio installs. We want Android emulation as a first-class peer of the
|
||||
iOS feature: full AVD lifecycle management, a live ~60fps pane, the full
|
||||
tap/gesture/type/button/rotate control surface, accessibility tree, app
|
||||
install/launch, runtime permissions, logcat, plus a dedicated
|
||||
`orca-emulator-android` agent skill.
|
||||
|
||||
## Current architecture (what we reuse vs. replace)
|
||||
|
||||
The existing stack already separates a backend from everything above it. The
|
||||
renderer pane, session registry, RPC/CLI shape, and tab system are effectively
|
||||
**backend-agnostic** and are reused unchanged:
|
||||
|
||||
- **Frame transport is main-owned.** `src/main/ipc/emulator-frame-stream.ts:40`
|
||||
runs the MJPEG socket in the main process and forwards raw JPEG bytes to the
|
||||
renderer over `emulator:frameStreamFrame`. The renderer
|
||||
(`src/renderer/src/components/emulator-pane/use-emulator-frame-stream.ts:74`)
|
||||
just wraps each frame in a `Blob`/`<img>`. The renderer is a **frame
|
||||
consumer**, decoupled from the source.
|
||||
- **Per-worktree "active emulator"** lives in
|
||||
`src/main/emulator/emulator-session-registry.ts` (like the active browser
|
||||
tab). Backend-agnostic.
|
||||
- **RPC** is declared in `src/main/runtime/rpc/methods/emulator.ts` and
|
||||
implemented in `src/main/runtime/orca-runtime-emulator.ts`.
|
||||
- **CLI** is `src/cli/specs/emulator.ts` + `src/cli/handlers/emulator.ts`.
|
||||
- **Pane** is `src/renderer/src/components/emulator-pane/**` (~50 files).
|
||||
|
||||
What is iOS-bound and needs an Android sibling:
|
||||
|
||||
- Device management: `xcrun simctl` → `adb` / `emulator` / `avdmanager`.
|
||||
- Streaming helper: `serve-sim` (MJPEG/H.264 over HTTP+WS) → `scrcpy-server.jar`
|
||||
(H.264 + control over adb-forwarded sockets).
|
||||
- Input: serve-sim normalized-coord WS → adb-backed Android input commands.
|
||||
- Availability gate: darwin-only → SDK-present on any OS.
|
||||
|
||||
## Goals
|
||||
|
||||
- Android emulation on **Windows, Linux, and macOS** (macOS users choose iOS or
|
||||
Android in the same pane).
|
||||
- **Full AVD lifecycle**: discover installed AVDs via the SDK, boot/shutdown
|
||||
them from Orca, and attach to already-running emulators + physical `adb`
|
||||
devices.
|
||||
- **Live ~60fps pane** via scrcpy H.264 decoded in the renderer with WebCodecs.
|
||||
- Control parity: tap, swipe/gesture, type, hardware buttons (Back, Home,
|
||||
Recents, Power, Volume), rotate.
|
||||
- Extra capabilities: accessibility tree (`uiautomator dump`), app
|
||||
install/launch (`adb install` / `am start`), runtime permissions
|
||||
(`pm grant/revoke/reset`), logcat capture.
|
||||
- A dedicated `skills/orca-emulator-android/SKILL.md`.
|
||||
|
||||
## Non-goals (v1)
|
||||
|
||||
- Camera/sensor injection (the Android emulator's virtual-scene path is a much
|
||||
larger problem than serve-sim's iOS camera injection; defer).
|
||||
- Remote/SSH device control (matches the current iOS limitation; emulator
|
||||
hardware is local).
|
||||
- Wear OS / Android TV / Automotive form factors.
|
||||
- Migrating the iOS backend to H.264 (the interface allows it later; not done
|
||||
now).
|
||||
|
||||
## Design
|
||||
|
||||
### Extract an `EmulatorBackend` interface; make the bridge a router
|
||||
|
||||
Today `EmulatorBridge` *is* the iOS implementation. Refactor it into a thin
|
||||
router over a backend interface so iOS and Android share the session registry,
|
||||
RPC/CLI shape, frame IPC, and tab system. This is the only change to existing
|
||||
iOS behavior, and it is a pure extraction (no semantic change).
|
||||
|
||||
New module `src/main/emulator/backends/emulator-backend.ts`:
|
||||
|
||||
```ts
|
||||
export type EmulatorBackendKind = 'ios' | 'android'
|
||||
export type EmulatorStreamCodec = 'mjpeg' | 'h264'
|
||||
|
||||
export type EmulatorDevice = {
|
||||
backend: EmulatorBackendKind
|
||||
id: string // opaque: simulator UDID, adb serial, or AVD name
|
||||
name: string
|
||||
state: 'shutdown' | 'booting' | 'booted'
|
||||
kind?: string // form factor / api level, display only
|
||||
isAvailable: boolean
|
||||
}
|
||||
|
||||
export type EmulatorBackendCapabilities = {
|
||||
install: boolean
|
||||
launch: boolean
|
||||
permissions: boolean
|
||||
accessibilityTree: boolean
|
||||
logcat: boolean
|
||||
}
|
||||
|
||||
export interface EmulatorBackend {
|
||||
readonly kind: EmulatorBackendKind
|
||||
readonly capabilities: EmulatorBackendCapabilities
|
||||
isSupportedOnHost(): boolean
|
||||
checkAvailability(): Promise<BackendAvailability>
|
||||
listDevices(): Promise<EmulatorDevice[]>
|
||||
bootDevice(id: string): Promise<EmulatorDevice>
|
||||
startSession(id: string): Promise<EmulatorSessionInfo> // includes streamCodec
|
||||
tap(id, x, y): Promise<void>
|
||||
gesture(id, points): Promise<void>
|
||||
type(id, text): Promise<void>
|
||||
button(id, name): Promise<void>
|
||||
rotate(id, orientation): Promise<void>
|
||||
exec(id, command): Promise<unknown>
|
||||
// capability-gated:
|
||||
installApp?(id, path): Promise<void>
|
||||
launchApp?(id, pkg, activity?): Promise<void>
|
||||
setPermission?(id, op): Promise<void>
|
||||
accessibilityTree?(id): Promise<unknown>
|
||||
logcat?(id, opts): Promise<...>
|
||||
stopSession(id): Promise<void>
|
||||
kill(id): Promise<void>
|
||||
shutdown(id): Promise<void>
|
||||
}
|
||||
```
|
||||
|
||||
- `src/main/emulator/backends/ios-emulator-backend.ts` — the existing serve-sim
|
||||
+ simctl logic extracted from `EmulatorBridge`, implementing the interface
|
||||
with `kind: 'ios'`, `streamCodec: 'mjpeg'`, and capabilities mapped to what
|
||||
serve-sim already supports.
|
||||
- `src/main/emulator/backends/android-emulator-backend.ts` — new, orchestrates
|
||||
the Android modules below with `kind: 'android'`, `streamCodec: 'h264'`.
|
||||
- `EmulatorBridge` keeps its public method names (so RPC/runtime callers don't
|
||||
churn) but becomes a router: it holds the available backends, resolves which
|
||||
backend owns a given device/session (via the session registry's recorded
|
||||
`backend` tag, or by probing `listDevices()` for an unknown id), and
|
||||
delegates. The session registry record gains a `backend: EmulatorBackendKind`
|
||||
field; `EmulatorSessionInfo` gains `streamCodec`. The existing `deviceUdid`
|
||||
field is retained as the opaque `id` to preserve wire-compat across the
|
||||
renderer and CLI.
|
||||
|
||||
### New Android modules — `src/main/emulator/android/`
|
||||
|
||||
Each module is small and single-purpose with a co-located `.test.ts`, matching
|
||||
the existing `serve-sim-*` / `simctl-*` granularity (no file approaches the
|
||||
`max-lines` limit):
|
||||
|
||||
- `android-sdk-discovery.ts` — resolve the SDK root and the `adb` / `emulator` /
|
||||
`avdmanager` binaries from `ANDROID_HOME`, then `ANDROID_SDK_ROOT`, then per-OS
|
||||
defaults: `%LOCALAPPDATA%\Android\Sdk` (Windows), `~/Library/Android/sdk`
|
||||
(macOS), `~/Android/Sdk` (Linux). All paths via `path.join`.
|
||||
- `adb-devices.ts` — `adb devices -l`, resolve serial, `wait-for-device` +
|
||||
`getprop sys.boot_completed` poll, and `wm size` for the device resolution.
|
||||
- `avd-manager.ts` — `emulator -list-avds`, boot an AVD via a detached
|
||||
`emulator @<name>` spawn, shut down via `adb -s <serial> emu kill`.
|
||||
- `scrcpy-server-deploy.ts` — push the version-pinned `scrcpy-server.jar`, start
|
||||
it via `app_process`, and set up the `adb forward` tunnel(s).
|
||||
- `scrcpy-stream-session.ts` — owns the server process, adb tunnel, and video
|
||||
socket lifecycle.
|
||||
- `scrcpy-video-frame-parser.ts` — read the video socket, parse scrcpy frame headers
|
||||
(PTS + length), and emit H.264 access units plus the codec config (SPS/PPS).
|
||||
- `scrcpy-control-protocol.ts` — encode scrcpy control messages (touch
|
||||
down/move/up with pointer id + pressure, inject keycode, inject UTF-8 text,
|
||||
scroll, set screen power, rotate, clipboard) for a future low-latency input path.
|
||||
- `android-input-mapping.ts` — convert normalized 0–1 ↔ device pixels using the
|
||||
live frame size; map button names → Android keycodes (BACK=4, HOME=3,
|
||||
APP_SWITCH=187, POWER=26, VOLUME_UP=24, VOLUME_DOWN=25).
|
||||
- `android-input-commands.ts` — current adb-backed tap/type/button/rotate/gesture
|
||||
command construction.
|
||||
- `uiautomator-tree.ts` — `adb shell uiautomator dump` → parsed XML tree.
|
||||
- `android-app-control.ts` — `adb install <apk>`, `am start` package/activity.
|
||||
- `android-permissions.ts` — `pm grant` / `revoke` / `reset`.
|
||||
- `android-logcat.ts` — tail/filter `adb logcat` with bounded buffering.
|
||||
- `android-availability.ts` — SDK present? AVDs + connected devices list, with
|
||||
clear, surfaced messages (mirroring the iOS availability message style).
|
||||
|
||||
### Streaming & control data flow
|
||||
|
||||
**Control currently uses `adb shell input` commands.** Coordinates stay
|
||||
normalized 0–1 at every public boundary (CLI, RPC, renderer); the Android backend
|
||||
maps them to device pixels before issuing adb-backed tap/gesture/button commands.
|
||||
The scrcpy control protocol encoders are present for a future low-latency input
|
||||
path, but video streaming does not require that path.
|
||||
|
||||
**Video path (H.264 → renderer WebCodecs):**
|
||||
|
||||
1. `android-emulator-backend.startSession()` deploys + starts scrcpy-server,
|
||||
opens the video + control sockets, and returns `EmulatorSessionInfo` with
|
||||
`streamCodec: 'h264'`.
|
||||
2. `scrcpy-video-stream.ts` reads access units and the SPS/PPS config and pushes
|
||||
them over a **new IPC channel** `emulator:videoStream{Start,Config,Frame,Stop}`
|
||||
(a sibling of the existing `emulator:frameStream*`), keyed by stream id.
|
||||
3. New renderer hook
|
||||
`src/renderer/src/components/emulator-pane/use-emulator-video-stream.ts`
|
||||
feeds the access units to a WebCodecs `VideoDecoder`, drawing decoded
|
||||
`VideoFrame`s to a `<canvas>`.
|
||||
4. `src/renderer/src/components/emulator-pane/emulator-screen-stream-content.tsx`
|
||||
branches on `session.streamCodec`: `mjpeg` keeps today's `<img>` path
|
||||
untouched; `h264` uses the canvas path. No iOS behavior changes.
|
||||
|
||||
## Coordinate & input mapping
|
||||
|
||||
- Public API (CLI/RPC/pane gestures) stays normalized 0–1, top-left origin, as
|
||||
the iOS path already mandates.
|
||||
- `android-input-mapping.ts` multiplies by the current device display size before
|
||||
adb input commands are built. Rotation changes the effective frame size; the
|
||||
mapper reads the current size each gesture rather than caching.
|
||||
- Hardware buttons: adb keyevents inject keycodes. Android adds
|
||||
**Back** and **Recents** (no iOS equivalent); the button name → keycode map
|
||||
and the renderer's hardware-button row gain Android variants.
|
||||
|
||||
## RPC + CLI surface
|
||||
|
||||
Extend `src/main/runtime/rpc/methods/emulator.ts`,
|
||||
`src/main/runtime/orca-runtime-emulator.ts`, `src/cli/specs/emulator.ts`, and
|
||||
`src/cli/handlers/emulator.ts`:
|
||||
|
||||
- `orca emulator list` gains a **platform column** and shows iOS + Android
|
||||
devices/AVDs together; device selection resolves the backend automatically
|
||||
(by recorded session tag, else by which backend's `listDevices()` owns the id).
|
||||
- Existing verbs (`attach`, `tap`, `gesture`, `type`, `button`, `rotate`,
|
||||
`exec`, `kill`, `shutdown`) route unchanged to the resolved backend.
|
||||
- New capability-gated verbs: `install`, `launch`, `permissions`, `ax`,
|
||||
`logcat`. On a backend lacking the capability they fail with a clear
|
||||
`emulator_unsupported` error rather than silently no-op.
|
||||
- Existing `--worktree` / `--device` targeting is unchanged.
|
||||
|
||||
## Renderer pane
|
||||
|
||||
- `src/renderer/src/components/emulator-pane/emulator-phone-hardware-buttons.tsx`
|
||||
→ Android variant (Back, Home, Recents, Power, Volume) selected by backend
|
||||
kind.
|
||||
- Android device bezel/frame + Android entries (and a "boot AVD" affordance) in
|
||||
the attach/list UI.
|
||||
- `MobileEmulatorAgentSetupGuide*` → Android prerequisites step (install Android
|
||||
Studio / SDK, set `ANDROID_HOME`).
|
||||
- Codec-aware stream content (the canvas path above).
|
||||
- All UI follows `docs/STYLEGUIDE.md`: existing tokens from
|
||||
`src/renderer/src/assets/main.css` and shadcn primitives in
|
||||
`src/renderer/src/components/ui/`; no new color/size/shadow values.
|
||||
- Shortcut labels and any new accelerators use the platform checks required by
|
||||
`AGENTS.md` (`CmdOrCtrl`, `⌘`/`Ctrl+`).
|
||||
|
||||
## Packaging & dependencies
|
||||
|
||||
- Bundle the single, version-pinned `scrcpy-server.jar` (~80 KB) as an app
|
||||
resource; wire it into `config/electron-builder.config.cjs` and
|
||||
`config/packaged-runtime-node-modules.cjs`. Pin the scrcpy version — the
|
||||
server protocol is coupled to the jar.
|
||||
- Do **not** bundle `adb` / `emulator` / `avdmanager` (large; Android Studio
|
||||
installs them). Discover them at runtime and surface a clear setup message if
|
||||
the SDK is absent.
|
||||
- No new runtime npm dependency is required for decode (WebCodecs is built into
|
||||
Electron's Chromium). The wasm-decoder fallback (see Risks) would add a dep
|
||||
only if the WebCodecs spike fails.
|
||||
|
||||
## Skill
|
||||
|
||||
New `skills/orca-emulator-android/SKILL.md`, mirroring
|
||||
`skills/orca-emulator/SKILL.md`:
|
||||
|
||||
- Prerequisites: Android Studio / SDK installed, `ANDROID_HOME` (or
|
||||
`ANDROID_SDK_ROOT`) set, at least one AVD or a connected device.
|
||||
- The `orca emulator ...` command table (shared CLI; Android examples).
|
||||
- Gotchas: Orca handles pixel ↔ normalized conversion (agents always pass 0–1);
|
||||
adb device/serial targeting; no camera injection in v1; scrcpy version
|
||||
coupling.
|
||||
- Cross-reference from the iOS skill's "When NOT to use" (which already
|
||||
anticipates an Android backend under the same namespace).
|
||||
- Register it the same way `orca-emulator` is registered.
|
||||
|
||||
## Availability & platform gating
|
||||
|
||||
`src/main/emulator/emulator-availability.ts` becomes an aggregator that asks
|
||||
each backend `isSupportedOnHost()` + `checkAvailability()`:
|
||||
|
||||
- iOS backend: supported only on `darwin` (unchanged behavior/messages).
|
||||
- Android backend: supported on any OS where the SDK is discoverable.
|
||||
- The combined result drives the pane's availability UI; Windows/Linux report an
|
||||
available mobile backend for the first time.
|
||||
|
||||
## Edge cases
|
||||
|
||||
- adb device in `offline` / `unauthorized` state → clear surfaced error, not a
|
||||
hang.
|
||||
- AVD boot timeout (cold boot can take minutes) → bounded wait with a
|
||||
cancel/error path; pane shows "booting".
|
||||
- SDK present but no AVDs and no devices → availability message points to "create
|
||||
an AVD in Android Studio".
|
||||
- Device rotates while a gesture is mid-flight → mapper re-reads frame size per
|
||||
event; no cached dimensions.
|
||||
- Multiple Android devices in one worktree → same "one active per worktree"
|
||||
model as iOS; explicit `--device <serial>` for the rest.
|
||||
- WebCodecs decoder error / key-frame loss → request a new keyframe from scrcpy
|
||||
and surface a transient "reconnecting" state (parity with the MJPEG reconnect
|
||||
in `mjpeg-frame-stream.ts`).
|
||||
- Windows path handling for the SDK and the pushed jar uses `path.join` only;
|
||||
never assume `/` or `\`.
|
||||
- App quit / pane close cleans up scrcpy-server, the adb tunnel, and (for managed
|
||||
AVDs) the emulator, mirroring `EmulatorBridge.onAppQuit()` /
|
||||
`destroyAllSessions()`.
|
||||
|
||||
## Test plan
|
||||
|
||||
Unit tests (co-located, node Vitest, matching the module's existing test
|
||||
density):
|
||||
|
||||
- `android-sdk-discovery` — env precedence + per-OS default paths (mock env/fs;
|
||||
assert Windows/macOS/Linux branches).
|
||||
- `adb-devices` — parse `adb devices -l` (booted, offline, unauthorized,
|
||||
physical), boot-complete polling.
|
||||
- `avd-manager` — parse `emulator -list-avds`, boot command construction.
|
||||
- `scrcpy-control-channel` — exact byte encoding of touch/key/text/scroll
|
||||
messages.
|
||||
- `android-input-mapping` — normalized↔pixel round-trips, rotation, keycode map.
|
||||
- `uiautomator-tree` — XML → tree parsing, including malformed input.
|
||||
- `android-availability` + `emulator-availability` aggregation — iOS-only,
|
||||
Android-only, both, neither.
|
||||
- backend router resolution in `emulator-bridge` — id → backend, unknown id,
|
||||
cross-backend isolation.
|
||||
|
||||
Integration tests mock `adb` / `emulator` and the scrcpy sockets the same way
|
||||
the iOS tests mock serve-sim (`serve-sim-*.test.ts`, `emulator-bridge.test.ts`).
|
||||
|
||||
Electron validation (manual, on a machine with the Android SDK):
|
||||
|
||||
- Boot an AVD from Orca; confirm the live pane streams and is responsive.
|
||||
- tap / swipe / type / Back / Home / Recents / rotate.
|
||||
- `ax`, `install` + `launch`, `permissions grant`, `logcat`.
|
||||
- Cross-platform smoke on Windows (primary driver) and macOS (iOS + Android
|
||||
coexistence).
|
||||
|
||||
## Risks / verify-first
|
||||
|
||||
- **Electron H.264 WebCodecs decode** — verify in a step-0 spike that an Electron
|
||||
renderer `VideoDecoder` decodes scrcpy's H.264. Electron ships proprietary
|
||||
codec decode, so this is expected to pass. Fallback if not: a wasm H.264
|
||||
decoder (Broadway / tinyh264) or dropping to a main-process H.264→JPEG
|
||||
transcode — **neither changes the backend interface**, since the session
|
||||
advertises its codec.
|
||||
- **scrcpy-server protocol is version-coupled** to the bundled jar (same class of
|
||||
risk as serve-sim's private SimulatorKit APIs). Pin the version; record it next
|
||||
to the bundled jar.
|
||||
- **adb/emulator environment variance** — offline/unauthorized devices, cold-boot
|
||||
timeouts, missing SDK. All handled via explicit, surfaced errors.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Step-0 spike: confirm WebCodecs H.264 decode in the Electron renderer.
|
||||
2. Extract the `EmulatorBackend` interface + `IosEmulatorBackend` (pure
|
||||
refactor); keep all iOS tests green.
|
||||
3. Android device management (`android-sdk-discovery`, `adb-devices`,
|
||||
`avd-manager`, `android-availability`) + availability aggregation; surface
|
||||
Android devices in `orca emulator list`.
|
||||
4. scrcpy streaming (`scrcpy-server-deploy`, `scrcpy-video-stream`) + the video
|
||||
IPC channel + the renderer WebCodecs canvas path; live pane renders.
|
||||
5. scrcpy control (`scrcpy-control-channel`, `android-input-mapping`) +
|
||||
tap/gesture/type/button/rotate end-to-end.
|
||||
6. Extra capabilities: `ax`, `install`/`launch`, `permissions`, `logcat`.
|
||||
7. Renderer polish: Android hardware buttons, bezel, setup guide.
|
||||
8. Packaging (`scrcpy-server.jar` resource) + the `orca-emulator-android` skill.
|
||||
9. Tests at each step; typecheck + lint; Electron validation on Windows + macOS.
|
||||
|
||||
## Open decisions
|
||||
|
||||
- Whether `orca emulator install`/`launch`/`logcat` should also be exposed for
|
||||
iOS later (iOS install is `xcrun simctl install`); v1 leaves them
|
||||
Android-only via capability flags.
|
||||
- Whether to expose an explicit `orca emulator boot <avd>` verb vs. folding boot
|
||||
into `attach`; initial version folds boot into `attach` (parity with iOS,
|
||||
which boots on attach) and adds a `--no-boot` opt-out.
|
||||
@@ -1,75 +0,0 @@
|
||||
# Automations Navigation Stack
|
||||
|
||||
## Problem
|
||||
|
||||
- `worktree-nav-history.ts` models view entries as `'tasks'` only; `'automations'` cannot be recorded or replayed.
|
||||
- `openTaskPage` records a view visit before switching view; `openAutomationsPage` does not.
|
||||
- `closeTaskPage` rewinds history index when closing from a `'tasks'` history node; `closeAutomationsPage` does not.
|
||||
- Keyboard history navigation already works on Automations (`Cmd/Ctrl+Alt+Arrow`), but titlebar Back/Forward is hidden there.
|
||||
- `setWorktreeNavViewActivator` is currently Tasks-sentinel oriented in types/comments and must be widened for Automations.
|
||||
|
||||
## Goal
|
||||
|
||||
Make Automations a first-class entry in the existing mixed worktree/page navigation stack, matching Tasks behavior for open, back/forward traversal, close-page rewind, and titlebar controls.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Do not add persistence for navigation history; the existing stack is session-only and renderer-local.
|
||||
- Do not preserve per-automation detail selection through Back/Forward beyond existing `selectedAutomationId` state.
|
||||
- Do not change Activity, Settings, Space, Skills, or terminal navigation behavior.
|
||||
- Do not add new shortcuts; reuse existing cross-platform `Cmd/Ctrl+Alt+Arrow` handling.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add explicit view-entry type.
|
||||
- `type WorktreeNavHistoryViewEntry = 'tasks' | 'automations'`.
|
||||
- `type WorktreeNavHistoryEntry = string | WorktreeNavHistoryViewEntry`.
|
||||
- Update `recordViewVisit`, `ViewActivateFn`, and `setWorktreeNavViewActivator` signatures accordingly.
|
||||
- Update `isLiveEntry` to treat both page sentinels as live.
|
||||
|
||||
2. Generalize history replay branch.
|
||||
- In `navigateToIndex`, dispatch page sentinels through `viewActivator(entry)` and worktree ids through `activator(id)`.
|
||||
- Keep page replay on `setActiveView(entry)` (not `openTaskPage`/`openAutomationsPage`) to avoid mutating `previousViewBefore*` and avoid appending history during replay.
|
||||
- Keep existing index semantics: update index only after successful activation path.
|
||||
|
||||
3. Record and close Automations like Tasks.
|
||||
- `openAutomationsPage`: call `recordViewVisit('automations')` before switching `activeView`.
|
||||
- `closeAutomationsPage`: if current history node is `'automations'`, rewind to `findPrevLiveWorktreeHistoryIndex(state)` when available; otherwise keep index unchanged.
|
||||
- This rewind must apply regardless of close trigger (Esc / header X / any direct `closeAutomationsPage` call site).
|
||||
|
||||
4. Align titlebar controls with shortcut scope.
|
||||
- Show titlebar Back/Forward when `activeView` is `terminal`, `tasks`, or `automations`.
|
||||
- Keep shortcut logic unchanged; it already includes Automations.
|
||||
|
||||
5. Tests.
|
||||
- `worktree-nav-history.test.ts`: add Automations sentinel coverage for replay path, adjacent dedupe, dead-worktree skip, and rewind/forward behavior.
|
||||
- `ui.test.ts`: add Automations open/close history-index parity tests with Tasks, including “only automations in history” no-op rewind.
|
||||
- `App.tsx`: assert Back/Forward controls render on Automations (not optional; this is where current behavior regressed from shortcut scope).
|
||||
- `worktree-activation` wiring test coverage (or equivalent integration assertion) should verify `setWorktreeNavViewActivator` accepts/replays both sentinels.
|
||||
|
||||
## Known residual quirks
|
||||
|
||||
- Replay uses `setActiveView(...)`, so `previousViewBeforeTasks/Automations` is not recomputed on back/forward landing. Close from a replayed page can return to stale `previousViewBefore*`; this is existing Tasks behavior.
|
||||
- History is capped at 50 entries. Long sessions may evict older entries, including page sentinels; this is existing behavior.
|
||||
- History is renderer-local and session-local (no persistence, no cross-window reconciliation).
|
||||
- Liveness is evaluated against current store state at navigation time. If a target worktree becomes invalid between target selection and activation, `activateAndRevealWorktree` may fail and index stays put.
|
||||
|
||||
## Edge cases
|
||||
|
||||
- `A -> Automations -> B`, Back lands on Automations, Back again lands on A.
|
||||
- `A -> Automations -> Automations` records only one Automations entry.
|
||||
- `A -> Automations`, close rewinds index to A; Forward reopens Automations.
|
||||
- `Automations` as the only history entry: close leaves index at `0` (do not force `-1`, or Forward target is lost).
|
||||
- If the prior worktree was deleted while Automations is open, Back/Close rewind skips it and lands on the next live prior entry.
|
||||
- Back-to-Automations must not call `openAutomationsPage`, or it would overwrite `previousViewBeforeAutomations` and append duplicate history.
|
||||
- Shortcut labels and handling remain cross-platform (`⌘⌥` on Mac, `Ctrl+Alt` elsewhere).
|
||||
- Multi-window: each renderer has an independent history stack; no cross-window reconciliation is attempted.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Update `worktree-nav-history.ts` types, live-entry predicate, and replay branch.
|
||||
2. Update `ui.ts` to record and rewind Automations visits.
|
||||
3. Update `worktree-activation.ts` comments/types for generalized view activator.
|
||||
4. Update `App.tsx` titlebar visibility and comments.
|
||||
5. Add/adjust unit tests for history slice, UI slice, and titlebar visibility.
|
||||
6. Run `worktree-nav-history.test.ts` and `ui.test.ts`, then `pnpm typecheck` and `pnpm lint`.
|
||||
@@ -1,183 +0,0 @@
|
||||
# Browser Normal Download Behavior
|
||||
|
||||
## Problem
|
||||
|
||||
The built-in browser does not behave like a normal desktop browser when a page downloads a file.
|
||||
|
||||
- `src/main/browser/browser-session-registry.ts:553` installs a `will-download` handler for browser sessions.
|
||||
- `src/main/browser/browser-manager.ts:952` pauses every download before Orca has a save path.
|
||||
- `src/renderer/src/components/browser-pane/BrowserPane.tsx:4915` shows a `Save` / `Cancel` prompt instead of starting the download.
|
||||
- `src/main/ipc/browser.ts:342` opens a native save dialog after the renderer clicks `Save`.
|
||||
- `src/main/browser/browser-manager.ts:1026` calls `DownloadItem.setSavePath()` only after that renderer + dialog round trip.
|
||||
- Electron's installed type contract says `setSavePath()` is only available during the session `will-download` callback (`node_modules/electron/electron.d.ts:8271`).
|
||||
|
||||
That late path assignment explains the "clicked Save, still did not save" failure mode and makes the flow higher-friction than Chrome/Safari/Edge defaults.
|
||||
|
||||
## Root Cause
|
||||
|
||||
Orca treats downloads as renderer-approved actions. Electron treats the destination as a main-process `will-download` decision. The current flow crosses that boundary too late: it pauses the download, asks the renderer to approve it, asks the OS where to save it, and only then sets the save path.
|
||||
|
||||
## Goal
|
||||
|
||||
Make built-in browser downloads feel like a normal browser:
|
||||
|
||||
- Download starts automatically.
|
||||
- File saves to the OS Downloads directory by default.
|
||||
- Name collisions are resolved without overwriting.
|
||||
- Browser chrome shows progress and completion.
|
||||
- Completed downloads offer familiar actions such as opening or revealing the file.
|
||||
- Cancel remains available while downloading.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- A full persistent download manager/history.
|
||||
- A settings UI for "ask where to save every file."
|
||||
- Cross-device transfer of downloads from a remote browser host to a local client.
|
||||
- Changing generic filesystem downloads outside the browser.
|
||||
|
||||
## Design
|
||||
|
||||
1. **Resolve the save path synchronously in main**
|
||||
|
||||
Add a small browser-specific destination module, e.g. `src/main/browser/browser-download-destination.ts`, that:
|
||||
|
||||
- uses `app.getPath('downloads')`;
|
||||
- normalizes the filename to a safe basename;
|
||||
- uses `path.join` for cross-platform paths;
|
||||
- avoids overwrites with browser-style suffixes (`report.csv`, `report (1).csv`);
|
||||
- checks existing files synchronously because Electron requires `setSavePath()` during `will-download`;
|
||||
- also checks a main-process reservation set for active browser downloads, so two same-name downloads that start before either file exists still get distinct paths;
|
||||
- keys reservations by a normalized absolute path, with platform-aware case folding where the target filesystem is conventionally case-insensitive, so `Report.csv` and `report.csv` cannot collide on Windows;
|
||||
- caps suffix attempts and fails the download with a clear error instead of spinning forever in a crowded Downloads directory.
|
||||
|
||||
Do not create a placeholder file just to reserve the path: Electron may treat an existing target as an overwrite. The in-memory reservation prevents Orca-internal concurrent collisions; an external process can still create the same path after the check, so this remains best-effort at the filesystem boundary.
|
||||
|
||||
2. **Set the destination during `will-download`**
|
||||
|
||||
In `BrowserManager.handleGuestWillDownload`, compute and reserve the path, then call `DownloadItem.setSavePath()` immediately while still in the `will-download` call stack. Do not pause for renderer approval, do not open `dialog.showSaveDialog`, and do not use `setSaveDialogOptions()` for this flow because that still preserves dialog behavior. If destination resolution or `setSavePath()` fails, release the reservation, cancel the item, and send or queue a failed terminal event with a specific, non-secret error.
|
||||
|
||||
3. **Track downloads from start to finish in main**
|
||||
|
||||
Replace the approval-centric state with browser download state:
|
||||
|
||||
- `downloading`: save path is already assigned; item is progressing, waiting on network, or temporarily interrupted.
|
||||
- `completed` / `failed` / `canceled`: terminal states sent to the renderer.
|
||||
|
||||
Register `updated` and `done` listeners immediately in `will-download`, store latest received-byte count plus any terminal result, and keep the existing guest-to-tab queue so downloads that start before registration still surface when the tab binds. Queue state snapshots, not every progress event: if a download finishes before the tab registers, flush a started row followed by its terminal state so the renderer does not drop an orphan progress/finish event. If an unregistered guest is destroyed or retired before the tab binds, cancel its queued active downloads and release their reservations instead of only dropping the pending queue entry. Send exactly one terminal event per download, detach only this feature's listener references during cleanup, and release the reserved path on every terminal path and on explicit cancel.
|
||||
|
||||
4. **Update IPC shape for browser-like status**
|
||||
|
||||
Keep the existing renderer event channels if that keeps the diff smaller, but change the payload contract from "approval requested" to "download started" semantics. Include `browserPageId` on start/progress/finish when the tab is known, include `savePath` on start and terminal data, and keep progress payloads to `downloadId`, byte counts, and transient state. Remove the renderer `acceptDownload` path for normal browser downloads and delete the save-dialog IPC test; `cancelDownload` remains useful while an item is active.
|
||||
|
||||
5. **Render browser chrome, not an approval prompt**
|
||||
|
||||
In `BrowserPane`, replace the `Save` / `Cancel` prompt with a compact download row/list under the toolbar:
|
||||
|
||||
- active row: filename, origin, progress label, `Cancel`;
|
||||
- completed row: filename, "Downloaded" status, `Open`, `Show`, dismiss;
|
||||
- failed/canceled row: filename, concise failure/cancel reason, dismiss.
|
||||
|
||||
Track more than one download per pane so a second download does not hide the first. Cap visible recent completed rows to a small number, such as three, to avoid growing the browser surface. This is a per-pane transient list, not persisted history.
|
||||
|
||||
6. **Use existing shell bridges for actions**
|
||||
|
||||
Use `window.api.shell.openFilePath(savePath)` for `Open` and `window.api.shell.openInFileManager(savePath)` for `Show`. `openPath` is a legacy reveal wrapper whose `void` return type prevents the preload bridge from reporting success or failure back to the renderer. If either action fails or the file has been moved/deleted, show an inline or toast failure that does not claim the file opened.
|
||||
|
||||
## Data Flow
|
||||
|
||||
```text
|
||||
Browser session will-download
|
||||
-> BrowserManager computes and reserves ~/Downloads/name.ext
|
||||
-> DownloadItem.setSavePath(path) during will-download
|
||||
-> BrowserManager tracks item and sends/queues browser download-started
|
||||
-> BrowserPane renders progress row
|
||||
-> DownloadItem updated/done
|
||||
-> BrowserManager sends progress/finished
|
||||
-> BrowserPane shows completed row with Open / Show
|
||||
```
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- Duplicate filenames must not overwrite existing files.
|
||||
- Simultaneous same-name downloads in the same Orca process must not choose the same path before either file exists.
|
||||
- Same-name reservation checks must respect platform path identity, including case-insensitive collisions on Windows.
|
||||
- External filesystem races between path selection and Chromium's file creation are unavoidable with `setSavePath()`; treat them as residual risk, not a guarantee.
|
||||
- Path traversal or separator-like filenames must collapse to a safe basename.
|
||||
- Empty filenames fall back to `download`.
|
||||
- Unknown total bytes should show received bytes or a generic "Downloading" state without broken math.
|
||||
- Multiple simultaneous downloads from the same tab must render independently.
|
||||
- A download that starts, progresses, or finishes before the webview registers must still appear once the tab binds.
|
||||
- A queued download whose guest is destroyed or retired before registration must be canceled and release its reserved path.
|
||||
- Since this design intentionally avoids a global persistent download manager, closing the owning browser tab must cancel active downloads rather than leaving hidden file writes with no chrome.
|
||||
- `setSavePath()` failure should not leave a hidden, still-running download.
|
||||
- `updated` events with `interrupted` state should keep the row honest without treating them as terminal; `done` is the terminal source of truth.
|
||||
- Explicit cancel and Electron's eventual `done` callback must not produce duplicate terminal UI events.
|
||||
- Completed file actions may fail if the file was moved/deleted after download; UI must report that honestly.
|
||||
- On Windows, Linux, and macOS, all paths are built with Node/Electron path APIs.
|
||||
- In SSH/remote workflows, the file is saved on the machine running the browser runtime; UI copy must not imply cross-machine transfer.
|
||||
- Web clients keep their existing "handled by server browser" behavior unless the server-side browser implements equivalent events.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- Unit: destination builder sanitizes names, preserves extensions, picks collision-free paths, respects active path reservations including platform path identity, releases reservations, and stops at a bounded suffix limit.
|
||||
- Unit: `BrowserManager.handleGuestWillDownload` calls `setSavePath()` during handling, does not pause/resume for approval, registers listeners immediately, sends started/progress/finished events exactly once, and cancels cleanly on destination failure.
|
||||
- Unit: queued download-started/progress/finished state flushes after guest registration with the latest state.
|
||||
- Unit: multiple download events for one browser page are tracked independently.
|
||||
- Unit: guest cleanup cancels queued-but-unbound active downloads and releases reserved paths.
|
||||
- Unit: tab unregister cancels every active download for that tab and releases reserved paths.
|
||||
- IPC: remove `browser:acceptDownload` and its native save-dialog test for normal downloads; keep `browser:cancelDownload` authorization coverage.
|
||||
- Renderer: download list state covers active, completed, failed, canceled, unknown-size, multiple same-tab downloads, bounded recent rows, and missing-file action failures.
|
||||
- Shell IPC/preload: `Open` uses `openFilePath`; `Show` uses `openInFileManager` and surfaces structured failure.
|
||||
- Electron validation: from a local test page, click a download link and verify a file appears in the OS Downloads folder without a save dialog.
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
The changed browser chrome should be quiet and dense, matching the toolbar area around it. Use existing tokens (`background`, `foreground`, `muted-foreground`, `border`, `accent`) and shadcn `Button` variants/sizes. Do not use amber warning color for ordinary downloads. The active state should be readable without looking like an error. Buttons must not wrap, overlap, or resize the toolbar/pane unexpectedly. Copy must describe real state only: "Downloading", "Downloaded", "Canceled", or the specific failure.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
Stage 5 must capture:
|
||||
|
||||
1. Active download in progress, with no save prompt visible.
|
||||
2. Completed download row with file actions visible.
|
||||
3. A repeat download of the same filename showing successful completion without overwrite.
|
||||
4. Multiple browser downloads visible at once or in the recent-download cap.
|
||||
5. Adjacent browser toolbar smoke state after the download row is dismissed.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add the destination builder and focused tests.
|
||||
2. Move BrowserManager download handling to immediate save-path assignment and progress tracking.
|
||||
3. Update browser IPC/preload/API types to remove approval semantics and carry save-path/status data.
|
||||
4. Refresh BrowserPane state and UI for active/recent downloads.
|
||||
5. Add renderer notices, tests, and localization catalog entries as required.
|
||||
6. Run targeted unit tests, typecheck, lint, then Electron validation with screenshots.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: Kept to local built-in browser download behavior. Reduced by excluding a preferences UI, persistent download history, and remote-to-local transfer. The smallest useful normal-browser behavior is automatic save to Downloads plus transient progress/completion chrome.
|
||||
- Architecture/data flow: Main owns destination choice and file writes because Electron requires `setSavePath()` during `will-download`. Renderer owns only display and user actions (`Cancel`, `Open`, `Show`, dismiss). Existing session policy installation remains the entry point; existing shell bridges handle file actions. Browser web clients remain unchanged.
|
||||
- Failure modes covered:
|
||||
- Late `setSavePath()` is removed by assigning the path synchronously in `will-download`.
|
||||
- Duplicate filenames use existing-file checks plus active path reservations instead of overwriting each other inside Orca.
|
||||
- Unsafe or empty filenames are normalized before `path.join`.
|
||||
- Downloads starting or finishing before tab registration are snapshotted and flushed in order.
|
||||
- Queued downloads are canceled if their guest is destroyed or retired before registration.
|
||||
- Multiple downloads no longer overwrite a single pane state.
|
||||
- Tab close/app shutdown cancels active items rather than leaving hidden downloads without chrome.
|
||||
- File action failures after external deletion are surfaced without overclaiming.
|
||||
- Test coverage required:
|
||||
- Unit: `src/main/browser/browser-download-destination.test.ts` for basename/suffix/collision/reservation behavior and bounded failure.
|
||||
- Unit: `src/main/browser/browser-manager.test.ts` for immediate `setSavePath`, listener registration, queued snapshots, progress/finish, cancellation, path-reservation release, and failure.
|
||||
- Unit/IPC: `src/main/ipc/browser.test.ts` removes the native save-dialog accept path and keeps cancel authorization.
|
||||
- Renderer: focused tests around download notice/list state if an existing seam is available; otherwise cover formatting helpers and rely on Electron validation for BrowserPane DOM behavior.
|
||||
- Electron: local server download verifies file creation in Downloads without save dialog.
|
||||
- Performance/blast radius: No startup cost. Per-download synchronous filesystem checks are bounded by the collision limit and happen only during `will-download`; this is acceptable for one user action but must not walk unbounded directories. Renderer IPC volume stays proportional to Electron download progress events already emitted. No migration.
|
||||
- UI quality bar: Validation should judge a neutral browser-toolbar-adjacent download row/list against `docs/STYLEGUIDE.md`: no amber error styling for ordinary progress, compact button sizes, no overlap/wrapping, honest copy, clear active/completed/failed hierarchy, and stable layout while progress changes.
|
||||
- Required review screenshots:
|
||||
1. Active download in progress with no save prompt.
|
||||
2. Completed download row with `Open` / `Show` actions.
|
||||
3. Repeat same-name download completed with distinct filename.
|
||||
4. Multiple downloads visible or capped as designed.
|
||||
5. Browser toolbar after dismissing download chrome.
|
||||
- Residual risks: Headless Electron may not reliably prove absence of a native save dialog; validation should instead verify no Orca `Save` prompt appears and the file lands in Downloads. If the OS Downloads path is redirected or unavailable, behavior depends on Electron's `app.getPath('downloads')` result.
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 30 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 24 KiB |
@@ -1,75 +0,0 @@
|
||||
# Claude Fable Weekly Usage Meter
|
||||
|
||||
## Problem
|
||||
|
||||
Claude Code now exposes weekly subscription usage alongside the 5-hour window, and its live `/usage` panel can show an explicit Fable-specific weekly bucket. Anthropic documents `rate_limits.five_hour` and `rate_limits.seven_day` in Claude Code statusline JSON, with weekly data present for Claude.ai subscribers after the first API response. The existing Orca Claude meter already has a weekly slot in shared state, but it needs a distinct Fable weekly slot so the status bar can show all three visible meters when Claude reports them.
|
||||
|
||||
Relevant code:
|
||||
|
||||
- `src/shared/rate-limit-types.ts:46` models provider usage with `session` and `weekly` windows.
|
||||
- `src/main/rate-limits/claude-fetcher.ts:373` maps OAuth `five_hour` and `seven_day` into Orca's Claude provider state.
|
||||
- `src/main/rate-limits/claude-pty.ts:18` parses hidden `claude` `/usage` output, but `WEEKLY_RE` only accepts `Current week`.
|
||||
- `src/renderer/src/components/status-bar/StatusBar.tsx:1112` renders both session and weekly windows when both are present.
|
||||
- `src/renderer/src/components/status-bar/tooltip.tsx:138` includes weekly usage in the details popover.
|
||||
|
||||
Research:
|
||||
|
||||
- Official Claude Code statusline docs: [`rate_limits.five_hour.used_percentage` and `rate_limits.seven_day.used_percentage`](https://code.claude.com/docs/en/statusline#available-data), plus matching `resets_at`, are the 5-hour and 7-day rate-limit fields.
|
||||
- `harveyxiacn/cc-usage-monitor` uses Claude Code's statusline `rate_limits` data and shows both [`5h` and `7d` windows](https://github.com/harveyxiacn/cc-usage-monitor), matching Orca's existing `session` and `weekly` model.
|
||||
- `leeguooooo/claude-code-usage-bar` independently exposes the same [`5h` and `7d` rate-limit usage](https://github.com/leeguooooo/claude-code-usage-bar) in a Claude Code statusLine integration.
|
||||
- Fable is not part of the documented statusline schema above. Orca only treats it as Fable weekly usage when the live `/usage` panel renders a standalone `Fable` label or an OAuth response uses an explicit weekly/seven-day Fable field name.
|
||||
|
||||
Redacted live `/usage` shape this parser targets:
|
||||
|
||||
```text
|
||||
Plan usage limits
|
||||
|
||||
Current session
|
||||
18% remaining
|
||||
Resets in 2h 10m
|
||||
|
||||
Current week (all models)
|
||||
84% left
|
||||
Resets in 5d 4h
|
||||
|
||||
Fable
|
||||
42% consumed
|
||||
Resets in 3d 2h
|
||||
```
|
||||
|
||||
## Goal
|
||||
|
||||
Make Orca's existing Claude status-bar meter show the weekly Claude and Fable usage windows whenever Claude Code reports them, including newer `/usage` panel wording such as `Weekly limits`, `Fable`, or `7-day`.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Do not infer subscription quota from token logs.
|
||||
- Do not spend user Claude quota during automated verification.
|
||||
- Do not change provider account switching, polling cadence, or OAuth credential handling.
|
||||
|
||||
## Design
|
||||
|
||||
1. Keep `ProviderRateLimits.weekly` as the canonical generic 7-day UI field. OAuth already maps `seven_day` to `weekly`, and the status bar already renders it next to the 5-hour window.
|
||||
2. Add `ProviderRateLimits.fableWeekly` as a distinct optional Claude window so the chip and popover can render Session, Weekly, and Fable simultaneously.
|
||||
3. Accept both OAuth `utilization` windows and Claude Code-style `used_percentage` windows with epoch-second `resets_at` values.
|
||||
4. Broaden the hidden Claude CLI parser so the generic weekly label accepts both old `Current week` wording and newer usage/statusline wording: `Weekly limits`, `Weekly usage`, `weekly rate limit`, and `7-day`.
|
||||
5. Parse only a standalone `Fable` label into `fableWeekly` instead of collapsing it into generic `weekly`; ambiguous Fable copy is a section boundary, not a meter.
|
||||
6. Broaden percent parsing to treat `consumed` like `used`, because Anthropic describes rate-limit percentages as consumed.
|
||||
7. Add focused tests for the new weekly wording and retain existing old-copy coverage.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- Weekly data may be absent for API-key users or before the first Claude API response; keep `weekly: null`.
|
||||
- The hidden PTY fallback may still only return session data; the status bar should continue showing the 5-hour meter without error.
|
||||
- Reset timestamps/descriptions may be absent from CLI output; keep `resetsAt: null` and parse only visible reset text.
|
||||
- Fable data may be absent from the documented statusline payload even when the interactive `/usage` panel shows it; keep `fableWeekly: null` unless an explicit weekly/seven-day field or standalone `Fable` label is present.
|
||||
- A bare OAuth `fable` field is ambiguous because it does not encode the window length; ignore it until the upstream contract is clearer.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Update OAuth window mapping for statusline-style percentages, reset timestamps, and distinct Fable weekly fields when present.
|
||||
2. Update `claude-pty` weekly label, Fable label, and percent parsing.
|
||||
3. Add focused tests for statusline-style OAuth data, `Weekly limits`, `Fable`, and `7-day` wording.
|
||||
4. Run focused tests, then typecheck/lint.
|
||||
5. Validate in Electron by injecting a Claude provider state with 5-hour, generic weekly, and Fable weekly data and capturing status-bar screenshots.
|
||||
6. Commit, push, open a PR, and attach screenshots in a PR comment.
|
||||
@@ -1,84 +0,0 @@
|
||||
# Claude Scoped OAuth Usage Limits
|
||||
|
||||
## Problem
|
||||
|
||||
Anthropic's current OAuth usage response reports Fable in `limits` as a model-scoped weekly limit instead of one of the legacy top-level Fable fields. Orca ignores `limits`, maps `fableWeekly` to `null`, and then depends on a hidden Claude `/usage` PTY read that is disabled on Windows and can fail silently elsewhere.
|
||||
|
||||
- `src/main/rate-limits/claude-fetcher.ts:300` models only top-level OAuth windows.
|
||||
- `src/main/rate-limits/claude-fetcher.ts:393` maps only legacy Fable field names.
|
||||
- `src/main/rate-limits/service.ts:1203` disables the PTY supplement on Windows.
|
||||
- `src/renderer/src/components/status-bar/tooltip.tsx:172` renders Fable whenever `fableWeekly` is populated.
|
||||
|
||||
## Root Cause
|
||||
|
||||
The OAuth response contract evolved from dedicated model fields to generic entries shaped like `kind: "weekly_scoped"`, `percent`, `resets_at`, and `scope.model.display_name`. Orca's response type and mapper were not updated for that shape.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Do not change polling, credentials, token refresh, account switching, renderer layout, or usage percentage semantics.
|
||||
- Do not remove the existing PTY supplement or legacy field compatibility.
|
||||
- Do not generalize shared renderer state to arbitrary model windows in this targeted bug fix.
|
||||
|
||||
## Design
|
||||
|
||||
1. Extend the private OAuth response type with an optional `limits` array containing only the fields needed for safe parsing.
|
||||
2. Select a Fable entry only when `kind` is `weekly_scoped`, the model display name is Fable (case-insensitive), and `percent` is finite.
|
||||
3. Map the scoped entry to the existing seven-day `fableWeekly` window, including its reset timestamp.
|
||||
4. Prefer the current scoped entry, then retain the three legacy top-level fields as fallbacks.
|
||||
5. Keep malformed, unrelated, or absent entries non-fatal. Do NOT gate on `is_active`: it marks which limit is currently binding, not whether the entry's data is valid, so an `is_active: false` Fable entry with a finite `percent` must still render (#8979). Accept a missing activity flag for compatibility.
|
||||
|
||||
## Data Flow
|
||||
|
||||
- OAuth response
|
||||
- `limits[].weekly_scoped` Fable -> `fableWeekly`
|
||||
- otherwise legacy explicit Fable field -> `fableWeekly`
|
||||
- otherwise existing optional PTY supplement
|
||||
- Existing provider state -> existing status-bar and details rendering
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- `limits` is missing, null, malformed, or contains null entries.
|
||||
- A scoped entry names another model.
|
||||
- Fable percent is missing, non-numeric, or non-finite.
|
||||
- Fable is inactive (`is_active: false`) but still carries a finite `percent`/reset, so it must render (#8979).
|
||||
- `is_active` is omitted by an older server response but the remaining scoped entry is valid.
|
||||
- Both current and legacy fields exist; the current scoped entry wins.
|
||||
- Reset timestamps may be ISO strings, epoch seconds, epoch milliseconds, or absent.
|
||||
- Windows, WSL, SSH, and remote runtimes use the same OAuth mapper and require no platform-specific execution.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- Unit: reproduce a current real-response shape and assert Fable maps without a PTY attempt.
|
||||
- Unit: assert scoped data wins over a legacy field.
|
||||
- Unit: assert malformed and unrelated scoped entries are ignored while legacy fallback remains available; assert an inactive-but-valid Fable entry still surfaces (#8979).
|
||||
- Regression: retain existing legacy-field and bare-`fable` behavior tests.
|
||||
- Verification: focused Claude fetcher tests, typecheck, lint, and max-lines ratchet.
|
||||
- Electron: refresh Claude usage and confirm Session, Weekly, and Fable remain visible in the existing status-bar details surface.
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
No UI implementation changes. The existing Fable row must reappear with the same typography, spacing, progress bar, percentage semantics, and reset copy as adjacent Session and Weekly rows.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
1. Claude usage details showing Session, Weekly, and Fable from a live OAuth refresh.
|
||||
2. Adjacent status-bar context showing the Claude provider remains visually unchanged outside the restored row.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add the scoped OAuth response types and mapper.
|
||||
2. Add focused current-schema and compatibility regression tests.
|
||||
3. Run focused and repository checks.
|
||||
4. Validate the restored row in Electron and capture review screenshots.
|
||||
5. Commit, push, and open an unmerged PR.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: Kept to the private OAuth mapper and tests; no shared-state or renderer generalization is required to restore Fable.
|
||||
- Architecture/data flow: OAuth remains authoritative, with structured scoped data preferred over legacy fields and PTY used only as the existing final supplement.
|
||||
- Failure modes covered: malformed optional data, unrelated models, inactive-but-valid limits (still rendered, #8979), missing activity flags, duplicate old/new representations, missing reset metadata, and platform-neutral execution.
|
||||
- Test coverage required: current-schema success without PTY, precedence, inactive-but-valid rendering, malformed/unrelated entries, and legacy fallback.
|
||||
- Performance/blast radius: One bounded linear scan of the small response `limits` array per existing OAuth refresh; no new requests, polling, subprocesses, IPC, storage, or renderer work.
|
||||
- UI quality bar: Existing status-bar visuals must remain unchanged except for the restored Fable row.
|
||||
- Required review screenshots: Live Claude details with all three rows; surrounding status-bar context.
|
||||
- Residual risks: Anthropic may rename the scoped model display label; legacy and PTY fallbacks remain available.
|
||||
@@ -1,391 +0,0 @@
|
||||
# Claude Usage Tracking: CodexBar Parity Plan
|
||||
|
||||
## Goal
|
||||
|
||||
Make Orca's Claude usage limit tracking behave like CodexBar's Claude implementation: automatic, resilient, and source-aware internally, without asking users to choose between OAuth, CLI, or other data sources.
|
||||
|
||||
This plan intentionally does not introduce new product behavior from scratch. Each proposed change is based on CodexBar's existing implementation.
|
||||
|
||||
## User-Facing Principle
|
||||
|
||||
Users should not need to pick a usage source.
|
||||
|
||||
The normal product behavior should remain automatic:
|
||||
|
||||
- Try the best live Claude usage source.
|
||||
- Repair or fall back when a source fails.
|
||||
- Keep the last useful usage snapshot visible when refresh is deferred or temporarily unavailable.
|
||||
- Show a specific, actionable status only when Orca cannot recover automatically.
|
||||
|
||||
Any "source planner" described below is internal plumbing only. It should not imply a visible source picker for normal users.
|
||||
|
||||
## CodexBar References
|
||||
|
||||
CodexBar's Claude implementation already separates source selection from execution:
|
||||
|
||||
- `ClaudeSourcePlanner.resolve(...)` builds an ordered automatic plan.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeSourcePlanner.swift:173`
|
||||
- App auto mode tries OAuth, then CLI, then web.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeSourcePlanner.swift:173`
|
||||
- CLI runtime auto mode tries web, then CLI.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeSourcePlanner.swift:181`
|
||||
- `ClaudeUsageFetcher.StepExecutor` executes the selected path.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:461`
|
||||
- OAuth failures can trigger delegated Claude CLI refresh, then credentials are reloaded and OAuth is retried.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:324`
|
||||
- OAuth credential loading accounts for Keychain prompt policy and cached credentials.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:250`
|
||||
- Claude source types are explicit: auto, api, oauth, web, cli.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageDataSource.swift:3`
|
||||
|
||||
CodexBar's Codex implementation is also a useful pattern for fallback discipline:
|
||||
|
||||
- Auto mode tries OAuth, then CLI.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Codex/CodexProviderDescriptor.swift:43`
|
||||
- Codex OAuth refresh is performed before usage fetch when credentials need refresh.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Codex/CodexProviderDescriptor.swift:169`
|
||||
- Fallback from OAuth to CLI is limited to failures the CLI can plausibly repair.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Codex/CodexProviderDescriptor.swift:199`
|
||||
- Codex CLI usage is fetched through `codex app-server` JSON-RPC.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/UsageFetcher.swift:1012`
|
||||
|
||||
## Current Orca Behavior To Preserve Or Change
|
||||
|
||||
Orca currently reads Claude OAuth credentials and calls Anthropic's OAuth usage endpoint:
|
||||
|
||||
- OAuth usage endpoint and headers are in `claude-fetcher.ts`.
|
||||
Reference: `src/main/rate-limits/claude-fetcher.ts:24`
|
||||
- OAuth credential reads intentionally let the server decide whether a token is valid because local expiry metadata is not authoritative.
|
||||
Reference: `src/main/rate-limits/claude-fetcher.ts:80`
|
||||
- System-default Keychain lookup intentionally mirrors Claude's legacy service ordering.
|
||||
Reference: `src/main/rate-limits/claude-fetcher.ts:193`
|
||||
- Renderer currently maps many auth-looking failures into "Refresh failed" / softer auth copy.
|
||||
Reference: `src/renderer/src/components/status-bar/tooltip.tsx:115`
|
||||
|
||||
Preserve:
|
||||
|
||||
- Managed-account safety around live Claude sessions and refresh-token rotation.
|
||||
- System-default support.
|
||||
- Existing OAuth usage endpoint mapping.
|
||||
- Existing PTY fallback parser behavior where safe.
|
||||
|
||||
Change:
|
||||
|
||||
- Do not treat a single OAuth failure as overall Claude usage failure.
|
||||
- Distinguish deferred, recoverable, fallbackable, and terminal failures.
|
||||
- Use CLI fallback and delegated refresh intentionally, following CodexBar's shape.
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
### 1. Add An Internal Claude Usage Refresh Plan
|
||||
|
||||
Create an internal planner that returns ordered attempts for the current account/runtime state.
|
||||
|
||||
Initial app automatic order should match CodexBar's app auto ordering:
|
||||
|
||||
1. OAuth usage API.
|
||||
2. CLI/PTY usage fallback.
|
||||
3. Web usage source later, only if Orca intentionally adopts CodexBar's web/cookie machinery.
|
||||
|
||||
CodexBar basis:
|
||||
|
||||
- `ClaudeSourcePlanner.makeSteps` app auto returns OAuth, CLI, web.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeSourcePlanner.swift:173`
|
||||
- `ClaudeUsageDataSource` defines source identifiers separately from execution.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageDataSource.swift:3`
|
||||
|
||||
Orca implementation target:
|
||||
|
||||
- Add a focused module near `src/main/rate-limits/`, for example `claude-usage-refresh-plan.ts`.
|
||||
- Keep it internal to main-process rate-limit refresh.
|
||||
- Do not expose a normal user setting for source selection.
|
||||
|
||||
### 2. Add Source Attempt Execution
|
||||
|
||||
Separate "which source should be tried" from "how each source fetches usage."
|
||||
|
||||
CodexBar basis:
|
||||
|
||||
- `StepExecutor.loadLatestUsage` switches on source and executes OAuth, web, or CLI.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:461`
|
||||
|
||||
Orca implementation target:
|
||||
|
||||
- Split Claude refresh into source attempt functions:
|
||||
- `fetchClaudeUsageViaOAuth(...)`
|
||||
- `fetchClaudeUsageViaCli(...)`
|
||||
- possible future `fetchClaudeUsageViaWeb(...)`
|
||||
- Keep the existing OAuth endpoint logic in the OAuth attempt.
|
||||
- Reuse existing `fetchViaPty` for the CLI attempt.
|
||||
|
||||
### 3. Classify OAuth Failures Before Deciding What To Do
|
||||
|
||||
Add structured OAuth failure classification.
|
||||
|
||||
Failure kinds should include:
|
||||
|
||||
- missing credentials
|
||||
- stale or unauthorized access token
|
||||
- refreshable credentials present but access token unavailable
|
||||
- delegated refresh required
|
||||
- delegated refresh deferred by live Claude session
|
||||
- Keychain denied or unavailable
|
||||
- missing required scope
|
||||
- network/proxy/DNS failure
|
||||
- Anthropic server failure
|
||||
- response parse failure
|
||||
- rate-limited usage endpoint
|
||||
|
||||
CodexBar basis:
|
||||
|
||||
- Codex fallback is intentionally limited to specific OAuth credential/auth errors.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Codex/CodexProviderDescriptor.swift:199`
|
||||
- Claude OAuth maps credential/fetch errors distinctly before retrying or surfacing.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:286`
|
||||
- Missing Claude OAuth scope gets a specific actionable message.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:444`
|
||||
|
||||
Orca implementation target:
|
||||
|
||||
- Add `claude-usage-error-classification.ts`.
|
||||
- Use classification to decide:
|
||||
- retry OAuth after delegated refresh
|
||||
- fall back to CLI
|
||||
- defer because live Claude owns refresh
|
||||
- surface terminal error
|
||||
|
||||
### 4. Add Delegated Claude CLI Refresh For Safe Cases
|
||||
|
||||
When OAuth credentials appear stale or access is unauthorized, let Claude CLI repair its own credentials, then re-read credentials and retry OAuth once.
|
||||
|
||||
CodexBar basis:
|
||||
|
||||
- Expired Claude OAuth credentials can trigger `loadAfterDelegatedRefresh`.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:324`
|
||||
- CodexBar asserts delegated refresh is allowed in the current interaction context before running it.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:345`
|
||||
- After delegated refresh, CodexBar invalidates changed credential caches, syncs Keychain without prompt, reloads credentials, and retries OAuth.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:369`
|
||||
|
||||
Orca implementation target:
|
||||
|
||||
- Add a guarded delegated refresh step for system-default accounts and managed accounts only when no live Claude PTY owns the same credentials.
|
||||
- After delegation, re-run Orca's existing credential read order and retry the OAuth usage request once.
|
||||
- Keep this disabled for cases where Orca already knows live Claude is using/rotating that credential set.
|
||||
|
||||
### 5. Preserve Managed Live-Session Safety, But Change The State
|
||||
|
||||
Current Orca managed-account behavior avoids rotating refresh tokens while a live Claude terminal may rotate them. Keep that safety rule.
|
||||
|
||||
Change the user-visible outcome from generic failure to a deferred state.
|
||||
|
||||
CodexBar basis:
|
||||
|
||||
- Delegated refresh is gated by interaction policy and can be unavailable rather than blindly attempted.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:345`
|
||||
- CodexBar tracks delegated refresh outcomes and reports them distinctly.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:350`
|
||||
|
||||
Orca implementation target:
|
||||
|
||||
- Add a first-class `deferredByLiveClaudeSession` usage refresh outcome.
|
||||
- Keep last successful snapshot visible if present.
|
||||
- Tooltip/status should say the refresh is waiting for the live Claude session rather than "Refresh failed."
|
||||
|
||||
### 6. Apply The Same Recovery Logic To System Default
|
||||
|
||||
Do not assume failures are managed-account only.
|
||||
|
||||
System default can still fail when:
|
||||
|
||||
- Keychain access is denied.
|
||||
- Claude rotated credentials and Orca has stale cached data.
|
||||
- The access token is rejected by the OAuth usage endpoint.
|
||||
- Required scope is missing.
|
||||
- Network/proxy settings block `api.anthropic.com`.
|
||||
|
||||
CodexBar basis:
|
||||
|
||||
- OAuth credential loading accounts for cached credentials, Keychain prompt policy, and Keychain access.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:250`
|
||||
- Post-delegation retry re-reads credentials instead of reusing the stale token.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:408`
|
||||
|
||||
Orca implementation target:
|
||||
|
||||
- Use the same internal plan for system default and managed accounts.
|
||||
- For system default, allow delegated refresh when safe.
|
||||
- Re-read Keychain / `.credentials.json` after any delegated repair.
|
||||
|
||||
### 7. Store Attempt Metadata With Usage State
|
||||
|
||||
Add metadata to Claude provider state so the renderer can show precise state without parsing raw error strings.
|
||||
|
||||
Suggested metadata:
|
||||
|
||||
- `source`
|
||||
- `attemptedSources`
|
||||
- `failureKind`
|
||||
- `credentialSource`
|
||||
- `authProvenance`
|
||||
- `deferredByLiveClaudeSession`
|
||||
- `lastSuccessfulSource`
|
||||
|
||||
CodexBar basis:
|
||||
|
||||
- Source labels are preserved in fetch results for Codex OAuth and CLI.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Codex/CodexProviderDescriptor.swift:132`
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Codex/CodexProviderDescriptor.swift:253`
|
||||
- Claude planner logs selected source and ordered steps.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:512`
|
||||
|
||||
Orca implementation target:
|
||||
|
||||
- Extend shared rate-limit types conservatively.
|
||||
- Keep renderer copy based on structured state, not regex-only string matching.
|
||||
- Continue to include sanitized diagnostics in main-process logs.
|
||||
|
||||
### 8. Replace Generic UI Failure For Known States
|
||||
|
||||
Known recoverable or deferred states should not render as "Refresh failed."
|
||||
|
||||
Suggested user-facing states:
|
||||
|
||||
- `Waiting for Claude session`
|
||||
- `Refreshing sign-in`
|
||||
- `Claude CLI unavailable`
|
||||
- `Network issue`
|
||||
- `Usage unavailable`
|
||||
- `Refresh failed` only for unknown or terminal failures
|
||||
|
||||
CodexBar basis:
|
||||
|
||||
- Claude OAuth failures distinguish expired/delegated-refresh states from generic parse/network failure.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:338`
|
||||
- Codex OAuth refresh errors include specific relogin messages for expired/revoked/reused refresh tokens.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Codex/CodexOAuth/CodexTokenRefresher.swift:17`
|
||||
|
||||
Orca implementation target:
|
||||
|
||||
- Update status-bar tooltip mapping to prefer structured `failureKind`.
|
||||
- Keep the current auth regex fallback only for older/unstructured provider errors.
|
||||
|
||||
### 9. Add Debug-Only Source Visibility, Not A Normal Picker
|
||||
|
||||
Normal users should see automatic behavior only.
|
||||
|
||||
For debugging/support, it is useful to expose what happened:
|
||||
|
||||
- attempted OAuth
|
||||
- delegated refresh attempted/skipped
|
||||
- attempted CLI
|
||||
- final source used
|
||||
- sanitized failure kind
|
||||
|
||||
CodexBar basis:
|
||||
|
||||
- CodexBar has explicit source labels and source modes, but the app default remains automatic.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Codex/CodexProviderDescriptor.swift:35`
|
||||
- Claude planner can describe selected and ordered sources.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeSourcePlanner.swift:99`
|
||||
|
||||
Orca implementation target:
|
||||
|
||||
- Add internal logs and possibly a debug tooltip line.
|
||||
- Avoid a normal user-facing setting unless support data later proves it is needed.
|
||||
|
||||
### 10. Defer Web/Cookie Source Until After OAuth + CLI Parity
|
||||
|
||||
Do not implement Claude web/cookie tracking in the first pass.
|
||||
|
||||
CodexBar basis:
|
||||
|
||||
- CodexBar supports web as a later fallback source in Claude app auto.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeSourcePlanner.swift:177`
|
||||
- CodexBar's web paths are substantial and involve browser session/cookie machinery.
|
||||
Reference: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeWeb/ClaudeWebAPIFetcher.swift:100`
|
||||
|
||||
Orca implementation target:
|
||||
|
||||
- Put web source behind a future milestone.
|
||||
- First match the high-value resilience behavior: OAuth classification, delegated refresh, CLI fallback, deferred live-session state.
|
||||
|
||||
## Suggested PR Sequence
|
||||
|
||||
### PR 1: Internal Plan + Structured Outcomes
|
||||
|
||||
- Add internal Claude usage refresh plan.
|
||||
- Add structured source attempt result and failure classification.
|
||||
- Preserve existing behavior by executing only the current OAuth path first.
|
||||
- Update logs and tests around classification.
|
||||
|
||||
CodexBar references:
|
||||
|
||||
- `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeSourcePlanner.swift:173`
|
||||
- `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:461`
|
||||
- `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Codex/CodexProviderDescriptor.swift:199`
|
||||
|
||||
### PR 2: CLI Fallback In Automatic Mode
|
||||
|
||||
- Add CLI source attempt using existing PTY parser.
|
||||
- Fall back from OAuth to CLI for classified recoverable/auth cases.
|
||||
- Preserve last successful snapshot when fallback fails.
|
||||
|
||||
CodexBar references:
|
||||
|
||||
- `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeSourcePlanner.swift:173`
|
||||
- `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:461`
|
||||
- `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/UsageFetcher.swift:1012`
|
||||
|
||||
### PR 3: Delegated Refresh + Retry
|
||||
|
||||
- Add safe delegated Claude CLI refresh for stale OAuth states.
|
||||
- Re-read credentials after delegation.
|
||||
- Retry OAuth once.
|
||||
- Do not run delegated refresh when a live managed Claude session owns the credential rotation.
|
||||
|
||||
CodexBar references:
|
||||
|
||||
- `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:324`
|
||||
- `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:345`
|
||||
- `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:369`
|
||||
- `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:408`
|
||||
|
||||
### PR 4: Renderer State Copy
|
||||
|
||||
- Replace generic `Refresh failed` for known Claude states.
|
||||
- Prefer structured failure/deferred metadata over error regexes.
|
||||
- Keep regex fallback for unstructured errors.
|
||||
|
||||
CodexBar references:
|
||||
|
||||
- `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:338`
|
||||
- `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Codex/CodexOAuth/CodexTokenRefresher.swift:17`
|
||||
|
||||
## Test Plan
|
||||
|
||||
Add unit tests for:
|
||||
|
||||
- OAuth success remains OAuth success.
|
||||
- OAuth missing credentials falls back to CLI.
|
||||
- OAuth unauthorized attempts delegated refresh when safe.
|
||||
- Delegated refresh re-reads credentials and retries OAuth once.
|
||||
- Managed live Claude session returns deferred state instead of generic failure.
|
||||
- System-default stale credentials use the same repair path.
|
||||
- Missing scope produces actionable message.
|
||||
- Network failure is classified separately from auth failure.
|
||||
- CLI fallback unavailable preserves last known snapshot when present.
|
||||
- Renderer maps known states to specific labels.
|
||||
|
||||
CodexBar references:
|
||||
|
||||
- Source planning: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeSourcePlanner.swift:173`
|
||||
- OAuth delegated refresh: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Claude/ClaudeUsageFetcher.swift:324`
|
||||
- Fallback discipline: `/Users/jinwoohong/stably/codexbar/Sources/CodexBarCore/Providers/Codex/CodexProviderDescriptor.swift:199`
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Do not add a normal user-facing source picker.
|
||||
- Do not add Claude web/cookie tracking in the first implementation pass.
|
||||
- Do not weaken managed-account live-session token safety.
|
||||
- Do not rely on raw error-message regexes as the primary control flow.
|
||||
@@ -1,141 +0,0 @@
|
||||
# Cmd-J Tab and Agent Session Search
|
||||
|
||||
## Problem
|
||||
|
||||
Cmd-J can already search worktrees, settings, actions, browser pages, and simulator tabs, but not ordinary open terminal/editor tabs or their agent-session context. The existing open-tab list only combines browser and simulator matches in `WorktreeJumpPalette.tsx` (`browserItems`, `simulatorItems`, `openTabItems`). Terminal/editor activation exists elsewhere, notably the shortcut activation path in `src/renderer/src/lib/tab-number-shortcuts.ts`, but Cmd-J has no searchable row for those tab kinds. Agent prompt/session metadata is structured and bounded in `AgentStatusEntry`, `RetainedAgentEntry`, and `SleepingAgentSessionRecord`, yet Cmd-J does not index it.
|
||||
|
||||
## Goal
|
||||
|
||||
Let users open the existing Worktree Palette shortcut (`Cmd+J` on macOS, `Ctrl+Shift+J` on Windows/Linux by default) and type keywords from:
|
||||
|
||||
1. Open terminal and editor tab titles.
|
||||
2. Live or retained agent prompts/session ids associated with terminal panes.
|
||||
3. Sleeping agent session prompt/title/session-id metadata only when it can be attributed to an existing terminal tab.
|
||||
4. Worktree and repo metadata, matching the current browser/simulator tab behavior.
|
||||
|
||||
Selecting a matched tab should activate the owning worktree, split group, and tab, then focus the right surface for terminal/editor tabs.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Do not index terminal scrollback, file contents, or full assistant messages.
|
||||
- Do not add a new global search backend, IPC channel, persistence field, or database.
|
||||
- Do not change Cmd-J shortcut registration or platform key labels.
|
||||
- Do not alter worktree/settings/action ranking semantics outside combining the new tab result list.
|
||||
- Do not support launching/resuming a sleeping agent session from the result row; this feature only navigates to existing open tabs.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add a focused tab-search helper, likely `src/renderer/src/lib/workspace-tab-palette-search.ts`, modeled after `simulator-palette-search.ts`. It should build searchable entries from `unifiedTabsByWorktree` for terminal tabs and editor-family tabs (`editor`, `diff`, `conflict-review`, `check-details`; markdown preview is an `editor` tab whose `OpenFile.mode` is `markdown-preview`). Do not fold browser/simulator into this helper unless tests prove their current scoring, empty-query comparators, rendering data, and activation behavior are unchanged.
|
||||
|
||||
2. Resolve displayed titles through existing sources:
|
||||
- Terminal: map the unified terminal tab's `entityId` to `tabsByWorktree[worktreeId]`, then use `resolveTerminalTabTitle` from `src/shared/tab-title-resolution.ts:3` with `settings.tabAutoGenerateTitle`.
|
||||
- Editor-family tabs: map the unified tab's `entityId` to `openFiles`, then use `getEditorDisplayLabel`, with relative path/full path as secondary searchable text. If the backing `OpenFile` is missing, do not create a searchable editor row; `setActiveFile` cannot safely restore it.
|
||||
- Terminal fallback: use `resolveUnifiedTabLabel` from `src/shared/tab-title-resolution.ts:17` only when a terminal's legacy `TerminalTab` record is missing but the unified terminal tab still exists.
|
||||
|
||||
3. Add agent-session keywords only from bounded structured state:
|
||||
- `agentStatusByPaneKey`: `prompt`, `agentType`, `state`, `providerSession.key/id`, `terminalTitle`, and capped `stateHistory[].prompt`.
|
||||
- `retainedAgentsByPaneKey`: the retained `entry` fields above plus the retained terminal tab title snapshot.
|
||||
- `sleepingAgentSessionsByPaneKey`: `prompt`, `agent`, `providerSession.key/id`, `state`, and `terminalTitle`.
|
||||
Attach metadata to a terminal row only when it matches that terminal by explicit `tabId`, by retained `tab.id`, or by pane-key prefix `${terminalTabId}:`, where `terminalTabId` is the legacy terminal id (`unifiedTab.entityId`). The worktree must also match when the record carries one. Do not include terminal scrollback, full assistant messages, `lastAssistantMessage`, `toolName`, or `toolInput`. Keep rendered snippets trimmed/capped even though hook payloads and history length are already bounded.
|
||||
|
||||
4. Rank with predictable field weights:
|
||||
- Displayed tab title: highest priority. Terminal title precedence must match `resolveTerminalTabTitle`: custom title, quick-command label, generated title only when enabled, raw title, then fallback. Editor title precedence must match `getEditorDisplayLabel`.
|
||||
- Agent prompt/session metadata: next, shown as supporting text when it caused the match.
|
||||
- Worktree name and repo name: lower priority, matching browser/simulator ordering.
|
||||
- Empty query: preserve current behavior by showing open tab rows. Existing browser/simulator helpers compute context-first scores, but `WorktreeJumpPalette` currently merges all open-tab item types by `result.score` and then item id; do not replace that final merge comparator unless tests deliberately cover the browser/simulator ordering change. New terminal/editor rows should encode deterministic context-first ordering in their scores: current tab, current worktree, worktree order, then group/tab order. Browser/simulator already index across all worktrees, including archived/default-hidden worktrees; terminal/editor rows may follow that open-tab behavior, but only for rows backed by existing unified tabs.
|
||||
|
||||
5. Integrate in `WorktreeJumpPalette.tsx` with a small new `WorkspaceTabPaletteItem` type and helper import. Add explicit store selectors for the new inputs (`openFiles`, `retainedAgentsByPaneKey`, `sleepingAgentSessionsByPaneKey`, `activeTabId`, `activeTabIdByWorktree`, `activeFileId`, `activeFileIdByWorktree`, and `activeTabTypeByWorktree` for current-row detection). Replace `openTabItems` with browser + simulator + workspace tab items sorted by the existing combined open-tab ordering, keeping the existing `OPEN TABS` section and caps.
|
||||
|
||||
6. Add a generic tab activation helper, likely `src/renderer/src/lib/workspace-tab-palette-activation.ts`, that mirrors `activateTabNumberShortcut` (`src/renderer/src/lib/tab-number-shortcuts.ts:57`) and existing simulator selection (`src/renderer/src/components/WorktreeJumpPalette.tsx:1090`). Re-resolve the target from `useAppStore.getState()` at selection time before mutating state:
|
||||
- `activateAndRevealWorktree(worktreeId)`.
|
||||
- Verify the target worktree, group, and unified tab still exist; the tab must still have the expected content type and still belong to the target worktree/group. Return with the same toast pattern before mutating state if any of those checks fail.
|
||||
- Terminal: activate web runtime session when needed using `getRuntimeEnvironmentIdForWorktree`, `isWebRuntimeSessionActive`, and `activateWebRuntimeSessionTab`; set `activeTab` to terminal `entityId`; set active type to `terminal`; then `focusTerminalTabSurface(entityId)`.
|
||||
- Editor-family tabs: verify `openFiles` still contains `entityId`; focus the target group, set active file to `entityId`, activate the unified tab id, then set active type to `editor`. Activating after `setActiveFile` preserves the specific split tab and is required for `check-details`, which `setActiveFile` does not implicitly re-find.
|
||||
- Simulator/browser behavior should remain unchanged unless the shared helper explicitly preserves existing semantics.
|
||||
|
||||
7. Render terminal/editor rows with the existing open-tab row density and tokens near `src/renderer/src/components/WorktreeJumpPalette.tsx:1697`: icon, highlighted title, current-tab/current-worktree chip, supporting text, worktree, host badge, and repo badge. Use existing icons (`SquareTerminal`, `FileText` or file-type icon if cheap and already available). Update the no-results subtitle at `src/renderer/src/components/WorktreeJumpPalette.tsx:1385` to include tab title/agent prompt without making it verbose.
|
||||
|
||||
8. Keep generated lists computed in `useMemo`; all required source data already exists in the renderer store, but `WorktreeJumpPalette` must subscribe to the slices it does not currently read. No new IPC, polling, filesystem reads, persistence fields, or shared mutable cache are needed. Search work should stay proportional to open unified tabs plus the small in-memory agent maps.
|
||||
|
||||
## Data flow
|
||||
|
||||
- Store slices expose `unifiedTabsByWorktree`, `tabsByWorktree`, `openFiles`, worktrees/repos, live agent statuses, retained agents, sleeping sessions, active group ids, and active terminal/editor ids.
|
||||
- `buildSearchableWorkspaceTabs(...)` produces one entry per open terminal/editor tab with resolved labels and bounded agent keywords.
|
||||
- `searchWorkspaceTabs(entries, query)` returns scored/highlighted results.
|
||||
- `WorktreeJumpPalette` maps results to open-tab rows.
|
||||
- User selects a row.
|
||||
- Selection re-resolves the target from the live store, activates the owning worktree/group/tab, and focuses terminal/editor as appropriate.
|
||||
|
||||
## Edge cases
|
||||
|
||||
- Custom title, quick-command label, generated title, and raw title should follow the same precedence as the tab bar.
|
||||
- Generated titles disabled: do not make generated terminal/unified labels the displayed title or a title-weighted match. It is acceptable to search bounded agent prompt/session metadata regardless of this setting.
|
||||
- Split groups: activate the result's `groupId`, not just the worktree's last active group.
|
||||
- Terminal unified tab missing its legacy terminal record: still show a fallback title from the unified tab and navigate if the unified tab exists.
|
||||
- Editor-family unified tab missing its `OpenFile`: omit the row and treat selection as stale if it disappears after search.
|
||||
- Markdown preview tabs: include them through `contentType: 'editor'` and `getEditorDisplayLabel`; do not look for a separate unified content type.
|
||||
- Current-row detection is type-specific: terminal active ids are legacy terminal ids, editor active ids are file ids, while unified group state stores unified tab ids.
|
||||
- Agent pane keys are composite `${tabId}:${leafId}`; only attach agent metadata when it is attributed to the result tab by explicit `tabId`, retained `tab.id`, or pane-key prefix and does not conflict with record `worktreeId`.
|
||||
- Multiple agent panes in one terminal tab: include all bounded agent prompts/metadata, but show only the best matching supporting snippet.
|
||||
- Sleeping sessions: search metadata only when tied to an existing terminal tab; selecting the row must navigate to that tab and must not call resume/launch logic, regardless of `origin`.
|
||||
- Archived/default-hidden worktrees: preserve current open-tab search behavior by indexing open tabs across all worktrees.
|
||||
- SSH/web runtime tabs: activation must call the existing runtime activation path where terminal/browser tab shortcuts already do.
|
||||
- One-character query: keep the existing two-character minimum only for settings/actions; open-tab search follows current browser/simulator tab search behavior and may match one character.
|
||||
- Stale records: ignore agent records whose tab id cannot be tied to an existing open tab; do not create standalone agent-session rows.
|
||||
- Duplicate metadata from live + retained + sleeping records: de-duplicate by pane key and prefer live, then retained, then sleeping for keywords/supporting snippets.
|
||||
- External mutations during selection: if the target tab, backing `OpenFile`, group, or worktree disappeared after search, close nothing and show the same toast-and-return pattern used for missing browser/simulator rows. Validate all of these before calling `focusGroup`, because `focusGroup` itself will stamp the requested group id even if the group was removed.
|
||||
|
||||
## Test plan
|
||||
|
||||
- Unit: add `workspace-tab-palette-search.test.ts` covering terminal title precedence, generated-title disabled behavior, editor label/path search for every editor-family content type and markdown preview mode, agent prompt/session search, retained/sleeping metadata attribution by legacy terminal id, stale/orphan metadata exclusion, split-group current-tab detection, and deterministic ordering.
|
||||
- Unit: update/add `WorktreeJumpPalette` tests only if there is an existing lightweight component harness; otherwise cover integration behavior through pure helper tests and targeted activation helper tests.
|
||||
- Unit: add activation tests for a helper if extracted from `WorktreeJumpPalette`, including terminal web-runtime activation, editor-family activation for `editor`/`diff`/`conflict-review`/`check-details`, missing tab/group/backing-file/worktree failures, and split group focus.
|
||||
- Regression: ensure existing `simulator-palette-search.test.ts` and `palette-results.test.ts` still pass.
|
||||
- Validation: Electron golden path for searching a terminal tab title/agent prompt and selecting it, plus an editor-family tab selection; adjacent smoke for existing browser/simulator open-tab rows.
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
User-visible. The new rows must look like the existing Open Tabs rows: same spacing, typography, selection state, highlight weight, badges, truncation, host/repo badges, and row density. Long tab titles, prompts, repo names, and worktree names must truncate without overlap or layout jitter in the 736px palette and under the existing `max-w-[94vw]` mobile/narrow constraint. Use documented tokens and existing shadcn/cmdk row primitives; no new color values, font sizes, shadows, or card styling.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
1. Empty Cmd-J palette with Open Tabs showing a terminal/editor tab alongside existing tab rows.
|
||||
2. Typed query matching a terminal tab title.
|
||||
3. Typed query matching an agent prompt/session keyword with supporting text visible.
|
||||
4. Typed query matching an editor tab title or path.
|
||||
5. Adjacent smoke: existing browser or simulator tab search result still appears and keeps its styling.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add the pure tab-search helper and unit tests.
|
||||
2. Add/extract a small tab-activation helper if needed and unit-test it.
|
||||
3. Wire `WorktreeJumpPalette` to build/search/render/select workspace tab rows.
|
||||
4. Update no-results copy and imports.
|
||||
5. Run targeted tests, typecheck, lint.
|
||||
6. Validate in Electron and capture required screenshots.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: reduced to open terminal/editor tab navigation plus bounded agent prompt/session-id/title metadata. No terminal scrollback, file-content search, standalone sleeping-session rows, or resume/launch actions.
|
||||
- Architecture/data flow: renderer-only helper fed by explicit `WorktreeJumpPalette` store snapshots; selection re-resolves live state and delegates to a small activation helper that preserves current worktree/group/tab and web-runtime activation boundaries.
|
||||
- Failure modes covered:
|
||||
- stale tab/group/backing file/worktree between search and select -> toast and no state mutation beyond current palette behavior
|
||||
- duplicated live/retained/sleeping metadata -> de-dupe by pane key with live records preferred
|
||||
- orphan or cross-worktree agent records -> ignored unless tied to an existing terminal tab
|
||||
- split groups -> activate result `groupId`
|
||||
- generated titles disabled or overridden -> displayed title follows tab-bar precedence while agent prompt remains searchable
|
||||
- SSH/web runtime -> reuse existing runtime activation call shape
|
||||
- multi-window renderer state -> no shared cache or persisted search index
|
||||
- Test coverage required:
|
||||
- `src/renderer/src/lib/workspace-tab-palette-search.test.ts`: title precedence, editor path/title across editor-family types including markdown preview, agent prompt/session id, retained/sleeping attribution by legacy terminal id, duplicate metadata, orphan exclusion, current-tab/current-worktree ordering
|
||||
- `src/renderer/src/lib/workspace-tab-palette-activation.test.ts`: terminal/editor-family activation, split group focus, web-runtime terminal activation, missing tab/group/backing-file/worktree failures
|
||||
- existing `src/renderer/src/lib/simulator-palette-search.test.ts` and `src/renderer/src/components/cmd-j/palette-results.test.ts` unchanged/pass
|
||||
- Performance/blast radius: no new IPC, persistence, polling, filesystem search, or terminal output indexing. Work is proportional to current open tabs and small bounded agent maps already in memory.
|
||||
- UI quality bar: Electron validation must compare new rows with existing Open Tabs rows against `docs/STYLEGUIDE.md`, with no new colors/shadows/font sizes and no overflow/overlap under narrow palette width.
|
||||
- Required review screenshots:
|
||||
1. Empty Cmd-J palette with terminal/editor rows in Open Tabs.
|
||||
2. Typed query matching a terminal title.
|
||||
3. Typed query matching an agent prompt/session keyword.
|
||||
4. Typed query matching an editor tab title/path.
|
||||
5. Existing browser or simulator tab search still styled correctly.
|
||||
- Residual risks: Electron validation may need to seed a live agent prompt; if a real prompt cannot be created safely, use an existing local non-mutating agent tab or halt before PR creation with nearest screenshots.
|
||||
@@ -1,94 +0,0 @@
|
||||
# Compact Worktree Card Setting Graduation
|
||||
|
||||
## Problem
|
||||
|
||||
`experimentalCompactWorktreeCards` is exposed in two places: the Experimental settings pane and the
|
||||
sidebar workspace options menu. The sidebar menu already presents the durable user-facing model as
|
||||
`Card layout` with `Detailed` and `Compact`, so the Experimental row is redundant and makes the same
|
||||
preference look like two separate features.
|
||||
|
||||
## Goal
|
||||
|
||||
Graduate the preference out of Experimental. Keep the sidebar workspace options menu as the
|
||||
canonical control, preserve existing users' saved compact-card choice, and remove the Experimental
|
||||
pane row/search entry.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Do not change worktree card compact layout behavior.
|
||||
- Do not redesign the workspace options menu.
|
||||
- Do not remove workspace card property or agent activity layout controls.
|
||||
- Do not change SSH, provider metadata, prompt-cache, conflict, or port behavior.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add `compactWorktreeCards` to `GlobalSettings` and defaults.
|
||||
2. Preserve backward compatibility by hydrating `compactWorktreeCards` from legacy
|
||||
`experimentalCompactWorktreeCards` when the new field is absent.
|
||||
3. Update sidebar/worktree-card reads and writes to use `compactWorktreeCards`.
|
||||
4. Remove the Experimental pane row and search entry for `Compact worktree cards`.
|
||||
5. Keep the legacy optional type field only as a read-only migration input.
|
||||
|
||||
## Data Flow
|
||||
|
||||
- Persistence loads settings with defaults.
|
||||
- If `compactWorktreeCards` is missing, persistence copies the old
|
||||
`experimentalCompactWorktreeCards` value, falling back to the default.
|
||||
- The sidebar `Card layout` menu writes `compactWorktreeCards`.
|
||||
- `WorktreeCard` reads `settings?.compactWorktreeCards === true`.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- Old profiles with `experimentalCompactWorktreeCards: true` still render compact cards.
|
||||
- Old profiles with the flag missing still default to detailed cards.
|
||||
- Search in Settings no longer finds a duplicate Experimental result.
|
||||
- Compact-card behavior remains unchanged for metadata rows, unread placement, main-worktree
|
||||
marker, SSH icons, prompt-cache state, conflicts, sparse checkout badges, and inline agents.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- Update default-settings tests for `compactWorktreeCards`.
|
||||
- Add a persistence migration test for legacy `experimentalCompactWorktreeCards`.
|
||||
- Update Experimental pane tests to assert the row/search entry is absent.
|
||||
- Update WorktreeCard tests to set `compactWorktreeCards`.
|
||||
- Run focused tests for constants, persistence, ExperimentalPane, and WorktreeCard compact behavior.
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
The Experimental pane should simply omit the redundant row without leaving spacing gaps. The
|
||||
workspace options menu should continue to show `Card layout` with `Detailed` and `Compact`.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
1. Experimental pane without `Compact worktree cards`.
|
||||
2. Sidebar workspace options menu still showing `Card layout`.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add the new setting and legacy hydration.
|
||||
2. Update card/menu consumers.
|
||||
3. Remove the Experimental pane/search entry.
|
||||
4. Update focused tests.
|
||||
5. Validate the two visible settings surfaces.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: kept to one setting graduation; no card layout behavior changes.
|
||||
- Architecture/data flow: existing settings persistence remains the boundary; renderer consumers read
|
||||
the new key, persistence bridges legacy profiles.
|
||||
- Failure modes covered:
|
||||
- Existing compact users losing the preference: migration copies the legacy flag.
|
||||
- Duplicate settings search result: Experimental search entry is removed.
|
||||
- Renderer/main mismatch: `GlobalSettings`, defaults, and consumers are updated together.
|
||||
- Test coverage required:
|
||||
- `src/shared/constants.test.ts` for the default.
|
||||
- `src/main/persistence.test.ts` for legacy hydration.
|
||||
- `src/renderer/src/components/settings/ExperimentalPane.test.tsx` for removal.
|
||||
- Existing WorktreeCard tests updated to the new key.
|
||||
- Performance/blast radius: no new IPC, polling, file watching, or provider work.
|
||||
- UI quality bar: Experimental pane has no orphan row; sidebar card layout control remains present.
|
||||
- Required review screenshots:
|
||||
1. Experimental pane without the compact-card toggle.
|
||||
2. Sidebar workspace options menu with `Card layout`.
|
||||
- Residual risks: old profiles may keep the legacy key on disk until settings are next saved, but
|
||||
runtime behavior uses the migrated value.
|
||||
@@ -1,126 +0,0 @@
|
||||
# Configurable Open In Menu
|
||||
|
||||
## Current behavior (code-checked)
|
||||
|
||||
- `WorktreeOpenInMenu` renders exactly two entries: `VS Code` and platform file manager (`Finder`/`File Explorer`/`File Manager`).
|
||||
- `openWorktreePath()` blocks local launches for remote/server context via `isLocalPathOpenBlocked(...)` before IPC.
|
||||
- Renderer calls `window.api.shell.openInExternalEditor(path)` with one argument only.
|
||||
- Preload/API types expose `openInExternalEditor(path: string)` only.
|
||||
- Main IPC `shell:openInExternalEditor` always launches hardcoded `code` (via `resolveCliCommand('code')`), validates absolute+exists path, and returns `{ ok: false, reason: 'not-absolute' | 'not-found' | 'launch-failed' }` on failure.
|
||||
- Settings persistence currently shallow-merges most fields. Only `notifications` and `telemetry` are deep-merged in main; renderer deep-merges `notifications`, `telemetry`, and `voice` locally.
|
||||
- `settings:set` returns the merged settings object, but the renderer currently ignores that return value and applies its own optimistic merge.
|
||||
|
||||
## Goal
|
||||
|
||||
Add configurable extra editor launchers (Cursor, Zed, custom) to the worktree sidebar `Open in` submenu while preserving:
|
||||
|
||||
- VS Code as fixed default entry.
|
||||
- existing local-path blocking for remote/SSH/server contexts.
|
||||
- existing path validation and failure-to-toast behavior.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- No remote editor launching.
|
||||
- No command existence checks during settings editing.
|
||||
- No shell template expansion, env interpolation, per-launcher cwd overrides, or argv parsing.
|
||||
- No removal/configuration of the built-in VS Code row.
|
||||
|
||||
## Data model
|
||||
|
||||
Add to `GlobalSettings`:
|
||||
|
||||
- `openInApplications?: OpenInApplication[]`
|
||||
- `type OpenInApplication = { id: string; label: string; command: string }`
|
||||
|
||||
Default in `getDefaultSettings()`:
|
||||
|
||||
- `openInApplications: []`
|
||||
|
||||
Why optional in type but present in defaults: keeps backward compatibility with older persisted files while giving runtime code a stable default after merge.
|
||||
|
||||
## Normalization contract
|
||||
|
||||
Implement one shared normalizer in `src/shared/` and use it in both renderer update path and main persistence update path. It must run in main before persistence.
|
||||
|
||||
Rules:
|
||||
|
||||
- trim `label`/`command`.
|
||||
- drop rows with empty `label` or empty `command`.
|
||||
- drop rows with duplicate `id` (keep first).
|
||||
- if `id` is missing/blank, generate one (e.g. `crypto.randomUUID()` in renderer before save).
|
||||
- cap length (e.g. 8).
|
||||
|
||||
Do not dedupe by `command`: users may intentionally keep separate labels for the same command with different wrappers/scripts later.
|
||||
|
||||
Main remains source of truth. Renderer normalization is UX only; main normalization must always run.
|
||||
|
||||
Also normalize on load (not only on `settings:set`) so externally edited/stale persisted rows are repaired on startup.
|
||||
|
||||
## IPC and launch behavior
|
||||
|
||||
Change signature across shared preload surface and main handler:
|
||||
|
||||
- `openInExternalEditor(path: string, command?: string)`
|
||||
|
||||
Main launch behavior:
|
||||
|
||||
- if `command` is missing/blank after trim, fall back to `code`.
|
||||
- otherwise resolve and launch that command token (same resolution path currently used for `code` via `resolveCliCommand`).
|
||||
- keep existing `validateLocalPathTarget(...)` path checks.
|
||||
- keep `getSpawnArgsForWindows(command, [path])` path for Windows.
|
||||
- keep detached spawn semantics and `launch-failed` mapping.
|
||||
|
||||
Constraint to document in UI copy: command is not shell-parsed. `cursor --new-window` is treated as a binary name and will fail. Users must provide an executable command (or wrapper script) only.
|
||||
|
||||
Important: this is not “free”. Every call site and type layer (`preload/index.ts`, `preload/api-types.ts`, renderer callers, `shell.test.ts`) must be updated together.
|
||||
|
||||
## Menu behavior
|
||||
|
||||
`WorktreeOpenInMenu` order:
|
||||
|
||||
1. `VS Code` (fixed)
|
||||
2. configured `openInApplications`
|
||||
3. file manager
|
||||
|
||||
Each configured row invokes `openInExternalEditor(worktreePath, app.command)`.
|
||||
|
||||
Remote/local guard stays exactly where it is now (`openWorktreePath`) so all rows (including file manager) remain blocked consistently in remote contexts.
|
||||
|
||||
## Settings UI
|
||||
|
||||
Add General section: `Open In Menu`.
|
||||
|
||||
- static note: VS Code is always included.
|
||||
- presets: add Cursor (`cursor`) and Zed (`zed`).
|
||||
- editable rows for label/command.
|
||||
- remove row.
|
||||
- add custom row.
|
||||
|
||||
Search indexing: add entries in `general-search.ts` so settings search can discover this section.
|
||||
|
||||
## Consistency and concurrency
|
||||
|
||||
- Multi-window: renderer has a `settings:changed` listener, but main currently emits that event only for View > Appearance toggles. `settings:set` does not broadcast generic updates. So edits to `openInApplications` in one window are not guaranteed to appear live in another until reload/fetch.
|
||||
- Renderer optimistic merge is temporary UI state only. Main write result is authoritative and may normalize away invalid rows. Use the `settings:set` return value to rebase local state immediately after each write.
|
||||
- Concurrent edits are last-write-wins at the field level (`openInApplications` array replaced wholesale). There is no compare-and-swap/version guard.
|
||||
- External file mutation of `orca-data.json` is only observed on app restart; no live file watch exists.
|
||||
|
||||
## Edge cases
|
||||
|
||||
- Empty/whitespace command or label -> dropped by normalizer.
|
||||
- Missing `openInApplications` in persisted settings -> treated as `[]` via defaults merge.
|
||||
- Duplicate IDs (including hand-edited config) -> first survives, later rows dropped.
|
||||
- Command strings with spaces/flags (e.g. `cursor --foo`) -> fail at spawn unless provided via wrapper executable.
|
||||
- Launcher not in PATH or non-executable -> `launch-failed` and existing toast.
|
||||
- Path exists but is a file (not directory) still passes current validation and will be passed to launcher/file manager; this is existing behavior.
|
||||
- Relative/non-existent worktree path -> existing `not-absolute`/`not-found` error flow.
|
||||
- Remote/server worktree -> blocked before IPC regardless of configured launchers.
|
||||
|
||||
## Tests required
|
||||
|
||||
- `shell.test.ts`: optional command path, blank command fallback to `code`, Windows spawn arg path, failure mapping.
|
||||
- `WorktreeOpenInMenu.test.tsx`: configured rows render in order, command forwarded, remote guard still blocks all targets.
|
||||
- settings normalization tests (shared normalizer + persistence update path): trim, drop invalid rows, cap, duplicate-id behavior.
|
||||
- settings normalization tests: missing/blank id handling and generated-id stability on edit.
|
||||
- `settings:set`/renderer integration test: renderer applies authoritative returned settings, not only optimistic local merge.
|
||||
- General settings search entries include new section keywords.
|
||||
@@ -1,152 +0,0 @@
|
||||
# Delete Windows Workspace Without False Unregistered Error
|
||||
|
||||
## Problem
|
||||
|
||||
GitHub issue [#5864](https://github.com/stablyai/orca/issues/5864) reports that Orca on Windows v0.14.80 fails to delete a workspace created from a project `+` button:
|
||||
|
||||
`Error invoking remote method 'worktrees:remove': Error: Refusing to delete unregistered worktree path: C:/Users/andy/orca/workspaces/ops-tools/packaging-improvements-2`
|
||||
|
||||
Relevant flow:
|
||||
|
||||
- Renderer delete calls local IPC for local targets in `src/renderer/src/store/slices/worktrees.ts`.
|
||||
- Preload exposes that as `worktrees:remove` in `src/preload/index.ts`.
|
||||
- IPC delete lists Git worktrees, matches the requested path, and throws the unregistered error if no registered entry matches in `src/main/ipc/worktrees.ts`.
|
||||
- Runtime RPC delete has the same registered-worktree gate in `src/main/runtime/orca-runtime.ts`.
|
||||
- Windows create/list coverage exists in `src/main/ipc/worktrees-windows.test.ts`, but Windows delete coverage is missing.
|
||||
|
||||
## Root Cause
|
||||
|
||||
Delete is right to refuse arbitrary paths. This bug is a false negative in the proof step: Orca asks Git for the authoritative registered worktree list, but the list does not contain an entry equivalent to the project-created target.
|
||||
|
||||
Do not fix this by adding another path-normalization layer after the list. `findRegisteredDeletableWorktree` delegates to `areWorktreePathsEqual`, which already treats `C:/...`, `C:\...`, and drive-case variants as equal while keeping POSIX/WSL paths distinct. `git/worktree.removeWorktree` has a similar comparator for its fallback branch lookup.
|
||||
|
||||
The credible failure surfaces are before or around that comparator:
|
||||
|
||||
- Delete may list through a different local runtime than create/list/selector resolution, especially for project runtime settings on Windows.
|
||||
- `listWorktrees` currently returns `[]` for several Git/list failures. In delete, that collapses "could not prove registration" into the misleading unregistered-path error.
|
||||
- Runtime selector/list resolution calls `listRepoWorktreesForResolution(repo)`, which currently omits local project runtime options.
|
||||
- Runtime removal validates a registered row, but then calls `removeWorktree` without `knownRemovedWorktree`, allowing the Git helper to rescan under the supplied options.
|
||||
- Some runtime cleanup paths still omit or recompute local runtime options instead of using the option set captured for the delete.
|
||||
|
||||
Implementation must start with a failing regression. If an equivalent Windows row is present in the registered list under the right options, deletion should succeed without further path comparator changes.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Do not allow deletion of existing unregistered directories.
|
||||
- Do not bypass the main-worktree, nested-worktree, local dirty-worktree, archive-hook, branch-preservation, or concurrent-delete guards.
|
||||
- Do not change delete dialog UI/copy.
|
||||
- Do not change SSH provider semantics.
|
||||
- Do not add a broad path abstraction or metadata migration.
|
||||
|
||||
## Design
|
||||
|
||||
1. Capture one repo-scoped local Git option set for the delete.
|
||||
- For local repos, use the repo's project runtime options from `getLocalProjectWorktreeGitOptions(store, repo)`. This is already repo-scoped and surfaces repair-required project runtimes before any Git command.
|
||||
- Do not use `getLocalGitOptionsForRegisteredWorktree` for delete. It scans all repos and uses native `path.resolve`, which is not a safe Windows-equivalence test on macOS/Linux test hosts.
|
||||
- Do not choose options from a worktree path alone. The parsed `repoId` is the authority for local runtime selection; exact-ID fallback after selector failure should still use the owning repo's project runtime options.
|
||||
- Keep SSH paths on the existing provider branch.
|
||||
|
||||
2. Make the authoritative Git list strict enough for delete.
|
||||
- Delete must distinguish "Git listed zero matching worktrees" from "Git listing failed." A selected-runtime Git/list failure should surface the underlying failure, not turn into `Refusing to delete unregistered worktree path`.
|
||||
- If this requires a strict list API beside `listWorktrees`, keep it narrow and delete-only; do not change polling/list UI behavior that intentionally tolerates transient Git failures.
|
||||
- The registered row returned by Git remains the canonical removal target after `findRegisteredDeletableWorktree` succeeds.
|
||||
|
||||
3. Thread the captured option set through the full local removal path.
|
||||
- `listWorktrees`, archive hooks, orphan proof reads, missing-path checks, clean preflight, `git worktree remove`, branch cleanup, recursive orphan cleanup, filesystem delete, push-target cleanup, and `git worktree prune` must all use the same captured options.
|
||||
- Do not recompute project runtime options later in the operation. A project runtime setting change during an in-flight delete must not split one deletion across two runtimes.
|
||||
- IPC already passes `knownRemovedWorktree` to `removeWorktree`; keep that behavior.
|
||||
- Runtime removal must also pass `knownRemovedWorktree` so branch cleanup uses the validated row and avoids a second list.
|
||||
- Replace current runtime cleanup call sites that omit `localWorktreeGitOptions` for push-target remote cleanup.
|
||||
- Replace prune calls that recompute `getLocalProjectGitExecOptions(...)` with `{ cwd: repo.path, ...localWorktreeGitOptions }`.
|
||||
|
||||
4. Fix runtime resolution/listing.
|
||||
- Update `listRepoWorktreesForResolution(repo)` to call `listRepoWorktrees(repo, getLocalProjectWorktreeGitOptions(store, repo))` for local repos.
|
||||
- Runtime exact-ID deletes should re-list Git under the captured options before destructive work; selector caches are convenience only, not delete authority.
|
||||
- Runtime archive hooks should use the captured options rather than `this.getLocalGitExecutionOptionArgs(repo)[0]`.
|
||||
|
||||
## Data Flow
|
||||
|
||||
- Delete action -> `removeWorktree(worktreeId, force)` in renderer.
|
||||
- Local target -> `window.api.worktrees.remove({ worktreeId, force, skipArchive })`.
|
||||
- Main parses `repoId` and `worktreePath`.
|
||||
- Main resolves the repo and captures one local Git option set for that repo.
|
||||
- Main strictly lists registered Git worktrees with those options.
|
||||
- Main matches requested path to registered path with `areWorktreePathsEqual` via `findRegisteredDeletableWorktree`.
|
||||
- Main uses the registered canonical path for hooks, preflight, watcher close, Git removal, orphan cleanup, metadata cleanup, and sidebar refresh. PTY teardown remains keyed by the exact worktree ID.
|
||||
|
||||
Runtime RPC follows the same rule after selector resolution, and exact-ID fallback must still re-list Git before destructive work.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- `C:/...`, `C:\...`, and drive-letter case variants refer to the same Windows worktree.
|
||||
- POSIX WSL paths and Windows paths must not compare equal unless `listWorktrees` translated them through the selected WSL options.
|
||||
- UNC paths, drive-letter paths, and `/mnt/<drive>` paths need explicit tests because Node path behavior is platform-specific on macOS/Linux test hosts.
|
||||
- Main worktree deletion is still rejected.
|
||||
- Parent worktree deletion is still rejected if another registered worktree is nested inside it.
|
||||
- Existing unregistered directories are still rejected, even with `force`.
|
||||
- Already-missing Orca-known worktrees still clean metadata only.
|
||||
- Orphaned Orca-created worktree directories still require proof through the `.git` file before recursive deletion.
|
||||
- Multi-window IPC deletes coalesce only for the same exact worktree ID and options. Equivalent Windows paths with different IDs, or IPC/runtime deletes racing each other, must degrade to safe missing/orphan handling or a protected error.
|
||||
- External Git mutation between list and `git worktree remove` is handled by the existing missing/orphan branches; keep those branches under the same captured runtime options.
|
||||
- Project runtime setting changes during an in-flight delete affect only later deletes.
|
||||
- SSH deletes still use SSH Git/filesystem providers and do not touch local paths.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- Unit:
|
||||
- `pnpm vitest run src/main/ipc/worktrees-windows.test.ts`
|
||||
- `pnpm vitest run src/main/ipc/worktrees.test.ts --testNamePattern "local worktree removal|selected WSL project runtime|unregistered delete|contains another registered|already-missing"`
|
||||
- `pnpm vitest run src/main/runtime/orca-runtime.test.ts --testNamePattern "worktree removal|selected WSL project runtime|unregistered delete|contains another registered|already-missing"`
|
||||
- Required new coverage:
|
||||
- IPC Windows delete regression: request path uses `C:/...`, Git registered row uses backslashes and/or different drive-case, delete succeeds, hooks/preflight/removal use the canonical registered path, `knownRemovedWorktree` is passed, metadata is removed, and `worktrees:changed` emits.
|
||||
- Runtime Windows delete regression with the same path mismatch. Assert selector/list resolution and final removal both use selected project runtime options, and `knownRemovedWorktree` is passed.
|
||||
- Strict-list failure regression: a selected-runtime list failure rejects with the list failure, not the unregistered-path error.
|
||||
- Negative Windows/WSL mismatch: POSIX `/mnt/c/...` or WSL-native paths must not match unrelated Windows paths unless translated by the selected WSL options.
|
||||
- Runtime cleanup regressions for already-missing/orphan/push-target cleanup under selected WSL options.
|
||||
- Integration/e2e:
|
||||
- Electron smoke with a disposable local repo/worktree: delete succeeds, row disappears, no new delete UI regressions.
|
||||
- Real Windows validation is preferred. macOS/Linux unit tests can cover comparator and option plumbing, but they cannot fully prove Node and Git path behavior on Windows.
|
||||
- Full checks:
|
||||
- `pnpm typecheck`
|
||||
- `pnpm lint`
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
No intentional UI change. Existing delete dialog, progress state, toast behavior, and sidebar row removal should remain visually unchanged and follow `docs/STYLEGUIDE.md`.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
No design screenshots are required for a backend-only fix. If the PR needs Electron smoke evidence, attach only:
|
||||
|
||||
1. Disposable workspace delete confirmation before confirming.
|
||||
2. Sidebar after successful deletion with the row gone.
|
||||
|
||||
Do not spend review time manufacturing a protected/error screenshot; cover that with unit tests.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add focused Windows-path delete regression tests.
|
||||
2. Add strict delete listing or equivalent failure propagation.
|
||||
3. Update runtime selector/list resolution to use local project runtime options.
|
||||
4. Thread captured options and `knownRemovedWorktree` through IPC/runtime delete paths.
|
||||
5. Run focused tests, typecheck, lint.
|
||||
6. Electron-validate the unchanged delete UI on a disposable workspace and collect screenshots only if required.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: delete-only; no renderer changes, no new deletion authority, and no broad path-normalization rewrite.
|
||||
- Architecture/data flow: local IPC and runtime RPC both keep Git as the authority. The fix is to ask Git through the correct project runtime, treat list failures as failures, then use Git's registered row as the canonical removal target.
|
||||
- Failure modes covered:
|
||||
- Windows slash/drive-case mismatches.
|
||||
- Wrong or failed local project runtime listing.
|
||||
- Runtime selector resolution using host listings.
|
||||
- Runtime branch cleanup rescanning instead of using the validated row.
|
||||
- Metadata absent or stale during already-missing cleanup.
|
||||
- Existing unregistered directory remains protected.
|
||||
- Main and nested registered worktrees remain protected.
|
||||
- SSH paths stay provider-owned.
|
||||
- Performance/blast radius: no material concern if the delete path performs one strict authoritative list and passes `knownRemovedWorktree` to avoid the helper rescan.
|
||||
- Feasibility: this is not a "one comparator call" fix. The current APIs make `listWorktrees` failures look like empty lists, and runtime selector resolution currently omits local runtime options.
|
||||
- UI quality bar: no UI-visible design change; Electron should judge that existing delete dialog, progress, toast, and row removal still look unchanged against `docs/STYLEGUIDE.md`.
|
||||
- Required review screenshots: none for the backend fix; optional disposable-workspace smoke screenshots only if the PR process asks for visual evidence.
|
||||
- Residual risks: true Windows filesystem/Git spelling behavior still depends on a Windows runner or user validation; macOS/Linux tests cannot fully model it.
|
||||
@@ -1,247 +0,0 @@
|
||||
# Double-tap modifier keybindings — design
|
||||
|
||||
## Goal
|
||||
|
||||
Allow any keybinding action to be bound to a **double-tap of a bare modifier**
|
||||
(Shift, Cmd/Ctrl, Alt) in Settings → Shortcuts. A double-tap binding is stored,
|
||||
recorded, formatted, conflict-checked, and matched alongside normal bindings,
|
||||
and fires everywhere a normal shortcut does — including when a browser guest or
|
||||
terminal owns focus.
|
||||
|
||||
Example: bind `DoubleTap+Shift` to `worktree.quickOpen` ("Go to File"), then
|
||||
tapping Shift twice opens Go to File (IntelliJ "double-Shift" style).
|
||||
|
||||
## Why this is not just another binding
|
||||
|
||||
The existing keybinding system is **stateless and per-keydown**: every binding
|
||||
has at least one modifier and exactly one key, and matching compares a single
|
||||
`KeyboardEvent`'s modifier state + key against the stored binding string
|
||||
(`keybindingMatchesInput` in `src/shared/keybindings.ts`). A double-tap is a
|
||||
**timed sequence of a bare modifier with no key** — press M, release M, press M
|
||||
again within a short window. It cannot be represented by the current grammar or
|
||||
matched by the current stateless comparison.
|
||||
|
||||
Dispatch is also split across two layers, and both must participate for a
|
||||
double-tap to work for "any action":
|
||||
|
||||
- **Main process** — `before-input-event` in
|
||||
`src/main/window/createMainWindow.ts` matches an explicit allowlist of ~20
|
||||
actions via `resolveWindowShortcutAction`
|
||||
(`src/shared/window-shortcut-policy.ts`), calls `preventDefault()`, and
|
||||
forwards the action to the renderer over IPC. This layer exists so a subset of
|
||||
shortcuts work even when focus lives in a browser guest `webContents` or a
|
||||
contentEditable surface that bypasses the renderer's window-level listener.
|
||||
- **Renderer** — the window `keydown` handler in
|
||||
`src/renderer/src/App.tsx` matches most actions via `keybindingMatchesAction`
|
||||
and runs their effects inline.
|
||||
|
||||
## Approach (chosen): synthetic input through the existing matchers
|
||||
|
||||
Detect the double-tap with a small shared state machine, then represent the
|
||||
completed gesture as a **synthetic shortcut input** carrying a
|
||||
`doubleTapModifier` marker and run that input through the *existing* dispatch
|
||||
chains in both layers. The matcher is extended so a `DoubleTap+<Mod>` binding
|
||||
matches only that synthetic input (and never a normal keydown, and vice-versa).
|
||||
|
||||
Because the existing dispatch chains already call
|
||||
`keybindingMatchesAction(actionId, input, …)`, every action that is already
|
||||
wired in those chains gains double-tap support automatically — no per-action
|
||||
dispatch table to build or keep in sync.
|
||||
|
||||
Rejected alternatives:
|
||||
|
||||
- **Per-action dispatch registry** — detector resolves action ids and calls a
|
||||
new `dispatchActionById()` implemented per action. Avoids refactoring the
|
||||
renderer handler but duplicates action effects that already live there, drifts
|
||||
over time, and only supports actions we explicitly wire — not "any action".
|
||||
- **Re-dispatch a synthetic DOM `KeyboardEvent`** — a double-tap can't be
|
||||
expressed as a standard key event without a key, and re-dispatching risks
|
||||
event loops.
|
||||
|
||||
## Components
|
||||
|
||||
### 1. Binding grammar — `src/shared/keybindings.ts`
|
||||
|
||||
- New canonical form `DoubleTap+<Mod>` where `<Mod>` is one of `Shift`, `Mod`,
|
||||
`Cmd`, `Ctrl`, `Alt`. `Mod` resolves to Cmd on macOS and Ctrl on
|
||||
Windows/Linux, identical to normal bindings.
|
||||
- `ParsedKeybinding` gains `doubleTapModifier?: ModifierToken` and permits an
|
||||
empty `key` (only when `doubleTapModifier` is set).
|
||||
- `parseKeybinding` recognizes a leading `DoubleTap` token followed by exactly
|
||||
one modifier token and **no** key token. Anything else with `DoubleTap` is
|
||||
invalid.
|
||||
- `canonicalizeParsedKeybinding` emits `DoubleTap+<Mod>` (modifier in the same
|
||||
canonical position rules as today).
|
||||
- `normalizeKeybindingWithOptions` accepts a well-formed double-tap binding and
|
||||
rejects malformed ones with clear errors:
|
||||
- `DoubleTap` + a key (e.g. `DoubleTap+Shift+P`) → invalid.
|
||||
- `DoubleTap` + two modifiers (e.g. `DoubleTap+Shift+Alt`) → invalid.
|
||||
- `DoubleTap+Mod+Cmd` (both forms) → reuse the existing "Mod or
|
||||
platform-specific, not both" error.
|
||||
- bare `DoubleTap` with no modifier → invalid.
|
||||
- `formatKeybinding` returns the modifier glyph **twice**: macOS `['⇧','⇧']`,
|
||||
Windows/Linux `['Shift','Shift']`.
|
||||
- `ShortcutKeyCombo` renders the two chips. Double-tap is special-cased so the
|
||||
non-Mac separator reads "Shift Shift" (space), not "Shift+Shift". A
|
||||
"Double-tap Shift" tooltip clarifies the gesture.
|
||||
|
||||
### 2. Detector — new module `src/shared/modifier-double-tap-detector.ts`
|
||||
|
||||
A pure, dependency-free state machine. Timestamps are **injected** by the caller
|
||||
so it is deterministic and unit-testable.
|
||||
|
||||
```
|
||||
class ModifierDoubleTapDetector {
|
||||
// event: { type: 'keyDown' | 'keyUp', modifier: ModifierToken | null,
|
||||
// isModifierOnly: boolean, isAutoRepeat: boolean }
|
||||
process(event, timestampMs): DetectedDoubleTap | null
|
||||
reset(): void
|
||||
}
|
||||
```
|
||||
|
||||
State machine:
|
||||
|
||||
1. **idle** → on a modifier-only `keyDown` of M that is not autorepeat: remember
|
||||
M, wait for its release.
|
||||
2. **down1** → on `keyUp` of M (clean, no other key seen): record release time,
|
||||
move to **armed(M)** with deadline `releaseTime + WINDOW_MS`.
|
||||
3. **armed(M)** → on `keyDown` of the same M within the deadline, with no other
|
||||
modifier held and no intervening non-modifier key: **emit** a double-tap of M
|
||||
and reset.
|
||||
|
||||
Any of these reset to idle: a non-modifier key event at any point, a different
|
||||
or additional modifier, autorepeat-hold of the modifier, exceeding the window,
|
||||
or an explicit `reset()` (e.g. on window blur / focus change).
|
||||
|
||||
`WINDOW_MS = 300` (internal constant; not user-configurable). A helper derives
|
||||
`(modifier, isModifierOnly)` from an event's `code`/`key`.
|
||||
|
||||
### 3. Matcher extension — `src/shared/keybindings.ts`
|
||||
|
||||
- `KeybindingInput` gains `doubleTapModifier?: ModifierToken`.
|
||||
- `keybindingMatchesInput`: when the parsed binding is a double-tap binding,
|
||||
match iff `input.doubleTapModifier` equals the binding's modifier, resolved per
|
||||
platform (`Mod` → meta on macOS, control elsewhere). A double-tap binding never
|
||||
matches a normal keydown (no `doubleTapModifier`), and a normal binding never
|
||||
matches a synthetic double-tap input.
|
||||
- No change to `keybindingMatchesAction` — it already delegates to
|
||||
`keybindingMatchesInput`, so any action becomes double-tap-capable for free.
|
||||
|
||||
### 4. Dispatch wiring — both layers
|
||||
|
||||
- **Main** (`src/main/window/createMainWindow.ts`): instantiate a
|
||||
`ModifierDoubleTapDetector` per window. In `before-input-event`, feed every
|
||||
`keyDown`/`keyUp` to the detector (it only consumes bare-modifier events). On
|
||||
emit, build the synthetic input `{ doubleTapModifier: M }`, run the existing
|
||||
`resolveWindowShortcutAction(syntheticInput, platform, keybindings,
|
||||
terminalShortcutContext)`, and if an allowlisted action resolves, dispatch via
|
||||
the current IPC + `preventDefault()` path. `resolveWindowShortcutAction` needs
|
||||
no per-action change; the implicit numeric-index shortcuts are guarded on
|
||||
`input.key`, which is undefined for a double-tap input, so they cannot match.
|
||||
Only the emitting second-keydown event is `preventDefault()`-ed — never the
|
||||
first tap's down/up (those bare modifiers are harmless and the keyup is needed
|
||||
by the detector).
|
||||
- **Renderer** (`src/renderer/src/App.tsx`): extract the body of the window
|
||||
`onKeyDown` handler into `dispatchShortcutInput(input: ShortcutDispatchInput)`,
|
||||
where `ShortcutDispatchInput` exposes the modifier/key fields plus
|
||||
`doubleTapModifier?`, a `preventDefault()` (no-op for synthetic input),
|
||||
`defaultPrevented`, and the focus/target context. The real listener wraps the
|
||||
`KeyboardEvent`; a renderer `ModifierDoubleTapDetector` (fed by both a keydown
|
||||
and a **new** keyup window listener) produces a synthetic input on emit with
|
||||
`context` derived from `document.activeElement`, and calls
|
||||
`dispatchShortcutInput`.
|
||||
|
||||
#### No double-fire between layers
|
||||
|
||||
This reuses the exact disambiguation normal shortcuts already rely on:
|
||||
|
||||
- For an **allowlisted** action, main detects the double-tap on the second
|
||||
modifier keydown, resolves it, and calls `preventDefault()`. That suppresses
|
||||
the corresponding renderer DOM keydown, so the renderer detector never
|
||||
completes its second tap → it does not fire. (The renderer detector may have
|
||||
observed the first tap's down/up. It has no timer: the second-press window is
|
||||
enforced by comparing the next keydown's timestamp against a deadline. The
|
||||
suppressed second keydown never arrives, but its keyup still does — a keyup of
|
||||
the armed modifier with no intervening second keydown clears the armed state,
|
||||
so a later lone press of the same modifier cannot phantom-complete the gesture.)
|
||||
- For a **non-allowlisted** action, main's detector still emits but
|
||||
`resolveWindowShortcutAction` returns `null`, so main does not call
|
||||
`preventDefault()`. The second-keydown DOM event reaches the renderer, whose
|
||||
detector completes and fires via `dispatchShortcutInput`.
|
||||
|
||||
### 5. Recorder UX — `ShortcutBindingRow.tsx` + `ShortcutsPane.tsx`
|
||||
|
||||
The recorder currently captures on the first keydown, which makes a bare
|
||||
modifier error with "Press a key, not only a modifier." Change the row so that
|
||||
while recording it runs a `ModifierDoubleTapDetector` fed by the row button's
|
||||
keydown **and keyup** (the button holds focus during recording, so it receives
|
||||
both):
|
||||
|
||||
- A bare-modifier keydown no longer captures immediately — the detector observes
|
||||
it.
|
||||
- A non-modifier keydown (with or without modifiers) captures a normal binding,
|
||||
exactly as today.
|
||||
- A completed double-tap captures `DoubleTap+<Mod>`: the row passes
|
||||
`{ doubleTapModifier: M }` into the capture path, and
|
||||
`keybindingFromInputWithOptions` short-circuits to build `DoubleTap+<Mod>`
|
||||
(mapping meta → `Mod` on macOS, etc.) and normalizes it.
|
||||
- A single lone modifier tap that never completes is ignored — the recorder
|
||||
keeps listening.
|
||||
|
||||
Helper text while recording: *"Press a shortcut, or double-tap a modifier (e.g.
|
||||
⇧⇧)."* Esc still cancels. The detector is reset when recording stops or the row
|
||||
loses focus.
|
||||
|
||||
### 6. Conflicts & terminal policy
|
||||
|
||||
`DoubleTap+Shift` is a canonical binding string, so `findKeybindingConflicts`
|
||||
compares it like any other binding — two actions sharing a double-tap surface a
|
||||
conflict in the UI. Terminal-policy gating (`keybindingIsActiveInContext`,
|
||||
orca-first / terminal-first) applies unchanged. Note that a bare modifier press
|
||||
emits no terminal bytes, so detecting a double-tap never steals readline input;
|
||||
policy is still honored for consistency.
|
||||
|
||||
## Data flow
|
||||
|
||||
- **Record:** row keydown/keyup → row detector → `{ doubleTapModifier: M }` →
|
||||
`keybindingFromInputForAction` → `DoubleTap+<Mod>` → stored as
|
||||
`["DoubleTap+Shift"]` in `~/.orca/keybindings.json`.
|
||||
- **Runtime:** physical modifier taps → main + renderer detectors → synthetic
|
||||
`{ doubleTapModifier: M }` → existing matchers → action dispatched (main IPC
|
||||
for allowlisted actions, renderer inline for the rest).
|
||||
|
||||
## Behavioral decisions
|
||||
|
||||
- **Trigger edge:** fire on the **second modifier keydown** (snappy), not the
|
||||
second keyup.
|
||||
- **Window:** `WINDOW_MS = 300`, internal constant, not user-configurable.
|
||||
- **Modifiers supported:** Shift, Cmd/Ctrl (`Mod`), Alt — any modifier, recorded
|
||||
as the platform-appropriate token following the existing capture convention.
|
||||
|
||||
## Testing
|
||||
|
||||
- New `src/shared/modifier-double-tap-detector.test.ts`: completion within
|
||||
window; timeout past window; reset on intervening non-modifier key; reset on
|
||||
different/extra modifier; autorepeat-hold is not a tap; wrong-modifier second
|
||||
tap; `reset()` clears state.
|
||||
- `src/shared/keybindings.test.ts` additions: parse / normalize / canonicalize /
|
||||
format for `DoubleTap+*` (incl. malformed-input rejection); platform token
|
||||
mapping (`DoubleTap+Mod` → Cmd on macOS, Ctrl elsewhere);
|
||||
`keybindingMatchesInput` with a synthetic `doubleTapModifier` input (positive
|
||||
and cross-type negatives); conflict detection across two double-tap bindings.
|
||||
- Manual: record `DoubleTap+Shift` on "Go to File"; confirm it fires globally
|
||||
including with a browser guest and a focused terminal; confirm normal Shift+key
|
||||
typing is unaffected; confirm chips and tokens are correct on macOS and
|
||||
Windows/Linux.
|
||||
|
||||
## Risks & edge cases
|
||||
|
||||
- **Accidental triggers during fast typing** — mitigated by requiring a clean
|
||||
down→up→down of the same modifier with no other key, inside a 300ms window.
|
||||
- **macOS Sticky Keys (press Shift 5×)** — unaffected; the gesture is two taps
|
||||
within a tight window.
|
||||
- **Double-fire main vs renderer** — resolved by the
|
||||
`preventDefault`-on-emit mechanism described in §4.
|
||||
- **Focus/window changes mid-sequence** — both detectors reset on blur / focus
|
||||
change (hook into the existing recorder/terminal focus reset paths in the main
|
||||
process and a window blur listener in the renderer).
|
||||
@@ -1,83 +0,0 @@
|
||||
# Droid Orchestration Group
|
||||
|
||||
## Problem
|
||||
|
||||
Issue #4560 reports that Orca CLI / orchestration cannot be used with a Droid agent. Droid is already a first-class launchable agent in `src/shared/tui-agent-config.ts:240`, title detection token-matches Droid in `src/shared/agent-detection.ts:38` and `src/shared/agent-detection.ts:397`, and `--inject` accepts a detected running agent through `runtime.isTerminalRunningAgent` in `src/main/runtime/rpc/methods/orchestration.ts:429`. The gap found locally is that orchestration agent groups are hardcoded to `claude`, `openclaude`, `codex`, `opencode`, and `gemini` in `src/main/runtime/orchestration/groups.ts:7`, so `@droid` resolves to no recipients.
|
||||
|
||||
## Root Cause
|
||||
|
||||
The orchestration group resolver has its own closed list of addressable agent-name groups instead of deriving from the agent set that Orca can launch and recognize. Droid was added to the catalog and status paths, but not to this separate group list.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Do not change Droid hook installation or Droid CLI launch semantics.
|
||||
- Do not add a protocol adapter or new orchestration transport.
|
||||
- Do not broaden `--inject` to send preambles into arbitrary shells.
|
||||
- Do not change UI layout, styling, or agent picker ordering.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add `droid` to orchestration's agent-name group allowlist.
|
||||
2. Keep title matching token-based so `@droid` does not match Android paths, titles, or package names.
|
||||
3. Update orchestration group tests to cover `@droid` positive and Android false-positive cases.
|
||||
4. Update CLI-facing error/help text and shipped orchestration skill docs where they name example agent groups so Droid is not implied unsupported.
|
||||
|
||||
## Data Flow
|
||||
|
||||
- User sends `orca orchestration send --to @droid ...`.
|
||||
- CLI calls `orchestration.send`.
|
||||
- Runtime lists terminal summaries.
|
||||
- `resolveGroupAddress` sees `@droid`, matches terminal titles with the existing token regex, and returns Droid terminal handles.
|
||||
- Runtime inserts one message per recipient and delivers pending messages to idle terminals.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- `@droid` must match `Droid ready` and `Droid - action required`.
|
||||
- `@droid` must not match `Android build`, `/tmp/android`, or `my-droid-worker`.
|
||||
- Sender is still excluded from group fan-out.
|
||||
- Unknown groups continue resolving to an empty list.
|
||||
- SSH/remote terminals rely on the same terminal summaries and titles, so no local-path assumptions are introduced.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- Unit: `src/main/runtime/orchestration/groups.test.ts` covers `@droid` positive fan-out and Android/path/hyphen false positives.
|
||||
- Unit: existing `src/shared/agent-detection` coverage remains the title-status source of truth; no changes expected.
|
||||
- Unit: existing orchestration RPC group fan-out tests should continue passing.
|
||||
- Manual/CLI: with a Droid terminal title, `orca orchestration send --to @droid --subject ...` should resolve recipients; without one it should report no recipients.
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
Not UI-visible. Behavior changes only affect CLI orchestration group routing and error/help copy.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
No required UI screenshots. Stage 6 should capture a terminal/CLI validation artifact only if Electron validation creates a visible terminal state.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Update orchestration group allowlist and tests.
|
||||
2. Update example/error copy.
|
||||
3. Run focused unit tests for group resolution and orchestration send behavior.
|
||||
4. Run typecheck/lint if the focused tests pass.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: reduced to group resolution and copy because Droid is already in launch, hook, title, and process-recognition paths.
|
||||
- Architecture/data flow: keep the boundary inside `src/main/runtime/orchestration/groups.ts`; runtime RPC continues delegating fan-out through the existing resolver.
|
||||
- Failure modes covered:
|
||||
- Android false positives from substring matching.
|
||||
- Hyphen/path token false positives.
|
||||
- Sender exclusion in group fan-out.
|
||||
- Unknown groups preserving empty-resolution behavior.
|
||||
- Test coverage required:
|
||||
- `src/main/runtime/orchestration/groups.test.ts` for `@droid` matching and false positives.
|
||||
- Existing `src/main/runtime/rpc/methods/orchestration.test.ts` smoke for agent group fan-out.
|
||||
- Performance/blast radius: no material concern; one string added to a small in-memory list and one extra unit-test case.
|
||||
- UI quality bar: not UI-visible.
|
||||
- Required review screenshots: none; validation should rely on CLI/test output unless a visible terminal state is exercised.
|
||||
- Residual risks: if Droid's real TUI never sets a title containing `Droid`, `@droid` still needs foreground-process-aware group resolution in a follow-up. Current code already synthesizes Droid titles from hooks, so this is expected to work for hook-enabled Droid sessions.
|
||||
|
||||
## Codex Review
|
||||
|
||||
- Round 1: tightened scope to include shipped orchestration skill/help text because it documents the same hardcoded group list users see when learning the feature.
|
||||
- Residual issues: none known within the small group-routing fix.
|
||||
@@ -1,92 +0,0 @@
|
||||
# Layout-aware find in editable Monaco editors
|
||||
|
||||
## Problem
|
||||
|
||||
Issue [#7953](https://github.com/stablyai/orca/issues/7953) reports that `Cmd+F` can type `f` into a TypeScript file instead of opening find on macOS.
|
||||
|
||||
Orca's editable Monaco surfaces currently install its layout-aware save shortcut through `editor-shortcuts.ts` (`src/renderer/src/components/editor/editor-shortcuts.ts:18`), but leave find entirely to Monaco's internal keycode dispatch. Orca already declares `editor.find` as `Mod+F` (`src/shared/keybindings.ts:784`) and its matcher resolves logical keys before physical-code fallback (`src/shared/keybindings.ts:2041`).
|
||||
|
||||
A real Electron repro sends a macOS event with logical key `f`, physical code `KeyU`, and virtual key code `U`, as produced by a non-QWERTY layout. Monaco leaves its find widget closed. The equivalent QWERTY `KeyF` event opens it.
|
||||
|
||||
## Root cause
|
||||
|
||||
Monaco's built-in find keybinding follows the physical/virtual keycode delivered by Chromium. Orca's shortcut system is layout-aware, but its editable Monaco integrations do not use it for find. On layouts where the key that produces `f` is not physical `KeyF`, Monaco misses the chord and Native Edit Context remains in editing mode.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Reimplementing Monaco's find widget, match navigation, or search state.
|
||||
- Changing find behavior in markdown preview, rich markdown, PDF, browser, terminal, or file search.
|
||||
- Changing find behavior in read-only diff surfaces.
|
||||
- Reworking all Monaco keybindings or making Monaco defaults fully obey shortcut unbinding in this patch.
|
||||
- Adding telemetry for a local keyboard action.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add a focused editor find installer beside the existing save installer in `editor-shortcuts.ts`. It matches `editor.find` through `editorShortcutMatches`, consumes every matched event before it reaches Native Edit Context or Monaco, and invokes a supplied callback only for the initial, non-repeat keydown. Repeat events must still be prevented and propagation-stopped so Monaco's QWERTY binding cannot reopen/reset the widget.
|
||||
2. Install that handler on every editable Monaco container in the source editor, editable diff views, and notebook code cells. Run that editor's existing `actions.find` action and dispose the bridge from its existing teardown callback.
|
||||
3. Add unit coverage at the DOM-listener seam for logical `f` with a non-`KeyF` physical code, QWERTY/default behavior, repeat suppression, unrelated typing, and cleanup.
|
||||
4. Preserve an Electron regression loop that drives both QWERTY and layout-aware raw key events against a real `.ts` editor and verifies the existing Monaco find widget becomes visible without dirtying the file.
|
||||
|
||||
## Data flow
|
||||
|
||||
- macOS/Linux/Windows keydown reaches the focused editable Monaco container.
|
||||
- `editorShortcutMatches('editor.find', event)` resolves the active platform, user bindings, modifiers, and logical key.
|
||||
- On match, Orca consumes the DOM event and calls Monaco's existing `actions.find` action.
|
||||
- Monaco owns the visible find widget and focus exactly as before.
|
||||
|
||||
## Edge cases
|
||||
|
||||
- Auto-repeat must be consumed without invoking find again; returning early before prevention would let Monaco handle a repeated QWERTY `KeyF` event.
|
||||
- Ordinary unmodified `f` typing and unrelated shortcuts must continue to Monaco unchanged.
|
||||
- A removed/disposed source editor, diff pane, or notebook cell must not retain the listener.
|
||||
- QWERTY `Cmd/Ctrl+F` must still open the same Monaco widget once, not twice.
|
||||
- User-configured bindings accepted by Orca's `editor.find` matcher should open find; Monaco's own default bindings remain outside the scope of this patch.
|
||||
- The behavior is renderer-local and does not read files or execute commands, so local, SSH, and Remote Orca files share the same path.
|
||||
|
||||
## Test plan
|
||||
|
||||
- Unit: `editor-shortcuts.test.ts` dispatches keyboard events through a real element and parameterizes the shared bridge across macOS (`metaKey`) and Linux/Windows (`ctrlKey`) using logical `f` with physical `KeyU`. It also asserts QWERTY/default handling, matched-repeat prevention without a second callback, unrelated typing, and disposal behavior used by every editable Monaco integration.
|
||||
- Electron: open a disposable `.ts` file and drive `Cmd+F`/`Ctrl+F` using the platform modifier; assert `.find-widget.visible`, focused find input, unchanged source text, and clean editor state.
|
||||
- Electron layout regression: on macOS, dispatch logical `f` with non-QWERTY physical/virtual key identity; assert the same find state and unchanged source text.
|
||||
- Adjacent smoke: dismiss find, type a normal character, and verify it edits the file rather than reopening find.
|
||||
- Static: run focused Vitest, `pnpm typecheck`, and `pnpm lint`.
|
||||
|
||||
## UI quality bar
|
||||
|
||||
No new UI. The existing Monaco find widget must appear in its current position and styling, focus its input, and leave the editor content unchanged. No overlap, clipping, duplicate widget, or focus flicker is acceptable.
|
||||
|
||||
## Review screenshots
|
||||
|
||||
1. QWERTY/default shortcut with the existing Monaco find widget visible in a `.ts` editor.
|
||||
2. Non-QWERTY logical-`f` regression path with the same find widget visible and source text unchanged.
|
||||
3. Adjacent ordinary typing state after find is dismissed, showing the source editor still accepts text normally.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add failing unit coverage for the layout-aware find installer contract.
|
||||
2. Implement the installer in `editor-shortcuts.ts`.
|
||||
3. Wire it to each editable Monaco surface's existing find action and lifecycle cleanup.
|
||||
4. Run focused tests, typecheck, lint, and the Electron QWERTY/layout/typing scenarios.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: Kept to one shared shortcut installer and the existing mount/teardown seams for source editors, editable diff panes, and notebook code cells; no new find implementation or global shortcut interception.
|
||||
- Architecture/data flow: The renderer-local Monaco container owns the keydown. Orca's canonical matcher resolves the logical key, while Monaco continues to own widget state and rendering. No main/preload/IPC, persistence, network, SSH, or provider boundary changes.
|
||||
- Failure modes covered:
|
||||
- Non-QWERTY logical key differs from physical/virtual keycode.
|
||||
- QWERTY double handling.
|
||||
- Auto-repeat escaping to Monaco's native QWERTY handler.
|
||||
- Listener surviving editor disposal.
|
||||
- Ordinary typing being consumed.
|
||||
- Custom `editor.find` chord accepted by Orca but not Monaco.
|
||||
- Test coverage required:
|
||||
- DOM-listener unit tests in `src/renderer/src/components/editor/editor-shortcuts.test.ts`, parameterized for Darwin/Meta, Linux/Ctrl, and Windows/Ctrl.
|
||||
- Electron-visible QWERTY and layout-aware `.ts` scenarios.
|
||||
- Adjacent ordinary typing smoke test.
|
||||
- Performance/blast radius: One capture listener per mounted editable Monaco editor, doing a constant-time keybinding comparison only for events within that editor. Multiple mounted diff sections do not fan out because each listener is scoped to its own container. Listeners are removed with Monaco disposal; no polling, scans, IPC, storage, or render-loop work.
|
||||
- UI quality bar: Existing Monaco find widget only; verify focus, unchanged source text, no duplicate opening, and unchanged styling against `docs/STYLEGUIDE.md`.
|
||||
- Required review screenshots:
|
||||
1. Default QWERTY find-open state.
|
||||
2. Non-QWERTY logical-key find-open state.
|
||||
3. Find-dismissed ordinary typing state.
|
||||
- Residual risks: Monaco's internal default bindings remain active when a user explicitly rebinds `editor.find`; fully suppressing/remapping Monaco's native keybinding table is a separate, larger change.
|
||||
@@ -1,50 +0,0 @@
|
||||
# Failed Automation Rerun Action
|
||||
|
||||
## Problem
|
||||
|
||||
- Failed Orca automation run details show only the disabled/open-target action when no workspace launched, so a user who sees a `dispatch_failed` error has no local recovery action in the failed-run view: `src/renderer/src/components/automations/AutomationsPage.tsx:1858`.
|
||||
- The reusable detail header already accepts actions, but the run detail action set is limited to `getAutomationRunViewState`/`openRunWorkspace`: `src/renderer/src/components/automations/AutomationRunPageFrame.tsx:9`, `src/renderer/src/components/automations/automation-run-view-state.ts:13`.
|
||||
- Manual rerun behavior already exists as `runNow`, which creates a fresh manual run for the automation; the renderer wrapper currently refreshes the page after calling it: `src/renderer/src/components/automations/AutomationsPage.tsx:1033`, `src/main/automations/service.ts:66`.
|
||||
|
||||
## Goal
|
||||
|
||||
Add an easy rerun button to Orca automation run detail pages for failed launch/recovery statuses. The button creates a fresh manual run for the same automation through the existing `runNow` path.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Do not mutate or replay the failed run record.
|
||||
- Do not add backend APIs or provider-specific rerun behavior.
|
||||
- Do not add rerun support for external Hermes/OpenClaw run details in this change.
|
||||
- Do not bypass existing SSH availability, worktree creation, or dispatch failure handling.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add a small pure predicate near the run view state code, for example `canRerunAutomationRun({ automation, run })`.
|
||||
- Return `true` only when an Orca automation still exists, `run.automationId === automation.id`, and the run status is one of `dispatch_failed`, `skipped_unavailable`, or `skipped_needs_interactive_auth`.
|
||||
- Do not show rerun for `pending`, `dispatching`, `dispatched`, `completed`, or `skipped_missed`. `skipped_missed` is scheduler catch-up history, not a launch failure the detail page should recover.
|
||||
2. In `AutomationsPage`, render a `Rerun` action in `AutomationRunPageFrame.actions` when that predicate is true for `selected` and `selectedAutomationRunPage`.
|
||||
3. The action calls `window.api.automations.runNow({ id: selected.id })` through a small handler, then `refresh()`, then shows the existing queued toast. Wrap the call in `try/catch/finally`: if the automation was deleted or the IPC rejects, toast the error and refresh so the stale run detail can disappear.
|
||||
4. Preserve dispatch behavior by reusing `runNow`; do not duplicate local/SSH dispatch logic in the renderer. `runNow` creates a new manual run and `AutomationService.requestDispatch` sends the existing `automations:dispatchRequested` payload to the renderer, where `useAutomationDispatchEvents` handles SSH reconnect, interactive-auth skips, worktree creation/reuse, and terminal launch.
|
||||
5. Add a local in-flight state keyed by the failed run id. Disable only that rerun button while pending so repeated clicks in one window cannot queue duplicates before the first request settles.
|
||||
6. Keep the existing `View run` / `Open workspace` action beside the new rerun action. Do not gate rerun on `selectedAutomationRunPageViewState.canOpen`; failed runs with no launch should still show the disabled view action plus enabled rerun.
|
||||
7. Use existing shadcn `Button`, lucide icon sizing, and styleguide tokens. The button should be compact (`size="sm"`), outline-level emphasis, and fit the existing header action row.
|
||||
8. Add focused tests for the pure predicate in `automation-run-view-state.test.ts`. Avoid component-level tests unless a harness already exists locally.
|
||||
|
||||
## Edge cases
|
||||
|
||||
- Failed run has no workspace because base ref refresh, SSH connection, missing project/workspace, or renderer availability failed: rerun remains available and lets the existing dispatch path try again.
|
||||
- Failed run has a workspace but terminal is closed: rerun stays available, and open workspace behavior remains unchanged.
|
||||
- Automation was deleted while the request is in flight or by another window: `runNow` can throw `Automation not found.`; catch it, clear pending state, and refresh.
|
||||
- Selection changed while the request is in flight: capture `automation.id` and `run.id` before awaiting, clear that run id in `finally`, and avoid reading mutable `selected` after the await.
|
||||
- SSH automation cannot reconnect or needs credentials: rerun still goes through `runNow`; existing dispatch code records `skipped_unavailable` or `skipped_needs_interactive_auth` as a new run.
|
||||
- The user clicks rerun repeatedly in the same window: disable the rerun button while the request is pending.
|
||||
- The user clicks rerun in two windows: the renderer guard will not prevent duplicate manual runs across windows. Do not claim backend idempotency unless a service-level dedupe key is added.
|
||||
- Refresh after rerun may leave the failed run detail selected because `selectedAutomationRunPageId` still points at the old run. That is acceptable for this change, but the run list count and rows must refresh so the new manual run is visible after navigating back.
|
||||
- `runNow` itself does not broadcast `orca:automations-changed`; the initiating page must call `refresh()` after the IPC resolves. Other windows update only when dispatch result handling fires the existing event or when focus/visibility refresh runs.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add a small predicate/helper for rerun action visibility and unit tests if it can live near automation run view state without mixing responsibilities.
|
||||
2. Add rerun pending state, error handling, and handler in `AutomationsPage`.
|
||||
3. Render the new action in the selected Orca run detail header.
|
||||
4. Run focused tests, then `pnpm typecheck` and `pnpm lint`.
|
||||
@@ -1,73 +0,0 @@
|
||||
# Floating Terminal Panel Position Persistence
|
||||
|
||||
## Problem
|
||||
|
||||
The floating workspace panel appears in a different default location after app restart instead of returning to the user's last dragged or resized placement.
|
||||
|
||||
- `src/renderer/src/components/floating-terminal/FloatingTerminalPanel.tsx:132` initializes panel `bounds` from `getDefaultFloatingTerminalBounds()` on every renderer mount.
|
||||
- `src/renderer/src/components/floating-terminal/FloatingTerminalPanel.tsx:349` only normalizes that in-memory initial state when the panel opens; it does not read or write durable position state.
|
||||
- `src/renderer/src/components/floating-terminal/FloatingTerminalPanel.tsx:1039` updates bounds while dragging, and `src/renderer/src/components/floating-terminal/FloatingTerminalResizeHandles.tsx:98` updates bounds while resizing, but both changes remain React state only.
|
||||
- The toggle button already persists its own location through localStorage in `src/renderer/src/components/floating-terminal/FloatingTerminalToggleButton.tsx:33`, so the inconsistency is isolated to the larger panel.
|
||||
|
||||
## Root Cause
|
||||
|
||||
Panel geometry is transient renderer state. Restarting Orca remounts `FloatingTerminalPanel`, so the panel recomputes from the current viewport instead of restoring the last user placement. The component also has no source tracking, so its legacy right-gap normalization cannot distinguish a default position from an intentional user drag.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Do not change terminal, browser, or markdown tab persistence.
|
||||
- Do not persist remote or SSH-specific state; panel geometry is local renderer chrome.
|
||||
- Do not persist maximized panel bounds as the normal restored size.
|
||||
- Do not add new settings UI or change design tokens.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add floating panel bounds persistence helpers beside the existing panel bounds math:
|
||||
- use a panel-specific versioned key, e.g. `orca-floating-terminal-panel-bounds-v1`;
|
||||
- parse only finite `left`, `top`, `width`, and `height` numbers;
|
||||
- distinguish `default` versus `user` bounds sources;
|
||||
- expose a panel viewport-usability guard so saved user bounds are not clamped against Electron's transient zero-sized startup viewport;
|
||||
- expand clamping to normalize both position and size. The current `clampFloatingTerminalBounds` only clamps `left` and `top`; persisted restores also need the resize-handle width/height caps.
|
||||
2. Read and write storage defensively:
|
||||
- `window` absence or `localStorage` get/set failures fall back to in-memory behavior for the session;
|
||||
- malformed, partial, non-finite, or non-object JSON falls back to default bounds.
|
||||
3. Initialize `FloatingTerminalPanel` once from persisted bounds when present, otherwise from the current default. Store the initial source in a ref, mirroring the toggle button pattern.
|
||||
4. Reconcile bounds in `useLayoutEffect` before first paint and on viewport resize:
|
||||
- default-sourced bounds re-anchor to the current bottom-right default;
|
||||
- user-sourced bounds clamp into the visible viewport and persist the clamped result only after the viewport is usable;
|
||||
- remove `normalizedInitialBoundsRef` and the `rightGap > 160` reset. That heuristic is superseded by source-aware reconciliation and would otherwise wipe valid saved left-side placements.
|
||||
5. Replace direct `setBounds` calls for user-driven placement changes with a panel-local geometry updater:
|
||||
- drag and resize pointer moves should clamp and update React state for smooth feedback, but stage the latest bounds in a ref;
|
||||
- pointer up and pointer cancel commit the staged bounds to storage only after movement produced staged geometry. `localStorage.setItem` is synchronous, so do not write on every pointer move or after a titlebar click with no movement;
|
||||
- the panel-level `onMouseUp` size capture must not convert a default-sourced panel into a user-sourced panel after an ordinary click. Commit measured dimensions only after a real geometry interaction, or when the panel was already user-sourced;
|
||||
- resize handles should receive explicit preview/commit callbacks instead of the raw React setter, so resize, drag, and restore use the same persistence rules.
|
||||
6. When entering maximized mode, store the pre-maximized bounds and source in memory only. Do not persist the maximized rectangle. While maximized, viewport resize should recompute maximized bounds without touching the stored normal bounds or source. On restore, return to the stored normal bounds, reconcile them through the same source-aware rules, and persist only if the restored source is `user`.
|
||||
|
||||
## Consistency Model
|
||||
|
||||
- Persistence is a restart seed, not live cross-window synchronization.
|
||||
- Multiple renderer windows share the same localStorage key and therefore use last-writer-wins across restarts/reloads. Do not subscribe to `storage` events for live updates; another window or DevTools edit should not move an open panel mid-drag.
|
||||
- External storage mutations are picked up on the next renderer mount or reload.
|
||||
- The state is local renderer chrome. It must not go through worktree settings, terminal state, or SSH-backed runtime APIs.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- Malformed or partial localStorage JSON falls back to default bounds.
|
||||
- Unavailable localStorage should not break the floating workspace; persistence simply becomes best-effort.
|
||||
- Startup can briefly report a zero-sized renderer; saved user bounds must not be clamped to that unusable viewport.
|
||||
- A saved position from a larger monitor should be clamped back on-screen on the current monitor.
|
||||
- A saved size larger than the current viewport should shrink to the largest size that still leaves a small visible margin while respecting minimum panel dimensions.
|
||||
- A viewport smaller than the minimum panel size should keep the panel at the minimum size and keep its top-left corner reachable.
|
||||
- Maximized mode should not overwrite the normal saved size and position.
|
||||
- Plain clicks inside a default-positioned panel should not make that default position sticky forever.
|
||||
- Pointer cancellation should commit the last valid drag or resize bounds, matching pointer-up behavior.
|
||||
- SSH-backed terminals keep using the same floating workspace UI; geometry persistence stays local and does not assume local command execution.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Extend `floating-terminal-panel-bounds.ts` with parse, source, viewport usability, resolve, and size-aware clamp helpers plus focused unit coverage.
|
||||
2. Wire `FloatingTerminalPanel` to read, reconcile, and persist panel bounds through those helpers; remove the legacy right-gap normalization.
|
||||
3. Update `FloatingTerminalResizeHandles` to use preview/commit callbacks so drag, resize, measured-size capture, and maximize restore share one persistence path.
|
||||
4. Add component coverage for persisted startup, bad storage, zero-sized startup deferral, default re-anchoring, user clamping, and the "plain click does not persist default" case.
|
||||
5. Run focused Vitest coverage, then `pnpm typecheck` and `pnpm lint`.
|
||||
6. Verify in Electron by moving/resizing the panel, reloading or restarting the dev app, checking maximized restore, and confirming evidence screenshots are not committed.
|
||||
@@ -1,137 +0,0 @@
|
||||
# GitHub Tasks Close Reason Parity
|
||||
|
||||
## Problem
|
||||
|
||||
- [TaskPage.tsx](/Users/jinwoohong/orca/workspaces/orca/tasks-page-parity/src/renderer/src/components/TaskPage.tsx:1025) renders `GHStatusCell` with only `Open` and `Closed`.
|
||||
- [TaskPage.tsx](/Users/jinwoohong/orca/workspaces/orca/tasks-page-parity/src/renderer/src/components/TaskPage.tsx:1064) sends `{ state: 'closed' }`, so the list path cannot choose GitHub close reasons.
|
||||
- [TaskPage.tsx](/Users/jinwoohong/orca/workspaces/orca/tasks-page-parity/src/renderer/src/components/TaskPage.tsx:1137) styles closed issues with rose/destructive color, while GitHub treats closing as a neutral/purple completion action rather than a delete/error action.
|
||||
- [GitHubItemDialog.tsx](/Users/jinwoohong/orca/workspaces/orca/tasks-page-parity/src/renderer/src/components/GitHubItemDialog.tsx:4960) has a separate issue-detail status popover; it must expose the same close reasons so opening an issue from Tasks does not fall back to the old Open/Closed-only UI.
|
||||
- [GitHubIssueCommentComposer.tsx](/Users/jinwoohong/orca/workspaces/orca/tasks-page-parity/src/renderer/src/components/github/GitHubIssueCommentComposer.tsx:188) already supports close reasons in the detail composer, but the Tasks list does not.
|
||||
|
||||
## Goal
|
||||
|
||||
Bring the GitHub Tasks list status menu closer to GitHub:
|
||||
|
||||
1. Closed issue UI must stop using destructive red styling.
|
||||
2. Open issues must expose close-as-completed, close-as-not-planned, and close-as-duplicate from the status menu.
|
||||
3. Duplicate closes must require a target issue number and pass it as `duplicateOf`.
|
||||
4. Reopening still works from the same status menu.
|
||||
5. GitHub issue detail metadata must use the same close-reason and duplicate-picker behavior as the Tasks row.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- No provider-generic changes for GitLab, Linear, or Jira.
|
||||
- No network-backed GitHub issue search picker in this pass; the duplicate picker uses the loaded Tasks cache plus an exact issue-number fallback.
|
||||
- No schema changes or cache migration.
|
||||
- No change to PR status behavior.
|
||||
- No automatic cross-window broadcast beyond the existing cache/list refresh mechanics; this pass updates the current renderer optimistically and relies on normal refetch in other windows.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add a small TaskPage GitHub status menu model in a named module, including option metadata, duplicate-target validation, and payload construction for close reasons.
|
||||
2. Update `GHStatusCell` so `handleStateChange` accepts close options, optimistically patches only the issue `state`, and sends `stateReason` plus optional `duplicateOf`.
|
||||
3. Route issue-state mutations by issue identity:
|
||||
- If the row URL parses to `owner/repo`, use `github.project.updateIssueBySlug` / runtime `github.project.updateIssueBySlug`. This avoids closing the wrong repository for GitHub project/custom-source rows whose issue repo can differ from the caller repo.
|
||||
- Otherwise keep the existing `github.updateIssue` path with `repoPath`/`repoId`/`sourceContext`.
|
||||
4. Render the status popover with `Open`, `Close as completed`, `Close as not planned`, and `Close as duplicate` in both the Tasks row and issue-detail metadata sidebar. The duplicate row advances to a second-step picker with a back button, search field, loaded issue candidates, and an exact-number fallback.
|
||||
5. Replace rose closed-state classes with token-based primary/ring color-mix classes so the closed pill is completion-like, not destructive. Keep the open-state green treatment for parity with the existing Tasks page unless a broader status-color pass changes it.
|
||||
6. Keep the payload serializable for IPC/runtime/SSH: `{ state, stateReason, duplicateOf }` only contains strings and numbers.
|
||||
|
||||
## API Notes
|
||||
|
||||
- The local path in [issues.ts](/Users/jinwoohong/orca/workspaces/orca/tasks-page-parity/src/main/github/issues.ts:231) already closes issues with `gh issue close`. Preserve that model and pass:
|
||||
- `--reason completed` for `stateReason: 'completed'`
|
||||
- `--reason "not planned"` for `stateReason: 'not_planned'`
|
||||
- `--duplicate-of <number>` for `stateReason: 'duplicate'` with `duplicateOf`
|
||||
- The slug path in [mutations.ts](/Users/jinwoohong/orca/workspaces/orca/tasks-page-parity/src/main/github/project-view/mutations.ts:160) must not implement duplicates by PATCHing `duplicate_of` on `repos/{owner}/{repo}/issues/{n}`. `gh issue close --duplicate-of` is the supported CLI surface already used by the path-based mutation, so slug-addressed state changes should use `gh issue close/reopen --repo owner/repo` for state and reserve REST PATCH for title/body.
|
||||
- When `stateReason: 'duplicate'` is sent without a valid `duplicateOf`, reject it before dispatch. Do not silently downgrade to plain closed or `--reason duplicate`, because GitHub's duplicate UX expects the target issue to be recorded.
|
||||
- Keep `state_reason` REST PATCH only for non-duplicate close reasons if the implementation deliberately stays on REST for completed/not-planned. The simpler consistency target is to route all slug-addressed state changes through `gh issue close/reopen`.
|
||||
|
||||
## Data Flow
|
||||
|
||||
- User opens a GitHub issue status pill.
|
||||
- Completed/not-planned click -> `handleStateChange('closed', { stateReason })`.
|
||||
- Duplicate click -> second-step picker -> select a loaded issue or exact target number -> `handleStateChange('closed', { stateReason: 'duplicate', duplicateOf })`.
|
||||
- Cell optimistically patches local state and store row state.
|
||||
- Mutation goes through local IPC or runtime RPC with the same repo/source context.
|
||||
- Failure reverts the local/store state and shows the existing error toast.
|
||||
- Success records the existing `github-tasks` feature interaction and should invalidate or refresh the relevant work-items cache entry if the current filter can hide the row after the state changes (for example, an `is:open` filter). Without that, a closed row can remain visible until a later refetch.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- Duplicate target is blank, zero, negative, decimal, or the same issue number: keep the picker open and show inline validation after Enter.
|
||||
- Duplicate target can be a different repository's issue only when the implementation accepts a URL; this pass takes a loaded same-repository issue or number, so validation and copy should describe it as an issue in the same repository.
|
||||
- The row refreshes while the menu is open: reconcile the optimistic draft before paint as the current status cell already does.
|
||||
- Rapid repeated choices: retain the existing request id guard so stale responses cannot revert a newer choice.
|
||||
- SSH/runtime target: payload must remain serializable and use the existing runtime method.
|
||||
- Multi-window consistency: do not assume another window's in-memory `workItemsCache` observes the optimistic patch. Ensure the mutation path updates GitHub authoritatively and that normal cache invalidation/refetch behavior eventually corrects other windows.
|
||||
- Project/custom-source rows: prefer the parsed issue URL slug over the selected local repo when available, because a GitHub Project can contain issues from repositories other than the current worktree.
|
||||
- PR rows and rows without a repo continue to render a non-editable status pill.
|
||||
- Rows without a parsed slug and without a local repo/source context should stay non-editable; do not attempt a mutation from only an issue number.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- Unit: menu model builds `{ state: 'closed', stateReason: 'completed' }`, `{ state: 'closed', stateReason: 'not_planned' }`, and duplicate payloads only for valid duplicate targets.
|
||||
- Unit: duplicate validation rejects missing/self/non-positive/non-integer targets.
|
||||
- Existing unit: optimistic status draft reconciliation remains unchanged.
|
||||
- Main unit: `updateIssue` emits `gh issue close --reason completed`, `gh issue close --reason "not planned"`, `gh issue close --duplicate-of <n>`, and `gh issue reopen`.
|
||||
- Main unit: `updateIssueBySlug` uses `gh issue close/reopen --repo owner/repo` for state changes, rejects duplicate without `duplicateOf`, and does not send unsupported `duplicate_of` REST fields.
|
||||
- Renderer unit: `GHStatusCell` uses slug-addressed mutation when `item.url` contains an owner/repo and falls back to `github.updateIssue` only when slug parsing is unavailable.
|
||||
- Store/cache unit: successful close from an open-filtered Tasks list invalidates or refreshes the affected work-items cache so hidden-by-filter rows do not linger indefinitely.
|
||||
- Electron validation: Tasks GitHub issue row status menu shows the new close options and closed issue pill is not red.
|
||||
- Electron validation: duplicate close picker appears after the duplicate action and supports issue search/exact-number fallback. Do not submit a real close mutation against user data.
|
||||
- Electron validation: GitHub issue detail status sidebar shows the same close options and duplicate picker as the list row.
|
||||
- Electron/runtime smoke: same menu opens and validation works when the active runtime target is an SSH/environment source; avoid a real close mutation unless using disposable test data.
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
- Popover should feel like an action menu, not an error/destructive confirmation.
|
||||
- Closed issue pill must be visually distinct from open but not red/destructive.
|
||||
- Duplicate picker must fit in the popover at desktop and narrow widths without clipping.
|
||||
- Hover, focus, disabled, and inline validation states use existing shadcn primitives/tokens.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
1. GitHub Tasks issue row with status popover open showing all close reasons.
|
||||
2. Duplicate close second-step picker with search and issue candidates.
|
||||
3. Closed issue row/pill showing non-red completion styling.
|
||||
4. GitHub issue detail sidebar status popover showing all close reasons.
|
||||
5. GitHub issue detail duplicate close second-step picker.
|
||||
6. Adjacent smoke: GitHub Tasks header/search area still renders normally.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add status menu model and tests.
|
||||
2. Update `GHStatusCell` UI and mutation payload.
|
||||
3. Run focused tests, typecheck, and lint.
|
||||
4. Run UI quality review.
|
||||
5. Validate in Electron and capture screenshots.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: kept to the GitHub Tasks status cell plus a small model module; no provider-wide or network-backed search-picker work.
|
||||
- Architecture/data flow: preserves current renderer -> IPC/runtime mutation boundaries, but must route rows with parseable GitHub slugs through `updateIssueBySlug` so project/custom-source issues mutate the issue's own repository rather than the selected worktree repo.
|
||||
- API feasibility: path-based mutations already use the supported `gh issue close --duplicate-of` CLI path; slug-addressed mutations need the same CLI close/reopen treatment instead of REST `duplicate_of`.
|
||||
- Failure modes covered:
|
||||
- Invalid duplicate targets stay local and do not mutate.
|
||||
- Failed mutations revert optimistic state using the existing request id guard.
|
||||
- Runtime/SSH remains on the existing serializable RPC method.
|
||||
- Unsupported duplicate API shape is avoided by keeping duplicate close on `gh issue close --duplicate-of`.
|
||||
- Rows filtered by open/closed status do not rely solely on optimistic patching; the relevant work-items cache must be invalidated/refetched after success.
|
||||
- Test coverage required:
|
||||
- Unit tests for close update payloads and duplicate validation.
|
||||
- Main-process tests for both `updateIssue` and `updateIssueBySlug` close/reopen command generation.
|
||||
- Renderer routing tests for slug-addressed versus repo-path-addressed issue rows.
|
||||
- Cache invalidation/refetch coverage for status-filtered Tasks lists.
|
||||
- Existing status draft tests for optimistic reconciliation.
|
||||
- Electron screenshots for menu, duplicate validation, closed styling, and adjacent header smoke.
|
||||
- Performance/blast radius: no material concern; one extra tiny model import and no new polling/IPC.
|
||||
- UI quality bar: compact GitHub-like action menu, token-based non-destructive closed styling, no clipping or overlap.
|
||||
- Required review screenshots:
|
||||
1. Status popover with close reasons.
|
||||
2. Duplicate second-step picker with search and issue candidates.
|
||||
3. Non-red closed status pill.
|
||||
4. Tasks header/search smoke.
|
||||
- Residual risks:
|
||||
- Duplicate target search is limited to loaded Tasks cache candidates, with exact-number fallback for unloaded same-repository issues.
|
||||
- Other open Orca windows may show stale status until their normal GitHub Tasks data refresh runs.
|
||||
@@ -1,119 +0,0 @@
|
||||
# Image Viewer Pinch Zoom
|
||||
|
||||
## Problem
|
||||
|
||||
- `src/renderer/src/components/editor/ImageViewer.tsx:27` stores viewer zoom and exposes toolbar zoom controls.
|
||||
- `src/renderer/src/components/editor/ImageViewer.tsx:106` renders the inline image surface without a wheel handler.
|
||||
- `src/renderer/src/components/editor/ImageViewer.tsx:198` renders the popup image surface without a wheel handler.
|
||||
- On Chromium/Electron, trackpad pinch gestures arrive as `wheel` events with `ctrlKey: true`; the viewer does not intercept them, so users cannot pinch to zoom the image in or out.
|
||||
|
||||
## Root Cause
|
||||
|
||||
`ImageViewer` only changes zoom through button clicks. The image surfaces let ctrl-wheel events bubble/default, so pinch gestures never update `zoom` and may be consumed by Chromium-level page zoom instead. The inline surface is scrollable only in `fill` layout; in `intrinsic` layout it is `overflow-visible`, so the fix must not depend on scrollability.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Do not redesign the image viewer chrome or add new controls.
|
||||
- Do not change PDF handling; `application/pdf` still delegates to `PdfViewer`.
|
||||
- Do not implement pan/drag or persistent per-file zoom.
|
||||
- Do not change image loading, file IPC, or SSH/runtime preview fetching.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add pure zoom helpers in a concrete renderer module such as `image-viewer-zoom.ts` so the math can be tested under the repo's node-based Vitest setup:
|
||||
- `clampZoom(next)` clamps to the existing `MIN_ZOOM` and `MAX_ZOOM`.
|
||||
- `shouldHandleImageZoomWheel(eventLike)` returns true only for ctrl-wheel input.
|
||||
- `getPinchZoomFactor(deltaY, deltaMode)` normalizes pixel/line/page wheel deltas and returns a bounded multiplier; `deltaY === 0` should not change zoom.
|
||||
- `getNextWheelZoom(currentZoom, deltaY, deltaMode)` applies the factor and clamp without touching React state.
|
||||
2. Add an `applyZoomChange(fn)` wrapper inside `ImageViewer` that uses functional `setZoom`, and reset `zoom` to `1` when `filePath`, `mimeType`, or `cleanedContent` changes. `EditorContent` can reuse the same `ImageViewer` component position across image files, so local zoom must not accidentally carry across file switches or external reloads.
|
||||
3. Add refs for the inline image surface and popup image surface. Bind native `wheel` listeners with `{ passive: false }`, not React `onWheel`; this repo already uses native non-passive wheel listeners where Chromium default prevention must be reliable. Keep the listener callback stable enough that it is not rebound on every zoom tick.
|
||||
4. The wheel handler must:
|
||||
- ignore ordinary wheel/trackpad scroll;
|
||||
- handle only `event.ctrlKey` wheel events, which Chromium/Electron uses for trackpad pinch and Ctrl+wheel zoom;
|
||||
- call `preventDefault()` and `stopPropagation()` for every handled ctrl-wheel event, including when already clamped, so browser/app zoom does not also change;
|
||||
- map negative `deltaY` to zoom in and positive `deltaY` to zoom out;
|
||||
- use the bounded delta-scaled multiplier instead of applying the full toolbar `ZOOM_STEP` once per wheel event.
|
||||
5. Attach the listener to both image surfaces, not to `document` or `window`, so editor/terminal/browser panes outside the image viewer keep their existing wheel behavior. The popup listener must attach after the Radix dialog content mounts and clean up when it unmounts; a callback ref or an effect keyed by `isPopupOpen` is acceptable.
|
||||
6. Keep existing toolbar buttons wired through the same clamp helper.
|
||||
|
||||
## Data Flow
|
||||
|
||||
- Trackpad pinch over image surface
|
||||
- Chromium emits `WheelEvent` with `ctrlKey`
|
||||
- Native non-passive `wheel` listener intercepts it
|
||||
- `zoom` state updates
|
||||
- Existing inline and popup image transforms render at the new scale
|
||||
- Footer percent updates from `zoomPercent`
|
||||
- When the rendered file changes, `zoom` resets to `1` while object URL creation/revocation stays on the existing path
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- Ordinary scrolling without `ctrlKey` must still scroll the image surface.
|
||||
- Pinch gestures at `MIN_ZOOM` or `MAX_ZOOM` must stay clamped.
|
||||
- Ctrl-wheel at `MIN_ZOOM` or `MAX_ZOOM` must still prevent default browser zoom.
|
||||
- Popup and inline surfaces within one `ImageViewer` must stay in sync because they share one `zoom` state.
|
||||
- Image diff panes each mount their own `ImageViewer`; pinch over one side should only zoom that side. Do not introduce cross-pane sync in this fix.
|
||||
- `layout="intrinsic"` must receive pinch events even though the inline surface is not an overflow scroller.
|
||||
- Ctrl-wheel over the footer toolbar should keep existing button behavior and not become a hidden zoom target; the listener belongs on the image surface only.
|
||||
- PDF previews must remain unaffected.
|
||||
- The behavior must work for local and SSH-backed images because it is renderer-only after bytes are loaded.
|
||||
- Windows/Linux touchpads that also surface pinch as `ctrlKey` wheel events should work without platform-specific branches.
|
||||
- File switches, file reloads, external file mutations, and multi-window sessions should not add shared state: zoom remains local to the mounted viewer, resets for new loaded image content, object URL cleanup remains unchanged, and native wheel listeners must be removed on unmount/remount.
|
||||
- Existing CSS transform zoom does not resize the scrollable layout box. Do not try to solve transform-origin panning or full-image scroll extents in this change; keep pinch behavior consistent with the existing toolbar zoom.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- Unit tests: cover the extracted zoom helpers under the existing node Vitest config; this repo does not currently include jsdom, happy-dom, or Testing Library, so do not promise DOM component tests unless that tooling is deliberately added.
|
||||
- Unit tests: assert negative/positive/zero `deltaY`, pixel/line/page `deltaMode` normalization, min/max clamping, and bounded per-event zoom factors.
|
||||
- Unit tests: assert the wheel decision helper ignores non-ctrl wheel events and treats ctrl-wheel as handled even when the resulting zoom is already clamped or `deltaY` is `0`.
|
||||
- Electron validation: open a PNG in Orca, dispatch a cancelable `WheelEvent` with `ctrlKey` on the inline image surface, verify the displayed percent and visual scale change, and verify an ordinary wheel still scrolls where applicable.
|
||||
- Electron validation: open popup and repeat after the dialog mounts; close/reopen the popup and repeat once to catch duplicate or stale native listeners.
|
||||
- Electron validation: open an image diff and verify ctrl-wheel on one pane changes only that pane's percent.
|
||||
- Electron validation: switch from one image file to another or reload changed image content and verify zoom returns to `100%`.
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
Pinch zoom should feel like an existing viewer capability rather than a new UI surface: no layout shift, no new visible controls, footer percent remains stable, ordinary scrolling remains available, zoom changes are not jumpy under high-frequency trackpad events, and the popup chrome matches the current image viewer styling.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
1. Inline image viewer at default `100%`.
|
||||
2. Inline image viewer after pinch zoom in, showing a higher footer percent.
|
||||
3. Popup image viewer after pinch zoom out/in, showing the same percent as the inline viewer for that `ImageViewer`.
|
||||
4. Image diff viewer after pinch zooming only one pane, showing the other pane unchanged.
|
||||
5. Adjacent smoke state: normal editor/file surface still renders after closing the popup.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add wheel/pinch zoom handling to `ImageViewer`.
|
||||
2. Add focused tests for the pinch handler behavior.
|
||||
3. Run typecheck, lint, and relevant renderer tests.
|
||||
4. Validate in Electron and capture screenshots.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: kept to `ImageViewer` gesture handling and focused tests; no new viewer state model, persistence, or chrome changes.
|
||||
- Architecture/data flow: renderer-only DOM wheel handling updates existing `zoom` state; no main-process, IPC, SSH, runtime, or persistence boundary changes.
|
||||
- Failure modes covered:
|
||||
- ordinary wheel scroll accidentally blocked;
|
||||
- browser/app zoom also responding to pinch;
|
||||
- zoom exceeding existing min/max;
|
||||
- popup and inline surfaces diverging;
|
||||
- diff panes being accidentally synchronized;
|
||||
- native listener leaks or duplicate listeners after popup open/close;
|
||||
- stale zoom state under rapid wheel event bursts;
|
||||
- accidental zoom carryover across image file switches or external reloads;
|
||||
- PDF previews accidentally receiving image gesture behavior.
|
||||
- Test coverage required:
|
||||
- node unit tests for extracted zoom math and wheel-decision helpers;
|
||||
- Electron validation for native listener default-prevention behavior, popup wheel handling, diff-pane isolation, and zoom reset on image content changes;
|
||||
- screenshot validation for inline default, inline zoomed, popup zoomed, image-diff isolation, and adjacent editor state.
|
||||
- Performance/blast radius: low but not free; trackpads emit many wheel events, so the handler must do O(1) work, use functional state updates, avoid layout reads, and avoid document/window listeners. Blast radius stays inside mounted `ImageViewer` instances.
|
||||
- UI quality bar: no new visible UI; existing footer percent and scrollable image surface should remain visually stable.
|
||||
- Required review screenshots:
|
||||
1. Inline image viewer at `100%`.
|
||||
2. Inline image viewer after pinch-equivalent zoom in.
|
||||
3. Popup image viewer after pinch-equivalent zoom.
|
||||
4. Image diff viewer after pinch-equivalent zoom on one pane only.
|
||||
5. Editor/file surface after closing popup.
|
||||
- Residual risks: automated Electron validation can dispatch cancelable ctrl-wheel DOM events against the listener, but it does not fully prove OS-level physical trackpad pinch behavior or Chromium's browser-zoom default path. A manual trackpad smoke test is still the final confidence check when hardware is available.
|
||||
@@ -1,95 +0,0 @@
|
||||
# VS Code WSL Workspace Launch
|
||||
|
||||
## Problem
|
||||
|
||||
On Windows, choosing **Open in VS Code** for a workspace stored under a WSL UNC path opens the folder in a Windows VS Code environment instead of a Remote - WSL window ([issue #7649](https://github.com/stablyai/orca/issues/7649)). The renderer passes the workspace path and configured editor command unchanged (`src/renderer/src/components/sidebar/WorktreeOpenInMenu.tsx:103-121`), and the main process delegates launch argument construction to `resolveExternalEditorLaunchSpec` (`src/main/ipc/shell.ts:101-110`). The builder currently gives every non-Cursor executable only the original path (`src/main/external-editor-launch.ts:109-116`).
|
||||
|
||||
The deterministic reproduction for `\\wsl.localhost\Ubuntu\home\aliuq\project` produces `code <UNC path>` with no remote authority. VS Code's supported Windows CLI form is `code --remote wsl+<distro> <Linux path>`.
|
||||
|
||||
## Root cause
|
||||
|
||||
`resolveExternalEditorLaunchSpec` does not distinguish a VS Code launch targeting a WSL UNC workspace. Orca already has a shared parser for both modern `\\wsl.localhost\...` and legacy `\\wsl$\...` paths (`src/shared/wsl-paths.ts:1-20`), but the editor launcher never uses it. VS Code therefore receives the Windows-visible UNC folder and correctly opens it as a local Windows workspace.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Change the Open in menu, settings UI, IPC payload, file-manager behavior, or SSH/remote-runtime behavior.
|
||||
- Infer WSL identity for ordinary drive-letter paths from project runtime settings.
|
||||
- Rewrite user-defined compound shell commands or add remote flags to Cursor, VSCodium, or arbitrary editors.
|
||||
- Install or configure the VS Code WSL extension.
|
||||
|
||||
## Design
|
||||
|
||||
1. In the external-editor launch-spec builder, parse the target path with the shared WSL UNC parser when the host platform is Windows.
|
||||
2. For direct/executable VS Code Stable or Insiders launchers only, reuse the existing normalized launcher-basename check and translate a recognized WSL target into `['--remote', 'wsl+<distro>', '<linuxPath>']`. The exact allowlist recognizes Stable's `code`, Insiders' `code-insiders`, and the direct `Code - Insiders.exe` basename without matching unrelated `code-*` editors. Matching is case-insensitive and strips every Windows launcher suffix already supported by Orca (`.cmd`, `.exe`, and `.bat`).
|
||||
3. Keep local paths, non-Windows hosts, non-VS-Code applications, and compound commands on their existing argument paths. The existing main-process spawn and Windows shim handling remain unchanged.
|
||||
4. Replace the temporary reproduction harness with focused regression cases in `src/main/external-editor-launch.test.ts` covering modern and legacy WSL UNC forms plus unaffected local/custom-editor behavior.
|
||||
|
||||
## Data flow
|
||||
|
||||
- Worktree menu selects VS Code and sends `(workspacePath, 'code')` over existing IPC.
|
||||
- Main process validates the absolute existing host path.
|
||||
- Launch-spec builder resolves the VS Code executable.
|
||||
- On Windows + WSL UNC + VS Code, the builder emits the Remote - WSL authority and Linux-native folder path.
|
||||
- Existing Windows spawn wrapping launches VS Code with those arguments.
|
||||
|
||||
## Edge cases
|
||||
|
||||
- Modern `\\wsl.localhost\<distro>\...` and legacy `\\wsl$\<distro>\...` paths both preserve the distro spelling and convert separators to a POSIX path.
|
||||
- Distro names and Linux folder paths containing spaces remain single arguments because launch-spec construction and Windows shim wrapping preserve argument-array boundaries.
|
||||
- A WSL distro root maps to `/`.
|
||||
- Windows drive-letter and ordinary UNC paths stay local.
|
||||
- macOS/Linux behavior stays unchanged even for strings that resemble WSL UNC paths.
|
||||
- Cursor retains `--new-window`; other custom editors retain their existing single path argument.
|
||||
- Compound commands remain user-owned and are not rewritten because inserting flags safely would require parsing arbitrary shell syntax.
|
||||
- SSH and remote-runtime workspaces remain blocked from local path opening by the existing renderer guard; this change does not alter that boundary.
|
||||
- If the VS Code WSL extension is unavailable, launch behavior is left to VS Code and Orca retains its existing spawn-success contract.
|
||||
|
||||
## Test plan
|
||||
|
||||
- Unit: demonstrate the pre-fix launch spec lacks `--remote` for a modern WSL UNC path.
|
||||
- Unit: assert the fixed modern UNC launch is `--remote`, `wsl+Ubuntu`, `/home/...`.
|
||||
- Unit: assert legacy `\\wsl$` and distro-root paths produce the same Remote - WSL form.
|
||||
- Unit: assert direct and resolved Windows VS Code Stable and Insiders launchers are matched case-insensitively across `.exe`, `.cmd`, and `.bat` suffixes.
|
||||
- Unit: assert distro names and Linux folder paths containing spaces remain intact arguments through launch-spec construction and Windows shim forwarding.
|
||||
- Unit: assert a Windows local path remains unchanged and explicit `darwin` and `linux` hosts do not acquire WSL remote arguments.
|
||||
- Unit: assert Cursor and another custom editor are not given VS Code remote arguments.
|
||||
- Integration/Electron: create a throwaway repo in the installed Ubuntu WSL distro, add/open it in Orca, choose Open in VS Code, and verify the VS Code remote indicator and an integrated-terminal Linux probe.
|
||||
- Adjacent smoke: open a local Windows workspace in VS Code and verify it remains a local Windows window.
|
||||
- Repository gates: focused Vitest files, `pnpm typecheck`, `pnpm lint`, and `pnpm check:max-lines-ratchet`.
|
||||
|
||||
## UI quality bar
|
||||
|
||||
Not UI-visible in Orca. The existing menu, labels, loading behavior, and errors do not change. The user-visible acceptance criterion is external: the launched VS Code window must identify the selected WSL distro and its terminal must run Linux.
|
||||
|
||||
## Review screenshots
|
||||
|
||||
1. Golden path: VS Code opened from a throwaway WSL workspace, showing the Remote - WSL indicator and a terminal Linux probe.
|
||||
2. Adjacent local path: VS Code opened from a local Windows workspace, showing a local Windows terminal/environment.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add launch-spec regression tests and observe the WSL case fail against the desired arguments.
|
||||
2. Add the scoped VS Code + Windows + WSL argument translation.
|
||||
3. Run focused and repository-wide static/test gates.
|
||||
4. Validate WSL and local launches end to end, retaining local screenshots outside the PR.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: Kept to the launch-spec seam; no renderer, IPC, persistence, runtime-routing, or settings changes are needed because WSL filesystem identity is encoded in the UNC path.
|
||||
- Architecture/data flow: Reuse `parseWslUncPath` in the main-process pure argument builder, then leave executable resolution, Windows shim wrapping, spawn lifecycle, and renderer guards unchanged.
|
||||
- Failure modes covered:
|
||||
- Modern and legacy WSL UNC aliases route to the correct distro and Linux path.
|
||||
- Local/ordinary UNC paths and non-Windows platforms do not acquire remote flags.
|
||||
- Case variants and supported Windows VS Code shim suffixes are recognized without classifying custom editors or compound shell commands as VS Code.
|
||||
- Distro and folder names containing spaces survive the Windows shim as distinct arguments.
|
||||
- Missing VS Code WSL support still follows the existing launch contract rather than adding a new partial-failure protocol.
|
||||
- Test coverage required:
|
||||
- Pure launch-spec regression cases in `src/main/external-editor-launch.test.ts` for WSL aliases/root, launcher case/suffix variants, and unaffected branches.
|
||||
- `src/main/ipc/shell.test.ts` plus the existing Windows shim contract to prove remote arguments, including spaces, are forwarded as distinct values.
|
||||
- Live Windows + Ubuntu WSL + VS Code smoke for the actual environment boundary.
|
||||
- Performance/blast radius: One regex parse per external-editor click only; no startup, polling, watcher, terminal, or renderer cost. Blast radius is limited to direct VS Code launches of WSL UNC paths on Windows.
|
||||
- UI quality bar: Not UI-visible in Orca; VS Code must visibly attach to the requested WSL distro and run a Linux terminal.
|
||||
- Required review screenshots:
|
||||
1. WSL VS Code window with distro indicator and Linux terminal probe.
|
||||
2. Local Windows VS Code window demonstrating unchanged local launch behavior.
|
||||
- Residual risks: VS Code without the WSL extension may reject or prompt on the valid remote launch; this is external dependency behavior and should not cause Orca to fall back silently to the wrong Windows environment.
|
||||
@@ -1,203 +0,0 @@
|
||||
# Kill all sessions also closes terminal tabs
|
||||
|
||||
GitHub: https://github.com/stablyai/orca/issues/8001
|
||||
Branch: `bug-kill-all-sessions-doesnt-kill-terminals`
|
||||
|
||||
## Problem
|
||||
|
||||
Settings → Manage Sessions and Resource Manager expose **Kill all sessions**. The action currently calls only `window.api.pty.management.killAll()`; it does not remove renderer terminal tabs or dispose xterm instances.
|
||||
|
||||
The main handler is narrower than the UI wording:
|
||||
|
||||
- `pty:management:killAll` snapshots sessions from the current and legacy **daemon** adapters, shuts them down in parallel, then polls only those initial IDs.
|
||||
- It does not inventory SSH or runtime-hosted terminals. A degraded local provider is also outside the management adapter set.
|
||||
- The nominal poll sleep budget is 6.5 seconds (65 × 100 ms), but adapter round-trip time is additional. Daemon requests time out after 30 seconds and connection setup has separate 5-second steps, so total latency can be much longer.
|
||||
- Failed adapter listings are dropped by `collectSessions`, so counts are not authoritative when an adapter is unreachable. This applies during polling too: an adapter that listed an initial session and then becomes unreachable can make that session disappear from `remainingCount` and be counted as killed without a confirming listing.
|
||||
|
||||
Renderer exit handling then preserves two important startup-failure states:
|
||||
|
||||
- a sole, freshly spawned pane that exits before any user input; and
|
||||
- a freshly split pane that exits before input or output.
|
||||
|
||||
Those guards are correct for direnv/shell setup failures, but they cannot distinguish an explicit bulk kill. A sole fresh-spawned pane remains if the user never typed, even if it produced output or lived for a while; typed/reattached panes normally close through the existing exit path.
|
||||
|
||||
## Goal and invariant
|
||||
|
||||
After confirmation, every terminal tab that existed in the invoking desktop renderer at that moment is removed, including dead/no-PTY tabs, and its renderer resources are disposed. Terminal tabs created later are not targeted. Initial daemon sessions still receive the existing management shutdown request, while current non-runtime PTY bindings owned by the targeted tabs receive exact per-ID shutdown requests.
|
||||
|
||||
The target is the confirmed terminal **surface ID**, not a liveness inference. If the same targeted tab rebinds before cleanup completes, it is still closed; a newly created tab ID survives.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Changing **Restart daemon**, which intentionally leaves panes available to reopen.
|
||||
- Deleting or sleeping worktrees, closing browser/editor tabs, or killing the daemon process.
|
||||
- Changing the sole-pane/fresh-split startup-failure guards.
|
||||
- Promising an immediate OS working-set drop; GC and allocator behavior are nondeterministic. The deterministic contract is that tabs/xterms are released and observable daemon/exact-binding shutdown-request failures are surfaced. Runtime-host result propagation remains an accepted gap below.
|
||||
- Turning this issue into a new cross-provider global kill API. Exact `pty.kill(id)` calls for current bindings of the confirmed tabs are in scope; inventorying and killing unrelated provider sessions is not.
|
||||
|
||||
## Design
|
||||
|
||||
### 1. Snapshot terminal surfaces once
|
||||
|
||||
At confirmation, before `onKillAllStart` and before the first `await`, collect and deduplicate terminal entity IDs from both `tabsByWorktree` and terminal entries in `unifiedTabsByWorktree`. Include the floating-terminal workspace.
|
||||
|
||||
Keep this immutable target set through the async daemon call:
|
||||
|
||||
- a target already closed elsewhere becomes a no-op;
|
||||
- a target moved between groups/worktrees is resolved from current state and still closes;
|
||||
- a terminal created after the snapshot is never closed.
|
||||
|
||||
Do not snapshot all terminal IDs again after the daemon call, and do not retain the confirmation-time worktree as cleanup authority. The target ID is immutable; ownership and active-last ordering are resolved again from current state immediately before cleanup.
|
||||
|
||||
### 2. Keep daemon shutdown semantics, then close the snapshot
|
||||
|
||||
Call the existing `window.api.pty.management.killAll()` once. After it settles, resolve the still-present targets and deduplicate their current `ptyIdsByTabId` entries. These are the renderer's current binding ownership records, not independent liveness proof; do not pull IDs from `tab.ptyId`, deferred SSH restore state, or `terminalLayoutsByTabId.ptyIdsByLeafId`, which can be restore hints rather than current ownership.
|
||||
|
||||
Force-close every snapshotted surface through `closeTerminalTab(id, { force: true })`, then await one existing `window.api.pty.kill(id)` call for each captured non-`remote:` PTY ID. Run both phases for management success, partial success, and IPC rejection because the confirmation explicitly covers closing the terminal surfaces. Use per-target/per-PTY settlement so one unexpected store or provider failure does not stop the remaining cleanup. Already-gone PTYs are successful no-ops in the main handler; other exact-kill rejections are reported separately.
|
||||
|
||||
Close targets outside the cleanup-time `activeWorktreeId` first and targets currently owned by it last. A tab moved into the active worktree or a workspace selected while the daemon call was pending must therefore move to the last partition. Let `closeTerminalTab` choose the existing post-state for the last local terminal: editor, then browser, then `setActiveWorktree(null)`. Do not pre-clear `activeWorktreeId`; the sleep flow needs that ordering because it leaves tab records mounted while clearing PTYs, whereas this flow removes the tabs. Add active-switch and active-last regression tests and only adopt sleep-intent/deactivate-first if those tests prove a respawn.
|
||||
|
||||
This is not one backend call end-to-end. The coordinator issues one daemon-management IPC, one renderer close per unique target, and at most one exact kill IPC per unique current non-runtime PTY binding. The explicit exact kills make local/SSH shutdown requests settle before caller refresh instead of relying on React unmount timing. A mounted transport may race that request and issue an idempotent duplicate during unmount; count that separately in live performance evidence. A still-bound daemon session can receive the exact retry after the management poll, so daemon toast counts remain the management handler's earlier reported snapshot, not final process truth. Runtime-hosted tabs additionally issue one `session.tabs.close` flow per tab.
|
||||
|
||||
The coordinator must live outside the hook (for example, `kill-all-terminal-surfaces.ts`) and must not gate cleanup on `mountedRef`. Navigating away or unmounting the invoking popover/settings component while IPC is pending does not revoke an already confirmed destructive action; only React callbacks and hook state updates remain mount-gated.
|
||||
|
||||
### 3. Do not add a post-kill orphan sweep
|
||||
|
||||
Do not call `pty.listSessions()` and kill everything returned after the management call. Exact kills captured from `ptyIdsByTabId` for the immutable target surfaces are allowed and required; they do not discover or cross into unrelated sessions.
|
||||
|
||||
The management handler already targets daemon orphans in its initial snapshot. A later broad sweep would cross the confirmation boundary by killing local/SSH sessions or fresh sessions created while the existing poll was running. It would also add provider inventory fan-out to a recovery action and conflict with the main handler's initial-ID accounting.
|
||||
|
||||
The existing explicit **Kill orphan terminals** action remains separate.
|
||||
|
||||
### 4. Make completion and failure copy honest
|
||||
|
||||
Have the renderer cleanup return a bounded summary: target count, targets absent at completion, failed close attempts, exact PTY kill requests accepted/rejected, and daemon result/error. Verify absence in both terminal and unified state after each close attempt. Toasts must report renderer cleanup separately from daemon counts; do not show **No sessions running** when terminal tabs were closed.
|
||||
|
||||
Because the management API suppresses adapter-list failures, copy must describe daemon counts as reported, not claim that every daemon process was verified dead. Returning adapter errors is a follow-up unless this PR chooses to widen the API. Exact `pty.kill` rejection counts may be stated as failed shutdown requests, not as proof that the processes remain alive.
|
||||
|
||||
Examples of states, not required wording:
|
||||
|
||||
- all daemon targets were reported exited, exact shutdown requests were accepted, and tabs closed: success;
|
||||
- `remainingCount > 0`: warning that management reported daemon processes not exited before exact binding cleanup;
|
||||
- management IPC rejected: error that tabs closed, with daemon shutdown unverified and any exact PTY kill failures called out;
|
||||
- no daemon sessions and no terminal tabs: existing informational state.
|
||||
|
||||
Run `onKillAllSettled` only after surface removal and exact PTY kill settlement. `closeTerminalTab` returns before React unmount effects run, so surface removal alone is not a sufficient boundary for Resource Manager's `pty.listSessions()` refresh. Keep one confirmation dialog and update its description to say that terminal tabs across workspaces close and unsaved terminal work is lost.
|
||||
|
||||
### 5. Provider limits
|
||||
|
||||
`closeTerminalTab` synchronously prunes host-backed local mirrors but currently returns `void` and discards the promise from `closeWebRuntimeSessionTab`. The underlying helper is already awaitable: its close request has a 15-second timeout and, after success, it awaits an eager list refresh with another 15-second timeout. Its boolean can therefore settle after roughly 30 seconds, while close-intent suppression expires after 10 seconds. This change must not claim verified runtime-host completion unless the bulk helper propagates that existing result and aligns the intent lifetime.
|
||||
|
||||
For this Windows/local bug, runtime-host cleanup is best-effort and an explicit accepted gap. A follow-up may propagate the existing async close result through terminal-tab actions and align the RPC timeout/intent lifetime. SSH must be exercised if the fixture is available; otherwise record live SSH process absence as an accepted gap. No provider-specific local filesystem or process assumptions are added.
|
||||
|
||||
## Data flow
|
||||
|
||||
```text
|
||||
confirm
|
||||
→ snapshot unique terminal surface IDs
|
||||
→ pty.management.killAll() daemon current + legacy; existing polling
|
||||
→ resolve current target ownership + bound PTY IDs
|
||||
→ close snapshotted tabs, active last renderer/xterm cleanup; runtime-host close starts
|
||||
→ await exact non-runtime pty.kill IDs local/SSH acknowledgement; no provider sweep
|
||||
→ toast daemon result + surface/exact-kill summary
|
||||
→ caller refresh
|
||||
```
|
||||
|
||||
## Concurrency and consistency
|
||||
|
||||
| Case | Required behavior |
|
||||
| ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||
| No daemon sessions; dead/empty tabs exist | Close target tabs and report tab cleanup, not “No sessions.” |
|
||||
| Daemon session refuses to exit | Close the confirmed tab; report that management saw it remaining before the exact retry. Refresh may expose it as an orphan. |
|
||||
| Adapter listing fails | Close target tabs; do not claim all processes were verified dead. Existing management counts may read as zero. |
|
||||
| Management IPC rejects | Still close confirmed tabs and issue exact current-binding kills; report daemon uncertainty and exact-kill errors. |
|
||||
| New tab/session during the wait | New tab ID survives. No post-snapshot provider sweep. |
|
||||
| Target closes or moves during the wait | Missing target no-ops; moved target closes by current ownership. |
|
||||
| Target tab rebinds to a new PTY | Close it because the confirmed surface, not the old PTY snapshot, is the authority. |
|
||||
| Pinned or split terminal | `force: true` bypasses a second prompt; closing the tab closes all of its panes. |
|
||||
| Active last terminal | Existing close routing selects editor/browser or deactivates; no replacement terminal spawns. |
|
||||
| Two overlapping invocations | Cleanup is idempotent by tab ID. Each main call retains its own initial daemon snapshot/counts. |
|
||||
| Binding changes after exact-ID capture | Surface close still wins; transport unmount kills the replacement, but that late kill is not in the awaited count. |
|
||||
| Runtime-host snapshot races close | Existing close intent suppresses stale snapshots temporarily; host completion remains an accepted gap. |
|
||||
| External/mobile session creation | Sessions created after the main/renderer snapshots are not chased. Existing PTY-exit publication updates mirrors. |
|
||||
|
||||
Orca's production UI currently tracks a single desktop `mainWindow`/renderer. The main daemon action is process-global while renderer cleanup is renderer-local. If multiple desktop windows become supported, this action must be broadcast from main with an action ID and per-window acknowledgement; “shared store probably mirrors it” is not sufficient.
|
||||
|
||||
## Tests and reliability gate
|
||||
|
||||
Add an experimental, `protection: "partial"` `terminal-session.kill-all-surface-cleanup` entry to `config/reliability-gates.jsonc`, owned by `terminal-runtime` at the renderer/main contract layer. The entry must name the focused coordinator and `pty-management` test files/commands and include non-empty assertion refs; otherwise the manifest checker rejects a partial gate.
|
||||
|
||||
- **Invariant:** confirmed terminal surfaces close exactly once; later-created surfaces survive; no broad post-snapshot kill occurs.
|
||||
- **Failure source:** issue #8001 plus the sole-fresh/fresh-split exit guards that intentionally preserve dead startup-failure panes.
|
||||
- **Deterministic oracle:** the initial tab IDs disappear from both terminal/unified state, non-terminal and later-created tabs remain, active state is valid, exact kills are issued only for deduplicated current target bindings, all exact-kill promises settle before the caller callback, and no `pty.listSessions` sweep occurs. Provider inventory absence is live validation, not the renderer-unit oracle.
|
||||
- **Diagnostics:** emit one content-free bounded summary with target/absent/failed-close counts, exact-kill accepted/rejected counts, and the daemon result or error. Runtime-host completion remains unknown until terminal-tab actions propagate the existing async close result.
|
||||
|
||||
Required deterministic coverage:
|
||||
|
||||
- snapshot/dedup across multiple worktrees, unified-only terminals, splits, and floating terminals;
|
||||
- pinned close with `force`, while browser/editor tabs remain;
|
||||
- terminal added after the snapshot survives; missing/moved target behavior;
|
||||
- active-last post-state for editor, browser, and no-other-content cases, including no auto-spawn;
|
||||
- coordinator ordering for success, partial result, zero sessions, and rejected management IPC;
|
||||
- exact binding capture excludes restore hints and `remote:` IDs; late-created tab bindings are not captured;
|
||||
- exactly one management call, zero `pty.listSessions` calls, one close attempt per unique target, and one coordinator-issued exact kill per unique captured non-runtime PTY ID;
|
||||
- invoking component unmount during the management wait does not cancel store/provider cleanup or invoke mount-gated callbacks;
|
||||
- existing `src/main/ipc/pty-management.test.ts` cases remain green.
|
||||
|
||||
Electron validation on Windows must reproduce an empty shell plus an established terminal, invoke each entry point, and prove:
|
||||
|
||||
- target terminal tabs and `.xterm` surfaces are gone;
|
||||
- initial local/daemon PTY IDs are absent after settle, except daemon IDs reported remaining and exact IDs whose shutdown request failed;
|
||||
- a terminal created after confirmation survives;
|
||||
- Resource Manager and Manage Sessions refresh to the same result.
|
||||
|
||||
Planned provider/platform accounting:
|
||||
|
||||
| Row | Planned status |
|
||||
| --- | --- |
|
||||
| Local PTY / daemon / Windows | Covered by deterministic coordinator/main tests plus the required live Electron run. |
|
||||
| macOS / Linux local and daemon | Shared code is covered deterministically; live process absence remains an accepted gap until run there. |
|
||||
| SSH | Exact request/settlement is covered by provider-contract mocks; live remote-process absence is covered only when the SSH fixture runs, otherwise accepted-gap. |
|
||||
| WSL | Uses the local exact-ID path, but real WSL process absence is an accepted gap unless included in the Windows run. |
|
||||
| Remote runtime | Local mirror removal is covered; host completion is accepted-gap while `closeTerminalTab` discards the async result. |
|
||||
| Mobile/relay | No newly created session is chased; shared host-tab disappearance and live relay shutdown remain accepted gaps unless exercised with their fixtures. |
|
||||
|
||||
Screenshots are UI evidence only; they do not prove PTY or memory cleanup.
|
||||
|
||||
## Performance and blast radius
|
||||
|
||||
No interval, watcher, or extra provider listing is added. The existing management call can wait for 65 sleeps plus adapter latency. The coordinator adds at most one existing exact-kill IPC per unique current non-runtime PTY binding; record both those calls and any idempotent unmount duplicates as part of the performance evidence.
|
||||
|
||||
Repeated `closeTerminalTab` calls are not O(tabs): target resolution and store cascades scan/clone multiple maps per close, so worst-case renderer work is superlinear. Measure the synchronous close phase with a representative high-tab fixture (at least 100 terminal tabs). Record close attempts, Zustand writes, duration, and long tasks. If it creates a >50 ms renderer task, add a focused bulk reducer or yield-safe batching rather than declaring the rare action free.
|
||||
|
||||
For resource reclamation, prefer deterministic counts: zero target `TerminalPane`/xterm instances, released listeners/transports, and no initial PTY IDs. A repeated open/kill cycle may supplement this with heap/working-set evidence, but absolute memory deltas are not a stable pass/fail oracle.
|
||||
|
||||
## UI quality bar and screenshots
|
||||
|
||||
No new layout or visual token is needed. Keep the existing shadcn `Dialog`/destructive `Button`, compact typography, dismissal lock while busy, and accurate consequence-first copy. The post-state must never be a blank/crashed TerminalPane or a wall of dead empty panes.
|
||||
|
||||
Required review screenshots:
|
||||
|
||||
1. Resource Manager before kill with an empty terminal and an established terminal visible in the workspace.
|
||||
2. Resource Manager kill-all confirmation with updated close-tabs copy.
|
||||
3. Matched post-kill workspace showing target terminal tabs gone and refreshed counts.
|
||||
4. Manage Sessions confirmation or post-state, proving the second entry point uses the same behavior.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- **Scope:** renderer surface cleanup layered on the existing daemon management action; no daemon redesign and no broad orphan/provider sweep.
|
||||
- **Architecture/data flow:** main owns its initial daemon-session shutdown; renderer owns the confirmed terminal-surface snapshot, exact current-binding shutdown, and tab/xterm disposal; runtime-host close remains behind existing routing.
|
||||
- **Failure modes:** partial/rejected daemon kill, exact provider-kill failure, no-session cleanup, pinning, splits, cleanup-time active selection, new/moved/disappeared tabs, same-tab rebind, overlapping actions, invoking-component unmount, stale runtime snapshots, adapter-list uncertainty, and future multi-window ownership are explicit above.
|
||||
- **Tests:** deterministic state/coordinator and main-handler tests plus Windows Electron proof; a new experimental partial reliability gate records provider gaps.
|
||||
- **Performance/blast radius:** one existing management IPC, bounded exact per-PTY kill IPCs, no new listing/polling, but N close cascades require measurement because current helpers are not linear or atomic.
|
||||
- **UI quality bar:** existing dialog primitives and truthful copy; screenshots prove both entry points and the terminal-free post-state, not memory reclamation.
|
||||
- **Residual risks:** daemon adapter listing can stall until client timeouts and failures are treated as empty; terminal-tab actions discard the runtime-host close result and its 10-second intent is shorter than the possible two-request close flow; a binding created after exact-ID capture is killed only by transport unmount; live SSH/WSL/mobile behavior may remain accepted gaps until fixtures prove it.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add the snapshot/coordinator and deterministic tests.
|
||||
2. Wire it only through `useDaemonActions.runKillAll`; keep the coordinator outside the hook and update toast/dialog copy.
|
||||
3. Add the experimental reliability gate and performance count/latency evidence.
|
||||
4. Run focused tests, typecheck, lint, and max-lines ratchet checks.
|
||||
5. Validate both entry points in Electron on Windows and capture the required screenshots.
|
||||
6. Force-add this doc when staging because `docs/**` is ignored by default.
|
||||
@@ -1,133 +0,0 @@
|
||||
# Linear Issues Load More
|
||||
|
||||
## Problem
|
||||
|
||||
- `src/renderer/src/components/TaskPage.tsx:288` defines `LINEAR_ITEM_LIMIT = 36`.
|
||||
- The plain Linear Issues tabs fetch with that fixed limit in `TaskPage.tsx:4678` and store only `LinearIssue[]`, so All/Assigned/Created/Completed have no `hasMore` state and no in-app way to request more rows.
|
||||
- `src/main/linear/issues.ts:291` returns `Promise<LinearIssue[]>` from `listIssues`. The current list GraphQL queries also do not request `pageInfo`, so the main process cannot infer whether Linear has more results.
|
||||
- `src/main/ipc/linear.ts:115` and `src/main/runtime/orca-runtime.ts:12415` clamp plain issue list reads to 50. A 36-row "Load more" step would request 72 but receive at most 50 unless these clamps change.
|
||||
- Project and custom-view issue reads already return `LinearCollectionResult<LinearIssue>` and render `LinearCollectionNotice`, but their backend helpers cap at 50 and only expose a passive "Search or open Linear" message.
|
||||
|
||||
## Goal
|
||||
|
||||
Let users browse more issues from the Linear Issues All tab inside Orca with an explicit "Load more" action. Apply the same plain-list behavior to Assigned, Created, and Completed because they share the same store/runtime/main read path.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Do not add cursor-based infinite scrolling.
|
||||
- Do not change Linear search behavior; search can stay capped and relevance ordered.
|
||||
- Do not add load-more behavior to project/custom-view issue lists in this change.
|
||||
- Do not change Linear auth, workspace selection, team filtering semantics, or issue mutation behavior.
|
||||
|
||||
## Design
|
||||
|
||||
1. Return collection metadata from plain issue list reads.
|
||||
- Change main `listIssues` to return `LinearCollectionResult<LinearIssue>`.
|
||||
- Add `pageInfo { hasNextPage }` to `ALL_ISSUES_QUERY`, `VIEWER_ASSIGNED_ISSUES_QUERY`, and `VIEWER_CREATED_ISSUES_QUERY`, and update `LinearIssueConnectionResponse` accordingly.
|
||||
- Keep `searchIssues` returning `LinearIssue[]`; it relies on Linear relevance order and should not get the load-more affordance.
|
||||
|
||||
2. Raise and align list limits deliberately.
|
||||
- Replace the current 50-item plain-list clamps in IPC and runtime with a named plain-issue-list max that is higher than one load-more step, for example 180 or 216. Keep the search clamp at 50.
|
||||
- Use the same clamp in local IPC and remote runtime paths. Do not let the renderer cache a request under limit 72 while the backend silently serves 50.
|
||||
- Main `listIssues` should clamp/floor its own `first` value too, so direct callers and future RPC paths cannot send unbounded GraphQL reads.
|
||||
- Keep project/custom-view clamps unchanged unless this feature explicitly expands those lists too.
|
||||
|
||||
3. Compute `hasMore` accurately.
|
||||
- For each workspace result, set `hasMore` from the connection `pageInfo.hasNextPage`.
|
||||
- For any multi-workspace plain-list read, also set `hasMore` when the merged, sorted list is clipped to the effective limit. This is not limited to the All preset; Assigned, Created, and Completed can also fan out across selected workspace `all`.
|
||||
- Sort and cap the merged list the same way the current implementation does. This remains a first-N refetch design, not cursor pagination.
|
||||
|
||||
4. Thread the envelope through IPC, runtime RPC, preload, and the renderer store.
|
||||
- Update `window.api.linear.listIssues`, `linearListIssues`, runtime RPC typing, preload API types, and `LinearSlice.listLinearIssues` to return `LinearCollectionResult<LinearIssue>`.
|
||||
- Plain list entries currently live in `linearSearchCache` under `linearListCacheKey`. Either keep that cache bucket and change the value type to support both arrays and collection results, or introduce a dedicated `linearListCache`. Do not mix raw arrays and envelopes under one declared `CacheEntry<LinearIssue[]>` type.
|
||||
- Split or retarget `inflightListRequests`/`InflightLinearListRequest` separately from search in-flight requests. The current shared in-flight type is `Promise<LinearIssue[]>`, which will be wrong once only list reads return an envelope.
|
||||
- Keep cache identity based on workspace, filter, and the effective clamped limit. Compute that effective limit before request signatures and cache keys; do not key a request by an unclamped value that the backend will silently reduce.
|
||||
- Existing generation and in-flight entry checks protect cache writes for the same key, but different limits are different keys. `TaskPage` still needs a latest-request guard so a slower 36-row promise cannot replace a newer 72-row window in component state.
|
||||
- Update `getCachedLinearIssues` or add a collection-aware cached read so `TaskPage` can keep existing rows visible while a larger window loads.
|
||||
- If plain lists keep using `linearSearchCache`, update every array-shaped consumer of that bucket, including `findTaskPageLinearIssue` and its `LinearSearchCache` alias in `task-page-cache-selectors.ts`, `patchLinearIssue`, and any `LinearSearchCache`/`LinearIssueReadArgs` test helpers. Otherwise a list envelope stored beside search arrays will break drawer lookup, row reconciliation, and optimistic patch propagation.
|
||||
|
||||
5. Add first-N "Load more" state in `TaskPage`.
|
||||
- Replace the fixed list-read limit with `linearIssueLimit` state initialized to `LINEAR_ITEM_LIMIT`.
|
||||
- Reset the limit to `LINEAR_ITEM_LIMIT` when workspace, preset, search query, Linear mode context, or selected project/custom-view changes back to the plain issue list.
|
||||
- For plain list reads, store `result.items` and `result.hasMore`; for search reads, keep the existing array path and no button.
|
||||
- On "Load more", increase by `LINEAR_ITEM_LIMIT`, fetch the larger first-N window, and leave current rows visible during the request.
|
||||
- The request signature and landing-refresh key must include the effective limit; otherwise a 36-row landing probe and a 72-row load-more request can be treated as the same request. Compare the resolving request's signature to the latest signature before setting `linearIssues` or `hasMore`.
|
||||
|
||||
6. Make the shared notice optionally actionable.
|
||||
- Extend `LinearCollectionNotice` with optional `onLoadMore`, `loading`, and label props.
|
||||
- Only render the button when `hasMore` and `onLoadMore` are both present.
|
||||
- Preserve the existing passive copy for project/view notices that do not pass a handler.
|
||||
- Use existing shadcn button primitives and styleguide tokens; keep the footer compact and keyboard reachable.
|
||||
|
||||
## Data Flow
|
||||
|
||||
- User opens Tasks -> Linear -> Issues -> All.
|
||||
- `TaskPage` reads `linearIssueLimit`.
|
||||
- Store calls `linearListIssues(settings, filter, linearIssueLimit, workspaceId)`.
|
||||
- Local IPC or remote runtime calls main `listIssues(filter, effectiveLimit, workspaceId)`.
|
||||
- Main requests `first: effectiveLimit` per selected workspace and returns `{ items, hasMore }`.
|
||||
- `TaskPage` renders `items` and passes `hasMore` plus `onLoadMore` to `LinearCollectionNotice`.
|
||||
- User clicks "Load more" -> `linearIssueLimit += 36` -> the effect refetches first N+36 and replaces the visible window when the newer request resolves.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- Search query is non-empty: do not show Load more; Linear search remains capped and relevance ordered.
|
||||
- User switches preset, workspace, Linear mode, or selected project/view context: reset the plain issue limit to 36.
|
||||
- Cached 36-row result exists and user requests 72: use a distinct cache key and keep 36 rows visible while fetching 72.
|
||||
- Refresh while at 72 rows: force-refresh the 72-row window, not the initial 36-row window.
|
||||
- Backend clamp reached: hide or disable Load more once the current limit equals the configured max, even if Linear reports `hasNextPage`.
|
||||
- Multi-workspace reads: if any workspace has more pages or the merged rows are clipped, show Load more for any plain preset.
|
||||
- Workspace failure in `all`: current plain `listIssues` swallows failures into `[]`; adding `errors` would be a behavior change. Either keep swallowing for this feature or deliberately adopt the project/view `errors` behavior and update UI/tests.
|
||||
- Auth failure for a concrete workspace should still throw after clearing the token when `shouldThrowAuthError` says the whole request should fail.
|
||||
- Team filtering happens after fetch and can hide rows. The notice count should use the unfiltered fetched count so users understand the loaded window size.
|
||||
- External Linear changes between clicks can reorder first-N results because sorting is by `updatedAt`. This is acceptable, but the UI should replace the window rather than append blindly.
|
||||
- Issue mutations currently patch cached rows they can find; they do not invalidate every first-N list window or pull newly eligible issues into the list. Manual refresh remains the consistency boundary.
|
||||
- A lower-limit request already in flight can resolve after the user clicks Load more. It must not replace the larger visible window or clear the larger request's loading state.
|
||||
- SSH/remote runtime: all reads must continue through runtime RPC or preload; no local-only Electron calls should be added.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- `src/main/linear/issues.test.ts`: `listIssues` returns `{ items, hasMore }`, requests `pageInfo`, propagates connection `hasNextPage`, and marks `hasMore` when multi-workspace merged rows are clipped.
|
||||
- Clamp tests for local IPC/runtime paths: plain list max is above 50 and aligned across local and remote; search remains capped at 50.
|
||||
- `src/renderer/src/store/slices/linear.test.ts`: list cache stores the envelope shape, serves higher-limit cache independently, keeps lower-limit rows visible during higher-limit fetch, preserves drawer lookup and optimistic patching for cached list envelopes, and forced refresh still blocks stale overwrites.
|
||||
- Store in-flight tests: list in-flight requests use the collection-result promise shape without changing search in-flight request behavior.
|
||||
- `TaskPage` request-state test if available: a slower lower-limit response does not replace a newer higher-limit response or clear its loading state.
|
||||
- `src/renderer/src/runtime/runtime-linear-client.test.ts`: local and remote `linear.listIssues` expect `LinearCollectionResult<LinearIssue>`.
|
||||
- Component test if available: `LinearCollectionNotice` renders button, disabled/loading state, and no-handler passive copy.
|
||||
- Electron validation: connected Linear All tab with Load more, pending state, post-load state, search mode without a button, and project/custom-view footer still using passive copy.
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
- The notice stays a compact footer matching existing bordered, muted Linear collection notices.
|
||||
- The load-more action is visually secondary, keyboard reachable, and does not resize or overlap the issue list on narrow widths.
|
||||
- While loading more, existing rows remain visible and the button clearly shows progress/disabled state.
|
||||
- Copy is direct: users should understand Orca can fetch more without opening Linear.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
1. Linear Issues All tab showing Load more available.
|
||||
2. Linear Issues All tab while a load-more request is pending.
|
||||
3. Linear Issues All tab after more rows are loaded.
|
||||
4. Linear Issues search results with no load-more button.
|
||||
5. Linear project or custom-view issues footer still showing the old passive message.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Update shared/preload/runtime types for plain `listIssues` collection results.
|
||||
2. Add `pageInfo` to main Linear issue list queries and return `items` plus `hasMore`.
|
||||
3. Raise and align plain-list clamps in main, IPC, and runtime without changing search clamps.
|
||||
4. Update renderer store caches and tests for the new list result shape.
|
||||
5. Update `TaskPage` state/effects/rendering for first-N load more.
|
||||
6. Update `LinearCollectionNotice` to accept an optional load-more action.
|
||||
7. Run focused tests, `pnpm typecheck`, `pnpm lint`, and Electron screenshot validation.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: Correctly keeps the feature to first-N load more for plain issue tabs. It must not imply cursor pagination, because there is no cursor state or merge logic in the current store.
|
||||
- Architecture/data flow: Main owns Linear `pageInfo` extraction and multi-workspace merge semantics; runtime/preload carry the envelope; the store owns envelope caching and stale-write guards; `TaskPage` owns visible window size and load-more UI.
|
||||
- Failure modes: Current auth/network handling differs between plain issue lists and project/view collections. Preserve that difference unless explicitly changing it, and test whichever behavior is chosen.
|
||||
- Concurrency: Include limit in request signatures, cache keys, landing probes, and force-refresh paths. A lower-limit response must not overwrite a newer higher-limit window.
|
||||
- Consistency: First-N refetches can reorder rows after external updates, and optimistic issue patches do not make all list windows complete. This is acceptable only if the UI replaces the full window and refresh remains available.
|
||||
- Performance/blast radius: No startup cost. Each click refetches first N per selected workspace, so multi-workspace All can multiply request cost. Keep a finite plain-list max and do not treat this as a free one-call operation.
|
||||
- UI quality bar: Compact secondary action, stable layout, no overlap/clipping, clear loading state, and preserved passive project/view copy.
|
||||
- Required screenshots: All tab available, pending, after load, search no-button, and project/view passive footer.
|
||||
@@ -1,126 +0,0 @@
|
||||
# Linear Scope Selector
|
||||
|
||||
## Problem
|
||||
|
||||
- `src/renderer/src/components/TaskPage.tsx:4368` renders workspace selection, "open in Linear", and team selection as separate controls even though they define one Linear issue-list scope.
|
||||
- `src/renderer/src/components/ui/team-multi-combobox.tsx:127` offers only "All teams" plus team rows. When a team is absent, there is no affordance that explains whether the key is team-limited, the user lacks private-team access, the team is archived/retired, or the backend failed to fetch every page.
|
||||
- Settings and onboarding both say a workspace is connected, but the connect copy only points to personal API-key settings. It does not explain full-access keys, team-limited keys, member API-key restrictions, or private-team access.
|
||||
- The backend already supports the core scope model: `workspaceId === 'all'` fans out across stored Linear clients, and team list calls are routed through the same runtime APIs used for local and SSH sessions. The gaps are renderer UX plus stale/incomplete data handling.
|
||||
|
||||
## Goal
|
||||
|
||||
Make Linear task scoping feel like one selector:
|
||||
|
||||
1. Replace the separate workspace dropdown and team dropdown in the Tasks toolbar with one Linear scope popover.
|
||||
2. Preserve the existing state model: `selectedWorkspaceId` is one workspace id or `all`; `defaultLinearTeamSelection` remains a nullable global list where `null` means sticky-all and an array means an explicit subset of team IDs.
|
||||
3. Add an "Add team access" path from the selector. It opens a reusable API-key dialog. Pasting a key for an already connected workspace replaces that workspace token because the workspace id is stable.
|
||||
4. Make the copy accurate: one full-access personal API key for a Linear workspace can cover every team the key owner can access in that workspace; restricted/team-limited keys only expose permitted teams; private teams require the key owner to be a member or otherwise have access.
|
||||
5. Link to the most specific Linear settings URL Orca can build from `organizationUrlKey`, with global fallbacks when the workspace is unknown or `all`.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Do not change Linear authentication storage, encryption, IPC/RPC method names, or the `LinearWorkspaceSelection` type.
|
||||
- Do not switch Linear auth to OAuth.
|
||||
- Do not create, join, unarchive, or grant access to Linear teams from Orca. "Add team access" means paste a key whose owner/scope can already see the team.
|
||||
- Do not make team selection per-workspace in this change.
|
||||
- Do not touch provider-generic review code.
|
||||
|
||||
## Required Fixes Before UI
|
||||
|
||||
1. Fix team-list completeness.
|
||||
- `src/main/linear/teams.ts` currently calls `entry.client.teams()` once per workspace. The SDK query is paginated, so this can omit teams in larger workspaces.
|
||||
- Fetch all pages before the selector relies on team absence as a meaningful signal. Use `teams({ first })` plus `fetchNext()` until `pageInfo.hasNextPage` is false, or an equivalent raw GraphQL query. Keep the existing `MAX_CONCURRENT` limiter and do not set `includeArchived`; retired teams should stay absent.
|
||||
|
||||
2. Invalidate caches when a Linear key is connected or replaced.
|
||||
- Replacing a team-limited key with a full-access key must not leave the old `linearTeamCache` visible for up to `TEAM_CACHE_TTL`.
|
||||
- On successful `connectLinear`, synchronously clear Linear issue/search/team caches, in-flight issue/search/list/team requests, and metadata. Do this before publishing success, then await a forced status refresh before resolving so callers see the selected workspace and workspace list that came from the new key. The renderer `linearConnect` result is typed as `{ viewer }` only; do not rely on the main-process-only `workspace` field.
|
||||
- Guard `fetchLinearIssue()` and `listLinearTeams()` cache writes with a request generation or entry identity check. Clearing their in-flight maps is not enough today: those promises write unconditionally after resolution and can repopulate old issue/team data after key replacement. `searchLinearIssues()` and `listLinearIssues()` already use in-flight entry identity checks for forced refreshes; keep them covered by the same generation if connect/disconnect clears their maps.
|
||||
- Force a team refetch for the selected/connected workspace if the Linear Tasks view is open.
|
||||
- Issue list caches also need invalidation because changing key scope can add or remove visible issues.
|
||||
|
||||
3. Handle auth-driven token removal explicitly.
|
||||
- Backend calls can clear a workspace token on auth errors. In `all` workspace mode, `listTeams()`, `listIssues()`, and `searchIssues()` may return partial results instead of throwing.
|
||||
- After any auth-driven clear, the renderer must get a forced Linear status refresh or a typed signal so disconnected workspaces disappear without waiting for a later manual check. The current array-returning issue/search/team APIs have no signal for `all`-mode partial auth clears, so either add an auth-cleared result envelope end-to-end or force a metadata-only status refresh after `all`-workspace issue/search/team reads. Do not set `linearStatus` to globally disconnected from a single request error; refresh status because multi-workspace failures may only remove one workspace.
|
||||
- Strengthen `checkLinearConnection()` status equality. It currently compares workspace count, effective selected id, connected state, and viewer email. It misses active workspace id and workspace metadata changes when the count is unchanged. Compare a stable workspace signature including id, organization id/name/url key, display name, and email.
|
||||
- When a forced status refresh observes a changed selected workspace or workspace signature, clear issue/search/team caches, in-flight issue/search/list/team requests, and metadata. `checkLinearConnection()` currently only updates `linearStatus`, so removed workspaces can leave stale rows in `all` caches.
|
||||
|
||||
4. Be honest about team filtering.
|
||||
- Current Linear issue reads do not accept team IDs; team selection filters the already-limited issue/search result in the renderer after the `LINEAR_ITEM_LIMIT` page arrives. In `all` workspace mode, each workspace may fetch up to the limit, but the backend aggregates and trims back to `LINEAR_ITEM_LIMIT` before the renderer filters by team.
|
||||
- This UI change should not imply exhaustive server-side team scope. Empty task states must say no fetched/current issues match the selected teams. True server-side team scoping needs a separate change to add team IDs to cache keys, runtime RPC params, and Linear GraphQL filters.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add URL helpers in `src/shared/linear-links.ts`.
|
||||
- `buildLinearPersonalApiKeySettingsUrl(organizationUrlKey?: string | null)` returns `https://linear.app/<slug>/settings/account/security` when a slug exists, otherwise `https://linear.app/settings/account/security`.
|
||||
- `buildLinearWorkspaceApiSettingsUrl(organizationUrlKey?: string | null)` returns `https://linear.app/<slug>/settings/api` when a slug exists, otherwise `https://linear.app/settings/api`.
|
||||
- Encode path segments consistently with `buildLinearTeamUrl`.
|
||||
|
||||
2. Add `LinearApiKeyDialog` in `src/renderer/src/components/linear-api-key-dialog.tsx`.
|
||||
- Props: `open`, `onOpenChange`, optional `workspace`, optional `title`, optional `description`, optional `connectLabel`, optional `onConnected`, optional `overlayClassName`/`contentClassName`.
|
||||
- Own input, connecting/error state, Enter-to-submit, and `connectLinear`. Fire `onConnected` only after `connectLinear` resolves with refreshed store status.
|
||||
- Use org-specific URLs only when a single workspace context is known. For `all`, use the global fallback and copy that tells the user to choose the intended Linear workspace.
|
||||
- Guidance:
|
||||
- Create a Personal API key from Account > Security & Access.
|
||||
- Prefer full access when Orca should show every team the account can access in that workspace.
|
||||
- If member API keys are blocked, ask a workspace admin to allow them from workspace API settings. Do not imply the workspace API page creates the personal key.
|
||||
- A key never grants teams the owner cannot access.
|
||||
- Make storage copy runtime-aware. Local runtime keys use the local OS keychain when Electron encryption is available; SSH/remote-runtime keys are stored by that runtime, not necessarily on this machine.
|
||||
|
||||
3. Replace the Tasks toolbar Linear controls with `LinearScopeSelector`.
|
||||
- Suggested file: `src/renderer/src/components/linear-scope-selector.tsx`.
|
||||
- Keep state updates in `TaskPage`: workspaces, selected workspace id, teams, selected team ids, callbacks for workspace select, team select, select-all teams, open selected team URL, and open API-key dialog.
|
||||
- Trigger label examples:
|
||||
- One workspace + sticky-all: `All teams`
|
||||
- One workspace + subset: `ENG, STA +1`
|
||||
- Multiple workspaces + `all` + sticky-all: `All workspaces`
|
||||
- Multiple workspaces + one workspace + sticky-all: `<Workspace name> / All teams`
|
||||
- Multiple workspaces + subset: `<Workspace name> / ENG, STA +1` or `All workspaces / ENG +1`
|
||||
- If the active scope is `all` and selected team keys are duplicated or span multiple workspaces, prefer `All workspaces / 2 teams` over an ambiguous key list.
|
||||
- Popover content:
|
||||
- Search filters team rows by team name, team key, and workspace name.
|
||||
- Workspace section appears only when more than one workspace is connected. It includes "All workspaces" and each workspace.
|
||||
- Selecting a workspace must call the existing `selectLinearWorkspace` flow, clear selected issue/list/error/loading state the same way `TaskPage` does now, and must not mutate `defaultLinearTeamSelection`.
|
||||
- Team section includes "All teams" and selectable team rows. "All teams" persists `defaultLinearTeamSelection: null`; explicit subsets persist an array. Normalize a selection equal to all available teams back to `null`, even if the user selected teams one by one. Never persist an empty array; keep the last team selected or save `null`.
|
||||
- Team rows show name, key, and workspace name when active workspace is `all` or when multiple workspaces exist.
|
||||
- Footer has "Add team access" with a key/link icon. Close the popover before opening the API-key dialog.
|
||||
- Keep the external-link button as an icon-only sibling. It remains an action, and should stay enabled only when exactly one selected team has a URL.
|
||||
|
||||
4. Keep team selection reconciliation, but document its limits.
|
||||
- `reconcileLinearTeamSelection()` preserves sticky-all and drops stale team IDs.
|
||||
- Because the saved team subset is global, switching workspaces may temporarily select all teams in the new workspace while preserving the old saved subset for later. Do not introduce per-workspace persistence here.
|
||||
|
||||
5. Update Settings and onboarding to use `LinearApiKeyDialog`.
|
||||
- Rename "Add workspace" to "Add Linear access" when disconnected and "Update access" or "Add workspace access" when connected.
|
||||
- Replace "Each workspace uses its own locally stored API key" with copy that says each connected Linear workspace has one key stored by the active runtime; a full-access key can cover all visible teams in that workspace, and a restricted key can be replaced any time.
|
||||
- Keep existing per-workspace Test and Disconnect controls.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- No Linear workspaces connected: no Tasks selector; Settings/onboarding still show Connect.
|
||||
- One workspace connected: hide the workspace section, but keep "Add team access" visible.
|
||||
- Multiple workspaces + `all`: team keys/names can repeat across workspaces; always show workspace names in rows.
|
||||
- Empty team result: show an empty state plus footer action. Do not claim the key is the only possible cause; absence can also come from private-team membership, archived teams, permissions, or a fetch failure.
|
||||
- Empty issue result after team selection: say no fetched/current issues match the selected teams. Do not imply Linear was queried exhaustively for those teams.
|
||||
- Legacy or missing `organizationUrlKey`: use global Linear settings URLs and keep the paste flow usable.
|
||||
- Replacement key for an existing workspace: select that workspace, invalidate caches, refresh status, and refetch teams immediately.
|
||||
- Auth errors: a backend call may clear a token. The selector must tolerate stale rows during the refresh, then drop disconnected workspaces when status updates.
|
||||
- Multi-window/external mutations: there is no real-time renderer broadcast. Force `checkLinearConnection(true)` after connect/disconnect/test flows and when opening the selector if stale status would be visible. Forced refresh must still update state and invalidate caches when workspace metadata changed but the workspace count did not. A same-workspace key replacement with identical viewer/workspace metadata is invisible to status today; do not claim that case is handled unless this change adds a non-secret credential revision or a renderer broadcast.
|
||||
- Remote runtime/SSH: continue routing through `connectLinear`, `selectLinearWorkspace`, `listLinearTeams`, and runtime RPC. Do not call local Electron APIs directly except for opening Linear URLs.
|
||||
- Accessibility: trigger is a combobox-style button, rows are keyboard-selectable, icon buttons have labels/tooltips, and the dialog traps focus.
|
||||
|
||||
## Tests
|
||||
|
||||
- `src/shared/linear-links.test.ts`: URL helpers, fallback behavior, and path encoding.
|
||||
- `src/main/linear/teams.test.ts`: paginated team fetching and `all` workspace aggregation.
|
||||
- `src/renderer/src/store/slices/linear.test.ts`: successful connect invalidates issue/search/team caches, drops stale in-flight writes, awaits refreshed status, and does not mark all Linear disconnected for one workspace auth failure.
|
||||
- `src/renderer/src/store/slices/linear.test.ts`: forced status refresh detects changed workspace ids/metadata with the same workspace count and invalidates Linear caches when the scope signature changes.
|
||||
- Component-independent label and selection-persistence helper tests for `LinearScopeSelector`, including selecting every visible team persisting sticky-all (`null`) rather than a frozen full-team array.
|
||||
- Avoid brittle popover DOM tests unless matching an existing selector test pattern.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Fix backend/store correctness: team pagination, connect invalidation, and auth-clear status refresh.
|
||||
2. Add Linear settings URL helpers and tests.
|
||||
3. Add `LinearApiKeyDialog`; migrate Settings, onboarding, and the existing Tasks connect dialog.
|
||||
4. Add `LinearScopeSelector` and replace only the Linear toolbar selector block in `TaskPage`.
|
||||
5. Run focused Linear tests, then `pnpm typecheck` and `pnpm lint`.
|
||||
@@ -1,217 +0,0 @@
|
||||
# Native Chat Codex TUI Parity
|
||||
|
||||
This note maps Codex TUI behavior to Orca native chat on branch
|
||||
`inspect/pr-5824-native-chat`. It is intentionally concrete: the current Orca
|
||||
surface is a PTY harness around the running TUI, while real native parity should
|
||||
move selected paths to Codex app-server protocol v2.
|
||||
|
||||
## Source Map
|
||||
|
||||
- Codex TUI composer: `/Users/jinwoohong/stably/codex/codex-rs/tui/src/bottom_pane/chat_composer.rs`
|
||||
- Slash command parsing and popup:
|
||||
`/Users/jinwoohong/stably/codex/codex-rs/tui/src/bottom_pane/prompt_args.rs`,
|
||||
`/Users/jinwoohong/stably/codex/codex-rs/tui/src/bottom_pane/slash_commands.rs`,
|
||||
`/Users/jinwoohong/stably/codex/codex-rs/tui/src/slash_command.rs`,
|
||||
`/Users/jinwoohong/stably/codex/codex-rs/tui/src/chatwidget/slash_dispatch.rs`
|
||||
- Skills and mentions:
|
||||
`/Users/jinwoohong/stably/codex/codex-rs/tui/src/bottom_pane/skill_popup.rs`,
|
||||
`/Users/jinwoohong/stably/codex/codex-rs/tui/src/skills_helpers.rs`,
|
||||
`/Users/jinwoohong/stably/codex/codex-rs/core-skills/src/loader.rs`,
|
||||
`/Users/jinwoohong/stably/codex/codex-rs/core-skills/src/root_loader.rs`,
|
||||
`/Users/jinwoohong/stably/codex/codex-rs/core-skills/src/injection.rs`
|
||||
- Structured input and native protocol:
|
||||
`/Users/jinwoohong/stably/codex/codex-rs/protocol/src/user_input.rs`,
|
||||
`/Users/jinwoohong/stably/codex/codex-rs/app-server-protocol/src/protocol/v2/turn.rs`,
|
||||
`/Users/jinwoohong/stably/codex/codex-rs/app-server-protocol/src/protocol/common.rs`
|
||||
|
||||
## Current Orca Architecture
|
||||
|
||||
Orca native chat currently sends through the hosted terminal PTY. The composer
|
||||
builds paste bytes, writes them through `sendRuntimePtyInput`, then sends a
|
||||
delayed Enter. This preserves local and SSH behavior because it uses the same
|
||||
runtime path as terminal typing.
|
||||
|
||||
That architecture is useful for incremental adoption, but it means native chat
|
||||
does not own Codex state. It cannot directly set model, reasoning, permissions,
|
||||
skills, or session lifecycle. It can only type commands into the TUI and observe
|
||||
agent hooks/transcripts after the fact.
|
||||
|
||||
## Slash Commands
|
||||
|
||||
Codex behavior:
|
||||
|
||||
- The parser accepts a first-line command of `/name <rest>`.
|
||||
- The slash popup uses Codex's `SlashCommand` enum order as presentation order.
|
||||
- Enter on a selected popup row dispatches the command. Tab completes it into
|
||||
the draft.
|
||||
- Some commands accept inline args: `review`, `rename`, `plan`, `goal`, `ide`,
|
||||
`keymap`, `mcp`, `raw`, `usage`, `pets`, `side`, `resume`, and
|
||||
`sandbox-add-read-dir`.
|
||||
- Commands are control actions, not ordinary user chat turns. For example
|
||||
`/clear` sends `AppEvent::ClearUi`; `/compact` starts compaction; `/model`
|
||||
opens the model picker; `/skills` opens skill management.
|
||||
|
||||
Current Orca behavior:
|
||||
|
||||
- Slash commands are still typed into the TUI over PTY.
|
||||
- Native optimistic chat bubbles are suppressed for slash drafts so `/clear`
|
||||
does not render as a fake queued user message.
|
||||
- The Codex slash catalog now mirrors the visible TUI command list much more
|
||||
closely, but it is still a copied catalog, not a live TUI query.
|
||||
|
||||
Recommended route:
|
||||
|
||||
- Short term: keep PTY dispatch for slash commands, but treat them as command
|
||||
submissions. No optimistic chat bubbles. Enter dispatches; Tab completes.
|
||||
- Medium term: route commands with app-server equivalents directly. Examples:
|
||||
`thread/compact/start`, `thread/list`, `thread/archive`, `thread/delete`,
|
||||
`model/list`, permissions/config reads and writes, `skills/list`.
|
||||
- Long term: stop maintaining a renderer-side Codex command catalog. Either ask
|
||||
Codex for the command inventory or host the Codex composer state machine.
|
||||
|
||||
## Skills And `$`
|
||||
|
||||
Codex behavior:
|
||||
|
||||
- `$` opens the skill popup. Rows show display name, description, category tags,
|
||||
selection state, filtering, sorting, and scrolling.
|
||||
- Codex discovers skills from repo, user, system, admin, and plugin roots. Repo
|
||||
scope sorts before user/system/admin. Exact duplicate paths are deduped.
|
||||
- Skill selection is structured. `UserInput` has `Skill { name, path }`, and
|
||||
app-server protocol v2 mirrors it. Text `$skill` mentions are only the
|
||||
fallback path and must be unambiguous.
|
||||
- Skill injection reads the selected `SKILL.md` by path, records telemetry, and
|
||||
avoids double-injecting already provided host skill prompts.
|
||||
|
||||
Current Orca behavior:
|
||||
|
||||
- Native chat discovers skills through Orca's skills IPC with the active
|
||||
terminal tab's cwd. This is important for worktree symlinks like
|
||||
`.agents/skills`.
|
||||
- `$` autocomplete inserts plain `$skillName` text. That can work through the
|
||||
TUI's text fallback, but it is not equivalent to structured
|
||||
`UserInput::Skill { name, path }`.
|
||||
|
||||
Recommended route:
|
||||
|
||||
- PTY mode: keep `$skill` text insertion, but preserve Codex-like filtering,
|
||||
scrolling, dedupe, and active-cwd discovery.
|
||||
- Native mode: retain the selected skill's path and submit
|
||||
`UserInput::Skill { name, path }` through app-server `turn` input. This avoids
|
||||
ambiguity when multiple skills share a name and lets Codex inject the exact
|
||||
file the user selected.
|
||||
|
||||
## Files, Mentions, And Images
|
||||
|
||||
Codex behavior:
|
||||
|
||||
- User input supports `Text` with text elements, `Image`, `LocalImage`,
|
||||
`Skill`, and `Mention`.
|
||||
- The TUI has file search/mentions and image placeholders. Large pastes become
|
||||
placeholders so text element ranges stay aligned.
|
||||
- Remote image rows are first-class composer attachments and can be removed with
|
||||
keyboard navigation.
|
||||
|
||||
Current Orca behavior:
|
||||
|
||||
- File attach inserts a path/reference into the draft and relies on the TUI to
|
||||
interpret it.
|
||||
- Image paste saves a temp file, then inserts the agent-specific reference.
|
||||
- Local attachments are blocked for remote sessions because the local path may
|
||||
not exist on the SSH target.
|
||||
|
||||
Recommended route:
|
||||
|
||||
- PTY mode: keep conservative path insertion and remote-session blocking.
|
||||
- Native mode: send structured `LocalImage` or `Image` input through Codex
|
||||
protocol and use remote runtime file transfer semantics for SSH.
|
||||
|
||||
## Model, Reasoning, Permissions
|
||||
|
||||
Codex behavior:
|
||||
|
||||
- `/model`, `/permissions`, `/keymap`, `/vim`, `/experimental`, and related
|
||||
commands are stateful TUI/app-server surfaces.
|
||||
- App-server v2 already exposes model listing, config requirements, approval
|
||||
policies, permission profiles, and reasoning effort fields.
|
||||
|
||||
Current Orca behavior:
|
||||
|
||||
- Native chat does not know or set Codex model/reasoning directly. Typing
|
||||
`/model` opens Codex's TUI picker.
|
||||
- Earlier UI controls for model/thinking were removed because they were not
|
||||
wired to real Codex state.
|
||||
|
||||
Recommended route:
|
||||
|
||||
- Do not re-add model or reasoning dropdowns until they read from and write to
|
||||
Codex app-server state.
|
||||
- In PTY mode, expose `/model` as a command shortcut only.
|
||||
|
||||
## Approvals, Elicitations, And Tool UI
|
||||
|
||||
Codex behavior:
|
||||
|
||||
- Approval overlays cover exec approval, permission approval, file change
|
||||
approval, network approval, MCP elicitation, and request-user-input forms.
|
||||
- App-server notifications include thread status, waiting-on-approval/user-input
|
||||
flags, item start/completion, diff/plan updates, and skill changes.
|
||||
|
||||
Current Orca behavior:
|
||||
|
||||
- Native chat has interactive cards sourced from Orca's existing agent status
|
||||
hooks. This is good for common question/approval flows, but it is not the full
|
||||
Codex approval overlay model.
|
||||
|
||||
Recommended route:
|
||||
|
||||
- Keep PTY fallback for anything not represented in Orca hooks.
|
||||
- For Codex-native mode, subscribe to app-server notifications and render
|
||||
approvals/tool calls from protocol events rather than scraping terminal text.
|
||||
|
||||
## Session And History
|
||||
|
||||
Codex behavior:
|
||||
|
||||
- `/new`, `/resume`, `/fork`, `/archive`, `/delete`, `/compact`, and `/clear`
|
||||
are session lifecycle commands.
|
||||
- The composer has local and persistent history; Up/Down recall, Ctrl+R reverse
|
||||
search, Esc edit/interrupt behavior, Ctrl+J newline, Ctrl+T transcript, and
|
||||
Ctrl+C quit/interrupt behavior.
|
||||
|
||||
Current Orca behavior:
|
||||
|
||||
- Native chat has small in-memory draft history and Enter/Shift+Enter.
|
||||
- Session commands are typed into the hosted TUI.
|
||||
|
||||
Recommended route:
|
||||
|
||||
- Short term: keep TUI command dispatch and avoid fake optimistic bubbles for
|
||||
lifecycle commands.
|
||||
- Native mode: use app-server thread APIs for lifecycle and expose real thread
|
||||
transitions in the Orca UI.
|
||||
|
||||
## Priority
|
||||
|
||||
1. Fix PTY-command correctness: Enter dispatches slash commands, Tab completes,
|
||||
slash commands never render as queued chat turns, interrupt clears working UI.
|
||||
2. Make `$` skill popup match Codex basics: active cwd, dedupe, scrolling,
|
||||
filtering, source labels, and no product-specific hardcoding.
|
||||
3. Keep fake model/thinking controls out until backed by Codex app-server state.
|
||||
4. Add an app-server integration spike for Codex native mode: `skills/list`,
|
||||
structured `UserInput::Skill`, model list/settings, and thread lifecycle.
|
||||
5. Move approvals/tool rendering from hook approximations to protocol events.
|
||||
|
||||
## Test Targets
|
||||
|
||||
- `/clear` from native slash popup dispatches immediately and produces no
|
||||
pending user bubble.
|
||||
- `/compact`, `/model`, `/skills`, `/resume`, `/diff`, `/status`, and unknown
|
||||
slash commands behave like the hosted TUI.
|
||||
- `$ref-oss` appears exactly once when the worktree has `.agents/skills` as a
|
||||
symlink.
|
||||
- Down-arrow in `$` suggestions scrolls the popup window.
|
||||
- Interrupt during work returns the composer from Stop to Send after the agent
|
||||
status settles.
|
||||
- SSH sessions never insert local-only attachment paths as if they were remote
|
||||
files.
|
||||
@@ -1,79 +0,0 @@
|
||||
# New Worktree Sidebar Reveal
|
||||
|
||||
## Problem
|
||||
|
||||
Issue https://github.com/stablyai/orca-internal/issues/350 asks that newly created worktrees jump into view in the left sidebar list with no scroll animation.
|
||||
|
||||
Current behavior:
|
||||
|
||||
- `activateAndRevealWorktree(...)` always calls `state.revealWorktreeInSidebar(worktreeId)` with no options.
|
||||
- `revealWorktreeInSidebar` defaults `behavior` to `'smooth'` (`ui.ts`).
|
||||
- `WorktreeList` forwards that behavior to `virtualizer.scrollToIndex(..., { behavior })`.
|
||||
|
||||
Result: off-screen targets animate by default, including freshly created worktrees.
|
||||
|
||||
## Root Cause
|
||||
|
||||
`activateAndRevealWorktree` conflates two intents:
|
||||
|
||||
1. activate existing worktree navigation (smooth reveal is fine);
|
||||
2. activate a just-created worktree (must jump immediately).
|
||||
|
||||
Created-worktree callers cannot currently express reveal intent, so they inherit `'smooth'`.
|
||||
|
||||
## Scope and Non-goals
|
||||
|
||||
- Add an opt-in reveal behavior at activation call sites.
|
||||
- Apply `'auto'` only where the worktree is newly created/added in that flow.
|
||||
- Preserve existing behavior for normal worktree navigation (clicks, keyboard, history nav, palette selection of existing worktrees, port/status-driven activation) unless a caller opts in.
|
||||
- Do not change direct raw reveal paths in IPC handlers that intentionally call `store.revealWorktreeInSidebar(...)` outside `activateAndRevealWorktree` (terminal/editor/mobile focus paths remain smooth).
|
||||
- Do not change sorting/grouping/filter UI, list virtualization strategy, or sidebar styling.
|
||||
|
||||
## Design
|
||||
|
||||
1. Extend `activateAndRevealWorktree` options:
|
||||
- `sidebarRevealBehavior?: PendingSidebarWorktreeReveal['behavior']`.
|
||||
2. In `activateAndRevealWorktree`, call:
|
||||
- `state.revealWorktreeInSidebar(worktreeId, { behavior: opts.sidebarRevealBehavior })` when provided;
|
||||
- otherwise keep `state.revealWorktreeInSidebar(worktreeId)` so default behavior stays unchanged.
|
||||
3. Pass `sidebarRevealBehavior: 'auto'` only from created/added-worktree flows:
|
||||
- `useComposerState` full-create path;
|
||||
- `useComposerState` quick-create path;
|
||||
- `useIpcEvents` `onActivateWorktree` only when the event corresponds to a newly created worktree;
|
||||
- `launch-work-item-direct`;
|
||||
- folder add/create flows that activate a newly-added synthetic folder worktree (`AddRepoCreateStep` folder branch, `NonGitFolderDialog`, and `repos` slice `addNonGitFolder` path).
|
||||
4. Keep existing navigation activations smooth, including:
|
||||
- `AddRepoDialog` / `ProjectAddedDialog` “open primary worktree” actions (these can target pre-existing worktrees, not guaranteed newly created);
|
||||
- all existing `activateAndRevealWorktree(...)` callers that do not opt in.
|
||||
5. Keep `WorktreeList` reveal effect unchanged; it already honors `pendingRevealWorktree.behavior`.
|
||||
|
||||
## Correctness Notes and Edge Cases
|
||||
|
||||
- Repo-filter clearing remains unchanged: `activateAndRevealWorktree` only clears `filterRepoIds` when target repo is excluded.
|
||||
- Other visibility constraints are not auto-cleared. If the target exists but is hidden by other sidebar state, `resolvePendingSidebarReveal(...)` keeps the reveal pending.
|
||||
- The reveal effect uncollapses lineage/group containers before scroll; behavior changes only animation mode, not visibility resolution.
|
||||
- Pending reveal is a single store slot (`pendingRevealWorktree`). Concurrent reveal requests are last-writer-wins; this change should not alter that behavior.
|
||||
- If activation cannot resolve the worktree (`getKnownWorktreeById` miss), behavior remains unchanged (`false`, no reveal queued).
|
||||
- `ui:activateWorktree` is an overloaded IPC used by both creation and non-creation activation paths. The renderer must choose `'auto'` only for create cases (for example, worktree absent before fetch and present after fetch), and keep default smooth reveal for existing-worktree activations.
|
||||
- Multi-window consistency remains per renderer window store; each window applies its own reveal behavior locally.
|
||||
- This change is renderer-only; it does not add main-process coordination and does not make reveal ordering transactional across concurrent async creators.
|
||||
|
||||
## Tests
|
||||
|
||||
Add/adjust focused tests in `worktree-activation` coverage:
|
||||
|
||||
- explicit `sidebarRevealBehavior: 'auto'` is forwarded to `revealWorktreeInSidebar(worktreeId, { behavior: 'auto' })`;
|
||||
- no option still calls `revealWorktreeInSidebar(worktreeId)` (store default remains smooth).
|
||||
|
||||
Add call-site regression tests (recommended, small):
|
||||
|
||||
- one composer create path passes `'auto'`;
|
||||
- one non-created navigation path stays default (no behavior option).
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add `sidebarRevealBehavior` option in `activateAndRevealWorktree`.
|
||||
2. Update created-worktree callers to pass `'auto'`.
|
||||
3. Add tests above.
|
||||
4. Run targeted Vitest tests, then `pnpm typecheck` and `pnpm lint`.
|
||||
5. Validate in Electron: with sidebar overflow, create a worktree and verify the list jumps to it without smooth animation.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,89 +0,0 @@
|
||||
# Orchestration Reset Scope Validation
|
||||
|
||||
## Problem
|
||||
|
||||
`orchestration.reset` silently clears all orchestration state when no scope is provided. The RPC schema accepts every scope as optional at [src/main/runtime/rpc/methods/orchestration.ts](/Users/jinwoohong/orca/workspaces/orca/bug-orchestration.reset-wipes-all-orchestration/src/main/runtime/rpc/methods/orchestration.ts:139), and the handler falls through to `db.resetAll()` at [src/main/runtime/rpc/methods/orchestration.ts](/Users/jinwoohong/orca/workspaces/orca/bug-orchestration.reset-wipes-all-orchestration/src/main/runtime/rpc/methods/orchestration.ts:585). Existing reset tests only cover explicit single scopes at [src/main/runtime/rpc/methods/orchestration.test.ts](/Users/jinwoohong/orca/workspaces/orca/bug-orchestration.reset-wipes-all-orchestration/src/main/runtime/rpc/methods/orchestration.test.ts:1024).
|
||||
|
||||
## Root Cause
|
||||
|
||||
`ResetParams` models `all`, `tasks`, and `messages` as independent optional booleans. The handler then chooses the first truthy scope and treats zero truthy scopes as `all`, so `{}` wipes everything and contradictory inputs such as `{ tasks: true, messages: true }` partially apply the first truthy branch.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Redesign orchestration storage or reset semantics.
|
||||
- Add confirmation prompts to the RPC protocol.
|
||||
- Change `resetAll`, `resetTasks`, or `resetMessages` database behavior.
|
||||
- Change unrelated orchestration commands or provider-specific behavior.
|
||||
|
||||
## Design
|
||||
|
||||
1. Enforce exactly one truthy reset scope at the `ResetParams` schema using `superRefine`.
|
||||
2. Remove the handler fallthrough to `db.resetAll()` so only validated explicit scopes can mutate state.
|
||||
3. Preserve the existing CLI no-flag shortcut by having [src/cli/handlers/orchestration.ts](/Users/jinwoohong/orca/workspaces/orca/bug-orchestration.reset-wipes-all-orchestration/src/cli/handlers/orchestration.ts:440) pass `all: true` when no reset scope flag is present. This keeps CLI compatibility explicit while preventing ambiguous direct RPC calls.
|
||||
4. Let explicit multi-flag CLI invocations reach RPC validation and fail with the shared invalid-argument path. Duplicating scope validation in the CLI is unnecessary because all CLI calls already pass through this RPC method.
|
||||
5. Add RPC regression tests that seed one message and one task, call invalid reset params, assert rejection, and assert both seeded records remain.
|
||||
6. Add CLI parser tests that `orca orchestration reset` calls RPC with `all: true`, and that explicit flags are passed through unchanged for RPC validation.
|
||||
|
||||
## Data Flow
|
||||
|
||||
- CLI no-flag path: `orca orchestration reset` -> CLI handler sends `{ all: true }` -> RPC schema validates -> handler calls `resetAll`.
|
||||
- CLI explicit-flag path: CLI handler forwards the provided flags -> RPC schema validates exactly one truthy scope -> handler calls one database reset method or rejects before side effects.
|
||||
- Direct RPC path: caller params -> RPC schema validates exactly one scope -> invalid params fail before handler side effects.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- `{}` rejects and leaves messages and tasks unchanged.
|
||||
- `{ all: false }` rejects and leaves messages and tasks unchanged.
|
||||
- `{ tasks: true, messages: true }` rejects and leaves messages and tasks unchanged.
|
||||
- `{ all: true, tasks: true }` rejects and leaves messages and tasks unchanged.
|
||||
- `{ all: false, tasks: true }` is valid and resets tasks only; false values are not selected scopes.
|
||||
- Non-boolean values such as `{ all: "true" }` are transformed to `undefined` by `OptionalBoolean` and must reject unless exactly one real boolean `true` is present.
|
||||
- Explicit `{ all: true }`, `{ tasks: true }`, and `{ messages: true }` continue to work.
|
||||
- Remote and SSH callers are covered because the validation sits behind the shared RPC method, not local CLI process state.
|
||||
- Unknown keys do not select a scope. If strict unknown-key rejection is desired, that is a separate RPC schema policy change and should not be bundled into this fix.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- Unit/RPC: extend `src/main/runtime/rpc/methods/orchestration.test.ts` with invalid reset scope tests covering empty params and multiple scopes with preservation assertions.
|
||||
- Unit/RPC: keep existing single-scope tests green to prove no regression to valid reset behavior.
|
||||
- CLI parser: extend `src/cli/index.test.ts` to assert no-flag `orchestration reset` sends `all: true` explicitly.
|
||||
- CLI parser: assert explicit `--tasks`, `--messages`, and multi-flag invocations are represented faithfully rather than silently normalized by the CLI.
|
||||
- Type/lint: run `pnpm typecheck`, `pnpm lint`, and targeted Vitest tests for the touched RPC and CLI files.
|
||||
- Electron/e2e: not required for golden behavior because this is non-UI RPC/CLI validation; Stage 6 should validate via tests and local CLI/RPC behavior instead of app screenshots.
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
Not UI-visible.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
No user-visible UI states. Screenshot artifacts are not required; the validation notes should state that UI screenshot review was skipped because the changed behavior is headless RPC/CLI behavior.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Tighten `ResetParams` validation.
|
||||
2. Simplify the reset handler to trust validated single-scope params.
|
||||
3. Make CLI no-flag reset pass `all: true` explicitly.
|
||||
4. Add RPC regression tests for invalid params preserving state.
|
||||
5. Add CLI parser coverage for the explicit no-flag shortcut and explicit/multi-flag passthrough.
|
||||
6. Run targeted tests, typecheck, and lint.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: Kept to reset RPC validation, CLI argument shaping, and regression tests; no storage or UI changes.
|
||||
- Architecture/data flow: Validation belongs at the shared RPC boundary so CLI, remote, SSH, and direct runtime callers get the same safety contract. CLI no-flag compatibility remains a CLI concern by passing `all: true`.
|
||||
- Failure modes covered:
|
||||
- Empty reset params cannot mutate state.
|
||||
- Contradictory scopes cannot partially apply the first truthy branch.
|
||||
- Failed validation happens before any database reset method runs.
|
||||
- CLI shorthand cannot rely on a dangerous RPC fallback.
|
||||
- CLI multi-flag input fails through the same RPC validation as any other caller.
|
||||
- Test coverage required:
|
||||
- `src/main/runtime/rpc/methods/orchestration.test.ts`: reject empty, false-only, and multi-scope params while preserving seeded message/task state.
|
||||
- `src/main/runtime/rpc/methods/orchestration.test.ts`: existing valid single-scope tests continue passing.
|
||||
- `src/cli/index.test.ts`: no-flag CLI reset passes `all: true`; explicit flags and multi-flag input remain directly represented.
|
||||
- Performance/blast radius: No material concern. One tiny schema refinement and branch simplification run only when reset is invoked.
|
||||
- UI quality bar: Not UI-visible.
|
||||
- Required review screenshots: None; final validation notes should explain that screenshot capture is skipped for headless RPC/CLI behavior.
|
||||
- Residual risks: CLI users may still accidentally clear all state with `orca orchestration reset` because the compatibility shortcut remains, but direct RPC callers can no longer do so accidentally and CLI behavior is now explicit in the caller.
|
||||
- Concurrency/consistency: This change prevents invalid reset requests from entering the mutation path, but it does not make the existing multi-statement reset methods transactional or coordinate concurrent reset/create/send calls across windows. That is acceptable for the issue scope because valid resets are still destructive administrative operations; adding reset serialization would be a separate storage-level change.
|
||||
@@ -1,93 +0,0 @@
|
||||
# Persist Source Control Tree View Choice
|
||||
|
||||
## Problem or Goal
|
||||
|
||||
The Source Control sidebar lets the user toggle changes between list and tree views, but the choice is session-local. After remount or app restart, it falls back to list view. Persist this as a per-user setting, not per-workspace state, so a user's preferred source-control layout follows them across repos and worktrees.
|
||||
|
||||
## Current Behavior
|
||||
|
||||
- `SourceControlViewMode` is a local union in `src/renderer/src/components/right-sidebar/SourceControl.tsx:127`.
|
||||
- `SourceControlInner` already reads global settings from the Zustand store at `src/renderer/src/components/right-sidebar/SourceControl.tsx:329`.
|
||||
- The source-control view mode is initialized with component-local React state at `src/renderer/src/components/right-sidebar/SourceControl.tsx:486`, hard-coded to `'list'`.
|
||||
- The tree/list toggle only calls `setSourceControlViewMode` at `src/renderer/src/components/right-sidebar/SourceControl.tsx:2454` and `src/renderer/src/components/right-sidebar/SourceControl.tsx:2457`.
|
||||
- The chosen mode controls uncommitted entries at `src/renderer/src/components/right-sidebar/SourceControl.tsx:2859` and branch comparison entries at `src/renderer/src/components/right-sidebar/SourceControl.tsx:2967`.
|
||||
- Settings are typed in `GlobalSettings` at `src/shared/types.ts:1271`, defaulted by `getDefaultSettings()` at `src/shared/constants.ts:154`, loaded with default merging at `src/main/persistence.ts:1217`, exposed through `settings:get` / `settings:set` at `src/main/ipc/settings.ts:29`, and updated in the renderer settings slice at `src/renderer/src/store/slices/settings.ts:236`.
|
||||
- `PersistedUIState` exists at `src/shared/types.ts:1704`, but the request specifically asks for the user's setting rather than workspace-specific UI state.
|
||||
|
||||
## Proposed Design
|
||||
|
||||
Add a new global user setting:
|
||||
|
||||
```ts
|
||||
sourceControlViewMode: 'list' | 'tree'
|
||||
```
|
||||
|
||||
Implementation details:
|
||||
|
||||
- Add a shared `SourceControlViewMode = 'list' | 'tree'` type and the field to `GlobalSettings` in `src/shared/types.ts`.
|
||||
- Add the default value to `getDefaultSettings()` in `src/shared/constants.ts`; use `'list'` to preserve existing behavior for new and upgraded users.
|
||||
- Reuse the existing persistence path. `src/main/persistence.ts` already merges `defaults.settings` with `parsed.settings`, so older profiles automatically hydrate the new field without a bespoke migration.
|
||||
- In `SourceControl.tsx`, stop using local `useState('list')` as the durable source of truth. Read the persisted value through a small guard such as `normalizeSourceControlViewMode(settings?.sourceControlViewMode)`, returning `'list'` for missing or invalid values.
|
||||
- Keep a narrowly scoped optimistic mode in `SourceControlInner`: `optimisticSourceControlViewMode: SourceControlViewMode | null`. The rendered mode is `optimisticSourceControlViewMode ?? normalizedSettingsMode`.
|
||||
- Select `updateSettings` from the store and update the toggle handler to compute the next value from the current rendered mode, set the optimistic mode immediately, and persist the next value through `updateSettings({ sourceControlViewMode: next })`.
|
||||
- Track a monotonically increasing write sequence with a ref. Only the latest in-flight write may clear or revert optimistic state, so out-of-order `settings:set` responses cannot make an older click win over the user's latest intent.
|
||||
- When `settings.sourceControlViewMode` changes from outside this component, clear the optimistic value if there is no newer in-flight write. This lets the authoritative settings snapshot take back over after hydration, Settings import, or another renderer path updates settings.
|
||||
- Keep tree expansion/collapse state (`collapsedTreeDirs`) local and session-only. Directory expansion is path/worktree-content-specific, while the requested setting is only the global list/tree layout preference.
|
||||
- Do not add a Settings pane control unless product wants one later. The existing toolbar icon remains the natural place where the user makes the choice; persisting that click is enough for this request.
|
||||
|
||||
The optimistic state is local UI state only; it is not a second persistence channel. It exists because `updateSettings` crosses async renderer/main IPC, and the toolbar should still behave as a normal toggle under slow writes or rapid clicks.
|
||||
|
||||
### Interaction and Data Flow
|
||||
|
||||
```text
|
||||
Toolbar click
|
||||
-> derive next mode from current rendered mode
|
||||
-> optimistic SourceControlInner state updates immediately
|
||||
-> updateSettings({ sourceControlViewMode: next })
|
||||
-> settings:set persists user settings in main
|
||||
-> renderer store receives authoritative GlobalSettings
|
||||
-> SourceControlInner clears optimistic state when the latest write settles
|
||||
```
|
||||
|
||||
- Happy path: the toolbar flips immediately, `settings:set` returns the saved settings object, and the optimistic value is cleared once the authoritative mode matches the latest requested mode.
|
||||
- Missing setting: defaults merge in `'list'`; upgraded profiles do not need a migration.
|
||||
- Invalid persisted value: the renderer guard treats it as `'list'` for display and for the next toggle write, which self-heals persistence on the next user action.
|
||||
- Write failure: keep the previous authoritative settings object, clear only the latest optimistic value, and let the UI fall back to the last saved mode. Existing `updateSettings` logs the failure; the component does not need a new error surface for this preference toggle.
|
||||
- Out-of-order writes: if write 1 sets `tree` and write 2 sets `list`, write 1 resolving after write 2 must not clear or overwrite the optimistic `list` intent in the component.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- Existing profiles with no `sourceControlViewMode` should behave exactly as before: list view.
|
||||
- Settings may be `null` before hydration; render should not crash. Disable the toggle until settings hydrate so the fallback `'list'` value is never persisted over an existing saved `'tree'` preference.
|
||||
- If the body renders before settings hydrate, use the guarded list fallback only as a temporary display value. Do not seed optimistic state until the real settings snapshot is available.
|
||||
- Corrupt or unknown persisted values should normalize to `'list'` at the component boundary. A broader settings migration is unnecessary for this narrowly scoped string preference.
|
||||
- A settings write failure should not corrupt local or persisted state. Existing `updateSettings` logs errors and leaves the previous settings object intact.
|
||||
- Rapid toggles should be last-intent-wins from the user's perspective, even if individual `settings:set` IPC responses resolve out of order.
|
||||
- The choice must apply globally across active worktree switches, repo switches, and local/SSH runtime targets.
|
||||
- Directory collapse state should not persist globally because tree node keys are derived from file paths and sections; persisting them would leak one repo's shape into another.
|
||||
- Source control can render both local and remote/SSH worktrees. This setting is renderer/user preference only and must not depend on filesystem paths, runtime target IDs, or workspace IDs.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- Unit: add a focused test for `getDefaultSettings()` in `src/shared/constants.test.ts` asserting `sourceControlViewMode` defaults to `'list'`.
|
||||
- Unit: add or extend a renderer test around `SourceControl` to verify clicking the tree/list toolbar calls `updateSettings({ sourceControlViewMode: 'tree' })` from the default list state, and then `updateSettings({ sourceControlViewMode: 'list' })` when currently tree.
|
||||
- Unit: cover the optimistic write sequence with delayed mocked `updateSettings` promises. A rapid `list -> tree -> list` interaction should leave the rendered mode and latest requested update at `list`, even if the earlier `tree` write resolves last.
|
||||
- Unit: cover `settings === null` hydration behavior: the toggle is disabled before hydration, then reflects a hydrated `'tree'` preference without persisting the fallback `'list'`.
|
||||
- Unit: cover the normalization helper for invalid values, missing values, and both valid modes.
|
||||
- Unit: if direct `SourceControl` rendering setup is too heavy, extract tiny pure helpers such as `getNextSourceControlViewMode(mode)` and `normalizeSourceControlViewMode(value)` near the component and test those helpers plus a shallow mocked component interaction.
|
||||
- Integration-light: `src/renderer/src/store/slices/settings.test.ts` already verifies rebasing local settings to the authoritative `settings:set` response. No new store behavior is required unless implementation changes `updateSettings`.
|
||||
- Manual/Electron: open Source Control, switch to tree view, switch worktrees and confirm the view remains tree, restart the app and confirm Source Control still opens in tree view, then switch back to list and confirm restart preserves list.
|
||||
|
||||
Playwright coverage is optional for this change. The behavior crosses app restart and local user-data persistence, which is better covered by Electron validation unless there is already a reliable e2e fixture for persistent settings across relaunch.
|
||||
|
||||
## Rollout Order
|
||||
|
||||
1. Add the `GlobalSettings` field and default.
|
||||
2. Wire `SourceControl` to read a normalized `settings.sourceControlViewMode` with a safe list fallback before hydration.
|
||||
3. Add optimistic last-intent-wins toggle handling and persist toolbar toggles through `updateSettings`.
|
||||
4. Add focused unit coverage for the default, normalization, hydration, and async toggle writes.
|
||||
5. Run `pnpm typecheck`, `pnpm lint`, targeted tests, then manual Electron validation.
|
||||
|
||||
## Ref-OSS
|
||||
|
||||
Not used. The change follows Orca's existing per-user settings pipeline and does not need external editor behavior to resolve the design.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,279 +0,0 @@
|
||||
# Daemon lifecycle retirement for issue #9138
|
||||
|
||||
## Status
|
||||
|
||||
Implemented and locally validated for PR #9277.
|
||||
|
||||
The earlier full ownership/audit prototype is preserved at:
|
||||
|
||||
- branch: `Jinwoo-H/issue-9138-full-ownership-audit-snapshot`
|
||||
- commit: `7c915909bd26670b8af36aa683cff85077395dd1`
|
||||
- GitHub: <https://github.com/stablyai/orca/tree/Jinwoo-H/issue-9138-full-ownership-audit-snapshot>
|
||||
|
||||
That branch is the recovery point for ownership persistence, cross-profile raw extraction, startup
|
||||
audit, the candidate journal, profile-transfer recovery, natural-exit reconciliation, and future
|
||||
legacy enforcement. None of those systems ship in this PR.
|
||||
|
||||
Current `main` assigned protocol v23 to the macOS login-shell preparation change while this work was
|
||||
in progress. The lifecycle contract therefore ships as v24; v23 is preserved as a legacy generation
|
||||
alongside v22 and older versions.
|
||||
|
||||
## Inputs and scope decision
|
||||
|
||||
Issue: <https://github.com/stablyai/orca/issues/9138>
|
||||
|
||||
Reviewed design comment by AmethystLiang:
|
||||
<https://github.com/stablyai/orca/issues/9138#issuecomment-5006601124>
|
||||
|
||||
The reviewed comment correctly identifies two different problems:
|
||||
|
||||
1. current-generation daemons have no daemon-owned empty lifecycle;
|
||||
2. legacy sessions need complete cross-profile ownership evidence before an app-side reaper can act.
|
||||
|
||||
This PR solves only the first problem. The second problem is much larger, adds steady-state
|
||||
persistence and startup-audit cost, and is audit-only until field evidence can justify enforcement.
|
||||
Keeping it out makes the user-visible fix small enough to review and benchmark independently.
|
||||
|
||||
The narrow implementation retains these important rules from AmethystLiang's design:
|
||||
|
||||
- daemon lifecycle behavior requires a protocol bump because old running daemons cannot acquire it;
|
||||
- live sessions always win over cleanup;
|
||||
- absence from a worktree, pane layout, profile, or failed listing is never destructive evidence;
|
||||
- exact PID, process-start time, and per-launch nonce identify a v24 endpoint incarnation;
|
||||
- the daemon, not app startup, makes the atomic empty decision;
|
||||
- pre-v24 daemons stay reattachable and are not automatically shut down;
|
||||
- SSH, WSL, remote-runtime, degraded-provider, sleep/wake, and profile behavior stay unchanged.
|
||||
|
||||
The narrow implementation changes one policy from the original comment: it does not use a blanket
|
||||
30-minute idle timer. Any loss of the last fully authenticated app client is an exact lifecycle
|
||||
event, so a daemon retires as soon as it can atomically prove it is empty. This removes runtime
|
||||
inactivity heuristics and periodic ownership work.
|
||||
|
||||
## User-visible behavior
|
||||
|
||||
```text
|
||||
Before
|
||||
|
||||
app disconnects ──> daemon stays forever
|
||||
├── live sessions stay (wanted)
|
||||
└── zero sessions also stay (leak)
|
||||
|
||||
After
|
||||
|
||||
clean app detach ──> daemon atomically checks itself
|
||||
├── any live session/work/client ──> stay alive
|
||||
└── exactly empty ──> exit immediately
|
||||
|
||||
unexpected drop ──> daemon atomically checks itself
|
||||
├── live session/work/connection ──> stay alive
|
||||
└── exactly empty ──> exit immediately
|
||||
|
||||
v23 and older ──> existing reattach behavior; no automatic retirement
|
||||
```
|
||||
|
||||
An end user with live terminals should notice no change. An end user who quits with no daemon-backed
|
||||
terminals should no longer accumulate the new v24 generation. If Orca crashes or loses its socket,
|
||||
live terminals still keep the daemon alive indefinitely. An empty daemon exits immediately; a later
|
||||
app restart launches a fresh daemon instead of reusing an empty process.
|
||||
|
||||
## Protocol and lifecycle design
|
||||
|
||||
### Endpoint identity
|
||||
|
||||
Protocol v24 hello responses include:
|
||||
|
||||
```ts
|
||||
type DaemonEndpointIdentity = {
|
||||
pid: number
|
||||
startedAtMs: number
|
||||
launchNonce: string
|
||||
}
|
||||
```
|
||||
|
||||
The parent generates the launch nonce, passes the nonce and PID-record path to the daemon, and writes
|
||||
the daemon's self-reported start time plus the same nonce to the PID record. Both authenticated client
|
||||
sockets must report the same valid identity. v24 rejects a missing or malformed identity; v23 keeps
|
||||
the previous identity-free handshake.
|
||||
|
||||
PID publication is fail-closed. Missing readiness identity, invalid PID, an existing PID record, or a
|
||||
write failure terminates the new child and fails launch instead of leaving an untracked daemon.
|
||||
|
||||
### Clean detach
|
||||
|
||||
At the end of `DaemonPtyAdapter.disconnectOnly()`, after final checkpoints and producer resumes, a
|
||||
v24 adapter establishes a full connection if necessary and sends `shutdownIfIdle` within one shared
|
||||
250 ms budget. v23 and older adapters skip it.
|
||||
|
||||
Initialization establishes one authenticated v24 lifecycle lease even before the first terminal is
|
||||
opened. This cancels the initial launch-adoption watchdog and ensures a never-used daemon can still
|
||||
receive clean retirement on quit. If startup fallback has already won, the late daemon is not
|
||||
installed; it instead receives the same bounded retirement attempt, which an adopted live session
|
||||
will reject.
|
||||
|
||||
The daemon accepts retirement only when, in one event-loop turn:
|
||||
|
||||
- the requesting authenticated client has both control and stream sockets;
|
||||
- it is the only authenticated client;
|
||||
- every accepted transport belongs to that client;
|
||||
- no `createOrAttach` operation is in flight;
|
||||
- the terminal host has zero sessions.
|
||||
|
||||
When all conditions hold, the daemon synchronously closes the listening server before replying. That
|
||||
is the admission fence: a new socket or terminal cannot appear after the empty proof. Cleanup then
|
||||
runs asynchronously and the process exits. A failed RPC is non-fatal to app quit and falls back to
|
||||
the same event-driven empty check when the authenticated sockets close.
|
||||
|
||||
### Initial adoption watchdog
|
||||
|
||||
A freshly launched v24 daemon gets up to two minutes to receive its first complete authenticated
|
||||
client pair. Without this startup-only watchdog, the daemon would prove itself empty and exit in the
|
||||
normal launch handoff before the parent could connect; without a bound, a parent crash during that
|
||||
handoff would orphan the new daemon forever.
|
||||
|
||||
A complete pair permanently cancels this watchdog, and terminal admission requires that complete
|
||||
pair. Raw and partial transports pause it without extending its original deadline. It is never
|
||||
rearmed after adoption and is not a terminal inactivity or crash-reconnect timer.
|
||||
|
||||
### Unexpected disconnect
|
||||
|
||||
When the last client that completed both authenticated sockets loses its control connection, the
|
||||
daemon records an event-driven retirement request with no wall-clock grace.
|
||||
|
||||
- A complete authenticated reconnect cancels the request if existing work or a transport kept the
|
||||
daemon alive long enough to reconnect.
|
||||
- Only a complete authenticated pair may admit a terminal; completing that pair cancels the request
|
||||
before admission can begin.
|
||||
- A raw socket, one-socket health probe, or partial authenticated connection blocks retirement but
|
||||
cannot erase evidence that the last fully connected app left.
|
||||
- Replacing a client ID first records the old full connection's loss; completing the replacement
|
||||
stream cancels that evidence, while an incomplete replacement only blocks retirement.
|
||||
- A live session prevents shutdown indefinitely. When the last session exits, the daemon immediately
|
||||
rechecks every guard and retires only if it is then exactly empty.
|
||||
|
||||
The adapter remembers an authenticated unexpected disconnect. If self-retirement later removes the
|
||||
token, a token-file `ENOENT` is respawnable only with that prior evidence. An initial missing token is
|
||||
not broadened into destructive or respawn authority.
|
||||
|
||||
### Artifact cleanup
|
||||
|
||||
The daemon removes only artifacts it can claim as its own:
|
||||
|
||||
- token contents must match the daemon's in-memory token;
|
||||
- PID and launch nonce must match the daemon process and launch nonce;
|
||||
- cleanup first renames the canonical entry to a unique claim, validates that claim, and never
|
||||
overwrites or unlinks a replacement installed at the canonical path.
|
||||
|
||||
Current-protocol external cleanup waits for v24 self-shutdown and does not unconditionally remove v24
|
||||
PID/socket artifacts. Legacy cleanup behavior is unchanged.
|
||||
|
||||
## Performance design
|
||||
|
||||
There is no polling, profile enumeration, ownership checksum, candidate journal, process scan, or
|
||||
steady-state persistence write in this PR.
|
||||
|
||||
The steady-state terminal hot path adds no timer work and no per-byte hashing. Initialization adds one
|
||||
two-socket authenticated lifecycle handshake; the only new RPC is on app/provider detach, and its
|
||||
connect-plus-request path shares a 250 ms cap, including when quit joins an existing connection
|
||||
attempt; teardown fences that attempt from resurrecting sockets afterward. Unexpected-disconnect
|
||||
bookkeeping changes only socket and session lifecycle events. Each unadopted daemon owns at most one
|
||||
unref'ed startup watchdog, which is canceled permanently on adoption.
|
||||
|
||||
Validation compares current main and the branch for:
|
||||
|
||||
- daemon connect plus two-socket hello latency;
|
||||
- repeated `listSessions` RPC latency;
|
||||
- terminal echo/stream throughput through a real socket daemon;
|
||||
- clean empty-detach latency;
|
||||
- event-loop delay under repeated RPC/stream work;
|
||||
- idle CPU/RSS and timer count where observable.
|
||||
|
||||
The acceptance target is no statistically meaningful terminal throughput regression and no new
|
||||
steady-state disk writes. Results are recorded in the PR body.
|
||||
|
||||
### Local performance regression screen
|
||||
|
||||
The final local host was not quiet enough for publication-grade absolute numbers: load averages were
|
||||
17-38 and unrelated Orca, browser, simulator, and VM processes occupied several cores. A paired
|
||||
same-host screen still found no large regression. Five `main` v23 samples were bracketed by ten v24
|
||||
branch samples; medians across sample medians were:
|
||||
|
||||
| Measure | `main` v23 | branch v24 |
|
||||
| -------------------- | ---------: | ---------: |
|
||||
| two-socket connect | 1.38 ms | 1.32 ms |
|
||||
| `listSessions` RPC | 0.0366 ms | 0.0374 ms |
|
||||
| terminal echo stream | 3.28 MiB/s | 3.14 MiB/s |
|
||||
|
||||
All three medians were within about 5%. Individual stream samples varied from 0.66 to 4.04 MiB/s and
|
||||
event-loop-delay samples had similar load-driven outliers, so these results are a coarse regression
|
||||
screen, not evidence of an exact performance delta. Static hot-path review confirms lifecycle work
|
||||
runs on connection, disconnection, session admission/exit, and quit events, with no new work per PTY
|
||||
byte and no steady-state persistence or polling.
|
||||
|
||||
## Verification and validation
|
||||
|
||||
### Focused unit and integration tests
|
||||
|
||||
- v24 requires valid matching endpoint identity on both sockets.
|
||||
- v23 and v22 accept the prior identity-free handshake and remain listed as previous protocols.
|
||||
- production launch passes PID path and nonce and writes the exact readiness identity.
|
||||
- incomplete readiness identity or failed exclusive PID publication kills and rejects the child.
|
||||
- clean empty detach exits immediately.
|
||||
- a never-used current adapter connects and retires cleanly on quit.
|
||||
- initial adoption cancels the launch watchdog and keeps first-terminal spawn working after its old
|
||||
deadline.
|
||||
- a live session, another client, raw transport, or in-flight admission rejects clean retirement.
|
||||
- a control-only overlapping client blocks but cannot erase the last full-client retirement request.
|
||||
- a same-client-ID control replacement cannot erase the prior full connection's retirement request.
|
||||
- a control-only client cannot admit a terminal or erase startup/retirement evidence with a failed
|
||||
request.
|
||||
- startup fail-open performs bounded empty retirement without installing a late provider.
|
||||
- quit remains bounded while a prior handshake is stalled and cannot resurrect client sockets later.
|
||||
- the synchronous listener fence rejects post-fence connections as retryable.
|
||||
- an unexpected empty disconnect retires immediately without a runtime inactivity timer.
|
||||
- a real reconnect cancels pending retirement while live work keeps the daemon available.
|
||||
- raw and health probes block but cannot erase pending retirement.
|
||||
- final session exit triggers an immediate guarded retirement check.
|
||||
- token/PID cleanup preserves malformed, stale, and replacement artifacts.
|
||||
- authenticated token disappearance performs one coalesced respawn; initial token absence does not.
|
||||
|
||||
### Process/E2E tests
|
||||
|
||||
- start a real isolated v24 daemon with real socket/named-pipe, token, and PID artifacts;
|
||||
- authenticate, disconnect the last empty client, and verify the exact process and owned artifacts
|
||||
exit;
|
||||
- prove a live session rejects retirement and remains reattachable;
|
||||
- run a protocol-v22 fixture beside v24 and prove v22 remains connectable/reattachable;
|
||||
- never target a production runtime directory or signal a process not created by the fixture.
|
||||
|
||||
### Repository validation
|
||||
|
||||
- Node typecheck;
|
||||
- oxlint and repository max-lines policy;
|
||||
- focused daemon, adapter, launcher, restart, and legacy-routing suites;
|
||||
- full daemon test suite;
|
||||
- desktop and web production builds;
|
||||
- `git diff --check` and review of every changed file against `origin/main`;
|
||||
- independent review-until-clean, with review loops recorded in `.orca/bug-factory.json`;
|
||||
- packaged Windows/Linux validation where CI is available; local macOS process E2E before publication.
|
||||
|
||||
Final local results on macOS arm64 after the event-driven policy revision:
|
||||
|
||||
- full daemon suite: 56 files passed, 2 skipped; 939 tests passed, 5 skipped;
|
||||
- process E2E: v22 remained live and reattachable while the exact empty v24 process and its owned
|
||||
artifacts retired immediately after its final authenticated client disconnected;
|
||||
- full Node typecheck, focused oxlint, max-lines ratchet, and `git diff --check` passed;
|
||||
- full desktop, web, and native production build passed with existing build warnings;
|
||||
- three independent post-revision review tracks covering architecture/state machines,
|
||||
ownership/adoption, and process lifecycle ended clean after actionable findings were fixed.
|
||||
|
||||
The local shell used Node 26.5.0 while the repository requests Node 24; the commands completed
|
||||
successfully, and repository CI remains responsible for the supported Node/platform matrix.
|
||||
|
||||
## Rollout and rollback
|
||||
|
||||
This PR changes only v24. Existing v23 and older daemons are preserved. Rolling back the app leaves
|
||||
v24 as another legacy generation and does not give an older app authority to shut it down.
|
||||
|
||||
If the lifecycle behavior must be disabled, revert the v24 protocol/lifecycle commit. The separated
|
||||
ownership/audit prototype remains recoverable from the archived branch and commit above; it should
|
||||
return only as a separately reviewed, benchmarked follow-up.
|
||||
@@ -1,545 +0,0 @@
|
||||
# Windows ConPTY Startup Query and Focus Authority Design
|
||||
|
||||
Date: 2026-07-19
|
||||
|
||||
Status: Implemented with the 2026-07-20 ownership amendment below
|
||||
|
||||
## 2026-07-20 Ownership Amendment
|
||||
|
||||
Fresh paired-runtime evidence showed that the display/controller platform is not a safe proxy for
|
||||
the PTY backend. A macOS client can attach to a native ConPTY owned by a paired Windows runtime, so
|
||||
renderer-side local/SSH/remote heuristics can transfer OSC 10/11 authority to the wrong responder.
|
||||
|
||||
The PTY-owning process now classifies the backend from its own platform and the shell that actually
|
||||
won spawn: `windows-conpty`, `windows-wsl`, or `posix-pty`. Native ConPTY consumes complete OSC 10/11
|
||||
queries before model, replay, or view delivery. During the bounded startup window it replies once
|
||||
when validated theme colors are available; after the deadline, or without colors, it consumes the
|
||||
query without replying. A consuming-view handshake does not transfer this authority. Split query
|
||||
candidates remain bounded and private across authority-close, expiry, and snapshot barriers; a
|
||||
candidate that proves malformed is released unchanged.
|
||||
|
||||
WSL and POSIX PTYs continue to transfer authority to the normal visible/hidden responder after the
|
||||
startup window. The same owner-side rule applies to local, daemon, SSH-relay, and paired-runtime
|
||||
PTYs. This amendment supersedes contrary transfer/fallback language below; the echo projection is
|
||||
selected only by the authoritative owner backend, never by renderer or connection metadata.
|
||||
|
||||
## Problem
|
||||
|
||||
On native Windows ConPTY sessions, a new agent can sometimes show terminal protocol bytes as user
|
||||
text:
|
||||
|
||||
```text
|
||||
]10;rgb:2e2e/3434/3434\]11;rgb:ffff/ffff/ffff\
|
||||
```
|
||||
|
||||
An independent symptom can prefix user input with `[I`, the printable tail of the standard terminal
|
||||
focus-in report `CSI I`.
|
||||
|
||||
The OSC text is an Orca-generated reply to the agent's OSC 10/11 foreground/background query. The
|
||||
agent can issue that query before a daemon-backed `spawn()` resolves to the renderer, and waits only
|
||||
about 100 ms for the answer. Orca therefore has a short-lived main-side startup responder in
|
||||
addition to the normal renderer/model query authorities. On affected ConPTY timing, the reply sent
|
||||
to the PTY is returned as cooked output with its ESC bytes removed. The current ingestion order
|
||||
records that cooked echo in the authoritative runtime model before any renderer-bound filtering.
|
||||
|
||||
The focus symptom must not be treated as the same bug without evidence. ConPTY deliberately emits
|
||||
DECSET 1004 (focus reporting) and DECSET 9001 (Win32 input mode) at startup. A direct native
|
||||
PowerShell ConPTY capture consistently produced the bootstrap pair, while an injected `CSI I` was
|
||||
consumed as a focus event and did not render as `[I`. The bootstrap is valid transport protocol;
|
||||
the failure requires an additional agent, timing, input-mode, or replay condition.
|
||||
|
||||
## Root Cause
|
||||
|
||||
OSC responders downstream of the PTY owner do not know whether the bytes came from native ConPTY,
|
||||
WSL, or a POSIX PTY. `LocalPtyProvider` calls the runtime before its public data listeners
|
||||
([`local-pty-provider.ts`](../../../src/main/providers/local-pty-provider.ts)), while daemon `Session`
|
||||
advances sequence state, writes its emulator, persists pending output, and fans out data before
|
||||
Electron main receives it ([`session.ts`](../../../src/main/daemon/session.ts)). A renderer-only
|
||||
filter can therefore misclassify paired runtimes and hide the symptom without removing it from the
|
||||
authoritative model, daemon history, snapshots, or remote delivery.
|
||||
|
||||
The corrupted echo is timing-dependent but its ordering failure is deterministic: any sanitizer
|
||||
downstream of an authoritative consumer is too late. The independent `[I` symptom has not yet met
|
||||
that evidentiary bar, so this design fixes the proven OSC path and adds the real focus-path harness
|
||||
without pre-approving a speculative focus workaround.
|
||||
|
||||
## Data Flow
|
||||
|
||||
```text
|
||||
node-pty / remote relay PTY
|
||||
-> shell-ready marker scan
|
||||
-> source-owned serialized ingress transaction
|
||||
-> consume an early OSC query and write one canonical reply
|
||||
-> match or losslessly release the measured native-Windows echo projection
|
||||
-> authoritative emulator + persistence/history
|
||||
-> runtime side effects and mobile/remote stream
|
||||
-> renderer delivery or hidden-drop decision
|
||||
-> live terminal / snapshot restore
|
||||
```
|
||||
|
||||
Raw sequence spans travel beside cleaned strings through every downstream hop. Empty transformed
|
||||
spans advance sequence and flow-control state without writing bytes into an emulator or view.
|
||||
|
||||
## Rejected Prototype
|
||||
|
||||
The current working-tree prototype is not the implementation of this design:
|
||||
|
||||
- It removes ConPTY's leading `?1004h` in the renderer. This changes valid native-console focus
|
||||
semantics for every Windows PTY, including programs unrelated to agents.
|
||||
- It filters OSC echo text only after runtime/model ingestion. The live pane can look clean while a
|
||||
hidden restore, reconnect, mobile view, or CLI snapshot still contains the garbage.
|
||||
- Its echo state activates only after both color slots are answered. An echo of the first response
|
||||
can escape if it arrives before the second query.
|
||||
- Its partial-match buffer can be lost on timeout, and its substring search can remove a later
|
||||
legitimate string that happens to equal a reply.
|
||||
|
||||
Implementation starts by removing the prototype's bootstrap output filter and renderer-only cooked
|
||||
echo filtering. Existing unrelated Windows focus-idle safeguards remain.
|
||||
|
||||
## Existing Contracts Preserved
|
||||
|
||||
This design extends, rather than replaces:
|
||||
|
||||
- [`terminal-model-view-contract.md`](../terminal-model-view-contract.md), especially singular query
|
||||
authority, authoritative model restore, and raw sequence ordering;
|
||||
- [`terminal-query-authority.md`](../terminal-query-authority.md), especially delivered-versus-
|
||||
hidden-dropped ownership and replay silence;
|
||||
- [`terminal-side-effect-authority.md`](../terminal-side-effect-authority.md), especially parsing PTY
|
||||
bytes once in main before renderer delivery.
|
||||
|
||||
The startup responder is a bounded exception needed before normal delivered/dropped ownership can be
|
||||
established. It must join the same ingestion decision, not operate as an unrelated renderer scrub.
|
||||
|
||||
## Decision 1: Source-Owned PTY Ingress Transaction
|
||||
|
||||
Sanitization must run on the host that owns the PTY, before that host mutates any authoritative
|
||||
model or persistence. Electron main is too late for daemon sessions: `Session` has already advanced
|
||||
its sequence, written its emulator, recorded pending output, and broadcast the data before main's
|
||||
provider callback runs.
|
||||
|
||||
The transaction therefore has three installations of the same shared state machine:
|
||||
|
||||
- in `LocalPtyProvider`, before its configured runtime callback and data listeners;
|
||||
- in daemon `Session`, before `outputSequence`, emulator writes, pending/checkpoint records, and
|
||||
attached-client fanout;
|
||||
- in relay `PtyHandler`, before relay replay/history buffering and `pty.data` fanout. Main's
|
||||
`SshPtyProvider` is only an RPC proxy and never sanitizes relay output.
|
||||
|
||||
Electron main receives already-classified daemon data. A remote-runtime desktop client does not
|
||||
reinterpret the stream; the remote Orca host owns its transaction. WSL sessions follow their actual
|
||||
provider owner but never enable the native-Windows compatibility projection.
|
||||
|
||||
Fresh-session creation carries startup-transaction intent atomically. Daemon `createOrAttach`
|
||||
receives the recognized-agent intent, execution-host kind, deadline, and validated renderer-pushed
|
||||
color attributes. It first decides fresh versus reattach; only a fresh result constructs the
|
||||
transaction before releasing the subprocess's already-buffered early output. A reattach discards
|
||||
the intent without arming state. Cancellation, spawn failure, and teardown clear intent before any
|
||||
PTY id can be reused.
|
||||
|
||||
Local creation installs the transaction before subscribing to node-pty output. Relay `pty.spawn`
|
||||
carries the same fresh-session intent and installs it before releasing relay PTY output; relay
|
||||
`pty.attach` never accepts it. If any owner cannot establish this ordering, the early responder is
|
||||
not armed and normal query authority handles the query.
|
||||
|
||||
Increment `DAEMON_PROTOCOL_VERSION` for the new create/wire shape and add a named numeric-threshold
|
||||
predicate in the daemon adapter/router. Current exact-version hello behavior remains; supported
|
||||
legacy versions route through their existing adapters and fail the predicate. The SSH relay gets a
|
||||
separate versioned spawn/data capability because daemon protocol support says nothing about relay
|
||||
support.
|
||||
|
||||
An old daemon or relay keeps the legacy behavior and is never treated as having sanitized snapshots
|
||||
or history. Main must not apply a second best-effort scrub to legacy output. New sessions receive
|
||||
the invariant only after the owning daemon/relay is upgraded or restarted; an already-attached
|
||||
legacy session remains explicitly outside it.
|
||||
|
||||
### Composition with shell-ready preprocessing
|
||||
|
||||
The ingress sequence domain begins after the existing shell-ready scanner. That scanner may hold
|
||||
transport bytes and removes its private ready marker; marker bytes have never belonged to terminal
|
||||
model or delivery sequence space and continue not to count. Its released non-marker bytes enter the
|
||||
new ingress transaction in original order.
|
||||
|
||||
Snapshot and teardown barriers drain in pipeline order: the shell-ready scanner first releases its
|
||||
non-marker buffer, then the ingress transaction resolves or abandons its candidate, then the model,
|
||||
persistence, and views observe the resulting emissions. No later stage may introduce an unmetered
|
||||
string transform.
|
||||
|
||||
### Raw sequence and emission contract
|
||||
|
||||
The state machine accepts source chunks with an explicit raw half-open range and returns zero or
|
||||
more ordered emissions:
|
||||
|
||||
```ts
|
||||
type PtyIngressSourceChunk = {
|
||||
data: string
|
||||
rawStartSeq: number
|
||||
rawEndSeq: number
|
||||
}
|
||||
|
||||
type PtyIngressEmission = {
|
||||
data: string
|
||||
rawStartSeq: number
|
||||
rawEndSeq: number
|
||||
transformed: boolean
|
||||
}
|
||||
```
|
||||
|
||||
The raw range is the post-shell-ready ingress sequence domain and remains contiguous even when
|
||||
`data` is shorter after sanitization. The ordered emissions partition accepted source ranges without
|
||||
overlap. Producer flow-control acknowledgement follows those emitted raw spans and is counted once
|
||||
from `rawEndSeq - rawStartSeq`, never from emitted string length. A held prefix delays its ACK; the
|
||||
buffer is strictly bounded and the serialized queue cannot acknowledge later output ahead of it.
|
||||
|
||||
The ingress raw high-water advances when a source chunk is accepted. Model-applied and
|
||||
view-delivered high-waters advance only through ordered emissions, including empty transformed
|
||||
emissions that consume a raw range. Runtime/mobile listener metadata carries
|
||||
`rawLength = rawEndSeq - rawStartSeq`, not `data.length`. A restore that overlaps a transformed span
|
||||
cannot slice cleaned text by raw offset and must request a fresh authoritative snapshot, matching
|
||||
the existing `rawLength !== data.length` safety rule.
|
||||
|
||||
This metadata is end-to-end, not local to the state machine. Implementation changes the complete
|
||||
path:
|
||||
|
||||
1. daemon `Session` or relay `PtyHandler` emission callback;
|
||||
2. daemon/relay batching, coalescing, splitting, and wire notification;
|
||||
3. daemon adapter or `SshPtyProvider` decode;
|
||||
4. `OrcaRuntimeService` model and runtime/mobile listeners;
|
||||
5. main renderer batching, pending/drop accounting, and preload payload;
|
||||
6. renderer reconciliation and remote-runtime binary/live frame decoding.
|
||||
|
||||
The wire representation carries `data`, `seq = rawEndSeq`, `rawLength`, and `transformed`. A
|
||||
span-only emission has empty `data` but non-zero `rawLength`; no layer may drop it before advancing
|
||||
its high-water and producer ACK. It is not written to an emulator or xterm. Coalescing is permitted
|
||||
only for contiguous spans and sums raw lengths independently of string lengths. A transformed
|
||||
emission is indivisible because there is no byte-for-byte raw-to-clean offset; splitters must flush
|
||||
it as its own frame or request snapshot reconciliation instead of slicing it.
|
||||
|
||||
If a snapshot is requested while a partial candidate is held, the transaction first abandons that
|
||||
candidate and releases its bytes unchanged as an ordered emission. The authoritative emulator and
|
||||
snapshot sequence therefore describe the same raw high-water.
|
||||
|
||||
### Serialization and teardown
|
||||
|
||||
Each PTY has a non-reentrant serialized ingress queue. A provider write may synchronously produce a
|
||||
nested callback, but that callback is appended after the current source chunk rather than delivered
|
||||
ahead of its remaining bytes. Timeout releases and snapshot barriers enter the same queue.
|
||||
|
||||
On exit, the queue releases all buffered bytes, applies those emissions to the authoritative model
|
||||
and persistence, and fans them out before `onPtyExit`, `pty:exit`, or PTY state cleanup. Relay
|
||||
disposal must flush both ingress prefixes and its existing pending output batches before clearing
|
||||
them or killing PTYs, matching the natural-exit flush-before-`pty.exit` order. No drain may recreate
|
||||
state after teardown. Ordinary chunks pass through as one unchanged emission.
|
||||
|
||||
## Decision 2: Startup OSC Queries Are Consumed Authoritatively
|
||||
|
||||
The early OSC 10/11 responder remains because removing it would regress daemon-hosted agent startup
|
||||
and the agent's short color-query timeout. Its implementation moves into the source-owned ingress
|
||||
transaction.
|
||||
|
||||
When registered for an agent spawn, it:
|
||||
|
||||
1. recognizes exact OSC 10/11 query grammar across provider chunks;
|
||||
2. builds replies from validated renderer-pushed foreground/background attributes;
|
||||
3. emits the canonical ST-terminated, 16-bit-channel reply used by renderer/model query authority,
|
||||
regardless of whether the query ended with BEL or ST;
|
||||
4. records each reply transaction before writing it to the provider;
|
||||
5. consumes the answered query from the authoritative model and view emissions so neither the
|
||||
hidden model nor a delivered renderer can answer it a second time;
|
||||
6. begins echo recognition as soon as each individual reply is written.
|
||||
|
||||
If attributes or a provider are unavailable, native ConPTY consumes the query without replying;
|
||||
WSL and POSIX PTYs pass it through unchanged to normal query authority. A reattach never registers
|
||||
startup response state, matching current behavior, but native ConPTY ownership still prevents a
|
||||
downstream reply.
|
||||
|
||||
### Exact authority transfer
|
||||
|
||||
Startup query response authority opens only for a fresh session whose atomic creation installed the
|
||||
transaction before buffered output release. For WSL and POSIX PTYs it closes at the first of:
|
||||
|
||||
- both OSC 10 and OSC 11 slots have been answered;
|
||||
- the startup deadline expires;
|
||||
- main sends an ordered authority-close control after either the consuming-view handshake or the
|
||||
hidden-runtime ownership mark is established;
|
||||
- the spawn fails, is cancelled, reattaches, or exits.
|
||||
|
||||
Native ConPTY does not transfer OSC 10/11 authority at those boundaries: the deadline stops source
|
||||
replies, while complete queries remain consumed for the life of the PTY. Closing response authority
|
||||
does not discard already-written reply candidates. Echo recognition has
|
||||
its own bounded lifetime and may finish or drain after normal authority takes over. A close and a
|
||||
provider callback are ordered by the source owner's per-PTY ingress queue. Transport attachment to
|
||||
a daemon/relay client is not a consuming-view signal. Main sends the close over a versioned control
|
||||
method, and the source owner acknowledges the applied ingress sequence. Queries before that ordered
|
||||
boundary are either consumed at source or removed from emissions; queries after it pass unchanged
|
||||
to the normal delivered/hidden decision. Each query therefore belongs to exactly one authority.
|
||||
|
||||
The regular authority rules continue after the bounded startup window:
|
||||
|
||||
- delivered live bytes are answered by the live view;
|
||||
- hidden-dropped live bytes are answered by the runtime model;
|
||||
- replayed, seeded, and snapshot bytes are answered by nobody;
|
||||
- the daemon's persistence emulator never writes replies.
|
||||
|
||||
Implementation must amend `terminal-model-view-contract.md` and `terminal-query-authority.md` to
|
||||
name this source-owner startup authority, its opening/closing events, and its no-replay rule. It is a
|
||||
real third responder class, not an undocumented exception.
|
||||
|
||||
## Decision 3: Matched Echo Suppression Is Lossless and Pre-Model
|
||||
|
||||
Only native Windows ConPTY agent spawns that pass the deterministic provider harness enable a
|
||||
compatibility projection for replies written by the startup transaction. WSL and POSIX SSH PTYs do
|
||||
not. A remote-runtime PTY can enable it only on its owning Windows host under the same evidence and
|
||||
capability gate.
|
||||
|
||||
The harness records the exact projection ConPTY returns for the canonical ST reply, including its
|
||||
chunking and any console transformation. The implementation must not assume that the projection is
|
||||
always merely "remove ESC", and BEL or other reply forms are not added without separate evidence.
|
||||
For every written reply, the transaction records that exact expected projection. Recognition is:
|
||||
|
||||
- FIFO in reply-write order;
|
||||
- anchored at the next possible output position, not an unbounded substring search;
|
||||
- active immediately for each reply instead of waiting for both color slots;
|
||||
- bounded by the startup deadline and maximum reply length;
|
||||
- streaming across chunk boundaries.
|
||||
|
||||
If incoming bytes diverge from the expected projection, all buffered bytes are released unchanged
|
||||
and that candidate is abandoned. If the deadline expires or the PTY is cleared while a prefix is
|
||||
buffered, the prefix is released through the serialized ingestion queue; it is never discarded. A
|
||||
match advances the raw span but emits no bytes to the model, persistence, or views.
|
||||
|
||||
Projection matching cannot prove provenance. An application can print the same projected text at
|
||||
the candidate position, causing a false-positive removal while the later real echo remains visible.
|
||||
This is the central drawback of the workaround. It is accepted only if the real provider harness
|
||||
shows a stable, immediate projection inside the narrow registered-agent startup window; otherwise
|
||||
Orca disables the projection and keeps the visible output rather than risking deletion.
|
||||
|
||||
When the projection is enabled, the exact-collision behavior is explicit: the first identical
|
||||
anchored candidate is removed and a later real echo is allowed through. The test fixture must assert
|
||||
that result. This accepts a narrowly bounded false-positive risk instead of pretending provenance
|
||||
is knowable; the release gate must document the observed timing window and justify that tradeoff.
|
||||
Unknown, delayed, or interleaved transformations pass through visibly.
|
||||
|
||||
## Decision 4: Preserve ConPTY Focus Protocol
|
||||
|
||||
Orca must deliver the ConPTY bootstrap `?1004h`/`?9001h` to live terminal emulators unchanged. It
|
||||
must not remove, reorder, or fabricate transport bootstrap modes.
|
||||
|
||||
The `[I` investigation gets a deterministic harness before a behavior change. The harness must
|
||||
exercise the actual renderer focus callback and provider write path, not only inject `CSI I`
|
||||
directly into node-pty. It records:
|
||||
|
||||
- raw provider output and its order;
|
||||
- whether the focus report came from live ConPTY bootstrap state, an application-owned DECSET 1004,
|
||||
or replayed snapshot state;
|
||||
- the exact bytes written to the provider;
|
||||
- the exact bytes returned by the provider and stored in the model;
|
||||
- agent lifecycle state when the report was emitted.
|
||||
|
||||
The implementation gate is strict:
|
||||
|
||||
- If stale snapshot modes cause the report, fix snapshot rehydration. Transport bootstrap focus mode
|
||||
is not persisted as application ownership.
|
||||
- If a live agent receives transport focus before it owns terminal focus reporting, record that
|
||||
evidence without shipping a suppression heuristic from this document.
|
||||
- If provider input/output transformation corrupts a correctly owned focus report, fix or sanitize
|
||||
that transformation at the same pre-model ingress boundary used for OSC replies.
|
||||
|
||||
No global `?1004h` filter ships under any outcome.
|
||||
|
||||
If the harness proves a focus-ownership race, a follow-up design is required before implementation.
|
||||
That design must define the output-to-input ownership signal, distinguish xterm focus events from
|
||||
identical typed/pasted/programmatic bytes, specify startup transitions and deadlines, define any
|
||||
snapshot/wire metadata, and cover the separate explicit reattach-focus write path. This document
|
||||
does not pre-approve an ownership state machine whose input provenance cannot yet be represented.
|
||||
|
||||
## Snapshot and Replay Rules
|
||||
|
||||
Interactive modes in a snapshot are capabilities of the live application, not proof that a new
|
||||
view should emit input immediately.
|
||||
|
||||
- Cold restore into a fresh shell keeps the existing full mode reset.
|
||||
- Reattach to a live agent may rehydrate application-owned focus mode, but never transport-only
|
||||
bootstrap ownership.
|
||||
- Snapshot serialization/replay must not mutate live ownership trackers.
|
||||
- A snapshot containing an OSC query or an old Orca reply never produces a provider write.
|
||||
- Model and renderer snapshots must both be free of matched cooked reply projections.
|
||||
|
||||
Any future focus ownership metadata must be explicit; it cannot be inferred from serialized
|
||||
`?1004h` text.
|
||||
|
||||
## Failure Policy
|
||||
|
||||
Safety is asymmetric:
|
||||
|
||||
- This design does not intentionally suppress a focus notification; evidence of a focus-ownership
|
||||
race triggers a follow-up design instead.
|
||||
- Passing through an unrecognized OSC echo is safer than deleting output that may belong to the
|
||||
application.
|
||||
- Missing a startup color reply falls back to the existing renderer/model authority. Duplicate
|
||||
replies are forbidden.
|
||||
- Losing buffered output on timeout or teardown is forbidden.
|
||||
|
||||
## Cross-Platform and Remote Scope
|
||||
|
||||
- Native Windows local and daemon ConPTY: startup response plus evidence-gated echo compatibility
|
||||
path; focus investigation only until a proven root cause has its own complete design.
|
||||
- WSL: normal Linux terminal semantics; no ConPTY echo or focus workaround.
|
||||
- SSH: the same ingress/query ownership ordering, but no native Windows echo projection unless the
|
||||
remote host protocol later supplies explicit equivalent evidence.
|
||||
- Remote runtime: the remote Orca host owns ingestion and must implement the same contract there;
|
||||
desktop local main does not reinterpret its stream.
|
||||
- Mobile/web views: consume the sanitized authoritative model stream and retain exactly-one query
|
||||
response authority through the existing terminal-driver election.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- A query or echo split at any byte boundary, including OSC ST split across chunks.
|
||||
- The first reply echo arriving before the second color query.
|
||||
- Unrelated output, an exact application-text collision, or a partial match before the real echo.
|
||||
- Timeout, snapshot, detach, process exit, daemon shutdown, or relay disposal while bytes are held.
|
||||
- A provider write causing a synchronous nested output callback.
|
||||
- Fresh spawn versus reattach, cancellation, PTY-id reuse, and an authority-close control racing
|
||||
with output.
|
||||
- BEL-terminated queries still receiving the canonical ST reply.
|
||||
- Empty transformed spans crossing coalescing, splitting, ACK, mobile, and remote-runtime layers.
|
||||
- Old daemon/relay protocol versions and sessions that survive an application upgrade.
|
||||
- WSL or POSIX SSH running from a Windows desktop without inheriting local ConPTY workarounds.
|
||||
- Focus gained through normal terminal input versus the separate explicit reattach-focus write path.
|
||||
|
||||
## Test Plan
|
||||
|
||||
### Deterministic provider harness
|
||||
|
||||
- Capture the native ConPTY bootstrap across natural and forced chunk boundaries.
|
||||
- Reproduce the OSC reply echo with the real provider and an agent query fixture.
|
||||
- Exercise BEL and ST queries and assert the same canonical ST reply, plus separate OSC 10/11
|
||||
queries and combined OSC 10 `?;?`.
|
||||
- Force the first reply echo before the second query.
|
||||
- Split every byte boundary in query and echo fixtures.
|
||||
- Print the expected projection immediately before the real echo and assert that the first
|
||||
identical candidate is removed while the later echo passes through.
|
||||
- Exercise focus gain/loss through the actual xterm focus path.
|
||||
|
||||
### Ingress integration
|
||||
|
||||
- Assert local runtime ingestion and daemon emulator/pending/checkpoint persistence receive
|
||||
classified data before storing it.
|
||||
- Assert renderer and mobile delivery receive the same visible output.
|
||||
- Assert raw start/end spans advance by original provider length, producer ACK contribution is
|
||||
counted exactly once, and mobile/runtime metadata reports the raw span rather than string length.
|
||||
- Assert a partial candidate is released unchanged on mismatch, timeout, snapshot barrier, move,
|
||||
and teardown, including a prefix held from an earlier callback.
|
||||
- Assert re-entrant provider callbacks remain ordered behind the source chunk that caused the
|
||||
write.
|
||||
- Assert restore overlap across a transformed or delayed span requests a fresh snapshot rather
|
||||
than slicing cleaned text.
|
||||
- Assert `LocalPtyProvider`, daemon `Session`, and relay `PtyHandler` install the source-side seam;
|
||||
assert `SshPtyProvider` does not reinterpret relay data.
|
||||
- Assert WSL, SSH, and remote-runtime streams do not enable the native-Windows projection.
|
||||
- Assert a capable daemon sanitizes live output, snapshots, pending records, checkpoints, and cold
|
||||
restore; assert capable relay replay/history has the same property. Assert old daemon and relay
|
||||
versions are detected and never represented as sanitized.
|
||||
|
||||
### Authority and restore
|
||||
|
||||
- Assert an early-consumed query is answered once by its source owner and never by renderer or
|
||||
hidden model.
|
||||
- Assert normal delivered/dropped query authority resumes after startup state clears.
|
||||
- Assert the main snapshot, renderer snapshot, hidden reveal, reconnect, and mobile subscription do
|
||||
not contain cooked OSC text.
|
||||
- Assert replay never sends OSC or focus replies.
|
||||
- Assert ordinary native console focus behavior remains enabled.
|
||||
- Assert the focus harness captures both terminal `onData` and explicit reattach-focus writes. Any
|
||||
later ownership implementation defines its tests in the required follow-up design.
|
||||
|
||||
### End-to-end acceptance
|
||||
|
||||
On native Windows, repeatedly create, hide, reveal, and reconnect new and resumed agent sessions.
|
||||
Before typing, neither live output nor any restore path may contain `]10;rgb`/`]11;rgb`. Repeat the
|
||||
focus/blur scenarios to classify `[I`; if it reproduces through an ownership race, this work stops
|
||||
at the follow-up-design gate rather than claiming the symptom fixed. Application-owned focus
|
||||
behavior must still move the TUI caret correctly after focus and reattach. Repeat with a plain
|
||||
PowerShell terminal and a native focus-event consumer to prove no global regression.
|
||||
|
||||
Run renderer and main PTY suites, runtime snapshot/query suites, node/web typechecks, lint,
|
||||
formatting, max-lines ratchet, reliability gates, and Electron validation. SSH ingestion changes also
|
||||
require the repository's SSH end-to-end procedure.
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
This is not a layout, styling, or copy change. Existing terminal rendering and focus behavior must
|
||||
look unchanged except that matched protocol garbage is absent. A passing terminal screenshot has a
|
||||
clean prompt, no clipped or duplicated startup output, no restore flash, and the existing cursor and
|
||||
focus presentation.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
1. A fresh native-Windows agent prompt after startup, with no OSC reply text.
|
||||
2. The same session after hide/reveal restore, still clean and without duplicated output.
|
||||
3. The session after focus, blur, and reconnect, showing the focus-harness outcome and prompt state.
|
||||
4. A plain native PowerShell terminal after focus/blur, showing unchanged adjacent behavior.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. **Correct seam and rollback.** Remove the prototype filters. Add the shared serialized ingress
|
||||
state machine, explicit raw-span emissions, and separate ACK accounting after shell-ready
|
||||
preprocessing. Install pass-through mode in `LocalPtyProvider`, daemon `Session`, and relay
|
||||
`PtyHandler` before their models, persistence/replay, and fanout.
|
||||
2. **Protocol and authority contract.** Bump the daemon protocol, add relay capability/version gates,
|
||||
carry atomic fresh-spawn intent, define legacy fallback, and amend the canonical model/query
|
||||
authority documents with exact transfer events.
|
||||
3. **Startup transaction.** Move OSC startup recognition/reply into source ingress, retain canonical
|
||||
ST replies, consume answered queries for model and views, and retain raw sequence accounting.
|
||||
4. **Windows compatibility projection.** Gate the measured projection on provider evidence; add FIFO
|
||||
anchored recognition, serialized re-entrant delivery, lossless drains, false-positive coverage,
|
||||
and authoritative daemon/model/snapshot tests.
|
||||
5. **Focus evidence.** Land the real focus-path harness. If it proves a focus-ownership race, stop
|
||||
for the required follow-up design; a direct snapshot or provider-transformation bug may be fixed
|
||||
only with a failing regression test that selects that branch.
|
||||
6. **Electron and SSH gates.** Validate visible, hidden, restored, mobile-owned, native console, WSL,
|
||||
and SSH scenarios before removing the old startup implementation.
|
||||
|
||||
Each slice must keep query authority singular. The compatibility projection does not ship without a
|
||||
model-snapshot assertion, and no focus behavior change ships before the deterministic focus harness
|
||||
fails on the old behavior and passes on the new behavior.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: limited to the proven OSC startup corruption plus deterministic focus evidence. Global
|
||||
focus filtering and an unproven ownership state machine remain out of scope.
|
||||
- Architecture/data flow: classification belongs at each PTY source owner after shell-ready
|
||||
preprocessing and before every authoritative model, persistence, replay, or delivery consumer.
|
||||
- Failure modes covered: partial/mismatched projections, false-positive collision, nested writes,
|
||||
authority races, snapshot and teardown drains, protocol-version skew, reattach, and host
|
||||
isolation.
|
||||
- Test coverage required: byte-boundary unit tests for the shared transaction; local, daemon, relay,
|
||||
runtime/mobile, restore, and legacy-protocol integration tests; real native-Windows provider and
|
||||
renderer-focus harnesses; Electron and SSH end-to-end validation.
|
||||
- Performance/blast radius: ordinary output is a pass-through emission. Buffering is bounded by one
|
||||
startup reply candidate and its deadline. Protocol and sequence metadata touch every delivery
|
||||
path, so existing high-throughput, ACK, hidden-drop, and reconnect tests are mandatory.
|
||||
- UI quality bar: terminal layout and styling are unchanged; only matched startup garbage
|
||||
disappears, without cursor/focus regressions or restore flashes.
|
||||
- Required review screenshots: the four terminal states in `Review Screenshots`.
|
||||
- Residual risks: the native projection may be too unstable to enable; exact projected application
|
||||
output can collide; `[I` may require a separately reviewed focus-ownership design.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Replacing xterm's general query parser.
|
||||
- Filtering arbitrary escape-looking terminal output.
|
||||
- Disabling ConPTY focus or Win32 input mode globally.
|
||||
- Changing WSL, SSH, or remote-runtime terminal semantics to imitate local Windows.
|
||||
- Solving unrelated MCP startup warnings reported beside the terminal garbage.
|
||||
|
||||
## Final Invariants
|
||||
|
||||
1. Provider bytes are classified once before model ingestion and view delivery.
|
||||
2. A live query has exactly one responder; replay has none.
|
||||
3. Source-owner persistence, runtime/model state, and every view agree on removal of a matched
|
||||
startup-reply projection.
|
||||
4. Raw provider sequence accounting survives sanitization.
|
||||
5. Buffered unmatched output is always released; the sanitizer cannot silently lose user data.
|
||||
6. ConPTY bootstrap modes reach live emulators unchanged.
|
||||
7. No focus suppression ships from this design; a proven ownership race requires a follow-up design.
|
||||
8. PTY teardown clears all startup-transaction buffers and focus-harness measurement state.
|
||||
@@ -1,620 +0,0 @@
|
||||
# Windows daemon-generation safety investigation (#9749)
|
||||
|
||||
Investigation and completion snapshot: 2026-07-21 16:59 PDT
|
||||
(2026-07-21 23:59 UTC)
|
||||
|
||||
Branch baseline: `OrcaWin/issue-9749-windows-daemon-generation-safety` at
|
||||
`937a2015e`, 40 commits after `v1.4.148-rc.1`. This document is the hard gate
|
||||
before a reproduction harness or production change. GitHub access during the
|
||||
investigation was read-only, and no installed Orca daemon, pipe, token, process,
|
||||
or terminal session was contacted or changed.
|
||||
|
||||
## Findings
|
||||
|
||||
The reported incident is a composition of three lifecycle paths, not one:
|
||||
|
||||
1. **Survival and adoption:** normal app quit deliberately disconnects from
|
||||
daemon clients without shutting down their PTYs. Protocol-specific named
|
||||
pipes let multiple generations coexist, and legacy adapters intentionally
|
||||
reconnect to them so live PTYs remain warm and reattachable across upgrades.
|
||||
2. **Broad current-generation replacement:**
|
||||
`cleanupDaemonForProtocol` sends the only production
|
||||
`shutdown { killSessions: true }` request found in the repository. Its
|
||||
production callers replace or explicitly restart the current generation;
|
||||
legacy discovery does not call it. A failed `listSessions` is currently
|
||||
converted to an empty list before this broad shutdown, which makes its
|
||||
reported kill count untrustworthy but does not suppress the shutdown.
|
||||
3. **Reconnect-triggered per-session destruction:** #8871 provides the strongest
|
||||
causal evidence. A reconnecting renderer restores stale remote handles,
|
||||
synthesizes `pty-exit`, drops that reason at `session.tabs.close`, and the
|
||||
authoritative host interprets the close as user intent. Its PTY router then
|
||||
forwards individual `kill` requests to whichever current or legacy adapter
|
||||
claimed each reusable session ID during discovery.
|
||||
|
||||
`client-hello` is necessary to discover and route legacy sessions, but neither
|
||||
the hello handler nor legacy discovery sends a kill or shutdown request. The
|
||||
~3.3-second renderer-bootstrap-to-kill evidence in #8871, repeated renderer
|
||||
spawn/burst correlations, and the untyped close path are substantially stronger
|
||||
than #9749's inference that greeting an old pipe causes that daemon to kill its
|
||||
table autonomously.
|
||||
|
||||
The immediate safety boundary is therefore destructive request authority and
|
||||
provenance. Cross-profile, sleeping-session, and generation-retirement policy
|
||||
remains the larger #9138/#9229 problem.
|
||||
|
||||
## Deterministic native-Windows reproduction
|
||||
|
||||
Reproduction snapshot: 2026-07-21 14:36 PDT (2026-07-21 21:36 UTC).
|
||||
|
||||
`tests/e2e/daemon-generation-reconnect-safety.spec.ts` now constructs an
|
||||
isolated `orca-9749-dg-*` runtime under the Windows temporary directory. It
|
||||
starts three real daemon-server processes on versioned v21/v22/v23 named
|
||||
pipes, with a live canary and a stale-mirror canary in each generation. Each
|
||||
canary records the PTY-root and descendant PID/start identity independently.
|
||||
The fixture refuses cleanup outside its exact temporary root and terminates
|
||||
only recorded fixture process incarnations; it never enumerates or connects to
|
||||
installed Orca endpoints.
|
||||
|
||||
The Electron-as-Node reconnect client performs three production
|
||||
`DaemonPtyAdapter`/`DaemonPtyRouter.discoverLegacySessions` bursts, reattaches
|
||||
every original PID, pings every canary, and opens a simultaneous second client
|
||||
to each generation. It then sends duplicate `session.tabs.close` RPCs carrying
|
||||
`reason: 'pty-exit'` through the real schema, `OrcaRuntimeService`, and routed
|
||||
daemon adapters while the reconnect-client process remains alive.
|
||||
|
||||
The current-main run failed at the intended external invariant:
|
||||
|
||||
- before the close, all three daemons, six PTY roots, and six descendants were
|
||||
alive;
|
||||
- each daemon accepted eight new control/stream hellos across the reconnect and
|
||||
parallel-client cycles;
|
||||
- v21, v22, and v23 each logged two `session-killed` requests for the same
|
||||
stale-mirror session ID within 1–4 ms;
|
||||
- all three stale-mirror PTY roots and descendants exited, while all three
|
||||
unrelated live canaries, all daemon processes, and reconnect client PID 26876
|
||||
remained alive;
|
||||
- the final assertion requires those stale-mirror roots to remain alive, so it
|
||||
is RED before the fix and will become GREEN only when lifecycle-originated
|
||||
closes are adjudicated non-destructively at the host.
|
||||
|
||||
Focused command:
|
||||
|
||||
```text
|
||||
pnpm exec playwright test tests/e2e/daemon-generation-reconnect-safety.spec.ts --config tests/playwright.config.ts --project electron-headless --workers=1
|
||||
```
|
||||
|
||||
The captured per-generation timestamp/PID/hello/kill/liveness report is written
|
||||
to the Playwright test output as `daemon-generation-reconnect-events.json`.
|
||||
|
||||
## Release and protocol chronology
|
||||
|
||||
| Release or branch | Date | Daemon protocol | Relevant lifecycle behavior |
|
||||
| --------------------- | ---------- | --------------: | -------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `v1.4.141` | 2026-07-14 | 21 | Legacy adoption already intentional; #8871 observed here. |
|
||||
| `v1.4.142` | 2026-07-15 | 22 | New versioned endpoint; v21 can remain reattachable. |
|
||||
| `v1.4.143` | 2026-07-16 | 22 | #9138 macOS accumulation reported. |
|
||||
| `v1.4.144` | 2026-07-17 | 22 | #9195 Windows survival reported. |
|
||||
| `v1.4.145` | 2026-07-18 | 22 | No generation-retirement change. |
|
||||
| `v1.4.146` | 2026-07-19 | 23 | #9749's old current generation; already contains #8661's continue-shutdown-on-dispose-failure behavior. |
|
||||
| `v1.4.147` | 2026-07-20 | 24 | First stable release containing #9277: authenticated identity and atomic empty-daemon retirement. |
|
||||
| `v1.4.148` | 2026-07-21 | 24 | Reporter current release; legacy v23 and older remain intentionally adoptable. |
|
||||
| `main` at `937a2015e` | 2026-07-21 | 25 | Protocol bumped by #9651 (`cc44acaaa`) for PTY startup ingress; v24 is now legacy. No stable tag contains this commit yet. |
|
||||
|
||||
`PREVIOUS_DAEMON_PROTOCOL_VERSIONS` is cumulative rather than one-version-only.
|
||||
At the investigated `main`, it contains versions 1 through 24.
|
||||
|
||||
## Investigation matrix
|
||||
|
||||
Confidence is **proven** when the issue evidence and source/diff establish the
|
||||
mechanism, **supported** when multiple observations fit a reachable source path,
|
||||
and **suspected** where attribution is missing.
|
||||
|
||||
| Item | State; dates; releases/protocols | Exact symptom | Mechanism and relevant code/commits | Shipped status; unresolved #9749 relevance; scope boundary |
|
||||
| --------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| [#9749](https://github.com/stablyai/orca/issues/9749) | Open; 2026-07-21; Windows 11; daemon-host 1.4.146→1.4.148; old v21/v22/v23 and current v24 observed | Three surviving daemons were greeted at `16:41:32.277Z`–`.286Z`; later bursts logged 55/30/65/60/60 v22 kills and 10/32 v23 kills, including repeated IDs, while 191,266 main-process spans showed no coincident app death. One v23 broad `shutdown reason:rpc killSessions:true` and repeated `shutdown-dispose-failed` were present. | **Supported composition, reporter causality not proven.** Versioned legacy adoption explains hellos; `cleanupDaemonForProtocol` explains broad shutdown; #8871's stale-mirror close echo best explains reconnect-time individual kills. `daemon-server.ts` logs `session-killed` before awaiting `host.kill`, so repeated records prove repeated requests, not repeated physical death. | No fix shipped for the destructive initiator. #9277 mitigates empty v24+ accumulation only. Skipping all legacy hello or killing legacy generations on sight would destroy the promised warm-reattach behavior and is unsafe scope creep. |
|
||||
| [#9138](https://github.com/stablyai/orca/issues/9138) | Open; 2026-07-17; macOS 1.4.143/v22; observed v18/v20/v21/v22 | UI showed 8 sessions while about 46 Claude processes remained; removing stale trees removed about 370 processes and reduced swap from 25 GB to under 5 GB. | **Proven accumulation, ownership policy deliberately conservative.** Normal disconnect, versioned endpoints, incomplete cross-profile ownership, sleeping/cold restore, and legacy wildcard claims prevent safe blind retirement. Prototype commit `7c915909b` implements an audit/journal/incarnation design but is unmerged. | No complete fix shipped. #9277 safely handles only empty current-generation v24+ daemons. The broader ownership journal, grace period, all-profile evidence, and enforcement rollout belong here, not the immediate #9749 close-authority patch. |
|
||||
| [#9211](https://github.com/stablyai/orca/issues/9211) | Closed duplicate 2026-07-17; v21/v22 | A v21 daemon remained four days beside v22, and each app launch greeted both. | **Proven intentional legacy discovery with missing retirement.** `createLegacyDaemonAdapters` plus `discoverLegacySessions`. | Consolidated into #9138; no separate shipped fix. Same accumulation input as #9749, but not its destructive initiator. |
|
||||
| [#9229](https://github.com/stablyai/orca/issues/9229) | Open P1; 2026-07-17; Linux headless | Failed shutdown left a 15.55 GiB/81-process old runtime beside a 1.21 GiB/4-process replacement. | **Supported reconciliation design.** Requires provenance, one destructive authority, exact daemon/session PID+start incarnations, complete evidence, and fail-closed missing reads. | Unshipped. Supplies invariants for later reconciliation. Implementing its full profile migration and journal in #9749 would be unsafe scope expansion. |
|
||||
| [#9195](https://github.com/stablyai/orca/issues/9195) | Open; 2026-07-17; Windows 1.4.144/v22; comments through #9277 release read | `orca-terminal-daemon.exe` remains after app exit; later comments observed v21/v22/v23 and invisible sessions. | **Proven intentional for non-empty daemons.** Normal quit calls `disconnectDaemon`, not `shutdownDaemon`; the child is detached/unref'd. Empty accumulation was an unhandled gap before #9277. | #9277 shipped in 1.4.147 for empty v24+ only. Treating every survivor as a bug would regress warm reattachment. |
|
||||
| [PR #9277](https://github.com/stablyai/orca/pull/9277) | Merged 2026-07-20 as `7adda25b0`; first stable `v1.4.147`; v23→v24 | Empty current-generation daemons accumulated after clean app disconnect or failed adoption. | **Proven by diff/tests.** Hello returns PID/start-time/launch-nonce identity; control/stream identity must match. `shutdownIfIdle` atomically checks one complete client, no unknown transport, no sessions, and no admission in flight. Shutdown fences admission before disposal. A two-minute watchdog covers only never-adopted startup. | Shipped in `v1.4.147-rc.4`, `v1.4.147`, `v1.4.148-rc.1`, and `v1.4.148`. It explicitly does not perform startup reaping, retire legacy daemons, infer ownership, or kill reattachable PTYs. Strong identity/capability foundation; partial mitigation only. |
|
||||
| [#8871](https://github.com/stablyai/orca/issues/8871) | Open P0; 2026-07-15; first observed 1.4.141/v21; all corrections/comments read | First reconnect kill followed renderer bootstrap by 3.348 s. Three later fresh renderer processes correlated within about 1 s with bursts killing 4, 7, and 7 worktrees while app and daemon PIDs remained stable. | **Supported-to-proven request path.** Persisted remote handle → subscribe returns `no_connected_pty` → synthetic `pty-exit` → `closeTerminalTab(reason:'pty-exit')` → reason dropped from `session.tabs.close` → `closeMobileSessionTab` kills host PTY. Early pre-connect kills were correctly downgraded to unattributed. Close propagation intersects landed #8628 and later #8958. | Not fixed on main. This is the strongest immediate #9749 foundation. Trigger repair alone is insufficient; the authoritative host must adjudicate intent. |
|
||||
| [PR #8872](https://github.com/stablyai/orca/pull/8872) | Open; 2026-07-15; head `bb69fac775`; rebased 2026-07-21 | Prevents mirror `pty-exit`/cleanup evidence from killing a host PTY while retaining real user close and dead-tab retirement. | **Actual diff/tests inspected.** Threads typed `user`/`pty-exit`/`cleanup`; host refuses non-user closes if any parent leaf has a connected PTY, republishes an unchanged snapshot with a guarded replay marker, and handles dead-leaf/live-sibling loops. Adds an optional daemon `kill intent:'auto'` guard, but intentionally sends no auto intent until protocol/capability negotiation exists. | Unshipped. The earlier Windows/WSL live matrix passed on an older head and was explicitly invalidated by the rebase, so native validation must be rerun. This is the best narrow safety foundation, but reasonless old clients remain destructive on a new host. |
|
||||
| [PR #8888](https://github.com/stablyai/orca/pull/8888) | Open; 2026-07-15; head `b13235211`; reviews/follow-ups read | Ambiguous paired-runtime close RPCs could destroy host tabs with no requester attribution. | **Actual diff/tests inspected.** Default-denies intent-less paired-runtime `session.tabs.close`, `terminal.close`, and `terminal.closeTab`; validates user source/target, dedupes request IDs per device across reconnects, rate-limits, restricts create rollback to its connection, and traces device/connection/source/decision without bearer tokens. Adds local daemon-control client ID to `session-killed`. | Unshipped. Useful defense-in-depth and logging foundation. Its “old paired client gets successful no-op” behavior is safely conservative but needs explicit compatibility/product acceptance; taking the entire policy is broader than the smallest #9749 fix. |
|
||||
| [#9414](https://github.com/stablyai/orca/issues/9414) | Open tracking issue; 2026-07-19 | Recognition-dependent terminal lifecycle actions can destroy or strand arbitrary processes. | **Proven design boundary.** Host owns adjudication; stale client transport state and agent-name recognition are not kill authority. Tracks #8872/#8888 and lifecycle-state work. | Unshipped tracker. Aligns with #9749 invariants; generic agent recognition work is separate scope. |
|
||||
| [PR #8628](https://github.com/stablyai/orca/pull/8628) | Merged 2026-07-14 as `36cd8a334`; releases after that date | Tab close did not durably retire all associated terminal/session state. | **Actual merge diff inspected.** Centralized terminal retirement/ownership and ensured remote-owned closes reach the authoritative host. The remote call still carried no close reason, so lifecycle and user closes were indistinguishable. | Shipped and important context, not a regression to revert wholesale. #9749 must preserve its durable explicit-user close while adding authority. |
|
||||
| [#8878](https://github.com/stablyai/orca/issues/8878) / [PR #9098](https://github.com/stablyai/orca/pull/9098) | Issue and PR open; 2026-07-15/17; PR head `9f3abd778` | A reconnecting paired client resumes a provider session still live on the host, producing duplicate TUIs. | **Proven companion feedback loop.** Client-local resume runs before authoritative mirror arrival; a #8871 kill also leaves a resume record. PR gates resume for runtime-owned worktrees while preserving the record. | Unshipped. Relevant reconnect stress case, but provider-session resume dedupe is not needed to stop #9749 kills. |
|
||||
| [#9352](https://github.com/stablyai/orca/issues/9352) / [#9585](https://github.com/stablyai/orca/issues/9585) | Open; 2026-07-18/20; remote macOS and Windows | Closed or killed remote tabs return as `ptyId:null` phantoms; host snapshots keep dead terminal surfaces, and repeated host restarts accumulate them. | **Proven stale mirror/snapshot state.** Host `touchMobileSessionSnapshotsForPty` republishes the same tab; viewer mirrors every terminal surface. Remote transport also leaks the explicit-kill error. | Unshipped. Explains repeated stale close inputs and must be in stress coverage, but pruning dead surfaces is a separate lifecycle fix requiring sleeping-session care. |
|
||||
| [#9217](https://github.com/stablyai/orca/issues/9217) / [#8970](https://github.com/stablyai/orca/issues/8970) | #9217 closed duplicate 2026-07-19; #8970 open; v1.4.143 | Agent/sidebar rows remain after local close or SSH relay connection loss. | **Proven UI/status lifecycle gaps.** SSH teardown intentionally preserves PTY ownership for reattach but omitted status clearing; renderer lacks a sweep. | Separate non-destructive roster cleanup. Combining sidebar cleanup with #9749 would be scope creep. |
|
||||
| [#8851](https://github.com/stablyai/orca/issues/8851) / [PR #8825](https://github.com/stablyai/orca/pull/8825) | Issue closed; PR merged 2026-07-15 as `c8986ca52`; 1.4.143 notes | Finished named Claude children remained as idle sidebar rows. | **Proven Claude roster mechanism, not PTY lifecycle.** Working-only roster and hydration cleanup. | Shipped, but #8970 proves top-level/session residuals. Unrelated to destructive daemon authority. |
|
||||
| [#8275](https://github.com/stablyai/orca/issues/8275) / [#8276](https://github.com/stablyai/orca/issues/8276) | #8275 open `cannot_repro`; #8276 closed duplicate; 2026-07-11; v20→v22 attempts | Rapid worktree removal was followed by daemon death and unrelated split panes exiting `-1`; no shutdown record. | **Different mechanism.** Shared daemon process dies during PTY teardown; current v22 attempt did not reproduce. | Not the #9749 initiator: #9749 daemons stay alive and log explicit shutdown/kill requests. Keep daemon-death regression coverage, but do not merge root causes. |
|
||||
| [PR #8140](https://github.com/stablyai/orca/pull/8140) | Merged 2026-07-10 as `03a673708`/PR head `1710325e0`; fixes #8048 | Graceful then immediate Windows PTY teardown double-closed the same ConPTY handle and killed the shared daemon. | **Proven by actual native harness/diff.** `nodePtyKillIssued` makes later Windows force a no-op. Harness uses unique pipe/temp state, 25 victims, and a witness PTY/daemon survival assertion. | Shipped. Prevents one daemon-death path; does not authorize reconnect closes and does not retire descendants. Reuse its isolation/witness patterns only. |
|
||||
| [PR #8284](https://github.com/stablyai/orca/pull/8284) | Closed unmerged 2026-07-16; head `ebe0b6523` | Proposed serial worktree PTY admission and verified fail-closed teardown across Windows/POSIX/SSH. | **Actual 50-file diff/tests inspected.** Retained shutdown ownership, admission fences, physical-exit proof, and Windows relay ConPTY ownership. | Contrary to the issue prompt, it did **not** merge. Landed work was split/superseded by #8661 and #8706. Its teardown patterns are useful, but adopting its broad branch is unsafe. |
|
||||
| [PR #8661](https://github.com/stablyai/orca/pull/8661) | Merged before 1.4.146; key commit `a635ff9a7` | Disposal failure could prevent orderly runtime/daemon termination. | **Proven current source behavior.** Shutdown RPC catches `host.dispose`, logs `shutdown-dispose-failed`, then continues fencing, client destruction, and server close; resource disposal is retried. | Shipped before #9749. Corrects the report's inference that the failure necessarily leaves the endpoint authoritative forever. A native handle may still keep a process alive, but the server intends to close. |
|
||||
| [#9045](https://github.com/stablyai/orca/issues/9045) | Open; 2026-07-16; Windows | Worktree deletion fails because agent descendants retain filesystem handles after PTY teardown. | **Supported descendant ownership gap.** Root PTY exit is not full tree exit on Windows. | Unresolved. It concerns cleanup after a legitimate kill, not who may initiate it. |
|
||||
| [#9704](https://github.com/stablyai/orca/issues/9704) | Open; 2026-07-21; Windows 1.4.147/v24 | Killed PTY descendants survive (six trees/18 processes/~1.1 GB, later ~2 GB); runtime lists dead sessions as connected. | **Proven descendant leakage plus stale registry.** Explicitly asks for initiator attribution rather than assuming the kill was valid. | Unresolved. Different from #9749 because the root session was killed; #9704 concerns what survives afterward. |
|
||||
| [PR #9752](https://github.com/stablyai/orca/pull/9752) | Open; 2026-07-21; head `6be947317` | Windows agent descendants survive explicit or natural PTY-root exit. | **Actual native patch and tests inspected.** Suspends recognized native-Windows agent ConPTY roots, creates/configures/assigns a kill-on-close Job Object before resume, owns the handle atomically, and falls back to direct-root termination. Plain terminals, WSL, POSIX, SSH relay, and unrelated sessions are excluded; Windows process-table commands are removed. | Unshipped. Correct post-authorization cleanup, explicitly not an initiator fix. Combining it into the #9749 authority patch would obscure causality; compose/test separately if it lands first. |
|
||||
| [PR #9266](https://github.com/stablyai/orca/pull/9266) / [PR #9612](https://github.com/stablyai/orca/pull/9612) | Both open; 2026-07-18/20 | Alternative Windows descendant tree termination using process enumeration/taskkill-style sweeps. | **Competing cleanup approaches.** Carry PID-reuse, access-denied, cost, and partial-tree risks that native Job ownership avoids. | Unshipped. Do not duplicate inside #9749. |
|
||||
| [PR #8706](https://github.com/stablyai/orca/pull/8706) | Merged 2026-07-15 as `40d015992`/merge `6dbeeda3e`; stable thereafter | POSIX agent descendants survived root teardown. | **Proven POSIX snapshot-before-root-kill.** Windows intentionally returns no snapshot. | Shipped for macOS/Linux only. No #9749 authority effect. |
|
||||
| [#9193](https://github.com/stablyai/orca/issues/9193) / [PR #9288](https://github.com/stablyai/orca/pull/9288) | Both open; 2026-07-17/18 | `terminal close --tab` cannot address live floating/tabless PTYs; pane close can kill, and Windows may retain a stale entry. | **Proven addressing/registry gap.** PR routes tabless PTY through existing pane close. | Unshipped. Diagnostic and stale-registry relevance only; making more sessions closeable is not authority fencing. |
|
||||
| [#9563](https://github.com/stablyai/orca/issues/9563) / [PR #9634](https://github.com/stablyai/orca/pull/9634) | Both open; 2026-07-20/21; headless macOS | LaunchAgent host invokes update, disconnects clients, old binary respawns, and ShipIt reports “App Still Running.” | **Supported updater/headless ownership race.** PR defers installation while serving headlessly. | Unshipped. Must be a relaunch scenario in the harness, but updater policy is separate from close authority. |
|
||||
| [#8261](https://github.com/stablyai/orca/issues/8261) | Open; 2026-07-11; macOS/Linux headless comments | Silent update installation kills active PTYs; one headless log has `shutdown reason:rpc killSessions:true`. | **Supported broad shutdown during update.** | Unresolved adjacent caller/lifecycle context. Updater UX and install policy are scope creep; broad shutdown attribution is relevant. |
|
||||
| [#8459](https://github.com/stablyai/orca/issues/8459) | Open; 2026-07-13 | Resource Manager labels live daemon sessions orphan from renderer-only evidence and bulk-kills them. | **Proven ownership-safety precedent.** Absence from one renderer is not authority. | Unshipped. Same invariant as #9749, different UI initiator. Do not couple UI resource-manager redesign. |
|
||||
| [#8585](https://github.com/stablyai/orca/issues/8585) | Open; 2026-07-13; SSH relay | Failed relay `--connect` unlinks a socket while the old relay and PTYs remain alive. | **Different namespace/transport ownership leak.** | Unresolved. SSH regression consideration, not a native daemon-generation fix. |
|
||||
| [#7783](https://github.com/stablyai/orca/issues/7783) | Open; 2026-07-08; macOS | Helper survives app quit with roughly 189 descendants. | **Supported historical survival/descendant leak.** | Unresolved adjacent accumulation evidence; no reconnect-kill attribution. |
|
||||
| [#8457](https://github.com/stablyai/orca/issues/8457) | Open; 2026-07-13 | Headless serve and GUI relaunch ownership collide, interrupting or duplicating live agents. | **Supported multi-owner lifecycle conflict.** | Reinforces exactly-one reconciliation authority. Full headless lifecycle redesign is separate. |
|
||||
| [#8362](https://github.com/stablyai/orca/issues/8362) | Open; 2026-07-12; remote relay | PTY master FDs leak across relay children. | **Different mechanism: missing close-on-exec/inherited descriptors.** | Unresolved, but unrelated to named-pipe discovery or destructive requests. |
|
||||
| [#9569](https://github.com/stablyai/orca/issues/9569) / [PR #9587](https://github.com/stablyai/orca/pull/9587) | Issue closed 2026-07-20; PR open | Worktree removal dials a dead legacy v22 socket after v23 upgrade and fails ENOENT. | **Proven stale adapter routing.** PR tolerates dead legacy adapter teardown. | Unshipped. Demonstrates adapter lifecycle staleness; no authority fix. |
|
||||
| [#8689](https://github.com/stablyai/orca/issues/8689) / [PR #8697](https://github.com/stablyai/orca/pull/8697) | Closed/merged 2026-07-14; merge `840d3277d` | Daemon accepts a connection but never answers hello, wedging startup. | **Proven bounded handshake/replacement path.** | Shipped. Harness must bound hello and avoid reconnect storms; not a session-kill mechanism. |
|
||||
| [PR #7538](https://github.com/stablyai/orca/pull/7538) | Merged 2026-07-07 as `03cfc5bd1` | Windows update moved daemon code while live daemon/PTYs should survive. | **Proven historical compatibility intent.** Relocated host preserves same-protocol daemon across update. | Shipped. Later legacy adapters extended preservation across protocol bumps; blanket reaping would regress this contract. |
|
||||
| [PR #2974](https://github.com/stablyai/orca/pull/2974) | Merged 2026-05-28 as `5a852415a` | Resolver refresh risked killing live PTYs. | **Proven preserve-live policy.** Protocol bump/legacy routing is preferred to broad cleanup. | Shipped. Strong evidence against “kill old generation on sight.” |
|
||||
| [PR #7836](https://github.com/stablyai/orca/pull/7836) | Merged 2026-07-18 as `5f6728c1b` | Shutdown/provider selection race could clear a binding while the daemon PTY survived. | **Proven ownership race fix.** Retains provider/shutdown ownership until outcome. | Shipped. Preserve in regression tests; not close-intent adjudication. |
|
||||
| [PR #1343](https://github.com/stablyai/orca/pull/1343) | Merged 2026-05-03 as `df1fefcc2` | Users lacked session visibility; stale PID files risked PID-reuse mistakes. | **Proven management/PID-start-time guard.** | Shipped. Useful diagnostic/incarnation precedent, but observability alone cannot prevent #9749. |
|
||||
| [PR #9516](https://github.com/stablyai/orca/pull/9516) | Merged 2026-07-20 as `2e67af82d`/`de86f482c` | Windows worktree teardown RPCs could hang indefinitely. | **Proven bounded-deadline change.** | Shipped. Bounds cleanup but does not decide whether cleanup is authorized. |
|
||||
| [PR #8768](https://github.com/stablyai/orca/pull/8768) / [PR #8817](https://github.com/stablyai/orca/pull/8817) | Merged 2026-07-14/15 as `02de3c565` and `f7926c11f` | Restored/legacy PTYs could render blank or be unmounted while still live. | **Proven adoption compatibility.** Keep legacy daemon PTYs mounted and defer snapshots correctly. | Shipped. Direct reason that refusing all legacy discovery is unsafe. |
|
||||
| [#9441](https://github.com/stablyai/orca/issues/9441) / [PR #9446](https://github.com/stablyai/orca/pull/9446) | Open; 2026-07-19; macOS 1.4.146 | Large persisted profile drives high CPU/RSS and exits during startup restoration; clean user-data does not reproduce. | **Supported restore-load ordering issue.** PR defers full worktree scan. | Unshipped. Profile-switch/load stress case only; not destructive daemon authority. |
|
||||
|
||||
## Timestamped incident and call-flow reconstruction
|
||||
|
||||
### A. How generations survive
|
||||
|
||||
1. **2026-07-15 13:50 local:** #9749's v21 daemon starts.
|
||||
2. An app quit/update runs `disconnectDaemon`, whose adapter `disconnectOnly`
|
||||
closes client sockets and leaves live PTYs/history reattachable. The daemon is
|
||||
detached/unref'd, so parent death is not daemon death.
|
||||
3. **2026-07-18 14:26 local:** a v22 daemon starts on a different versioned
|
||||
endpoint while v21 retains its PTYs.
|
||||
4. **2026-07-20 14:50 local:** v23 starts while both prior endpoints remain.
|
||||
5. Windows endpoints are generated by
|
||||
`getDaemonSocketPath(runtimeDir, protocolVersion)` as
|
||||
`\\?\pipe\orca-terminal-host-v<protocol>-<sha256(runtimeDir)[0..12]>`.
|
||||
Tokens and PID records are likewise protocol-specific files. No endpoint
|
||||
collision forces an old generation out.
|
||||
6. Before protocol 24, a non-empty daemon had no generation-retirement
|
||||
protocol. Since #9277, an empty v24+ daemon can atomically self-retire, but a
|
||||
live session intentionally blocks it and v23-or-older behavior is unchanged.
|
||||
7. #9749's claim that `shutdown-dispose-failed` necessarily leaves the pipe open
|
||||
is not source-proven for 1.4.146. Commit `a635ff9a7` catches disposal failure
|
||||
and continues ordinary shutdown; #9277 additionally closes admission first.
|
||||
A stuck native handle may keep a process alive, but the endpoint is meant to
|
||||
stop being authoritative.
|
||||
|
||||
### B. Why startup greets every surviving generation
|
||||
|
||||
1. Current startup establishes the v25 (v24 in the reporter build) adapter and
|
||||
its complete control/stream lifecycle lease.
|
||||
2. `createLegacyDaemonAdapters(runtimeDir)` loops every value in
|
||||
`PREVIOUS_DAEMON_PROTOCOL_VERSIONS`, derives that version's pipe/token/PID
|
||||
paths, and probes each endpoint.
|
||||
3. A responsive endpoint receives a `DaemonPtyAdapter` configured with that
|
||||
exact old protocol. It has no respawn callback, because new code must not
|
||||
recreate old environment semantics.
|
||||
4. `DaemonPtyRouter.discoverLegacySessions()` calls `adapter.listProcesses()`
|
||||
for each legacy adapter.
|
||||
5. `listProcesses()` calls `ensureConnected()`. `DaemonClient.doConnect()` opens
|
||||
a control socket, sends hello, then opens a stream socket and sends hello
|
||||
using one client UUID. This is the precise source of each control/stream pair
|
||||
in #9749 at `16:41:32.277Z` through `.286Z`.
|
||||
6. v24+ hellos return PID/start-time/launch-nonce and require both sockets to
|
||||
match. Old protocols return no identity, so successful token+protocol hello
|
||||
authenticates the endpoint but cannot prove a process incarnation.
|
||||
7. `listSessions` results populate `sessionAdapters: Map<sessionId, adapter>`.
|
||||
That map is keyed only by reusable session ID, not daemon/session
|
||||
incarnation; a later generation can overwrite an earlier claim.
|
||||
8. No code in hello acceptance, adapter construction, or discovery sends
|
||||
`kill`, `shutdown`, or `shutdownIfIdle` to a legacy daemon.
|
||||
|
||||
### C. Exact broad shutdown caller
|
||||
|
||||
1. Current-daemon replacement/manual restart/full cleanup calls
|
||||
`cleanupDaemonForProtocol(runtimeDir, PROTOCOL_VERSION)` (or the explicitly
|
||||
supplied current handle protocol).
|
||||
2. It probes that version's endpoint and creates a `DaemonClient` for the same
|
||||
protocol.
|
||||
3. It connects with the same control/stream hello sequence.
|
||||
4. It requests `listSessions`; any error is converted to `{ sessions: [] }`.
|
||||
5. It then unconditionally sends `shutdown { killSessions: true }` and treats a
|
||||
reply race with daemon exit as success.
|
||||
6. `daemon-server.ts` logs `shutdown reason:'rpc' killSessions:true`, begins the
|
||||
ordinary shutdown admission fence, awaits `host.dispose`, logs but catches
|
||||
`shutdown-dispose-failed`, writes the reply if possible, disposes resources,
|
||||
destroys clients/transports, unlinks owned identity artifacts, and closes
|
||||
the server.
|
||||
7. Repository search found no other direct production sender of
|
||||
`shutdown { killSessions: true }`. Legacy adapter discovery is not a caller.
|
||||
8. Unsafe residual: list failure cannot be treated as proof of emptiness for
|
||||
any future generation reaper, and broad shutdown still lacks an origin,
|
||||
daemon-incarnation, ownership, and intent audit record.
|
||||
|
||||
### D. Supported reconnect-to-mass-kill path
|
||||
|
||||
1. **Renderer bootstrap T+0:** a paired desktop/runtime renderer hydrates
|
||||
persisted mirrors containing process-lifetime remote terminal handles.
|
||||
2. **T+milliseconds:** before the fresh authoritative session snapshot fully
|
||||
reconciles, remote transport subscribes using a stale handle.
|
||||
3. The host cannot resolve a connected PTY for that handle and returns a gone
|
||||
condition; remote transport synthesizes `pty-exit`.
|
||||
4. `Terminal.tsx` calls `closeTerminalTab(tabId, { reason: 'pty-exit' })`.
|
||||
5. Current main uses that reason for local retirement behavior but
|
||||
`closeWebRuntimeSessionTab` sends only `{ worktree, tabId }`.
|
||||
6. Runtime RPC `session.tabs.close` has no origin/intent in its schema or
|
||||
handler. `OrcaRuntimeService.closeMobileSessionTab` treats it like an
|
||||
explicit user request and invokes either direct `ptyController.kill`, a
|
||||
whole-parent renderer close, or headless teardown.
|
||||
7. For daemon-backed terminals, the PTY controller is the `DaemonPtyRouter`.
|
||||
`adapterFor(sessionId)` uses the discovery map to select a current or legacy
|
||||
generation and its adapter sends `kill { sessionId, immediate }`.
|
||||
8. The owning daemon logs `session-killed` before awaiting `host.kill`. This is
|
||||
why app and daemon PIDs remain alive while real terminal sessions disappear.
|
||||
9. **#8871 observed T+3.348 s** for the first bootstrap-to-kill incident. Three
|
||||
other new renderer processes aligned within about one second with 4-, 7-,
|
||||
and 7-worktree kill bursts.
|
||||
10. Stale host tab surfaces (#9352/#9585), persisted client mirrors, reconnect
|
||||
retries, and republished snapshots can invoke the same close again. If the
|
||||
daemon still retains the session entry or physical exit is unresolved, a
|
||||
reconnect can rediscover and target the same ID again. Because logging
|
||||
precedes the awaited kill, repeated `session-killed` records can also be
|
||||
repeated failed/not-yet-settled attempts; they do not prove a dead process
|
||||
was resurrected and killed twice.
|
||||
|
||||
### E. Why adjacent bugs are different
|
||||
|
||||
- **#8275/#8048/#8140:** PTY teardown double-closes a Windows ConPTY native
|
||||
handle and the shared daemon dies. There is no broad shutdown event. All
|
||||
sessions disappear because their owner process died.
|
||||
- **#9704/#9045/#9752:** a valid or invalid kill has already targeted the PTY
|
||||
root, but Windows descendants remain and retain memory/files. The owner stays
|
||||
alive or the registry stays stale. This is cleanup completeness after a kill,
|
||||
not destructive authority.
|
||||
- **#9749/#8871:** app and daemons remain alive. Explicit RPCs reach live daemon
|
||||
sessions because stale client lifecycle evidence is interpreted as intent.
|
||||
|
||||
## Compatibility behavior that must remain
|
||||
|
||||
- App quit is a disconnect, not terminal shutdown.
|
||||
- Same-protocol daemon survival across packaged Windows updates (#7538) avoids
|
||||
terminating live work.
|
||||
- Old-protocol adapters remain addressable after an upgrade so mounted and
|
||||
sleeping PTYs can reattach (#2974, #8768, #8817).
|
||||
- Legacy daemons cannot be judged empty from one current profile or renderer.
|
||||
Missing ownership data, inactive profiles, sleeping sessions, remote/SSH
|
||||
routes, and legacy claims all mean keep/audit.
|
||||
- Current protocol 24+ can retire only after its own atomic server-side idle
|
||||
predicate proves there is nothing to preserve.
|
||||
- Older clients/servers must not infer support from an ignored additive field.
|
||||
In particular, no caller may send daemon `kill intent:'auto'` until a
|
||||
protocol bump or negotiated capability proves the daemon will enforce it.
|
||||
|
||||
## Direction comparison
|
||||
|
||||
| Direction | Immediate safety | Compatibility and failure mode | Decision |
|
||||
| ------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
|
||||
| Skip `client-hello` for every old protocol | Avoids routing kills to legacy sessions, but also makes their live PTYs invisible/unattachable. | Directly violates warm legacy reattachment and converts preservation into inaccessible leaks. | Reject. Hello is not the authority bug. |
|
||||
| Force-exit on `shutdown-dispose-failed` | Bounds a half-shutdown process if endpoint fencing and handle cleanup are correct. | Can silently destroy promised live PTYs; does not stop reconnect close RPCs; overlaps #9752 descendant semantics. Current source already continues server shutdown after disposal error. | Not the immediate fix. Test bounded endpoint loss separately. |
|
||||
| Startup reaping | Can reduce accumulated attack surface. | Unsafe without #9138/#9229 all-profile evidence, exact incarnations, grace observations, barriers, and one authority. | Audit-only follow-up, not #9749 patch. |
|
||||
| Explicit generation handoff/retirement | Correct long-term lifecycle model. | Requires old/new capability negotiation and ownership persistence across profiles, SSH, WSL, and sleeping sessions. | Broader #9138/#9229 work. |
|
||||
| Daemon-side fencing | Prevents a retiring daemon from accepting new work or acting after retirement begins. | v24 #9277 already fences ordinary/idle shutdown admission; older protocols cannot be retrofitted. | Preserve and extend only with negotiated capability. |
|
||||
| Host close-intent adjudication (#8872) | Stops the demonstrated stale `pty-exit` echo at the component that owns the live PTY, while real user close and genuinely dead tab retirement still work. | Old clients remain ambiguous unless paired with a default-deny compatibility policy. | Best narrow foundation. |
|
||||
| Connection/device provenance policy (#8888) | Default-denies ambiguous paired-runtime destruction, adds dedupe/rate bounds and strong attribution. | Older paired clients receive a safe successful no-op; policy is broader than one close reason and must preserve mobile/CLI/local/SSH semantics. | Reuse focused policy/logging pieces; assess full policy after the failing harness. |
|
||||
| Job Objects (#9752) | Reaps descendants after an authorized native-Windows agent PTY kill. | Cannot determine intent; plain terminal and WSL exclusions are semantically important. | Compose separately, never substitute for authority. |
|
||||
|
||||
The smallest robust immediate change is expected to combine typed close intent
|
||||
with host-side liveness adjudication and non-secret requester logging. The
|
||||
three-generation harness must decide whether #8888's default-deny/dedupe layer
|
||||
is also required for old-client and repeated-reconnect safety. Full generation
|
||||
retirement stays in #9138/#9229.
|
||||
|
||||
## Harness gate for the next phase
|
||||
|
||||
The first executable artifact will be an isolated native-Windows harness, not a
|
||||
production edit. It must:
|
||||
|
||||
- allocate a temporary runtime/user-data root and unique pipe namespace;
|
||||
- launch three disposable protocol fixtures (for example v21/v22/v23) with
|
||||
distinct live canary children plus stale/terminating table entries;
|
||||
- use the real `DaemonClient`, legacy adapter discovery, router, and runtime
|
||||
session-close path where feasible instead of calling a proposed helper;
|
||||
- prove hello/discovery alone is non-destructive;
|
||||
- separately trigger the exact broad current-protocol shutdown caller and the
|
||||
reconnect stale-mirror close path;
|
||||
- distinguish daemon/app liveness, PTY-root liveness, and descendant liveness
|
||||
with independent counters and process handles;
|
||||
- repeat reconnect bursts and record duplicate requests for a retained ID;
|
||||
- model a PTY owner whose disposal never proves physical exit and assert a
|
||||
bounded, non-authoritative endpoint state;
|
||||
- cover current→next protocol upgrade, same-version quit/relaunch, profile
|
||||
switch, remote-server paired client, multiple simultaneous clients, mixed
|
||||
client/server versions, and WSL/SSH routing boundaries;
|
||||
- validate PID/start identity, dead parent, access-denied identity probes, no
|
||||
listener/pipe/handle leaks, and no CIM/PowerShell per-session hot path;
|
||||
- guarantee cleanup in `finally` using only fixture-owned exact PIDs, handles,
|
||||
files, and pipe names.
|
||||
|
||||
Externally visible RED invariants are: reconnect kills one or more canary PTYs
|
||||
while the app/fixture processes remain alive; repeated stale input can issue
|
||||
another destructive request for the same retained incarnation; and a refused
|
||||
disposal does not reach a bounded terminal endpoint state. The post-fix GREEN
|
||||
invariants are survival of every unrelated canary, one exact kill for an
|
||||
explicit user target, legacy warm reattachment, bounded retirement fencing, and
|
||||
zero leaked fixture processes/handles/pipes.
|
||||
|
||||
## Implemented immediate safety boundary
|
||||
|
||||
Implementation snapshot: 2026-07-21 15:26 PDT (2026-07-21 22:26 UTC).
|
||||
|
||||
The initial implementation used a 30-second capability cache keyed only by
|
||||
runtime-environment ID. That was rejected before finalization: a positive
|
||||
`status.get` result could outlive a server replacement under the same
|
||||
environment, and the later destructive request had no proof that it reached the
|
||||
generation that supplied the capability.
|
||||
|
||||
The implemented boundary makes compatibility and identity validation atomic
|
||||
with the lifecycle request:
|
||||
|
||||
1. Explicit user closes remain on `session.tabs.close`, preserving the durable
|
||||
host-owned close behavior shipped by #8628 and compatibility with old
|
||||
servers that ignore the additive `reason:'user'` field.
|
||||
2. Renderer-originated `pty-exit` and `cleanup` echoes use the additive
|
||||
`session.tabs.closeLifecycle` method. An old server returns
|
||||
`method_not_found` before entering its legacy destructive close handler. The
|
||||
client clears optimistic close suppression and requests an authoritative
|
||||
snapshot; it never falls back to `session.tabs.close`.
|
||||
3. The lifecycle method requires both the `publicationEpoch` observed in the
|
||||
host snapshot and the exact terminal handle observed for that tab. Missing
|
||||
evidence means keep, refresh, and audit rather than kill.
|
||||
4. The host refreshes its PTY records, rejects a different publication epoch,
|
||||
rejects a terminal handle that no longer belongs to the addressed parent,
|
||||
rejects when provider liveness is unavailable, and rejects while any parent
|
||||
leaf still has a connected PTY. Refusals carry a bounded reason
|
||||
(`stale-publication`, `stale-terminal`, `unknown-liveness`,
|
||||
`live-host-pty`, or `retirement-owner`) and republish only when doing so
|
||||
cannot create the known dead-leaf/live-sibling echo loop.
|
||||
5. A lifecycle close never signals a PTY or relays a renderer close. A dead
|
||||
whole headless parent can be retired from persisted/runtime state with
|
||||
`killPtys:false`; a renderer-owned parent or partial split remains with its
|
||||
authoritative owner. Thus a reusable tab ID or incomplete provider read
|
||||
cannot become destructive authority.
|
||||
6. Reasonless closes from authenticated legacy mobile or runtime clients retain
|
||||
their pre-change explicit-user meaning, so upgrading only the host does not
|
||||
break close. Their old lifecycle/user ambiguity remains until the client
|
||||
upgrades; unattributed in-process reasonless calls are refused and replayed.
|
||||
7. Renderer close intents are scoped by runtime environment and worktree, and
|
||||
terminal-incarnation evidence must match that exact runtime environment.
|
||||
Identical tab/worktree IDs in another profile cannot suppress or authorize
|
||||
this profile's retirement.
|
||||
|
||||
The RPC span records origin/client kind, close reason, connection ID, request
|
||||
ID, publication epoch, and allow/refusal decision. It does not record terminal
|
||||
contents, authentication tokens, or environment secrets. The legacy adapter
|
||||
hello/discovery path, warm PTY adoption, daemon shutdown protocol, and Job
|
||||
Object descendant cleanup remain unchanged.
|
||||
|
||||
This is the smallest immediate #9749 fix. Cross-profile generation inventory,
|
||||
all-profile ownership evidence, sleeping-session policy, and explicit daemon
|
||||
handoff/retirement remain #9138/#9229. Windows descendant reaping after an
|
||||
authorized kill remains #9704/#9752.
|
||||
|
||||
## GREEN evidence
|
||||
|
||||
The post-fix native-Windows run completed at 2026-07-21 15:25 PDT:
|
||||
|
||||
- v21/v22/v23 used distinct versioned named pipes under a disposable runtime
|
||||
root, with six independent PTY-root/descendant canaries;
|
||||
- three reconnect discovery bursts plus simultaneous clients opened the real
|
||||
control/stream hello pairs without destructive side effects;
|
||||
- desktop and two remote/profile connection identities attempted each stale
|
||||
mirror retirement three times, then a full reconnect-client process
|
||||
exit/relaunch repeated the same persisted IDs for six attempts total;
|
||||
- the lifecycle requests traversed the production schema, dispatcher,
|
||||
`OrcaRuntimeService`, and `DaemonPtyRouter` using publication/terminal
|
||||
incarnation claims;
|
||||
- every daemon, PTY root, and descendant remained alive while the app/client
|
||||
process remained alive;
|
||||
- the contained refusal-to-exit PTY produced `shutdown-dispose-failed`, lost
|
||||
named-pipe authority within the bounded deadline, and was cleaned by exact
|
||||
fixture-owned process identity;
|
||||
- the reconnect/relaunch test passed in 42.9 seconds and the bounded-disposal
|
||||
test passed in 15.2 seconds.
|
||||
|
||||
Focused verification at this checkpoint: node and web typechecks passed;
|
||||
changed-file `oxlint` and `git diff --check` passed; 181 focused renderer/RPC
|
||||
tests passed; and 12 host close-adjudication tests passed (784 unrelated tests
|
||||
filtered out). No PowerShell/CIM process-per-session path, polling loop, broad
|
||||
installed-daemon discovery, or Job Object implementation was added.
|
||||
|
||||
Additional validation completed at 2026-07-21 15:48 PDT:
|
||||
|
||||
- the native generation harness passed 25 reconnect bursts in 52.1 seconds;
|
||||
every v21/v22/v23 daemon and all six PTY-root/descendant canaries survived;
|
||||
- the mixed-version daemon-lifecycle E2E kept the non-empty v22 daemon
|
||||
reattachable while the empty current v24 daemon retired through #9277;
|
||||
- a fresh `pnpm build:electron-vite` and a fresh paired-web-client build both
|
||||
completed successfully;
|
||||
- 182 remote-runtime, multi-client, remote-server parity, SSH-provider, WSL
|
||||
host-context, and remote PTY transport tests passed;
|
||||
- the complete runtime service/RPC group passed 884 of 885 tests. The lone
|
||||
failure, `preserves existing badgeColor on runtime createRepo dedupe`, is an
|
||||
existing Windows-only POSIX path expectation (`/tmp/...` versus
|
||||
`\\tmp\\...`) in code untouched by this change; every close, remote, SSH,
|
||||
and WSL case in that run passed;
|
||||
- CLI typecheck, switch-independent changed-file lint, reliability gates,
|
||||
max-lines ratchet, and `git diff --check` passed. The repository-wide
|
||||
switch-exhaustiveness command is blocked by the pre-existing unmatched
|
||||
`undefined | 'current' | 'duplicate'` cases in
|
||||
`skill-freshness-group.tsx`, outside this diff.
|
||||
|
||||
Two practical Electron runs exposed setup/teardown limitations without
|
||||
contradicting the close-safety result:
|
||||
|
||||
- `restart-restore-terminal-input.spec.ts` completed the clean-restart, live
|
||||
daemon, restored-output, keyboard-input, and direct-input assertions, then
|
||||
failed only in `RestartSession.dispose()` with `EPERM` deleting its isolated
|
||||
profile. Restart Manager and Sysinternals Handle found no surviving file
|
||||
lock after teardown; the exact fixture root deleted successfully later
|
||||
without terminating a process. The same failure reproduced with the temp
|
||||
root inside this worktree and with the production diff to
|
||||
`orca-restart.ts` empty, so it is recorded as a fixture cleanup limitation,
|
||||
not a session-liveness failure;
|
||||
- the paired-browser navigation E2E built the web client and launched the
|
||||
isolated desktop, but timed out before pairing because its host fixture
|
||||
displayed `No workspaces found`. The deterministic multi-client runtime
|
||||
integration passed; no terminal-close assertion failed in this E2E.
|
||||
|
||||
All diagnostic downloads and worktree-local E2E temp roots were removed by
|
||||
their exact verified paths. No installed Orca daemon pipe or real user terminal
|
||||
was discovered, greeted, stopped, or mutated during these runs.
|
||||
|
||||
## Internal review-until-clean and final native evidence
|
||||
|
||||
The requested `$internal-review-until-clean` loop ran against merge base
|
||||
`937a2015eaf85144d02848c5b6d4c09ecd423830`. Round 1 found and fixed four
|
||||
in-scope safety defects:
|
||||
|
||||
- lifecycle retirement could still relay a destructive renderer close or kill
|
||||
retained/disconnected headless IDs; lifecycle requests now never signal a
|
||||
process and only state-retire a dead whole headless parent;
|
||||
- an unavailable/access-denied PTY inventory was treated like authoritative
|
||||
absence; it now returns `unknown-liveness` and keeps/audits;
|
||||
- pending close intent was keyed only by worktree and could cross-contaminate
|
||||
two runtime profiles; it is now scoped and cleaned by environment/worktree;
|
||||
- the harness accepted a two-second PID start-time tolerance; capture and
|
||||
revalidation now compare the same CIM `CreationDate` exactly.
|
||||
|
||||
The elegance pass also removed an unnecessary cached capability probe. The
|
||||
additive method dispatch on the exact connection is the atomic compatibility
|
||||
boundary; a cached positive result could outlive server replacement. The
|
||||
performance pass found no production polling, process enumeration, listener,
|
||||
or subprocess addition. The existing bounded controller inventory refresh is
|
||||
unchanged in frequency, snapshot refreshes coalesce per environment/worktree,
|
||||
and all added tracking maps have completion or ownership cleanup. Round 2
|
||||
re-interrogated the full diff and found no remaining proven in-scope issue.
|
||||
After strengthening the native harness to invoke production desktop discovery,
|
||||
round 3 found one Windows-only test defect: three scanner tests modeled a live
|
||||
v9 endpoint through POSIX `existsSync` but let every Windows named-pipe probe
|
||||
connect. Their socket mock now accepts only v9 and errors every other version;
|
||||
all 133 daemon lifecycle tests pass. The subsequent full-diff review is clean.
|
||||
|
||||
The latest native Windows run captured its event reconstruction at
|
||||
2026-07-21 16:58 PDT (2026-07-21 23:58 UTC). It launched v21/v22/v23/v24/v25
|
||||
on isolated versioned named pipes, then called the same
|
||||
`createLegacyDaemonAdapters` scanner as desktop startup: the v25 client found
|
||||
exactly v21-v24. Every generation accepted 16 reconnect control/stream hellos;
|
||||
desktop and two remote-profile paths sent six lifecycle attempts for each
|
||||
persisted stale-mirror ID across process relaunch. All five daemons, all ten
|
||||
PTY roots, and all ten descendants were alive afterward, with zero
|
||||
`session-killed` events. This directly covers the v24→v25 current-to-next
|
||||
upgrade boundary while keeping older generations reattachable.
|
||||
|
||||
The bounded `shutdown-dispose-failed` scenario also passed and now separates
|
||||
authority from liveness explicitly: the late connection failed after endpoint
|
||||
fencing while the refusing daemon, PTY root, and descendant remained alive
|
||||
until exact fixture cleanup. The full Playwright command, including a fresh
|
||||
Electron E2E build, exited successfully in 137.1 seconds, and no
|
||||
`orca-9749-dg-*` directory remained. A final no-rebuild rerun passed both
|
||||
scenarios in 99.1 seconds; the practical Electron clean-relaunch check passed
|
||||
again in 24.0 seconds, and mixed-version retirement/live-session preservation
|
||||
passed 2/2 in 23.1 seconds.
|
||||
|
||||
Latest focused verification includes 15/15 host adjudication tests, 948/949
|
||||
focused production/RPC/renderer tests, 133/133 daemon discovery/adoption/
|
||||
retirement/access-failure tests, all three typechecks, and 215
|
||||
remote-runtime, multi-client, remote-server, SSH-provider, WSL-context, remote
|
||||
PTY, and shared-control tests. The sole focused failure remains the untouched
|
||||
Windows `/tmp` normalization baseline documented above. The experimental
|
||||
`terminal-session.daemon-generation-reconnect-safety` reliability gate records
|
||||
the invariant, RED/GREEN oracle, performance budget, promotion criteria, and
|
||||
known platform/provider gaps.
|
||||
|
||||
## Fresh PR review after current-main integration
|
||||
|
||||
The explicitly requested post-PR `$internal-review-until-clean` pass completed
|
||||
at 2026-07-21 18:02 PDT after merging `v1.4.150-rc.0` main, including the
|
||||
remote-runtime network-recovery work from #9774. It found and fixed three
|
||||
additional contract gaps:
|
||||
|
||||
- a stale PTY-exit callback could borrow a replacement or sibling handle from
|
||||
tab-wide state; lifecycle evidence now comes only from the exact callback PTY;
|
||||
- the legacy close endpoint accepted lifecycle reasons without incarnation
|
||||
evidence; it now accepts only explicit user intent, with reasonless
|
||||
compatibility retained for authenticated legacy mobile and runtime clients;
|
||||
- keep-on-unknown preserved the PTY but could leave its client mirror hidden;
|
||||
the host now republishes unchanged authority when inventory is unavailable.
|
||||
|
||||
The PR feedback loop also corrected the bulk-close payload assertion and made
|
||||
the fixture protocol list collision-safe. The final native no-build run passed
|
||||
both scenarios in 98.8 seconds, the fresh-build run passed in 137.1 seconds,
|
||||
mixed-version retirement passed, and practical Electron restart/input passed
|
||||
two scenarios with one intentionally skipped wedge scenario. Current-main
|
||||
remote recovery (112 tests), focused close/reconnect suites, all 15 host
|
||||
adjudication cases, all typechecks, reliability gates, max-lines, changed lint,
|
||||
formatting, and diff checks pass. The full lint command remains blocked only by
|
||||
pre-existing current-main switch-exhaustiveness and localization findings; no
|
||||
remaining in-scope review finding is open.
|
||||
|
||||
## Additional clean review after `v1.4.150-rc.0` integration
|
||||
|
||||
This additional requested `$internal-review-until-clean` pass completed at
|
||||
2026-07-21 18:56 PDT (2026-07-22 01:56 UTC) against merge base
|
||||
`4d0e3f51ce0325a8f4670b4074618494984ab63d`. Round 1 found and fixed four
|
||||
in-scope evidence/performance gaps:
|
||||
|
||||
- the native harness omitted production `DaemonPtyRouter.listProcesses`, so
|
||||
its synthetic lifecycle closes could pass through `unknown-liveness`; it now
|
||||
routes the production inventory, uses worktree-prefixed daemon session IDs,
|
||||
and requires every close to return `live-host-pty` with a republished
|
||||
snapshot;
|
||||
- concurrent reconnect closes each started a full cross-generation PTY
|
||||
inventory; the host now shares one in-flight inventory and a deterministic
|
||||
count test proves two concurrent closes call `listProcesses` once;
|
||||
- the renderer introduced a second snapshot-refresh map; it now reuses the
|
||||
existing environment/worktree remote-session deduper used by PTY reconnect;
|
||||
- the reliability gate omitted the parked-tab callback path; its exact exiting
|
||||
PTY incarnation assertion is now part of the gate.
|
||||
|
||||
The review also added a wire-compatibility assertion proving that the additive
|
||||
`{ reason: 'user' }` field is stripped by the previous `ActivateTab` server
|
||||
schema. The repeated elegance and performance interrogation found no remaining
|
||||
avoidable infrastructure, polling, subprocess churn, listener/handle leak, or
|
||||
unbounded reconnect work. Round 2 re-read the full production and fixture diff,
|
||||
constructed stale-publication, stale-handle, concurrent-close, mixed-client,
|
||||
and old-server failure paths, and found no remaining proven in-scope issue.
|
||||
|
||||
Fresh verification includes all three typechecks; reliability-manifest,
|
||||
max-lines, changed-file lint, formatting, and diff checks; 175 remote snapshot
|
||||
and PTY transport tests; and the isolated lifecycle/reconnect adjudication
|
||||
group. The strengthened native five-generation Windows harness passed after a
|
||||
fresh Electron E2E build in 137.2 seconds, required `live-host-pty` for every
|
||||
synthetic close, left every daemon/root/descendant alive, and left no
|
||||
`orca-9749-dg-*` directory. The full focused gate reached 992/993 passing tests;
|
||||
the only failure remains the untouched Windows `/tmp` versus `\\tmp`
|
||||
`createRepo` baseline. The newly merged headless-update group reached 143/144
|
||||
passing tests plus 25 skips; its only failure is an untouched LF-only
|
||||
source-text assertion that does not match CRLF on Windows.
|
||||
|
||||
## Completion evidence matrix
|
||||
|
||||
| Original acceptance requirement | Authoritative evidence | Status |
|
||||
| ------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------ |
|
||||
| Complete recursive issue/PR/commit/tag investigation before production edits | The 41-row investigation matrix above, release chronology, and timestamped call-flow reconstruction cover every required starting item and every directly discovered related item. GitHub reads were completed before the first production edit. | Proven |
|
||||
| Explain survival, generation discovery/hello, broad shutdown caller, repeated reconnect kills, adjacent-bug distinctions, and compatibility | Sections A–E identify `disconnectDaemon`, `createLegacyDaemonAdapters` → `discoverLegacySessions` → control/stream hello, `cleanupDaemonForProtocol`, the stale-handle `pty-exit` path, #8275 versus #9704, and the warm legacy reattach contract. | Proven |
|
||||
| Isolated native-Windows multi-generation reproduction with external liveness oracle | `daemon-generation-reconnect-safety.spec.ts` uses an exact temporary user-data/runtime root, versioned pipe names, disposable ConPTY children, independent daemon/root/descendant PID-start identities, bounded output, and exact cleanup. The historical RED run above recorded real repeated `session-killed` events while daemon/client witnesses stayed alive. | Proven |
|
||||
| Exercise the desktop discovery path and current→next mixed-version upgrade | The latest native run calls production `createLegacyDaemonAdapters`; v25 discovers exactly v21/v22/v23/v24, reattaches every original process incarnation, and leaves all five generations alive. | Proven |
|
||||
| Reconnect bursts, app quit/relaunch, simultaneous clients, repeated IDs, profile and remote-runtime boundaries | Three router rebuilds, a full reconnect-client process exit/relaunch, parallel direct clients, and six desktop/two-profile lifecycle attempts per persisted ID are native. Environment-scoped close-intent and remote-runtime transport suites supply deterministic profile-switch/remote-server boundary proof. | Proven (native transport plus deterministic profile/provider boundaries) |
|
||||
| `shutdown-dispose-failed` has a bounded non-authoritative state without conflating process death | The native refusal fixture loses pipe authority within the deadline, rejects a late client, logs the failure, proves its daemon/root/descendant still live, then cleans only exact recorded fixture incarnations. | Proven |
|
||||
| Smallest immediate fix preserves legacy adoption and separates broader retirement/descendant cleanup | Additive `session.tabs.closeLifecycle`, host liveness/incarnation adjudication, no destructive fallback, and state-only dead-headless retirement leave hello/adoption, #9138/#9229 retirement, and #9704/#9752 descendant semantics unchanged. | Proven |
|
||||
| Missing evidence keeps/audits; retirement is incarnation/profile safe; one owner has destructive authority | Host tests cover unavailable inventory, stale publication/handle, live split siblings, renderer ownership, and authenticated legacy versus unattributed reasonless callers. Renderer tests cover exact environment handles and cross-profile intent isolation. Lifecycle requests never signal a PTY or relay renderer teardown. | Proven |
|
||||
| Windows identity, dead-parent/never-adopted, ACL/access failure, rapid reconnect, and multi-client behavior | Native CIM `CreationDate` identity is exact; the five-generation run covers rapid reconnect and concurrent clients. The 133-test daemon group covers never-adopted retirement, admission fencing, overlapping clients, and EACCES/EPERM process-signal failures. | Proven (native identity/reconnect; deterministic ACL failure) |
|
||||
| No production PowerShell/CIM hot path, polling/listener/handle leak, or reconnect storm | Process enumeration exists only in fixture helpers; production adds no subprocess or timer. Refreshes coalesce by environment/worktree, listener ownership is unchanged, every fixture allocation has bounded cleanup, and 25-burst stress evidence is recorded above. | Proven |
|
||||
| Cross-platform, SSH, WSL, remote-server, and multiple-client compatibility | 215 deterministic tests cover remote runtime/server, shared control, SSH provider, WSL host context, and PTY transport. Platform-specific fixture behavior is runtime-gated. | Deterministic proof complete; live Linux SSH/WSL unavailable |
|
||||
| Practical Electron restart behavior | A real isolated Electron application created a daemon-backed terminal, wrote and restored output across clean app quit/relaunch, preserved the exact daemon PID, and accepted both keyboard and direct terminal input after reattachment. | Proven on native Windows (`electron-headless`, 24.0 s) |
|
||||
| Internal review-until-clean and final gates | The original three review rounds and both additional PR review loops are clean. The latest loop fixed four oracle/performance/gate gaps, then completed a clean full-diff re-review. Typecheck, lint, format, reliability manifest, max-lines ratchet, Electron build, native harness, and focused suites pass apart from the documented untouched baselines. | Proven |
|
||||
| Public GitHub and real daemon safety | No public GitHub mutation occurred. Fixture guards reject non-temporary roots and known Orca user-data paths; no installed pipe/token/session was discovered or contacted. | Proven |
|
||||
|
||||
Live Linux SSH validation remains an explicit gap: the required throwaway
|
||||
Docker target is unavailable on this runner (`docker` is not installed and no
|
||||
Docker Desktop process or standard executable path exists), and `wsl.exe`
|
||||
reports that WSL is not installed. A real remote or localhost was deliberately
|
||||
not substituted. The Orca worktree comment was updated through the scoped
|
||||
`worktree set --comment` CLI with the investigation, RED reproduction,
|
||||
root-cause, implementation, native-validation, and clean-review milestones.
|
||||
No terminal or daemon command was issued through the CLI, and no public GitHub
|
||||
comment was made.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,576 +0,0 @@
|
||||
# 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.
|
||||
@@ -1,456 +0,0 @@
|
||||
# Remote agent-session host authority
|
||||
|
||||
Status: implemented single-PR v1 design for issues #8878 and #9352; deterministic validation complete.
|
||||
|
||||
## Reliability contract
|
||||
|
||||
- **Invariant (`agent-session.remote-host-authority`):** one provider-session identity has at most one live PTY owner and canonical host surface on every claim-capable route; exact exit retires that incarnation durably.
|
||||
- **Failure source:** issues #8878 and #9352, including concurrent remote clients, ambiguous replies, exit-before-publication, and stale client snapshots.
|
||||
- **Oracle:** the focused ownership/lifecycle matrix and `pnpm test:repro:remote-agent-session` prove one physical spawn, canonical retry adoption, exact exit retirement, stale-publication rejection, and no restart resurrection.
|
||||
- **Gate:** the experimental `agent-session.remote-host-authority` entry in `config/reliability-gates.jsonc`.
|
||||
- **Coverage:** deterministic macOS local/daemon/remote-runtime evidence plus SSH/relay fault-injection; Linux, Windows, WSL, and live SSH remain explicit gaps.
|
||||
- **Performance budget:** no polling or terminal-output work; admission-only provider reconciliation is inflight-deduped, and operation state is capped and expiring.
|
||||
- **Diagnostics:** structured RPC error codes, PTY incarnation IDs, owner generations, operation dispositions, and the repro artifact distinguish fallback, adoption, conflict, and retirement failures.
|
||||
- **Residual gaps:** durable fresh-operation journaling, automatic sleep checkpoints, verified nested-SSH namespaces, and multi-process profile coordination are documented under Future extensions.
|
||||
|
||||
## Summary
|
||||
|
||||
A remote Orca host, not an attached renderer, decides whether a provider agent
|
||||
session already has a live PTY. Clients send structured intent (fresh launch or
|
||||
explicit provider identity); the host returns one canonical terminal surface.
|
||||
|
||||
This fixes two related failures:
|
||||
|
||||
- A paired client could consume its own persisted sleep record and launch a
|
||||
second TUI while the remote host still owned the first one (#8878).
|
||||
- An exited host terminal could remain in `session.tabs.list` as a handle-less
|
||||
placeholder, get persisted by clients, and return as a ghost tab (#9352).
|
||||
|
||||
The v1 protocol deliberately fails closed after authority side effects begin.
|
||||
At mixed-version boundaries the host may return
|
||||
`agent_session_legacy_required`, but only after a read-only execution-owner
|
||||
check and before trust, claim, spawn, or any retained replay fence. The client can then run
|
||||
its retained exact legacy request, so upgrading any subset of clients, hosts,
|
||||
daemons, or relays does not remove workflows that worked before the upgrade.
|
||||
|
||||
## Scope and guarantees
|
||||
|
||||
This change guarantees:
|
||||
|
||||
1. Runtime-owned worktrees always queue renderer sleep records into the normal
|
||||
transport. A fully capable route turns that intent into an authoritative
|
||||
ensure/adoption; mixed-version routes preserve the legacy wake behavior.
|
||||
2. On capable hosts, known provider sessions resume through a structured
|
||||
`terminal.ensureAgentSession` request.
|
||||
3. On claim-capable execution routes, concurrent or repeated ensures for the
|
||||
same canonical provider identity return one execution owner and one
|
||||
canonical terminal surface.
|
||||
4. A fresh launch uses `terminal.createAgentSession` with a caller-scoped
|
||||
operation ID. Stable runtime surface identity, daemon session identity, and
|
||||
relay operation identity prevent response-loss retries from creating a
|
||||
second process while their respective owner remains alive.
|
||||
5. New hosts continue accepting agent-bearing legacy terminal-create RPCs, so
|
||||
old clients behave exactly as they did before the host upgrade.
|
||||
6. Structured explicit resume returns `agent_session_legacy_required` before
|
||||
side effects when a daemon is old or an SSH route cannot attest its execution
|
||||
namespace. A claim-capable route still fails closed on malformed,
|
||||
conflicting, or unknown ownership after dispatch.
|
||||
7. Natural or explicit PTY exit retires only the exact PTY incarnation and
|
||||
terminal surface from both `terminal.list` and `session.tabs.list`, repairs
|
||||
active/group topology, and removes durable host persistence.
|
||||
8. New clients use structured authority only when advertised. Capability
|
||||
absence or a transient read-only probe failure selects the exact legacy
|
||||
payload; protocol incompatibility remains blocked.
|
||||
|
||||
The following are not v1 guarantees:
|
||||
|
||||
- automatic resume of an intentionally sleeping remote agent;
|
||||
- fresh-launch exactly-once behavior across a full runtime process restart;
|
||||
- host-authoritative deduplication of resumes through an unverified
|
||||
direct/nested SSH execution namespace (those launches retain legacy behavior);
|
||||
- supervising a provider process after its owning PTY exits;
|
||||
- coordinating multiple independent Orca main processes for one profile;
|
||||
- preventing a nonconforming new client from deliberately sending the same
|
||||
legacy wire request as an old client; authenticated request-level capability
|
||||
negotiation does not yet exist, so the server cannot distinguish them.
|
||||
|
||||
Those constraints are explicit so future work can extend the protocol without
|
||||
weakening the v1 safety boundary.
|
||||
|
||||
## Authority model
|
||||
|
||||
There are three layers:
|
||||
|
||||
| Layer | Responsibility |
|
||||
| --------------------------------- | --------------------------------------------------------------------------------------- |
|
||||
| Client/renderer | Sends structured intent and mirrors host snapshots |
|
||||
| Runtime/controller | Resolves worktree and provider identity, signs a claim, publishes the canonical surface |
|
||||
| Execution owner (daemon or relay) | Atomically claim-or-spawn, prove liveness, and recover live claims from listings |
|
||||
|
||||
The execution owner is the lowest process that can atomically answer “is there
|
||||
already a live PTY for this agent identity?” Keeping the registry there closes
|
||||
the race between multiple runtime calls. The controller also keeps a registry
|
||||
above providers so separate local/SSH routes cannot independently claim the
|
||||
same identity.
|
||||
|
||||
## Structured requests
|
||||
|
||||
### Explicit resume
|
||||
|
||||
`terminal.ensureAgentSession` accepts only a supported agent and normalized
|
||||
provider identity:
|
||||
|
||||
```ts
|
||||
{
|
||||
kind: 'explicit'
|
||||
worktree: string
|
||||
agent: ResumableTuiAgent
|
||||
providerSession: {
|
||||
key: 'session_id' | 'conversation_id'
|
||||
id: string
|
||||
transcriptPath?: string
|
||||
}
|
||||
agentArgs?: string | null
|
||||
launchPreferences?: { model?: string; effort?: string; mode?: string }
|
||||
presentation?: 'focused' | 'background'
|
||||
placement?: { tabId?: string; leafId?: string }
|
||||
}
|
||||
```
|
||||
|
||||
The host canonicalizes the provider identity, binds it to the execution
|
||||
namespace and canonical worktree, and signs a digest claim. Raw resume commands
|
||||
do not cross a claim-capable boundary; compatibility-selected legacy and
|
||||
unverified nested SSH paths retain their prior opaque command behavior.
|
||||
|
||||
The execution owner performs one atomic operation:
|
||||
|
||||
```text
|
||||
claim absent -> reserve -> spawn -> publish live owner -> created
|
||||
claim live -> prove PTY liveness -> return canonical owner -> adopted
|
||||
claim unknown -> fail closed; do not spawn
|
||||
claim conflict -> fail closed; do not spawn
|
||||
```
|
||||
|
||||
Only an adopted owner may override the requested tab, leaf, handle, or PTY ID.
|
||||
A fresh provider result must match the surface requested by the host.
|
||||
|
||||
### Fresh launch
|
||||
|
||||
`terminal.createAgentSession` accepts structured agent, prompt-delivery mode,
|
||||
launch preferences, optional explicit agent arguments, and a cryptographically
|
||||
random client operation ID. Draft prompts remain drafts; submitted prompts use
|
||||
the normal startup-delivery path. Omitted agent arguments preserve host
|
||||
defaults, while an explicit string is preserved as a client override and an
|
||||
explicit null/empty value clears host argument defaults. Free-form client
|
||||
environment variables are deliberately not accepted because PATH, loaders, and
|
||||
other process authority remain host-owned.
|
||||
|
||||
The runtime reserves the caller-scoped operation before any asynchronous
|
||||
workspace or capability preflight, then fingerprints the host-resolved request
|
||||
under the authenticated device identity:
|
||||
|
||||
- same caller + operation ID + same fingerprint returns `replayed`;
|
||||
- same caller + operation ID + different fingerprint fails;
|
||||
- malformed, future-dated, expired, or over-capacity operations fail closed.
|
||||
|
||||
The operation ledger is memory-bound and retained for 24 hours. Pre-spawn
|
||||
failures release the entry for a safe retry. Once PTY creation commits, or the
|
||||
provider reports an unknown physical outcome, the same rejected promise remains
|
||||
as the replay fence. This handles response loss and ordinary reconnects to the
|
||||
same running host. It does not claim exactly-once creation after the runtime
|
||||
process itself restarts.
|
||||
|
||||
Physical commit is the native-spawn boundary, not listener registration or
|
||||
surface publication. The in-process provider reports it immediately after
|
||||
`node-pty` returns; daemon and relay paths report it when their lower owner
|
||||
returns from spawn/create-or-attach. Commit reporting is one-shot across these
|
||||
layers. Any later error retains the operation fence because the PTY may already
|
||||
exist even if publication failed.
|
||||
|
||||
The runtime derives the execution-operation ID, tab ID, leaf ID, and terminal
|
||||
handle deterministically from the authenticated operation. A daemon-backed
|
||||
spawn derives a legacy-length session ID from that execution operation, so
|
||||
`createOrAttach` returns the same PTY after a lost response without shrinking
|
||||
the accepted worktree-ID boundary or skipping first-spawn setup. An SSH
|
||||
provider performs a bounded read-only relay probe before structured work:
|
||||
|
||||
- a relay advertising `agentSessionCreateOperationVersion: 1` receives the
|
||||
operation ID and replays one successful spawn result for 24 hours;
|
||||
- an older, malformed, or temporarily unreachable relay makes the host return
|
||||
`agent_session_legacy_required`, after which the client sends its unchanged
|
||||
legacy payload;
|
||||
- negative relay capability results are not pinned, so an in-place upgrade is
|
||||
observed on the next request.
|
||||
|
||||
Relay operation-owned PTYs survive stale request contexts so the retry can
|
||||
recover the same PTY and incarnation. Ordinary stale shell spawns keep the
|
||||
existing cleanup behavior.
|
||||
|
||||
## Claim identity
|
||||
|
||||
The claim contains no raw provider session ID. A host-only signer hashes:
|
||||
|
||||
- normalized agent/provider identity;
|
||||
- canonical worktree scope;
|
||||
- execution machine and principal;
|
||||
- container/runtime namespace;
|
||||
- a conservative provider-root bucket. The v1 implementation deliberately
|
||||
merges account roots for an agent, which can produce a safe conflict but
|
||||
cannot authorize duplicate execution.
|
||||
|
||||
The wire binding includes a key ID, digest version, identity digest, worktree
|
||||
scope digest, and agent kind. Owner state adds a random generation, PTY ID, and
|
||||
canonical surface.
|
||||
|
||||
Generation and PTY-incarnation guards prevent a late exit or liveness result
|
||||
from releasing, retiring, or adopting a replacement owner that reused the same
|
||||
PTY ID.
|
||||
|
||||
## Recovery and failure semantics
|
||||
|
||||
Before every claimed ensure, the controller stages complete listings from local
|
||||
and registered SSH providers, validates every owner, and atomically replaces
|
||||
the authoritative portion of its registry. Absent owners are pruned only for
|
||||
providers whose listing is authoritative; disconnected scopes retain their
|
||||
fence. Active reservations survive reconciliation. Valid metadata also rebuilds
|
||||
PTY-to-provider routing.
|
||||
|
||||
Controller-owned in-process fallback claims are intentionally not serialized
|
||||
in ordinary local process listings. Their listing absence is therefore not
|
||||
authoritative: the controller keeps the claim while the exact PTY incarnation
|
||||
remains listed and releases it through the normal exit path. Daemon routers and
|
||||
degraded providers likewise advertise listing authority only for a proven
|
||||
PTY-to-provider route; an unknown ID never falls through to an unrelated
|
||||
current/fallback provider for this decision.
|
||||
|
||||
Recovery is fail closed:
|
||||
|
||||
- owner PTY differs from the listed session: `agent_session_ownership_unknown`;
|
||||
- two listings disagree about an identity or generation:
|
||||
`agent_session_conflict`;
|
||||
- the recorded provider is disconnected or unregistered:
|
||||
`execution_owner_unavailable`;
|
||||
- a claim-bearing spawn reaches a daemon/relay without execution-owner claim
|
||||
protocol v2 (including PTY incarnation proof):
|
||||
`agent_session_claim_unavailable`. Nested SSH routes that cannot construct a
|
||||
claim are selected into legacy behavior before this boundary.
|
||||
|
||||
Unknown liveness never means dead. A transient relay outage therefore retains
|
||||
the claim and cannot authorize a replacement agent.
|
||||
|
||||
Daemon adoption is attach-only. If the owner exits between liveness proof and
|
||||
attach, the request fails rather than falling through to a new unclaimed shell.
|
||||
|
||||
Serialized relay shell state intentionally omits provider claims. Spawn-based
|
||||
revival creates a new shell and cannot inherit authority from the old process.
|
||||
|
||||
## Renderer behavior
|
||||
|
||||
Runtime-owned worktrees queue cached resume evidence through the same mounted
|
||||
pane transport regardless of capability-cache timing. A capable host adopts or
|
||||
creates one canonical owner; an old host or execution owner receives the exact
|
||||
legacy launch. A cold or expired cache therefore cannot bypass authority or
|
||||
remove the pre-change workflow.
|
||||
|
||||
AI Vault resumes use provider metadata for agents with a structured identity,
|
||||
including Antigravity conversation IDs and Pi transcript/session paths. If
|
||||
metadata or host capability is absent, Orca preserves the prior opaque legacy
|
||||
resume request instead of blocking the user.
|
||||
|
||||
Background launches, quick launches, and mounted remote panes use
|
||||
`terminal.createAgentSession` on capable hosts. Otherwise each call site sends
|
||||
the exact pre-change `terminal.create` or `session.tabs.createTerminal` payload.
|
||||
The common router calls legacy after only these safe outcomes: the host capability
|
||||
is unavailable before dispatch; the structured RPC returns the stable
|
||||
pre-side-effect `agent_session_legacy_required` code; or a replaced old host
|
||||
returns `method_not_found`, proving it never recognized the structured request.
|
||||
Timeouts, malformed results, and every other structured error never downgrade.
|
||||
|
||||
Structured create/ensure responses record an exact
|
||||
environment/worktree/provisional-tab to canonical-host-tab handoff. Snapshot
|
||||
reconciliation removes a provisional pane only when its requested tab ID is
|
||||
mirrored or that explicit handoff points to a host tab in the snapshot; agent
|
||||
kind alone is never identity. This prevents an unrelated Claude/Codex session
|
||||
from deleting a same-agent automatic-resume pane. The matched pane's pending
|
||||
startup and automatic-resume claim are removed atomically, and the client
|
||||
re-accepts the current host snapshot in case it arrived before the response.
|
||||
|
||||
Every structured result is host-owned. If snapshot handoff destroys the
|
||||
provisional transport while create/ensure is in flight, late completion cannot
|
||||
close the canonical PTY even when reconciliation is still catching up.
|
||||
|
||||
After the host accepts creation, a later tab-move or snapshot-refresh failure
|
||||
still returns `created`. Reporting the launch as failed would invite a retry
|
||||
with a new operation ID and could duplicate the fresh agent.
|
||||
|
||||
## Exit and persistence lifecycle
|
||||
|
||||
PTY exit is terminal authority. A generic persisted `sleeping` row is not a
|
||||
reason to preserve a surface. Only an exact, runtime-owned stop transaction may
|
||||
temporarily preserve the intentional handle-less surface. Otherwise the
|
||||
runtime:
|
||||
|
||||
1. verifies the PTY incarnation and identifies the exact worktree/tab/leaf;
|
||||
2. removes that leaf from the host snapshot;
|
||||
3. removes an empty parent tab;
|
||||
4. repairs split groups, active group/tab, recent order, and layout;
|
||||
5. removes the terminal binding from the persisted host workspace session and
|
||||
advances that repo's host topology revision;
|
||||
6. synchronously flushes that retirement before publishing the in-memory
|
||||
absence;
|
||||
7. rebases later renderer writes onto the host's current terminal membership,
|
||||
so metadata and layout edits remain writable but missing/live panes cannot
|
||||
be added or removed by a stale client.
|
||||
|
||||
The durable fence is one monotonic revision per affected repo, not one record
|
||||
per historical close or deleted worktree. Its storage is therefore proportional
|
||||
to repos plus current terminal surfaces. A real host-admitted spawn advances
|
||||
the revision when it adds a tab or leaf, allowing fresh terminals after a
|
||||
retirement while an older renderer snapshot remains unable to revive the old
|
||||
surface. Legacy per-pane tombstones are accepted for mixed-version recovery
|
||||
and collapsed into the repo revision on the next normalized write.
|
||||
The revision remains private to each execution host: renderer hydration and
|
||||
writes omit it, avoiding collisions when different hosts contain the same repo
|
||||
ID. Each host preserves the revision while rebasing client session writes.
|
||||
|
||||
An exit can also beat initial terminal registration. The runtime records that
|
||||
PTY/incarnation before any surface exists, rejects registration of the same or
|
||||
unproven incarnation before mutating provider/output sequence, execution
|
||||
context, ownership, lease, binding, handle, terminal, or tab state. The native
|
||||
callback or successful lower-owner return still reports physical-spawn commit
|
||||
before this admission check so a lost provider response cannot authorize a
|
||||
second fresh agent. A proven different incarnation, or an explicit new local
|
||||
lifecycle for a provider that cannot report incarnation identity, clears the
|
||||
fence. When registration rejects the recorded incarnation, that specific
|
||||
caller's fence is released after rejection so repeated early-exit failures do
|
||||
not accumulate process memory.
|
||||
|
||||
Registration intent is explicit: the controller marks the expected PTY before
|
||||
dispatch and clears that intent on every success or failure path. Surface
|
||||
absence is never treated as evidence that registration is still in flight.
|
||||
SSH and daemon providers also settle an attach/create response against any exit
|
||||
that arrived in the same transport batch before returning control upward. This
|
||||
keeps response/exit ordering and incarnation comparison at the layer that can
|
||||
observe both events.
|
||||
|
||||
“Explicitly killed” is treated as a normal terminal-gone lifecycle outcome in
|
||||
the remote transport, not as an unexpected product-error toast.
|
||||
|
||||
## Protocol and compatibility
|
||||
|
||||
The runtime protocol remains v3, with minimum compatible client and server v2.
|
||||
This change adds optional RPCs and fields, so a protocol fence would make a
|
||||
rolling upgrade worse without providing an authorization boundary. The runtime
|
||||
advertises `agent-session.host-authority.v1`; clients negotiate that capability
|
||||
before choosing a launch path.
|
||||
|
||||
| Client | Host | Result |
|
||||
| ------ | ---- | -------------------------------------------------------------------------------------------------------- |
|
||||
| New | New | Structured authority is enabled when the resolved execution owner also supports it. |
|
||||
| New | Old | The client selects legacy before spawn, or falls back on safe `method_not_found`; behavior is unchanged. |
|
||||
| Old | New | The host still accepts legacy agent-bearing terminal creates; behavior is unchanged. |
|
||||
| Old | Old | Unchanged legacy behavior. |
|
||||
|
||||
Capability probing is read-only. A transient probe failure may select legacy,
|
||||
because no structured side effect has started. A real protocol compatibility
|
||||
block is still surfaced and never bypassed. A capable host then checks the
|
||||
resolved daemon or relay. Only `agent_session_legacy_required`, emitted before
|
||||
trust, claim, spawn, or any retained replay fence, permits legacy; every later error stays on
|
||||
the structured path. The other post-dispatch exception is `method_not_found`
|
||||
from an old host, which proves the method could not have started. Host and
|
||||
lower-owner unsupported verdicts are not pinned, and observing a new runtime ID
|
||||
invalidates a predecessor's positive verdict, so rolling upgrades and process
|
||||
replacement re-probe promptly. The SSH probe is bounded below the client RPC
|
||||
timeout, concurrent callers have independent cancellation, successful
|
||||
structured creates require PTY and incarnation identity, and request
|
||||
cancellation is checked at the real provider seams: after asynchronous
|
||||
capability/connection preflight and immediately before local native spawn,
|
||||
daemon `createOrAttach`, or SSH `pty.spawn`. Once SSH dispatch begins, an
|
||||
operation failure is treated as an unknown physical outcome rather than a safe
|
||||
fresh retry.
|
||||
|
||||
The same monotonic rule applies below the runtime:
|
||||
|
||||
| Runtime/controller | Execution owner | Result |
|
||||
| ------------------ | ---------------- | ------------------------------------------------------------------------------------------------------------- |
|
||||
| New | New daemon | Stable operation-derived session ID makes retry attach to the same PTY. |
|
||||
| New | Old daemon | The host returns `legacy_required` before side effects; the client sends its exact old resume/create request. |
|
||||
| New | New relay | Relay operation ledger replays the same PTY and incarnation. |
|
||||
| New | Old relay | The host returns `legacy_required` before side effects; the client sends its exact old spawn request. |
|
||||
| Old | New daemon/relay | New optional fields are absent, so pre-change behavior is unchanged. |
|
||||
|
||||
This contract is monotonic: upgrading any subset never removes a workflow that
|
||||
worked before. The bug fix activates only where every authority layer required
|
||||
for that specific path can prove support.
|
||||
|
||||
## Deterministic reproduction harness
|
||||
|
||||
Run:
|
||||
|
||||
```sh
|
||||
pnpm test:repro:remote-agent-session
|
||||
```
|
||||
|
||||
The harness builds Orca, starts a real headless Electron `orca serve` process on
|
||||
an ephemeral port, and connects independent Node client processes over the
|
||||
normal encrypted WebSocket pairing path. It creates and registers a real Git
|
||||
repository in an isolated profile and uses the real daemon claim registry with
|
||||
a controlled agent subprocess. No installed agent, external service, fixed
|
||||
port, timing race, or Docker daemon is needed.
|
||||
|
||||
It asserts:
|
||||
|
||||
- two clients race the same structured resume;
|
||||
- exactly one daemon subprocess is spawned;
|
||||
- both clients receive the same canonical handle, tab, pane, and PTY;
|
||||
- a retry that may have lost its earlier response adopts that owner;
|
||||
- a real `terminal.close` produces PTY exit and both `terminal.list` and
|
||||
`session.tabs.list` omit the surface;
|
||||
- a stale layout publication cannot recreate the retired surface;
|
||||
- restarting the serve process with the same profile cannot resurrect the
|
||||
terminal or tab.
|
||||
|
||||
Lower-level tests separately cover daemon attach races, controller recovery,
|
||||
provider disconnects, conflicting listings, old SSH relays, malformed SSH
|
||||
claim results, cancellation at physical provider seams, pre-publication native
|
||||
spawn failures, exact provisional handoff, early exit before registration, and
|
||||
exit-driven durable retirement.
|
||||
|
||||
## Future extensions
|
||||
|
||||
### Host-owned automatic sleep checkpoints
|
||||
|
||||
Automatic remote sleep/resume should be added only as a host transaction:
|
||||
|
||||
1. persist a random, generation-bound checkpoint before stopping;
|
||||
2. publish a non-connectable transition state;
|
||||
3. stop and verify the exact owner;
|
||||
4. commit sleeping state only after the owner is gone;
|
||||
5. consume the checkpoint atomically during ensure.
|
||||
|
||||
Until this exists, renderer-local records may trigger resume intent but cannot
|
||||
authorize a second owner on a claim-capable route. Compatibility-selected
|
||||
legacy mode keeps the pre-change behavior.
|
||||
|
||||
### Durable fresh-operation journal
|
||||
|
||||
If fresh-launch exactly-once behavior must survive runtime restart, replace the
|
||||
memory ledger with a profile-scoped durable journal. It must persist the caller,
|
||||
operation ID, request fingerprint, canonical result/tombstone, and retention
|
||||
deadline before returning success. Capacity must reject rather than evict an
|
||||
unexpired tombstone.
|
||||
|
||||
### Verified SSH execution namespaces
|
||||
|
||||
Direct or nested SSH agent-session authority requires relay-attested machine,
|
||||
principal, container, and provider-root identity plus a separately versioned
|
||||
claim capability. Connection labels or target aliases are not proof. Until
|
||||
that attestation exists, the host requests exact legacy fallback before spawn;
|
||||
v1 does not claim deduplication for that route.
|
||||
|
||||
### Multi-process coordination
|
||||
|
||||
Supporting multiple Orca main processes against one profile requires an
|
||||
OS-held coordinator lease around claim and journal mutation. The current v1
|
||||
contract coordinates clients of one runtime/controller process and its daemon
|
||||
or registered relays.
|
||||
@@ -1,54 +0,0 @@
|
||||
# Resource Manager memory metrics
|
||||
|
||||
Resource Manager reports two different kinds of memory data. Process totals describe Orca and
|
||||
locally managed terminal processes; host totals describe the machine running Orca. They are not
|
||||
interchangeable.
|
||||
|
||||
## Process memory
|
||||
|
||||
Each snapshot declares one `processMemoryMetric`:
|
||||
|
||||
| Platform | Metric | Source |
|
||||
| ------------ | ------------- | ---------------------------------------------------------- |
|
||||
| macOS, Linux | `rss` | `ps` resident set size |
|
||||
| Windows | `working-set` | CIM `WorkingSetSize`, with a Typeperf working-set fallback |
|
||||
|
||||
Orca walks each registered local PTY subtree and claims every PID at most once. App, session,
|
||||
worktree, history, and snapshot memory values are sums of those per-process samples.
|
||||
|
||||
RSS and working set are not unique physical-memory measurements. Shared pages can appear in more
|
||||
than one process, and macOS can count the same resident page through multiple mappings in one
|
||||
process. A sum can therefore exceed physical RAM. Product copy and diagnostics must identify the
|
||||
metric as a sum and must not present it as a percentage of system RAM.
|
||||
|
||||
Remote SSH and relay sessions do not receive invented local samples. They remain unavailable until
|
||||
the executing host supplies resource data. Folder workspaces use the same registered-PTY
|
||||
attribution as Git worktrees.
|
||||
|
||||
## Host memory
|
||||
|
||||
`HostMemory` keeps immediate free memory separate from memory available without material pressure:
|
||||
|
||||
- `freeMemory` is Node's host free-memory value.
|
||||
- `availableMemory` is the best bounded platform value.
|
||||
- `usedMemory` is `totalMemory - availableMemory`.
|
||||
- `memoryUsagePercent` is derived from `usedMemory`.
|
||||
- `availableMemorySource` identifies how availability was measured.
|
||||
|
||||
The sources are:
|
||||
|
||||
| Platform | Preferred source | Fallback |
|
||||
| -------- | ----------------------------------------- | ---------------- |
|
||||
| macOS | `memory_pressure -Q` available percentage | Node free memory |
|
||||
| Linux | `/proc/meminfo` `MemAvailable` | Node free memory |
|
||||
| Windows | Node free memory | Node free memory |
|
||||
|
||||
This percentage describes host availability. It is not derived from the summed process metric.
|
||||
|
||||
## Bounded collection
|
||||
|
||||
Resource Manager polls while its popover is open, so every snapshot must remain bounded under a
|
||||
large process tree. macOS `footprint` provides a more physical process metric, but collecting it
|
||||
across dozens of processes is too expensive for this path. A future physical-footprint backend
|
||||
must use a bounded host API or helper and declare a distinct metric before product copy treats it
|
||||
as physical memory.
|
||||
@@ -1,138 +0,0 @@
|
||||
# Refresh GitHub Issues After Create
|
||||
|
||||
## Problem
|
||||
|
||||
Issue https://github.com/stablyai/orca-internal/issues/101 reports that the GitHub issues list can stay stale after creating a new issue.
|
||||
|
||||
- `src/renderer/src/components/TaskPage.tsx:3891` bumps `taskRefreshNonce` after successful issue creation, intending to refetch the list.
|
||||
- `src/renderer/src/store/slices/github.ts:1644` honors `force` only for the renderer cache and in-flight dedupe.
|
||||
- `src/renderer/src/store/slices/github.ts:1666` calls `window.api.gh.listWorkItems` without telling main to bypass the GitHub CLI cache.
|
||||
- `src/main/github/client.ts:821` and `src/main/github/client.ts:846` use `gh api --cache 120s` for the recent issues and PR REST paths, so a forced renderer refresh can still receive a pre-create response for up to two minutes.
|
||||
- `src/main/runtime/rpc/methods/github.ts:10` and `src/main/runtime/rpc/methods/github.ts:283` do not accept or forward a cache-bypass flag for SSH/runtime clients.
|
||||
|
||||
## Root Cause
|
||||
|
||||
The post-create flow forces only Orca's renderer-side work-item cache. It does not bypass the GitHub CLI REST cache used by the main-process recent work-item fetch, so the refreshed request can reuse stale `gh api --cache 120s` data.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Replace normal list caching or reduce default cache TTLs.
|
||||
- Change query/search filtering behavior.
|
||||
- Change GitLab, Linear, project view, or PR detail caches.
|
||||
- Add polling after issue creation.
|
||||
- Add new UI controls or visible copy.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add an optional `noCache` flag to the renderer work-item fetch options and the GitHub work-items list contract:
|
||||
- `FetchOptions` in `src/renderer/src/store/slices/github.ts`;
|
||||
- preload API type and implementation for `gh.listWorkItems`;
|
||||
- IPC handler args for `gh:listWorkItems`;
|
||||
- web preload routing, which forwards `gh.listWorkItems` to `github.listWorkItems` for web/remote clients;
|
||||
- runtime RPC schema and handler for `github.listWorkItems`;
|
||||
- `OrcaRuntime.listRepoWorkItems`;
|
||||
- `listWorkItems` and the internal recent-list helper in `src/main/github/client.ts`.
|
||||
|
||||
2. Keep `force` and `noCache` separate. `force` means "bypass renderer cache and in-flight dedupe"; `noCache` means "bypass `gh api --cache`". In TaskPage, pass `{ force: forcedFetch || shouldProbeOnLanding, noCache: forcedFetch }` so nonce-triggered refreshes and preference invalidation bypass the GitHub CLI cache, while the one-time landing probe still behaves like today's background revalidation. Today `taskRefreshNonce` is shared by create, manual refresh, retry, filtering, preset changes, and PR merge refresh, so the implementation should either accept that whole nonce-triggered set as the no-cache scope or split create/manual refresh intent into a separate signal before narrowing it.
|
||||
|
||||
3. When `fetchWorkItems(..., { noCache: true })` calls `window.api.gh.listWorkItems`, pass `noCache: true`; otherwise omit it or pass `false`.
|
||||
|
||||
4. Track `noCache` alongside `force` in `inflightWorkItemsRequests`. A request with `noCache: true` must not dedupe onto an existing request with `noCache: false`, even if that existing request is forced; wait for the existing request to settle and issue a fresh no-cache request. This preserves the create path when it races a landing probe, which is `force: true` but intentionally cacheable.
|
||||
|
||||
5. In `listRecentWorkItems`, build REST args with `[]` when `noCache` is true and `['--cache', '120s']` otherwise. Apply this only to the REST `gh api` issue/PR list calls that currently use the cache. Keep fallback `gh issue list` / `gh pr list` and queried paths unchanged because they do not use this REST cache.
|
||||
|
||||
6. Preserve current force semantics:
|
||||
- non-forced loads keep using the 120-second CLI cache;
|
||||
- forced loads still wait out non-forced in-flight requests before issuing a fresh request;
|
||||
- no-cache loads also wait out cacheable in-flight requests before issuing a fresh request;
|
||||
- force continues to refresh all selected repos through the existing TaskPage effect.
|
||||
|
||||
7. Add regression coverage:
|
||||
- renderer store: `force + noCache` sends `noCache: true`; `force` without `noCache` and non-force calls omit it;
|
||||
- renderer store: `force + noCache` does not dedupe onto an in-flight `force` request that lacks `noCache`;
|
||||
- TaskPage or a focused equivalent: post-create/manual nonce path sets `noCache`, but landing probe does not;
|
||||
- desktop IPC: `gh:listWorkItems` forwards `noCache`;
|
||||
- web preload: `gh.listWorkItems` forwards `noCache` through the runtime route;
|
||||
- main GitHub client: `listWorkItems(..., { noCache: true })` omits `--cache 120s` on recent REST issue/PR calls;
|
||||
- runtime RPC: `github.listWorkItems` accepts and forwards `noCache`.
|
||||
|
||||
## Data Flow
|
||||
|
||||
- User creates GitHub issue in Tasks.
|
||||
- `handleCreateNewIssue` bumps `taskRefreshNonce`.
|
||||
- TaskPage effect computes `forcedFetch=true`.
|
||||
- `fetchWorkItemsAcrossRepos` calls `fetchWorkItems` with `{ force: true, noCache: true }` for the nonce-triggered refresh.
|
||||
- `fetchWorkItems` bypasses renderer cache and, when `noCache` is set, calls `gh.listWorkItems({ noCache: true })`.
|
||||
- Desktop IPC or runtime RPC forwards `noCache`.
|
||||
- `listRecentWorkItems` omits `gh api --cache 120s` for that fetch.
|
||||
- GitHub returns a fresh recent issue list; cache is repopulated with the new issue.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- Multiple selected repos: all selected repos refresh through the existing fan-out; `noCache` applies only to `forcedFetch`, not the landing probe.
|
||||
- Fork/upstream issue source: source resolution stays unchanged, and the cache bypass applies to whichever source is selected.
|
||||
- SSH/runtime repo: runtime RPC accepts and forwards `noCache`, so remote clients do not retain the stale-cache bug.
|
||||
- In-flight non-forced request: existing force logic waits for the stale request to settle, then issues a fresh no-cache request.
|
||||
- In-flight forced landing probe: a nonce-triggered no-cache request must not dedupe onto the cacheable landing probe; otherwise create can still repaint from `gh api --cache 120s`.
|
||||
- One-time landing probe: it still uses `force` to bypass renderer freshness, but must not set `noCache`; otherwise merely opening Tasks with cached rows would spend uncached GitHub API requests.
|
||||
- Search query active: queried paths already use `gh issue list` / `gh pr list` rather than cached REST calls, so no behavior change is required.
|
||||
- Pagination: next-page fetches use queried/cursor paths and do not populate the renderer work-items cache, so `noCache` is page-0-only.
|
||||
- Concurrent windows: the creating window refreshes immediately; other renderer windows keep their own cache until their next refresh, landing probe, or TTL expiry. This change should not introduce cross-window invalidation.
|
||||
- External GitHub mutations: external issue changes still rely on existing TTL/manual refresh behavior; this fix only guarantees freshness for Orca-originated create flows.
|
||||
- Network/auth errors: existing partial-failure handling and banners remain unchanged.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- Unit: extend `src/renderer/src/store/slices/github.test.ts` or add focused coverage for `fetchWorkItems` `force`/`noCache` IPC args and the no-cache-vs-cacheable-in-flight dedupe case.
|
||||
- Unit: cover the TaskPage nonce path or isolate the option computation so nonce-triggered refreshes set `noCache` and the landing probe does not. If implementation narrows no-cache to a new create/manual-refresh signal, cover that narrower signal explicitly.
|
||||
- Unit: extend `src/main/ipc/github.test.ts` to assert `gh:listWorkItems` forwards `noCache` to the client.
|
||||
- Unit: extend `src/renderer/src/web/web-preload-api.test.ts` to assert web/remote `gh.listWorkItems` preserves `noCache`.
|
||||
- Unit: extend `src/main/github/client-issue-source.test.ts` or `src/main/github/client-work-items.test.ts` to assert recent no-cache requests omit `--cache 120s` while normal recent requests keep it.
|
||||
- Unit: extend `src/main/runtime/rpc/methods/github.test.ts` and/or `src/main/runtime/orca-runtime.test.ts` for `noCache` schema/forwarding.
|
||||
- Typecheck: `pnpm typecheck`.
|
||||
- Lint: `pnpm lint`.
|
||||
- Electron validation: create an issue only in a throwaway/test repo if available; otherwise validate the refresh behavior with mocked/local unit tests and capture the Tasks issue list state without mutating live data.
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
Not UI-visible. The existing issue list UI and create-issue dialog should look unchanged; only freshness after a forced refresh changes.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
1. GitHub Tasks issue list after refresh/create path is reachable.
|
||||
2. Create issue dialog before submission, if validation can use a throwaway repo.
|
||||
3. Post-create issue detail/list state, only if validation can use a throwaway repo without mutating live user data.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add `noCache` to renderer fetch options plus shared/preload/web/runtime IPC contracts.
|
||||
2. Thread `noCache` through web routing, runtime, and desktop main-process handlers.
|
||||
3. Apply `noCache` to the recent REST work-item list args.
|
||||
4. Pass `noCache` from nonce-triggered renderer work-item fetches, but not landing probes.
|
||||
5. Add regression tests.
|
||||
6. Run typecheck, lint, and focused tests.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: reduced to force-refresh cache bypass for the existing work-item list path; no polling, UI changes, or TTL changes.
|
||||
- Architecture/data flow: the renderer already owns refresh intent, while main owns GitHub CLI args. Thread `noCache` as explicit request metadata across preload, web preload, desktop IPC, runtime RPC, and SSH-aware runtime methods; do not infer it from every `force` call because landing probes also use `force`.
|
||||
- Failure modes covered:
|
||||
- stale `gh api --cache 120s` response after create;
|
||||
- forced fetch deduping onto a non-forced in-flight request;
|
||||
- runtime/SSH clients lacking the cache-bypass argument;
|
||||
- upstream/origin issue-source selection still resolving before fetch;
|
||||
- queried path accidentally changing despite not using REST cache.
|
||||
- Test coverage required:
|
||||
- renderer store IPC args for `force`/`noCache` combinations;
|
||||
- TaskPage option computation for nonce-triggered refresh vs landing probe;
|
||||
- desktop IPC and web preload forwarding;
|
||||
- main GitHub client recent-list REST args with and without `noCache`;
|
||||
- runtime RPC schema/handler forwarding `noCache`;
|
||||
- focused typecheck/lint.
|
||||
- Performance/blast radius: low when `noCache` is limited to nonce-triggered refreshes and preference invalidation. Normal loads and landing probes keep the CLI cache; the no-cache path doubles the fresh REST calls for repos that have both issue and PR sources, so avoid broadening it to every renderer `force`.
|
||||
- UI quality bar: not UI-visible; UI should remain unchanged apart from fresher rows.
|
||||
- Required review screenshots:
|
||||
1. Tasks GitHub issues list reachable after implementation.
|
||||
2. Create issue dialog reachable, if a throwaway repo is available.
|
||||
3. Post-create or post-refresh list state, if validation can avoid mutating live data.
|
||||
- Residual risks: validating the actual create flow may be skipped unless a safe throwaway GitHub repo is available; cross-window freshness and external GitHub mutations remain bounded by existing refresh/TTL behavior.
|
||||
@@ -1,108 +0,0 @@
|
||||
# Remote Web Paste And Activity Fixes
|
||||
|
||||
## Problem
|
||||
|
||||
- Paired browser image paste reads a clipboard image in `src/renderer/src/web/web-preload-api.ts:120`, converts it to PNG base64, and sends the whole string through `clipboard.saveImageAsTempFile` at `src/renderer/src/web/web-preload-api.ts:1613`. `src/main/runtime/rpc/ws-transport.ts` sets `maxPayload` to 1 MiB, and the browser RPC client encrypts JSON requests into base64 text frames. A screenshot well below the existing 24 MiB clipboard schema limit can still exceed the encrypted WebSocket frame cap and close the socket as `Remote Orca runtime connection interrupted`.
|
||||
- Paired browser workspace activity is inflated. `src/renderer/src/lib/worktree-status.ts` and `src/renderer/src/lib/worktree-activity-state.ts` currently treat any mirrored web terminal surface ID as active, even when `src/renderer/src/runtime/web-session-tabs-sync.ts` only has a pending host terminal with no ready PTY handle.
|
||||
|
||||
## Root Cause
|
||||
|
||||
- The clipboard RPC accepts up to 24 MiB of base64 in `src/main/runtime/rpc/methods/clipboard.ts`, but the web transport limit applies before the server can validate RPC params. Because the web client encrypts JSON and base64-encodes the encrypted bytes, the safe plaintext chunk is materially smaller than 1 MiB. The existing 512 KiB file-upload chunk size in `src/renderer/src/runtime/runtime-file-client.ts` is safe after JSON plus encryption expansion; a chunk close to 1 MiB is not.
|
||||
- The file-upload RPCs cannot be reused directly. They write worktree-relative files and then commit a rename; clipboard paste must call `saveClipboardImageBufferAsTempFile`, return a local or SSH temp path, and preserve the terminal repo's `connectionId`.
|
||||
- Web session-tab sync intentionally mirrors pending host terminal surfaces so the tab model stays in parity, but it writes `ptyIdsByTabId[mirroredTabId]` only from `status: "ready"` surfaces. The status/filter helpers then bypass that liveness map with `isWebTerminalSurfaceTabId`, so pending mirrors look active.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Do not raise the global WebSocket `maxPayload`; it protects all runtime traffic, including pre-auth and mobile sockets.
|
||||
- Do not change sidebar grouping, labels, counts, pairing flow, terminal UI, or clipboard permission UI.
|
||||
- Do not change local Electron clipboard behavior or the existing one-shot RPC contract.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add bounded chunked clipboard-image RPCs.
|
||||
- Keep `clipboard.saveImageAsTempFile` for small/old clients.
|
||||
- Add `clipboard.startImageUpload`, `clipboard.appendImageUploadChunk`, `clipboard.commitImageUpload`, and `clipboard.abortImageUpload`.
|
||||
- `start` takes `expectedBase64Length` and `connectionId`, rejects values over the existing 24 MiB base64 limit, records the target connection, and returns an unguessable upload ID.
|
||||
- `append` takes `uploadId`, `offset`, and `contentBase64`; reject unknown IDs, out-of-order offsets, chunks above 512 KiB, invalid base64 characters, and cumulative length beyond `expectedBase64Length`.
|
||||
- `commit` verifies the received length equals `expectedBase64Length`, validates the full base64 payload with the same rules as the one-shot RPC, calls `saveClipboardImageBufferAsTempFile` with the recorded `connectionId`, and deletes the upload state in `finally`.
|
||||
- `abort` deletes the upload state and is idempotent.
|
||||
- Bound server memory with a small max concurrent upload count and a TTL cleanup for abandoned uploads. Upload state is process-local; reconnects restart the paste instead of resuming.
|
||||
|
||||
2. Switch paired browser image paste to the chunked path.
|
||||
- After `navigator.clipboard.read()` and PNG conversion, return `null` for no image as today.
|
||||
- Preflight `contentBase64.length` against the 24 MiB limit before starting an upload.
|
||||
- Send 512 KiB base64 slices. This is below the 1 MiB encrypted frame cap after JSON and E2EE base64 expansion.
|
||||
- Abort best-effort on append or commit failure. If `start` returns `method_not_found`, fall back to `clipboard.saveImageAsTempFile` only when the payload is below a conservative single-frame threshold; never send a large fallback frame.
|
||||
|
||||
3. Tighten workspace activity liveness.
|
||||
- Treat terminal workspaces as active only when `tabHasLivePty(ptyIdsByTabId, tab.id)` is true.
|
||||
- Remove the blanket `isWebTerminalSurfaceTabId` active shortcut from `getWorktreeStatus` and `hasActiveWorkspaceActivity`.
|
||||
- Keep browser tabs active without terminals.
|
||||
- Keep fresh/retained explicit agent rows able to promote status to `permission`, `working`, or `done`; this is separate from terminal liveness.
|
||||
|
||||
## Data Flow
|
||||
|
||||
- Paste image:
|
||||
- Browser paste command -> `navigator.clipboard.read()` -> PNG base64 in web preload memory.
|
||||
- `clipboard.startImageUpload({ expectedBase64Length, connectionId })` -> upload ID.
|
||||
- Repeated `clipboard.appendImageUploadChunk({ uploadId, offset, contentBase64 })`.
|
||||
- `clipboard.commitImageUpload({ uploadId })` -> runtime saves temp image locally or on the SSH target -> terminal receives the temp path.
|
||||
|
||||
- Workspace activity:
|
||||
- Host `session.tabs.listAll` or subscription snapshot includes terminal surfaces.
|
||||
- Web sync mirrors tabs but writes live PTY handles only for ready surfaces.
|
||||
- Sidebar status/filter reads `ptyIdsByTabId` and browser tabs.
|
||||
- Pending mirrored terminals with no PTY remain visible but do not count as active.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- Clipboard has no image or browser lacks `navigator.clipboard.read`: return `null`, no upload session.
|
||||
- Clipboard read/permission/conversion fails: existing terminal paste error path reports the failure; the runtime socket should stay open.
|
||||
- Non-PNG clipboard images may grow during PNG conversion; validate the post-conversion base64 length.
|
||||
- Image exceeds 24 MiB base64: reject before upload and enforce again on the server.
|
||||
- Chunk boundaries must preserve base64 validity; the 512 KiB chunk size is divisible by 4, and the final full payload validation catches padding errors.
|
||||
- Append retry or concurrent append with the same upload ID: offset validation rejects duplicate, skipped, or out-of-order data.
|
||||
- Multiple paired browser clients or windows paste at once: upload IDs isolate sessions and the concurrent-upload cap bounds memory.
|
||||
- Append or commit fails: browser aborts best-effort; server TTL cleans abandoned state.
|
||||
- SSH connection missing or drops during commit: commit fails, upload state is still deleted, and the paste path reports the error.
|
||||
- Runtime restarts during upload: pending RPC fails; no resume is attempted.
|
||||
- Pending host terminal surface later becomes ready: the next snapshot writes PTY handles and the workspace becomes active.
|
||||
- Host closes a terminal or browser tab: the next snapshot removes the mirrored tab and stale PTY/browser handles before activity is recomputed.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- Unit: `src/main/runtime/rpc/methods/clipboard.test.ts` for start/append/commit/abort, offset validation, invalid base64, size limit, TTL cleanup, commit cleanup on save failure, SSH `connectionId` forwarding, and concurrent upload isolation.
|
||||
- Unit: `src/renderer/src/web/web-preload-api.test.ts` for chunk sequencing, 512 KiB max chunks, `method_not_found` small-payload fallback, no large fallback frame, and abort on append/commit failure.
|
||||
- Unit: `src/renderer/src/lib/worktree-status.test.ts` and `src/renderer/src/lib/worktree-activity-state.test.ts` for pending mirrored terminal inactivity, ready mirrored terminal activity, browser-only activity, and explicit agent-row promotion.
|
||||
- Focused run: `pnpm exec vitest run --config config/vitest.config.ts src/main/runtime/rpc/methods/clipboard.test.ts src/renderer/src/web/web-preload-api.test.ts src/renderer/src/lib/worktree-status.test.ts src/renderer/src/lib/worktree-activity-state.test.ts`.
|
||||
- Type/lint: `pnpm typecheck`, `pnpm lint`.
|
||||
- Paired-client validation: restart the host app, pair a real browser client, paste a screenshot large enough that the old one-shot RPC exceeded the 1 MiB encrypted frame cap into a local terminal and an SSH-backed terminal, confirm the runtime socket stays connected, then compare browser and host sidebar activity.
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
No layout changes. The paired browser sidebar should show active dots only for workspaces with live terminal PTYs, browser tabs, or explicit agent rows. Image paste should insert the generated temp image path into the terminal without connection-error toasts or DevTools runtime disconnect errors.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
1. Paired browser sidebar after hydration with inactive Done/Todo workspaces visible but not marked active.
|
||||
2. Paired browser terminal after image paste, showing the generated temp image path inserted.
|
||||
3. Host sidebar for the same session, showing matching active workspace state.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add chunked clipboard RPC implementation and tests.
|
||||
2. Switch web preload image paste to chunked upload and tests.
|
||||
3. Tighten activity/status liveness helpers and tests.
|
||||
4. Run focused tests, typecheck, and lint.
|
||||
5. Validate in a paired Electron/browser session, including SSH paste, and capture the review screenshots.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: narrow to web clipboard transport and activity liveness. No global WebSocket limit, sidebar redesign, or local Electron clipboard changes.
|
||||
- Architecture/data flow: web preload owns browser clipboard read and chunk sequencing; main runtime clipboard RPC owns upload session state and final temp-file save; sidebar helpers stay pure and consume the existing live-PTY map.
|
||||
- Failure modes: oversized images must fail before a large frame is sent; abandoned uploads expire; failed append/commit paths clean up; pending host terminal mirrors do not inflate activity; SSH commit failures do not leak upload state.
|
||||
- Tests: cover RPC lifecycle and bounds, web preload sequencing/fallback/abort, status/filter liveness, and real paired-client paste/sidebar parity.
|
||||
- Performance/blast radius: chunking is not free. A max-size image is dozens of serialized runtime RPC calls and duplicates base64 in browser and main memory. The impact is limited to image paste by TTL, size, and concurrency caps. Activity changes affect sidebar filters, jump palette activity, and status dots.
|
||||
- UI quality: no new chrome. Judge only sidebar parity, paste result, and absence of runtime disconnect/toast regressions.
|
||||
- Screenshots: browser sidebar, browser terminal after paste, and matching host sidebar.
|
||||
- Residual risk: clipboard permission and image conversion behavior are browser-dependent, so paired browser validation is required in addition to unit tests.
|
||||
@@ -1,171 +0,0 @@
|
||||
# Renderer Memory Profile, 2026-06-01
|
||||
|
||||
## Scope
|
||||
|
||||
This profile investigated high Orca renderer memory while working in
|
||||
`/Users/nwparker/orca/workspaces/orca/goal`. The user suspected the browser
|
||||
might not actually have an open tab, so the investigation checked browser,
|
||||
renderer, terminal, and Resource Usage attribution paths separately.
|
||||
|
||||
## Live Evidence
|
||||
|
||||
- Orca runtime was reachable through the packaged CLI fallback. The public
|
||||
`/usr/local/bin/orca` shim pointed at a removed development app path, so it
|
||||
failed before contacting the runtime.
|
||||
- `orca tab list --worktree all --json` returned `tabs: []`. There were no live
|
||||
Orca browser tabs in the measured session.
|
||||
- The live packaged app had one renderer process and no separate browser guest
|
||||
renderer process. A later `ps` sample showed:
|
||||
- main process: 390 MB RSS
|
||||
- renderer process: 460 MB RSS, about 40 percent CPU
|
||||
- GPU process: 145 MB RSS
|
||||
- network service: 59 MB RSS
|
||||
- audio service: 48 MB RSS
|
||||
- `sample` on the renderer showed V8, IPC, and deserialization stacks while the
|
||||
renderer was busy. It did not show browser guest activity.
|
||||
- `vmmap -summary` on the renderer showed about 218 MB physical footprint and a
|
||||
373 MB peak, while total resident accounting was about 1.7 GB. Most of that
|
||||
larger number was shared Electron/Chromium mappings, especially read-only
|
||||
library mappings.
|
||||
- `orca terminal list --worktree active --json` showed the active Codex terminal
|
||||
preview retaining repeated status redraw fragments such as repeated
|
||||
`Working` text. The retained terminal tail buffers were bounded, but the
|
||||
text normalization path was treating redraw controls as append-only text.
|
||||
|
||||
## Findings
|
||||
|
||||
1. Browser tabs were not the live-session memory source. The session had no
|
||||
browser tabs and no browser guest renderer process.
|
||||
2. The browser-pane retention fix is still useful: inactive worktree browser
|
||||
webviews are now unmounted so Chromium can release guest renderers. Browser
|
||||
state remains in Orca, and automation-visible webviews stay mounted so
|
||||
agent-browser can keep driving them.
|
||||
3. Resource Usage was using `app.getAppMetrics().memory.workingSetSize` for
|
||||
Orca app buckets. On macOS this can count large shared Electron/Chromium
|
||||
mappings and make the renderer look much larger than its private footprint.
|
||||
4. The active terminal path was producing noisy previews from TUI redraws. This
|
||||
explains the high active renderer churn observed during the profile, even
|
||||
though the terminal memory buffers were already capped.
|
||||
|
||||
## Changes Made
|
||||
|
||||
- Browser panes now mount their backing webview only when the pane is active or
|
||||
automation-visible. This sleeps inactive worktree browser guest renderers
|
||||
without sleeping the main Orca renderer.
|
||||
- Browser crash breadcrumbs now include webview counts, parked webview counts,
|
||||
hidden webviews, and registered browser guest counts.
|
||||
- The memory collector now prefers the existing host process RSS sweep for
|
||||
Electron app bucket memory, falling back to Electron working-set data only
|
||||
when a host row is missing.
|
||||
- Terminal preview retention now applies carriage-return and backspace redraw
|
||||
controls before appending text to the retained preview tail.
|
||||
|
||||
## Validation
|
||||
|
||||
- Browser overlay, webview registry, and crash diagnostics tests passed.
|
||||
- Browser tab e2e tests passed.
|
||||
- Memory collector tests passed, including host RSS preference and fallback
|
||||
coverage.
|
||||
- Runtime terminal tests passed for carriage-return and backspace redraw
|
||||
normalization, plus the existing bounded partial-tail coverage.
|
||||
|
||||
## Remaining Risk
|
||||
|
||||
The current packaged Orca app was not running this worktree's patched code
|
||||
during the live profile. The fixes are covered by unit and e2e tests, but the
|
||||
next packaged build should be re-profiled under the same active Codex TUI load
|
||||
to confirm the Resource Usage display and terminal previews match the expected
|
||||
lower-churn behavior.
|
||||
|
||||
## Follow-up: CLI Profiling Blocker
|
||||
|
||||
Continuing the profile after this change confirmed the public
|
||||
`/usr/local/bin/orca` command was still broken because it was a regular
|
||||
generated launcher file pointing at a removed development build. The CLI
|
||||
installer previously self-healed stale symlinks, but treated regular files as
|
||||
conflicts. That meant Settings could not replace an Orca-owned stale launcher,
|
||||
forcing profiling to use the packaged CLI fallback.
|
||||
|
||||
The follow-up fix teaches the installer to recognize only generated Orca Unix
|
||||
launcher files as stale and replaceable. Arbitrary regular files at the command
|
||||
path remain conflicts.
|
||||
|
||||
## Follow-up: Repeatable Memory Diagnostics
|
||||
|
||||
The next profiling blocker was repeatability: collecting a useful memory sample
|
||||
still required combining Resource Usage IPC, terminal lists, browser tab state,
|
||||
and host process output by hand. This branch adds `orca diagnostics memory`,
|
||||
which exposes the existing main-process memory collector through runtime RPC.
|
||||
|
||||
The command returns the same `MemorySnapshot` shape used by Resource Usage when
|
||||
run with `--json`, including host memory, Orca app process buckets, worktree
|
||||
terminal memory, per-session process roots, and history samples. Text output
|
||||
prints a compact point-in-time summary and the top worktrees by retained
|
||||
terminal memory.
|
||||
|
||||
## Follow-up: Agent-Browser Paintability Guard
|
||||
|
||||
The browser parking fix depends on automation-visible panes staying paintable
|
||||
without activating the user's worktree. The renderer bridge previously waited
|
||||
for two animation frames before creating the automation visibility lease, so the
|
||||
paint wait happened while the parked webview was still hidden. Non-screenshot
|
||||
agent-browser commands could therefore start immediately after the lease was
|
||||
created, before React had made the hidden pane paintable.
|
||||
|
||||
The follow-up changes the order: create the automation visibility lease first,
|
||||
then wait for paint while the pane is actually visible to automation. A
|
||||
renderer-side timeout releases the lease if paint never arrives, so a hung RAF
|
||||
does not pin an inactive browser pane indefinitely.
|
||||
|
||||
## Follow-up: Browser Registration Readiness
|
||||
|
||||
One remaining automation race was the wake path for parked or restored browser
|
||||
tabs. Runtime browser commands asked the renderer to mount a hidden browser
|
||||
pane, then waited a fixed 500 ms before reading the agent-browser tab registry.
|
||||
On slow webview startup, that could still race `registerGuest` and make
|
||||
agent-browser report no tab even though the tab was in the process of mounting.
|
||||
|
||||
The follow-up extends the existing tab-registration wait from page-specific
|
||||
creation to worktree/global wake flows. Runtime commands now wait for the
|
||||
renderer's actual `browser:registerGuest` IPC before routing automation, with
|
||||
the same timeout fallback used by tab creation.
|
||||
|
||||
## Follow-up: Worktree Activation No-Op Fanout
|
||||
|
||||
The next renderer-store check found that repeated activation of an already
|
||||
active, already-reconciled worktree could still publish a new Zustand root state
|
||||
because `setActiveWorktree` rebuilt `activeTabTypeByWorktree` even when its
|
||||
stored value was unchanged. That woke every store subscriber, including session
|
||||
persistence and runtime graph sync, for a visible no-op.
|
||||
|
||||
The follow-up preserves the existing state reference when all derived active
|
||||
fields, unread state, and first-activation bookkeeping are unchanged. A
|
||||
regression test subscribes to the store and asserts that reselecting the
|
||||
already-active reconciled worktree does not notify subscribers.
|
||||
|
||||
## Follow-up: Activation Helper Visit Writes
|
||||
|
||||
After the store-level no-op fix, the higher-level `activateAndRevealWorktree`
|
||||
helper could still restamp focus-recency and append navigation history for a
|
||||
plain reselect of the already-active worktree in terminal view. That path did
|
||||
not change the visible workspace, but the recency stamp is part of the persisted
|
||||
session payload and can still wake the session writer.
|
||||
|
||||
The follow-up skips only that true no-op visit write. Activations that switch
|
||||
repo, leave another app view, or carry startup/setup/default-tab work still
|
||||
record the visit, and the sidebar reveal still runs for the no-op case.
|
||||
|
||||
## Follow-up: ANSI Terminal Redraw Controls
|
||||
|
||||
The installed app used for the continuation profile still predates the merged
|
||||
memory diagnostics and terminal-preview fixes, but its live active terminal
|
||||
preview continued to show redraw noise and there were still no browser tabs.
|
||||
That kept the remaining source-backed target on retained terminal previews.
|
||||
|
||||
The previous preview fix handled carriage-return and backspace redraws, but
|
||||
not ANSI CSI erase/cursor sequences commonly emitted by spinner-style TUIs.
|
||||
The follow-up extends the retained-preview line model to strip formatting/OSC
|
||||
metadata and apply line erase plus horizontal cursor movement before retaining
|
||||
the text tail. The regression test covers cursor-left overwrite, erase-line
|
||||
without a carriage return, SGR/private cursor controls, OSC title metadata, and
|
||||
the existing terminal read cursor metadata.
|
||||
@@ -1,131 +0,0 @@
|
||||
# Show Full Tab Title Tooltip
|
||||
|
||||
## Problem
|
||||
|
||||
Issue #2966 reports that long tab titles are truncated with an ellipsis but do not expose the full name on hover or focus.
|
||||
|
||||
- Terminal tab labels render in `src/renderer/src/components/tab-bar/SortableTab.tsx:324` as `truncate max-w-[72px]` with no tooltip.
|
||||
- Browser tab labels render in `src/renderer/src/components/tab-bar/BrowserTab.tsx:163` as `truncate max-w-[100px]` with no tooltip.
|
||||
- Editor tab labels render in `src/renderer/src/components/tab-bar/EditorFileTab.tsx:289` as `truncate max-w-[80px]` with no tooltip.
|
||||
- The app already has a Radix-backed shadcn tooltip wrapper in `src/renderer/src/components/ui/tooltip.tsx:23`.
|
||||
- The app-level `TooltipProvider` is mounted in `src/renderer/src/App.tsx` with `delayDuration={400}`; this feature should use that provider, not add another one.
|
||||
|
||||
## Root Cause
|
||||
|
||||
The tab components render plain text spans for their ellipsized labels. The full title exists in component state, but the focusable tab root is not wired to the shared `Tooltip`/`TooltipTrigger`/`TooltipContent` primitive, so neither hover nor keyboard focus exposes it.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Do not change tab width, scrolling, drag-and-drop behavior, context menus, title generation, or rename semantics.
|
||||
- Do not add persistence, IPC, or main-process behavior.
|
||||
- Do not replace the tab bar layout or introduce a new tooltip primitive.
|
||||
- Do not add custom overflow measurement in this pass unless a reviewed implementation finds the always-available tooltip materially harmful.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add full-title tooltips to non-editing tabs in the existing tab components.
|
||||
- Terminal: display `tab.customTitle ?? tab.title`.
|
||||
- Browser: display `getBrowserTabLabel(tab)`.
|
||||
- Editor: display `getEditorDisplayLabel(file)`, preserving preview italic and external mutation/status adornments outside the label.
|
||||
2. Use the existing shadcn tooltip primitive from `@/components/ui/tooltip`.
|
||||
- Do not add a nested `TooltipProvider`; the app root already supplies the 400ms delay required by the style guide.
|
||||
- In non-rename states, wrap the sortable tab root with `<Tooltip><TooltipTrigger asChild>...` so both pointer hover and keyboard focus on the dnd-kit focusable tab (`role`, `tabIndex=0`) surface the tooltip.
|
||||
- Keep the tooltip gated off while a context menu is open. Right-click opens a Radix menu from the same root hover area, so the full-title tooltip must not remain visible over the menu.
|
||||
- Do not make the label span itself the only trigger: it is not focusable today, and adding `tabIndex` to the label would create a second keyboard stop inside each tab.
|
||||
- Render `<TooltipContent side="bottom" sideOffset={6} className="max-w-80 whitespace-normal break-words text-left">full label</TooltipContent>`.
|
||||
- `side="bottom"` is intentional because the tab strip sits at the top edge; Radix collision handling can still flip/shift when needed.
|
||||
- Keep tooltip content non-interactive; it is only a label.
|
||||
3. Keep edit states out of the tooltip path.
|
||||
- Terminal rename input and editor rename input should remain direct inputs with no tooltip wrapper. Editor rename is nested inside an otherwise sortable root, so `isRenaming` must also disable the root tooltip, not only the label span tooltip.
|
||||
- Double-click handlers for rename/pin must keep their current event behavior.
|
||||
4. Preserve drag, activation, and close controls.
|
||||
- `TooltipTrigger asChild` must attach to the existing sortable root element without introducing a new DOM wrapper, so `setNodeRef`, dnd-kit attributes/listeners, activation, context-menu capture, middle-click close, and close/collapse buttons keep their current event paths.
|
||||
- Because wrapping the root makes the entire tab chrome a tooltip trigger, Electron validation must check the tooltip does not obscure or compete with close/collapse/context-menu affordances. The shared `TooltipContent` is already `pointer-events-none`, but visual overlap and native `title` on the terminal collapse button still need checking.
|
||||
- The outer tab remains the sortable/activation target.
|
||||
5. Add focused regression coverage for the render contract.
|
||||
- Unit tests should assert that terminal, browser, and editor rendered tab roots are passed through the tooltip primitive with the correct full label.
|
||||
- Tests can mock tooltip components to avoid Radix portal timing and assert structural wiring. Because these components call hooks and the Vitest environment is Node-only, render them with `react-dom/server` or another existing local pattern, and mock `@dnd-kit/sortable` so the root exposes deterministic `role`/`tabIndex` attributes.
|
||||
|
||||
## Data Flow
|
||||
|
||||
- Store/runtime tab state updates title fields.
|
||||
- `TabBar` maps current visible tabs to `SortableTab`, `BrowserTab`, and `EditorFileTab`.
|
||||
- Each tab component computes the displayed label.
|
||||
- The non-editing sortable root remains the trigger so pointer hover and keyboard focus share the same tooltip path.
|
||||
- Hover/focus opens Radix tooltip content containing the same full label after the app's normal 400ms delay.
|
||||
- Title changes from runtime/browser/editor state re-render the same component; do not cache tooltip text outside the render path.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- Terminal custom title overrides the runtime title in both visible label and tooltip.
|
||||
- Terminal title updates from remote/SSH PTY state should update the tooltip through normal React props.
|
||||
- Browser tab with missing/blank title should show the URL-derived fallback or `New Tab`, matching the visible label.
|
||||
- Browser tooltip text must use `getBrowserTabLabel(tab)` from the same `tab` prop as the visible label, not `getLiveBrowserUrl` or the redacted context-menu URL; otherwise live URL drift can make the tooltip disagree with the tab.
|
||||
- Editor preview, dirty, git-status, conflict-review, diff, markdown-preview, and external-mutation labels should keep existing styling and adjacent badges.
|
||||
- Rename modes must not show stale title tooltips over the input.
|
||||
- Keyboard focus on a terminal, browser, or editor tab must show the same tooltip as hover. The existing dnd-kit root provides the focus target; do not add focusable descendants for tooltip-only behavior.
|
||||
- Context menu, middle-click close, drag start, and split drop indicators must still work because the sortable root and pointer handlers remain unchanged.
|
||||
- Very long tooltip text should wrap within a bounded width and stay readable in light/dark themes.
|
||||
- Context-menu open must force the corresponding tooltip closed for terminal, browser, and editor tabs.
|
||||
- Hovering root-child controls such as close, terminal collapse, loading indicators, dirty dots, and status badges may enter the root trigger; the tooltip must remain non-blocking and should not create duplicate/conflicting hover copy that makes those controls harder to use.
|
||||
- Multi-window and web/SSH remote-client paths should need no IPC or persistence work because this is renderer-only display of existing tab state. The implementation must still derive text from current props every render so external title/file mutations do not leave stale tooltip content while a tab remains mounted.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- Unit: add or update tab-bar component tests that mock tooltip primitives and assert:
|
||||
- terminal tab label tooltip content uses custom title when present;
|
||||
- browser tab label tooltip content uses `getBrowserTabLabel`;
|
||||
- editor tab label tooltip content uses `getEditorDisplayLabel`;
|
||||
- the tooltip trigger is the sortable root in non-rename mode, preserving dnd-kit `role`/`tabIndex` focusability;
|
||||
- rename/context-menu suppression is unit-tested only where the implementation exposes that state through a small testable render path; do not contort Node-only server-render tests to fake private interactive state.
|
||||
- Integration/Electron: create long terminal/browser/editor tab labels, hover each tab, wait for the app's 400ms tooltip delay, and verify a tooltip with the full label appears while tab activation/close still works.
|
||||
- Integration/Electron: keyboard-focus one terminal, browser, and editor tab and verify the tooltip appears without adding an extra tab stop inside the label.
|
||||
- Integration/Electron: enter terminal/editor rename modes and open terminal/browser/editor context menus, then verify the full-title tooltip is absent or dismissed.
|
||||
- Regression: run `pnpm typecheck`, `pnpm lint`, and the relevant tab-bar Vitest tests via `pnpm test -- <test-file>` if focused files are added.
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
- Tooltip appears near the hovered/focused truncated label without covering the close button unnecessarily.
|
||||
- Tooltip uses existing Orca token-based styling through `TooltipContent`; no new colors, shadows, or typography.
|
||||
- Long text wraps at a readable max width, including long path/URL segments, and does not clip off-screen in a normal desktop viewport.
|
||||
- Tab dimensions, hover colors, active indicator, unread bell, dirty dot, git status, and close-button reveal behavior do not shift.
|
||||
- Light and dark theme surfaces remain legible.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
1. Terminal tab with a long custom or runtime title hovered, showing the full title tooltip.
|
||||
2. Browser tab with a long page title or URL hovered, showing the full title tooltip.
|
||||
3. Editor tab with a long filename/path-derived label hovered, showing the full title tooltip while dirty/status adornments still look unchanged.
|
||||
4. Adjacent smoke state: a keyboard-focused tab shows the tooltip, and close/context-menu affordances still work after tooltip wiring.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add tooltip imports and wrap the non-editing sortable tab roots in `SortableTab`, `BrowserTab`, and `EditorFileTab`.
|
||||
2. Add focused tests for tooltip label wiring.
|
||||
3. Run relevant tests, typecheck, and lint.
|
||||
4. Validate in Electron with hover screenshots for terminal, browser, editor, and adjacent tab controls.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: kept to renderer tab-label rendering only. No overflow observer, persistence, IPC, or new primitive is needed to satisfy the issue.
|
||||
- Architecture/data flow: title data already reaches the tab components; tooltip content should be derived in the same component that renders each visible label. This keeps terminal, browser, and editor ownership unchanged and avoids cross-window/SSH special cases. The trigger must be the focusable sortable root, not the inner label span, because the issue requires focus behavior.
|
||||
- Failure modes covered:
|
||||
- Tooltip root/trigger wiring could interfere with drag/activation if it adds an extra DOM wrapper or drops the dnd-kit ref/listeners/attributes.
|
||||
- Rename mode could show stale tooltip content over an input if the tooltip is not gated out.
|
||||
- Context-menu open could leave a delayed tooltip rendered over menu items unless `menuOpen` suppresses it.
|
||||
- Long tooltip text could overflow the viewport if content width is unbounded.
|
||||
- Browser fallback labels could drift if tooltip recomputes a different label than the visible span.
|
||||
- Editor badges/status text could shift if the tooltip adds a block wrapper inside the label row.
|
||||
- Root-level hover could show the tooltip while the pointer is over close/collapse/context-menu surfaces; validation must prove it does not block those controls or create unusable duplicate copy.
|
||||
- Test coverage required:
|
||||
- Unit/component: tab-bar label tooltip wiring for terminal, browser, and editor components.
|
||||
- Unit/component: terminal custom title precedence, browser fallback label parity, and non-rename root trigger focusability.
|
||||
- Electron validation: hover, keyboard-focus, rename suppression, context-menu suppression, and adjacent close/context-menu smoke for terminal/browser/editor labels.
|
||||
- Performance/blast radius: small but not free. This adds one Radix tooltip root per visible tab and a few event handlers on the existing tab root; that is acceptable because tab count is bounded by rendered tabs and there is no IPC, polling, file watching, persistence, startup work, or overflow measurement.
|
||||
- UI quality bar: existing tooltip primitive only, bounded wrapping, no tab-size shift, no overlap with close/action affordances, legible in light/dark.
|
||||
- Required review screenshots:
|
||||
1. Long terminal tab tooltip.
|
||||
2. Long browser tab tooltip.
|
||||
3. Long editor tab tooltip with existing adornments intact.
|
||||
4. Keyboard-focus tooltip plus adjacent close/context-menu smoke state.
|
||||
- Residual risks: Radix `TooltipTrigger asChild` must merge props/ref with the dnd-kit sortable root without disrupting pointer or keyboard drag behavior; unit tests with mocked dnd-kit can only prove wiring, so Electron validation must explicitly cover drag/activation adjacency, context-menu suppression, and focus-triggered display.
|
||||
@@ -1,368 +0,0 @@
|
||||
# Source Control Push Failure AI Recovery
|
||||
|
||||
## Problem
|
||||
|
||||
Push, force-push, publish, and sync push-stage failures flow through the shared
|
||||
remote operation formatter in `src/renderer/src/lib/source-control-remote-error.ts:94`
|
||||
and the editor-store toast paths in `src/renderer/src/store/slices/editor.ts:3716`
|
||||
and `src/renderer/src/store/slices/editor.ts:3821`. A local pre-push hook or
|
||||
lint hook is not an auth, protected-branch, or transport problem, so generic
|
||||
remote guidance sends the user in the wrong direction.
|
||||
|
||||
PR #7787 proves the behavior is useful, but the prototype needs tightening before
|
||||
it is maintainable:
|
||||
|
||||
- `src/renderer/src/components/right-sidebar/SourceControl.tsx:1938` and
|
||||
`src/renderer/src/components/right-sidebar/SourceControl.tsx:5799` repeat
|
||||
push-failure predicates and feed live branch/file state into a prompt that says
|
||||
"at failure time".
|
||||
- `src/renderer/src/components/right-sidebar/use-source-control-recovery-ai.ts:63`
|
||||
imports push detection again instead of consuming one derived recovery model.
|
||||
- `src/renderer/src/components/right-sidebar/source-control-ai-commit-failure-launch.ts:24`
|
||||
and `src/renderer/src/components/right-sidebar/source-control-ai-push-failure-launch.ts:24`
|
||||
are copied launch flows with action-specific copy.
|
||||
- `src/shared/source-control-commit-failure-agent-command.ts:6` and
|
||||
`src/shared/source-control-push-failure-agent-command.ts:6` are identical
|
||||
command-template builders.
|
||||
- `src/renderer/src/components/right-sidebar/source-control-fix-split-button.tsx:21`
|
||||
already contains a reusable split button, while `SourceControl.tsx:6415`
|
||||
carries a second inline version.
|
||||
- `src/renderer/src/lib/source-control-remote-error.ts:148` currently treats
|
||||
any `isSync` error as push-like for hook detection. `syncBranch` calls the
|
||||
formatter for fetch, upstream-status, pull, and push failures, so the renderer
|
||||
cannot prove a sync error came from the push stage without an explicit marker.
|
||||
- `src/renderer/src/components/right-sidebar/SourceControl.push-failure-recovery.test.ts:2`
|
||||
imports prompt helpers through the large React module instead of shared prompt
|
||||
modules.
|
||||
|
||||
## Goal
|
||||
|
||||
Add first-class recovery for pre-push hook failures without growing a parallel
|
||||
push-only subsystem:
|
||||
|
||||
1. Toasts for push, force-push, publish, and sync push-stage failures say
|
||||
"blocked" for detected pre-push or lint-hook output.
|
||||
2. Source Control shows a concise Push blocked panel with Details and AI Fix
|
||||
only for a failure snapshot that is both push-like and hook-like.
|
||||
3. AI Fix launches the configured `fixPushFailure` Source Control action with a
|
||||
safe, provider-neutral prompt.
|
||||
4. Commit-failure recovery and push-failure recovery share launch,
|
||||
command-template, split-button, and dense error-panel primitives.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Do not fix server-side pre-receive hooks, hosted CI failures, or provider-side
|
||||
protected-branch failures from this entry point.
|
||||
- Do not bypass hooks, add `--no-verify`, push from the launched agent, create a
|
||||
PR, or assume GitHub-specific terminology.
|
||||
- Do not add app-wide persistence for this transient failure panel.
|
||||
- Do not redesign the Source Control panel or the Source Control AI settings
|
||||
model.
|
||||
- Do not fold unrelated launch surfaces such as checks recovery into this change
|
||||
unless a tiny shared helper is already needed for commit/push recovery.
|
||||
|
||||
## Design
|
||||
|
||||
1. Keep push-hook detection and prompt building in shared code.
|
||||
- `src/shared/source-control-push-failure.ts` owns normalization, bounded
|
||||
scanning, summary text, Details eligibility, prompt truncation, prompt
|
||||
rules, and changed-file list bounding.
|
||||
- Detection must stay conservative: explicit `pre-push`/`prepush`,
|
||||
`hook declined to push`, hook-runner output in push context, or lint output
|
||||
in push context. Auth, non-fast-forward, protected branch, pre-receive,
|
||||
submodule, and generic transport failures stay on the existing remote-error
|
||||
path.
|
||||
- Keep the output scan bounded at 64 KiB and the prompt failure-output
|
||||
section bounded. Also cap prompt file lines to a small constant with an
|
||||
omitted-count line; do not rely on the git-status cap, which is far too high
|
||||
for prompt context.
|
||||
|
||||
2. Make remote-error formatting sync-stage aware.
|
||||
- Extend `RemoteOperationErrorOptions` with an explicit push-stage flag for
|
||||
sync, for example `isSyncPushStage`.
|
||||
- Gate push-hook classification on `isPush`, `isForcePush`, `publish`, or
|
||||
`isSyncPushStage`; do not use bare `isSync` as evidence of a push failure.
|
||||
- In `syncBranch`, pass the push-stage flag only inside the two inner
|
||||
`pushRuntimeGit` catch blocks. The outer fetch, upstream-status, and pull
|
||||
catches still pass `isSync` for Sync-shaped generic copy but must not render
|
||||
blocked hook copy.
|
||||
- Carry the same push-stage fact back to the renderer, either by tagging the
|
||||
thrown `Error` with a narrow exported marker or by wrapping it in a typed
|
||||
error that preserves the original message/cause. `SourceControl` must set
|
||||
`syncPushStage` only from that marker, not from `kind === 'sync'` plus
|
||||
hook-like stderr.
|
||||
- Keep submodule push messages before hook detection so submodule guidance
|
||||
remains more specific than AI recovery.
|
||||
|
||||
3. Replace one-off command builders with one shared recovery command builder.
|
||||
- Add a shared builder that accepts `{ actionId, promptOverride,
|
||||
commandInputTemplate, basePrompt }` and renders the existing Source Control
|
||||
AI command template for launch actions.
|
||||
- Keep compatibility exports for commit and push helpers if nearby tests or
|
||||
call sites still use those names, but make them wrappers over the generic
|
||||
builder.
|
||||
- Move prompt-builder tests to import from shared modules, not
|
||||
`SourceControl.tsx`.
|
||||
|
||||
4. Capture and derive push recovery state once.
|
||||
- Extend `SourceControlActionError` with the raw error, a push-stage marker
|
||||
for sync failures, the branch name at failure time, a bounded status-entry
|
||||
snapshot at failure time, and a per-worktree sequence token.
|
||||
- `runRemoteAction` clears the worktree's previous error and increments its
|
||||
sequence before starting. A catch may write an error only if its sequence
|
||||
still owns that worktree, so a slow failure cannot overwrite a newer retry
|
||||
or success.
|
||||
- Add a focused renderer helper that accepts the captured
|
||||
`SourceControlActionError` and the current branch name, then returns either
|
||||
`null` or a model with raw/sanitized detail text, summary, details flag,
|
||||
kind label, and AI prompt.
|
||||
- The helper returns `null` unless the operation is `push`, `force_push`,
|
||||
`publish`, or `sync` with the sync push-stage marker and
|
||||
`isPushHookFailure(rawError)` passes.
|
||||
- If the current branch is known and differs from the captured branch, hide or
|
||||
clear the model instead of launching an agent with wrong branch context.
|
||||
- Pass that single model to `useSourceControlAi` and `CommitArea`; neither
|
||||
prop construction nor `CommitArea` should repeat the push-hook predicate.
|
||||
|
||||
5. Use one generic recovery launcher for commit and push failures.
|
||||
- Replace the separate commit and push launch files with
|
||||
`source-control-ai-recovery-launch.ts`, or keep the old files as one-line
|
||||
wrappers if import stability is cheaper.
|
||||
- The generic launcher owns connection resolution, SSH/local agent discovery,
|
||||
saved-agent validation, agent-args validation, agent selection, terminal
|
||||
launch, focus, and success/failure toasts.
|
||||
- Resolve connection without collapsing local and unresolved states: read
|
||||
`const worktreeConnectionId = getConnectionId(worktreeId)`, use it when it
|
||||
is a string or `null`, and only fall back to `sourceRepoConnectionId` when
|
||||
the worktree lookup returns `undefined`. If the fallback is also
|
||||
`undefined`, show the workspace-connection error instead of launching
|
||||
locally. `null` means proven local; a string means SSH/remote.
|
||||
- Validate saved CLI args before agent detection or terminal creation. On
|
||||
Windows, keep using PowerShell-safe planning through
|
||||
`planAgentCliArgsSuffix(..., 'powershell')`.
|
||||
- Action-specific data is limited to action id, base prompt, empty-prompt
|
||||
copy, unavailable-agent copy, and success copy.
|
||||
|
||||
6. Keep the recovery hook thin.
|
||||
- `use-source-control-recovery-ai.ts` builds the commit prompt, accepts the
|
||||
already-derived push recovery prompt/model, keeps independent loading
|
||||
flags, and calls the generic launcher.
|
||||
- It should not import push-hook detection, resolve agents, or duplicate
|
||||
launch plumbing.
|
||||
|
||||
7. Extract and reuse the recovery UI.
|
||||
- Reuse or replace the existing
|
||||
`src/renderer/src/components/right-sidebar/source-control-fix-split-button.tsx`
|
||||
rather than adding another split-button component.
|
||||
- Move the dense recovery notice and Details dialog into focused renderer
|
||||
modules named for source-control recovery. Avoid `helpers`, `utils`, and new
|
||||
max-lines suppressions.
|
||||
- Reuse the same notice/dialog component for commit and push recovery with
|
||||
action-specific labels, summary, details, prompt, saved recipe, and launch
|
||||
callback.
|
||||
- Keep normal remote errors filtered out when a push recovery model is
|
||||
rendered, so the user does not see both Push blocked and generic remote
|
||||
error copy for the same failure.
|
||||
|
||||
8. Retain `fixPushFailure` in the existing Source Control AI action model.
|
||||
- The prototype already adds `fixPushFailure` to
|
||||
`src/shared/source-control-ai-actions.ts`; keep it as a launch action like
|
||||
`fixCommitFailure`.
|
||||
- Verify default settings, normalizers, global settings rows, repository
|
||||
override rows, labels, descriptions, and variable chips all include Push
|
||||
failure fixes.
|
||||
- Do not create a push-specific settings store or migration. Existing
|
||||
`normalizeSourceControlAiSettings` hydrates missing action defaults.
|
||||
|
||||
## Data Flow
|
||||
|
||||
- User clicks Push, Force Push, Publish Branch, or Sync.
|
||||
- `runRemoteAction` clears that worktree's previous remote error, records a new
|
||||
sequence token, and starts the editor-store remote action.
|
||||
- Git push fails and throws.
|
||||
- `pushBranch` or sync's inner push-stage catch calls
|
||||
`resolveRemoteOperationErrorMessage` with push-like options. Sync fetch, pull,
|
||||
and upstream-status failures do not pass the push-stage flag.
|
||||
- Sync's inner push-stage catch marks the rethrown error as push-stage so
|
||||
`runRemoteAction` can preserve `syncPushStage` in the captured snapshot.
|
||||
- The formatter classifies hook output before auth/transport fallbacks only for
|
||||
push-like options and shows blocked toast copy.
|
||||
- `SourceControl` catches the same error, and if the sequence still owns the
|
||||
worktree, stores `{ kind, rawError, message, syncPushStage, branchName,
|
||||
entriesSnapshot }`.
|
||||
- The push recovery helper derives one `pushRecovery` model from that snapshot.
|
||||
- `CommitArea` renders normal remote errors or the Push blocked recovery notice.
|
||||
- AI Fix builds the `fixPushFailure` command input and launches the selected
|
||||
agent in the owning local or SSH runtime.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- Auth, missing repo, protected-branch, pre-receive, non-fast-forward, and
|
||||
transport failures must not show the Push blocked panel.
|
||||
- Submodule push errors keep their existing specialized messages before
|
||||
push-hook detection.
|
||||
- Sync failures from fetch, upstream-status, or pull stages must not show Push
|
||||
blocked, even if stderr contains words like "lint" or "hook".
|
||||
- Create PR intent remote failures use the same `runRemoteAction` plumbing; if
|
||||
CommitArea is not visible, blocked toast copy is still required but no hidden
|
||||
panel work is needed.
|
||||
- A newer remote operation for the same worktree must clear stale recovery state
|
||||
immediately and prevent an older in-flight failure from writing after it.
|
||||
- Switching worktrees or branches must not show another worktree or branch's
|
||||
push failure.
|
||||
- External edits or another Orca window may make the failure stale. Do not add
|
||||
cross-window persistence for this feature; rely on local retry/remount/branch
|
||||
mismatch clearing and list this as residual risk.
|
||||
- Source Control AI hidden for a repo still shows the blocked notice and Details;
|
||||
it hides AI Fix.
|
||||
- SSH worktrees must detect and launch agents on the owning connection, not a
|
||||
local fallback.
|
||||
- Windows launch planning must continue to use PowerShell-safe agent args.
|
||||
- Very large hook output and very large changed-file sets must be bounded before
|
||||
prompt generation.
|
||||
- ANSI/control output must not leak into summaries or Details comparison logic.
|
||||
Details may show sanitized text while preserving enough line breaks for
|
||||
debugging.
|
||||
- Empty custom command templates must stay empty so the launcher rejects them
|
||||
with a clear settings error.
|
||||
- Prompt text must treat file paths, branch names, and hook output as data, not
|
||||
instructions.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- Shared unit tests:
|
||||
- `src/shared/source-control-push-failure.test.ts` covers detection positives,
|
||||
auth/protected/pre-receive/non-fast-forward negatives, ANSI/control
|
||||
stripping, bounded scanning, details comparison, prompt output truncation,
|
||||
prompt file-list capping, and provider-neutral prompt rules.
|
||||
- Shared command-template tests cover the generic recovery builder plus
|
||||
commit/push wrappers, including empty templates and prompt overrides.
|
||||
- `src/shared/source-control-ai-actions.test.ts` covers `fixPushFailure`
|
||||
label, default template, variables, normalization, and action-list inclusion.
|
||||
- Remote formatter and store tests:
|
||||
- `src/renderer/src/lib/source-control-remote-error.test.ts` covers push,
|
||||
force-push, publish, and sync push-stage blocked copy plus sync non-push
|
||||
stage negatives, auth/non-fast-forward/protected/pre-receive/submodule
|
||||
regressions.
|
||||
- `src/renderer/src/store/slices/editor.test.ts` covers the `pushBranch` toast
|
||||
path and both sync push-stage and sync non-push-stage toasts.
|
||||
- Renderer model and UI tests:
|
||||
- A focused push recovery derivation test covers operation kind, sync
|
||||
push-stage marker, branch mismatch, stale sequence ownership, snapshot file
|
||||
entries, summary, details flag, prompt contents, and ordinary remote errors.
|
||||
- `CommitArea` tests cover the Push blocked notice, Details dialog, AI Fix
|
||||
visible/hidden, ordinary remote errors, no duplicate remote error when a push
|
||||
model exists, and unchanged commit-failure recovery rendering.
|
||||
- Settings tests cover global and repository Source Control AI action rows
|
||||
showing Push failure fixes.
|
||||
- Launcher tests:
|
||||
- Generic recovery launcher tests cover commit and push action ids, invalid CLI
|
||||
args before detection, empty template rejection, unavailable saved agent,
|
||||
local versus SSH agent detection, successful launch/focus, and success copy.
|
||||
- Checks:
|
||||
- Run targeted vitest files above, `pnpm typecheck`, `pnpm lint`, and
|
||||
`pnpm check:max-lines-ratchet`.
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
The Source Control recovery UI must match `docs/STYLEGUIDE.md`: monochrome,
|
||||
quiet, dense, token-based, and consistent with adjacent commit-failure recovery.
|
||||
Use existing shadcn `Button`, `DropdownMenu`, and `Dialog` primitives, lucide
|
||||
icons, `card`/`border`/`destructive`/`muted` tokens, and the existing action
|
||||
recipe row patterns. The Push blocked notice should keep the summary readable at
|
||||
narrow right-sidebar widths, avoid nested cards, avoid new color values, show
|
||||
stable split-button geometry while launching, and keep Details as progressive
|
||||
disclosure for long hook output. Dialogs and dropdowns must remain usable in
|
||||
light/dark mode and under SSH latency.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
1. Source Control after a simulated pre-push hook failure: Push blocked notice
|
||||
with summary, AI Fix, and Details.
|
||||
2. Push failure Details dialog showing hook output and Fix with AI.
|
||||
3. AI Fix customize-launch dialog for `fixPushFailure`.
|
||||
4. Ordinary push auth/protected/remote failure state: regular remote error, no
|
||||
Push blocked notice.
|
||||
5. Sync fetch/pull-stage failure state: Sync-shaped remote error, no Push
|
||||
blocked notice.
|
||||
6. Source Control AI hidden for the repo: Push blocked notice and Details, no AI
|
||||
Fix.
|
||||
7. Source Control AI settings showing the Push failure fixes launch recipe.
|
||||
8. Adjacent commit-failure recovery notice still rendering correctly after the
|
||||
shared UI extraction.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Tighten shared push-failure classifier/prompt bounds and add the generic
|
||||
recovery command builder.
|
||||
2. Make remote formatter/store sync-stage aware and update toast tests.
|
||||
3. Add the `SourceControlActionError` snapshot/sequence data and one push
|
||||
recovery derivation helper.
|
||||
4. Replace duplicated commit/push launchers with the generic recovery launcher
|
||||
and thin hook wiring.
|
||||
5. Extract/reuse source-control recovery UI components, including the existing
|
||||
split-button module.
|
||||
6. Verify `fixPushFailure` settings/default/normalizer coverage and i18n labels.
|
||||
7. Update targeted tests and run typecheck, lint, and max-lines ratchet.
|
||||
8. Validate rendered Electron states with screenshots before opening the PR.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: Reduced from PR #7787's push-specific parallel path to a shared
|
||||
recovery layer. Keep the feature limited to local pre-push/lint-hook detection,
|
||||
blocked copy, an inline recovery notice, Details, and AI launch. No persistence
|
||||
or provider-specific recovery.
|
||||
- Architecture/data flow: Shared code owns classification, prompt text, and
|
||||
command-template rendering; the editor store owns stage-aware toast formatting;
|
||||
`SourceControl` owns transient worktree-scoped failure snapshots and sequence
|
||||
invalidation; the generic launcher owns local/SSH agent discovery and terminal
|
||||
launch.
|
||||
- Failure modes covered:
|
||||
- Sync stage ambiguity: only the inner push stage may classify as hook-blocked.
|
||||
- Auth/protected/pre-receive/non-fast-forward/submodule/transport errors stay
|
||||
out of push recovery.
|
||||
- Branch or worktree switches suppress stale recovery models.
|
||||
- Per-worktree sequence tokens prevent older in-flight failures from
|
||||
overwriting newer retries or successes.
|
||||
- Empty custom templates, invalid CLI args, unavailable saved agents, missing
|
||||
worktree context, SSH host detection, and Windows shell planning fail before
|
||||
terminal launch.
|
||||
- Large or hostile hook output and file lists are bounded and treated as data
|
||||
in prompts.
|
||||
- Test coverage required:
|
||||
- Shared classifier/prompt/command/action-model tests in `src/shared`.
|
||||
- Remote formatter and editor-store tests for push, force-push, publish, sync
|
||||
push-stage, and sync non-push-stage paths.
|
||||
- Renderer derivation and `CommitArea` tests for Push blocked, Details, AI Fix,
|
||||
hidden AI actions, stale branch/sequence, ordinary remote errors, and
|
||||
existing commit failure recovery.
|
||||
- Generic launcher tests for local/SSH, invalid args, saved-agent unavailable,
|
||||
empty template, and success launch.
|
||||
- Settings tests for global and repo Push failure fixes rows.
|
||||
- Electron validation for all required screenshots; no separate E2E is
|
||||
required if renderer tests cover the model and Electron validates the real UI.
|
||||
- Performance/blast radius: No polling, watchers, migrations, or startup work.
|
||||
Runtime cost is one bounded classifier pass over at most 64 KiB, bounded prompt
|
||||
output, and a bounded file snapshot only when a remote action fails. Largest
|
||||
blast radius is the shared recovery UI and launcher used by existing commit
|
||||
failures, so commit recovery needs tests and a screenshot.
|
||||
- UI quality bar: Match `docs/STYLEGUIDE.md` and adjacent Source Control density:
|
||||
token-based error state, stable split-button geometry, progressive Details
|
||||
disclosure, no nested cards, concise copy, light/dark compatibility, and
|
||||
visible disabled/loading state under SSH latency.
|
||||
- Required review screenshots:
|
||||
1. Push blocked notice after pre-push hook failure.
|
||||
2. Push failure Details dialog with Fix with AI.
|
||||
3. `fixPushFailure` customize-launch dialog.
|
||||
4. Ordinary push auth/protected/remote failure with no Push blocked panel.
|
||||
5. Sync non-push-stage failure with no Push blocked panel.
|
||||
6. Source Control AI hidden: Push blocked without AI Fix.
|
||||
7. Source Control AI settings showing Push failure fixes.
|
||||
8. Existing commit-failure recovery notice after shared UI extraction.
|
||||
- Residual risks: Classifier false positives remain possible for unusual local
|
||||
hook-runner output that mentions push context; keep tests biased toward
|
||||
preserving auth, protected-branch, and non-fast-forward behavior. Failure
|
||||
panels are renderer-local, so another Orca window or an external terminal can
|
||||
fix the problem while the old panel remains visible until local retry, remount,
|
||||
or branch/worktree change. Electron validation may need a mocked or temporary
|
||||
repo scenario to trigger a real pre-push hook without mutating user data.
|
||||
@@ -1,61 +0,0 @@
|
||||
# SSH Config Target Compatibility
|
||||
|
||||
## Problem
|
||||
|
||||
- `src/main/ssh/ssh-connection-utils.ts:108` resolves OpenSSH config with `ssh -G`, but then prefers the persisted `target.host` over `resolved.hostname`.
|
||||
- `src/main/ssh/ssh-connection-utils.ts:109` treats persisted port `22` as an explicit override, so a config-host target can ignore a resolved non-default `Port`.
|
||||
- `src/main/ssh/ssh-config-parser.ts:210` imports config aliases with `host` set to the alias when the concrete `Host` block lacks an inline `HostName`; later `ssh -G` may know the real host, but the connection path ignores it.
|
||||
- `src/renderer/src/components/settings/SshPane.tsx:63` requires both host and username, even though OpenSSH config aliases can resolve the user and users commonly paste `user@host:port` targets.
|
||||
- `src/main/ssh/ssh-config-parser.ts:330` parses `ForwardAgent`, but `src/main/ssh/ssh-connection-utils.ts:112` did not pass it into ssh2, so remote git commands that rely on the local agent could fail.
|
||||
|
||||
## Goal
|
||||
|
||||
Make Orca behave like a mature SSH client for common config-host flows: aliases imported from `~/.ssh/config`, aliases with inherited `HostName`/`Port`, and pasted SSH targets should connect without users re-entering information that OpenSSH can resolve.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Do not add persistent secret storage for SSH passwords or key passphrases.
|
||||
- Do not redesign the whole SSH settings page.
|
||||
- Do not change relay deployment or remote PTY lease semantics.
|
||||
- Do not add a known-host trust UI in this patch.
|
||||
|
||||
## Design
|
||||
|
||||
1. Preserve explicit target overrides while letting config aliases use resolved values.
|
||||
- In `buildConnectConfig`, prefer `resolved.hostname` only when the persisted host is blank, the same as `configHost`, or the same as the label.
|
||||
- Prefer `resolved.port` when the target is a config-host target still on the default `22`; keep non-default target ports as explicit overrides.
|
||||
- Continue using target username first, then resolved user.
|
||||
|
||||
2. Honor resolved agent forwarding where ssh2 can support it.
|
||||
- Set `agentForward` only when resolved config requested forwarding and an agent is actually configured.
|
||||
- Leave system-SSH transport unchanged because it already delegates to OpenSSH config.
|
||||
|
||||
3. Normalize settings form drafts before save.
|
||||
- Accept `ssh://user@host:port`, `user@host:port`, and plain aliases in the Host field.
|
||||
- Auto-fill username and port from pasted inputs only when the dedicated fields are still empty/default.
|
||||
- Allow username to be omitted; `ssh -G` can provide it during connect.
|
||||
|
||||
4. Keep UI changes small.
|
||||
- Rename copy only where needed to avoid implying username is mandatory.
|
||||
- Render username-less targets without a leading `@`.
|
||||
- Do not introduce new colors, typography, or layout patterns.
|
||||
|
||||
5. Cover behavior with focused tests.
|
||||
- Add connection-config tests for config-host resolved hostname/port precedence.
|
||||
- Add connection-config tests for `ForwardAgent yes`.
|
||||
- Add renderer utility tests for pasted SSH target normalization.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- Explicit non-default port in Orca still wins over `ssh -G`.
|
||||
- Empty or unparsable host input remains invalid.
|
||||
- IPv6 bracket syntax is accepted for `ssh://` URLs and preserved conservatively for scp-like inputs.
|
||||
- Plain config aliases remain valid even without a username.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add the renderer draft-normalization helper and tests.
|
||||
2. Wire the SSH settings form save path and labels to the helper.
|
||||
3. Update `buildConnectConfig` precedence/agent-forwarding and tests.
|
||||
4. Clean up username-less target display.
|
||||
5. Run focused tests and typecheck/lint where feasible.
|
||||
@@ -1,243 +0,0 @@
|
||||
# SSH Handler Re-registration Port Forwards
|
||||
|
||||
## Problem
|
||||
|
||||
Issue #2932 reported that macOS window reactivation can re-run
|
||||
`attachMainWindowServices`, which calls `registerSshHandlers` again
|
||||
([src/main/window/attach-main-window-services.ts:83](src/main/window/attach-main-window-services.ts:83)).
|
||||
|
||||
Before this change, `registerSshHandlers` removed and re-added IPC handlers but
|
||||
also replaced the module-level `connectionManager` and `portForwardManager`
|
||||
([src/main/ipc/ssh.ts:438](src/main/ipc/ssh.ts:438),
|
||||
[src/main/ipc/ssh.ts:439](src/main/ipc/ssh.ts:439)).
|
||||
`activeSessions` remains module-global
|
||||
([src/main/ipc/ssh.ts:63](src/main/ipc/ssh.ts:63)),
|
||||
so live relay sessions kept references to the old port-forward manager while
|
||||
new IPC handlers read a fresh empty one.
|
||||
|
||||
The visible failure is:
|
||||
|
||||
1. Connect an SSH target.
|
||||
2. Add a local port forward.
|
||||
3. Close all windows on macOS while the app process remains alive.
|
||||
4. Reactivate Orca, causing SSH handlers to register again.
|
||||
5. `ssh:listPortForwards` returns an empty list, `ssh:removePortForward` cannot
|
||||
remove the old forward id, `ssh:addPortForward`/`ssh:updatePortForward` can
|
||||
fail because the fresh connection manager has no live connection, and
|
||||
`ssh:disconnect` does not close the old SSH connection or local listener.
|
||||
Re-adding the same local port fails because the old server remains bound.
|
||||
|
||||
## Root Cause
|
||||
|
||||
SSH handler registration mixes two lifetimes:
|
||||
|
||||
- Process-lifetime session state: active SSH connections, relay sessions, port
|
||||
listeners, relay lost backoff, reset/connect in-flight maps.
|
||||
- Window-lifetime callback state: `getMainWindow` and renderer IPC handlers.
|
||||
|
||||
The previous re-registration path preserved `activeSessions` but replaced the
|
||||
managers that sessions and IPC handlers must share. Port-forward IPC operations
|
||||
use `portForwardManager` ([src/main/ipc/ssh.ts:992](src/main/ipc/ssh.ts:992),
|
||||
[src/main/ipc/ssh.ts:1047](src/main/ipc/ssh.ts:1047),
|
||||
[src/main/ipc/ssh.ts:1056](src/main/ipc/ssh.ts:1056)),
|
||||
and disconnect/terminate cleanup also uses that variable
|
||||
([src/main/ipc/ssh.ts:750](src/main/ipc/ssh.ts:750),
|
||||
[src/main/ipc/ssh.ts:814](src/main/ipc/ssh.ts:814)).
|
||||
After replacement, those operations no longer targeted the manager that owns the
|
||||
live local servers. Replacing `connectionManager` also strands the live
|
||||
`SshConnection` objects: existing relay sessions still hold their current
|
||||
connection, but new IPC handlers and `getSshConnectionManager()` see an empty
|
||||
manager.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Do not change relay protocol, remote deployment, or SSH transport behavior.
|
||||
- Do not redesign port-forward persistence or enrichment.
|
||||
- Do not change renderer UI.
|
||||
- Do not introduce a second SSH service layer.
|
||||
- Do not force-dispose live SSH sessions merely because a window was recreated.
|
||||
|
||||
## Design
|
||||
|
||||
1. Preserve process-lifetime managers across handler re-registration.
|
||||
Instantiate `SshConnectionManager` and `SshPortForwardManager` only when
|
||||
absent; later `registerSshHandlers` calls reuse the existing instances.
|
||||
|
||||
2. Refresh every live callback owner on re-registration. This is required; a
|
||||
plain `connectionManager ??= new SshConnectionManager(callbacks)` is not
|
||||
enough.
|
||||
- `SshConnectionManager` must update callbacks used by both future and
|
||||
existing `SshConnection` objects, either via explicit `setCallbacks` methods
|
||||
on manager/connection or via a stable callback proxy whose implementation
|
||||
is mutable.
|
||||
- Existing `SshRelaySession` objects must refresh `getMainWindow`, store,
|
||||
runtime, and detected-port callback references. Event handlers must call
|
||||
the current callback at event time; do not capture the old `getMainWindow`
|
||||
in long-lived provider callbacks.
|
||||
- The credential-request tracking set must not be per-registration if live
|
||||
connections can switch callbacks during an in-flight `ssh:connect`.
|
||||
|
||||
3. Re-register IPC handlers and dependent global listeners on every call.
|
||||
`ipcMain` handlers, advertised URL refresh, credential IPC, browse handler,
|
||||
and power-monitor listeners are window-registration concerns and should still
|
||||
point at the latest window.
|
||||
|
||||
4. Preserve existing explicit teardown behavior.
|
||||
`ssh:disconnect`, `ssh:terminateSessions`, `ssh:removeTarget`, reset, and
|
||||
double-connect cleanup must still remove forwards through the shared manager
|
||||
before detaching or disposing sessions.
|
||||
|
||||
5. Add regression tests in `src/main/ipc/ssh.test.ts`.
|
||||
Connect a target, add a mocked port forward, call `registerSshHandlers`
|
||||
again, then assert:
|
||||
- `ssh:listPortForwards` still returns the original forward.
|
||||
- `ssh:removePortForward` can remove the original id.
|
||||
- `ssh:addPortForward`/`ssh:updatePortForward` still use the original live
|
||||
connection.
|
||||
- A second re-registration followed by `ssh:disconnect` still calls
|
||||
`removeAllForwards` and `disconnect` on the original shared managers.
|
||||
- State, credential, PTY, and detected-port callbacks from an existing live
|
||||
session publish to the newest window after re-registration.
|
||||
|
||||
## Data Flow
|
||||
|
||||
- First registration:
|
||||
- `registerSshHandlers(store, getWindowA)` creates store wrapper, connection
|
||||
manager, port-forward manager, handlers, listeners, and current callback
|
||||
environment.
|
||||
- `ssh:connect` creates a relay session with the shared port-forward manager.
|
||||
- `ssh:addPortForward` stores a local server in that same manager.
|
||||
|
||||
- Window reactivation:
|
||||
- `registerSshHandlers(store, getWindowB)` removes/re-adds IPC handlers.
|
||||
- Existing managers are reused.
|
||||
- Existing connection and relay-session callback owners are refreshed to the
|
||||
latest store/runtime/window environment.
|
||||
- New handlers close over `getWindowB` and call the same managers.
|
||||
|
||||
- Cleanup:
|
||||
- `ssh:removePortForward` and `ssh:disconnect` operate on the same manager
|
||||
that owns the live forward, then broadcast through the latest window.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- Re-registration while a target is connected and has active port forwards.
|
||||
- Re-registration while `ssh:connect`, `restorePortForwards`, reset, reconnect,
|
||||
or disconnect is in flight. The operation must not split credential tracking
|
||||
or create a session that holds stale callbacks.
|
||||
- Re-registration while no targets are connected.
|
||||
- Re-registration after the store object changes. Either update existing relay
|
||||
sessions to use the new store/runtime or document and test the stronger
|
||||
invariant that production re-registration always passes the same process
|
||||
store/runtime.
|
||||
- Re-registration after the window changes. All broadcasts, credential prompts,
|
||||
PTY events, detected-port events, advertised URL refreshes, relay-loss state
|
||||
changes, and terminal relay errors must use the newest `getMainWindow`.
|
||||
- Disconnect after re-registration must release old local ports.
|
||||
- `ssh:connect` after window reactivation must be idempotent when the existing
|
||||
session is already ready and healthy: return the connected state without
|
||||
tearing down forwards. Explicit reset/reconnect or non-ready replacement paths
|
||||
must still await old port teardown before restoring forwards.
|
||||
- `getSshConnectionManager()` consumers must continue to see live connections
|
||||
after re-registration.
|
||||
- Test isolation must not depend on module-singleton state leaking between
|
||||
tests. Add explicit reset/teardown support if preserving managers makes
|
||||
`beforeEach(registerSshHandlers)` insufficient.
|
||||
- SSH and relay paths must keep working for remote targets; the fix must not
|
||||
assume local filesystem or local-only execution.
|
||||
- Windows/Linux remain unaffected: re-registration can still happen during
|
||||
development or future window lifecycles, and the fix must avoid path or
|
||||
platform assumptions.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- Unit: `pnpm vitest run --config config/vitest.config.ts src/main/ipc/ssh.test.ts`
|
||||
- Add regression coverage for list/remove/disconnect after handler
|
||||
re-registration.
|
||||
- Add coverage that add/update after re-registration uses the still-live
|
||||
connection manager connection, not a fresh empty manager.
|
||||
- Add coverage that existing connection/session callbacks publish to a second
|
||||
mock window after re-registration.
|
||||
- Add an in-flight connect or credential-request test if callback refresh uses
|
||||
mutable callback objects.
|
||||
- Existing connect, disconnect, reset, relay-loss, and terminate tests cover
|
||||
adjacent lifecycle behavior.
|
||||
- Typecheck: `pnpm typecheck`.
|
||||
- Lint: `pnpm lint`.
|
||||
- Electron/SSH validation: use an existing SSH target such as `openclaw 2` if
|
||||
available in the running app, add a disposable local port forward, trigger
|
||||
window/service re-registration by closing and reopening the main window on
|
||||
macOS, then verify the forward remains listed and removable. IPC/unit tests
|
||||
are supporting evidence only; if the golden path cannot be exercised safely,
|
||||
halt before PR and report the missing evidence.
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
Not UI-visible. No layout, copy, or visual styling changes are expected. The
|
||||
only user-visible expectation is that existing SSH port-forward rows remain
|
||||
present and actionable after window reactivation.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
1. SSH target connected with a port forward listed before re-registration.
|
||||
2. Same SSH target after window reactivation, showing the same port forward
|
||||
still listed.
|
||||
3. Same SSH target after removing the port forward, showing it gone without an
|
||||
error.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add the focused regression test to prove the current lifecycle bug.
|
||||
2. Change SSH handler registration to reuse process-lifetime managers.
|
||||
3. Run the focused test, then typecheck and lint.
|
||||
4. Validate in Electron against an SSH target if feasible; otherwise halt
|
||||
before PR if the golden-path SSH UI cannot be exercised.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: reduced to SSH IPC lifecycle only. No relay, renderer, or persistence
|
||||
redesign is needed because the broken boundary is manager replacement during
|
||||
handler re-registration.
|
||||
- Architecture/data flow: process-lifetime managers stay module-level and are
|
||||
reused; window-lifetime IPC handlers/listeners are refreshed; existing
|
||||
connection and relay-session callback owners must also be refreshed or proxied
|
||||
so live events target the current BrowserWindow.
|
||||
- Failure modes covered:
|
||||
- Active forwards becoming invisible after re-registration.
|
||||
- `ssh:removePortForward` missing the old forward id.
|
||||
- `ssh:addPortForward`/`ssh:updatePortForward` failing against a fresh empty
|
||||
connection manager.
|
||||
- `ssh:disconnect` failing to close old SSH connections and local listeners
|
||||
after re-registration.
|
||||
- Store/window/runtime callback refresh after re-registration.
|
||||
- Re-registration during in-flight connect/reset/reconnect.
|
||||
- No-session re-registration continuing to work.
|
||||
- Test coverage required:
|
||||
- Unit in `src/main/ipc/ssh.test.ts` for connect/add/list/remove across
|
||||
`registerSshHandlers` calls.
|
||||
- Unit in `src/main/ipc/ssh.test.ts` for disconnect cleanup after
|
||||
re-registration.
|
||||
- Unit in `src/main/ipc/ssh.test.ts` for existing live callbacks reaching the
|
||||
newest window after re-registration.
|
||||
- Unit in `src/main/ipc/ssh.test.ts` for no-session re-registration and test
|
||||
teardown/reset of module singletons.
|
||||
- Existing lifecycle tests for reset, terminate, relay loss, and sleep remain
|
||||
adjacent coverage.
|
||||
- Performance/blast radius: no material startup or IPC cost. Reusing managers
|
||||
avoids leaked runtime state and does not add polling, watchers, or
|
||||
cross-process calls. Callback refresh is O(number of live SSH connections and
|
||||
sessions) per registration, which should be tiny.
|
||||
- UI quality bar: not UI-visible; preserve existing SSH port-forward UI state
|
||||
rather than changing layout or copy.
|
||||
- Required review screenshots:
|
||||
1. Connected SSH target with active port forward before re-registration.
|
||||
2. Connected SSH target with same port forward after re-registration.
|
||||
3. Connected SSH target after removing that forward.
|
||||
- Feasibility: one-time manager creation is feasible only with callback refresh
|
||||
for existing `SshConnection` and `SshRelaySession` instances. If that refresh
|
||||
proves larger than expected, prefer a stable callback proxy over recreating
|
||||
managers; do not dispose live sessions just to make callback ownership easier.
|
||||
- Residual risks: Electron validation may be constrained by availability of an
|
||||
existing SSH target and by avoiding live-user port collisions. If the golden
|
||||
path cannot be exercised safely, stop before opening a PR and report the
|
||||
missing manual evidence.
|
||||
@@ -1,114 +0,0 @@
|
||||
# Terminal Close Confirmation
|
||||
|
||||
## Problem
|
||||
|
||||
- `CloseTerminalDialog` repeats the action users already requested with "Close Terminal?" and a generic "process will be killed" warning (`src/renderer/src/components/terminal-pane/CloseTerminalDialog.tsx:30`).
|
||||
- `Cmd/Ctrl+W` closes only the focused split pane, or the tab when it is the last pane; the guard exists so tab-level close does not kill every pane by accident (`src/renderer/src/components/terminal-pane/keyboard-handlers.ts:364`).
|
||||
- The running-process guard probes the PTY over the active runtime/SSH path and shows the dialog only when child processes exist (`src/renderer/src/components/terminal-pane/TerminalPane.tsx:781`).
|
||||
- There is no way for power users to say "I understand, close it next time" even though similar destructive workflows persist skip-confirm settings (`src/shared/types.ts:2522`, `src/renderer/src/components/settings/GeneralWorkspaceSettingsSection.tsx:58`).
|
||||
|
||||
## Goal
|
||||
|
||||
Make the terminal close confirmation communicate the consequence, respect focused-pane scope, and allow users to disable future running-process close confirmations from the dialog or Settings.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Do not change window-close behavior; whole-window shutdown intentionally bypasses the child-process dialog.
|
||||
- Do not change idle-shell behavior; idle shells still close immediately.
|
||||
- Do not add bulk-close UI for this change.
|
||||
- Do not introduce provider-specific agent kill logic; closing still uses the existing terminal close path.
|
||||
- Do not add telemetry.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add a persisted `skipCloseTerminalWithRunningProcessConfirm` boolean to `GlobalSettings`, defaulting to `false`.
|
||||
2. Keep the existing child-process probe. If the new setting is true, close immediately after the probe reports child processes instead of showing the dialog.
|
||||
3. Track the pending close as `{ paneId, copyKind }`, where `copyKind` is `agent` only when `agentStatusByPaneKey[makePaneKey(tabId, leafId)]` has a live non-unknown `agentType`; otherwise it is `command`.
|
||||
4. Update dialog copy:
|
||||
- command: title `Stop running command?`, body `Closing this terminal will stop the command running inside it.`, destructive button `Stop and Close`.
|
||||
- agent: title `Stop this agent?`, body `Closing this terminal will stop the agent's current work.`, destructive button `Stop Agent`.
|
||||
5. Add a checkbox: `Don't ask again for running terminals`. When checked and confirmed, persist `skipCloseTerminalWithRunningProcessConfirm: true` before closing the pane.
|
||||
6. Add a Terminal Interaction settings switch: `Ask Before Closing Running Terminals`, checked when the skip flag is false.
|
||||
7. Add the new setting to terminal settings search so "confirm", "close", "running", "agent", and "command" find it.
|
||||
|
||||
## Data flow
|
||||
|
||||
- `Cmd/Ctrl+W` or pane close action
|
||||
- `TerminalPane.handleRequestClosePane(paneId)`
|
||||
- Get `ptyId`; no PTY closes immediately
|
||||
- `inspectRuntimeTerminalProcess(settings, ptyId)`
|
||||
- No child processes closes immediately
|
||||
- Child processes + skip setting closes immediately
|
||||
- Child processes + confirmation enabled opens `CloseTerminalDialog(copyKind)`
|
||||
- Confirm optionally persists skip flag, then calls `executeClosePane(paneId)`
|
||||
|
||||
## Edge cases
|
||||
|
||||
- If process inspection rejects, preserve the existing fallback: close the pane instead of trapping the shortcut.
|
||||
- If the pane is removed before the dialog confirms, `executeClosePane` already no-ops when the manager cannot close it.
|
||||
- For split panes, only the active pane gets the prompt and closes.
|
||||
- For last-pane tabs, confirming still delegates to `onCloseTab`.
|
||||
- Agent copy appears only from live pane status. Freshly launched agents that have not emitted hooks yet may use command copy; that is acceptable because the consequence is still accurate.
|
||||
- SSH/runtime-host terminals still use the existing runtime process inspection; the setting lives in global renderer settings and is passed through the same update path.
|
||||
- The skip flag affects only terminal running-process close confirmations, not workspace deletion, automation deletion, window close, or future bulk-close prompts.
|
||||
|
||||
## Test plan
|
||||
|
||||
- Unit/component:
|
||||
- `CloseTerminalDialog` renders command copy, agent copy, checkbox, and reports the checked state on confirm.
|
||||
- Settings search includes the running-terminal confirmation entry.
|
||||
- Default settings include `skipCloseTerminalWithRunningProcessConfirm: false`.
|
||||
- Integration/lightweight:
|
||||
- Verify `TerminalPane` opens agent copy when live pane status has `agentType` and command copy otherwise.
|
||||
- Verify checked confirm persists the skip flag before closing.
|
||||
- Electron:
|
||||
- Running command + default setting shows command confirmation.
|
||||
- Running command + checkbox checked confirms and future close skips the dialog.
|
||||
- Agent pane with live status shows agent confirmation copy.
|
||||
- Idle shell closes without confirmation.
|
||||
|
||||
## UI quality bar
|
||||
|
||||
- Dialog uses existing shadcn `Dialog` and `Button` primitives, token colors, and current compact modal sizing.
|
||||
- Copy names the destructive consequence first and avoids implying every terminal/tab/window will close.
|
||||
- Checkbox is visually subordinate to the message and aligned with existing dense dialog spacing.
|
||||
- Settings row matches neighboring Terminal Interaction switch rows and is searchable.
|
||||
- No layout shift, clipping, or button text overflow at the current modal width.
|
||||
|
||||
## Review screenshots
|
||||
|
||||
1. Running-command confirmation dialog.
|
||||
2. Running-agent confirmation dialog.
|
||||
3. Terminal Interaction settings row for `Ask Before Closing Running Terminals`.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add shared setting type/default.
|
||||
2. Add dialog copy modes and checkbox.
|
||||
3. Wire `TerminalPane` to derive copy kind, honor skip flag, and persist "don't ask again" on confirm.
|
||||
4. Add Terminal settings row and search entry.
|
||||
5. Add targeted tests.
|
||||
6. Force-add this design doc when staging because root `.gitignore` treats new `docs/**` files as local-only by default.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: kept focused on the existing running-process confirmation; no new close routing, bulk-close behavior, or native window-close changes.
|
||||
- Architecture/data flow: renderer-only UI setting rides the existing settings persistence path; process detection remains owned by `inspectRuntimeTerminalProcess` so SSH/runtime compatibility does not fork.
|
||||
- Failure modes covered:
|
||||
- process-inspection rejection preserves current close fallback
|
||||
- stale pane between prompt and confirm no-ops through existing manager guard
|
||||
- split-pane close remains pane-scoped
|
||||
- missing/stale agent status falls back to generic command copy
|
||||
- skip flag is scoped to terminal running-process confirmations only
|
||||
- Test coverage required:
|
||||
- component test for `CloseTerminalDialog` copy/checkbox
|
||||
- shared default/type coverage via existing typecheck plus default-setting assertion
|
||||
- settings search test for new discoverable entry
|
||||
- focused TerminalPane behavior test if practical; otherwise Electron validation covers prompt routing
|
||||
- Performance/blast radius: no polling, IPC, startup, or renderer-jank impact; only an extra settings boolean read during an already user-triggered close path.
|
||||
- UI quality bar: Electron validation should judge the modal and Terminal settings row against `docs/STYLEGUIDE.md`, existing `Dialog`/`Button`/`SettingsSwitchRow`, and adjacent Terminal Interaction density.
|
||||
- Required review screenshots:
|
||||
1. Running-command confirmation dialog
|
||||
2. Running-agent confirmation dialog
|
||||
3. Terminal Interaction settings row
|
||||
- Residual risks: agent-specific copy depends on live hook status, so newly launched or manually run agents can still receive generic command copy; the design doc is ignored by default and must be force-staged for the PR.
|
||||
@@ -1,99 +0,0 @@
|
||||
# Terminal Main-Owned State
|
||||
|
||||
This document covers the hidden-output recovery slice. The broader terminal
|
||||
model/view boundary is defined in
|
||||
[`reference/terminal-model-view-contract.md`](./reference/terminal-model-view-contract.md).
|
||||
|
||||
## Problem
|
||||
|
||||
Hidden and background terminal panes cannot rely on renderer memory as the only
|
||||
place that terminal output exists. Chromium may throttle a hidden Electron
|
||||
document while the PTY continues producing bytes. If the renderer retains every
|
||||
hidden byte until xterm can parse it, a noisy terminal can pin large strings in
|
||||
renderer memory and stall or crash the app.
|
||||
|
||||
The renderer must keep a hard memory bound, but the user-visible terminal state
|
||||
should still be recoverable when the pane becomes visible again.
|
||||
|
||||
## Reference Pattern
|
||||
|
||||
Use a host-owned terminal model as the recovery source and treat the renderer as
|
||||
a view:
|
||||
|
||||
- The host process receives PTY bytes first and appends them to a bounded
|
||||
headless terminal model.
|
||||
- The renderer writes visible output directly for low latency.
|
||||
- Hidden renderer queues are bounded. When they overflow, the renderer marks its
|
||||
xterm as stale and drops further hidden bytes instead of retaining them.
|
||||
- On visibility resume, the renderer asks the host for a serialized snapshot,
|
||||
clears its xterm, replays that snapshot, then resumes live writes.
|
||||
- Live output racing with restore carries a monotonic sequence number, so bytes
|
||||
already included in the snapshot are not written twice.
|
||||
|
||||
This gives the foreground path the same latency profile as today, bounds hidden
|
||||
renderer memory, and preserves terminal state from the host-owned model instead
|
||||
of depending on an unbounded renderer backlog.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Renderer hidden-output memory is capped per terminal.
|
||||
- A hidden flood must not grow the renderer by retaining strings or chunk arrays
|
||||
past the cap.
|
||||
- Restoring a stale renderer must use main/runtime state for local, daemon, and
|
||||
SSH PTYs.
|
||||
- Remote runtime PTYs that do not have local main-owned state must keep the
|
||||
existing warning fallback rather than pretending recovery is available.
|
||||
- Restore must avoid xterm query auto-replies reaching the shell.
|
||||
- Clear, resize, exit, and pane disposal must clean up recovery state.
|
||||
- The SSH path must participate in the same sequencing and snapshot behavior as
|
||||
local PTYs.
|
||||
|
||||
## Chosen Design
|
||||
|
||||
The existing runtime headless terminal is the main-owned model. Every PTY byte
|
||||
already reaches `OrcaRuntimeService.onPtyData` before renderer delivery for
|
||||
local, daemon, and SSH PTYs. That path keeps a headless xterm emulator updated
|
||||
and can serialize it.
|
||||
|
||||
Since the hidden-delivery gate shipped (`terminalHiddenDeliveryGate`, default
|
||||
on — see the contract's Architecture Status), main drops hidden renderer-bound
|
||||
bytes after model ingestion and emits an out-of-band restore marker, so a
|
||||
gated hidden pane accumulates no renderer backlog at all. The overflow path
|
||||
below is the fallback for kill-switch-off mode and for hidden PTYs with an
|
||||
active delivery-interest sidecar.
|
||||
|
||||
The renderer scheduler keeps its 2 MB background cap. When the cap is exceeded:
|
||||
|
||||
1. The scheduler replaces the queued backlog with a small warning fallback.
|
||||
2. The terminal connection marks that pane as needing main-state recovery.
|
||||
3. Further hidden bytes for that stale pane are not enqueued in the renderer.
|
||||
4. When the pane/document becomes visible, the connection requests a main-owned
|
||||
snapshot, clears xterm, replays the snapshot under the replay guard, and
|
||||
sends the normal post-reattach reset.
|
||||
5. Live foreground chunks that arrive while restore is in flight are retained in
|
||||
a small bounded queue. After snapshot replay, sequence numbers decide which
|
||||
chunks were already included and which still need to be written.
|
||||
|
||||
If the main snapshot is unavailable, the small warning fallback remains the
|
||||
visible behavior. That is the expected fallback for surfaces without local
|
||||
main-owned terminal state.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- This does not add a durable full byte log. The host-owned model is bounded
|
||||
terminal state, not an infinite transcript.
|
||||
- This does not throttle the PTY producer. Producer backpressure can be added
|
||||
later with ACKs if we need to reduce host-side work during extreme floods.
|
||||
- This does not change foreground terminal write latency.
|
||||
|
||||
## Verification
|
||||
|
||||
- Unit-test scheduler overflow callback behavior and chunk-count bounding.
|
||||
- Unit-test renderer recovery so hidden overflow drops renderer backlog, fetches
|
||||
the main snapshot on visibility/foreground resume, and does not duplicate
|
||||
sequenced live output.
|
||||
- Unit-test main IPC snapshot sequencing.
|
||||
- Run terminal scheduler and PTY connection tests.
|
||||
- Run typecheck.
|
||||
- Exercise the Electron hidden-flood repro and confirm renderer memory stays
|
||||
bounded while the recovered terminal shows the host-owned terminal state.
|
||||
@@ -1,329 +0,0 @@
|
||||
# Terminal Scroll Intent Architecture
|
||||
|
||||
## Problem
|
||||
|
||||
Terminal panes can jump or jitter when a user switches workspaces while a TUI
|
||||
pane is scrolled near, but not exactly at, the bottom. The most visible case is a
|
||||
Codex-style alternate-screen TUI in a split pane:
|
||||
|
||||
1. The user scrolls slightly up from the bottom.
|
||||
2. The user switches to another workspace.
|
||||
3. The user switches back.
|
||||
4. The terminal sometimes jumps to the top, jumps to the bottom, flashes at a
|
||||
wrong position, or restores an older viewport.
|
||||
|
||||
The current code tries to repair the viewport after layout, fit, split
|
||||
reparenting, hidden-output replay, and visibility resume. Those repairs compete
|
||||
with each other because none of them owns the user's scroll intent. A delayed
|
||||
restore can replay an old state after the user has already scrolled, while a
|
||||
follow-output path can force the bottom even when the user is reading scrollback.
|
||||
|
||||
## Reference Investigation Summary
|
||||
|
||||
The useful reference pattern is not a timer-based restore loop. It is an
|
||||
explicit pinned-to-bottom model owned by the terminal frontend:
|
||||
|
||||
- The frontend stores bottom-following state separately from xterm's transient
|
||||
`viewportY`.
|
||||
- `xterm.onScroll` is not used as user intent. In xterm, that event can be
|
||||
content-driven and can briefly report bottom during fast output or layout work.
|
||||
- User wheel and keyboard scroll commands update the intent.
|
||||
- `scrollToBottom()` is an explicit command that sets the intent back to
|
||||
follow-output.
|
||||
- Every write snapshots the intent before writing. If the terminal was following
|
||||
output, it scrolls to bottom after the write. If the user was pinned to a
|
||||
viewport, it preserves the prior viewport line.
|
||||
- Fit/resize uses the same rule: follow bottom if explicitly pinned, otherwise
|
||||
preserve the current viewport.
|
||||
- Alternate-screen state is tracked from `buffer.active.type`, but it is not a
|
||||
reason to infer user scroll intent from `onScroll`.
|
||||
|
||||
The reference implementation also patches private xterm internals to disable
|
||||
xterm's implicit scroll-to-bottom behavior and call the original bottom-scroll
|
||||
only from explicit owner paths. That gives a clean ownership boundary, but it is
|
||||
an escalation point for Orca because private internals increase xterm upgrade
|
||||
risk.
|
||||
|
||||
## Current Orca Risk Points
|
||||
|
||||
The current Orca branch already has several independent scroll actors:
|
||||
|
||||
- `src/renderer/src/lib/pane-manager/pane-scroll.ts` captures `viewportY`,
|
||||
`baseY`, bottom state, and sometimes a marker, then restores using immediate,
|
||||
rAF, and timeout paths.
|
||||
- `src/renderer/src/lib/pane-manager/pane-tree-ops.ts` captures and restores
|
||||
scroll around `safeFit()`.
|
||||
- `src/renderer/src/lib/pane-manager/pane-split-scroll.ts` schedules split
|
||||
reparent restores across rAF and timeout phases.
|
||||
- `src/renderer/src/components/terminal-pane/use-terminal-scroll-visibility-memory.ts`
|
||||
listens to `terminal.onScroll` and stores snapshots while visible.
|
||||
- `src/renderer/src/components/terminal-pane/pty-connection.ts` writes PTY output
|
||||
through foreground, background, hidden-output skip, snapshot replay, and
|
||||
restore paths.
|
||||
- `src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.ts` can
|
||||
write immediately, enqueue foreground writes, coalesce synchronized output, or
|
||||
drain hidden/background chunks later.
|
||||
|
||||
The biggest architectural mismatch is the visibility memory hook's use of
|
||||
`terminal.onScroll` as a snapshot trigger. That event is not a reliable user
|
||||
scroll signal. During workspace switching, output parsing, hidden replay, or fit
|
||||
can make it persist transient positions that later appear as "older position"
|
||||
restores.
|
||||
|
||||
## Design Goal
|
||||
|
||||
Make terminal viewport movement a result of explicit scroll intent, not a side
|
||||
effect of visibility, output, or layout timing.
|
||||
|
||||
The terminal should have one active scroll intent per pane:
|
||||
|
||||
- `followOutput`: the terminal is logically pinned to the live output bottom.
|
||||
New output, explicit focus-follow requests, and fits may keep it at bottom.
|
||||
- `pinnedViewport`: the user is reading a specific viewport. New output,
|
||||
workspace switches, hidden-output replay, and fits must not move the viewport
|
||||
except when scrollback pruning or buffer replacement makes the exact line
|
||||
impossible.
|
||||
|
||||
## State Model
|
||||
|
||||
Add a focused module, for example:
|
||||
|
||||
`src/renderer/src/lib/pane-manager/terminal-scroll-intent.ts`
|
||||
|
||||
Suggested state:
|
||||
|
||||
```ts
|
||||
export type TerminalScrollIntentKind = 'followOutput' | 'pinnedViewport'
|
||||
|
||||
export type TerminalScrollIntent = {
|
||||
kind: TerminalScrollIntentKind
|
||||
bufferType: 'normal' | 'alternate'
|
||||
viewportY: number
|
||||
baseY: number
|
||||
capturedAt: number
|
||||
}
|
||||
```
|
||||
|
||||
The state should be keyed by the live `Terminal` or by pane leaf identity where
|
||||
it needs to survive pane replacement. For normal workspace switches that keep
|
||||
the same xterm instance, the live terminal-keyed state should be authoritative.
|
||||
|
||||
## Intent Transitions
|
||||
|
||||
Only these events should change scroll intent:
|
||||
|
||||
- User wheel scrolls upward: set `pinnedViewport` immediately before xterm write
|
||||
callbacks or rAF can pull the viewport back down.
|
||||
- User wheel scrolls downward: after xterm applies the scroll, recompute whether
|
||||
the viewport reached bottom. If yes, set `followOutput`; otherwise keep
|
||||
`pinnedViewport`.
|
||||
- User keyboard scroll commands: apply the same rules as wheel.
|
||||
- Explicit `scrollToBottom()`, "follow output", or focus command with
|
||||
follow-output semantics: set `followOutput`.
|
||||
- Programmatic `scrollToTop()` or page/line scroll commands: set
|
||||
`pinnedViewport`, unless the resulting viewport is bottom.
|
||||
- Buffer change to alternate screen: record `bufferType`, but do not infer
|
||||
follow-output from `onScroll`.
|
||||
- Buffer return to normal screen: recompute from current viewport only if no
|
||||
stronger user intent exists for the normal buffer.
|
||||
- Scrollback prune: clamp a pinned viewport to the nearest valid line without
|
||||
changing intent.
|
||||
- Terminal remount/replay: restore from durable fallback only if the live xterm
|
||||
instance was actually replaced.
|
||||
|
||||
Do not use xterm `onScroll` to set intent. It may still be useful as a passive
|
||||
diagnostic signal, but it should not persist authoritative scroll state.
|
||||
|
||||
## Write Contract
|
||||
|
||||
All PTY output that reaches xterm should pass through one wrapper that enforces
|
||||
intent around the actual `terminal.write` call.
|
||||
|
||||
Suggested owner:
|
||||
|
||||
`src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler.ts`
|
||||
|
||||
Contract:
|
||||
|
||||
1. Capture intent and current `viewportY` before the write is scheduled.
|
||||
2. Execute the write through the existing foreground/background/coalescing path.
|
||||
3. After the write has parsed enough for xterm buffer state to be meaningful:
|
||||
- If intent is `followOutput`, scroll to bottom.
|
||||
- If intent is `pinnedViewport`, clamp and restore the saved viewport line.
|
||||
4. Do not schedule multi-frame retries for normal output. A single post-write
|
||||
enforcement point should be enough for standard writes.
|
||||
|
||||
For foreground synchronized-output holds, the enforcement point should run after
|
||||
the held/coalesced frame is released, not for each partial cursor-hide chunk.
|
||||
|
||||
For background writes, preserve `pinnedViewport` if the pane is hidden or
|
||||
inactive. Hidden output should not silently repin the terminal.
|
||||
|
||||
## Fit And Resize Contract
|
||||
|
||||
`safeFit()` should stop using generic delayed scroll restoration as its normal
|
||||
behavior.
|
||||
|
||||
New rule:
|
||||
|
||||
1. If dimensions do not change, do nothing.
|
||||
2. Before fit, capture current intent and viewport.
|
||||
3. Fit.
|
||||
4. If intent is `followOutput`, scroll to bottom.
|
||||
5. If intent is `pinnedViewport`, restore the saved viewport line clamped to the
|
||||
new `baseY`.
|
||||
|
||||
Avoid fitting hidden or zero-geometry panes. Existing geometry guards should
|
||||
remain because fitting to transient workspace-switch geometry can send bad sizes
|
||||
to the PTY and trigger TUI redraw churn.
|
||||
|
||||
## Visibility And Workspace Switch Contract
|
||||
|
||||
Workspace switching should not be a scroll operation.
|
||||
|
||||
On hide:
|
||||
|
||||
- Capture the current intent once.
|
||||
- Do not run scroll restore.
|
||||
- Do not update intent from `onScroll`.
|
||||
- Continue hidden-output throttling/snapshot behavior as today.
|
||||
|
||||
On show:
|
||||
|
||||
- Reattach or refresh renderer resources as needed.
|
||||
- Flush only the bounded amount of hidden output required for the active pane.
|
||||
- Apply intent once after the visible output catch-up:
|
||||
- `followOutput` goes to bottom.
|
||||
- `pinnedViewport` stays pinned.
|
||||
- Do not run repeated rAF/timeout scroll restores.
|
||||
|
||||
If the underlying terminal instance was replaced, use durable fallback state.
|
||||
If the instance stayed alive, its live scroll intent is authoritative.
|
||||
|
||||
## Hidden Output And Snapshot Replay
|
||||
|
||||
Hidden-output snapshot replay is a true fallback path because it clears and
|
||||
reconstructs xterm content. It needs scroll handling, but it should still obey
|
||||
intent:
|
||||
|
||||
- Before snapshot replay, capture intent and viewport.
|
||||
- Replay serialized content.
|
||||
- Fit only if needed and only with valid visible geometry.
|
||||
- Reapply the captured intent once:
|
||||
- `followOutput`: bottom.
|
||||
- `pinnedViewport`: previous viewport line, clamped.
|
||||
- Do not let replay set follow-output just because the replayed buffer ends at
|
||||
bottom.
|
||||
|
||||
If hidden output arrives while the user is pinned, background catch-up should not
|
||||
move the visible viewport on activation.
|
||||
|
||||
## Split Reparenting
|
||||
|
||||
DOM reparenting can reset browser scroll state and WebGL resources. This is a
|
||||
legitimate place for a fallback restore, but it should be scoped:
|
||||
|
||||
- Capture intent before reparent.
|
||||
- Reparent.
|
||||
- Reattach renderer if required.
|
||||
- Apply intent once after DOM settles.
|
||||
- Avoid restoring alternate-screen scrollback, because alternate screen has no
|
||||
normal scrollback and a TUI owns its cursor.
|
||||
|
||||
The current split-specific rAF/timer code should become a local fallback for DOM
|
||||
reparenting only, not a general model copied into workspace switching.
|
||||
|
||||
## Performance Constraints
|
||||
|
||||
The design must preserve Orca's terminal performance priorities:
|
||||
|
||||
- Do not keep all hidden terminals hot-rendering.
|
||||
- Keep PTY/session/xterm state warm when feasible, but suspend hidden rendering
|
||||
work and throttle hidden output as today.
|
||||
- Avoid per-output layout reads. Intent enforcement should read xterm buffer
|
||||
fields, not DOM geometry.
|
||||
- Avoid multi-frame restore loops. They cause visible jitter and keep the
|
||||
renderer busy after activation.
|
||||
- Keep active-pane hidden-output catch-up bounded. Inactive visible split panes
|
||||
can catch up over later frames.
|
||||
- Do not send resize/SIGWINCH unless dimensions actually changed and the
|
||||
renderer is the authoritative size owner.
|
||||
|
||||
The intended steady-state cost is one small buffer-state capture per xterm write
|
||||
batch, not per byte and not per animation frame.
|
||||
|
||||
## Implementation Plan
|
||||
|
||||
1. Add `terminal-scroll-intent.ts`.
|
||||
- Track `followOutput` vs `pinnedViewport`.
|
||||
- Provide helpers for user scroll, explicit bottom, write capture, fit
|
||||
capture, and intent enforcement.
|
||||
|
||||
2. Replace visibility-memory `onScroll` ownership.
|
||||
- Remove authoritative snapshot updates from `terminal.onScroll`.
|
||||
- Add capture-phase wheel listeners and keyboard scroll command hooks.
|
||||
- Keep `onScroll` only for diagnostics if needed.
|
||||
|
||||
3. Route explicit scroll commands through intent helpers.
|
||||
- `scrollToBottom()` sets `followOutput`.
|
||||
- `scrollToTop()`, page up, and line up set `pinnedViewport`.
|
||||
- Downward commands recompute after the command.
|
||||
|
||||
4. Wrap output writes.
|
||||
- Add an intent-aware writer boundary in the output scheduler or in a narrow
|
||||
wrapper used by the scheduler.
|
||||
- Ensure foreground coalescing applies intent after the coalesced frame.
|
||||
- Ensure background drains preserve pinned viewports.
|
||||
|
||||
5. Convert `safeFit()` to intent-aware fit.
|
||||
- Capture intent before fit.
|
||||
- Apply once after fit.
|
||||
- Remove generic deferred scroll restore from normal fit.
|
||||
|
||||
6. Limit restore fallbacks.
|
||||
- Keep fallback restore only for true remount/replay/reparent cases.
|
||||
- Remove workspace-switch rAF/timeout restore loops once intent enforcement is
|
||||
in place.
|
||||
|
||||
7. Add focused tests.
|
||||
- User scroll up sets `pinnedViewport`.
|
||||
- Output while pinned preserves viewport.
|
||||
- Output while following scrolls to bottom.
|
||||
- Fit while pinned preserves viewport.
|
||||
- Fit while following stays at bottom.
|
||||
- Hidden-output replay while pinned does not repin.
|
||||
- Workspace hide/show does not change intent.
|
||||
- `onScroll` does not mutate intent.
|
||||
|
||||
8. Add an E2E reproduction.
|
||||
- Use the existing `scroll-primary` and `scroll-secondary` worktrees.
|
||||
- Top pane in `scroll-primary` contains the TUI with enough scrollback.
|
||||
- Scroll slightly above bottom, switch to `scroll-secondary`, then switch back.
|
||||
- Assert the terminal remains within a small viewport tolerance and does not
|
||||
visit top/bottom during the transition.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- Switching away and back does not move a pinned TUI viewport.
|
||||
- No visible flash to top or bottom during activation.
|
||||
- Scrolling all the way to bottom re-enables follow-output and does not later
|
||||
restore an older pinned position.
|
||||
- Hidden output in inactive workspaces does not change visible scroll position
|
||||
until the user explicitly follows output or reaches bottom.
|
||||
- Alternate-screen TUIs do not receive extra restore/fill behavior that shifts
|
||||
their cursor or scroll region.
|
||||
- The active pane remains responsive during heavy hidden-output catch-up.
|
||||
|
||||
## Open Decisions
|
||||
|
||||
- Whether Orca should patch private xterm bottom-scroll internals. The reference
|
||||
pattern does this for strict ownership, but Orca should first try public API
|
||||
enforcement at write/fit boundaries and only escalate if xterm continues to
|
||||
auto-follow independently.
|
||||
- Whether scroll intent should be stored only by live `Terminal` instance or also
|
||||
mirrored by leaf ID for remount fallback. The initial implementation should
|
||||
use live instance state plus a leaf-keyed fallback for true replacement.
|
||||
- Whether alternate screen needs a separate intent record from normal screen.
|
||||
The first version can use one record with `bufferType`; a separate normal vs
|
||||
alternate record is justified only if testing shows mode switches overwrite
|
||||
user intent.
|
||||
@@ -1,104 +0,0 @@
|
||||
# Windows Secure-File ACL Hardening
|
||||
|
||||
## Problem
|
||||
|
||||
Credential files Orca writes on Windows (runtime env auth store, device registry,
|
||||
e2ee keypair) must end up readable only by the current user, SYSTEM, and
|
||||
Administrators. On POSIX this is a one-line `chmodSync`, but `writeFileSync`'s
|
||||
`mode` option is a no-op on Windows, so the NTFS ACL has to be rewritten by
|
||||
shelling out to PowerShell (`Get-Acl` / `Set-Acl`). PowerShell cold-start is
|
||||
~1–1.5 s.
|
||||
|
||||
`readEnvironmentStore` calls `hardenExistingSecureFile` on every read. The
|
||||
env-store parent directory's mtime churns constantly (every secure write updates
|
||||
it), so an mtime-keyed idempotency cache never matches and a blocking PowerShell
|
||||
spawn fires on every call. After the remote-runtime tab-sync polling change, the
|
||||
store is read ~2×/s, turning sporadic mtime misses into a continuous main-thread
|
||||
storm (~1.8 powershell.exe spawns/sec) that saturates the Electron main thread
|
||||
and times out `runtimeEnvironments:call`. See #4901 / #5006.
|
||||
|
||||
## Model
|
||||
|
||||
`src/shared/secure-file.ts` applies two different caching + execution strategies,
|
||||
chosen by whether the target is a directory and whether it is on the write path:
|
||||
|
||||
- **Directories — async + path-cached for the process lifetime.**
|
||||
A directory's required ACL does not change when its mtime changes, so once a
|
||||
directory has been hardened in this process it is trusted for the rest of the
|
||||
process. Directory hardening uses fire-and-forget `execFile` so it never blocks
|
||||
the main thread. This is the change that kills the #4901 storm.
|
||||
- _Known limitation:_ a directory that is deleted and recreated mid-process is
|
||||
not re-hardened until the next restart. The `.orca` secure dirs are not
|
||||
deleted at runtime, so this is acceptable.
|
||||
|
||||
- **Credential files on the write path — synchronous, cache only on success.**
|
||||
Because `writeFileSync({ mode })` is a no-op on Windows, a freshly written file
|
||||
carries the parent directory's inherited (broader) ACL. `writeSecureFile` must
|
||||
therefore restrict the file's ACL **synchronously** (via `execFileSync`) on the
|
||||
temp file and on the renamed target before it returns — otherwise the function
|
||||
would return with the credential briefly readable under inherited ACLs during
|
||||
the ~1–1.5 s PowerShell cold-start window. The write path is infrequent, so the
|
||||
synchronous cost is acceptable. The path is cached as hardened **only on
|
||||
confirmed success**, so a failed apply is retried on the next write.
|
||||
|
||||
- **Existing files on the read path — async + metadata-cached.**
|
||||
`hardenExistingSecureFile` re-asserts the ACL on an already-existing file at
|
||||
most once per process (keyed on inode/size/timestamps so post-rename inode
|
||||
changes are detected). Async is safe here because it only re-asserts an ACL on a
|
||||
file that already exists; new files are hardened synchronously on the write path
|
||||
above. Because it fires at most once per file, it does not storm.
|
||||
|
||||
The net effect: the frequent read path never blocks the main thread, while the
|
||||
infrequent write path closes the async window so credential files are never
|
||||
published with a broader-than-intended ACL.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Read-path directory and existing-file hardening must not spawn PowerShell more
|
||||
than once per path per process, regardless of mtime churn.
|
||||
- `writeSecureFile` must apply the credential file's ACL synchronously before
|
||||
returning; the file ACL must not be left to a background process.
|
||||
- A failed synchronous file-ACL apply must not crash the write and must not be
|
||||
cached as hardened (so it retries).
|
||||
- No PowerShell is spawned on non-win32 platforms.
|
||||
|
||||
## Manual Windows end-to-end test plan
|
||||
|
||||
The automated e2e harness (`pnpm test:e2e`, Playwright `electron-headless`) runs
|
||||
on `ubuntu-latest`, where `applySecurePathRestriction` short-circuits to
|
||||
`chmodSync` and never reaches the PowerShell path. The ACL storm therefore cannot
|
||||
be reproduced in the cross-platform e2e harness; verify it manually on Windows.
|
||||
|
||||
Pre-req: a Windows client paired to a remote `orca serve` runtime.
|
||||
|
||||
Watcher (PowerShell, run before launching Orca):
|
||||
|
||||
```powershell
|
||||
while ($true) {
|
||||
$n = (Get-CimInstance Win32_Process -Filter "Name='powershell.exe'").Count
|
||||
"{0} powershell.exe count = {1}" -f (Get-Date -Format HH:mm:ss), $n
|
||||
Start-Sleep -Milliseconds 500
|
||||
}
|
||||
```
|
||||
|
||||
Steps:
|
||||
|
||||
1. Launch the **stock v1.4.52/v1.4.53** build and open the remote workspace.
|
||||
- **Before fix:** the watcher oscillates ~1–2 powershell.exe processes/sec
|
||||
continuously through the load window; the app is unresponsive and the
|
||||
`[web-session-tabs-sync] … RemoteRuntimeClientError: Timed out` error
|
||||
appears in the console.
|
||||
2. Launch the **fixed** build and open the same remote workspace.
|
||||
- **After fix:** the watcher stays at `0` (no continuous powershell churn); the
|
||||
env-store directory is hardened at most once; the app loads without the
|
||||
session-tabs timeout.
|
||||
3. Write a credential (e.g. sign in / register a device so a secure file is
|
||||
written), then immediately inspect the file ACL:
|
||||
|
||||
```powershell
|
||||
icacls "$env:APPDATA\orca\orca-environments.json"
|
||||
```
|
||||
|
||||
- **Expected:** only the current user, `SYSTEM`, and `Administrators` have
|
||||
access the instant the write completes (no inherited entries), confirming the
|
||||
synchronous file-ACL apply closed the async window.
|
||||
@@ -1,238 +0,0 @@
|
||||
# Workspace Space Scan Resource Bounds
|
||||
|
||||
## Problem
|
||||
|
||||
Resource Manager scans every non-prunable worktree to calculate workspace disk usage. A fleet with
|
||||
hundreds of worktrees can make Orca and the host unresponsive while the scan is active.
|
||||
|
||||
Two independent resource failures are possible:
|
||||
|
||||
- macOS and Linux run recursive `du` processes for several worktrees at once. Competing full-tree
|
||||
metadata walks can saturate local storage and stall unrelated applications.
|
||||
- Windows, unsupported `du` variants, timeouts, and filesystem errors use a portable recursive
|
||||
walker. The old walker allocated a promise and retained result node for every entry without a
|
||||
capacity limit, so a large worktree could exhaust the main or relay process heap.
|
||||
|
||||
The July 27 incident occurred with 298 Orca worktrees. Renderer telemetry remained far below its
|
||||
heap limit, while quitting Orca immediately restored host responsiveness. The installed binary also
|
||||
contained the uncapped portable fallback.
|
||||
|
||||
## Root Cause
|
||||
|
||||
`src/main/workspace-space-analysis.ts` admitted up to three worktree scans per repository while
|
||||
scanning two repositories concurrently. That allowed as many as six local `du` traversals.
|
||||
|
||||
Both the desktop portable walker and `src/relay/workspace-space-scan.ts` recursively called
|
||||
`Promise.all(entries.map(...))`. Filesystem operation limiters capped active `stat` and `readdir`
|
||||
calls, but they did not cap queued promises, retained paths, directory arrays, or aggregate result
|
||||
nodes. A failed `du` scan then repeated the same traversal through this higher-memory path.
|
||||
|
||||
Shared fixed-worker traversal and capacity primitives already exist, but the active desktop and
|
||||
relay scanners did not use them.
|
||||
|
||||
## Goals
|
||||
|
||||
- Keep the host responsive while scanning hundreds of local worktrees.
|
||||
- Bound portable traversal memory before admitting filesystem entries.
|
||||
- Preserve size totals, symlink behavior, top-level compaction, partial failures, cancellation, and
|
||||
progress reporting.
|
||||
- Apply equivalent bounds to local, folder-workspace, WSL, and SSH relay paths.
|
||||
- Preserve the current WSL-aware Git worktree listing and abort signals.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Make a 298-worktree scan finish quickly.
|
||||
- Change Resource Manager UI, progress copy, deletion rules, or scan persistence.
|
||||
- Exclude `node_modules`, build output, or other directories from reported size.
|
||||
- Change Git worktree discovery or cleanup behavior.
|
||||
- Introduce polling, caching, or background automatic scans.
|
||||
|
||||
## Design
|
||||
|
||||
### Local disk admission
|
||||
|
||||
Create one scan-wide limiter for local worktree traversal. Repository discovery and remote scans can
|
||||
remain concurrent, but every local worktree must acquire the single local slot before invoking
|
||||
`du` or the portable walker.
|
||||
|
||||
The slot is global to one Resource Manager scan, not per repository. This changes the maximum local
|
||||
full-tree traversal count from six to one. Cancellation rejects queued admissions and stops the
|
||||
active child process through the existing `AbortSignal`.
|
||||
|
||||
### Remote fallback admission
|
||||
|
||||
The desktop-side request-by-request SSH fallback runs its traversal inside the desktop main
|
||||
process, so its budget is charged against Orca's heap rather than the remote host. Repository and
|
||||
worktree concurrency alone would let six of these traversals hold six independent budgets at once.
|
||||
A second scan-wide limiter admits at most two, capping aggregate admission at 2 × 64 MiB instead of
|
||||
6 × 64 MiB. Bulk relay scans stay outside this limiter: their traversal memory lives on the remote
|
||||
host, one hard capacity per request.
|
||||
|
||||
### Fixed-worker portable traversal
|
||||
|
||||
Use `scanWorkspaceSpaceEntryTree` for desktop local fallback, desktop remote-provider fallback, and
|
||||
relay fallback scans. The traversal:
|
||||
|
||||
- owns only the configured number of live entry jobs;
|
||||
- preserves source order and aggregate sizes;
|
||||
- uses iterative directory frames instead of recursive promise fanout;
|
||||
- stops on cancellation and removes its abort listener;
|
||||
- treats unreadable or disappearing entries as partial failures;
|
||||
- does not follow symlink targets.
|
||||
|
||||
Top-level `du` result processing uses `mapWithConcurrency` so unusually wide workspace roots do not
|
||||
allocate one live operation per entry.
|
||||
|
||||
### Capacity admission
|
||||
|
||||
Every portable entry is admitted through `WorkspaceSpaceScanBudget` before retention:
|
||||
|
||||
- maximum entries in any one directory listing: 100,000;
|
||||
- maximum estimated live scan state per worktree traversal: 64 MiB.
|
||||
|
||||
The entry cap is per listing rather than per traversal because only a single directory's width is
|
||||
fixed by directory shape. A traversal-wide entry counter is charged by every worker holding a
|
||||
listing at once, so its verdict scales with the configured concurrency: at 48 workers, 48 × 2,100
|
||||
files (100,848 entries) was rejected while 100 × 1,500 (150,100 entries, 50% more) was admitted.
|
||||
Aggregate live retention stays bounded by the 64 MiB byte cap, which all concurrent listings share.
|
||||
|
||||
The retained-byte estimate includes entry name UTF-16 storage plus conservative per-entry object
|
||||
overhead, and each listing's parent path once. The parent path is charged per listing rather than
|
||||
per entry because a listing's entries all share a single parent-path string; charging it per entry
|
||||
multiplied it by the directory's width, so the 64 MiB cap tracked checkout depth instead of live
|
||||
heap and rejected the layouts above once the worktree path passed ~58 characters. These are
|
||||
admission limits, not post-allocation observations.
|
||||
|
||||
The budget measures what the traversal is holding **right now**, not what it has ever seen. A
|
||||
directory listing is charged when admitted and released once every one of its entries has been
|
||||
dispatched, so the caps bound the widest concurrent frontier rather than total tree size. This
|
||||
distinction decides real workspaces: a cumulative counter charged an ordinary 76,788-entry Orca
|
||||
worktree 61.2 MiB of its 64 MiB cap — 4% headroom, and tipping over purely because a longer branch
|
||||
name lengthens every absolute path. The same worktree peaks between 4 MiB and 8 MiB of live state.
|
||||
|
||||
Neither cap may depend on where a user checks out their worktrees, so the estimate charges each
|
||||
absolute path once per listing rather than once per entry. A live cap depends only on directory
|
||||
shape, so it rejects genuinely pathological layouts (one directory holding six figures of entries)
|
||||
and nothing else.
|
||||
|
||||
Top-level directory enumeration for the `du` path uses the same budget. A capacity error must not
|
||||
fall through into the portable walker, because that would repeat an already rejected traversal.
|
||||
|
||||
### Failure behavior
|
||||
|
||||
- Desktop local scan: return an unavailable worktree row with the capacity error. `classifyError`
|
||||
maps `WorkspaceSpaceScanCapacityError` to `unavailable` rather than `error`, because the workspace
|
||||
is intact and readable, just too large to size safely. The Resource Manager renders that row as
|
||||
"Unavailable" instead of "Failed".
|
||||
- SSH relay scan: reject the bulk scan; the desktop provider converts it to an unavailable row.
|
||||
- Generic `du` failure: use the bounded portable fallback.
|
||||
- Cancellation: propagate the scan-cancelled error rather than converting it to a row failure.
|
||||
- Missing or unreadable entries below the capacity limit: preserve existing partial-result
|
||||
behavior.
|
||||
|
||||
### Platform and workspace parity
|
||||
|
||||
- macOS/Linux: one local `du` at a time; bounded Node fallback.
|
||||
- Windows: one local bounded Node traversal at a time.
|
||||
- WSL: retain `getLocalProjectWorktreeGitOptions` and its selected distro for worktree discovery;
|
||||
UNC/native filesystem traversal uses the same local admission and capacity bounds.
|
||||
- SSH: prefer the bulk relay scan; both the relay and the request-by-request compatibility fallback
|
||||
use the shared capacity model.
|
||||
- Folder workspaces: the synthetic main worktree passes through the same local limiter and scanner.
|
||||
|
||||
## Data Flow
|
||||
|
||||
1. Resource Manager starts one deduplicated scan and creates an abort controller.
|
||||
2. Repository workers list worktrees with existing host-specific Git options and the scan signal.
|
||||
3. Remote worktrees continue through provider concurrency. Local worktrees wait for the scan-wide
|
||||
local slot.
|
||||
4. POSIX local or relay scans try `du`.
|
||||
5. Top-level entries are admitted against the scan budget and projected with bounded concurrency.
|
||||
6. If `du` fails generically, the fixed-worker portable traversal scans within the same limits.
|
||||
7. Capacity failures become unavailable rows; successful results keep existing compaction and
|
||||
progress behavior.
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
### Only reduce `du` concurrency
|
||||
|
||||
This protects local storage but leaves Windows, SSH compatibility fallback, and failed `du` scans
|
||||
capable of unbounded heap growth.
|
||||
|
||||
### Only add traversal capacity limits
|
||||
|
||||
This prevents OOM but still permits several recursive `du` processes to compete for local storage,
|
||||
which does not address the observed whole-host stall.
|
||||
|
||||
### Remove the portable fallback
|
||||
|
||||
This would fail Windows scans and POSIX environments where `du -d` is unavailable or errors during
|
||||
active filesystem churn.
|
||||
|
||||
### Skip dependency and build directories
|
||||
|
||||
This would make Resource Manager under-report the directories users most often want to reclaim.
|
||||
|
||||
## Measurement and Performance Budget
|
||||
|
||||
The deterministic regression measurements are:
|
||||
|
||||
- peak simultaneous local `du` calls across repositories: exactly one;
|
||||
- peak simultaneous desktop-side SSH fallback traversals across repositories: at most two;
|
||||
- portable traversal live entry jobs: no more than its configured worker count;
|
||||
- portable entries in any one directory listing: at most 100,000;
|
||||
- estimated live portable state: at most 64 MiB per worktree; an ordinary 76,788-entry worktree
|
||||
peaks between 4 MiB and 8 MiB;
|
||||
- progress and final row counts remain unchanged for scans below the limits.
|
||||
|
||||
A follow-up diagnostic span should record strategy (`du` or portable), worktree duration, fallback
|
||||
reason, admitted entry count, estimated retained bytes, and peak local scan concurrency. It must
|
||||
record counts and identifiers rather than raw paths or directory trees.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- Desktop integration: force the portable path over its entry budget and assert an unavailable row.
|
||||
- Relay integration: force the portable path over its entry budget and assert a capacity failure on
|
||||
both the Windows/portable and POSIX `du` entry points.
|
||||
- Remote fallback concurrency: hold six SSH fallback traversals across two repositories and assert
|
||||
no more than two run at once.
|
||||
- Concurrency: start local worktrees from two repositories, hold the first `du`, and assert the
|
||||
second does not start until the first completes.
|
||||
- Shared traversal: verify worker peak, source order, exact-limit success, over-limit failure, deep
|
||||
trees, partial failures, and cancellation cleanup.
|
||||
- Existing desktop coverage: local results, symlinks, progress, cancellation, WSL routing, SSH bulk
|
||||
scans, disconnected SSH, `du` timeout fallback, and IPC deduplication.
|
||||
- Run `pnpm run typecheck` and `pnpm run build`.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Connect the shared fixed-worker traversal and capacity budget to desktop and relay scanners.
|
||||
2. Add the scan-wide single local traversal slot.
|
||||
3. Add focused capacity and concurrency regression tests.
|
||||
4. Ship without a migration or feature flag; behavior below the limits is unchanged.
|
||||
5. Monitor capacity failures and scan duration before considering a higher local concurrency.
|
||||
|
||||
## Risks
|
||||
|
||||
- Scanning hundreds of worktrees takes longer because local work is serialized. The feature already
|
||||
streams progress and allows users to leave the page, and host responsiveness takes priority over
|
||||
scan throughput.
|
||||
- A legitimate worktree above the capacity limit is reported unavailable instead of partially
|
||||
sized. Failing closed avoids presenting an incomplete size as safe deletion evidence. With a live
|
||||
cap this now requires a pathological directory rather than merely a large repository.
|
||||
- Because the local slot is acquired inside the per-repository worker pool, a local worktree waiting
|
||||
on the slot still occupies one of the six in-flight scan slots. On fleets mixing local and SSH
|
||||
repositories this can delay remote repositories behind serialized local work, even though remote
|
||||
scans never contend for the local disk.
|
||||
- Remote hosts can still process concurrent worktrees, but each relay request has an independent
|
||||
hard capacity and remote concurrency does not contend with the user's local disk.
|
||||
|
||||
## Validation
|
||||
|
||||
- Focused tests: 36 passed across desktop analysis, IPC, relay, shared traversal, scan budget, and
|
||||
concurrency primitives.
|
||||
- TypeScript: all node, CLI, and web projects passed.
|
||||
- Production build: relay targets, CLI, Electron, renderer, web projection, and macOS native
|
||||
components completed successfully.
|
||||
- No live 298-worktree rescan is required for correctness validation; the concurrency and capacity
|
||||
properties are deterministic tests.
|
||||
@@ -1,78 +0,0 @@
|
||||
# Worktree Delete Preflight
|
||||
|
||||
## Problem
|
||||
|
||||
- Local delete paths kill PTYs before git deletion:
|
||||
- `worktrees:remove` IPC (`src/main/ipc/worktrees.ts`)
|
||||
- `removeManagedWorktree` runtime/RPC (`src/main/runtime/orca-runtime.ts`)
|
||||
- On non-force failures (dirty/untracked is common), the worktree stays on disk but terminals are already gone.
|
||||
- PTY teardown is intentionally destructive and best-effort (`src/main/runtime/worktree-teardown.ts`), so non-force deletability must be checked first.
|
||||
|
||||
## Ground Truth From Code
|
||||
|
||||
- There is no dry-run remove path currently used in git helpers (`src/main/git/worktree.ts`).
|
||||
- Errors shown to users are normalized through `formatWorktreeRemovalError` (`src/main/ipc/worktree-logic.ts`).
|
||||
- SSH-backed repos already delegate deletion to provider APIs and should remain provider-owned.
|
||||
- Current orphan cleanup (`is not a working tree` handling + prune + metadata cleanup) lives in IPC/runtime remove catch blocks and must not regress.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Do not change force-delete semantics; force may still kill PTYs before git remove.
|
||||
- Do not add new renderer confirmation states or copy.
|
||||
- Do not attempt to predict every possible git remove failure.
|
||||
- Do not change SSH provider teardown ownership.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add local preflight helper in `src/main/git/worktree.ts`.
|
||||
- Export `assertWorktreeCleanForRemoval(worktreePath: string, force = false): Promise<void>`.
|
||||
- If `force`, return immediately.
|
||||
- Run `git status --porcelain --untracked-files=all` in `cwd = worktreePath`.
|
||||
- If output is non-empty, throw a dedicated error (dirty/untracked).
|
||||
- If command fails, rethrow original error.
|
||||
|
||||
2. IPC local delete ordering (`worktrees:remove`).
|
||||
- Keep canonicalization and protected-path validation first (`getRegisteredDeletableWorktree`).
|
||||
- Keep SSH provider branch unchanged.
|
||||
- Keep archive hook and symlink cleanup before preflight, so preflight checks the exact post-hook/post-symlink state that `git worktree remove` will see.
|
||||
- Run preflight.
|
||||
- If preflight throws an orphan/missing-worktree style error, continue to existing remove path so current orphan cleanup behavior still executes.
|
||||
Treat at least these as orphan-compatible for preflight: `is not a working tree`, `not a git repository`, and missing-path (`ENOENT`) failures from running status in a removed directory.
|
||||
- For other preflight failures, throw via `formatWorktreeRemovalError(...)`.
|
||||
- Only after successful preflight: run `killAllProcessesForWorktree(...)`, then `removeWorktree(...)`.
|
||||
|
||||
3. Runtime/RPC local delete ordering (`removeManagedWorktree`).
|
||||
- Keep SSH branch unchanged.
|
||||
- Keep current hook behavior (archive optional via `--run-hooks`, warning when configured but skipped).
|
||||
- Run preflight after hook handling.
|
||||
- Preserve orphan compatibility exactly as in IPC: preflight must not short-circuit existing orphan cleanup semantics (including `not a git repository`/`ENOENT` preflight failures that should fall through to the existing remove/catch path).
|
||||
- On successful preflight: run PTY teardown, then `removeWorktree`.
|
||||
- Route failures through existing formatted error surface.
|
||||
|
||||
4. Failure-class behavior contract.
|
||||
- Dirty/untracked (non-force): fail before PTY teardown.
|
||||
- Preflight subprocess/tooling failures: fail before PTY teardown, formatted.
|
||||
- Orphan/missing-worktree conditions (`is not a working tree`, `not a git repository`, `ENOENT`): retain current cleanup-and-metadata-removal behavior by running the existing remove/catch flow without PTY teardown.
|
||||
- Force deletes: no preflight; keep current teardown-before-remove order.
|
||||
|
||||
5. Tests.
|
||||
- Update ordering assertions for non-force local deletes to `preflight -> kill -> git`.
|
||||
- Add IPC/runtime tests proving dirty non-force failures happen before any PTY kill.
|
||||
- Add IPC/runtime tests proving preflight error formatting uses `formatWorktreeRemovalError` path.
|
||||
- Add IPC/runtime regression tests proving orphan cleanup still runs when preflight encounters orphan-like failures.
|
||||
- Keep force ordering tests (`kill -> git`).
|
||||
- Keep SSH tests proving local PTY teardown is not used for SSH-backed repos.
|
||||
|
||||
## Concurrency, Consistency, Limits
|
||||
|
||||
- Preflight narrows, but does not close, the race window: external edits can occur after preflight and before `git worktree remove`.
|
||||
- Multi-window and out-of-band mutation races remain possible between canonicalization, hooks/symlink cleanup, preflight, kill, and remove.
|
||||
- IPC has symlink cleanup before preflight; runtime does not. That asymmetry remains unless runtime gains equivalent cleanup.
|
||||
- Cost is one additional git subprocess per non-force local delete; this is acceptable for a user-initiated destructive action.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Implement `assertWorktreeCleanForRemoval` + unit tests in `src/main/git/remove-worktree.test.ts`.
|
||||
2. Wire IPC ordering and failure mapping in `src/main/ipc/worktrees.ts`; update `src/main/ipc/worktrees.test.ts`.
|
||||
3. Wire runtime ordering and failure mapping in `src/main/runtime/orca-runtime.ts`; update `src/main/runtime/orca-runtime.test.ts`.
|
||||
4. Run focused tests, then `pnpm typecheck` and `pnpm lint`.
|
||||
@@ -1,139 +0,0 @@
|
||||
# Worktree Sidebar Drag Autoscroll
|
||||
|
||||
## Problem
|
||||
|
||||
The left sidebar supports reordering worktree rows, but holding a drag near the top or bottom of the scrollable sidebar does not continue scrolling.
|
||||
|
||||
- `src/renderer/src/components/sidebar/WorktreeList.tsx:399` keeps active worktree drag state and cached group rects.
|
||||
- `src/renderer/src/components/sidebar/WorktreeList.tsx:757` computes the drop from `clientY`, the current sidebar `getBoundingClientRect()`, and `scrollTop`.
|
||||
- `src/renderer/src/components/sidebar/WorktreeList.tsx:1400` updates the custom pointer drag only after pointer events.
|
||||
- `src/renderer/src/components/sidebar/WorktreeList.tsx:1660` uses the native drag path for card drag start/over/drop.
|
||||
- `src/renderer/src/components/sidebar/WorktreeList.tsx:1920` renders the scroll container as `[data-worktree-sidebar]`.
|
||||
|
||||
## Current Behavior
|
||||
|
||||
The custom pointer path promotes to an active drag after `SIDEBAR_POINTER_DRAG_THRESHOLD_PX`, creates a fixed preview, stores a `WorktreeDragSession`, and schedules `flushWorktreePointerDrag()` on pointer movement. Drop still uses `computeWorktreeDrop()` and `onReorderWorktrees()`. If `computeWorktreeDrop()` returns null, pointer drops may instead pin or move the worktree to a workspace status target.
|
||||
|
||||
The native HTML5 handlers still exist: they store the same `WorktreeDragSession` on `onCardDragStart`, compute the reorder preview in `onDragOver`, commit through `onDrop` or the capture-phase document drop handler, and clear on `onCardDragEnd` through `WorktreeCard`. In the current list rendering, `WorktreeCard` is passed `nativeDragEnabled={false}`, so the active user-facing worktree reorder path is the custom pointer path. If the native handlers remain in place, keep them consistent; workspace status/pin drops are already handled by `useWorkspaceStatusDocumentDrop()`.
|
||||
|
||||
Scroll bookkeeping already exists. `handleScroll()` calls `markScrollMovement()`, which suppresses virtualizer measurement correction. Direct wheel/touch/scrollbar input additionally calls `markDirectScrollInput()`, which blocks anchor restoration retries. Autoscroll must mark programmatic movement, not direct user input.
|
||||
|
||||
## Root Cause
|
||||
|
||||
Both drag paths are event-driven. When the pointer is held at a sidebar edge, no frame loop changes `scrollTop`; without a scroll change, the virtualized list does not reveal farther rows and `computeWorktreeDrop()` keeps evaluating against the same viewport.
|
||||
|
||||
There is also a virtualization constraint: `computeWorktreeDrop()` only considers `worktreeDragSessionRef.current.rects`, which are a snapshot of the source group's mounted rows at drag start. Autoscroll would reveal new rows but still reject drops outside the original snapshot unless the active session refreshes its source-group rects from the current DOM. Refreshing rects must stay limited to the same `sourceGroupKey`; ordering still commits through the existing `worktreeDragUnitGroups`, `getFullDropIndexForWorktreeDragUnit()`, and `onReorderWorktrees()` path.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Do not change manual ordering, rank persistence, group membership, lineage expansion, selection, pinning, or workspace status semantics.
|
||||
- Do not change the workspace board drawer drag behavior.
|
||||
- Do not add settings, controls, new visual affordances, IPC, persistence, SSH, filesystem, or git-provider behavior.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add a concrete helper for sidebar drag autoscroll, for example `worktree-sidebar-drag-autoscroll.ts`. It should compute a bounded next `scrollTop` from:
|
||||
- latest pointer `clientX`/`clientY`;
|
||||
- container bounds;
|
||||
- `scrollTop`, `scrollHeight`, and `clientHeight`;
|
||||
- elapsed frame time, clamped so a throttled/background frame cannot jump the list.
|
||||
2. The helper must return no-op when the pointer is outside the container horizontally, the pointer is outside the vertical edge zones, or the container is already at the relevant scroll bound.
|
||||
3. Add a small session refresh helper that replaces `worktreeDragSessionRef.current` with the latest `getWorktreeDragRectsForGroup(scrollRef.current, session.sourceGroupKey)` result and revalidates the latest groups: `worktreeDragGroups` must still contain the source group and `session.draggingWorktreeId`, and `worktreeDragUnitGroups` must still contain `session.reorderUnitDraggedIds` for the same `sourceGroupKey`. Do not require every `session.reorderDraggedIds` entry to be in the source group, because the existing multi-select/lineage reorder path filters those ids during commit. If the source group or reordered unit ids disappear, clear the drag instead of committing stale ids.
|
||||
4. Track autoscroll animation frame ids separately from `WorktreePointerDrag.frameId`. The existing `frameId` is for preview/drop flushing; sharing it would make it easy to cancel the wrong work or skip a needed preview update.
|
||||
5. Pointer drag path:
|
||||
- start autoscroll only after `beginWorktreePointerDrag()` promotes the drag to active;
|
||||
- each autoscroll frame reads the latest `drag.currentX/currentY`;
|
||||
- apply `container.scrollTop = nextScrollTop` only when it changes;
|
||||
- call `markScrollMovement()` before or immediately after the scroll write instead of `markDirectScrollInput()`;
|
||||
- refresh source-group rects from the mounted DOM before recomputing a drop; if the virtualizer has not rendered the newly exposed rows yet, keep the current null-drop behavior for that frame;
|
||||
- schedule `scheduleWorktreePointerDragFrame(drag)` after a scroll write so the preview line is recomputed against the new `scrollTop` and refreshed rects.
|
||||
6. Native drag path, if it is kept or re-enabled:
|
||||
- store the latest native drag-over `clientX/clientY` in a small ref while a `WorktreeDragSession` exists;
|
||||
- run a separate autoscroll frame loop from `onDragOver`;
|
||||
- after a scroll write, refresh source-group rects, recompute the native drop preview from the stored `clientY`, and update `worktreeDragState`;
|
||||
- set `event.dataTransfer.dropEffect = 'move'` only inside real `dragover`/`drop` event handlers when the current drop is valid. A RAF callback cannot update the native drag cursor/effect; it can only update sidebar preview state until the next native drag event.
|
||||
7. Cleanup must cancel both pointer and native autoscroll loops on drop, document drop, dragend, pointerup, pointercancel, document visibility loss, component unmount, and `clearWorktreeDrag()`.
|
||||
|
||||
Keep the implementation local to the renderer sidebar. The scroll container remains `scrollRef.current`; do not query arbitrary sidebars globally.
|
||||
|
||||
## Data Flow
|
||||
|
||||
Pointer:
|
||||
|
||||
- Pointer down snapshots source-group rects and arms a non-active pointer drag.
|
||||
- Pointer move beyond the threshold promotes to active, creates the preview, stores the drag session, and starts autoscroll.
|
||||
- Autoscroll frames update `scrollTop` when the latest pointer point is in an edge zone.
|
||||
- After each scroll write, the active session refreshes source-group rects from the current DOM and the normal pointer drag frame recomputes the drop preview using the existing `computeWorktreeDrop()`.
|
||||
- Pointer up commits through the existing `onReorderWorktrees()` path, or through the existing pin/status fallback when no reorder drop is valid.
|
||||
|
||||
Native:
|
||||
|
||||
- If enabled, native drag start stores the drag session and cached source-group rects.
|
||||
- Native drag over stores the latest point, computes the current drop, and starts autoscroll.
|
||||
- Autoscroll frames reuse the latest stored point to update scroll, refresh source-group rects, and recompute preview. They do not try to set `DataTransfer.dropEffect`.
|
||||
- Native drop/document drop commits through the existing reorder path; dragend clears state.
|
||||
|
||||
## Edge Cases
|
||||
|
||||
- Top and bottom bounds: do not keep writing the same `scrollTop`.
|
||||
- Horizontal outside: no sidebar autoscroll if `clientX` is left or right of the scroll container.
|
||||
- Vertical outside: allow scrolling when `clientY` is at or slightly beyond the top/bottom edge, but cap speed.
|
||||
- Threshold: custom pointer autoscroll must not start before the existing drag threshold.
|
||||
- Native event sparsity: continue from the last known drag-over point while events pause, but stop on dragend/drop/visibility loss.
|
||||
- Drop validity while scrolling: if refreshed source-group rects still do not cover the pointer after scroll, preserve the current null-drop behavior rather than guessing a new index.
|
||||
- Virtualized rows: rows can mount/unmount while scrolling. Refresh rects from `[data-worktree-drag-id]` for the source group only, and tolerate a frame where the virtualizer has not mounted newly visible rows yet.
|
||||
- Source mutations: if the dragged worktree, source group, or reorder unit disappears during drag, clear the drag instead of committing against stale ids.
|
||||
- Concurrent ordering changes: final drop should use the latest `worktreeDragGroups`/`worktreeDragUnitGroups` already captured by React callbacks, but the source group and reordered unit ids must be revalidated before commit. Do not rederive a different dragged set mid-drag.
|
||||
- Multi-window/external mutations: this is renderer-local UI state. Do not persist autoscroll state or broadcast it; external list mutations should only invalidate or clear the active drag.
|
||||
- Workspace status and pin targets: preserve pointer fallback behavior and do not make native reorder autoscroll steal document-level status/pin drops. The capture-phase document reorder handler should only prevent default/stop propagation when `computeWorktreeDrop()` returns a valid reorder drop.
|
||||
- Unmount/remount: cancel animation frames and remove previews/styles in the existing cleanup path.
|
||||
|
||||
## Test Plan
|
||||
|
||||
- Unit: add tests for the autoscroll calculation helper covering top edge, bottom edge, middle no-op, horizontal outside, scroll bounds, capped speed, and elapsed-time scaling.
|
||||
- Unit: add tests for the rect/session refresh helper with same-group refresh, missing source group, missing dragged ids, and empty mounted rects.
|
||||
- Unit: add tests for any extracted native/pointer loop coordinator only if it can run without a full virtualized React render.
|
||||
- Unit: keep `worktree-manual-order.test.ts` and `worktree-drag-units.test.ts` passing to prove rank and drag-unit semantics did not change.
|
||||
- Typecheck/lint: run `pnpm run typecheck` and `pnpm run lint`.
|
||||
- Focused tests: run `pnpm test -- src/renderer/src/components/sidebar/worktree-manual-order.test.ts src/renderer/src/components/sidebar/worktree-drag-units.test.ts` plus the new autoscroll helper tests.
|
||||
- Electron/manual: validate a long worktree list by dragging near the bottom until the list scrolls, dropping, then dragging near the top until it scrolls back. Also smoke native drag if it is reachable in the current app configuration.
|
||||
|
||||
## UI Quality Bar
|
||||
|
||||
Follow `docs/STYLEGUIDE.md` and the existing sidebar tokens. This change should not introduce new colors, shadows, controls, or copy. The only visible behavior change is smooth scrolling while dragging near the sidebar edge. The existing floating preview, insertion line, row opacity, status/pin highlights, focus ring, and sidebar scrollbar styling should remain unchanged.
|
||||
|
||||
No clipping, flicker, stuck insertion line, unexpected row jump, or preview lag should appear during autoscroll.
|
||||
|
||||
## Review Screenshots
|
||||
|
||||
Required evidence:
|
||||
|
||||
1. Sidebar precondition with enough worktrees to scroll.
|
||||
2. Pointer drag held near the bottom edge after autoscroll advances the list, with preview and insertion line visible.
|
||||
3. Pointer drag held near the top edge after autoscroll moves back upward, with preview and insertion line visible.
|
||||
4. Final dropped order visible in the sidebar.
|
||||
|
||||
Optional evidence if native drag is enabled in the tested build:
|
||||
|
||||
5. Native drag autoscroll in progress or a note explaining why native drag could not be exercised.
|
||||
|
||||
Do not commit evidence images.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add `worktree-sidebar-drag-autoscroll.ts` and focused unit tests.
|
||||
2. Add session rect refresh/revalidation and use it before drag preview/drop recomputation during active autoscroll.
|
||||
3. Wire custom pointer-drag autoscroll with separate frame cleanup.
|
||||
4. If the native handlers remain supported or are re-enabled, wire native drag-over autoscroll with latest-point storage and document dragend/drop cleanup, keeping `dropEffect` writes inside drag events.
|
||||
5. Run typecheck, lint, focused sidebar tests, and Electron validation with screenshots.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: correctly limited to the worktree sidebar drag paths. The plan must not touch persistence, ordering algorithms, workspace board drawer drag, SSH, filesystem, or git-provider code.
|
||||
- Architecture/data flow: renderer-only helper is appropriate. Pointer and native drag should share the scroll calculation and rect refresh/revalidation, not necessarily the same animation-frame state, because their preview/drop update paths differ.
|
||||
- Failure modes: frame leaks, stale last drag-over points, redundant bound writes, stale session ids after external mutations, virtualization gaps, document-level status/pin drops, invalid `dropEffect` assumptions, and unmount cleanup are in scope.
|
||||
- Tests: pure scroll helper and rect-refresh tests are required. Full virtualized pointer behavior is not a good jsdom target; use focused unit tests plus Electron/manual validation. Existing manual-order tests are regression tests only, not evidence that autoscroll works.
|
||||
- Performance/blast radius: one RAF loop per active drag path is acceptable only while a drag session exists. Avoid layout thrash by reading container rect once per frame before writing `scrollTop`, and avoid React state writes when the recomputed preview is unchanged.
|
||||
- UI quality: no new design surface. Verify smoothness, insertion-line accuracy, existing preview styling, and absence of row jumps against the style guide.
|
||||
- Screenshot requirement: screenshots are required for review evidence but must not be committed.
|
||||
- Residual risks: native drag event behavior differs across Electron/platforms, and virtualized rows may lag one frame behind programmatic scroll writes. Validate the main pointer path first and explicitly document any native limitation found during implementation.
|
||||
@@ -1,115 +0,0 @@
|
||||
# Wrapped Terminal File-Link Fragments
|
||||
|
||||
## Problem
|
||||
|
||||
A file path hard-wrapped between terminal rows is not clickable when the continuation row also contains sibling content. In the reported three-link line, the middle path ends the first row and continues at the start of the second, while the first and third paths remain clickable.
|
||||
|
||||
The provider builds hard-wrap candidates in `wrapped-terminal-link-ranges.ts:172-224`, and both hover and direct modifier-click consume them through `terminal-link-handlers.ts:106-135` and `terminal-file-link-hit-testing.ts:100-109`.
|
||||
|
||||
## Root cause
|
||||
|
||||
`buildHardWrappedPathLogicalLineCandidates` trims and joins whole physical rows. A continuation row is accepted only when the entire trimmed row is a path fragment (`wrapped-terminal-link-ranges.ts:195-203`). A row such as `transparent-...png · validation-screenshots/03-after-light-theme.png` therefore stops reconstruction. Orca probes the two incomplete middle fragments separately, rejects both as nonexistent, and retains only the complete first and third paths.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Changing file-path parsing, filesystem existence semantics, tooltip copy, or open routing.
|
||||
- Joining arbitrary prose, spaced paths, or multiple sibling links into one path.
|
||||
- Relying on xterm soft-wrap metadata for output that was hard-wrapped by an agent or TUI.
|
||||
- Adding a new IPC method, bypassing the existing existence cache, or changing local/SSH/runtime routing.
|
||||
|
||||
## Design
|
||||
|
||||
1. Add a focused regression using the exact three-link/two-row shape. Make the existence stub return true only for the three complete paths, then assert that provider calls for either physical row return the same middle link and exact multi-row range. Assert that no candidate/link spans either `·` separator.
|
||||
2. Reuse the existing conservative hard-wrap fragment alphabet. From a possible first row, slice its maximal fragment suffix; append zero or more continuation rows only while their whole trimmed text is a fragment; then slice the maximal fragment prefix from the first mixed-content row and stop. The only suffixes accepted without a path-name character are an exact POSIX root (`/`), one backslash for the first half of a UNC root, a bare ASCII drive prefix such as `C:`, and the complete relative prefixes `./`, `../`, and `~/`. A boundary candidate is emitted only when it covers the requested row, has at least two non-empty row fragments, and the fully joined text passes the existing path-start predicate. It may end at the first proper prefix slice of a mixed row or at the last available whole-fragment row; the latter is limited to whitelisted incomplete starts and is skipped when whole-row reconstruction already emitted the same text. Existing whole-row candidates remain responsible for ordinary/deep hard wraps, including a mixed starting row followed only by whole-fragment rows.
|
||||
3. Slice `columns` with each fragment so ranges retain the original xterm cells. Build the async-staleness fingerprint from each source row's full translated text and metadata as well as the selected slice; changing a sibling token must invalidate an in-flight result even if the reconstructed path is unchanged.
|
||||
4. Generate at most one boundary candidate per scanned start row—never every suffix/prefix combination. Preserve the existing bounds of 20 possible start rows and 20 rows per candidate, logical-line deduplication, and longest-non-overlapping-link selection. The existing builder can emit up to 210 whole-row candidates in its all-fragment worst case; this change may add at most 20 boundary candidates, not another quadratic set.
|
||||
5. Keep existence validation in the provider's current local/SSH/runtime path and cache. The valid reconstructed path necessarily adds its desired existence lookup compared with the broken behavior; do not add probes for arbitrary suffix/prefix combinations or change existing overlap/cache behavior in this focused fix.
|
||||
6. Verify direct modifier-click fallback from both halves. This path shares the candidate builder but remains synchronous and uses its existing cache/known-root preference before `openDetectedFilePath` performs normal routing checks.
|
||||
|
||||
## Data flow
|
||||
|
||||
- xterm buffer row under hover/click
|
||||
- bounded hard-wrap start/candidate windows and conservative endpoint slicing
|
||||
- whole-row candidates plus at most one boundary candidate per start row
|
||||
- existing terminal file-link parser
|
||||
- existing local/SSH/runtime path resolution and existence cache
|
||||
- mapped multi-row xterm range
|
||||
- hover tooltip or modifier-click open
|
||||
|
||||
## Edge cases
|
||||
|
||||
- A row boundary immediately after POSIX `/`, drive prefix `C:`, the first `\` of a UNC path, or complete `./`, `../`, and `~/` prefixes must reconstruct the complete path. Other punctuation-only suffixes and bare prose tokens remain ineligible, and the joined text must independently satisfy the full path-start predicate.
|
||||
- A continuation prefix may end before a separator (`·`), prose, or a sibling path; none of that suffix may enter the reconstructed candidate.
|
||||
- A starting suffix may begin after prose or a sibling path; its original xterm column must be retained.
|
||||
- Rows containing only one path fragment must keep the existing deep (up to 20 rows) reconstruction behavior.
|
||||
- Soft-wrapped rows, Unicode/multi-code-unit column mappings, known worktree roots, and spaced paths must remain unchanged. In particular, this change does not broaden fragment extraction to whitespace-containing paths.
|
||||
- Full-row source fingerprints must reject stale async results when text inside or outside the selected fragment changes.
|
||||
- Provider calls for remote paths must still use the owning pane's runtime environment or SSH connection and the connection-scoped existence-cache key; fragment extraction itself must not assume a local filesystem.
|
||||
- Incomplete fragment combinations remain filtered by the existing filesystem existence check.
|
||||
|
||||
## Test plan
|
||||
|
||||
- Candidate/range unit: cover the exact suffix/prefix slices, original xterm columns, full-row fingerprint changes, at most one added boundary candidate per start row, and no candidate spanning a sibling separator.
|
||||
- Provider integration: add the exact reported three-link regression to `terminal-link-handlers.test.ts`; across provider calls for both physical rows, assert all three complete links, the same middle range from each call, no incomplete or giant merged link, and that the complete middle path reaches the normal existence check.
|
||||
- Direct click: exercise hit-testing on the first and second physical halves of the middle path and assert both route the same complete path.
|
||||
- Compatibility: cover a backslash/drive-letter wrapped path and a remote-runtime or SSH existence call, proving the reconstructed path keeps the owning connection/environment.
|
||||
- Regression: run `wrapped-terminal-link-ranges.test.ts`, `terminal-link-handlers.test.ts`, and terminal-link parser tests.
|
||||
- Static: run formatter/check, web typecheck, lint, max-lines ratchet, and relevant repository checks.
|
||||
- Electron: render the exact text at the reproduced 133-column terminal width; verify pointer/tooltip and modifier-click from both middle fragments, then smoke-test the first and third links.
|
||||
|
||||
## UI quality bar
|
||||
|
||||
No visual styling changes. The exact same terminal text and layout must render without overlap, clipping, or altered wrapping. The only visible behavior change is that both physical halves of the middle path show the same pointer affordance and tooltip and activate the same file, consistent with the first and third links and `docs/STYLEGUIDE.md` interaction guidance.
|
||||
|
||||
## Review screenshots
|
||||
|
||||
1. Before, on the base revision: full Electron window hovering the broken middle path at the reproduced width (no tooltip/link affordance).
|
||||
2. After: full Electron window hovering the first physical half of the middle path, with tooltip visible.
|
||||
3. After: full Electron window hovering the continuation half, with the same tooltip/path visible.
|
||||
4. After adjacent-feature smoke: full Electron window hovering the first or third complete sibling link.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Add the failing exact-shape regression and range/click assertions.
|
||||
2. Implement boundary-fragment candidate extraction and cell mapping.
|
||||
3. Run focused tests and static checks.
|
||||
4. Validate the exact scenario in Electron and capture screenshots.
|
||||
5. Open an unmerged PR.
|
||||
|
||||
## Lightweight Eng Review
|
||||
|
||||
- Scope: limited to hard-wrapped path candidate reconstruction; parser, routing, cache, and UI styling stay unchanged.
|
||||
- Architecture/data flow: the shared candidate builder remains the single boundary for hover and click behavior, so local, daemon, SSH, and remote runtime flows receive identical ranges before their existing existence checks.
|
||||
- Failure modes covered:
|
||||
- sibling links accidentally merged into one spaced path
|
||||
- only one physical half hit-tests
|
||||
- incorrect xterm columns after slicing
|
||||
- Windows separators rejected
|
||||
- deep single-fragment rows regress
|
||||
- extra remote/local existence probes on hover
|
||||
- Test coverage required:
|
||||
- exact three-link provider regression from both hovered rows
|
||||
- exact range boundary assertions
|
||||
- direct click from both halves
|
||||
- existing deep-wrap, Unicode, stale-result, parser, SSH/runtime tests
|
||||
- Performance/blast radius: preserve the current 20-start-row/20-rows-per-candidate bounds (up to 210 existing whole-row candidates). Boundary extraction is linear per examined row and adds at most 20 candidates, only where a mixed continuation stops whole-row reconstruction. Resolving the previously missing complete path adds the intended cached existence check; the change adds no IPC method and does not alter local/remote routing or cache keys.
|
||||
- UI quality bar: unchanged rendering and style; consistent pointer, tooltip, and activation across both middle fragments, checked in the real Electron terminal against the style guide.
|
||||
- Required review screenshots:
|
||||
1. exact three-link full-window baseline
|
||||
2. middle first-half hover/tooltip
|
||||
3. middle continuation-half hover/tooltip
|
||||
4. first/third sibling hover smoke
|
||||
- Residual risks: local macOS is the available live Electron environment; Windows separator and SSH/runtime behavior require automated coverage and shared-code review.
|
||||
|
||||
## Terminal Reliability Proof
|
||||
|
||||
- Reliability class: `terminal-link.path-boundary-reconstruction`; the broader manifest entry `xterm-addon.boundary-containment` is related but does not register file-link correctness, so this remains an explicit accepted manifest gap rather than changing that gate's scope in a bug fix.
|
||||
- Product change type: renderer runtime hardening with deterministic regression coverage.
|
||||
- Invariant: one logical hard-wrapped file path maps to the same original xterm cells and owning local/SSH/runtime context from either physical row, without absorbing sibling text.
|
||||
- Failure source: the reproduced three-link line where only the first and third links were clickable.
|
||||
- Oracle: both provider row calls return the same complete middle path/range; direct hit-testing on either half opens that path; root-, drive-, and UNC-boundary candidates retain their exact xterm ranges; no emitted boundary candidate contains `·`.
|
||||
- Provider/platform matrix: local and SSH provider behavior covered; Windows separators/cell mapping covered; daemon and remote-runtime use the same builder and routing but are not live-tested; Linux, Windows, WSL, mobile/relay are accepted live-validation gaps.
|
||||
- Performance budget: the scan stays capped at 20 starts and 20 rows per candidate, emits at most one boundary candidate per start, and rejects non-path starts before reading possible continuation rows. No polling, timers, listeners, subprocesses, or new IPC methods are added; only the newly valid path reaches the existing cached existence probe.
|
||||
- Diagnostics: the full source-row fingerprint rejects stale async results; deterministic range/provider tests are the regression breadcrumb. No new product telemetry or raw terminal logging is warranted.
|
||||
- Gate status: no manifest entry added or promoted. Revisit only if this parser grows beyond bounded local row reconstruction or the regression recurs outside the covered provider/platform matrix.
|
||||
- Rollback/demotion rule: revert boundary-fragment reconstruction if Electron shows sibling-path merging, incorrect hit regions, or material hover latency; keep the exact red regression as the behavioral oracle.
|
||||
@@ -1,153 +0,0 @@
|
||||
# WSL OSC 7 Sleep/Wake CWD
|
||||
|
||||
## Problem
|
||||
|
||||
On native Windows, a WSL terminal can persist a fake UNC current working directory and then fail to wake. The deterministic trigger is a WSL shell emitting `file://<machine-hostname>/home/...` before sleep:
|
||||
|
||||
- `osc7-file-uri.ts` treats every non-local authority as a UNC server when parsing Win32 paths.
|
||||
- `Session` constructs its daemon `HeadlessEmulator` without the WSL execution context, so checkpoints can store `\\<machine-hostname>\home\...`.
|
||||
- `OrcaRuntimeService` likewise gives every local Windows PTY Win32 OSC 7 semantics; `remotePosixAuthority` only protects POSIX SSH PTYs.
|
||||
- `HistoryReader.restoreFromIncrementalLog` creates a third context-free emulator. A log containing the OSC 7 can therefore re-create the bad CWD even if the base checkpoint is valid.
|
||||
- `DaemonPtyAdapter.doSpawn` prefers `restoreInfo.cwd` over the requested worktree CWD. `pty-subprocess.ts` later validates the fake UNC and rejects it before spawning WSL.
|
||||
|
||||
Reproduction on Windows 11 build 26200, WSL 2.3.26.0, Ubuntu 24.04.1 LTS, and Orca 1.4.144-rc.4:
|
||||
|
||||
1. Open a terminal in `\\wsl.localhost\Ubuntu\home\<user>\...`.
|
||||
2. Emit `OSC 7;file://<machine-hostname>/home/<user>/...`.
|
||||
3. Sleep for 38-69 seconds, then wake.
|
||||
|
||||
Both triggered attempts failed. The saved CWD became `\\<machine-hostname>\home\<user>\...`; the original WSL UNC remained valid. A 60-second control sleep without the hostname OSC 7 passed.
|
||||
|
||||
## Root cause and invariant
|
||||
|
||||
OSC 7 authority semantics follow the PTY's execution environment, not Electron's host OS. A native Windows shell may legitimately mean `\\server\share` by `file://server/share`; a WSL shell means a POSIX pathname inside its already-known distro. Orca currently classifies local WSL PTYs as generic Win32 PTYs.
|
||||
|
||||
The fix must establish one immutable `wslDistro: string | null` per PTY incarnation before any OSC 7 bytes or recovered history are parsed. The same value must drive daemon live parsing, incremental-history replay, runtime parsing, and legacy CWD recovery. URI authority must never select a distro.
|
||||
|
||||
Resolve that value with the same precedence already used to launch WSL:
|
||||
|
||||
1. distro in an explicit WSL UNC `cwd`;
|
||||
2. distro in the worktree encoded by the daemon session ID;
|
||||
3. trimmed `terminalWindowsWslDistro` selected for the spawn.
|
||||
|
||||
Centralize this resolution with the existing WSL session-context code so the parser and subprocess cannot disagree. Do not infer local WSL context for `connectionId`/SSH PTYs.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Do not change native Windows UNC, POSIX SSH, or remote Windows drive-path semantics.
|
||||
- Do not redesign terminal history, sleep, renderer link routing, or PTY identity.
|
||||
- Do not probe WSL, DNS, the filesystem, or the network on the output path.
|
||||
- Do not infer a distro from an OSC hostname or mutable global/default-distro state.
|
||||
|
||||
## Design
|
||||
|
||||
### 1. Pure conversion and parser context
|
||||
|
||||
Move `toWindowsWslPath` to `src/shared/wsl-paths.ts` and re-export it from `src/main/wsl.ts` for existing callers. Preserve its current rules: lowercase `/mnt/<ascii-letter>` maps to a native drive; every other absolute Linux path maps under `\\wsl.localhost\<distro>`. `/MNT` and `/mnt/C` are case-sensitive Linux paths, not drvfs aliases.
|
||||
|
||||
Add `wslDistro?: string` to `ParseFileUriPathOptions`. When present, `parseFileUriPathParts` must:
|
||||
|
||||
- decode `url.pathname` exactly once;
|
||||
- construct the path with `toWindowsWslPath(decodedPath, wslDistro)`, regardless of URI authority;
|
||||
- continue returning the normalized URI hostname as metadata;
|
||||
- reject malformed URLs/percent encoding as today and leave the prior CWD unchanged.
|
||||
|
||||
Without `wslDistro`, retain every existing `pathFlavor` and `remotePosixAuthority` branch.
|
||||
|
||||
Thread the option through `TerminalOscCwdTitleScanner` and `HeadlessEmulator`. Scanner options are constructor-scoped, so split sequences retain the same context without global state.
|
||||
|
||||
### 2. Daemon and history ownership
|
||||
|
||||
`TerminalHost` resolves the immutable distro before spawning. Pass it both to `createPtySubprocess` and to a new `SessionOptions.wslDistro`; `Session` passes it to its `HeadlessEmulator`. Store the resolved value on `Session` and return it on create/attach so a later window observes the live session's context instead of reinterpreting it from current settings. Make the response field additive/optional for compatibility with an older preserved daemon.
|
||||
|
||||
Extend `HistoryReader.detectColdRestore` with optional parser context and use it for the scratch `HeadlessEmulator` in `restoreFromIncrementalLog`. Every detect path in `DaemonPtyAdapter`--initial detection, probe/create race recovery, and failed history seeding--must pass the same resolved distro. This is required; fixing only the live `Session` leaves incremental restore able to reproduce the bug.
|
||||
|
||||
### 3. Narrow legacy checkpoint recovery
|
||||
|
||||
Immediately after each cold-restore detection, normalize `restoreInfo.cwd` before it becomes `effectiveCwd` or `coldRestore.cwd`. Recovery runs only on native Windows with a resolved local WSL distro:
|
||||
|
||||
1. Preserve an absolute drive path.
|
||||
2. Preserve a `\\wsl.localhost\...` or `\\wsl$\...` path only when its distro matches the resolved distro case-insensitively.
|
||||
3. Convert an absolute POSIX path through the resolved distro.
|
||||
4. Repair the known legacy shape only when the UNC server equals `os.hostname()` case-insensitively: strip the server, interpret the share and tail as the Linux absolute path, then convert it. Thus `\\HOST\mnt\c\x` becomes `C:\x`.
|
||||
5. For a mismatched-distro WSL UNC, another UNC server, a relative path, or malformed input, discard the recovered CWD and fall back to the current requested CWD (or the normal spawn default if none was supplied). Do not guess.
|
||||
|
||||
Apply the corrected/fallback value to both subprocess creation and the returned cold-restore payload. This keeps runtime seeding, the sticky restore cache, `initialCwds`, and the next checkpoint consistent. The repair is idempotent and never mutates history files in place.
|
||||
|
||||
### 4. Runtime ownership and races
|
||||
|
||||
Add `wslDistro: string | null` to `RuntimePtyWorktreeRecord`; a boolean `isWsl` is insufficient for multi-distro parsing. Pass the resolved distro from the spawn result into runtime registration. For reconstructed local records, a WSL UNC worktree may supply a fallback distro via `parseWslUncPath`; never do this for SSH records.
|
||||
|
||||
Daemon PTYs can emit output before `provider.spawn` resolves, and cold-restore seeding currently runs before `registerPty`. Register the expected daemon session's execution context before spawn, then replace it with the daemon-returned immutable value before snapshot/cold-restore seeding. If late discovery changes a context after a runtime emulator was created, discard that emulator and re-seed it from the authoritative provider snapshot; never keep a buffer whose CWD was parsed under mixed contexts.
|
||||
|
||||
Clear execution context with the other per-PTY parser maps on exit, pruning, failed spawn, and provider-generation reset. Reusing a PTY ID must not inherit a prior distro.
|
||||
|
||||
## Data flow
|
||||
|
||||
```text
|
||||
spawn cwd/session/preference
|
||||
-> resolve one immutable local WSL distro
|
||||
-> daemon Session scanner + HistoryReader replay scanner
|
||||
-> decoded OSC 7 pathname (authority retained only as metadata)
|
||||
-> toWindowsWslPath(pathname, distro)
|
||||
-> daemon checkpoint + runtime live/headless CWD
|
||||
-> sleep/wake with a valid WSL UNC or drive CWD
|
||||
```
|
||||
|
||||
Legacy recovery is a boundary repair:
|
||||
|
||||
```text
|
||||
WSL cold restore + old checkpoint CWD
|
||||
-> exact allowlist normalization
|
||||
-> corrected spawn and coldRestore payload
|
||||
-> next checkpoint naturally persists the corrected live CWD
|
||||
```
|
||||
|
||||
## Consistency and failure modes
|
||||
|
||||
- Context is per PTY incarnation, not global, so simultaneous Ubuntu and Debian panes cannot contaminate each other.
|
||||
- The first creator owns a daemon session's immutable context. Concurrent/multi-window attaches consume the stored value; changed settings do not mutate a live session.
|
||||
- A distro mismatch in externally changed history falls back to the requested worktree CWD instead of launching the wrong distro.
|
||||
- Atomic checkpoint replacement remains unchanged. Concurrent restore callers may read different complete generations, but each normalizes before spawn and daemon create/attach still selects one live session.
|
||||
- Missing context deliberately preserves current behavior. Tests must cover every local WSL construction path so this fallback cannot silently remain on the affected path.
|
||||
- Native UNC and SSH behavior remain isolated because neither receives local WSL context.
|
||||
- No filesystem/network work is added per output chunk; parsing remains bounded string work on completed OSC sequences.
|
||||
|
||||
## Test plan
|
||||
|
||||
- `osc7-file-uri.test.ts` and shared WSL-path tests: hostname/localhost/empty WSL authorities; hostname metadata; `/home`, `/`, lowercase `/mnt/c`, `/MNT`, `/mnt/C`; spaces/percent decoding; invalid encoding; native UNC; POSIX SSH; Windows SSH drive paths.
|
||||
- `headless-emulator.test.ts`: WSL context propagation across ordinary and split OSC sequences; two emulators with different distros.
|
||||
- `terminal-host.test.ts`/`session.test.ts`: resolved context reaches the daemon emulator; attach returns the session's stored context and does not adopt a conflicting later preference.
|
||||
- `history-reader.test.ts`: incremental-log replay containing the exact hostname OSC 7 yields the correct WSL CWD.
|
||||
- `daemon-pty-adapter.test.ts`: cover every `detectColdRestore` branch plus sticky-cache output. Repair hostname UNC and POSIX CWDs; preserve matching WSL UNC and drive paths; reject mismatched distro, other UNC, relative, native, and SSH/non-WSL cases. Assert both create/attach CWD and `coldRestore.cwd`.
|
||||
- `orca-runtime.test.ts` and IPC PTY tests: context exists before early daemon output and before headless seeding; Windows-host worktree with a selected WSL distro; WSL UNC fallback after reconstruction; attach correction; PTY-ID reuse; simultaneous distros; local native and SSH isolation.
|
||||
- Run focused tests, then `pnpm typecheck` and `pnpm lint`.
|
||||
- Electron on native Windows: in a real Ubuntu WSL pane, emit the exact hostname OSC 7, sleep/wake twice, run `pwd` after each wake, and verify no `DaemonProtocolError`. Native UNC semantics are covered by deterministic unit tests; a screenshot of an arbitrary UNC string is not meaningful validation.
|
||||
|
||||
## UI quality and review evidence
|
||||
|
||||
There is no UI, layout, copy, or interaction change, so the Stage 5 visual-quality loop is skipped. Terminal content, CWD, and adjacent native/SSH behavior must remain unchanged.
|
||||
|
||||
Electron validation still requires three evidence screenshots for user review:
|
||||
|
||||
1. Before sleep: the WSL terminal shows the printed hostname/emission command and `pwd`.
|
||||
2. After the first wake: the same pane shows the same `pwd` and no wake error.
|
||||
3. After the second wake: the same pane again shows the same `pwd` and no wake error.
|
||||
|
||||
## Lightweight engineering review
|
||||
|
||||
- **Scope:** Parser context, immutable context propagation, history replay, and narrow legacy recovery. Runtime/IPC fields are necessary because parsing begins outside the daemon and may precede spawn completion.
|
||||
- **Architecture/data flow:** One resolved distro drives every parser for one PTY incarnation. The URI hostname remains metadata; it never selects path namespace or distro.
|
||||
- **Failure modes:** Covers missing/stale context, incremental replay, probe/create races, sticky restore, mismatched external history, split chunks, concurrent attaches, multi-window reuse, multi-distro isolation, PTY-ID reuse, and SSH/native boundaries.
|
||||
- **Tests:** Requires parser tables, propagation tests at every emulator construction site, all adapter restore branches, runtime early-byte/seed races, and the deterministic Windows Electron reproduction twice.
|
||||
- **Performance/blast radius:** One optional string per PTY/session and bounded conversion per OSC 7; no probes or new hot-path I/O. Non-WSL behavior is unchanged when the option is absent.
|
||||
- **UI/screenshots:** No design-review loop. Three Electron screenshots are required as functional evidence; native UNC stays an automated regression test.
|
||||
- **Residual risk:** Legacy checkpoints created from a non-machine hostname cannot be distinguished safely from a real UNC and therefore fall back to the requested CWD. A renamed/uninstalled distro still fails normally; this change does not guess a replacement.
|
||||
|
||||
## Rollout
|
||||
|
||||
1. Centralize distro resolution and WSL path conversion.
|
||||
2. Make the parser, daemon Session, and history replay distro-aware.
|
||||
3. Add allowlisted legacy recovery and keep spawn/cold-restore metadata consistent.
|
||||
4. Make runtime context available before output/seeding and reset it per incarnation.
|
||||
5. Add regressions, run static checks, then validate two Windows sleep/wake cycles with review screenshots.
|
||||
@@ -206,6 +206,8 @@ export const electronViteConfig: UserConfig = {
|
||||
external: isExternalMainModule,
|
||||
input: {
|
||||
index: resolve('src/main/index.ts'),
|
||||
// Why: sandboxed webview preloads cannot load Rollup helper chunks.
|
||||
'browser-window-close-preload': resolve('src/preload/browser-window-close.ts'),
|
||||
'daemon-entry': resolve('src/main/daemon/daemon-entry.ts'),
|
||||
'plugin-host-entry': resolve('src/main/plugins/plugin-host-entry.ts'),
|
||||
'computer-sidecar': resolve('src/main/computer/sidecar-entry.ts'),
|
||||
|
||||
@@ -94,6 +94,7 @@ import {
|
||||
import { useWorkspaceSections } from '../../../src/worktree/use-workspace-sections'
|
||||
import { getMobileWorkspaceLineageGroupKey } from '../../../src/worktree/mobile-workspace-lineage'
|
||||
import { areWorktreeListsEqual } from '../../../src/worktree/worktree-list-snapshot'
|
||||
import { WorktreeCatalogSnapshotClient } from '../../../src/worktree/worktree-catalog-snapshot-client'
|
||||
import { repoColor } from '../../../src/worktree/repo-color'
|
||||
import {
|
||||
WORKSPACE_GROUP_OPTIONS as GROUP_OPTIONS,
|
||||
@@ -141,6 +142,9 @@ export function HostScreen({
|
||||
const lastConnectedAt = useLastConnectedAt(hostId)
|
||||
const clientRef = useRef<RpcClient | null>(null)
|
||||
const fetchWorktreesInFlightRef = useRef(false)
|
||||
// Why: useRef, not useMemo — React may discard memoized values, which would silently
|
||||
// reset the snapshot token this object exists to own.
|
||||
const worktreeCatalogRef = useRef(new WorktreeCatalogSnapshotClient())
|
||||
const fetchRepoMetadataInFlightRef = useRef(new WeakSet<RpcClient>())
|
||||
const fetchRepoMetadataPendingRef = useRef(new WeakSet<RpcClient>())
|
||||
const repoMetadataFetchedAtRef = useRef(0)
|
||||
@@ -423,31 +427,32 @@ export function HostScreen({
|
||||
const requestHostId = hostId
|
||||
|
||||
try {
|
||||
// Why: worktree.ps silently truncates at 200; use a high cap so large hosts don't drop workspaces.
|
||||
const response = await requestClient.sendRequest('worktree.ps', { limit: 10000 })
|
||||
const pendingCatalog = await worktreeCatalogRef.current.fetch(requestClient, requestHostId)
|
||||
if (clientRef.current !== requestClient || hostId !== requestHostId) {
|
||||
return
|
||||
}
|
||||
if (!options.allowDuringModal && newWorktreeModalVisibleRef.current) {
|
||||
return
|
||||
}
|
||||
if (response.ok) {
|
||||
const result = (response as RpcSuccess).result as { worktrees: Worktree[] }
|
||||
// Why: unchanged responses still yield the confirmed rows, so every poll reasserts
|
||||
// host truth over optimistic local edits regardless of payload size.
|
||||
const confirmed = worktreeCatalogRef.current.admit(pendingCatalog)
|
||||
if (confirmed) {
|
||||
// Why: reuse the existing array on identical snapshots to keep SectionList/sort rebuilds off the tap path.
|
||||
setWorktrees((current) =>
|
||||
areWorktreeListsEqual(current, result.worktrees) ? current : result.worktrees
|
||||
areWorktreeListsEqual(current, confirmed) ? current : confirmed
|
||||
)
|
||||
setLastKnownWorktrees((current) =>
|
||||
areWorktreeListsEqual(current, result.worktrees) ? current : result.worktrees
|
||||
areWorktreeListsEqual(current, confirmed) ? current : confirmed
|
||||
)
|
||||
setWorktreesLoaded(true)
|
||||
// Why (#8498): overwrite the home-written cache with the confirmed snapshot so a reconnect/remount can't serve a stale list.
|
||||
if (hostId) {
|
||||
setCachedWorktrees(hostId, result.worktrees)
|
||||
setCachedWorktrees(hostId, confirmed)
|
||||
}
|
||||
// Drop the optimistic active override once the host reports it active, so later desktop changes win.
|
||||
setOptimisticActiveWorktreeId((pending) =>
|
||||
pending && result.worktrees.some((w) => w.worktreeId === pending && w.isActive)
|
||||
pending && confirmed.some((w) => w.worktreeId === pending && w.isActive)
|
||||
? null
|
||||
: pending
|
||||
)
|
||||
@@ -459,7 +464,7 @@ export function HostScreen({
|
||||
}
|
||||
const still = new Set<string>()
|
||||
for (const id of prev) {
|
||||
const wt = result.worktrees.find((w) => w.worktreeId === id)
|
||||
const wt = confirmed.find((w) => w.worktreeId === id)
|
||||
if (wt && wt.liveTerminalCount > 0) {
|
||||
still.add(id)
|
||||
}
|
||||
@@ -468,9 +473,7 @@ export function HostScreen({
|
||||
})
|
||||
|
||||
// Sync pin state from server so desktop-initiated pins reflect without relying on stale AsyncStorage.
|
||||
const serverPinned = new Set(
|
||||
result.worktrees.filter((w) => w.isPinned).map((w) => w.worktreeId)
|
||||
)
|
||||
const serverPinned = new Set(confirmed.filter((w) => w.isPinned).map((w) => w.worktreeId))
|
||||
setPinnedIds((prev) => {
|
||||
if (serverPinned.size === prev.size && [...serverPinned].every((id) => prev.has(id))) {
|
||||
return prev
|
||||
|
||||
@@ -117,10 +117,10 @@ import { createTerminalLiveAccessoryInput } from '../../../../src/terminal/termi
|
||||
import { sendTerminalLiveAccessoryRawBytes } from '../../../../src/terminal/terminal-live-accessory-raw-send'
|
||||
import {
|
||||
clearTerminalLiveInputFocusTimer,
|
||||
focusTerminalLiveInputTarget,
|
||||
isTerminalLiveInputWithinByteLimit,
|
||||
scheduleTerminalLiveInputFocus
|
||||
} from '../../../../src/terminal/terminal-live-input'
|
||||
import { useTerminalLiveInputFocus } from '../../../../src/terminal/use-terminal-live-input-focus'
|
||||
import { dismissTerminalKeyboard } from '../../../../src/terminal/terminal-keyboard-dismiss'
|
||||
import type { TerminalLiveInputSender } from '../../../../src/terminal/terminal-live-input-sender'
|
||||
import { isTerminalSendRpcAccepted } from '../../../../src/terminal/terminal-send-rpc-response'
|
||||
@@ -1082,6 +1082,22 @@ export default function SessionScreen() {
|
||||
activeSessionTabType: activeSessionTab?.type
|
||||
})
|
||||
const liveInputEnabled = activeHandle ? liveInputTerminalHandles.has(activeHandle) : false
|
||||
const { focusLiveInput, handleTerminalTap, resetLiveInputFocus } = useTerminalLiveInputFocus({
|
||||
activeHandleRef,
|
||||
canSend,
|
||||
inputRef: liveInputRef,
|
||||
keyboardHeight,
|
||||
lifecycleIdentity: client,
|
||||
lifecycleKey: JSON.stringify([hostId, worktreeId, connState]),
|
||||
liveInputEnabled,
|
||||
timerRef: liveInputFocusTimerRef
|
||||
})
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
// Expo retains this route while pushed screens are visible.
|
||||
return resetLiveInputFocus
|
||||
}, [resetLiveInputFocus])
|
||||
)
|
||||
const [browserScreencastSupported, setBrowserScreencastSupported] = useState<boolean | null>(null)
|
||||
// Why: hosts without aiVault.v1 reject listSessions, so hide the header entry instead of a dead-end "update this host" panel.
|
||||
const [agentSessionHistorySupported, setAgentSessionHistorySupported] = useState<boolean | null>(
|
||||
@@ -3092,17 +3108,6 @@ export default function SessionScreen() {
|
||||
)
|
||||
sendLiveTerminalInputRef.current = sendLiveTerminalInput
|
||||
|
||||
const focusLiveInput = useCallback(() => {
|
||||
if (!canSend || !liveInputEnabled) {
|
||||
return
|
||||
}
|
||||
focusTerminalLiveInputTarget(liveInputRef.current, {
|
||||
keyboardHeight,
|
||||
refocus: () =>
|
||||
scheduleTerminalLiveInputFocus(liveInputFocusTimerRef, () => liveInputRef.current?.focus())
|
||||
})
|
||||
}, [canSend, keyboardHeight, liveInputEnabled])
|
||||
|
||||
const clearSessionTabActionSheetKeyboardListener = useCallback(() => {
|
||||
sessionTabActionSheetKeyboardHideSubRef.current?.remove()
|
||||
sessionTabActionSheetKeyboardHideSubRef.current = null
|
||||
@@ -3177,16 +3182,6 @@ export default function SessionScreen() {
|
||||
})
|
||||
}, [])
|
||||
|
||||
const handleTerminalTap = useCallback(
|
||||
(handle: string) => {
|
||||
if (handle !== activeHandleRef.current) {
|
||||
return
|
||||
}
|
||||
focusLiveInput()
|
||||
},
|
||||
[focusLiveInput]
|
||||
)
|
||||
|
||||
// Tap a terminal file path → resolve on host, open as file tab (mirrors desktop Cmd/Ctrl-click); silent on a miss.
|
||||
const handleFileTapActivationSeqRef = useRef(0)
|
||||
const handleFileTap = useCallback(
|
||||
|
||||
+12
-6
@@ -19,6 +19,7 @@ import { loadHosts } from '../src/transport/host-store'
|
||||
import { navigateToMobileHostEdit } from '../src/transport/host-edit-navigation'
|
||||
import { removeHostAndCloseClient } from '../src/transport/host-removal-lifecycle'
|
||||
import { pickResumeWorktree } from '../src/worktree/resume-worktree'
|
||||
import { WORKTREE_PS_FULL_LIMIT } from '../src/worktree/worktree-catalog-snapshot-client'
|
||||
import type { RpcClient } from '../src/transport/rpc-client'
|
||||
import { sendSingleFlightRequest } from '../src/transport/request-single-flight'
|
||||
import {
|
||||
@@ -49,7 +50,9 @@ import {
|
||||
normalizeVisibleTaskProviders,
|
||||
type TaskProvider
|
||||
} from '../src/tasks/mobile-task-providers'
|
||||
import { useOpenMobileTasks } from '../src/tasks/use-open-mobile-tasks'
|
||||
import { useResponsiveLayout } from '../src/layout/responsive-layout'
|
||||
import { createMobileSessionHref } from '../src/session/mobile-session-route'
|
||||
|
||||
function endpointLabel(endpoint: string): string {
|
||||
try {
|
||||
@@ -176,8 +179,7 @@ function fetchWorktreeInfo(
|
||||
})
|
||||
}
|
||||
|
||||
// Why: worktree.ps defaults to 200 and silently truncates; request all so counts are accurate.
|
||||
sendSingleFlightRequest(client, hostId, 'worktree.ps', { limit: 10000 })
|
||||
sendSingleFlightRequest(client, hostId, 'worktree.ps', { limit: WORKTREE_PS_FULL_LIMIT })
|
||||
.then((response) => {
|
||||
if (disposed()) {
|
||||
return
|
||||
@@ -285,6 +287,7 @@ function repoColor(name: string): string {
|
||||
|
||||
export default function HomeScreen() {
|
||||
const router = useRouter()
|
||||
const openMobileTasks = useOpenMobileTasks()
|
||||
const insets = useSafeAreaInsets()
|
||||
// Why: cap/center content on wide/tablet canvases so cards don't stretch edge-to-edge on iPad.
|
||||
const { isWideLayout, contentMaxWidth } = useResponsiveLayout()
|
||||
@@ -600,10 +603,9 @@ export default function HomeScreen() {
|
||||
if (!primaryConnectedHost) {
|
||||
return
|
||||
}
|
||||
const suffix = provider ? `?taskSource=${provider}` : ''
|
||||
router.push(`/h/${primaryConnectedHost.id}/tasks${suffix}`)
|
||||
openMobileTasks(primaryConnectedHost.id, provider)
|
||||
},
|
||||
[primaryConnectedHost, router]
|
||||
[openMobileTasks, primaryConnectedHost]
|
||||
)
|
||||
const renderTaskHomeCard = () => (
|
||||
<Pressable
|
||||
@@ -807,7 +809,11 @@ export default function HomeScreen() {
|
||||
style={({ pressed }) => [styles.resumeCard, pressed && styles.hostCardPressed]}
|
||||
onPress={() =>
|
||||
router.push(
|
||||
`/h/${resumeWorktree.hostId}/session/${encodeURIComponent(resumeWorktree.worktree.worktreeId)}`
|
||||
createMobileSessionHref({
|
||||
hostId: resumeWorktree.hostId,
|
||||
worktreeId: resumeWorktree.worktree.worktreeId,
|
||||
name: resumeWorktree.worktree.displayName || resumeWorktree.worktree.repo
|
||||
})
|
||||
)
|
||||
}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createMobileSessionHref } from './mobile-session-route'
|
||||
|
||||
const homeSource = readFileSync(new URL('../../app/index.tsx', import.meta.url), 'utf8')
|
||||
|
||||
describe('mobile session route', () => {
|
||||
it('keeps dynamic route identities raw for Expo Router to encode', () => {
|
||||
expect(
|
||||
createMobileSessionHref({
|
||||
hostId: 'host/one',
|
||||
worktreeId: 'repo::/Users/ada/orca/workspaces/fix #1',
|
||||
name: 'Fix #1'
|
||||
})
|
||||
).toEqual({
|
||||
pathname: '/h/[hostId]/session/[worktreeId]',
|
||||
params: {
|
||||
hostId: 'host/one',
|
||||
worktreeId: 'repo::/Users/ada/orca/workspaces/fix #1',
|
||||
name: 'Fix #1'
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('routes the home Resume card through the typed dynamic href', () => {
|
||||
const start = homeSource.indexOf('{/* ─── Resume card ─── */}')
|
||||
const end = homeSource.indexOf('{/* ─── Quick actions ─── */}', start)
|
||||
const resumeCard = homeSource.slice(start, end)
|
||||
|
||||
expect(start).toBeGreaterThanOrEqual(0)
|
||||
expect(end).toBeGreaterThan(start)
|
||||
expect(resumeCard).toContain('createMobileSessionHref({')
|
||||
expect(resumeCard).not.toContain('encodeURIComponent(resumeWorktree.worktree.worktreeId)')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,17 @@
|
||||
export type MobileSessionRouteParams = {
|
||||
hostId: string
|
||||
worktreeId: string
|
||||
name?: string
|
||||
}
|
||||
|
||||
export type MobileSessionHref = {
|
||||
pathname: '/h/[hostId]/session/[worktreeId]'
|
||||
params: MobileSessionRouteParams
|
||||
}
|
||||
|
||||
export function createMobileSessionHref(params: MobileSessionRouteParams): MobileSessionHref {
|
||||
return {
|
||||
pathname: '/h/[hostId]/session/[worktreeId]',
|
||||
params
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
coordinateMobileTasksNavigation,
|
||||
mobileTasksHostRoute,
|
||||
navigateToMobileTasks,
|
||||
type MobileTasksNavigationState
|
||||
} from './mobile-task-navigation'
|
||||
|
||||
function navigationHarness(initialState: MobileTasksNavigationState) {
|
||||
let stateListener = () => {}
|
||||
let state = initialState
|
||||
const unsubscribeState = vi.fn()
|
||||
const navigation = {
|
||||
addListener: vi.fn((_event: 'state', listener: () => void) => {
|
||||
stateListener = listener
|
||||
return unsubscribeState
|
||||
}),
|
||||
dispatch: vi.fn(),
|
||||
getState: () => state
|
||||
}
|
||||
return {
|
||||
navigation,
|
||||
setState(nextState: MobileTasksNavigationState) {
|
||||
state = nextState
|
||||
stateListener()
|
||||
},
|
||||
unsubscribeState
|
||||
}
|
||||
}
|
||||
|
||||
describe('mobile task navigation', () => {
|
||||
it('waits for the expected host commit before navigating to Tasks', () => {
|
||||
const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] })
|
||||
const push = vi.fn()
|
||||
|
||||
navigateToMobileTasks(harness.navigation, { push }, 'host/1')
|
||||
|
||||
expect(harness.navigation.addListener.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
push.mock.invocationCallOrder[0]!
|
||||
)
|
||||
expect(push).toHaveBeenCalledWith(mobileTasksHostRoute('host/1'))
|
||||
expect(harness.navigation.dispatch).not.toHaveBeenCalled()
|
||||
|
||||
harness.setState({
|
||||
index: 1,
|
||||
routes: [{ name: 'index' }, { name: 'h', params: { hostId: 'host/1' } }]
|
||||
})
|
||||
expect(harness.navigation.dispatch).not.toHaveBeenCalled()
|
||||
|
||||
harness.setState({
|
||||
index: 1,
|
||||
routes: [
|
||||
{ name: 'index' },
|
||||
{
|
||||
name: 'h',
|
||||
state: {
|
||||
key: '/h',
|
||||
index: 0,
|
||||
routes: [{ key: 'host-index', name: '[hostId]/index', params: { hostId: 'host/1' } }]
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
expect(harness.unsubscribeState).toHaveBeenCalledOnce()
|
||||
expect(harness.unsubscribeState.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
harness.navigation.dispatch.mock.invocationCallOrder[0]!
|
||||
)
|
||||
expect(harness.navigation.dispatch).toHaveBeenCalledWith({
|
||||
type: 'REPLACE',
|
||||
target: '/h',
|
||||
source: 'host-index',
|
||||
payload: { name: '[hostId]/tasks', params: { hostId: 'host/1' } }
|
||||
})
|
||||
})
|
||||
|
||||
it('ignores unrelated state events and preserves the provider', () => {
|
||||
const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] })
|
||||
|
||||
navigateToMobileTasks(harness.navigation, { push: vi.fn() }, 'host-1', 'linear')
|
||||
harness.setState({ index: 1, routes: [{ name: 'index' }, { name: 'settings' }] })
|
||||
expect(harness.navigation.dispatch).not.toHaveBeenCalled()
|
||||
harness.setState({ index: 0, routes: [{ name: 'h', params: { hostId: 'host-2' } }] })
|
||||
expect(harness.navigation.dispatch).not.toHaveBeenCalled()
|
||||
harness.setState({
|
||||
index: 0,
|
||||
routes: [
|
||||
{
|
||||
name: 'h',
|
||||
state: {
|
||||
key: '/h',
|
||||
index: 0,
|
||||
routes: [{ key: 'host-index', name: '[hostId]/index', params: { hostId: 'host-1' } }]
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
expect(harness.navigation.dispatch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
payload: {
|
||||
name: '[hostId]/tasks',
|
||||
params: { hostId: 'host-1', taskSource: 'linear' }
|
||||
}
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('cleanup prevents a stale navigation from replacing', () => {
|
||||
const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] })
|
||||
const controller = navigateToMobileTasks(harness.navigation, { push: vi.fn() }, 'host-1')
|
||||
|
||||
controller.cancel()
|
||||
harness.setState({ index: 0, routes: [{ name: 'h', params: { hostId: 'host-1' } }] })
|
||||
|
||||
expect(harness.unsubscribeState).toHaveBeenCalledOnce()
|
||||
expect(harness.navigation.dispatch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reuses a pending host push and applies the latest provider', () => {
|
||||
const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] })
|
||||
const push = vi.fn()
|
||||
|
||||
const first = coordinateMobileTasksNavigation(
|
||||
null,
|
||||
harness.navigation,
|
||||
{ push },
|
||||
'host-1',
|
||||
'github'
|
||||
)
|
||||
const second = coordinateMobileTasksNavigation(
|
||||
first,
|
||||
harness.navigation,
|
||||
{ push },
|
||||
'host-1',
|
||||
'linear'
|
||||
)
|
||||
harness.setState({
|
||||
index: 0,
|
||||
routes: [
|
||||
{
|
||||
name: 'h',
|
||||
state: {
|
||||
key: '/h',
|
||||
index: 0,
|
||||
routes: [{ key: 'host-index', name: '[hostId]/index', params: { hostId: 'host-1' } }]
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
expect(second).toBe(first)
|
||||
expect(push).toHaveBeenCalledOnce()
|
||||
expect(harness.navigation.dispatch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
payload: {
|
||||
name: '[hostId]/tasks',
|
||||
params: { hostId: 'host-1', taskSource: 'linear' }
|
||||
}
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('keeps waiting through host setup and cleans up when navigation leaves', () => {
|
||||
const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] })
|
||||
|
||||
navigateToMobileTasks(harness.navigation, { push: vi.fn() }, 'host-1')
|
||||
harness.setState({ index: 0, routes: [{ name: 'h', params: { hostId: 'host-1' } }] })
|
||||
expect(harness.unsubscribeState).not.toHaveBeenCalled()
|
||||
harness.setState({ index: 0, routes: [{ name: 'index' }] })
|
||||
harness.setState({
|
||||
index: 0,
|
||||
routes: [
|
||||
{
|
||||
name: 'h',
|
||||
state: {
|
||||
key: '/h',
|
||||
index: 0,
|
||||
routes: [{ key: 'host-index', name: '[hostId]/index', params: { hostId: 'host-1' } }]
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
expect(harness.unsubscribeState).toHaveBeenCalledOnce()
|
||||
expect(harness.navigation.dispatch).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('unsubscribes when mounting the host throws synchronously', () => {
|
||||
const harness = navigationHarness({ index: 0, routes: [{ name: 'index' }] })
|
||||
const error = new Error('navigation failed')
|
||||
|
||||
expect(() =>
|
||||
navigateToMobileTasks(
|
||||
harness.navigation,
|
||||
{
|
||||
push: () => {
|
||||
throw error
|
||||
}
|
||||
},
|
||||
'host-1'
|
||||
)
|
||||
).toThrow(error)
|
||||
expect(harness.unsubscribeState).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,154 @@
|
||||
import type { TaskProvider } from './mobile-task-providers'
|
||||
|
||||
export type MobileTasksHostRoute = `/h/${string}`
|
||||
|
||||
export type MobileTasksNavigationState = Readonly<{
|
||||
key?: string
|
||||
index: number
|
||||
routes: readonly MobileTasksNavigationRoute[]
|
||||
}>
|
||||
|
||||
export type MobileTasksNavigationRoute = Readonly<{
|
||||
key?: string
|
||||
name: string
|
||||
params?: Readonly<{ hostId?: unknown }>
|
||||
state?: MobileTasksNavigationState
|
||||
}>
|
||||
|
||||
export type MobileTasksRootNavigation = {
|
||||
addListener: (event: 'state', listener: () => void) => () => void
|
||||
dispatch: (action: MobileTasksHostReplaceAction) => void
|
||||
getState: () => MobileTasksNavigationState
|
||||
}
|
||||
|
||||
export type MobileTasksHostReplaceAction = Readonly<{
|
||||
type: 'REPLACE'
|
||||
target: string
|
||||
source: string
|
||||
payload: Readonly<{
|
||||
name: '[hostId]/tasks'
|
||||
params: Readonly<{ hostId: string; taskSource?: TaskProvider }>
|
||||
}>
|
||||
}>
|
||||
|
||||
export type MobileTasksRouter = {
|
||||
push: (route: MobileTasksHostRoute) => void
|
||||
}
|
||||
|
||||
export type MobileTasksNavigationController = Readonly<{
|
||||
cancel: () => void
|
||||
isActive: () => boolean
|
||||
selectProvider: (provider?: TaskProvider) => void
|
||||
}>
|
||||
|
||||
export type PendingMobileTasksNavigation = Readonly<{
|
||||
hostId: string
|
||||
controller: MobileTasksNavigationController
|
||||
}>
|
||||
|
||||
export function mobileTasksHostRoute(hostId: string): MobileTasksHostRoute {
|
||||
return `/h/${encodeURIComponent(hostId)}`
|
||||
}
|
||||
|
||||
function mountedHostStack(
|
||||
state: MobileTasksNavigationState,
|
||||
expectedHostId: string
|
||||
): { key: string; routeKey: string } | null {
|
||||
const hostContainer = state.routes[state.index]
|
||||
const hostState = hostContainer?.state
|
||||
const hostRoute = hostState?.routes[hostState.index]
|
||||
if (
|
||||
hostContainer?.name !== 'h' ||
|
||||
!hostState?.key ||
|
||||
hostRoute?.name !== '[hostId]/index' ||
|
||||
!hostRoute.key ||
|
||||
hostRoute.params?.hostId !== expectedHostId
|
||||
) {
|
||||
return null
|
||||
}
|
||||
return { key: hostState.key, routeKey: hostRoute.key }
|
||||
}
|
||||
|
||||
export function navigateToMobileTasks(
|
||||
navigation: MobileTasksRootNavigation,
|
||||
router: MobileTasksRouter,
|
||||
hostId: string,
|
||||
provider?: TaskProvider
|
||||
): MobileTasksNavigationController {
|
||||
let active = true
|
||||
let hostRouteSeen = false
|
||||
let selectedProvider = provider
|
||||
let unsubscribeState = () => {}
|
||||
const dispose = () => {
|
||||
if (!active) {
|
||||
return
|
||||
}
|
||||
active = false
|
||||
unsubscribeState()
|
||||
}
|
||||
|
||||
// Why: cold Expo deep links resolve to index; target Tasks only after its HostStack exists.
|
||||
const onState = () => {
|
||||
if (!active) {
|
||||
return
|
||||
}
|
||||
const state = navigation.getState()
|
||||
const currentRoute = state.routes[state.index]
|
||||
if (currentRoute?.name === 'h') {
|
||||
hostRouteSeen = true
|
||||
} else if (hostRouteSeen) {
|
||||
dispose()
|
||||
return
|
||||
}
|
||||
const hostStack = mountedHostStack(state, hostId)
|
||||
if (!hostStack) {
|
||||
return
|
||||
}
|
||||
dispose()
|
||||
const action: MobileTasksHostReplaceAction = {
|
||||
type: 'REPLACE',
|
||||
target: hostStack.key,
|
||||
source: hostStack.routeKey,
|
||||
payload: {
|
||||
name: '[hostId]/tasks',
|
||||
params: selectedProvider ? { hostId, taskSource: selectedProvider } : { hostId }
|
||||
}
|
||||
}
|
||||
navigation.dispatch(action)
|
||||
}
|
||||
|
||||
try {
|
||||
unsubscribeState = navigation.addListener('state', onState)
|
||||
router.push(mobileTasksHostRoute(hostId))
|
||||
} catch (error) {
|
||||
dispose()
|
||||
throw error
|
||||
}
|
||||
return {
|
||||
cancel: dispose,
|
||||
isActive: () => active,
|
||||
selectProvider: (nextProvider) => {
|
||||
if (active) {
|
||||
selectedProvider = nextProvider
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function coordinateMobileTasksNavigation(
|
||||
current: PendingMobileTasksNavigation | null,
|
||||
navigation: MobileTasksRootNavigation,
|
||||
router: MobileTasksRouter,
|
||||
hostId: string,
|
||||
provider?: TaskProvider
|
||||
): PendingMobileTasksNavigation {
|
||||
if (current?.hostId === hostId && current.controller.isActive()) {
|
||||
current.controller.selectProvider(provider)
|
||||
return current
|
||||
}
|
||||
current?.controller.cancel()
|
||||
return {
|
||||
hostId,
|
||||
controller: navigateToMobileTasks(navigation, router, hostId, provider)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useCallback, useEffect, useRef } from 'react'
|
||||
import { useNavigation, useRouter } from 'expo-router'
|
||||
import {
|
||||
coordinateMobileTasksNavigation,
|
||||
type MobileTasksRootNavigation,
|
||||
type PendingMobileTasksNavigation
|
||||
} from './mobile-task-navigation'
|
||||
import type { TaskProvider } from './mobile-task-providers'
|
||||
|
||||
export function useOpenMobileTasks(): (hostId: string, provider?: TaskProvider) => void {
|
||||
const navigation = useNavigation<MobileTasksRootNavigation>()
|
||||
const router = useRouter()
|
||||
const pendingRef = useRef<PendingMobileTasksNavigation | null>(null)
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
pendingRef.current?.controller.cancel()
|
||||
pendingRef.current = null
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
return useCallback(
|
||||
(hostId, provider) => {
|
||||
pendingRef.current = coordinateMobileTasksNavigation(
|
||||
pendingRef.current,
|
||||
navigation,
|
||||
router,
|
||||
hostId,
|
||||
provider
|
||||
)
|
||||
},
|
||||
[navigation, router]
|
||||
)
|
||||
}
|
||||
@@ -13,6 +13,10 @@ const commandInputStylesSource = readFileSync(
|
||||
new URL('../../app/h/[hostId]/session/mobile-session-command-input-styles.ts', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
const liveInputFocusSource = readFileSync(
|
||||
new URL('./use-terminal-live-input-focus.ts', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
|
||||
function liveInputBarBlock(): string {
|
||||
const start = sessionRouteSource.indexOf('{liveInputEnabled ? (')
|
||||
@@ -35,9 +39,15 @@ describe('terminal live input affordance', () => {
|
||||
expect(block).toContain('pressed && styles.liveInputFocusTargetPressed')
|
||||
expect(block).toContain('!canSend && styles.liveInputFocusTargetDisabled')
|
||||
expect(block).toContain('showSoftInputOnFocus')
|
||||
expect(sessionRouteSource).toContain('focusTerminalLiveInputTarget(liveInputRef.current')
|
||||
expect(sessionRouteSource).toContain('keyboardHeight')
|
||||
expect(sessionRouteSource).toContain('scheduleTerminalLiveInputFocus(liveInputFocusTimerRef')
|
||||
expect(sessionRouteSource).toContain('useTerminalLiveInputFocus({')
|
||||
expect(sessionRouteSource).toContain('return resetLiveInputFocus')
|
||||
expect(liveInputFocusSource).toContain('focusTerminalLiveInputTarget(inputRef.current')
|
||||
expect(liveInputFocusSource).toContain('lifecycleIdentity,')
|
||||
expect(liveInputFocusSource).toContain('resetLiveInputFocus')
|
||||
expect(liveInputFocusSource).toContain('keyboardHeight: context.keyboardHeight')
|
||||
expect(liveInputFocusSource).toContain(
|
||||
'scheduleTerminalLiveInputFocus(timerRef, focusLiveInput)'
|
||||
)
|
||||
})
|
||||
|
||||
it('makes the live keyboard target visible instead of status-only chrome', () => {
|
||||
|
||||
@@ -179,9 +179,8 @@ export const TERMINAL_MOUSE_CLICK_DRAG_JS = `
|
||||
// Why: a dismissing tap only clears the selection (touch parity); it must
|
||||
// not also open a link or focus the keyboard underneath.
|
||||
if (gesture.dismissedSelection) return;
|
||||
// Plain click == touch tap: links and file paths win, then tracking-mode
|
||||
// click reports, then keyboard focus.
|
||||
notifyTerminalSurfaceTap(e.clientX, e.clientY);
|
||||
// Pointer clicks keep their current link, file, TUI mouse, and focus priority.
|
||||
notifyTerminalSurfaceTap(e.clientX, e.clientY, false);
|
||||
}, true);
|
||||
|
||||
targetSurface.addEventListener('pointercancel', function(e) {
|
||||
|
||||
@@ -18,6 +18,7 @@ describe('terminal WebView external mouse click', () => {
|
||||
expect(bytes.slice(0, 4)).toBe(`${ESC}[M `)
|
||||
expect(bytes.slice(6, 10)).toBe(`${ESC}[M#`)
|
||||
expect(bytes.slice(4, 6)).toBe(bytes.slice(10, 12))
|
||||
expect(mouse.postedMessages().filter((message) => message.type === 'terminal-tap')).toEqual([])
|
||||
})
|
||||
|
||||
it('dismisses an existing selection with a click without focusing the keyboard', () => {
|
||||
|
||||
@@ -212,10 +212,12 @@ describe('TerminalWebView scroll routing', () => {
|
||||
"document.addEventListener('touchend'",
|
||||
'}, { capture: true, passive: true });'
|
||||
)
|
||||
expect(touchEndBlock).toContain('notifyTerminalSurfaceTap(tapCandidate.x, tapCandidate.y)')
|
||||
expect(touchEndBlock).toContain(
|
||||
'notifyTerminalSurfaceTap(tapCandidate.x, tapCandidate.y, true)'
|
||||
)
|
||||
|
||||
const tapHandlerBlock = sliceBetween(
|
||||
'function notifyTerminalSurfaceTap(originX, originY)',
|
||||
'function notifyTerminalSurfaceTap(originX, originY, focusKeyboard)',
|
||||
"document.addEventListener('touchstart'"
|
||||
)
|
||||
expect(tapHandlerBlock.indexOf('oscLinkAtViewportPoint')).toBeLessThan(
|
||||
@@ -229,6 +231,9 @@ describe('TerminalWebView scroll routing', () => {
|
||||
)
|
||||
expect(tapHandlerBlock).toContain("notify({ type: 'open-url', url: tappedUrl });")
|
||||
expect(tapHandlerBlock).toContain("notify({ type: 'terminal-input', bytes: clickInput });")
|
||||
expect(tapHandlerBlock).toContain(
|
||||
'if (focusKeyboard || !isClickMouseTrackingMode(getMouseTrackingMode()))'
|
||||
)
|
||||
expect(tapHandlerBlock).toContain("notify({ type: 'terminal-tap' });")
|
||||
})
|
||||
|
||||
|
||||
@@ -163,7 +163,7 @@ export const TERMINAL_TAP_DISPATCH_JS = `
|
||||
selMode !== 'select' &&
|
||||
Date.now() - tapCandidate.t <= TAP_MAX_MS
|
||||
) {
|
||||
notifyTerminalSurfaceTap(tapCandidate.x, tapCandidate.y);
|
||||
notifyTerminalSurfaceTap(tapCandidate.x, tapCandidate.y, true);
|
||||
}
|
||||
clearLongPress();
|
||||
tapCandidate = null;
|
||||
|
||||
@@ -19,12 +19,12 @@ function bodyMarkup(): string {
|
||||
}
|
||||
|
||||
// Minimal xterm stub: one scrollback line containing a URL, fixed 8x15 cells.
|
||||
function makeTerminal(lineRef: { current: string }) {
|
||||
function makeTerminal(lineRef: { current: string }, mouseTrackingMode = 'none') {
|
||||
return {
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
options: { fontSize: 13 },
|
||||
modes: {},
|
||||
modes: { mouseTrackingMode },
|
||||
element: { scrollWidth: 800, scrollHeight: 360 },
|
||||
_core: { _renderService: { dimensions: { css: { cell: { width: 8, height: 15 } } } } },
|
||||
buffer: {
|
||||
@@ -76,13 +76,14 @@ type OscLinkRange = { row: number; startCol: number; endCol: number; uri: string
|
||||
|
||||
function boot(
|
||||
line: string,
|
||||
oscLinks?: OscLinkRange[]
|
||||
oscLinks?: OscLinkRange[],
|
||||
mouseTrackingMode = 'none'
|
||||
): { posted: Posted; setLine: (line: string) => void } {
|
||||
const posted: Posted = []
|
||||
const lineRef = { current: line }
|
||||
const w = window as unknown as { Terminal: unknown; ReactNativeWebView: unknown }
|
||||
w.Terminal = function () {
|
||||
return makeTerminal(lineRef)
|
||||
return makeTerminal(lineRef, mouseTrackingMode)
|
||||
}
|
||||
w.ReactNativeWebView = {
|
||||
postMessage(s: string) {
|
||||
@@ -150,6 +151,31 @@ describe('terminal WebView tap routing', () => {
|
||||
expect(posted.find((m) => m.type === 'open-url')?.url).toBe('https://example.com/foo')
|
||||
})
|
||||
|
||||
it('focuses native input after reporting a touch tap to a mouse-tracking TUI', async () => {
|
||||
const { posted } = boot('interactive prompt', undefined, 'drag')
|
||||
await settle()
|
||||
|
||||
fireTouch('touchstart', [{ x: 20, y: tapY }])
|
||||
fireTouch('touchend', [])
|
||||
|
||||
expect(
|
||||
posted
|
||||
.filter((message) => message.type === 'terminal-input' || message.type === 'terminal-tap')
|
||||
.map((message) => message.type)
|
||||
).toEqual(['terminal-input', 'terminal-tap'])
|
||||
})
|
||||
|
||||
it('reports a non-mouse touch tap without terminal mouse bytes', async () => {
|
||||
const { posted } = boot('plain prompt')
|
||||
await settle()
|
||||
|
||||
fireTouch('touchstart', [{ x: 20, y: tapY }])
|
||||
fireTouch('touchend', [])
|
||||
|
||||
expect(posted.find((message) => message.type === 'terminal-input')).toBeUndefined()
|
||||
expect(posted.filter((message) => message.type === 'terminal-tap')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('opens the URL even right after a width-change reflow', async () => {
|
||||
// Why: scrollback reflow rewraps the local buffer; the tap path must keep
|
||||
// working afterward (the reflow message must not disturb tap routing).
|
||||
|
||||
@@ -205,7 +205,7 @@ export const URL_TAP_WEBVIEW_JS = `
|
||||
} catch (e) { return 0; }
|
||||
}
|
||||
|
||||
function notifyTerminalSurfaceTap(originX, originY) {
|
||||
function notifyTerminalSurfaceTap(originX, originY, focusKeyboard) {
|
||||
var tappedOscLink = oscLinkAtViewportPoint(originX, originY);
|
||||
if (tappedOscLink && tappedOscLink.kind === 'file') {
|
||||
notify({
|
||||
@@ -245,7 +245,9 @@ export const URL_TAP_WEBVIEW_JS = `
|
||||
var clickInput = buildMouseClickInput(originX, originY);
|
||||
if (clickInput) {
|
||||
notify({ type: 'terminal-input', bytes: clickInput });
|
||||
} else if (!isClickMouseTrackingMode(getMouseTrackingMode())) {
|
||||
}
|
||||
// Touch still needs native input focus after the TUI consumes its mouse click.
|
||||
if (focusKeyboard || !isClickMouseTrackingMode(getMouseTrackingMode())) {
|
||||
notify({ type: 'terminal-tap' });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
import { createElement, type RefObject } from 'react'
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type {
|
||||
TerminalLiveInputFocusTarget,
|
||||
TerminalLiveInputFocusTimerRef
|
||||
} from './terminal-live-input'
|
||||
import { useTerminalLiveInputFocus } from './use-terminal-live-input-focus'
|
||||
|
||||
type HarnessProps = {
|
||||
readonly activeHandleRef: RefObject<string | null>
|
||||
readonly canSend: boolean
|
||||
readonly inputRef: RefObject<TerminalLiveInputFocusTarget | null>
|
||||
readonly keyboardHeight?: number
|
||||
readonly lifecycleIdentity: object | null
|
||||
readonly lifecycleKey: string
|
||||
readonly liveInputEnabled: boolean
|
||||
readonly timerRef: TerminalLiveInputFocusTimerRef
|
||||
}
|
||||
|
||||
type FocusHandlers = ReturnType<typeof useTerminalLiveInputFocus>
|
||||
|
||||
function suppressReactTestRendererWarning(): () => void {
|
||||
const originalConsoleError = console.error
|
||||
const spy = vi.spyOn(console, 'error').mockImplementation((...args) => {
|
||||
if (typeof args[0] === 'string' && args[0].includes('react-test-renderer is deprecated')) {
|
||||
return
|
||||
}
|
||||
originalConsoleError(...args)
|
||||
})
|
||||
return () => spy.mockRestore()
|
||||
}
|
||||
|
||||
function createFocusTarget(initiallyFocused = false): TerminalLiveInputFocusTarget & {
|
||||
readonly blur: ReturnType<typeof vi.fn>
|
||||
readonly focus: ReturnType<typeof vi.fn>
|
||||
} {
|
||||
let focused = initiallyFocused
|
||||
return {
|
||||
blur: vi.fn(() => {
|
||||
focused = false
|
||||
}),
|
||||
focus: vi.fn(() => {
|
||||
focused = true
|
||||
}),
|
||||
isFocused: () => focused
|
||||
}
|
||||
}
|
||||
|
||||
function createTimerRef(): TerminalLiveInputFocusTimerRef {
|
||||
return { current: null }
|
||||
}
|
||||
|
||||
function createHarness(initialProps: HarnessProps): {
|
||||
readonly handlers: () => FocusHandlers
|
||||
readonly render: (props: HarnessProps) => void
|
||||
readonly unmount: () => void
|
||||
} {
|
||||
let handlers: FocusHandlers | null = null
|
||||
let renderer: ReactTestRenderer | null = null
|
||||
|
||||
function Harness(props: HarnessProps): null {
|
||||
handlers = useTerminalLiveInputFocus({
|
||||
...props,
|
||||
keyboardHeight: props.keyboardHeight ?? 0
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
const restoreWarning = suppressReactTestRendererWarning()
|
||||
try {
|
||||
act(() => {
|
||||
renderer = create(createElement(Harness, initialProps))
|
||||
})
|
||||
} finally {
|
||||
restoreWarning()
|
||||
}
|
||||
if (!handlers || !renderer) {
|
||||
throw new Error('terminal live input focus harness did not render')
|
||||
}
|
||||
|
||||
return {
|
||||
handlers: () => {
|
||||
if (!handlers) {
|
||||
throw new Error('terminal live input focus harness is not mounted')
|
||||
}
|
||||
return handlers
|
||||
},
|
||||
render: (props) => {
|
||||
act(() => renderer?.update(createElement(Harness, props)))
|
||||
},
|
||||
unmount: () => {
|
||||
act(() => renderer?.unmount())
|
||||
handlers = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function connectedProps(
|
||||
inputRef: RefObject<TerminalLiveInputFocusTarget | null>,
|
||||
timerRef = createTimerRef(),
|
||||
activeHandleRef: RefObject<string | null> = { current: 'terminal-a' }
|
||||
): HarnessProps {
|
||||
return {
|
||||
activeHandleRef,
|
||||
canSend: true,
|
||||
inputRef,
|
||||
lifecycleIdentity: null,
|
||||
lifecycleKey: 'host-a:worktree-a:connected',
|
||||
liveInputEnabled: true,
|
||||
timerRef
|
||||
}
|
||||
}
|
||||
|
||||
describe('terminal live input focus hook', () => {
|
||||
beforeEach(() => {
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('defers initial terminal surface focus until the WebView touch has completed', () => {
|
||||
vi.useFakeTimers()
|
||||
const input = createFocusTarget()
|
||||
const harness = createHarness(connectedProps({ current: input }))
|
||||
|
||||
harness.handlers().handleTerminalTap('terminal-a')
|
||||
expect(input.focus).not.toHaveBeenCalled()
|
||||
|
||||
vi.runOnlyPendingTimers()
|
||||
expect(input.focus).toHaveBeenCalledTimes(1)
|
||||
harness.unmount()
|
||||
})
|
||||
|
||||
it('reacquires focus for mouse-aware and non-mouse terminal tap notifications', () => {
|
||||
vi.useFakeTimers()
|
||||
const input = createFocusTarget()
|
||||
const harness = createHarness(connectedProps({ current: input }))
|
||||
|
||||
harness.handlers().handleTerminalTap('terminal-a')
|
||||
vi.runOnlyPendingTimers()
|
||||
harness.handlers().handleTerminalTap('terminal-a')
|
||||
vi.runAllTimers()
|
||||
|
||||
expect(input.blur).toHaveBeenCalledTimes(1)
|
||||
expect(input.focus).toHaveBeenCalledTimes(2)
|
||||
harness.unmount()
|
||||
})
|
||||
|
||||
it('cancels focus when navigation reuses the mounted route', () => {
|
||||
vi.useFakeTimers()
|
||||
const oldInput = createFocusTarget()
|
||||
const inputRef: RefObject<TerminalLiveInputFocusTarget | null> = { current: oldInput }
|
||||
const timerRef = createTimerRef()
|
||||
const harness = createHarness(connectedProps(inputRef, timerRef))
|
||||
harness.handlers().handleTerminalTap('terminal-a')
|
||||
const newInput = createFocusTarget()
|
||||
inputRef.current = newInput
|
||||
harness.render({
|
||||
...connectedProps(inputRef, timerRef),
|
||||
lifecycleKey: 'host-a:worktree-b:connected'
|
||||
})
|
||||
vi.runOnlyPendingTimers()
|
||||
expect(oldInput.focus).not.toHaveBeenCalled()
|
||||
expect(newInput.focus).not.toHaveBeenCalled()
|
||||
|
||||
harness.handlers().handleTerminalTap('terminal-a')
|
||||
vi.runOnlyPendingTimers()
|
||||
expect(newInput.focus).toHaveBeenCalledTimes(1)
|
||||
harness.unmount()
|
||||
})
|
||||
|
||||
it('drops pending focus when reconnect reuses the mounted route', () => {
|
||||
vi.useFakeTimers()
|
||||
const oldInput = createFocusTarget()
|
||||
const oldInputRef = { current: oldInput }
|
||||
const timerRef = createTimerRef()
|
||||
const harness = createHarness(connectedProps(oldInputRef, timerRef))
|
||||
harness.handlers().handleTerminalTap('terminal-a')
|
||||
harness.render({
|
||||
...connectedProps(oldInputRef, timerRef),
|
||||
canSend: false,
|
||||
lifecycleIdentity: {},
|
||||
lifecycleKey: 'host-a:worktree-a:disconnected'
|
||||
})
|
||||
vi.runOnlyPendingTimers()
|
||||
expect(oldInput.focus).not.toHaveBeenCalled()
|
||||
|
||||
const replacementInput = createFocusTarget()
|
||||
oldInputRef.current = replacementInput
|
||||
harness.render({
|
||||
...connectedProps(oldInputRef, timerRef),
|
||||
lifecycleIdentity: {},
|
||||
lifecycleKey: 'host-a:worktree-a:connected'
|
||||
})
|
||||
harness.handlers().handleTerminalTap('terminal-a')
|
||||
vi.runOnlyPendingTimers()
|
||||
expect(replacementInput.focus).toHaveBeenCalledTimes(1)
|
||||
harness.unmount()
|
||||
})
|
||||
|
||||
it('cancels focus when a retained screen blurs', () => {
|
||||
vi.useFakeTimers()
|
||||
const input = createFocusTarget()
|
||||
const timerRef = createTimerRef()
|
||||
const harness = createHarness(connectedProps({ current: input }, timerRef))
|
||||
|
||||
harness.handlers().handleTerminalTap('terminal-a')
|
||||
harness.handlers().resetLiveInputFocus()
|
||||
vi.runOnlyPendingTimers()
|
||||
|
||||
expect(timerRef.current).toBeNull()
|
||||
expect(input.blur).toHaveBeenCalledTimes(1)
|
||||
expect(input.focus).not.toHaveBeenCalled()
|
||||
harness.unmount()
|
||||
})
|
||||
|
||||
it('does not let stale handle state focus a replacement terminal', () => {
|
||||
vi.useFakeTimers()
|
||||
const firstInput = createFocusTarget()
|
||||
const inputRef: RefObject<TerminalLiveInputFocusTarget | null> = { current: firstInput }
|
||||
const timerRef = createTimerRef()
|
||||
const activeHandleRef = { current: 'terminal-a' as string | null }
|
||||
const harness = createHarness(connectedProps(inputRef, timerRef, activeHandleRef))
|
||||
harness.handlers().handleTerminalTap('terminal-a')
|
||||
|
||||
const replacementInput = createFocusTarget()
|
||||
inputRef.current = replacementInput
|
||||
activeHandleRef.current = 'terminal-b'
|
||||
harness.render(connectedProps(inputRef, timerRef, activeHandleRef))
|
||||
vi.runOnlyPendingTimers()
|
||||
|
||||
expect(firstInput.focus).not.toHaveBeenCalled()
|
||||
expect(replacementInput.focus).not.toHaveBeenCalled()
|
||||
harness.handlers().handleTerminalTap('terminal-b')
|
||||
vi.runOnlyPendingTimers()
|
||||
expect(replacementInput.focus).toHaveBeenCalledTimes(1)
|
||||
harness.unmount()
|
||||
})
|
||||
|
||||
it('keeps the native focus target immediate outside the WebView tap path', () => {
|
||||
const input = createFocusTarget()
|
||||
const harness = createHarness(connectedProps({ current: input }))
|
||||
|
||||
harness.handlers().focusLiveInput()
|
||||
|
||||
expect(input.focus).toHaveBeenCalledTimes(1)
|
||||
harness.unmount()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,86 @@
|
||||
import { useCallback, useLayoutEffect, useRef, type RefObject } from 'react'
|
||||
import {
|
||||
clearTerminalLiveInputFocusTimer,
|
||||
focusTerminalLiveInputTarget,
|
||||
scheduleTerminalLiveInputFocus,
|
||||
type TerminalLiveInputFocusTarget,
|
||||
type TerminalLiveInputFocusTimerRef
|
||||
} from './terminal-live-input'
|
||||
|
||||
type TerminalLiveInputFocusContext = {
|
||||
readonly canSend: boolean
|
||||
readonly keyboardHeight: number
|
||||
readonly liveInputEnabled: boolean
|
||||
}
|
||||
|
||||
type UseTerminalLiveInputFocusOptions<T extends TerminalLiveInputFocusTarget> =
|
||||
TerminalLiveInputFocusContext & {
|
||||
readonly activeHandleRef: RefObject<string | null>
|
||||
readonly inputRef: RefObject<T | null>
|
||||
readonly lifecycleIdentity: object | null
|
||||
readonly lifecycleKey: string
|
||||
readonly timerRef: TerminalLiveInputFocusTimerRef
|
||||
}
|
||||
|
||||
type TerminalLiveInputFocusHandlers = {
|
||||
readonly focusLiveInput: () => void
|
||||
readonly handleTerminalTap: (handle: string) => void
|
||||
readonly resetLiveInputFocus: () => void
|
||||
}
|
||||
|
||||
export function useTerminalLiveInputFocus<T extends TerminalLiveInputFocusTarget>({
|
||||
activeHandleRef,
|
||||
canSend,
|
||||
inputRef,
|
||||
keyboardHeight,
|
||||
lifecycleIdentity,
|
||||
lifecycleKey,
|
||||
liveInputEnabled,
|
||||
timerRef
|
||||
}: UseTerminalLiveInputFocusOptions<T>): TerminalLiveInputFocusHandlers {
|
||||
const contextRef = useRef<TerminalLiveInputFocusContext>({
|
||||
canSend,
|
||||
keyboardHeight,
|
||||
liveInputEnabled
|
||||
})
|
||||
useLayoutEffect(() => {
|
||||
contextRef.current = { canSend, keyboardHeight, liveInputEnabled }
|
||||
}, [canSend, keyboardHeight, liveInputEnabled])
|
||||
|
||||
const resetLiveInputFocus = useCallback(() => {
|
||||
clearTerminalLiveInputFocusTimer(timerRef)
|
||||
inputRef.current?.blur()
|
||||
}, [inputRef, timerRef])
|
||||
|
||||
// Retained Expo routes must not carry focus work across navigation or reconnect scopes.
|
||||
useLayoutEffect(() => resetLiveInputFocus, [lifecycleIdentity, lifecycleKey, resetLiveInputFocus])
|
||||
|
||||
const focusLiveInput = useCallback(() => {
|
||||
const context = contextRef.current
|
||||
if (!context.canSend || !context.liveInputEnabled) {
|
||||
return
|
||||
}
|
||||
focusTerminalLiveInputTarget(inputRef.current, {
|
||||
keyboardHeight: context.keyboardHeight,
|
||||
refocus: () => scheduleTerminalLiveInputFocus(timerRef, focusLiveInput)
|
||||
})
|
||||
}, [inputRef, timerRef])
|
||||
|
||||
const handleTerminalTap = useCallback(
|
||||
(handle: string) => {
|
||||
const context = contextRef.current
|
||||
if (handle !== activeHandleRef.current || !context.canSend || !context.liveInputEnabled) {
|
||||
return
|
||||
}
|
||||
// WKWebView still owns first responder during its touchend notification.
|
||||
scheduleTerminalLiveInputFocus(timerRef, () => {
|
||||
if (activeHandleRef.current === handle) {
|
||||
focusLiveInput()
|
||||
}
|
||||
})
|
||||
},
|
||||
[activeHandleRef, focusLiveInput, timerRef]
|
||||
)
|
||||
|
||||
return { focusLiveInput, handleTerminalTap, resetLiveInputFocus }
|
||||
}
|
||||
@@ -101,12 +101,14 @@ describe('startHostWorktreeRefresh', () => {
|
||||
expect(fetchRepoMetadata).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('force-refreshes repo metadata on reposChanged', () => {
|
||||
it('refreshes worktrees and repo metadata on reposChanged', () => {
|
||||
start()
|
||||
fetchWorktrees.mockClear()
|
||||
fetchRepoMetadata.mockClear()
|
||||
|
||||
eventListener?.({ type: 'reposChanged' })
|
||||
|
||||
expect(fetchWorktrees).toHaveBeenCalledOnce()
|
||||
expect(fetchRepoMetadata).toHaveBeenCalledOnce()
|
||||
expect(fetchRepoMetadata).toHaveBeenCalledWith({ force: true, queueIfInFlight: true })
|
||||
})
|
||||
|
||||
@@ -69,6 +69,8 @@ export function startHostWorktreeRefresh({
|
||||
return
|
||||
}
|
||||
if (event.type === 'reposChanged') {
|
||||
// Why: folder workspace mutations publish reposChanged, and worktree.ps owns this catalog.
|
||||
void fetchWorktrees()
|
||||
void fetchRepoMetadata({ force: true, queueIfInFlight: true })
|
||||
} else if (event.type === 'worktreesChanged') {
|
||||
void fetchWorktrees()
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { RpcClient } from '../transport/rpc-client'
|
||||
import {
|
||||
admitWorktreeCatalogResponse,
|
||||
WORKTREE_PS_FULL_LIMIT,
|
||||
WorktreeCatalogSnapshotClient
|
||||
} from './worktree-catalog-snapshot-client'
|
||||
|
||||
describe('admitWorktreeCatalogResponse', () => {
|
||||
it('accepts new-host full and unchanged responses', () => {
|
||||
const full = admitWorktreeCatalogResponse(
|
||||
{ worktrees: [{ id: 'worktree-1' }], snapshotId: 'snapshot-1' },
|
||||
null
|
||||
)
|
||||
const unchanged = admitWorktreeCatalogResponse(
|
||||
{ unchanged: true, snapshotId: 'snapshot-1' },
|
||||
'snapshot-1'
|
||||
)
|
||||
|
||||
expect(full).toEqual({
|
||||
kind: 'full',
|
||||
snapshotId: 'snapshot-1',
|
||||
worktrees: [{ id: 'worktree-1' }]
|
||||
})
|
||||
expect(unchanged).toEqual({ kind: 'unchanged', snapshotId: 'snapshot-1' })
|
||||
})
|
||||
|
||||
it('treats an old-host full response as authoritative and clears the token', () => {
|
||||
expect(
|
||||
admitWorktreeCatalogResponse({ worktrees: [{ id: 'worktree-1' }] }, 'stale-token')
|
||||
).toEqual({
|
||||
kind: 'full',
|
||||
snapshotId: null,
|
||||
worktrees: [{ id: 'worktree-1' }]
|
||||
})
|
||||
})
|
||||
|
||||
it('classifies by rows, so a future `unchanged` catalog field cannot hide a full response', () => {
|
||||
expect(
|
||||
admitWorktreeCatalogResponse(
|
||||
{ worktrees: [{ id: 'worktree-1' }], unchanged: false, snapshotId: 'snapshot-1' },
|
||||
'snapshot-1'
|
||||
)
|
||||
).toEqual({
|
||||
kind: 'full',
|
||||
snapshotId: 'snapshot-1',
|
||||
worktrees: [{ id: 'worktree-1' }]
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects unchanged responses for a snapshot the client does not own', () => {
|
||||
expect(
|
||||
admitWorktreeCatalogResponse({ unchanged: true, snapshotId: 'snapshot-2' }, 'snapshot-1')
|
||||
).toEqual({ kind: 'invalid' })
|
||||
expect(admitWorktreeCatalogResponse({ unchanged: true }, 'snapshot-1')).toEqual({
|
||||
kind: 'invalid'
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects malformed success payloads', () => {
|
||||
expect(admitWorktreeCatalogResponse(null, 'snapshot-1')).toEqual({ kind: 'invalid' })
|
||||
expect(admitWorktreeCatalogResponse({ unchanged: false }, 'snapshot-1')).toEqual({
|
||||
kind: 'invalid'
|
||||
})
|
||||
})
|
||||
|
||||
it('accepts a full response but ignores an out-of-bounds snapshot id', () => {
|
||||
expect(
|
||||
admitWorktreeCatalogResponse({ worktrees: [], snapshotId: 'x'.repeat(129) }, null)
|
||||
).toEqual({ kind: 'full', snapshotId: null, worktrees: [] })
|
||||
})
|
||||
})
|
||||
|
||||
function clientWithResults(...results: unknown[]): RpcClient {
|
||||
return {
|
||||
sendRequest: vi.fn(
|
||||
async () =>
|
||||
({
|
||||
id: 'request',
|
||||
ok: true,
|
||||
result: results.shift(),
|
||||
_meta: { runtimeId: 'runtime' }
|
||||
}) as const
|
||||
)
|
||||
} as unknown as RpcClient
|
||||
}
|
||||
|
||||
describe('WorktreeCatalogSnapshotClient', () => {
|
||||
it('returns the confirmed rows on unchanged responses so callers can reassert them', async () => {
|
||||
const rows = [{ worktreeId: 'worktree-1' }]
|
||||
const client = clientWithResults(
|
||||
{ worktrees: rows, snapshotId: 'snapshot-1' },
|
||||
{ unchanged: true, snapshotId: 'snapshot-1' }
|
||||
)
|
||||
const snapshots = new WorktreeCatalogSnapshotClient()
|
||||
|
||||
const first = snapshots.admit(await snapshots.fetch(client, 'host-1'))
|
||||
const second = snapshots.admit(await snapshots.fetch(client, 'host-1'))
|
||||
|
||||
expect(first).toEqual(rows)
|
||||
expect(second).toEqual(rows)
|
||||
})
|
||||
|
||||
it('does not advance the token until the caller admits a response', async () => {
|
||||
const client = clientWithResults(
|
||||
{ worktrees: [], snapshotId: 'snapshot-1' },
|
||||
{ worktrees: [], snapshotId: 'snapshot-1' }
|
||||
)
|
||||
const snapshots = new WorktreeCatalogSnapshotClient()
|
||||
|
||||
await snapshots.fetch(client, 'host-1')
|
||||
snapshots.admit(await snapshots.fetch(client, 'host-1'))
|
||||
|
||||
expect(client.sendRequest).toHaveBeenNthCalledWith(2, 'worktree.ps', {
|
||||
limit: WORKTREE_PS_FULL_LIMIT,
|
||||
afterSnapshotId: null
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves the last admitted token across transport failures', async () => {
|
||||
const client = clientWithResults({ worktrees: [], snapshotId: 'snapshot-1' })
|
||||
const snapshots = new WorktreeCatalogSnapshotClient()
|
||||
|
||||
snapshots.admit(await snapshots.fetch(client, 'host-1'))
|
||||
snapshots.admit(null)
|
||||
await snapshots.fetch(client, 'host-1')
|
||||
|
||||
expect(client.sendRequest).toHaveBeenNthCalledWith(2, 'worktree.ps', {
|
||||
limit: WORKTREE_PS_FULL_LIMIT,
|
||||
afterSnapshotId: 'snapshot-1'
|
||||
})
|
||||
})
|
||||
|
||||
it('clears snapshot ownership after a mismatched unchanged response', async () => {
|
||||
const client = clientWithResults(
|
||||
{ worktrees: [], snapshotId: 'snapshot-1' },
|
||||
{ unchanged: true, snapshotId: 'snapshot-2' },
|
||||
{ worktrees: [], snapshotId: 'snapshot-3' }
|
||||
)
|
||||
const snapshots = new WorktreeCatalogSnapshotClient()
|
||||
|
||||
snapshots.admit(await snapshots.fetch(client, 'host-1'))
|
||||
snapshots.admit(await snapshots.fetch(client, 'host-1'))
|
||||
await snapshots.fetch(client, 'host-1')
|
||||
|
||||
expect(client.sendRequest).toHaveBeenNthCalledWith(3, 'worktree.ps', {
|
||||
limit: WORKTREE_PS_FULL_LIMIT,
|
||||
afterSnapshotId: null
|
||||
})
|
||||
})
|
||||
|
||||
it('resets snapshot ownership when the client or host changes', async () => {
|
||||
const firstClient = clientWithResults({ worktrees: [], snapshotId: 'snapshot-1' })
|
||||
const secondClient = clientWithResults({ worktrees: [], snapshotId: 'snapshot-2' })
|
||||
const snapshots = new WorktreeCatalogSnapshotClient()
|
||||
|
||||
snapshots.admit(await snapshots.fetch(firstClient, 'host-1'))
|
||||
await snapshots.fetch(secondClient, 'host-2')
|
||||
|
||||
expect(secondClient.sendRequest).toHaveBeenCalledWith('worktree.ps', {
|
||||
limit: WORKTREE_PS_FULL_LIMIT,
|
||||
afterSnapshotId: null
|
||||
})
|
||||
})
|
||||
|
||||
it('drops a superseded host response without invalidating the current token', async () => {
|
||||
const firstClient = clientWithResults({ worktrees: [], snapshotId: 'snapshot-1' })
|
||||
const secondClient = clientWithResults({ worktrees: [], snapshotId: 'snapshot-2' })
|
||||
const snapshots = new WorktreeCatalogSnapshotClient()
|
||||
|
||||
// Host A's response is still in flight when the screen switches to host B.
|
||||
const stale = await snapshots.fetch(firstClient, 'host-1')
|
||||
snapshots.admit(await snapshots.fetch(secondClient, 'host-2'))
|
||||
expect(snapshots.admit(stale)).toBeNull()
|
||||
|
||||
await snapshots.fetch(secondClient, 'host-2')
|
||||
expect(secondClient.sendRequest).toHaveBeenNthCalledWith(2, 'worktree.ps', {
|
||||
limit: WORKTREE_PS_FULL_LIMIT,
|
||||
afterSnapshotId: 'snapshot-2'
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,107 @@
|
||||
import type { RpcClient } from '../transport/rpc-client'
|
||||
import type { RpcSuccess } from '../transport/types'
|
||||
import type { Worktree } from './workspace-list-sections'
|
||||
|
||||
// Why: worktree.ps silently truncates at 200; use a high cap so large hosts don't drop workspaces.
|
||||
export const WORKTREE_PS_FULL_LIMIT = 10_000
|
||||
|
||||
export type WorktreeCatalogAdmission<T> =
|
||||
| { kind: 'full'; snapshotId: string | null; worktrees: T[] }
|
||||
| { kind: 'unchanged'; snapshotId: string }
|
||||
| { kind: 'invalid' }
|
||||
|
||||
type PendingWorktreeCatalog = {
|
||||
admission: WorktreeCatalogAdmission<Worktree>
|
||||
client: RpcClient
|
||||
hostId: string
|
||||
}
|
||||
|
||||
function validSnapshotId(value: unknown): string | null {
|
||||
return typeof value === 'string' && value.length > 0 && value.length <= 128 ? value : null
|
||||
}
|
||||
|
||||
export function admitWorktreeCatalogResponse<T>(
|
||||
result: unknown,
|
||||
requestedSnapshotId: string | null
|
||||
): WorktreeCatalogAdmission<T> {
|
||||
if (!result || typeof result !== 'object') {
|
||||
return { kind: 'invalid' }
|
||||
}
|
||||
const response = result as {
|
||||
snapshotId?: unknown
|
||||
unchanged?: unknown
|
||||
worktrees?: unknown
|
||||
}
|
||||
// Why: a full response is defined by carrying rows, so discriminate on that rather
|
||||
// than on the presence of `unchanged` — the latter could collide with a future
|
||||
// catalog field and silently reclassify a full response.
|
||||
if (Array.isArray(response.worktrees)) {
|
||||
return {
|
||||
kind: 'full',
|
||||
snapshotId: validSnapshotId(response.snapshotId),
|
||||
worktrees: response.worktrees as T[]
|
||||
}
|
||||
}
|
||||
|
||||
const snapshotId = validSnapshotId(response.snapshotId)
|
||||
if (response.unchanged === true && snapshotId && snapshotId === requestedSnapshotId) {
|
||||
return { kind: 'unchanged', snapshotId }
|
||||
}
|
||||
return { kind: 'invalid' }
|
||||
}
|
||||
|
||||
export class WorktreeCatalogSnapshotClient {
|
||||
private client: RpcClient | null = null
|
||||
private hostId: string | null = null
|
||||
private snapshotId: string | null = null
|
||||
private confirmedWorktrees: Worktree[] | null = null
|
||||
|
||||
async fetch(client: RpcClient, hostId: string): Promise<PendingWorktreeCatalog | null> {
|
||||
if (this.client !== client || this.hostId !== hostId) {
|
||||
this.client = client
|
||||
this.hostId = hostId
|
||||
this.snapshotId = null
|
||||
this.confirmedWorktrees = null
|
||||
}
|
||||
const requestedSnapshotId = this.snapshotId
|
||||
const response = await client.sendRequest('worktree.ps', {
|
||||
limit: WORKTREE_PS_FULL_LIMIT,
|
||||
afterSnapshotId: requestedSnapshotId
|
||||
})
|
||||
if (!response.ok) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
admission: admitWorktreeCatalogResponse<Worktree>(
|
||||
(response as RpcSuccess).result,
|
||||
requestedSnapshotId
|
||||
),
|
||||
client,
|
||||
hostId
|
||||
}
|
||||
}
|
||||
|
||||
/** The confirmed host catalog to apply, or null when there is nothing to apply. */
|
||||
admit(pending: PendingWorktreeCatalog | null): Worktree[] | null {
|
||||
if (!pending) {
|
||||
return null
|
||||
}
|
||||
// Why: a response from a superseded client/host is stale, not wrong — dropping it
|
||||
// must not invalidate the token the current client/host just established.
|
||||
if (pending.client !== this.client || pending.hostId !== this.hostId) {
|
||||
return null
|
||||
}
|
||||
if (pending.admission.kind === 'invalid') {
|
||||
this.snapshotId = null
|
||||
return null
|
||||
}
|
||||
|
||||
this.snapshotId = pending.admission.snapshotId
|
||||
if (pending.admission.kind === 'full') {
|
||||
this.confirmedWorktrees = pending.admission.worktrees
|
||||
}
|
||||
// Why: unchanged responses still return the confirmed rows so every poll reasserts
|
||||
// host truth over optimistic local edits, exactly as the full-payload path did.
|
||||
return this.confirmedWorktrees
|
||||
}
|
||||
}
|
||||
+8
-8
@@ -98,23 +98,23 @@
|
||||
"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",
|
||||
"win-crash-survival-e2e": "node tools/win-crash-survival-e2e/run.mjs",
|
||||
"win-update-e2e": "node tests/tools/win-update-e2e/run.mjs",
|
||||
"win-crash-survival-e2e": "node tests/tools/win-crash-survival-e2e/run.mjs",
|
||||
"test:e2e:ssh-codex-artifacts-repro": "node config/scripts/run-ssh-codex-artifacts-repro-e2e.mjs",
|
||||
"test:e2e:headful": "pnpm run ensure:electron-runtime && npx playwright test --config tests/playwright.config.ts --project electron-headful",
|
||||
"test:e2e:terminal-ime-native": "node config/scripts/run-terminal-ibus-hangul-e2e.mjs",
|
||||
"test:e2e:computer": "vitest run --config tests/e2e/vitest.config.ts",
|
||||
"bench:idle-cpu": "pnpm run ensure:electron-runtime && node config/scripts/run-idle-cpu-benchmark.mjs",
|
||||
"bench:macos-computer-helper-owner-loss": "node config/scripts/macos-computer-helper-owner-loss-benchmark.mjs",
|
||||
"bench:startup": "pnpm run ensure:electron-runtime && node tools/benchmarks/startup-time-bench.mjs",
|
||||
"bench:daemon-coldstart": "pnpm run ensure:electron-runtime && node tools/benchmarks/daemon-coldstart-bench.mjs",
|
||||
"bench:startup": "pnpm run ensure:electron-runtime && node tests/tools/benchmarks/startup-time-bench.mjs",
|
||||
"bench:daemon-coldstart": "pnpm run ensure:electron-runtime && node tests/tools/benchmarks/daemon-coldstart-bench.mjs",
|
||||
"bench:hang-watchdog-memory": "pnpm run ensure:electron-runtime && node config/scripts/hang-watchdog-memory-benchmark.mjs",
|
||||
"bench:main-thread-jank": "pnpm run ensure:electron-runtime && node tools/benchmarks/main-thread-jank-bench.mjs",
|
||||
"bench:worktree-deletion": "node tools/benchmarks/worktree-deletion-dev-bench.mjs",
|
||||
"bench:main-thread-jank": "pnpm run ensure:electron-runtime && node tests/tools/benchmarks/main-thread-jank-bench.mjs",
|
||||
"bench:worktree-deletion": "node tests/tools/benchmarks/worktree-deletion-dev-bench.mjs",
|
||||
"bench:zustand-selector-fanout": "node config/scripts/zustand-selector-fanout-benchmark.mjs",
|
||||
"bench:multi-workspace-typing": "pnpm run ensure:electron-runtime && node config/scripts/run-multi-workspace-typing-bench.mjs",
|
||||
"bench:cold-park-reveal": "pnpm run ensure:electron-runtime && node tools/benchmarks/terminal-cold-park-reveal-bench.mjs",
|
||||
"bench:cold-park-resource": "pnpm run ensure:electron-runtime && node tools/benchmarks/terminal-cold-park-resource-bench.mjs",
|
||||
"bench:cold-park-reveal": "pnpm run ensure:electron-runtime && node tests/tools/benchmarks/terminal-cold-park-reveal-bench.mjs",
|
||||
"bench:cold-park-resource": "pnpm run ensure:electron-runtime && node tests/tools/benchmarks/terminal-cold-park-resource-bench.mjs",
|
||||
"bench:compare": "node config/scripts/compare-benchmark-artifacts.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1512,6 +1512,38 @@ describe('browserManager', () => {
|
||||
expect(browserManager.getGuestWebContentsId('browser-destroyed-before-register')).toBeNull()
|
||||
})
|
||||
|
||||
it('removes a destroyed primary guest from its tab registration maps', () => {
|
||||
const guest = {
|
||||
id: 306,
|
||||
isDestroyed: vi.fn(() => false),
|
||||
getType: vi.fn(() => 'webview'),
|
||||
setBackgroundThrottling: guestSetBackgroundThrottlingMock,
|
||||
setWindowOpenHandler: guestSetWindowOpenHandlerMock,
|
||||
on: guestOnMock,
|
||||
off: guestOffMock,
|
||||
openDevTools: guestOpenDevToolsMock
|
||||
}
|
||||
webContentsFromIdMock.mockReturnValue(guest)
|
||||
|
||||
browserManager.attachGuestPolicies(guest as never)
|
||||
browserManager.registerGuest({
|
||||
browserPageId: 'browser-destroyed-after-register',
|
||||
webContentsId: guest.id,
|
||||
rendererWebContentsId
|
||||
})
|
||||
|
||||
const destroyedHandler = guestOnMock.mock.calls.find(
|
||||
([event]) => event === 'destroyed'
|
||||
)?.[1] as (() => void) | undefined
|
||||
destroyedHandler?.()
|
||||
|
||||
expect(browserManager.getGuestWebContentsId('browser-destroyed-after-register')).toBeNull()
|
||||
const managerState = browserManager as unknown as {
|
||||
tabIdByWebContentsId: Map<number, string>
|
||||
}
|
||||
expect(managerState.tabIdByWebContentsId.has(guest.id)).toBe(false)
|
||||
})
|
||||
|
||||
it('fully unregisters stale guests discovered during authorization', () => {
|
||||
const guest = {
|
||||
id: 305,
|
||||
|
||||
@@ -640,7 +640,6 @@ export class BrowserManager {
|
||||
|
||||
// Why: bot detectors probe APIs that differ in Electron webviews; inject overrides each load so manual browsing passes.
|
||||
const disposeAntiDetection = this.injectAntiDetection(guest)
|
||||
|
||||
// Why: disable throttling so background screenshots still get frames; else the compositor stalls and capture returns empty.
|
||||
guest.setBackgroundThrottling(false)
|
||||
const installClickedLinkRouting = (): void => {
|
||||
@@ -940,11 +939,15 @@ export class BrowserManager {
|
||||
private retireStaleGuestWebContents(previousWebContentsId: number): void {
|
||||
// Why: after a renderer-process swap, stop the dead guest id resolving to the live page so stale callbacks don't hit the wrong session.
|
||||
this.cleanupGuestPolicyAttachment(previousWebContentsId)
|
||||
this.tabIdByWebContentsId.delete(previousWebContentsId)
|
||||
}
|
||||
|
||||
private cleanupGuestPolicyAttachment(guestWebContentsId: number): void {
|
||||
const isPrimaryGuest = this.tabIdByWebContentsId.has(guestWebContentsId)
|
||||
const browserTabId = this.tabIdByWebContentsId.get(guestWebContentsId)
|
||||
const isPrimaryGuest = browserTabId !== undefined
|
||||
if (browserTabId && this.webContentsIdByTabId.get(browserTabId) === guestWebContentsId) {
|
||||
this.webContentsIdByTabId.delete(browserTabId)
|
||||
}
|
||||
this.tabIdByWebContentsId.delete(guestWebContentsId)
|
||||
this.certificateTrustController?.onGuestRetired(guestWebContentsId)
|
||||
const policyCleanup = this.policyCleanupByGuestId.get(guestWebContentsId)
|
||||
if (policyCleanup) {
|
||||
|
||||
@@ -1,13 +1,32 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
|
||||
import type * as NodeFs from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import {
|
||||
copyFileWithWindowsRetry,
|
||||
removeFileAtomicallyIfUnchanged,
|
||||
renameFileWithWindowsRetry,
|
||||
writeFileAtomically
|
||||
writeFileAtomically,
|
||||
writeFileAtomicallyIfUnchanged
|
||||
} from './fs-utils'
|
||||
|
||||
const fsMock = vi.hoisted(() => ({ linkSync: vi.fn(), renameSync: vi.fn() }))
|
||||
|
||||
vi.mock('node:fs', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof NodeFs>()
|
||||
fsMock.linkSync.mockImplementation(actual.linkSync)
|
||||
fsMock.renameSync.mockImplementation(actual.renameSync)
|
||||
return { ...actual, linkSync: fsMock.linkSync, renameSync: fsMock.renameSync }
|
||||
})
|
||||
|
||||
const originalPlatform = process.platform
|
||||
|
||||
afterEach(() => {
|
||||
Object.defineProperty(process, 'platform', { value: originalPlatform })
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('writeFileAtomically', () => {
|
||||
let dir: string
|
||||
|
||||
@@ -81,6 +100,145 @@ describe('writeFileAtomically', () => {
|
||||
cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
it('replaces only the expected file generation', () => {
|
||||
setup()
|
||||
try {
|
||||
const target = join(dir, 'guarded.toml')
|
||||
writeFileSync(target, 'baseline')
|
||||
|
||||
expect(writeFileAtomicallyIfUnchanged(target, 'baseline', 'next')).toBe(true)
|
||||
expect(readFileSync(target, 'utf-8')).toBe('next')
|
||||
|
||||
writeFileSync(target, 'concurrent')
|
||||
expect(writeFileAtomicallyIfUnchanged(target, 'next', 'stale-write')).toBe(false)
|
||||
expect(readFileSync(target, 'utf-8')).toBe('concurrent')
|
||||
} finally {
|
||||
cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
it('validates the generation moved after a Windows rename retry', () => {
|
||||
setup()
|
||||
try {
|
||||
const target = join(dir, 'guarded.toml')
|
||||
writeFileSync(target, 'baseline')
|
||||
Object.defineProperty(process, 'platform', { value: 'win32' })
|
||||
fsMock.renameSync.mockClear()
|
||||
fsMock.renameSync.mockImplementationOnce(() => {
|
||||
writeFileSync(target, 'concurrent')
|
||||
throw Object.assign(new Error('busy'), { code: 'EBUSY' })
|
||||
})
|
||||
|
||||
expect(writeFileAtomicallyIfUnchanged(target, 'baseline', 'stale-write')).toBe(false)
|
||||
expect(readFileSync(target, 'utf-8')).toBe('concurrent')
|
||||
expect(fsMock.renameSync).toHaveBeenCalledTimes(2)
|
||||
} finally {
|
||||
cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
it('preserves a replacement created before guarded publication', () => {
|
||||
setup()
|
||||
try {
|
||||
const target = join(dir, 'guarded.toml')
|
||||
writeFileSync(target, 'baseline')
|
||||
const rename = fsMock.renameSync.getMockImplementation()
|
||||
fsMock.renameSync.mockImplementationOnce((source: string, destination: string) => {
|
||||
rename!(source, destination)
|
||||
writeFileSync(target, 'concurrent')
|
||||
})
|
||||
|
||||
expect(writeFileAtomicallyIfUnchanged(target, 'baseline', 'stale-write')).toBe(false)
|
||||
expect(readFileSync(target, 'utf-8')).toBe('concurrent')
|
||||
} finally {
|
||||
cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
it('recovers an interrupted guarded operation before retrying', () => {
|
||||
setup()
|
||||
try {
|
||||
const target = join(dir, 'guarded.toml')
|
||||
const held = `${target}.orca-guarded`
|
||||
writeFileSync(held, 'baseline')
|
||||
|
||||
expect(writeFileAtomicallyIfUnchanged(target, 'baseline', 'next')).toBe(true)
|
||||
expect(readFileSync(target, 'utf-8')).toBe('next')
|
||||
expect(existsSync(held)).toBe(false)
|
||||
} finally {
|
||||
cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
it('fails before moving the target when hard-link publication is unsupported', () => {
|
||||
setup()
|
||||
try {
|
||||
const target = join(dir, 'guarded.toml')
|
||||
writeFileSync(target, 'baseline')
|
||||
fsMock.linkSync.mockImplementationOnce(() => {
|
||||
throw Object.assign(new Error('unsupported'), { code: 'ENOTSUP' })
|
||||
})
|
||||
|
||||
expect(() => writeFileAtomicallyIfUnchanged(target, 'baseline', 'next')).toThrow(
|
||||
'unsupported'
|
||||
)
|
||||
expect(readFileSync(target, 'utf-8')).toBe('baseline')
|
||||
expect(existsSync(`${target}.orca-guarded`)).toBe(false)
|
||||
} finally {
|
||||
cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
it('removes only the expected file generation', () => {
|
||||
setup()
|
||||
try {
|
||||
const target = join(dir, 'guarded-auth.json')
|
||||
writeFileSync(target, 'baseline')
|
||||
|
||||
expect(removeFileAtomicallyIfUnchanged(target, 'other')).toBe(false)
|
||||
expect(readFileSync(target, 'utf-8')).toBe('baseline')
|
||||
expect(removeFileAtomicallyIfUnchanged(target, 'baseline')).toBe(true)
|
||||
expect(existsSync(target)).toBe(false)
|
||||
} finally {
|
||||
cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
it('returns false when the target disappears during the removal probe', () => {
|
||||
setup()
|
||||
try {
|
||||
const target = join(dir, 'guarded-auth.json')
|
||||
writeFileSync(target, 'baseline')
|
||||
fsMock.linkSync.mockImplementationOnce(() => {
|
||||
rmSync(target)
|
||||
throw Object.assign(new Error('gone'), { code: 'ENOENT' })
|
||||
})
|
||||
|
||||
expect(removeFileAtomicallyIfUnchanged(target, 'baseline')).toBe(false)
|
||||
expect(existsSync(`${target}.orca-guarded`)).toBe(false)
|
||||
} finally {
|
||||
cleanup()
|
||||
}
|
||||
})
|
||||
|
||||
it('preserves a replacement created while the expected generation is quarantined', () => {
|
||||
setup()
|
||||
try {
|
||||
const target = join(dir, 'guarded-auth.json')
|
||||
writeFileSync(target, 'baseline')
|
||||
const rename = fsMock.renameSync.getMockImplementation()
|
||||
fsMock.renameSync.mockImplementationOnce((source: string, destination: string) => {
|
||||
rename!(source, destination)
|
||||
writeFileSync(target, 'concurrent')
|
||||
})
|
||||
|
||||
expect(removeFileAtomicallyIfUnchanged(target, 'baseline')).toBe(false)
|
||||
expect(readFileSync(target, 'utf-8')).toBe('concurrent')
|
||||
} finally {
|
||||
cleanup()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('retrying file operations', () => {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { copyFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { copyFileSync, existsSync, linkSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { dirname } from 'node:path'
|
||||
import { grantDirAcl, isPermissionError } from '../win32-utils'
|
||||
import { nodeFileContentsEqualSync } from '../../shared/node-file-content-equality'
|
||||
|
||||
export function writeFileAtomically(
|
||||
targetPath: string,
|
||||
@@ -39,6 +40,158 @@ export function writeFileAtomically(
|
||||
}
|
||||
}
|
||||
|
||||
export function writeFileAtomicallyIfUnchanged(
|
||||
targetPath: string,
|
||||
expectedContents: string | null,
|
||||
contents: string,
|
||||
options?: { mode?: number }
|
||||
): boolean {
|
||||
try {
|
||||
return attemptGuardedAtomicWrite(targetPath, expectedContents, contents, options)
|
||||
} catch (error) {
|
||||
if (!isPermissionError(error) || process.platform !== 'win32') {
|
||||
throw error
|
||||
}
|
||||
grantDirAcl(dirname(targetPath))
|
||||
return attemptGuardedAtomicWrite(targetPath, expectedContents, contents, options)
|
||||
}
|
||||
}
|
||||
|
||||
export function removeFileAtomicallyIfUnchanged(
|
||||
targetPath: string,
|
||||
expectedContents: string
|
||||
): boolean {
|
||||
const heldPath = getGuardedOperationHeldPath(targetPath)
|
||||
recoverInterruptedGuardedOperation(heldPath, targetPath)
|
||||
try {
|
||||
assertHardLinkPublicationSupported(targetPath, targetPath)
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return false
|
||||
}
|
||||
throw error
|
||||
}
|
||||
try {
|
||||
renameFileWithWindowsRetry(targetPath, heldPath)
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return false
|
||||
}
|
||||
throw error
|
||||
}
|
||||
try {
|
||||
if (!nodeFileContentsEqualSync(heldPath, expectedContents)) {
|
||||
restoreMovedFileWithoutOverwrite(heldPath, targetPath)
|
||||
return false
|
||||
}
|
||||
rmSync(heldPath, { force: true })
|
||||
return !existsSync(targetPath)
|
||||
} catch (error) {
|
||||
restoreMovedFileWithoutOverwrite(heldPath, targetPath)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export function recoverInterruptedGuardedFileOperation(targetPath: string): void {
|
||||
recoverInterruptedGuardedOperation(getGuardedOperationHeldPath(targetPath), targetPath)
|
||||
}
|
||||
|
||||
function restoreMovedFileWithoutOverwrite(sourcePath: string, targetPath: string): void {
|
||||
if (!existsSync(sourcePath)) {
|
||||
return
|
||||
}
|
||||
publishFileWithoutOverwrite(sourcePath, targetPath)
|
||||
rmSync(sourcePath, { force: true })
|
||||
}
|
||||
|
||||
function getGuardedOperationHeldPath(targetPath: string): string {
|
||||
return `${targetPath}.orca-guarded`
|
||||
}
|
||||
|
||||
function recoverInterruptedGuardedOperation(heldPath: string, targetPath: string): void {
|
||||
if (!existsSync(heldPath)) {
|
||||
return
|
||||
}
|
||||
publishFileWithoutOverwrite(heldPath, targetPath)
|
||||
rmSync(heldPath, { force: true })
|
||||
}
|
||||
|
||||
function attemptGuardedAtomicWrite(
|
||||
targetPath: string,
|
||||
expectedContents: string | null,
|
||||
contents: string,
|
||||
options?: { mode?: number }
|
||||
): boolean {
|
||||
const tmpPath = `${targetPath}.${process.pid}.${randomUUID()}.tmp`
|
||||
const heldPath = getGuardedOperationHeldPath(targetPath)
|
||||
recoverInterruptedGuardedOperation(heldPath, targetPath)
|
||||
try {
|
||||
writeFileSync(tmpPath, contents, { encoding: 'utf-8', mode: options?.mode })
|
||||
if (expectedContents === null) {
|
||||
return publishFileWithoutOverwrite(tmpPath, targetPath)
|
||||
}
|
||||
assertHardLinkPublicationSupported(tmpPath, targetPath)
|
||||
try {
|
||||
renameFileWithWindowsRetry(targetPath, heldPath)
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
|
||||
return false
|
||||
}
|
||||
throw error
|
||||
}
|
||||
if (!nodeFileContentsEqualSync(heldPath, expectedContents)) {
|
||||
restoreMovedFileWithoutOverwrite(heldPath, targetPath)
|
||||
return false
|
||||
}
|
||||
if (!publishFileWithoutOverwrite(tmpPath, targetPath)) {
|
||||
rmSync(heldPath, { force: true })
|
||||
return false
|
||||
}
|
||||
rmSync(heldPath, { force: true })
|
||||
return true
|
||||
} catch (error) {
|
||||
restoreMovedFileWithoutOverwrite(heldPath, targetPath)
|
||||
throw error
|
||||
} finally {
|
||||
rmSync(tmpPath, { force: true })
|
||||
}
|
||||
}
|
||||
|
||||
function assertHardLinkPublicationSupported(sourcePath: string, targetPath: string): void {
|
||||
const probePath = `${targetPath}.${process.pid}.${randomUUID()}.link-probe`
|
||||
try {
|
||||
if (!publishFileWithoutOverwrite(sourcePath, probePath)) {
|
||||
throw new Error(`Guarded file publication probe already exists: ${probePath}`)
|
||||
}
|
||||
} finally {
|
||||
rmSync(probePath, { force: true })
|
||||
}
|
||||
}
|
||||
|
||||
function publishFileWithoutOverwrite(sourcePath: string, targetPath: string): boolean {
|
||||
try {
|
||||
linkSync(sourcePath, targetPath)
|
||||
return true
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'EEXIST') {
|
||||
return false
|
||||
}
|
||||
if (isPermissionError(error) && process.platform === 'win32') {
|
||||
grantDirAcl(dirname(targetPath))
|
||||
try {
|
||||
linkSync(sourcePath, targetPath)
|
||||
return true
|
||||
} catch (retryError) {
|
||||
if ((retryError as NodeJS.ErrnoException).code === 'EEXIST') {
|
||||
return false
|
||||
}
|
||||
throw retryError
|
||||
}
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// Why: on Windows, file replacement and backup-copy operations can fail with
|
||||
// EPERM/EACCES/EBUSY if another process (antivirus, Claude CLI, Codex CLI)
|
||||
// holds the target file open. A short retry avoids transient failures without
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { syncLegacySharedCodexConfigForRetainedPanes } from './legacy-shared-config-compatibility'
|
||||
import type * as FsUtils from './fs-utils'
|
||||
|
||||
const generationRace = vi.hoisted(() => ({
|
||||
path: null as string | null,
|
||||
beforeGuardedReplace: null as (() => void) | null
|
||||
}))
|
||||
|
||||
vi.mock('./fs-utils', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof FsUtils>()
|
||||
return {
|
||||
...actual,
|
||||
writeFileAtomicallyIfUnchanged: (
|
||||
path: string,
|
||||
expectedContents: string | null,
|
||||
contents: string,
|
||||
options?: { mode?: number }
|
||||
) => {
|
||||
if (path === generationRace.path) {
|
||||
generationRace.beforeGuardedReplace?.()
|
||||
}
|
||||
return actual.writeFileAtomicallyIfUnchanged(path, expectedContents, contents, options)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
let root: string
|
||||
let sharedRuntimeHome: string
|
||||
let systemCodexHome: string
|
||||
|
||||
beforeEach(() => {
|
||||
root = mkdtempSync(join(tmpdir(), 'orca-legacy-codex-home-'))
|
||||
sharedRuntimeHome = join(root, 'codex-runtime-home', 'home')
|
||||
systemCodexHome = join(root, 'system-home', '.codex')
|
||||
mkdirSync(sharedRuntimeHome, { recursive: true })
|
||||
mkdirSync(systemCodexHome, { recursive: true })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
rmSync(root, { recursive: true, force: true })
|
||||
generationRace.path = null
|
||||
generationRace.beforeGuardedReplace = null
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('legacy shared Codex config compatibility', () => {
|
||||
it('refreshes retained panes with the authenticated production provider config', () => {
|
||||
const staleSharedAuth = '{"tokens":{"access_token":"stale"}}\n'
|
||||
const systemConfig = [
|
||||
'model_provider = "codex-lb"',
|
||||
'',
|
||||
'[model_providers.codex-lb]',
|
||||
'base_url = "https://codex-lb.example.test/v1"',
|
||||
'requires_openai_auth = true',
|
||||
''
|
||||
].join('\n')
|
||||
writeFileSync(join(systemCodexHome, 'config.toml'), systemConfig, 'utf-8')
|
||||
writeFileSync(join(sharedRuntimeHome, 'auth.json'), staleSharedAuth)
|
||||
writeFileSync(
|
||||
join(sharedRuntimeHome, 'config.toml'),
|
||||
[
|
||||
'model_provider = "stale-provider"',
|
||||
'',
|
||||
'[hooks.state."orca:stop:0:0"]',
|
||||
'enabled = true',
|
||||
''
|
||||
].join('\n')
|
||||
)
|
||||
|
||||
syncLegacySharedCodexConfigForRetainedPanes({ sharedRuntimeHome, systemCodexHome })
|
||||
|
||||
const sharedConfig = readFileSync(join(sharedRuntimeHome, 'config.toml'), 'utf-8')
|
||||
expect(sharedConfig).toContain('model_provider = "codex-lb"')
|
||||
expect(sharedConfig).toContain('requires_openai_auth = true')
|
||||
expect(sharedConfig).not.toContain('stale-provider')
|
||||
expect(sharedConfig).toContain('[hooks.state."orca:stop:0:0"]')
|
||||
expect(readFileSync(join(systemCodexHome, 'config.toml'), 'utf-8')).toBe(systemConfig)
|
||||
expect(readFileSync(join(sharedRuntimeHome, 'auth.json'), 'utf-8')).toBe(staleSharedAuth)
|
||||
})
|
||||
|
||||
it('does not delete config when the canonical source is transiently missing', () => {
|
||||
const staleConfig = 'model_provider = "stale-provider"\n'
|
||||
writeFileSync(join(sharedRuntimeHome, 'config.toml'), staleConfig, 'utf-8')
|
||||
|
||||
syncLegacySharedCodexConfigForRetainedPanes({ sharedRuntimeHome, systemCodexHome })
|
||||
|
||||
expect(readFileSync(join(sharedRuntimeHome, 'config.toml'), 'utf-8')).toBe(staleConfig)
|
||||
})
|
||||
|
||||
it('does not promote retained-pane settings into the real home', () => {
|
||||
writeFileSync(join(systemCodexHome, 'config.toml'), 'model = "canonical"\n', 'utf-8')
|
||||
writeFileSync(join(sharedRuntimeHome, 'config.toml'), 'model = "retained-pane-change"\n')
|
||||
|
||||
syncLegacySharedCodexConfigForRetainedPanes({ sharedRuntimeHome, systemCodexHome })
|
||||
|
||||
expect(readFileSync(join(systemCodexHome, 'config.toml'), 'utf-8')).toBe(
|
||||
'model = "canonical"\n'
|
||||
)
|
||||
expect(readFileSync(join(sharedRuntimeHome, 'config.toml'), 'utf-8')).toBe(
|
||||
'model = "canonical"\n'
|
||||
)
|
||||
})
|
||||
|
||||
it('does not overwrite trust appended by a retained Codex during the mirror', () => {
|
||||
const runtimeConfigPath = join(sharedRuntimeHome, 'config.toml')
|
||||
const runtimeConfig = 'model = "runtime-before"\n'
|
||||
const concurrentConfig = [
|
||||
runtimeConfig.trimEnd(),
|
||||
'',
|
||||
'[projects."/newly-trusted"]',
|
||||
'trust_level = "trusted"',
|
||||
''
|
||||
].join('\n')
|
||||
writeFileSync(join(systemCodexHome, 'config.toml'), 'model = "canonical"\n', 'utf-8')
|
||||
writeFileSync(runtimeConfigPath, runtimeConfig, 'utf-8')
|
||||
generationRace.path = runtimeConfigPath
|
||||
generationRace.beforeGuardedReplace = () => {
|
||||
writeFileSync(runtimeConfigPath, concurrentConfig, 'utf-8')
|
||||
}
|
||||
|
||||
syncLegacySharedCodexConfigForRetainedPanes({ sharedRuntimeHome, systemCodexHome })
|
||||
|
||||
expect(readFileSync(runtimeConfigPath, 'utf-8')).toBe(concurrentConfig)
|
||||
})
|
||||
|
||||
it('does not block real-home launch when compatibility config refresh fails', () => {
|
||||
const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
writeFileSync(join(systemCodexHome, 'config.toml'), 'model = "canonical"\n', 'utf-8')
|
||||
mkdirSync(join(sharedRuntimeHome, 'config.toml'))
|
||||
|
||||
expect(() =>
|
||||
syncLegacySharedCodexConfigForRetainedPanes({ sharedRuntimeHome, systemCodexHome })
|
||||
).not.toThrow()
|
||||
|
||||
expect(warnSpy).toHaveBeenCalledWith(
|
||||
'[codex-runtime-home] Failed to refresh legacy shared config:',
|
||||
expect.anything()
|
||||
)
|
||||
})
|
||||
})
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user