Repository navigation
fix(daemon): stop killing live coding agents when the daemon can't report its sessions - #13928
Conversation
…PTYs
A daemon too busy to answer listSessions was indistinguishable from a dead
one: getAliveDaemonSessionCount() returns null ("could not verify"), the
preserve gate required `!== null && > 0`, so the run fell through to
killStaleDaemon() and every running coding agent died with it. The sibling
replace branches all preserve on null; this one alone collapsed "can't tell"
into "empty", which src/main/daemon/AGENTS.md already forbids.
Give the decision an out-of-band second opinion. inspectDaemonPtyOwnership()
reads the OS process table — never the daemon socket, which is exactly what
failed — and reports whether the daemon's own process still has live PTY
descendants. Under preserveWhenOwningLivePtys, that evidence vetoes the
signal and the launcher adopts the daemon in degraded mode instead.
The veto is opt-in so it cannot make a daemon unkillable: only the
failed_health_check path enables it. Manage Sessions -> Restart still kills.
Only positive evidence preserves, so a wedged daemon with nothing to lose is
still replaced (#8689).
Also stop replacing silently: the verdict now prints on the post-kill truth,
which stays quiet on a cold start because nothing was killed.
Co-authored-by: Orca <[email protected]>
Adversarial review found the veto's own success path could not complete against the daemon it exists to protect. Preserving routed through holdDaemonAdoptionLease(), which opens a hello — the exact operation a wedged daemon cannot answer — so it threw, aborted initDaemonPtyProvider, and left no spawner. restartDaemon() throws without one, so the user lost the documented Manage Sessions -> Restart remedy on top of having no daemon: strictly worse than the data loss being fixed. A still-listening endpoint means wedged, not gone, so keep a lease-free handle instead. The lease only cancels the adoption watchdog, which never fires on a daemon that owns sessions. Degraded mode likewise tolerates a lease and a session discovery it cannot complete. Three more from the same review: - The veto keyed on reason === 'failed_health_check', but a daemon that answered listSessions with 0 lands in that same branch and must stay replaceable. Key on liveSessionCount === null, which is what the option actually documents. - Zombies are not evidence of live work. A wedged daemon cannot reap, so its exited agents linger as <defunct> and would read as "still running" — a false positive correlated with the wedge itself. Enumerate through the process table's stat column and exclude them; sample twice so a resolver probe or health-check shell cannot masquerade as an agent. - Restore the "did anything answer?" log guard alongside the confirmed kill, so a daemon that self-retires before the kill is still announced. Co-authored-by: Orca <[email protected]>
Mutation testing found four survivors — changes that break the fix while every test stays green: - Swapping the POSIX reader to the 500ms-cached one passed. It is not just a staleness hazard: inside the TTL both sampling attempts receive the same array, collapsing the two-sample confirmation to one. Pin the fresh reader. - Replacing killStaleDaemon's default inspector with one that never reports live PTYs — the veto disabled in production — passed, because every veto test injects the hook. Exercise the real seam. - Adding the veto to cleanupDaemonForProtocol passed, which is verbatim the failure its own doc warns about: a user-initiated restart of a daemon owning live PTYs would refuse, then throw. Pin that call's arity. - The ppid-cycle fixture put the cycle outside the daemon's subtree, so the walk never entered it and deleting the visited guard passed. Also bound the Windows enumeration, which had no budget of its own: two CIM queries with a wmic fallback can stall the launch path for tens of seconds. Blind is a safe answer there; hanging is not. Co-authored-by: Orca <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe change adds platform-specific daemon PTY ownership inspection with descendant traversal, filtering, repeated sampling, and timeout handling. Daemon occupancy resolution combines IPC session counts with verified process evidence. Daemon initialization preserves occupied daemons, holds unverifiable daemons, and supports degraded launch modes within a bounded grace period. Tests cover these paths. A POSIX reproduction command validates guarded and unguarded replacement with real processes. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
src/main/daemon/daemon-init.test.ts (1)
3245-3291: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for the endpoint-died branch of the new adoption fallback.
This test covers the case where
probeSocketsucceeds and the launcher returns a lease-free degraded handle. The newcatchblock indaemon-init.tshas a second branch: whenprobeSocketreturns false, it throwsDaemonEndpointOwnershipErrorbecause the endpoint is genuinely free.That branch has no test. An inverted probe condition would still pass every test in this cohort, and it would make the launcher return a degraded handle for a daemon that is actually gone.
The fixture here already stages everything needed. Only the probe result changes.
🧪 Proposed additional test
it('fails the launch when the preserved daemon died before adoption', async () => { // Why: a free endpoint means the daemon is gone, not wedged. Returning a degraded // handle here would strand the app on a daemon that no longer exists. const mod = await importFresh() await mod.initDaemonPtyProvider() const answeringDefault = function MockDaemonClient() { return { ensureConnected: vi.fn(async () => {}), request: vi.fn(async () => ({ sessions: [] })), disconnect: vi.fn() } } daemonClientMock.mockImplementation(function MockWedgedDaemonClient() { return { ensureConnected: vi.fn(async () => { throw new Error('Hello response timed out') }), getDaemonIdentity: vi.fn(readLaunchedDaemonIdentity), request: vi.fn(), disconnect: vi.fn() } }) killStaleDaemonMock.mockResolvedValueOnce({ killed: false, liveOwnerSurvived: true }) const launcher = spawnerInstances[0].launcher as ( socketPath: string, tokenPath: string ) => Promise<{ shutdown(): Promise<void>; mode?: string }> checkDaemonHealthMock.mockResolvedValueOnce('unreachable') // The endpoint stopped answering between the refusal and the adoption attempt. probeSocketExistsMock.mockReturnValue(false) try { await expect(launcher('/fake/socket', '/fake/token')).rejects.toThrow( /could not be confirmed stopped/ ) expect(forkMock).not.toHaveBeenCalled() } finally { daemonClientMock.mockImplementation(answeringDefault) } })config/scripts/daemon-replacement-live-agent-pty-preservation-repro.mjs (1)
597-606: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueStrip comments before parsing the launcher call, to match
readOptionsArgumentSlot.
readOptionsArgumentSlotstrips comments before callingsplitCallArguments, because comments carry commas that corrupt the top-level split.checkLauncherEnablesTheGuardparses the unstripped source with the same splitter.Today this works, because the call at
daemon-init.tshas no comment betweenkillStaleDaemon(and its closing paren. If someone adds a comment inside the argument list, the split breaks and phase 3 reports a wrong slot.Keep the unstripped source for the line-number calculation on Line 604, and use a stripped copy only for the split.
♻️ Proposed change
function checkLauncherEnablesTheGuard(optionsSlot) { const relativePath = 'src/main/daemon/daemon-init.ts' const source = readFileSync(join(repoRoot, relativePath), 'utf8') + // Blank out comments in place so offsets and line numbers still line up. + const scannable = source + .replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, ' ')) + .replace(/\/\/[^\n]*/g, (m) => ' '.repeat(m.length)) const marker = source.indexOf('preserveWhenOwningLivePtys') assert(marker !== -1, `${relativePath} never passes preserveWhenOwningLivePtys`) const callIndex = source.lastIndexOf('killStaleDaemon(', marker) assert(callIndex !== -1, `${relativePath} sets preserveWhenOwningLivePtys outside a call`) const line = source.slice(0, callIndex).split('\n').length - const args = splitCallArguments(source, callIndex + 'killStaleDaemon'.length) + const args = splitCallArguments(scannable, callIndex + 'killStaleDaemon'.length)
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: d79afc4c-ab57-478e-b5ea-6f68316b14bf
📒 Files selected for processing (8)
config/scripts/daemon-replacement-live-agent-pty-preservation-repro.mjspackage.jsonsrc/main/daemon/daemon-health.test.tssrc/main/daemon/daemon-health.tssrc/main/daemon/daemon-init.test.tssrc/main/daemon/daemon-init.tssrc/main/daemon/daemon-live-pty-evidence.test.tssrc/main/daemon/daemon-live-pty-evidence.ts
| async function loadDaemonPrimitives(scratch) { | ||
| const esbuild = await import('esbuild') | ||
| const entrySource = join(scratch, 'daemon-primitives-entry.ts') | ||
| const bundlePath = join(scratch, 'daemon-primitives.mjs') | ||
| const daemonDir = join(repoRoot, 'src', 'main', 'daemon') | ||
| writeFileSync( | ||
| entrySource, | ||
| [ | ||
| `export { checkDaemonHealth, killStaleDaemon } from ${JSON.stringify(join(daemonDir, 'daemon-health'))}`, | ||
| `export { inspectDaemonPtyOwnership } from ${JSON.stringify(join(daemonDir, 'daemon-live-pty-evidence'))}`, | ||
| `export { getDaemonPidPath, getDaemonSocketPath, getDaemonTokenPath } from ${JSON.stringify(join(daemonDir, 'daemon-spawner'))}`, | ||
| `export { DaemonClient } from ${JSON.stringify(join(daemonDir, 'client'))}`, | ||
| '' | ||
| ].join('\n') | ||
| ) | ||
| await esbuild.build({ | ||
| entryPoints: [entrySource], | ||
| outfile: bundlePath, | ||
| bundle: true, | ||
| platform: 'node', | ||
| format: 'esm', | ||
| packages: 'external', | ||
| logLevel: 'silent' | ||
| }) | ||
| return import(pathToFileURL(bundlePath).href) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Check the esbuild declaration and the electron-freeness of the bundled graph.
set -uo pipefail
echo '===== Is esbuild declared? ====='
jq -r '
{
dep: (.dependencies.esbuild // "absent"),
dev: (.devDependencies.esbuild // "absent")
}' package.json
echo
echo '===== Does the new import edge reach electron? ====='
for f in \
src/main/daemon/daemon-live-pty-evidence.ts \
src/main/providers/windows-foreground-process-rows.ts \
src/shared/process-table-snapshot.ts
do
if [ -f "$f" ]; then
echo "--- $f ---"
rg -nP "^\s*import .*from ['\"]" "$f"
else
echo "--- $f (not found; locating) ---"
fd -t f "$(basename "$f")" --exec rg -nP "^\s*import .*from ['\"]" {}
fi
done
echo
echo '===== Any electron import in the four bundled entry modules ====='
for n in daemon-health daemon-live-pty-evidence daemon-spawner client; do
fd -t f "^${n}\.ts$" src/main/daemon --exec rg -nP "from ['\"]electron['\"]" {} \
&& echo " ^ electron import found in $n"
doneRepository: stablyai/orca
Length of output: 880
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '===== package-manager declarations and script ====='
jq '{
packageManager,
engines,
scripts,
dependencies,
devDependencies
}' package.json
echo
echo '===== esbuild references in manifests and lockfiles ====='
rg -n '(^|["[:space:]])esbuild([@"[:space:]]|$)' \
package.json pnpm-workspace.yaml pnpm-lock.yaml package-lock.json yarn.lock 2>/dev/null || true
echo
echo '===== loader and bundled entry imports ====='
sed -n '1,170p' config/scripts/daemon-replacement-live-agent-pty-preservation-repro.mjs
for f in \
src/main/daemon/daemon-health.ts \
src/main/daemon/daemon-live-pty-evidence.ts \
src/main/daemon/daemon-spawner.ts \
src/main/daemon/client.ts \
src/main/providers/windows-foreground-process-rows.ts \
src/shared/process-table-snapshot.ts
do
echo "--- $f ---"
sed -n '1,180p' "$f"
done
echo
echo '===== transitive relative-import graph and package imports ====='
python3 - <<'PY'
import re
from pathlib import Path
entries = [
Path("src/main/daemon/daemon-health.ts"),
Path("src/main/daemon/daemon-live-pty-evidence.ts"),
Path("src/main/daemon/daemon-spawner.ts"),
Path("src/main/daemon/client.ts"),
]
seen = set()
stack = entries[:]
while stack:
p = stack.pop()
if p in seen:
continue
seen.add(p)
if not p.exists():
print(f"MISSING {p}")
continue
text = p.read_text()
imports = re.findall(r"""(?:import\s+(?:[^'"]+\s+from\s+)?|export\s+(?:[^'"]+\s+from\s+)?|import\s*\()\s*['"]([^'"]+)['"]""", text)
print(f"{p}:")
for spec in imports:
if spec.startswith("."):
q = (p.parent / spec)
candidates = [q, q.with_suffix(".ts"), q.with_suffix(".tsx"), q / "index.ts"]
target = next((x for x in candidates if x.exists()), None)
print(f" relative {spec} -> {target or 'MISSING'}")
if target:
stack.append(target)
else:
print(f" package {spec}")
print("\n===== electron references in discovered files =====")
for p in sorted(seen):
if p.exists():
for i, line in enumerate(p.read_text().splitlines(), 1):
if re.search(r"""(?:from\s+|import\s*\()\s*['"]electron(?:/[^'"]*)?['"]""", line):
print(f"{p}:{i}:{line}")
PYRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '===== root importer esbuild entries ====='
python3 - <<'PY'
from pathlib import Path
text = Path("pnpm-lock.yaml").read_text()
start = text.find("importers:")
end = text.find("\npackages:", start)
print(text[start:end][:12000])
PY
echo
echo '===== esbuild lockfile references ====='
rg -n -C 4 '^(\s+)?esbuild(@|:)|esbuild:' pnpm-lock.yaml | head -120
echo
echo '===== complete relative-import graph ====='
python3 - <<'PY'
import re
from pathlib import Path
entries = [
Path("src/main/daemon/daemon-health.ts"),
Path("src/main/daemon/daemon-live-pty-evidence.ts"),
Path("src/main/daemon/daemon-spawner.ts"),
Path("src/main/daemon/client.ts"),
]
seen = set()
stack = entries[:]
package_imports = []
electron_refs = []
def resolve_import(source, spec):
base = source.parent / spec
candidates = [base]
if base.suffix == "":
candidates += [
base.with_suffix(".ts"),
base.with_suffix(".tsx"),
base.with_suffix(".js"),
base.with_suffix(".mjs"),
base / "index.ts",
]
return next((p for p in candidates if p.exists()), None)
while stack:
source = stack.pop()
if source in seen:
continue
seen.add(source)
if not source.exists():
print(f"MISSING_ENTRY_OR_IMPORT {source}")
continue
for line_no, line in enumerate(source.read_text().splitlines(), 1):
matches = re.findall(
r"""(?:import\s+(?:[^'"]+\s+from\s+)?|export\s+(?:[^'"]+\s+from\s+)?|import\s*\()\s*['"]([^'"]+)['"]""",
line,
)
for spec in matches:
if spec == "electron" or spec.startswith("electron/"):
electron_refs.append((source, line_no, spec))
if spec.startswith("."):
target = resolve_import(source, spec)
if target is None:
print(f"UNRESOLVED_RELATIVE {source}:{line_no} {spec}")
else:
stack.append(target)
else:
package_imports.append((source, line_no, spec))
print(f"discovered_files={len(seen)}")
print("package_imports:")
for source, line_no, spec in sorted(package_imports):
print(f" {source}:{line_no}: {spec}")
print("electron_refs:")
for source, line_no, spec in sorted(electron_refs):
print(f" {source}:{line_no}: {spec}")
PYRepository: stablyai/orca
Length of output: 15269
Declare esbuild in devDependencies. The script imports it directly, but only a transitive lockfile entry exists. The complete bundled graph has no electron import.
…ons that can never be adopted Round-three review found the veto too eager in three ways, each of which traded the original data loss for a whole-session degrade or a permanently daemon-less app. Evidence was "any non-zombie descendant", justified by re-sampling to weed out transients. The two samples are taken back to back — one ps fork apart — so nothing transient is ever weeded out, and a hung helper (often the very reason the daemon is wedged) reads as an agent. Use the structural signal instead: a PTY child is a session leader, because forkpty calls setsid, and no helper the daemon forks ever is. Re-sampling now only retries blindness. A 'rejected' daemon answered and refused the handshake, so it can never be adopted; preserving it repeated the same failed adoption on every launch, forever. And the veto read the process table, not the socket, so it could fire on a daemon whose endpoint was already gone — adoption then threw, init aborted, and the app was left with no spawner and no working Restart. Gate on both: only preserve what could still be reached. Also: releasing the launcher's temporary lease after the permanent lease failed reopened the adoption gap that ordering exists to close, and the tolerance added to discoverDaemonSessions was dead code — nothing on that path rejects. Co-authored-by: Orca <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/daemon/daemon-live-pty-evidence.ts (1)
15-19: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueReduce the long implementation comments.
Keep the policy and platform constraints. Remove the detailed examples and repeated rationale. State each reason in one or two lines.
As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”
Also applies to: 62-71, 135-142
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 928b6dcc-fa3f-404d-a04c-03667a244e29
📒 Files selected for processing (3)
src/main/daemon/daemon-init.tssrc/main/daemon/daemon-live-pty-evidence.test.tssrc/main/daemon/daemon-live-pty-evidence.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- src/main/daemon/daemon-live-pty-evidence.test.ts
- src/main/daemon/daemon-init.ts
Three review rounds each found a new failure state in the previous shape, which was the design telling us something. The safety rule — never destroy running work — was replicated across the launcher's branches instead of being decided once, and the last round added it to one more branch behind a boolean. Policy had been put inside a mechanism: killStaleDaemon grew an input flag to disable its new veto, an output back-channel to report it, and a caller-side re-derivation of the classification the flag had lost. One structural error, one symptom per layer it crossed. Name the question instead. resolveDaemonOccupancy answers occupied | empty | unknown, asking the daemon first (authoritative both ways) and falling back to the process table only to RAISE the answer to occupied. OS evidence can prove work exists; it can never prove absence, so it never licenses a kill. The launcher now decides before it destroys anything, so killStaleDaemon goes back to being only "make this pid go away" — no options, nothing for a future caller to forget to disable, and Manage Sessions -> Restart cannot be vetoed because there is no veto left to hit. Holding is a real outcome now. A daemon that owns live terminals but cannot answer a handshake gets mode 'held': no adoption attempt, no lease, no fork beside it. That deletes the lease-free-handle fallback, the try/catch around preserve, and the tolerated-lease branch in init that existed only because the correct outcome had no representation. Two defects this removes outright: - The endpoint check used a local boolean probe that returns false on timeout, so under load — and unconditionally on Windows named pipes, where a busy server answers ERROR_PIPE_BUSY — the guard disabled itself in exactly the conditions it was written for. Use the canonical three-valued probe, whose own docs say absence of proof is not proof of death. - A daemon that answered and refused the handshake was killed with its agents. It is now held like any other occupied daemon. Also folds the replacement verdict onto pendingReplacement, retiring a pair of mutable launcher locals whose only job was moving one warning past the kill. Co-authored-by: Orca <[email protected]>
The module's contract is that 'unknown' is where every unanswerable question lands, but a throwing dependency escaped instead — routing a failed observation into the launch path rather than onto the safe residual. Latent today because both real implementations swallow their own failures, which is exactly the kind of thing that stops being true during a refactor. Co-authored-by: Orca <[email protected]>
Round-four review found the evidence proving the wrong thing. The filter excluded the daemon's plain subprocesses on the grounds that only a PTY child is a session leader — but the daemon opens PTYs for its own health probe and conpty warmup, and forkpty makes those session leaders too. The comment's own premise refuted its exclusion list. A daemon hosting zero user terminals could be held on the strength of its stuck probe child, and since the held daemon also had no sessions, dropping our authenticated pair let it retire and take the very state we were protecting. Exclude them by exact command, on both platforms. Two more from the same review: - pty-spawn-unhealthy is only reachable after a successful hello, so that daemon is adoptable. It was routed to 'held' — which never adopts — purely because the count had come from the process table. Check it first; hold now requires an unreachable daemon. - The grace loop rescanned the process table every pass, though it is waiting for IPC and the table cannot change its answer in five seconds. Ask the daemon during the wait and read the table once, after. raiseOccupancy- WithProcessEvidence makes that split explicit, and can only ever raise. Bound the wait by wall clock too: the retry count alone never bounded it, and startup fails open at 60s by abandoning the daemon provider outright, which would trade a wedged daemon for no daemon and a Restart that throws. Co-authored-by: Orca <[email protected]>
…t refused us Found while reviewing why a mutation looked equivalent. Gating the hold on health === 'unreachable' left 'rejected' — a daemon that answered and refused the handshake — falling through to preserveDaemon(), whose adoption opens the very hello it just refused. That throws, and the throw costs the app its daemon and its Restart remedy. Killing it instead is no better: it can still be hosting running agents. Neither of those daemons can complete a handshake, so neither may be adopted, and both must be held. Gate on that rather than on one of its two causes. Adds regression tests for the round-four fixes: the self-spawned probe exclusion is exact-match on both platforms, an adoptable pty-spawn-unhealthy daemon is never routed to a mode that cannot adopt, evidence can only raise a verdict, and the grace budget stays under the startup fail-open cap. Co-authored-by: Orca <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/main/daemon/daemon-init.test.ts (1)
97-100: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReset the two new mocks in
importFresh().
importFresh()resets every other shared mock at Lines 459-514, but notinspectDaemonPtyOwnershipMockorreadVerifiedDaemonPidMock. The new tests restore both in theirfinallyblocks, so the suite passes today. A future test that sets either mock and returns early would leakowns-live-ptysor a verified pid into later tests, which would silently convert a replacement case into a preserve case.♻️ Proposed reset in `importFresh()`
getProcessStartedAtMsMock.mockReset() getProcessStartedAtMsMock.mockReturnValue(1_000_000) + inspectDaemonPtyOwnershipMock.mockReset() + inspectDaemonPtyOwnershipMock.mockResolvedValue('unknown') + readVerifiedDaemonPidMock.mockReset() + readVerifiedDaemonPidMock.mockResolvedValue(null)
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 35763b87-f41a-498c-8c31-c43524117efd
📒 Files selected for processing (10)
config/scripts/daemon-replacement-live-agent-pty-preservation-repro.mjssrc/main/daemon/daemon-health.test.tssrc/main/daemon/daemon-health.tssrc/main/daemon/daemon-init.test.tssrc/main/daemon/daemon-init.tssrc/main/daemon/daemon-live-pty-evidence.test.tssrc/main/daemon/daemon-live-pty-evidence.tssrc/main/daemon/daemon-occupancy.test.tssrc/main/daemon/daemon-occupancy.tssrc/main/daemon/daemon-spawner.ts
💤 Files with no reviewable changes (1)
- src/main/daemon/daemon-health.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- src/main/daemon/daemon-health.ts
- src/main/daemon/daemon-live-pty-evidence.ts
- config/scripts/daemon-replacement-live-agent-pty-preservation-repro.mjs
…one place Round five found the same question — can this daemon complete a hello right now? — answered in three places with three different conclusions, because 'held' had been added as a fifth branch rather than as the classification the other branches route through. Two of those answers were wrong, and both ended in no daemon at all, which is the outcome 'held' exists to prevent. - A daemon whose adoption hello had just failed was handed back tagged 'degraded-new-pty-fallback'. Init skips the lease only for 'held', so it reopened the same connection, threw, and aborted startup — leaving the agents alive but unreachable and Manage Sessions -> Restart throwing. - The pty-spawn-unhealthy arm ran first and claimed a successful hello proved adoptability, but that reading is from before the grace window. A daemon that answered at t=0 and went silent through thirty seconds of retries took that arm and threw the same way. Ask whether it is answering now, first. The budget was a comment with a Date.now() beside it: one occupancy probe could cost 50s, because the client's default is a 5s hello per connection step plus a 30s request timeout. Bound the probe explicitly, start the clock before the first one, and size the window so the whole path — health check, pid verification, loop overshoot and process-table read — fits under the startup fail-open with room to spare. Also folds the four sibling branches onto the same occupancy resolution. getAliveDaemonSessionCount was byte-identical to countLiveSessionsOverIpc, so one concept had two implementations and only one of them had been fixed. The Windows probe exclusions could never match: the warmup spawns COMSPEC, an absolute path, against an exact-equality test on 'cmd.exe /c exit'. Compare the program by basename and keep the argv tail exact. Co-authored-by: Orca <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 257cef3c-863d-4881-a75f-4878e6fc31d6
📒 Files selected for processing (5)
config/scripts/daemon-replacement-live-agent-pty-preservation-repro.mjssrc/main/daemon/daemon-init.test.tssrc/main/daemon/daemon-init.tssrc/main/daemon/daemon-live-pty-evidence.tssrc/main/daemon/daemon-occupancy.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- src/main/daemon/daemon-live-pty-evidence.ts
- src/main/daemon/daemon-occupancy.ts
- config/scripts/daemon-replacement-live-agent-pty-preservation-repro.mjs
- src/main/daemon/daemon-init.ts
…ot own Closing a held daemon's pane reported success while the agent kept running. Unrouted ids resolve to the in-process fallback, whose shutdown returns silently for an id it has never heard of and whose write and resize are no-ops — and while a daemon is held nothing ever enumerates its sessions, so every one of them is unrouted. The pane vanished, the orphan outlived the app, and typing into a stuck terminal disappeared without a word. Only attach was fenced against that route. Extend the same rule to the operations that change or feed a session: route to the fallback only when it genuinely owns the pty, and otherwise say the session cannot be reached. The error type is load-bearing. pty:kill treats "Session not found" as proof the pty is already gone and synthesizes an exit, so reusing that error would have reproduced the lie one layer down. TerminalSessionOwnerUnverifiedError means "still there, we cannot reach its host", which is reported as a failed close and keeps ownership for a retry. Co-authored-by: Orca <[email protected]>
…that never had it Covers the held-daemon routing fence, including the coupling that is invisible from the routing file: the thrown error must not match pty:kill's already-gone predicate, or the close is swallowed into a synthesized exit and the orphan is hidden again. A rename would otherwise reintroduce the bug silently. Co-authored-by: Orca <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/daemon/degraded-daemon-session-routing.ts (1)
29-40: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueShorten the new comments.
Keep the ownership rationale, but reduce each comment to one concise sentence.
src/main/daemon/degraded-daemon-session-routing.ts#L29-L40: Replace the multi-paragraph operation-routing explanation with a brief ownership-safety rationale.src/main/daemon/degraded-daemon-pty-provider.test.ts#L691-L692: Reduce the held-daemon fixture explanation to one sentence.src/main/daemon/degraded-daemon-pty-provider.test.ts#L711-L712: Reduce the shutdown rationale to one sentence.src/main/daemon/degraded-daemon-pty-provider.test.ts#L723-L726: Move detailedpty:killbehavior to the test name or use one short statement.As per coding guidelines: “Comments must be concise, non-obvious, and brief—prefer one line.”
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ec5a9074-0e5d-48c0-9625-6eb3198fe4e1
📒 Files selected for processing (3)
src/main/daemon/degraded-daemon-pty-provider.test.tssrc/main/daemon/degraded-daemon-pty-provider.tssrc/main/daemon/degraded-daemon-session-routing.ts
…escribes Round-six follow-ups, none destructive. The process-table read had a deadline on Windows but not on POSIX, where the shared reader's ps timeout does not cover queueing behind an in-flight scan — so the one step that runs after the grace window could still outlast it. The pid handed to that read was verified before the grace window, which is long enough for the daemon to die and its pid to be recycled onto a shell with children. Verify it where it is used instead, and only when there is still something to raise: the common case now skips the identity probe altogether, which also takes a few seconds off the worst-case launch. Two renderer call sites killed PTYs without handling rejection. That was harmless while an unreachable session was answered by a silent no-op; now that it honestly rejects, pane teardown and repo removal would log an unhandled rejection every time — exactly when the daemon is already sick. Deliberately not taken from that review: giving the endpoint-occupied catch the same held fallback as the failed-health path. That path arrives with occupancy unknown or empty, so holding there would swallow a real launch failure to protect nothing. Splits the repro script, which had grown past the line limit, into the sequence it proves and the two things it proves it with: process-table inspection, and the static assertions on the launcher's hold decision. Co-authored-by: Orca <[email protected]>
…ne term The previous assertion compared the grace window to the fail-open cap, which passed while the real path ran to roughly twice the cap — a single probe cost 50s against a 5s assumption, and the terms on either side of the loop were never counted at all. Sum the declared budgets instead: health check, grace window, the one probe that always runs past a ceiling tested at loop entry, and the evidence read on both platforms. Raising any of them now has to face this, and the spare time the kill ladder and fork still need afterwards is stated rather than assumed. Lives outside the launcher's own spec because that file mocks daemon-health, which would shadow the constants being held to account. Co-authored-by: Orca <[email protected]>
Raised by a colleague's handoff on the same-day reports. macOS wraps every terminal in /usr/bin/login for TCC attribution, and #13764 shows the wrapper can outlive the shell it wrapped — leaving a session leader that hosts nothing. One affected host had accumulated enough of them to reach swap pressure. That is exactly the evidence this change treats as proof of live work, so a daemon whose sessions had all ended would have been held indefinitely on the strength of the corpses, on precisely the hosts where the problem is worst. Same class as the daemon's own probe PTYs: a session leader is necessary evidence, not sufficient. A wrapper still doing its job has the shell it exec'd beneath it. Co-authored-by: Orca <[email protected]>
…cannot silently rot The ownership evidence discounts the PTYs the daemon opens for itself, and that list is only safe while it is complete — a self-spawned PTY nobody excluded reads as user work and holds a daemon that owns nothing. The list grew one reviewer at a time, which is the wrong mechanism for a correctness invariant. Pin the input rather than the list. The daemon has exactly three PTY spawn sites: the user's terminal, the spawn health probe, and the Windows conpty warmup. A fourth now fails this test until someone decides which side it belongs on. Co-authored-by: Orca <[email protected]>
…rotect Readiness review, section 04. Every agent pane already drives the shared process-table reader on its own cadence, so the uncached read queues behind them — and the host with the most agents to lose is the one likeliest to blow the deadline on queueing alone. Both attempts return unknown and the daemon is killed anyway, which is the original bug wearing the fix as a costume. Fall back to the TTL-cached table, which on that host is always warm for exactly the reason the uncached read is always queued. A table a few hundred milliseconds old still answers whether this daemon has children, and the failure directions are not symmetric: over-holding costs one degraded launch that self-heals, under-counting ends running agents. The same review found the launch budget still overran the 60s startup fail-open — by ~7s on Windows — and that the test guarding it under-counted the path it was written to bound, for the second time. It omitted the identity probe before the evidence read and the endpoint check that ends the grace loop. Both are now summed, the headroom requirement covers the kill ladder and fork that follow a replace verdict, and the grace window and Windows probe deadline are sized to fit. Not taken from that review: reusing the verified pid inside killStaleDaemon to drop the duplicate probe. That second verification is what fences the signal to this incarnation, and a seconds-old result is exactly the pid-reuse hazard it exists to prevent. Co-authored-by: Orca <[email protected]>
Readiness review, sections 02/03/05/06 — no P0 or P1 in any of them. These are the P2s worth taking. The important one: on macOS a terminal contributes exactly one session leader, the login wrapper, because the shell it forks is in the same session and shows S+ rather than Ss. I had assumed the shell counted too. It does not — so a wrapper that looks childless in a single snapshot makes its whole terminal invisible, and that snapshot cannot tell a wrapper whose shell has gone from one whose shell has not yet appeared. Emptiness is the answer that authorizes a kill, so it now costs a second read; 'owns-live-ptys' still needs none. The fixtures said Ss where a real shell says S+, which is why the tests never noticed. Also from that review: a fabricated row was cast to ProcessTableRow to reuse a command-only predicate, which is sound only while that predicate reads nothing else — narrowed to Pick<'command'> so the compiler keeps it honest. The pty:signal listener relied on its provider staying async to convert a routing refusal into a rejection; it is an ipcMain.on listener with nothing above it, so it now catches synchronously too. And the repro's teardown signalled remembered pids a minute after phase 1 waited for them to die — re-verify by tag first, since signalling a recycled pid is the mistake the script exists to study. Co-authored-by: Orca <[email protected]>
…etter The readiness review found the Windows branch reading a wedged daemon's orphaned conpty hosts as live terminals. ClosePseudoConsole only runs on the daemon's own JS thread, so a daemon too wedged to answer is also too wedged to reap them, and they accumulate exactly when this code runs. A wedged, empty Windows daemon would then be held forever — #8689 re-opened, and a regression from main rather than a missing protection. The tempting fix is another exclusion. That would be the sixth revision to what counts as a live PTY, each one added because a reviewer found something that looks like a session and is not, and each one trading safety for availability in a fix whose entire purpose is the opposite trade. The list is the problem. POSIX has a real signal: forkpty makes a hosted terminal a session leader, which nothing the daemon forks for itself ever is. Windows has no equivalent, so its branch could only ever count descendants and subtract guesses. Delete it and answer 'unknown' — Windows keeps exactly the behaviour it has on main, and the protection is claimed only where it can be justified. Also stops a blind confirming read from upgrading an unconfirmed emptiness into a verdict. Emptiness is what authorizes a kill; a read that saw nothing corroborates nothing. Co-authored-by: Orca <[email protected]>
Behaviour-preserving. Windows now abstains once at the entry point rather than twice inside a retry loop that had nothing to retry, which also retires the platform check further down that could no longer be false. The self-spawn matcher kept backslash splitting and .exe stripping for a branch that no longer exists, and the launcher's grace loop repeated its own IPC call and stacked two explanations above the wrong statement. Co-authored-by: Orca <[email protected]>
Round seven found the one thing this PR must never do: kill a session that main would have kept. Main's grace loop probed with a non-shared 5s connect budget, so a wedged daemon got roughly a minute to come back. Bounding the probes and adding a wall clock cut that to about twelve seconds — a good trade on POSIX, where a daemon that outlasts the window is still protected by process-table evidence, and a bad one on Windows, which has no such evidence and now has nothing else. A Windows daemon wedged for half a minute while hosting agents was adopted by main and is killed by this branch. The fail-open cannot rescue it either: ensureRunning() is not abortable, so the launcher runs to completion. Size the window per platform instead, against what each actually spends: Windows pays no evidence read and no identity probe to feed one, so it can afford far more grace, and grace is worth more where it is the only thing there. Both numbers come from the budget test rather than taste. Three more from the same review: - The evidence read applied its deadline twice, once to the fresh table and again to the cached fallback, so an attempt could cost double what the launch budget was told. Share one deadline across both. - Two tests described protection the code no longer delivers: one asserted ~60s of grace the wall clock had already retired, the other passed only because its mocked probes are free and would fail against real ones. Say what the code actually promises, and freeze the clock where the point is retry depth. - The self-spawned PTY inventory promised more than it inspects. It sees direct node-pty calls in one directory; the macOS login-session probe reaches a PTY through expect(1) and is caught by the stranded-wrapper filter instead. Scope the claim, since that indirection is the shape the next escape will take. Co-authored-by: Orca <[email protected]>
…a sum Round eight found the fourth term missing from the hand-written budget — the launcher's own adoption connect, which runs before the health check on the non-shared five-second path. The three before it were an identity probe, an endpoint probe, and an evidence deadline applied twice. Every one of them passed the test meant to catch exactly that, because the test could only check the terms someone had remembered to add. So stop summing. The classification now runs against a deadline and stops when it expires, and the test asserts only that the deadline leaves room for the kill ladder and the fork that follow it. A budget that has to be remembered is a budget that will be wrong; this one cannot be, because nothing has to be counted. That also retires the platform-split grace window, which existed to hand Windows more of a sum nobody could total correctly. The same review found the regression it was compensating for was never the window. main gave each probe up to fifty seconds — five per connection step, thirty for the request — where this branch gave eight for both together. A daemon whose handshake needs more than four seconds therefore answered none of the probes, however many it got, and on Windows nothing else can speak for it. Splitting the two budgets fixes the case the window never could: connecting stays tight, because a daemon that cannot handshake is wedged and worth re-asking cheaply, while a daemon that did handshake is demonstrably alive and its count is worth waiting for. Also stops a Date.now spy leaking out of a failed test and freezing the clock for the rest of the file. Co-authored-by: Orca <[email protected]>
… names The clock introduced in the previous commit gated the probes but not the two steps after them. The identity re-check and the process-table read ran on their own deadlines, outside the ceiling, so the launcher could still spend its whole budget on probes and then take another ten seconds — the same overrun the sum used to produce, arrived at from the other end. Hold that time back from every probe instead. A probe is only started when the clock can still fund a handshake after the reserve, and its budget is what remains minus the reserve, so no probe can eat it however long the daemon takes to answer. Worst case is now the ceiling by construction rather than by addition. The reserve has a test asserting it is large enough for what it covers, which failed on its first run and caught that ten seconds was not. Co-authored-by: Orca <[email protected]>
Round nine found the re-verification was stricter than the check that triaged the daemon onto this path. The launcher gets here because a three-second health check — one socket, one hello — timed out. It then re-asked with two sockets and two hellos inside four shared seconds, and repeated that identical question up to twelve times. A daemon that consistently needs five seconds fails every one of them, so the retries could only ever agree with the check that sent it here. main re-asked with five seconds per connection step and thirty for the answer, and kept the sessions this branch destroyed. Retries and patience solve different problems. Keep the cheap probes, which catch a daemon that recovers on its own, then spend what is left of the clock on one tolerant ask — the only question that can disagree with the triage. It is skipped when the endpoint is provably gone, since a cold start arrives here too and has nothing to wait for. Two more from the same review. The clock claimed to cover the launcher's own adoption connect and started after it, so the fourth term that went missing from the sum was still uncounted; it now starts above that connect and bounds it. And Windows was holding back twelve seconds for an identity check and a process-table read it never performs — the reserve is zero where the steps it reserves for do not run. Retuned the ceiling to leave the kill ladder and fork real margin rather than half a second, with the packaged-Windows host copy named as what the margin is for. Co-authored-by: Orca <[email protected]>
… the answer The launcher asked the cheap question first and the patient one last. That is backwards. This path is only reached because a 3s health check timed out, so every 4s probe re-asks on a stricter budget than the one that triaged the daemon here — it can only ever agree. The one ask that could disagree ran last, by which point the clock could fund its handshake but not its answer, and a daemon that answered in 12s was read as dead and replaced along with its agents. Three changes, one idea: never make an ask you cannot afford to hear out. - The patient ask goes first, with every millisecond the answer does not need. - Cheap retries follow it, and stop once the clock cannot fund both halves. Funded to knock but not to listen is not an ask. - The adoption connect is capped. It is not a classification step — it acquires a lease preserveDaemon() re-establishes anyway — but on a daemon that accepts the socket and never completes hello it would spend the entire classification budget, leaving nothing for the probes that protect that daemon's sessions. The test double now forwards the connect budget instead of dropping it, so what the launcher was willing to wait for is observable at all.
The classification budget serves two verdicts with opposite time-costs. Reaching "don't kill" slowly is free — the daemon survives however long it took. Reaching 'empty' slowly is not, because the kill ladder and the fork still have to fit before the fail-open. At 34s that case cannot arise; at 44s it can, and an overrun there is the worst branch on offer: daemon killed, replacement forked then discarded, no provider installed, Restart broken. So the raise is not a number change, it is a number change plus a guard: hold rather than replace when the headroom left cannot fund the ladder and the fork. Safe precisely because that path has proven the daemon empty, so holding costs no agents. Written down next to the warning against tuning the budget, because the next person to want a bigger number will read that warning and need this one. Also recorded: the launcher closure has no access to the startup abort signal, so the cheap version of that guard is not available without threading it through the spawner.
Round twelve proved the loop unreachable by algebra rather than by tracing: remaining = B - E - max(CONNECT, (B - E) - REQUEST) = REQUEST, whenever B - E > CONNECT + REQUEST The patient connect takes every millisecond the answer does not need, so what survives it is always exactly OCCUPANCY_REQUEST_BUDGET_MS — and the gate wanted CONNECT + REQUEST. That holds for every ceiling, which also settles the raise I had been holding open: at 44s the remainder is still exactly the request budget, so ten more seconds of worst-case startup would have funded zero retries. Funding one honestly needs ~71s against a 60s fail-open. So WEDGED_DAEMON_GRACE_RETRIES = 11 documented patience the launcher did not have, and no number could give it. Deleted, with the derivation left where the loop was so the next person does not re-derive it from scratch. Little is lost. A 4s retry cannot reach a daemon needing longer than 4s to answer, which is the entire wedge population, while the one patient ask waits ~12s. The only case retries caught and this does not is a daemon recovering within seconds of being asked — and DegradedDaemonFreshSpawnRouter.recover() already returns it to full daemon service on the next spawn, off the startup clock. The budget tests could not have caught any of this: they recompute the expression from imported constants and never execute the launcher, so collapsing the patient connect back to the cheap constant — the round-eleven defect exactly — left all 1475 green. There is now a test that watches the launcher spend it, verified by mutation, and the arithmetic ones say plainly that they are not the guard. Also corrected: the evidence-read comment claimed the read only affects a log line. It decides the verdict wherever the unknown hold declines to — it has neither the proven-dead check nor the rejected check — so it is what holds a daemon whose socket vanished, and what holds a hello-rejected daemon still hosting agents.
…eachable Two corrections to the note, both of which change what it tells the next person. The reason the guard's case cannot arise at 34s is structural, not a lucky margin: an `empty` verdict means the daemon answered, so it resolved fast by construction, and proven-dead means nothing is listening, so the probe and the ladder both short-circuit. The path that actually spends the budget is the wedge that never answers — and that one now ends in a hold, paying neither the ladder nor the fork. Long path and expensive tail are disjoint. Raising the budget is precisely what re-couples them, by extending how late an `empty` may arrive. And the guard was costed as a signature change through DaemonSpawner, which is wrong. createOutOfProcessLauncher is a factory called where `signal` is already in scope; a third parameter closed over there leaves the launcher's call signature untouched. Overstating the price invites skipping the guard rather than paying it. Also recorded: two terms this budget does not bound at all — the healthy branch, which never consults the clock and still ends in a cleanup and a fork, and the unbounded daemon-host copy on packaged Windows.
The deletion was justified as "the loop could never run, at any budget." That is true of three wedge shapes and false of a fourth: a connect that fails fast leaves the budget nearly whole, and while refused and missing endpoints are caught by the proven-dead guard, the EPERM/EMFILE class reads 'unknown' and would have passed the gate. The deletion still stands — retrying an fd-exhausted or permission-denied connect fails identically the second time, and recover() restores full daemon service on the next spawn once the condition clears — but a comment that overstates its own reach is how the next person concludes the reasoning was never checked.
Deleting the obsolete grace-loop test took out the two tests either side of it — the ones pinning that the hold declines a proven-dead endpoint and a rejected daemon. Both exclusions went unpinned in the same commit that removed the loop, and the suite stayed green, because nothing else covers either path. Found by mutation rather than by reading: removing `health !== 'rejected'` from the hold left all 1472 passing. The pre-existing rejected test does not cover it — its second client answers listSessions, so occupancy resolves to 'empty' and the replace path is reached without the exclusion ever being consulted. The restored test keeps the daemon unreachable so the verdict stays 'unknown', which is the only state where the exclusion decides anything. Also pins the evidence gate, the other survivor: the threshold must cover an identity ps plus two ownership probes, or a read started at the last moment the gate allows finishes past the ceiling the kill ladder and fork are sized against. Mutation results now: patient connect collapsed -> caught; evidence gate -> caught; hold removed -> caught; proven-dead exclusion -> caught; rejected exclusion -> caught; fresh-spawn revert -> caught.
Two user-facing fixes were no-ops. translate() resolves from en.json, and the catalog only ever gained the string it was first synced with — the sync script adds missing keys and never updates changed defaults, which the extraction gate reports as "inline defaults differ" and then passes anyway. So editing the inline default changed the source and nothing else. Caught by rendering the component and reading what came out, not by reading the diff. What was stale in the catalog, and is now corrected there: The notice promised the panes reconnect on their own once the host recovers. They do not. TerminalErrorToast already tells the user "Reopen this pane to retry", because nothing re-attaches a pane whose owner could not be verified — the session is left untouched, which is the point, but recovery is a user action. Third claim of mine in this PR that was stronger than the code. And "Restarting the host clears this" still overstated the foreign-endpoint case, where killStaleDaemon matches no pid record and clears nothing. Also removes the components.settings.DaemonDegradedNotice.* namespace, left behind when the keys were renamed to the auto.* convention every sibling uses. It was dead weight carrying the oldest copy of all three strings.
The mode was introduced for a daemon that demonstrably owns live terminals and cannot answer a handshake. It is now also what an unclassifiable daemon gets, where the whole point is that we could not establish what it owns. A type whose comment asserts the one fact the branch could not determine is the same overclaim this PR has been correcting elsewhere. Also un-exports ENDPOINT_PROBE_TIMEOUT_MS: it was widened for a test that no longer references it, and nothing outside the module reads it.
`!mapped` was standing in for "this is a fresh spawn," and it is not the same question. The mapping is only recorded after a reply arrives, so a spawn that names a session and then loses its reply — the daemon created it, the answer timed out — is indistinguishable from a genuinely new one. Demoting there sent the retry to the fallback, which answers with a fresh local shell under the same id while the agent keeps running on the daemon. The pane binds to the shell; the agent is orphaned. That is the symptom this PR exists to remove, arriving through a door the PR opened itself. Reachability today looks nil — the only sessionId-bearing spawn in ipc/pty.ts carries attachOnly, which routes elsewhere — but the guard was unsound rather than merely unused, and "no caller does that yet" is not a property anyone maintains. Now an identified session pins to the provider that may already own it, and only an anonymous spawn moves the shared route. Anonymous spawns are what demotion was for: nothing can shadow them, and they are the ones paying a hello timeout plus a full re-classification per terminal. Found by GPT-5.6-Sol reviewing this file in isolation. Two tests added; reverting to the old guard fails one.
Adversarial review found all three; none is a regression against the pre-hold behaviour, and none should be closed by weakening the evidence rules. 'unknown' plus a proven-dead endpoint still kills when process evidence cannot answer. The probe proves the directory entry is gone, not the process — a socket entry can vanish while the daemon still hosts agents. Evidence covers that on POSIX because it runs for any 'unknown' rather than only a live endpoint, so the gap is the blind cases: clock spent, pid unverifiable, ps unreadable. It is not reachable on Windows at all, where a named pipe vanishes with its process, so a dead endpoint there implies no agents to lose. 'unknown' plus 'rejected' still kills, and the reviewer is right that inability to adopt is not inability to preserve — those agents keep running, unreachable. Killing stays the choice because a daemon that can never be adopted and is never replaced leaves the app permanently degraded with no route back, but that is a judgement, not a proof, and it is now written as one. And the verdict is not atomic with the kill: an 'empty' answer can go stale if another instance creates a session first. Pre-existing, and narrowed rather than widened here — the window now opens only after the daemon has reported zero sessions itself.
shutdownIfIdle is the right instrument and the daemon already implements it atomically: sole authenticated client, nothing in flight, zero sessions, listener closed before the acknowledgement. Asking it immediately before the kill closes the window that a re-read of listSessions can only move. It is not landing here. Gating every empty-verdict replacement on a new round trip means every failure of that round trip has to mean hold, which trades a rare race for a common failure mode and makes #8689 worse whenever the call is merely slow. It also flipped two endpoint-identity tests from rejecting to resolving, and an unexplained behaviour change is not something to merge at commit forty-two of a change whose whole subject is unintended consequences. Written down with the mechanism intact so the next person starts from a working design rather than rediscovering it.
Removing readSourceConstant matched a docblock far earlier in the file and deleted everything between, taking the imports and three functions with it. The script still parsed, still linted, and still passed `node --check` — it failed only when run, with `existsSync is not defined`, which is why it went unnoticed for two commits. The only end-to-end proof in this PR had been dead that whole time. Restored from before the deletion and the intended edit re-applied by itself. Now runs green: phase 1 kills a wedged daemon with real agents attached and confirms they die; phase 2 puts the identical wedge through the decision and shows the daemon unsignalled, both agents alive, and everything back with sessions intact on SIGCONT; phase 3 asserts the launcher holds — now including the unknown-hold, which is the branch this PR turns on. Lesson worth keeping: a syntax check is not a test. Running it is.
…t twice The second sample exists because one snapshot cannot tell a login(1) wrapper whose shell has not appeared yet from a wrapper whose shell has gone. But when the fresh read misses its deadline — the busy host this evidence exists to protect — both attempts fell through to the same TTL-cached table. Two agreeing samples, one observation, and the window being excluded is shorter than the cache. The confirming read is now denied the cached fallback. If it cannot get a fresh table it answers 'unknown', which holds. The first sample keeps the fallback, because there the cache protects the answer worth protecting: a stale table still shows that a daemon has children, and going blind there is what got them killed. Also records three limits of this evidence that review surfaced and that no code change should paper over — a reparented orphan outside the descendant tree, the Windows abstention, and an argv match that cannot establish executable identity. Each only fails to raise a verdict, so each costs a hold not taken rather than a kill licensed.
The stranded-login(1) exclusion ran on every POSIX host. Orca only wraps terminals in login(1) for TCC attribution on macOS, so off darwin the pattern can only match a user's own login — and one still prompting for credentials has no child yet, which is precisely the shape the exclusion throws away. A Linux daemon hosting that terminal read as childless, and a childless daemon is one nothing protects from the endpoint-dead path. Now scoped to darwin, where the problem it solves lives. And a count that is not a count is no longer read as emptiness. `counted > 0` maps NaN, -1 and 1.5 to 'empty', which is the single verdict that licenses a kill; the listSessions dep is injectable, so reaching it never required asking a daemon anything. Non-integers and negatives now resolve to 'unknown'. Both mutation-verified. Noting for whoever runs the next mutation pass: the first attempt at the login mutation silently failed to apply because the pattern had been reflowed by the formatter, and a mutation that does not apply looks exactly like a test suite that caught it. Assert the pattern matched.
Review confirmed the five destructive operations are guarded and that the error taxonomy holds — TerminalSessionOwnerUnverifiedError cannot be reclassified as a gone session anywhere in production, so no fake exit is ever synthesized from it. It also found six methods that still route raw, and they are worth naming rather than leaving for the next reader to rediscover: flow control, background state, buffer clear, startup authority and the per-session queries. For an unresolved daemon id those reach the fallback silently. None can destroy a session, which is why they are not being changed at this point in this branch, but a buffer clear that reports success while the daemon's history survives is a real lie. Recorded with the reason not to fix them casually: acknowledgeDataEvent is invoked directly from an ipcMain.on listener and setPtyBackgrounded from a synchronous callback, so a throwing owner check added there without changing the call sites turns a silent misroute into an escaping exception.
The review is right. Gating demotion on the absence of a sessionId assumed fresh spawns are anonymous, and they are not: every production fresh spawn mints an id before reaching the provider (ipc/pty.ts assigns spawnOptions.sessionId on all three paths). So the branch only ever ran in tests, and a daemon that recovered and wedged again kept every later terminal pointed at itself — each paying a hello timeout plus a full launcher re-classification, each failing anyway. That is the cost the demotion existed to remove, reintroduced while fixing something else. The mistake was treating one condition as two questions. Pinning protects THIS id, which the daemon may already have created before losing the reply, so a retry must never be answered locally under the same name. Demoting protects the NEXT terminal, which is a different session and cannot be shadowed by this one. They are independent, and both now happen. `attachOnly` is the honest discriminator for the second: an attach that names a session never reaches this router, so anything arriving here without it is a fresh terminal whatever id it carries. Both halves mutation-verified separately — restoring the sessionId guard fails three tests, dropping the pin fails two — including a test shaped like what ipc/pty.ts actually sends, which is what the old test suite never had.
…bout Both findings are right, and the first is pointed: this script demonstrates that signalling a pid you have not re-verified can kill someone else's work, and its own teardown did that twice. The staged daemon is killed on purpose in phase 1. Once Node reaps that child its pid is free for reuse, and teardown signalled the remembered number anyway; it now signals only while the child object still reports no exit. The markers were half-verified. Each proves its own identity by tag before being signalled, but its session leader was killed on a number remembered from staging a minute earlier — and the leader is the one pid here that can be recycled while its child lives on under a new parent. The leader is now re-read from the live marker and signalled only when the marker still claims it. Second finding: isRealUserDaemon matched a hardcoded macOS userData path, so on Linux a real daemon could never be recognised — the assertion that this run harmed nothing was inert on the platform where nobody would notice. Now matched per platform, with a loose fallback rather than a silent false. Repro re-run end to end: all three phases pass, pre-existing daemons still running, real userData daemon untouched.
Both guards in the fresh-spawn catch were too broad, and narrowing them is the one thing worth keeping from the restart-ownership branch. Demotion fired on any spawn failure. A rejected cwd or a bad profile says nothing about whether the daemon is reachable, and costing the whole session its daemon persistence over one of those degrades terminals the daemon would have served fine. It now requires the failure to look like an unreachable daemon. Pinning fired on any failure too. The pin exists for a request that was sent and whose answer was lost — that is the only shape that can hide a session the daemon already created. A failure that never reached it created nothing, so pinning that id would strand later attempts on a host holding nothing of theirs. It now requires an error that could have been dispatched. The distinction is sharper than the code it replaces: a hello timeout demotes but does not pin, because a handshake that never completed cannot have created a session. The old code pinned it anyway. Test doubles now raise DaemonProtocolError rather than plain Errors, which is what the client actually produces and what these predicates are written against. Both narrowings mutation-verified.
The readiness review flagged one claim it could neither confirm nor refute: the notice tells the user "reopening a pane retries, and works once it does", and nothing pinned that. It mattered because held mode is exactly the case where no route was ever recorded — discovery ran over the same IPC the daemon was failing — so recovery cannot come from a cached route. It has to come from the next attach re-inventorying a provider whose failure cooldown has expired. It does. While wedged the resolver refuses rather than letting the fallback answer with a fresh shell, and once the daemon answers again the same attach reattaches the original session. Verified by mutation: with the daemon left wedged, the test fails. Fourth user-facing claim in this branch checked against the code rather than assumed. The previous three were wrong.
Three conflicts, all in the ownership-critical files, and the two changes turn out to be making the same argument from opposite ends. STA-3077 made hasPty three-valued: null now means "this provider cannot answer", where before the only answers were yes and no. Its reasoning — an owner that cannot answer must stay unknown rather than become a liveness proof — is the same rule this branch applies to daemon occupancy. Both sides kept: the new signature, and the owner gate that sits above it. The gate needed no change, because `hasPty?.(id) !== true` already reads a null as "not proven" and refuses. But it needed a test. Mutating `!== true` to `=== false` left all 1525 daemon tests green: every double in the suite answers false, which makes the two predicates indistinguishable, while in production the difference is now the whole point — a null read as ownership lets the in-process fallback answer for a daemon-owned session, closing the pane while the agent runs on as an orphan. Two tests added at that boundary; the mutation is caught. pty:signal keeps both additions in the order that makes sense: their superseded-id fence first, then the routing call whose rejection is already handled.
…14361) * Revert "fix(daemon): stop killing live coding agents when the daemon can't report its sessions (#13928)" This reverts commit 2e8cf58. Reverted together with #13326: the 1.4.182-daily.202608131439 build carrying both loses every tab on an SSH disconnect/reconnect cycle. Reverting first so main stays releasable and the P0 fixes in the wild remain cherry-pickable, rather than fixing forward on a shipped regression. * Revert "fix(ssh): stop SSH reconnect from multiplying terminals and resuming agents twice (STA-3077)" (#13326) This reverts commit 3ab8b6a. Reported on 1.4.182-daily.202608131439: connect to an SSH worktree, disconnect the host from the hosts popup, reconnect — every tab is gone. That is worse than the behaviour this PR set out to fix, where most tabs were retained. Reverting rather than fixing forward, so main stays releasable and the P0 fixes already out in the wild stay cherry-pickable. STA-3077 stays open.
…nce stranding moved panes (#14384) * Reapply #13326 and #13928 (un-revert #14361) Restores the SSH reattach-identity and daemon-occupancy fixes. Reverting them reintroduced their P0s, filed as STA-4224, STA-4225, STA-4227, STA-4230, STA-4232, STA-4233 and STA-4234 against #14361. The tab loss that motivated the revert is fixed in the commits that follow, so this reapplication is not a straight redo. * fix(relay): stop the fallback attach fence refusing a pane that moved tabs The primary fence was moved to the shell's own incarnation precisely because paneKey/tabId froze the pane's LOCATION at spawn and refused panes that had merely moved. The fallback that older clients fall into kept the old rule, so the correction never reached it — the same 'the rule exists, but this path does not ask it' leak this work has hit repeatedly. A refusal here is not recoverable: an identity mismatch never grounds a respawn, so the pane keeps a live shell it can no longer reach and renders blank. Narrowed to paneKey, which is the identity; the tab is a location. Restoring the tabId comparison reddens the new test.
* test(e2e): stabilize triaged release failures (#14242)
* test(e2e): stabilize triaged release failures
* rm file
* feat(worktrees): add per-source visibility controls (#14189)
* feat(worktrees): add per-source visibility controls
* fix(worktrees): explain unsupported visibility hosts
* fix(worktrees): keep add location form inline
* fix(worktrees): align source visibility across runtimes
* test(worktrees): cover Windows drive-relative roots
* Add golden E2E tests for fresh terminal and shell commands (#14302)
* test(e2e): add golden tests for fresh terminal and shell commands
Adds regression tests for terminal initialization in fresh profiles and shell command execution to the golden test suite, integrated across Linux, macOS, and Windows CI.
* test(e2e): bracket shell command output between markers
The echoed command can wrap or be clipped by the buffer tail. Bracket output between begin and end markers to reliably identify real output, and strip ANSI escape sequences that interfere with parsing.
* test: add golden E2E tests for source control workflows (#14260)
* test: add golden E2E tests for source control workflows
- Tests core source control interactions: file edit/save, commit staging, and diff viewing
- Integrated into CI/CD pipelines for Linux, macOS, and Windows
- Includes helper utilities for test setup and worktree management
* test(e2e): verify golden commit author and fix test flakiness
- Configure git author name/email at worktree level during setup
- Verify commits are made with correct author details in assertions
- Add explicit timeouts to file visibility waits and git status polling
- Fix test ordering to seed edits after source control is open
- Simplify git status refresh logic to rely on automatic updates
* Add rollback to createGoldenWorktree on setup failure
Cleanup callbacks only register after setup succeeds. When a config
command fails, the half-built worktree and branch leak into later
test runs, causing flakiness. Now we roll back immediately and
re-throw the setup error.
* test(e2e): match explorer rows after the git status badge appears
The golden file-save spec used an exact /^README.md$/ filter. After save,
the explorer row text becomes "README.md M", so reopen clicked nothing.
* test: strengthen golden worktree setup verification
- Track working directory in git call inspection to verify correct execution context
- Verify user.name/email config applies to worktree-specific settings, not repo
- Add exhaustive setup call sequence assertions to catch setup/rollback leaks
* test(e2e): add golden E2E tests for workspace session management (#14304)
* test(e2e): add golden E2E tests for workspace session management
- Restore exact file and terminal state after quit/relaunch
- Verify terminal file link activation and external edit detection
- Test worktree creation and switching with isolated terminals
- Isolate test repo paths between concurrent CI runs with UUIDs
* Add platform-aware marker echo command utility
- Create splitMarkerEchoCommand() to generate shell commands that
safely echo test markers across Windows and Unix platforms
- Split markers into prefix/suffix fragments so output assertions
prove execution, not just shell echo-back
- Consolidate SORTABLE_TAB export and improve tab bar locator logic
- Refactor terminal link helpers to extract client point calculation
* test: add golden e2e tests for agent TUI launch and shell recovery (#14258)
* test: add golden e2e tests for agent TUI launch and shell recovery
Add test fixtures and E2E tests to verify agent TUI functionality:
- Stub agent implementation supports cross-platform execution (Unix/Windows)
- Test verifies multiline composer with Shift+Enter support in agent TUI
- Test verifies clean shell resumes after agent exit without state leakage
* test: add golden e2e tests for agent TUI launch and shell recovery
Add agent TUI launch and shell-recovery tests to the golden (release-blocking)
E2E suite, covering agent initialization and shell availability after agent
exit. Improve escape sequence handling in the stub agent to prevent stray key
reports from contaminating test output. Add terminal input readiness checks to
ensure commands execute reliably before verification.
* test: coerce golden stub stdin chunks for type-aware lint
Node types the stdin data event as string | Buffer even after
setEncoding('utf8'), so restrict-plus-operands failed CI.
* test: fix golden stub agent Windows batch files and add Ctrl+C support
- Store batch files with CRLF to avoid Windows 512-byte parser boundary bug
- Handle Ctrl+C (0x03) in raw mode as alternative to Ctrl+D (0x04)
- Update release notes documenting golden test skip behavior on older tags
* Remove Windows batch file gitattributes workaround
The -text whitespace=cr-at-eol rule preventing CRLF conversion for
.cmd files is no longer needed. Allow batch files to use normalized
line endings.
* Move worktree labels to right badge rail with truncation tooltips (#14313)
* refactor(palette): move worktree labels to right badge rail with tooltip
Move worktree and branch names from the tab title line to a dedicated right-side badge rail, preventing long titles from being truncated. Add smart tooltips showing full names when truncated, and distinguish between workspace names and branch names based on whether they're auto-generated labels.
* fix(palette): disconnect worktree rail ResizeObserver on unmount
Move truncation observation into a layout effect so React Doctor sees a cleanup path and the subscription cannot leak after unmount.
* Fix mobile HTML report rendering (#14196)
* fix(mobile): render local HTML reports at phone width
* fix(mobile): satisfy browser URL lint
* feat(agent-map): make an unread finish visible and let a glance demote it (#14197)
* feat(agent-map): make an unread finish visible and let a glance demote it
A finished agent was the quietest mark on the map. `status-glow` was defined
only for working/waiting/blocked, so a finish got a 1.7px emerald stroke on a
6px mark and no halo — invisible across a 200-agent fleet.
Worse, `dashboardCardDisplayState` folds `done && !unseen` into `idle`, so
opening an agent erased it: finished-but-unlanded work looked exactly like a
workspace that never ran. Looking at something is not the same as dealing
with it.
Split the two on the map only, via a local `AgentMapNodeStatus` at the single
`agentMapNodeStatus` seam. `DashboardCardDotState` crosses the pop-out bridge
and is unchanged, so there is no wire change and bucket counts are untouched.
- done + unseen: filled emerald core, emerald halo, one-shot 1.4s flare
- done + seen: hollow emerald, no halo — still yours to land
- workspace ring turns green only once the whole workspace has settled
The flare is gated on a wall-clock recency window, not the map's `now` prop:
`now` ticks every 30s to refresh relative timestamps, so measuring a 1.4s
window against it fired at random moments instead of on the transition.
* fix(agent-map): bound completion paint work
* perf(agent-map): avoid fleet flare allocation
* fix(agent-map): localize seen completion label
* Remove unrelated merge formatting changes
* test(agent-map): guard completion burst paint budget
* fix(mobile): stop republishing stale launch agent identity (#14244)
* fix(mobile): keep terminal identity scoped to leaves (#14247)
* fix(mobile): scope terminal identity to leaves
* fix(mobile): preserve leaf title projection
* fix(agent-map): hold orchestration chevrons at a fixed pitch (#14256)
* fix(dashboard): hold agent map orchestration chevrons at a fixed pitch
CHEVRON_SPACING only chose how many chevrons to draw; placement then divided
the edge evenly, so the pitch grew with the distance between agents and, past
the 32-chevron cap, grew without bound. Step at a literal 8px pitch instead,
centering the run so it never overhangs either node.
Fixed pitch makes length drive the chevron count, so cap coverage now decides
how far the run reaches: at 32 it spanned only 248px and every longer link
would have shown a chevron cluster stranded mid-edge. Raise it to 256 (~2048px,
past any real in-project link) and memoize the generated path per endpoint
coordinates, since the scene rebuilds every path string on each zoom frame and
on 4Hz snapshot refreshes while world positions stay put.
* test(agent-map): isolate lineage path cache coverage
* fix(orchestration): preserve direct user authority after worker_done (#14192)
* fix(orchestration): preserve direct user authority
* test(orchestration): assert settled dispatch boundaries
* fix(terminal): clear the SGR pen on hidden-output restore and abandon (#14241)
* fix(terminal): clear the SGR pen on hidden-output restore and abandon
The hidden-delivery gate drops renderer-bound PTY bytes while a pane has no
visible view. The renderer's xterm is a separate emulator from the daemon
model, so when the dropped span contains the sequence closing an attribute run
(e.g. the ESC[22m ending a bold run) the renderer's pen stays latched while the
daemon model stays correct. Neither recovery path cleared it:
- buildMainModelSnapshotReplayWrites reset the pen on the two alt-screen
branches but not on the normal-buffer branch, and replayed scrollbackAnsi
ahead of the reset it did emit, so replayed content inherited the stale pen.
- abandonHiddenOutputRestoreAndDrainPendingForeground declares the dropped
bytes unrecoverable (it writes a user-visible warning) and then drained the
queued foreground chunks straight into xterm under that same unknown pen.
Add RESET_GRAPHIC_RENDITION and emit it ahead of replayed content in every
branch, and on both abandon exits. The existing profiles all clear DEC mode
bits and none touched SGR.
* fix(terminal): also restore charset designation after a dropped-byte gap
A gap can strand more than the pen: a dropped `ESC(B` leaves line-drawing
selected and ordinary text renders as box characters. Route both recovery
paths through one RESET_AFTER_BYTE_GAP profile covering SGR + charset.
Deliberately not a soft reset (DECSTR): xterm's DECSTR wipes kitty flags and
stacks (terminal-kitty-keyboard-mode-tracker applySoftReset), which would
silence Option chords for a live agent that negotiates them only at startup.
Reset what a gap strands and no running TUI re-asserts on its own; leave the
rest to its next repaint.
* fix(terminal): close the emulator state gap where the drop is announced
The restore-needed marker is the single point where "renderer-bound bytes
were dropped" is known. The handler already resets the transport's
cross-chunk parser state there for exactly this reason — a partial escape
spanning the gap would corrupt the next chunk. The emulator carries state
across chunks in the same way, so reset it in the same place.
That makes restore, abandon and overflow all start from a known pen by
construction, instead of each recovery path having to remember.
* fix(terminal): fully ground byte-gap recovery state
* fix(terminal): reset state when remote restore re-arms
* fix(terminal): keep the gap reset on the warning abandon path
The reset had been folded into an else of the unavailable-warning branch, so
the primary abandon path relied on the marker's earlier reset still standing.
It does not always: this function captures a replayingSnapshot, so it can run
after a partially-applied replay has already moved the pen, and the warning
itself is plain text carrying no SGR. Restore the unconditional write, guarded
only against the remote re-arm which writes its own.
* fix(terminal): scope the byte-gap reset to the pen and skip it under flood
Two regression risks in the widened recovery reset, both removed:
- The profile had grown to cancel partial escapes, close OSC 8 and re-designate
all four ISO 2022 registers. Each changes what a live TUI sees on a path that
runs in production, and none has a reported symptom behind it — a legitimately
line-drawing TUI that does not re-designate after recovery would render box
characters as ASCII. Scope back to SGR, which is what the field reports show.
- The marker-time reset ran before the flood-backpressure guard, so a flood
wrote one reset per marker in exactly the case that guard exists to damp. Move
it after; the flood path repaints through buildMainModelSnapshotReplayWrites,
which grounds the pen itself, so no coverage is lost.
Coverage verified non-vacuous: blanking RESET_AFTER_BYTE_GAP fails 5 tests
across all four paths (replay branches, marker, abandon-with-warning, remote
re-arm).
* test(e2e): stabilize release triage coverage (#14328)
* test(e2e): stabilize release triage coverage
* test(e2e): avoid post-selection remount race
* test(e2e): wait for New tab search focus
* test(e2e): focus New tab search without pointer input
* test(e2e): reopen voice settings after device change
* test(renderer): cover Agent Dashboard status replay fanout (#14036)
* test(native-chat): deflake watcher rebind (#14335)
* fix(orchestration): retry silent mail pointers (#14332)
* fix(orchestration): retry silent mail pointers
* fix(orchestration): bound mail pointer repair
* fix(docs): replace stale preload typecheck reference (#14298)
* docs: fix stale preload typecheck reference
Signed-off-by: HoonDongKang <[email protected]>
* docs: keep .d.ts guidance canonical
---------
Signed-off-by: HoonDongKang <[email protected]>
Co-authored-by: Jinwoo-H <[email protected]>
* fix(sidebar): remove non-Orca source icons (#14345)
* feat(dashboard): give the agent question state its own color and glyph (#14248)
* feat(dashboard): give the agent question state its own color and glyph
On the agent map, 'working' (yellow-500) and 'waiting' (amber-500) sat 16 hue
degrees apart and rendered as identical halo rings, so the only cue separating
"busy, leave it alone" from "it is asking you something" was a hue step most
people cannot resolve at map zoom. Every other surface distinguishes the two by
shape (spinner vs question glyph); the map had dropped that.
Move 'waiting' to orange-500 — midway between working-yellow and blocked-red —
and give the map node the same question glyph the sidebar and tabs already use,
so the state reads by shape when hue fails (low zoom, red-green CVD).
Both live behind one token, --agent-question, plus a shared AgentQuestionIcon,
so the sidebar, terminal tabs, kanban, toolbar and map cannot drift apart again.
The unread amber pip is deliberately left alone: "new output" and "needs an
answer" are different states and now read as different colors.
* test(dashboard): retarget the agent-row question assertion at the shared token
DashboardAgentRow renders the glyph through AgentStateDot, so the component
already moved with the token — only its assertion still pinned text-amber-500.
Missed locally because I ran components/dashboard-popout but not
components/dashboard.
* fix(dashboard): raise light question marker contrast
* perf(dashboard): keep question badges on the SVG paint path
* fix(worker-start): match Codex effort ceilings (#14281)
Honor the advertised reasoning-effort ceilings for Codex models, preserve conservative unknown-model handling, and localize the new ultra effort label.
* feat(sidebar): replace the external-worktrees inbox list with one card (#14341)
The Non-Orca worktrees modal already lists every hidden external worktree
with search, virtualization, and per-row Show. Its filter is a strict
superset of the sidebar inbox's, so the expanded sidebar list was a second,
worse copy that grew to ~900px at 24 worktrees.
The inbox is now a single clickable card stating the count, which opens that
modal. Drops the expand state, nested list, per-row Import, and the
Keep hidden / Import all footer.
* fix(native-chat): retain watcher identity during initial drain (#14344)
* fix(skills): use exported recipe id in environment guide (#14280)
* fix(skills): use exported recipe id in environment guide
* fix(skills): keep recipe-derived Vercel names valid
---------
Co-authored-by: Jinwoo-H <[email protected]>
* feat(agent-map): flare fresh questions and finishes (#14349)
* fix(ai-vault): make the merged scan stamp independent of leg order (#14270)
* fix(ai-vault): make the merged scan stamp independent of leg order
The all-host merge picked its stamp with a strict `stampMs > latestMs` and
echoed the winning leg's verbatim string. Two legs reporting the same instant
in different legal ISO shapes ("...:05Z" vs "...:05.000Z") therefore resolved
by position in the results array, i.e. by host-enumeration order (local, then
SSH, then runtime). The prior lexicographic max was order-independent, so this
was a regression with no test covering it.
A merge has no single scan instant, so its stamp is derived data rather than
any one leg's string: return the canonical ISO form of the newest accepted
instant. That is order-independent and format-independent, and drops a
variable instead of adding a tie-break branch.
Also share one request resolver between main and the renderer so the
renderer's merged-scope predicate is equivalent to main's routing by
construction, rather than by a comment that overclaimed it.
* docs(ai-vault): scope the merged-predicate comment to the desktop IPC path
The replacement comment still asserted the result is always several hosts'
legs. The paired web transport drops executionHostScope and serves one host,
so 'all' there is a single scan. State that the predicate is deliberately
over-inclusive and why erring the other way would be unsafe.
* test(ai-vault): pin the merged-stamp Date range boundary
new Date(ms).toISOString() throws RangeError outside +/-8.64e15. That is
unreachable only because Date.parse applies TimeClip, so the NaN guard alone
constrains the argument. Nothing pinned that. Dropping the guard now fails
these two cases with the RangeError they exist to prevent.
* refactor(ai-vault): route session-title scope through the shared resolver
The last character-for-character copy of the request-scope default. Leaving
it would make the shared resolver the single source of truth for two of three
sites, which is the drift this change exists to remove. No behavior change.
* fix(browser): fence the cookie-clear fallback to the pre-clear snapshot (STA-4170) (#14343)
* fix(browser): fence the cookie-clear fallback to the pre-clear snapshot (STA-4170)
The post-rejection fallback re-read the live cookie jar and removed everything
removable at that moment, while restore only ever covered the pre-clear
identity snapshot. A cookie that arrived mid-clear -- a login the user had just
completed -- was therefore deleted with no identity able to put it back, and a
later removal failure still reported "existing cookies were restored".
Fix the removal plan at the same point as the identity snapshot so the mutated
set can never exceed the restore set. Arrivals are not touched at all, which
matches what the successful bulk-clear path already does.
* test(browser): lock same-coordinate arrival rollback to the pre-clear value (STA-4170)
* fix(daemon): isolate durable-history checkpoints per session (STA-4173) (#14346)
PR #14193 routed warm reattach and deep-buffer snapshots through
overlayDurableRestoreSnapshot, which joined a single process-wide
checkpoint tail with no deadline. One never-settling checkpoint blocked
every daemon-backed terminal from reattaching.
Checkpoint exclusivity only protects one session directory's
tmp-write/rename pair, so serialize per session instead. Reattach now
waits on a bounded deadline and degrades to the daemon's live window;
the abandoned compact keeps running and still commits, so a blown
deadline costs restore depth for one reattach, never durable history.
* revert(ssh): back out #13326 and #13928 — reconnect loses every tab (#14361)
* Revert "fix(daemon): stop killing live coding agents when the daemon can't report its sessions (#13928)"
This reverts commit 2e8cf589de2bee2365d3798b471f39bc7e13989b.
Reverted together with #13326: the 1.4.182-daily.202608131439 build carrying
both loses every tab on an SSH disconnect/reconnect cycle. Reverting first so
main stays releasable and the P0 fixes in the wild remain cherry-pickable,
rather than fixing forward on a shipped regression.
* Revert "fix(ssh): stop SSH reconnect from multiplying terminals and resuming agents twice (STA-3077)" (#13326)
This reverts commit 3ab8b6a11769666b7ac4d43a38a82c771dffaad6.
Reported on 1.4.182-daily.202608131439: connect to an SSH worktree, disconnect
the host from the hosts popup, reconnect — every tab is gone. That is worse than
the behaviour this PR set out to fix, where most tabs were retained.
Reverting rather than fixing forward, so main stays releasable and the P0 fixes
already out in the wild stay cherry-pickable. STA-3077 stays open.
* fix(terminal): resolve legacy wrapper fallbacks from PATH only (STA-4169) (#14365)
The retained git/gh compatibility wrappers resolved their real binary with an unqualified lookup. On Windows that searches the current directory before PATH, so a repository-local git.exe/gh.exe ran with the user's arguments. The POSIX wrapper had the same exposure through empty PATH elements, which mean the current directory.
All three wrappers now resolve only against the cleaned PATH: cmd and PowerShell walk it explicitly instead of delegating to a lookup that includes the cwd, and the POSIX filter drops empty elements. Candidates inside the wrapper directory stay rejected.
* fix(orchestration): wait for Claude composer render (#14342)
* fix(orchestration): make late task readiness atomic (#14163)
Derive initial dependency readiness inside the task INSERT so concurrent completion and creation cannot strand a task in pending.
Add deterministic state-machine coverage and a built-CLI RPC/runtime persistence E2E.
Fixes #14143
* fix(orchestration): resolve explicit worker worktrees directly (#14275)
* fix(orchestration): resolve explicit worker worktrees directly
* fix(orchestration): share worker workspace resolution
* fix(runtime): reject cross-host path ambiguity
* fix(orchestration): share federated workspace resolution
* refactor(runtime): share worktree host identity
* test(orchestration): align worker lifecycle fixtures
---------
Co-authored-by: Jinwoo-H <[email protected]>
* fix(terminal): make the bold font weight its own setting (#14368)
* fix(terminal): make the bold font weight its own setting
Deriving bold as max(700, regular + 200) silently destroyed bold. A family
exposes only a few real faces: the monospace the default chain resolves to on
macOS has exactly two, splitting at 600. Measured by rasterizing each weight to
a canvas — 100-500 are byte-identical (ink 3023) and 600-900 are byte-identical
(ink 3855), at every weight the same advance. So any base weight at or above 600
put both values in the same face and bold stopped existing, on 4 of the 9
positions the slider offers, with no error and nothing the user could do.
Arithmetic cannot fix it — on a two-face family there is no heavier face to
escape to. So bold is now user-owned: a new terminalFontWeightBold setting with
its own control, defaulting to 700. The default pair (500/700) straddles the
boundary, so existing profiles render exactly as before; a collision is now a
choice the user can see and undo.
The old test asserted 800 -> {800, 900} as 'keeps bold heavier', which is where
this hid: numerically heavier, identically rendered.
* fix(terminal): surface bold face collisions accurately
* fix(serve): exit cleanly after headless Linux signals (#14334)
* fix(serve): keep owned Xvfb alive through Electron teardown
* test(serve): gate packaged signal shutdown
* test: harden headless shutdown lifecycle gate
* fix(serve): isolate Xvfb from foreground signals
* docs(serve): preserve Xvfb during systemd stop
* test(serve): pin shutdown policy to owned Xvfb unit
* test(serve): harden shutdown gate portability
* test(serve): bound systemd unit parsing
* Fix paired remote terminal browser links
STA-4181
* Narrow paired browser link fix to registration race
* fix(terminal): reject cwd-resolving PATH entries and harden the legacy wrappers (#14370)
* fix(terminal): guard cmd wrapper PATH walks against an empty variable
An empty PATH or cleaned PATH left the substitution with an unbalanced quote, desynchronizing cmd parsing so the not-found branch emitted a parse error instead of its message. Reproduced and fixed on real Windows.
* fix(terminal): reject relative PATH entries and drop the dirname dependency
Adversarial review found the STA-4169 fix incomplete: it dropped empty PATH elements but kept relative ones, which resolve against the current directory identically. A repo-local git was still executed via PATH=. or node_modules/.bin, reproduced in all three wrappers.
Also removes the external dirname call in the POSIX wrapper (an unresolvable dirname silently made wrapper_dir the cwd, so the wrapper failed to exclude itself and reported git missing while git was on PATH), compares against the cached wrapper dir in the cmd subroutine where %~dp0 is rebound by CALL, and probes .cmd after .exe so a non-.exe git is still found.
* fix(terminal): test rooted paths in pure batch, not via an external tool
The rooted-path guard shelled out to findstr, which cmd resolves from the current directory first — so a repository-local findstr could run, and a malicious one could report success for every entry and defeat the guard entirely. Same hijack the guard exists to prevent. Now a pure-batch substring test with no external process.
Splits the Windows wrapper templates into their own module to stay under max-lines without a suppression.
* fix(terminal): reject drive-relative PATH entries and fix no-slash wrapper dir
Round-2 review: PowerShell IsPathRooted accepts drive-relative C:foo, which still resolves against the current directory on that drive. IsPathFullyQualified is absent on Windows PowerShell 5.1 (verified 5.1 on the test host), so match the same prefixes the cmd wrapper accepts.
The POSIX %/* strip yields the file name when the path has no slash, so wrapper_dir became the name, self-exclusion missed the shim dir, and the lookup resolved back to the wrapper (spurious 127). Handled with a case split.
Also probes .bat, since the replaced lookup honored PATHEXT.
* fix(agent-status): preserve Codex escape interruption (#14372)
* fix(vm): make hidden SSH cleanup retryable (#14351)
* feat(vm): add provisioned root recipe contract (#14352)
* fix(vm): adopt provisioned SSH checkout roots (#14353)
* feat(vm): create workspaces from provisioned SSH roots (#14359)
* feat(vm): use recipe-provisioned SSH roots
* fix(vm): preserve ordinary create failure timing
* test(vm): prepare provisioned root SSH fixture
* ci(vm): enable SSH setup for provisioned root E2E
* fix(macos): recover severed terminal TCC attribution after updates (#13992)
* fix(macos): recover severed terminal TCC attribution after updates
When a packaged update leaves the daemon healthy but TCC-severed (spawning
binary gone), surface a Manage Sessions toast and replace the daemon before a
new terminal only when zero live sessions remain. Does not broaden FDA or
auto-kill sessions. Addresses the Orca-specific path of #13594.
* fix(macos): coalesce severed-TCC toast checks and sync i18n keys
Add catalog entries for the Manage Sessions toast strings and guard overlapping
mount/focus probes with an in-flight latch so only one infinite toast can fire.
* test(macos): harden severed TCC recovery coverage
* fix(macos): clear recovered TCC warning
* fix(macos): clarify severed TCC warning copy
* fix(macos): bound TCC attribution health checks
* fix(macos): preserve bounded attribution checks after merge
* test(macos): use real execFile callback contract
* fix(macos): cover legacy daemon attribution
* fix(macos): clarify affected Orca terminals
---------
Co-authored-by: Brennan Benson <[email protected]>
* feat(dashboard): give the agent map a real filter panel (#14338)
* feat(dashboard): filter the agent map by multiple hosts
The map's host control was a single-choice segmented row in its own header:
pick All, Local, SSH, WSL, or Remote — never two at once. It also sat outside
the shared filter menu, so the menu's badge never counted it and "Clear all
filters" could not reach it.
Hosts are now checkboxes in the filter menu alongside agent state, so a fleet
split across a Mac and a Windows runtime can show both and hide the rest.
Hosts that contribute no agents are omitted, and the section hides entirely
for a single-host fleet.
Lifting `hostFilter` out of AgentMap also drops `compact`, which existed only
to hide the segmented control next to an open terminal panel.
The filter-option builders move to agent-dashboard-filter-options.ts to keep
AgentDashboardToolbar under the 400-line cap; that move is mechanical.
* feat(dashboard): give the agent map a real filter panel
The map's filters were a single-choice host row in its own header plus a few
rows borrowed from the board's dropdown. This replaces them with one panel that
owns every map facet.
- Quick views: Everything / Needs me / Stuck / Unread / Last 30 min /
Long runners / Stale > 3d / Orchestration. Each replaces the filters
wholesale rather than stacking on whatever was set.
- Provider (agent type) checkboxes.
- Three time ranges — session lifespan, since last message, time in current
state — on a non-linear scale so minutes and days are both reachable.
- Orchestration flows select the coordinator *and* the agents it dispatched;
a children-only filter hid the half that explains the flow.
- Sections collapse, each showing its value when closed. A section that is
filtering forces itself open so a collapsed row can never be the reason the
map looks emptier than the filters claim.
- The shown-count moves into the panel header, next to the controls that
change it, and now reflects the map's own facets rather than the board's.
The map's surface becomes a Popover, not a DropdownMenu: the panel holds range
sliders and a Radix menu swallows the arrow keys those need. The board keeps
its dropdown untouched via a new `filterControl` slot on the shared toolbar.
`ui/slider` renders one thumb per value so a two-value range works; the two
existing single-value callers are unchanged.
* fix(dashboard): preserve agent map filter semantics
* refine agent map filter facets
* perf(dashboard): keep map filters out of main view
* fix(terminal): bake the wrapper interpreter and emit CRLF for cmd (#14382)
* fix(terminal): bake the wrapper interpreter and emit CRLF for cmd
Round-3 review: the shebang resolved bash through the inherited PATH before any script hygiene, so a relative or empty PATH element let an untrusted checkout supply the interpreter. Bakes an absolute verified interpreter with an env fallback.
Normalizes trailing separators in the cmd comparisons; without it a wrapper-dir entry spelled with a trailing backslash escaped self-exclusion and the wrapper tail-chained to itself forever.
Found while verifying on Windows: cmd resolves call targets by byte offset and fails on LF-only files once they grow (worked at 2.4 KB, failed at 3.7 KB), so the Windows wrappers now emit CRLF. Also avoids two cmd parser traps: a trailing backslash before a closing quote in an if comparison, and percent expansion inside rem comments.
* fix(terminal): resolve the wrapper interpreter from absolute PATH entries too (STA-4226)
The well-known-candidate list would fall back to an ambient env lookup on distributions that place bash elsewhere (NixOS, Guix), restoring the exposure. Search absolute PATH entries before giving up, skipping relative and empty ones because those mean the current directory.
* fix(ssh): reapply the reattach-identity work and stop the fallback fence stranding moved panes (#14384)
* Reapply #13326 and #13928 (un-revert #14361)
Restores the SSH reattach-identity and daemon-occupancy fixes. Reverting them
reintroduced their P0s, filed as STA-4224, STA-4225, STA-4227, STA-4230,
STA-4232, STA-4233 and STA-4234 against #14361.
The tab loss that motivated the revert is fixed in the commits that follow, so
this reapplication is not a straight redo.
* fix(relay): stop the fallback attach fence refusing a pane that moved tabs
The primary fence was moved to the shell's own incarnation precisely because
paneKey/tabId froze the pane's LOCATION at spawn and refused panes that had
merely moved. The fallback that older clients fall into kept the old rule, so
the correction never reached it — the same 'the rule exists, but this path does
not ask it' leak this work has hit repeatedly.
A refusal here is not recoverable: an identity mismatch never grounds a respawn,
so the pane keeps a live shell it can no longer reach and renders blank.
Narrowed to paneKey, which is the identity; the tab is a location. Restoring the
tabId comparison reddens the new test.
* Fix Codex hook trust before manual shell launches (#14326)
* fix codex hook trust before shell launch
* fix packaged cli preflight dependency
* fix codex shell preflight safety
* fix Codex shell preflight settings and startup safety
* fix(updater): recover renderer shutdown checkpoint (#14373)
* fix(updater): recover renderer shutdown checkpoint
* test(updater): cover checkpoint recovery in Electron
* fix(updater): keep staging failures blocking
* fix(terminal): name the POSIX interpreter directly when generating on Windows (#14386)
The resolver could never succeed on Windows — no absolute candidate exists there and the PATH search split on the POSIX delimiter — so it always fell back to the ambient lookup it exists to avoid, on a wrapper Git Bash and WSL panes do execute.
Also rejects interpreter candidates containing whitespace (a shebang cannot quote) or that are directories (X_OK alone is true for those), and replaces the sentinel trailing-separator strip, which corrupted paths containing the sentinel, with a comparison against a variable holding the separator.
* fix(mobile): self-heal host opens and harden session liveness (#14333)
* fix(terminal): clear CDPATH when resolving the wrapper directory (#14387)
* fix(terminal): clear CDPATH when resolving the wrapper directory
cd consults CDPATH for a relative operand and echoes where it landed, which the command substitution captured — wrapper_dir came out wrong, the lookup resolved to the tombstone itself, and git died at 127 with a working git on PATH.
Also pins the self-reference guard that turns that failure into a clean 127 rather than repeated self-exec; deleting it previously left the suite green. Both new tests are mutation-verified: an earlier version of each passed with the bug reintroduced because the CDPATH fixture mirrored only the first path segment.
* test(terminal): pin the wrapper guards that survived mutation
A mutation campaign found several security properties with no coverage. Most important: nothing asserted the Windows *reject* path for relative candidates, so deleting it reopened the cwd hijack while every accept-path assertion stayed green.
Also pins the separator variable value (any other character silently un-pins the trailing-separator fix), and grounds the interpreter-search test in the running process cwd — a relative PATH entry resolves against that, so the previous fixture in a tmpdir passed whether or not the guard existed. Each is mutation-verified.
* Revert "fix(ssh): reapply the reattach-identity work and stop the fallback fence stranding moved panes" (#14395)
* perf(worktrees): bound the duplicate-id scan in reuseEqualCatalogRows (#14271)
* perf(worktrees): bound the duplicate-id scan in reuseEqualCatalogRows
Rows sharing an id are scanned linearly with a deep compare each, so a bucket
of k duplicates costs O(k^2). Both callers key on ids that are unique by
construction, so this is a bound on damage rather than a live fix.
Cap the scan instead of adding a second index: reuse is only an optimization,
so a missed match yields a new object identity, never a wrong row. A fingerprint
index would buy a little more reuse in a case nothing reaches, at the cost of a
second equality implementation that must stay in step with catalogValuesEqual
with no automated guard.
Worst-case duplicate bucket, no matches: k=1000 134ms -> 1.2ms, k=2000 541ms ->
2.2ms. Unique-id path unchanged (2000 rows: 0.86ms both).
* docs(worktrees): lead the duplicate-id cap comment with its reachability
A reader hitting MAX_DUPLICATE_ID_SCAN should learn first that no caller
produces duplicate ids today, so the cap reads as bounding future damage rather
than fixing something live.
* test(terminal): pin the wrapper security properties that survived mutation (#14394)
* test(terminal): pin the seven wrapper security properties that survived mutation
The PowerShell drive-relative pin was a prefix that also matched the insecure regex, so re-accepting C:foo left the suite green. Now asserts the full pattern.
Also pins all four PowerShell TrimEnd sites, the fallback wrapper-dir skip, the cmd legacy-dir trailing-separator strip, and C:/-style drive acceptance, plus a behavioural test for the POSIX legacy-dir reject with a distinct ORCA_ATTRIBUTION_SHIM_DIR. Each verified by reverting the property and confirming the suite fails.
* test(terminal): cover the trailing-separator scrub in the path matcher
isLegacyTerminalShimPathEntry sits outside the two generator modules, so the mutation campaign never re-ran it. Dropping its trailing-separator strip survived the suite: a PATH entry spelled with one would not match, leaving the legacy shim directory on the spawned PATH and the wrapper reachable. Mutation-verified on both the POSIX and Windows spellings.
* ci(windows): cover the worktree admin fingerprint on the Windows runner (#14378)
The fingerprint gate added in #14207 reads Git's administrative layout directly -- `.git` as a file or directory, `commondir`, and per-worktree `HEAD`, `gitdir`, and `locked` -- instead of shelling out to `git worktree list`. That makes it depend on Windows path resolution, CRLF inside those files, and whether `worktree move`/`lock` and deleting a live checkout behave as they do on POSIX.
PR CI runs the vitest suite on ubuntu-latest only, so none of that was exercised. Both suites were verified by hand on a real Windows host (Git 2.55.0.windows.3, Node 24.18.0) and pass 25/25, but nothing kept them passing.
Add them to the existing curated `Test Windows-specific boundaries` step rather than standing up a new job: the `package (windows)` job already checks out and installs dependencies, so this costs only the tests themselves.
* Center newly opened tabs at end, keep close controls visible (#14314)
* Center newly opened tabs at end, keep close controls visible
- Add end padding to tab strip to preserve close button visibility against fade
- Center scroll position for newly revealed end tabs, avoiding hard scroll-to-end
- Only pin-to-end for new tabs that are also active; restored mid-strip tabs stay in place
* test(tab-scroll): clarify when tabs center vs settle at end
Add lastTabGeometry helper to correctly derive scrollWidth from the pad policy. Update test expectations to document that center requests only land centered when the strip is within 2x the inset of the last tab's width; wider gaps settle at the end with inset.
* fix(tab-bar): sync active tab id ref after render
React Doctor rejects mutating refs during render. Keep the latest
active tab id in a layout effect so overflow navigation still sees
it without an impure render write.
* fix(orchestration): release federation ack checkpoints once a dispatch settles (#14380)
Checkpoints were inserted per synced federated dispatch and never removed; the
only eviction dropped the whole map, and none of its three call sites fire in
normal operation. A long-running federated coordinator retained one small
object per dispatch for the process lifetime.
Prune from the existing syncOrchestrationFederatedDispatch finally, which is
the one hook covering all five paths that create a checkpoint — including the
two RPCs that sync an already-terminal dispatch with no timer to prune after.
Refs STA-4014
* fix(worktree-scan): stop a stalled admin probe from poisoning repo refresh (#14379)
The scan cache stored the Git-admin fingerprint as an unsettled promise, so a
readdir/stat that never returns (hard NFS/SMB mount, dead sshfs, wedged cloud
FileProvider) left every later refresh awaiting it. The in-flight entry was
never cleared, so the repo fell back to persisted rows indefinitely — and since
computeResolvedWorktrees awaits all repos together, one wedged repo added 5s to
every snapshot for all of them.
Cache the settled value instead, filled by an identity-guarded writeback, and
bound the one branch that actually awaits the probe. withTimeout cannot cancel
a readdir, so an outstanding-probe guard keeps a wedged mount from issuing a
fresh probe every refresh and pinning every libuv fs thread.
Refs STA-4171
* fix(workspaces): gate the GitLab palette number match on repo identity (#14381)
* fix(workspaces): gate the GitLab palette number match on repo identity
After a full GitLab identity compare failed, matching fell through to an
unguarded iid compare, so a pasted URL could activate a workspace from another
project or host. GitLab iids are per-project and start at 1, so small-number
collisions across projects are the norm.
Mirror the GitHub shape rather than rejecting outright: gate the number-only
fallback on a tri-state repo identity check that stays permissive when identity
is unresolvable, so forks and host aliases keep matching. A stored URL that
parses to a different project with the same type and number is a direct
contradiction and is rejected even when identity is unknown.
Refs STA-4155
* fix(workspaces): keep the GitLab repo gate permissive for fork checkouts
deriveGitRemoteIdentity keeps a single remote and ranks `upstream` above
`origin`, so a fork checkout resolves to the upstream project and the fork's
own origin is invisible to the gate. Rejecting on that mismatch dropped MR
URLs from the fork the user actually checked out — a false negative the
tri-state was meant to prevent. Treat an upstream-derived identity as unknown.
Refs STA-4155
* docs(workspaces): note that the GitLab repo identity is a one-shot snapshot
* test(terminal): fix ordering pins that pass when the needle is absent (#14409)
Five pins compared indexOf positions without asserting presence, so a missing needle returned -1 and the assertion passed. Deleting the legacy-shim-dir capture in both Windows wrappers stayed green that way, disabling legacy-dir PATH removal. All five now route through a helper that asserts both operands exist first.
Adds coverage for four properties proven load-bearing by execution: the path_entry_kept guard (without it an empty cleaned PATH resolves a cwd-local git), the cleaned PATH on exec, and multi-separator matching in the shared path matcher.
* Forward Unix launcher signals to orca serve supervisor (#14071)
* fix(cli): forward Unix launcher signals to serve
* test(cli): retry incomplete listener state writes
* test(cli): cover both Unix launcher termination signals
* test(cli): cover macOS launcher signal oracle
* refactor(cli): keep Unix launcher exec atomic
---------
Co-authored-by: Jinwoo-H <[email protected]>
* fix(terminal): stop leaking raw PTY lifecycle tokens into the error toast (#14415)
* fix(terminal): stop raw PTY-not-found and session-expired tokens reaching the error toast
A reattach the host answers "no such session" for surfaced its wire token
verbatim — `SSH_SESSION_EXPIRED: orca:<conn>@@pty-N` or the relay's raw
`PTY "..." not found` — including the internal PTY id, and invited the user
to file an issue for an ordinary lifecycle event.
Humanize both in the toast's existing daemon-boundary seam and mark them
explained so the issue link is suppressed. The copy stays silent on whether
the remote shell died: absence from the host is not proof of exit.
Refs STA-4238
* style(terminal): apply oxfmt to the toast humanization tests
* fix(terminal): treat the humanized session copy as literal replacement text
* fix(repos): re-probe git remote identity so a stale snapshot stops misjudging identity gates (#14414)
* fix(repo-identity): re-probe resolved git remote identities on a long TTL
A resolved gitRemoteIdentity was written once and frozen for the life of the
repo record, so adding an `upstream` remote later — or a project rename or
transfer — left identity gates judging against the path the repo had when it
was added. Re-probe resolved repos on a 6h TTL, seeded 5 minutes after a repo
is first seen in a process and capped at 4 refreshes per sweep so a restart
cannot fan out a subprocess per repo. Only a successful probe that yields a
different canonicalKey overwrites; failures and no-remote answers leave the
existing identity alone.
Also explain why the worktree-scan admin fingerprint timeout deliberately
exceeds its caller budget, and log when that probe expires — expiry was
silent and indistinguishable from "fingerprint unavailable".
Refs STA-4247
* fix(projects): carry project state across derived project id changes
A project id is derived from repo identity, so a remote re-probe (or a
repo:->git:->github: promotion) rewrites it. The compatibility merge matched
prior rows by id only, dropping the user's localWindowsRuntimePreference and
leaving a ghost project row that independent host setups still pointed at.
Both merge sites now fall back to the prior row whose sourceRepoIds overlap and
re-point independent setups at the surviving project.
* fix(workspaces): gate the GitHub palette number match on repo remote identity (#14413)
* fix(workspaces): gate the GitHub palette number match on repo identity
`repoMatchesGitHubSlug` returned the permissive `'unknown'` whenever the repo
displayName was not in `owner/repo` form and no upstream metadata existed — the
common basename-named non-fork case. The caller only rejects on `false`, so a
pasted issue/PR URL could activate a workspace in a different repo that happened
to share the number, since issue/PR numbers are per-repo.
Mirror the GitLab gate from #14381: fall back to the probed
`gitRemoteIdentity.canonicalKey` before giving up, comparing host and owner/repo
after normalizing port, `www.`, and case. An `upstream`-derived identity stays
`'unknown'` because `deriveGitRemoteIdentity` ranks `upstream` above `origin`, so
a fork's own origin is invisible and rejecting would drop URLs from the fork the
user actually checked out.
The canonicalKey compare runs after the displayName branch: displayName is
compared host-agnostically, so mirrors and host aliases of the same owner/repo
keep matching as they do today, and the probed remote only fills in where no
name evidence exists.
Refs STA-4237
* fix(workspaces): keep SSH host aliases matching in the palette identity gate
`git remote -v` reports ssh.github.com, www., and ~/.ssh/config `Host` aliases
verbatim, so comparing a probed canonicalKey against a pasted URL host rejected
legitimate GitHub/GitLab remotes. Normalize the alias hosts both sides can fold
offline, and downgrade a host-only mismatch to 'unknown' when the probed host is
dotless (an unexpandable OpenSSH alias); dotted hosts like ghe.example.com still
lose. Lifts the GitHub host normalizer into shared instead of a third copy.
* fix(repos): keep the www host fold out of the derived project identity
getProjectIdentityKey feeds the persisted Project id, so folding www. there
re-keyed existing projects on upgrade and dropped localWindowsRuntimePreference.
Restrict the fold to the palette's URL-vs-remote comparison, and pin the derived
id for a www. remote so it cannot drift silently again.
* refactor(shared): split shared/types.ts into per-domain type modules (#14397)
`src/shared/types.ts` was 3,981 raw lines (2,825 counted, 9.4x the 300-line
budget) behind an `eslint-disable max-lines`, and is imported by 2,092 files —
the single widest contract surface in the repo.
Move all 320 top-level declarations into 46 per-domain modules
(`repo-types.ts`, `worktree-types.ts`, `github-pr-types.ts`, ...) and reduce
`types.ts` to an explicit re-export barrel, so the 2,092 import sites are
untouched.
`HostSettingOverrides` moves into the pre-existing `host-setting-overrides.ts`
alongside the accessors that operate on it, which also removes that module's
circular import back into `types.ts`.
Named re-exports only, never `export type *`: with star re-exports a name
exported by two modules is silently dropped, which would surface as a confusing
"has no exported member" at a random call site.
Verified lossless mechanically, not by inspection:
- export parity — the module's resolved export set through the TS checker is
identical before and after (396 names, no additions, no removals)
- declaration parity — all 320 declarations compare character-identical modulo
comments and whitespace, so no optionality, union order, or generic
parameter drifted
- `tsc --noEmit` green on the node, cli, and web projects
- `oxfmt --write` is byte-identical, so the barrel is format-stable
Drops the `max-lines` bypass and its baseline entry (ratchet 346 -> 345).
* refactor(shared): group worktree, github, and linear modules into folders (#14437)
`src/shared` is a flat directory of ~1,150 entries. The worktree, github, and
linear domains accounted for 71 of them, so finding the module you wanted meant
scanning a wall of same-prefixed filenames.
Move each domain into its own folder and drop the now-redundant prefix:
src/shared/github-pr-types.ts -> src/shared/github/pull-request-types.ts
src/shared/worktree-id.ts -> src/shared/worktree/id.ts
src/shared/linear-links.ts -> src/shared/linear/links.ts
This follows the existing `network/` and `new-workspace/` convention in the
same directory, which also drop the prefix inside the folder.
Whole clusters move, including tests. Foldering only part of a domain would be
worse than flat: a reader would have to check both `github/` and the flat
directory, and `github-auth-types.ts` / `github-project-types.ts` are type
modules that belong with the rest. No files with these prefixes remain flat.
Import specifiers were rewritten by resolving each one to an absolute path and
recomputing it, not by string substitution, so the `@/../../shared/...` alias
forms are handled correctly. 501 specifiers across 298 files.
Two things `tsc` cannot catch, handled explicitly:
- `github-project-types.ts` carries its own `max-lines` bypass, so its baseline
entry is REPOINTED to the new path rather than pruned. Pruning would drop the
bypass and then flag the new path as a fresh violation. Ratchet stays at 345.
- `mobile/` is outside `pnpm typecheck` and cannot be typechecked here
(`mobile/node_modules` is empty). Instead every relative specifier in the repo
was resolved against the filesystem: 174 unresolved before this change and 174
after — identical, so nothing broke in mobile either.
The pinned `tests/e2e/.cross-version-checkouts` fixtures are deliberately NOT
rewritten; they are a snapshot of an older release and still reference the old
paths.
Verified: cold `tsc --noEmit` green on node, cli, and web (buildinfo deleted
first — these projects are `composite: true` and reuse stale caches).
* refactor(preload): split the preload contract into per-domain api modules (#14403)
`src/preload/api-types.ts` was 3,752 raw lines (3,533 counted, 11.8x the
300-line budget) behind an `eslint-disable max-lines`. Almost all of it was a
single `PreloadApi` object type whose ~83 namespace properties were declared
inline, so any IPC surface change meant editing one 2,600-line type.
Give each namespace a named type in its own module under `src/preload/api/`
(`pty-api.ts`, `filesystem-api.ts`, `github-pull-request-api.ts`, ...) and
recompose `PreloadApi` from those names. `api-types.ts` keeps the `declare
global` Window augmentation and re-exports every moved name, so all 52 import
sites are untouched.
Two shapes needed care to stay type-identical rather than merely compatible:
- Three keys (`gh`, `git`, `ui`) are composed from two modules each. A plain
intersection is NOT identical to the original flat object literal, so those
use a `Merged<T>` mapped type; a negative control confirmed that dropping it
fails the parity assertion.
- Keys whose module groups several namespaces use indexed access
(`fs: FilesystemApi['fs']`) to preserve exact identity and source order.
`config/tsconfig.web.json` and `tsconfig.tc.web.json` enumerate files by path,
so they need `src/preload/api/**/*` alongside the existing `api-types.ts` seed
or the web projects fail TS6307.
Verified by exact type identity, not assignability: 41 assertions of the form
`Equals<Now.X, Before.X>` against a frozen pre-split snapshot, covering every
exported name, plus a per-key pass over all 83 `PreloadApi` keys. All three
projects typecheck clean with those assertions active.
Verification note: these tsconfigs are `composite: true`, and `tsc --noEmit`
will reuse a stale `.tsbuildinfo` and report clean for a state that genuinely
fails. Every result above was produced after deleting the buildinfo, including
a negative control confirming the gate still fails on deliberate drift.
Drops the `max-lines` bypass and its baseline entry (ratchet 346 -> 345).
* fix(stats): wrap usage breakdown model names (#14065)
* fix(test): deflake relay exec env, project boundary, and speech resume tests (#14446)
Three test-suite problems, all root-caused in the tests rather than in
production behavior.
1. src/relay/agent-exec-handler.test.ts (real failure, not a flake)
The two spawn-argument assertions failed with "Number of calls: 1" — spawn
ran, but the env differed. Cause: both assert
`expect.objectContaining({ ...process.env, ... })`, which demands that every
ambient variable reach the child verbatim. #7986 (1a6abc87d11) changed both
sides at once: it rewrote the assertion from `env: process.env` to that
objectContaining form, and in the same commit made the handler apply
`applyTerminalGitCredentialPromptGuard`, which appends its own entries to
Git's indexed-config protocol (GIT_CONFIG_COUNT / KEY_n / VALUE_n).
So whenever the test runner's own environment already carries that protocol —
exactly what Orca exports into its agent terminals — the snapshot expects
GIT_CONFIG_COUNT=2 while the correctly guarded child gets 4. The test passes
on a bare CI shell and fails when run from a guarded terminal.
The implementation is right: appending the guard after the caller's config is
the documented contract, and "guards wrapped agents after atomically replacing
inherited indexed config" already covers it. Fixed the test instead, by
clearing the guard-owned keys (GIT_CONFIG_* protocol and WSLENV) from the
ambient env for the duration of the suite and restoring them afterwards, so
the passthrough baseline is deterministic. No assertion was weakened or
removed.
2. project-view-wrapper-source-context-boundary.test.ts (flake: 30s timeout)
`buildProjectWorkItem` is a pure function, but it lived in
ProjectViewWrapper.tsx, so importing it pulled in the store, sonner, lucide,
and the whole UI kit — ~8.8s of transform and module evaluation for one
assertion, which tipped past the 30s limit under parallel load.
Extracted it to project-work-item.ts (its only dependency is
githubProjectHost) and pointed the test there. Both test cases are unchanged.
Also dropped the now-unneeded happy-dom environment, since nothing in the file
touches the DOM any more. 9.15s -> 0.12s.
3. model-manager-download-resume.test.ts (flake: 30s timeout)
"bounds a server that advances by pathologically tiny segments forever"
drives the loop to the MAX_TOTAL_DOWNLOAD_REQUESTS ceiling of 4096. Each
iteration did a real writeFileSync plus two statSync calls through
getPartialDownloadBytes — ~12k synchronous filesystem syscalls in a tight
loop. Fast on an idle disk, but it serializes against every other vitest
worker on a loaded machine, which is what blew the per-test timeout.
Stubbed getPartialDownloadBytes to read the byte counter the test already
maintains, so the loop is pure CPU. The file was only ever a stand-in for that
counter. Ceiling and rejection assertions are unchanged: 332ms -> 15ms.
The two remaining ~1.1s cases in that file spend their time in the real 1s
retry backoff around real stream and file-write plumbing; they are left on
real timers because faking them would mean faking the transport too, and 1.1s
leaves ample headroom.
* Revert "Center newly opened tabs at end, keep close controls visible" (#14450)
* fix(native-chat): keep caller abort ahead of WSL gate refusal (#14445)
Why: a hook-path or scan refusal that races the caller's abort was
converted into a WSL unavailability error, so cancellation looked like
a stalled distro.
* refactor(store): unify the duplicated catalog equality and identity-key helpers (#13804)
* refactor(store): unify the catalog structural-equality walks
Three near-identical structural deep-equality walks had landed independently in
the same window: areValuesEqual (#13744, repo-identity-reconcile.ts),
areCatalogEntriesEqual (#13770, repos.ts — already folded into the first on this
branch's base) and catalogValuesEqual (#13662,
worktree-catalog-reconciliation.ts). All three walk plain records and arrays and
fall back to reference equality for anything exotic.
They are not interchangeable. Two axes genuinely differ, and each caller depends
on its own side:
- Own-key set. #13744/#13770 require equal own-key counts plus hasOwnProperty,
so an absent key differs from a key present and holding `undefined`. #13662
compares the union of both sides' keys, so those are equal. The strict side is
load-bearing: the repo/project merges branch on
`'localWindowsRuntimePreference' in project` (repos-project-runtime.test.ts
"clears stale local runtime preferences"), and projects are now reconciled
with this comparator. The loose side is test-pinned by
worktree-catalog-reconciliation.test.ts "reuses rows with equivalent nested
catalog data", where a locally built row carries `optional: undefined` that
the host omits.
- Leaf comparison. #13744/#13770 use `===` (NaN never equal, 0 equals -0);
#13662 uses `Object.is` (the reverse).
So instead of picking a winner, src/shared/structural-value-equality.ts holds
one walk parameterised by those two axes and exports the two policies as
`structuralValuesEqual` and `structuralValuesEqualIgnoringUndefined`. Every
caller keeps its exact current semantics; the ~40 duplicated lines and the
silent divergence go away. src/shared/persisted-ui-equality.ts (a fourth copy
with a Set branch and no plain-object guard) is deliberately left alone: it
gates a disk write in main with no direct test coverage.
Also folded, all provably behaviour-identical:
- The `${hostId}\0${repoId}` composite key had three copies
(getRepoHostIdentityForParts, repoOwnerKey, getEntryKey) that must agree or
repos silently stop reconciling. Moved to src/shared/repo-host-identity.ts
because one of them lives in src/shared; the renderer module re-exports it.
- mergeFetchedReposForHost's hand-inlined upsert loop now calls mergeByIdentity.
mergeByIdentity additionally skips replacing a structurally equal row, which
cannot change the result here: reconcileFetchedRepos runs immediately after
over the same identities in the same order and restores exactly those rows.
- Renamed repos.ts's `catalogRowsUnchanged` to `arrayElementsUnchanged`. It is a
pure element-identity compare, two files away from
`catalogRowsEqual`, which is a full structural compare.
src/shared/structural-value-equality.test.ts pins both policies over arrays,
nested records, null-prototype records, absent-vs-undefined keys, symbol keys,
and non-plain objects (Date/Map/Set/class) falling back to reference equality.
* fix(store): keep merged sourceRepoIds order host-independent
Prefixing the cross-host remainder made a cross-host project's sourceRepoIds
order a function of the refreshing host, so the projects reconcile never reused
the row. Also pins the repo-derived host-id contribution the new per-project
slice feeds the host-id resolvers.
Co-authored-by: Orca <[email protected]>
* refactor(store): migrate call sites that landed after this branch
github.ts and ai-vault-session-identity.ts began using areValuesEqual on main
while this branch was stale, and repo-identity-reconcile's record reconciler
still called its own deleted walker. All three now use structuralValuesEqual;
reuseEqualCatalogRows keeps its duplicate-id cap and calls the ignoring-undefined
variant, which is the key-union semantics catalogValuesEqual had.
---------
Co-authored-by: Orca <[email protected]>
* fix(worktree-scan): keep the admin-fingerprint probe inside the caller's per-repo budget (#14454)
* fix(worktree-scan): keep the admin-fingerprint wait inside the caller's per-repo budget
The awaited probe was capped at 10s while `computeResolvedWorktrees` gives each repo
5s, so a slow mount always blew the budget: the caller gave up and republished
persisted rows. The resolved snapshot was then stamped from the *start* of the
compute, so a compute longer than its 1s TTL published an already-expired entry and
the next poll repeated the whole 5s wait — deterministically, on every TTL expiry.
Cap the probe at 2s so the remaining budget still covers the fallback
`git worktree list`, and stamp the snapshot on completion.
* fix(worktree-scan): derive the probe deadline from the caller budget
A flat 2s cut reuse for hosts whose probe lands between 2s and 5s, which used to fit
the caller's budget — trading the stall for a repeating `git worktree list`. Subtract
a fallback-scan allowance from RESOLVED_WORKTREE_REPO_TIMEOUT_MS instead, so the
invariant holds by construction and only probes that could not have fitted are cut.
Tests now pin both ends: too large fails the budget invariant, too small fails reuse
for a slow-but-healthy probe.
* Require an absolute Orca CLI for the agent-teams tmux shim (#14438)
The generated tmux shim fell back to a bare orca / orca.cmd / orca-ide, and cmd.exe resolves an unqualified command against the current directory before PATH (sh does the same via ./empty PATH entries), so a stray orca.cmd in an agent's checkout could run with the agent-teams team id and token in its environment.
Resolve only absolute paths, honor the Windows Path env spelling, degrade to in-process teammates when no CLI can be qualified, and make both shims exit 127 instead of guessing. Verified on macOS, Linux (dash + bash), and Windows (cmd.exe + Git Bash).
Fixes STA-4215.
* fix(browser): acknowledge paired tab before navigation (#14402)
* refactor(shared): drop the shared/types barrel and import from the real modules (#14447)
#14397 split `shared/types.ts` into 46 per-domain modules but kept the path as
a re-export barrel so the import sites did not have to change. This removes
the barrel: every consumer now imports from the module that actually declares
the type, and `src/shared/types.ts` is deleted.
Barrels hide where a type lives, make every consumer look like it depends on
the whole domain, and let an unrelated edit invalidate a module that ~2,000
files transitively import.
2,323 import declarations across 2,321 files. Rewritten mechanically: each
specifier was resolved to an absolute path via the TypeScript AST and
recomputed, rather than string-substituted, so alias forms (`@/../../shared/
types`) and per-specifier `type` modifiers survive.
Four cases the mechanical pass had to handle, each found by a gate rather than
by reading the diff:
- Modules inside `src/shared` import the barrel as `./types`, not
`shared/types`. A pre-filter on the latter string skipped 176 of them and
left imports dangling at a deleted file, which surfaced as confusing
`Property 'x' is optional in type 'Repo' but required in Pick<Repo, ...>`
errors rather than "module not found".
- The barrel RENAMED one type on the way through
(`WorkspaceSource as WorkspaceCreateTelemetrySource`), so the original name
in the owning module has to be re-aliased at each consumer.
- Three test files put `;(globalThis as ...)` on the line after the import.
TypeScript parses that `;` as the import statement's terminator, so
replacing through `statement.getEnd()` deletes it and breaks ASI. The
rewrite now stops at the module specifier.
- A file that already imported directly from a module got a SECOND import
from it, because the barrel re-exported those same names — which trips
`import/no-duplicates` under `--deny-warnings`. A post-pass merges
declarations sharing a specifier and type-only-ness; the `import type` plus
`import` pair from one module is left alone, since that form is allowed.
Splitting one barrel import into several genuinely adds lines, which pushed
`terminal-layout-pty-ownership.ts` t…
…port its sessions (stablyai#13928) * fix(daemon): stop killing a wedged daemon that still owns live agent PTYs A daemon too busy to answer listSessions was indistinguishable from a dead one: getAliveDaemonSessionCount() returns null ("could not verify"), the preserve gate required `!== null && > 0`, so the run fell through to killStaleDaemon() and every running coding agent died with it. The sibling replace branches all preserve on null; this one alone collapsed "can't tell" into "empty", which src/main/daemon/AGENTS.md already forbids. Give the decision an out-of-band second opinion. inspectDaemonPtyOwnership() reads the OS process table — never the daemon socket, which is exactly what failed — and reports whether the daemon's own process still has live PTY descendants. Under preserveWhenOwningLivePtys, that evidence vetoes the signal and the launcher adopts the daemon in degraded mode instead. The veto is opt-in so it cannot make a daemon unkillable: only the failed_health_check path enables it. Manage Sessions -> Restart still kills. Only positive evidence preserves, so a wedged daemon with nothing to lose is still replaced (#8689). Also stop replacing silently: the verdict now prints on the post-kill truth, which stays quiet on a cold start because nothing was killed. Co-authored-by: Orca <[email protected]> * fix(daemon): survive preserving a daemon too wedged to be adopted Adversarial review found the veto's own success path could not complete against the daemon it exists to protect. Preserving routed through holdDaemonAdoptionLease(), which opens a hello — the exact operation a wedged daemon cannot answer — so it threw, aborted initDaemonPtyProvider, and left no spawner. restartDaemon() throws without one, so the user lost the documented Manage Sessions -> Restart remedy on top of having no daemon: strictly worse than the data loss being fixed. A still-listening endpoint means wedged, not gone, so keep a lease-free handle instead. The lease only cancels the adoption watchdog, which never fires on a daemon that owns sessions. Degraded mode likewise tolerates a lease and a session discovery it cannot complete. Three more from the same review: - The veto keyed on reason === 'failed_health_check', but a daemon that answered listSessions with 0 lands in that same branch and must stay replaceable. Key on liveSessionCount === null, which is what the option actually documents. - Zombies are not evidence of live work. A wedged daemon cannot reap, so its exited agents linger as <defunct> and would read as "still running" — a false positive correlated with the wedge itself. Enumerate through the process table's stat column and exclude them; sample twice so a resolver probe or health-check shell cannot masquerade as an agent. - Restore the "did anything answer?" log guard alongside the confirmed kill, so a daemon that self-retires before the kill is still announced. Co-authored-by: Orca <[email protected]> * test(daemon): kill the mutations that let the PTY veto ship as a no-op Mutation testing found four survivors — changes that break the fix while every test stays green: - Swapping the POSIX reader to the 500ms-cached one passed. It is not just a staleness hazard: inside the TTL both sampling attempts receive the same array, collapsing the two-sample confirmation to one. Pin the fresh reader. - Replacing killStaleDaemon's default inspector with one that never reports live PTYs — the veto disabled in production — passed, because every veto test injects the hook. Exercise the real seam. - Adding the veto to cleanupDaemonForProtocol passed, which is verbatim the failure its own doc warns about: a user-initiated restart of a daemon owning live PTYs would refuse, then throw. Pin that call's arity. - The ppid-cycle fixture put the cycle outside the daemon's subtree, so the walk never entered it and deleting the visited guard passed. Also bound the Windows enumeration, which had no budget of its own: two CIM queries with a wmic fallback can stall the launch path for tens of seconds. Blind is a safe answer there; hanging is not. Co-authored-by: Orca <[email protected]> * fix(daemon): require session-leader evidence and stop preserving daemons that can never be adopted Round-three review found the veto too eager in three ways, each of which traded the original data loss for a whole-session degrade or a permanently daemon-less app. Evidence was "any non-zombie descendant", justified by re-sampling to weed out transients. The two samples are taken back to back — one ps fork apart — so nothing transient is ever weeded out, and a hung helper (often the very reason the daemon is wedged) reads as an agent. Use the structural signal instead: a PTY child is a session leader, because forkpty calls setsid, and no helper the daemon forks ever is. Re-sampling now only retries blindness. A 'rejected' daemon answered and refused the handshake, so it can never be adopted; preserving it repeated the same failed adoption on every launch, forever. And the veto read the process table, not the socket, so it could fire on a daemon whose endpoint was already gone — adoption then threw, init aborted, and the app was left with no spawner and no working Restart. Gate on both: only preserve what could still be reached. Also: releasing the launcher's temporary lease after the permanent lease failed reopened the adoption gap that ordering exists to close, and the tolerance added to discoverDaemonSessions was dead code — nothing on that path rejects. Co-authored-by: Orca <[email protected]> * refactor(daemon): decide occupancy before the kill, not inside it Three review rounds each found a new failure state in the previous shape, which was the design telling us something. The safety rule — never destroy running work — was replicated across the launcher's branches instead of being decided once, and the last round added it to one more branch behind a boolean. Policy had been put inside a mechanism: killStaleDaemon grew an input flag to disable its new veto, an output back-channel to report it, and a caller-side re-derivation of the classification the flag had lost. One structural error, one symptom per layer it crossed. Name the question instead. resolveDaemonOccupancy answers occupied | empty | unknown, asking the daemon first (authoritative both ways) and falling back to the process table only to RAISE the answer to occupied. OS evidence can prove work exists; it can never prove absence, so it never licenses a kill. The launcher now decides before it destroys anything, so killStaleDaemon goes back to being only "make this pid go away" — no options, nothing for a future caller to forget to disable, and Manage Sessions -> Restart cannot be vetoed because there is no veto left to hit. Holding is a real outcome now. A daemon that owns live terminals but cannot answer a handshake gets mode 'held': no adoption attempt, no lease, no fork beside it. That deletes the lease-free-handle fallback, the try/catch around preserve, and the tolerated-lease branch in init that existed only because the correct outcome had no representation. Two defects this removes outright: - The endpoint check used a local boolean probe that returns false on timeout, so under load — and unconditionally on Windows named pipes, where a busy server answers ERROR_PIPE_BUSY — the guard disabled itself in exactly the conditions it was written for. Use the canonical three-valued probe, whose own docs say absence of proof is not proof of death. - A daemon that answered and refused the handshake was killed with its agents. It is now held like any other occupied daemon. Also folds the replacement verdict onto pendingReplacement, retiring a pair of mutable launcher locals whose only job was moving one warning past the kill. Co-authored-by: Orca <[email protected]> * fix(daemon): make the occupancy residual total The module's contract is that 'unknown' is where every unanswerable question lands, but a throwing dependency escaped instead — routing a failed observation into the launch path rather than onto the safe residual. Latent today because both real implementations swallow their own failures, which is exactly the kind of thing that stops being true during a refactor. Co-authored-by: Orca <[email protected]> * fix(daemon): stop counting the daemon's own probe PTYs as hosted work Round-four review found the evidence proving the wrong thing. The filter excluded the daemon's plain subprocesses on the grounds that only a PTY child is a session leader — but the daemon opens PTYs for its own health probe and conpty warmup, and forkpty makes those session leaders too. The comment's own premise refuted its exclusion list. A daemon hosting zero user terminals could be held on the strength of its stuck probe child, and since the held daemon also had no sessions, dropping our authenticated pair let it retire and take the very state we were protecting. Exclude them by exact command, on both platforms. Two more from the same review: - pty-spawn-unhealthy is only reachable after a successful hello, so that daemon is adoptable. It was routed to 'held' — which never adopts — purely because the count had come from the process table. Check it first; hold now requires an unreachable daemon. - The grace loop rescanned the process table every pass, though it is waiting for IPC and the table cannot change its answer in five seconds. Ask the daemon during the wait and read the table once, after. raiseOccupancy- WithProcessEvidence makes that split explicit, and can only ever raise. Bound the wait by wall clock too: the retry count alone never bounded it, and startup fails open at 60s by abandoning the daemon provider outright, which would trade a wedged daemon for no daemon and a Restart that throws. Co-authored-by: Orca <[email protected]> * fix(daemon): hold a hello-rejected daemon instead of adopting one that refused us Found while reviewing why a mutation looked equivalent. Gating the hold on health === 'unreachable' left 'rejected' — a daemon that answered and refused the handshake — falling through to preserveDaemon(), whose adoption opens the very hello it just refused. That throws, and the throw costs the app its daemon and its Restart remedy. Killing it instead is no better: it can still be hosting running agents. Neither of those daemons can complete a handshake, so neither may be adopted, and both must be held. Gate on that rather than on one of its two causes. Adds regression tests for the round-four fixes: the self-spawned probe exclusion is exact-match on both platforms, an adoptable pty-spawn-unhealthy daemon is never routed to a mode that cannot adopt, evidence can only raise a verdict, and the grace budget stays under the startup fail-open cap. Co-authored-by: Orca <[email protected]> * fix(daemon): decide adoptability from what the daemon can do now, in one place Round five found the same question — can this daemon complete a hello right now? — answered in three places with three different conclusions, because 'held' had been added as a fifth branch rather than as the classification the other branches route through. Two of those answers were wrong, and both ended in no daemon at all, which is the outcome 'held' exists to prevent. - A daemon whose adoption hello had just failed was handed back tagged 'degraded-new-pty-fallback'. Init skips the lease only for 'held', so it reopened the same connection, threw, and aborted startup — leaving the agents alive but unreachable and Manage Sessions -> Restart throwing. - The pty-spawn-unhealthy arm ran first and claimed a successful hello proved adoptability, but that reading is from before the grace window. A daemon that answered at t=0 and went silent through thirty seconds of retries took that arm and threw the same way. Ask whether it is answering now, first. The budget was a comment with a Date.now() beside it: one occupancy probe could cost 50s, because the client's default is a 5s hello per connection step plus a 30s request timeout. Bound the probe explicitly, start the clock before the first one, and size the window so the whole path — health check, pid verification, loop overshoot and process-table read — fits under the startup fail-open with room to spare. Also folds the four sibling branches onto the same occupancy resolution. getAliveDaemonSessionCount was byte-identical to countLiveSessionsOverIpc, so one concept had two implementations and only one of them had been fixed. The Windows probe exclusions could never match: the warmup spawns COMSPEC, an absolute path, against an exact-equality test on 'cmd.exe /c exit'. Compare the program by basename and keep the argv tail exact. Co-authored-by: Orca <[email protected]> * fix(daemon): stop the local fallback answering for sessions it does not own Closing a held daemon's pane reported success while the agent kept running. Unrouted ids resolve to the in-process fallback, whose shutdown returns silently for an id it has never heard of and whose write and resize are no-ops — and while a daemon is held nothing ever enumerates its sessions, so every one of them is unrouted. The pane vanished, the orphan outlived the app, and typing into a stuck terminal disappeared without a word. Only attach was fenced against that route. Extend the same rule to the operations that change or feed a session: route to the fallback only when it genuinely owns the pty, and otherwise say the session cannot be reached. The error type is load-bearing. pty:kill treats "Session not found" as proof the pty is already gone and synthesizes an exit, so reusing that error would have reproduced the lie one layer down. TerminalSessionOwnerUnverifiedError means "still there, we cannot reach its host", which is reported as a failed close and keeps ownership for a retry. Co-authored-by: Orca <[email protected]> * test(daemon): pin that a held session cannot be closed by a provider that never had it Covers the held-daemon routing fence, including the coupling that is invisible from the routing file: the thrown error must not match pty:kill's already-gone predicate, or the close is swallowed into a synthesized exit and the orphan is hidden again. A rename would otherwise reintroduce the bug silently. Co-authored-by: Orca <[email protected]> * fix(daemon): bound the POSIX evidence read and re-verify the pid it describes Round-six follow-ups, none destructive. The process-table read had a deadline on Windows but not on POSIX, where the shared reader's ps timeout does not cover queueing behind an in-flight scan — so the one step that runs after the grace window could still outlast it. The pid handed to that read was verified before the grace window, which is long enough for the daemon to die and its pid to be recycled onto a shell with children. Verify it where it is used instead, and only when there is still something to raise: the common case now skips the identity probe altogether, which also takes a few seconds off the worst-case launch. Two renderer call sites killed PTYs without handling rejection. That was harmless while an unreachable session was answered by a silent no-op; now that it honestly rejects, pane teardown and repo removal would log an unhandled rejection every time — exactly when the daemon is already sick. Deliberately not taken from that review: giving the endpoint-occupied catch the same held fallback as the failed-health path. That path arrives with occupancy unknown or empty, so holding there would swallow a real launch failure to protect nothing. Splits the repro script, which had grown past the line limit, into the sequence it proves and the two things it proves it with: process-table inspection, and the static assertions on the launcher's hold decision. Co-authored-by: Orca <[email protected]> * test(daemon): hold the classification budget to the whole path, not one term The previous assertion compared the grace window to the fail-open cap, which passed while the real path ran to roughly twice the cap — a single probe cost 50s against a 5s assumption, and the terms on either side of the loop were never counted at all. Sum the declared budgets instead: health check, grace window, the one probe that always runs past a ceiling tested at loop entry, and the evidence read on both platforms. Raising any of them now has to face this, and the spare time the kill ladder and fork still need afterwards is stated rather than assumed. Lives outside the launcher's own spec because that file mocks daemon-health, which would shadow the constants being held to account. Co-authored-by: Orca <[email protected]> * fix(daemon): do not read a stranded login wrapper as a hosted terminal Raised by a colleague's handoff on the same-day reports. macOS wraps every terminal in /usr/bin/login for TCC attribution, and #13764 shows the wrapper can outlive the shell it wrapped — leaving a session leader that hosts nothing. One affected host had accumulated enough of them to reach swap pressure. That is exactly the evidence this change treats as proof of live work, so a daemon whose sessions had all ended would have been held indefinitely on the strength of the corpses, on precisely the hosts where the problem is worst. Same class as the daemon's own probe PTYs: a session leader is necessary evidence, not sufficient. A wrapper still doing its job has the shell it exec'd beneath it. Co-authored-by: Orca <[email protected]> * test(daemon): pin the daemon's PTY spawn sites so the exclusion list cannot silently rot The ownership evidence discounts the PTYs the daemon opens for itself, and that list is only safe while it is complete — a self-spawned PTY nobody excluded reads as user work and holds a daemon that owns nothing. The list grew one reviewer at a time, which is the wrong mechanism for a correctness invariant. Pin the input rather than the list. The daemon has exactly three PTY spawn sites: the user's terminal, the spawn health probe, and the Windows conpty warmup. A fourth now fails this test until someone decides which side it belongs on. Co-authored-by: Orca <[email protected]> * fix(daemon): stop the evidence going blind on the host it exists to protect Readiness review, section 04. Every agent pane already drives the shared process-table reader on its own cadence, so the uncached read queues behind them — and the host with the most agents to lose is the one likeliest to blow the deadline on queueing alone. Both attempts return unknown and the daemon is killed anyway, which is the original bug wearing the fix as a costume. Fall back to the TTL-cached table, which on that host is always warm for exactly the reason the uncached read is always queued. A table a few hundred milliseconds old still answers whether this daemon has children, and the failure directions are not symmetric: over-holding costs one degraded launch that self-heals, under-counting ends running agents. The same review found the launch budget still overran the 60s startup fail-open — by ~7s on Windows — and that the test guarding it under-counted the path it was written to bound, for the second time. It omitted the identity probe before the evidence read and the endpoint check that ends the grace loop. Both are now summed, the headroom requirement covers the kill ladder and fork that follow a replace verdict, and the grace window and Windows probe deadline are sized to fit. Not taken from that review: reusing the verified pid inside killStaleDaemon to drop the duplicate probe. That second verification is what fences the signal to this incarnation, and a seconds-old result is exactly the pid-reuse hazard it exists to prevent. Co-authored-by: Orca <[email protected]> * fix(daemon): confirm emptiness before it authorizes a kill Readiness review, sections 02/03/05/06 — no P0 or P1 in any of them. These are the P2s worth taking. The important one: on macOS a terminal contributes exactly one session leader, the login wrapper, because the shell it forks is in the same session and shows S+ rather than Ss. I had assumed the shell counted too. It does not — so a wrapper that looks childless in a single snapshot makes its whole terminal invisible, and that snapshot cannot tell a wrapper whose shell has gone from one whose shell has not yet appeared. Emptiness is the answer that authorizes a kill, so it now costs a second read; 'owns-live-ptys' still needs none. The fixtures said Ss where a real shell says S+, which is why the tests never noticed. Also from that review: a fabricated row was cast to ProcessTableRow to reuse a command-only predicate, which is sound only while that predicate reads nothing else — narrowed to Pick<'command'> so the compiler keeps it honest. The pty:signal listener relied on its provider staying async to convert a routing refusal into a rejection; it is an ipcMain.on listener with nothing above it, so it now catches synchronously too. And the repro's teardown signalled remembered pids a minute after phase 1 waited for them to die — re-verify by tag first, since signalling a recycled pid is the mistake the script exists to study. Co-authored-by: Orca <[email protected]> * fix(daemon): stop guessing at Windows occupancy instead of guessing better The readiness review found the Windows branch reading a wedged daemon's orphaned conpty hosts as live terminals. ClosePseudoConsole only runs on the daemon's own JS thread, so a daemon too wedged to answer is also too wedged to reap them, and they accumulate exactly when this code runs. A wedged, empty Windows daemon would then be held forever — #8689 re-opened, and a regression from main rather than a missing protection. The tempting fix is another exclusion. That would be the sixth revision to what counts as a live PTY, each one added because a reviewer found something that looks like a session and is not, and each one trading safety for availability in a fix whose entire purpose is the opposite trade. The list is the problem. POSIX has a real signal: forkpty makes a hosted terminal a session leader, which nothing the daemon forks for itself ever is. Windows has no equivalent, so its branch could only ever count descendants and subtract guesses. Delete it and answer 'unknown' — Windows keeps exactly the behaviour it has on main, and the protection is claimed only where it can be justified. Also stops a blind confirming read from upgrading an unconfirmed emptiness into a verdict. Emptiness is what authorizes a kill; a read that saw nothing corroborates nothing. Co-authored-by: Orca <[email protected]> * refactor(daemon): clear the debris the Windows removal left behind Behaviour-preserving. Windows now abstains once at the entry point rather than twice inside a retry loop that had nothing to retry, which also retires the platform check further down that could no longer be false. The self-spawn matcher kept backslash splitting and .exe stripping for a branch that no longer exists, and the launcher's grace loop repeated its own IPC call and stacked two explanations above the wrong statement. Co-authored-by: Orca <[email protected]> * fix(daemon): stop the budget cut spending Windows' only protection Round seven found the one thing this PR must never do: kill a session that main would have kept. Main's grace loop probed with a non-shared 5s connect budget, so a wedged daemon got roughly a minute to come back. Bounding the probes and adding a wall clock cut that to about twelve seconds — a good trade on POSIX, where a daemon that outlasts the window is still protected by process-table evidence, and a bad one on Windows, which has no such evidence and now has nothing else. A Windows daemon wedged for half a minute while hosting agents was adopted by main and is killed by this branch. The fail-open cannot rescue it either: ensureRunning() is not abortable, so the launcher runs to completion. Size the window per platform instead, against what each actually spends: Windows pays no evidence read and no identity probe to feed one, so it can afford far more grace, and grace is worth more where it is the only thing there. Both numbers come from the budget test rather than taste. Three more from the same review: - The evidence read applied its deadline twice, once to the fresh table and again to the cached fallback, so an attempt could cost double what the launch budget was told. Share one deadline across both. - Two tests described protection the code no longer delivers: one asserted ~60s of grace the wall clock had already retired, the other passed only because its mocked probes are free and would fail against real ones. Say what the code actually promises, and freeze the clock where the point is retry depth. - The self-spawned PTY inventory promised more than it inspects. It sees direct node-pty calls in one directory; the macOS login-session probe reaches a PTY through expect(1) and is caught by the stranded-wrapper filter instead. Scope the claim, since that indirection is the shape the next escape will take. Co-authored-by: Orca <[email protected]> * refactor(daemon): spend the launch budget against a clock instead of a sum Round eight found the fourth term missing from the hand-written budget — the launcher's own adoption connect, which runs before the health check on the non-shared five-second path. The three before it were an identity probe, an endpoint probe, and an evidence deadline applied twice. Every one of them passed the test meant to catch exactly that, because the test could only check the terms someone had remembered to add. So stop summing. The classification now runs against a deadline and stops when it expires, and the test asserts only that the deadline leaves room for the kill ladder and the fork that follow it. A budget that has to be remembered is a budget that will be wrong; this one cannot be, because nothing has to be counted. That also retires the platform-split grace window, which existed to hand Windows more of a sum nobody could total correctly. The same review found the regression it was compensating for was never the window. main gave each probe up to fifty seconds — five per connection step, thirty for the request — where this branch gave eight for both together. A daemon whose handshake needs more than four seconds therefore answered none of the probes, however many it got, and on Windows nothing else can speak for it. Splitting the two budgets fixes the case the window never could: connecting stays tight, because a daemon that cannot handshake is wedged and worth re-asking cheaply, while a daemon that did handshake is demonstrably alive and its count is worth waiting for. Also stops a Date.now spy leaking out of a failed test and freezing the clock for the rest of the file. Co-authored-by: Orca <[email protected]> * fix(daemon): make the classification clock actually bound the work it names The clock introduced in the previous commit gated the probes but not the two steps after them. The identity re-check and the process-table read ran on their own deadlines, outside the ceiling, so the launcher could still spend its whole budget on probes and then take another ten seconds — the same overrun the sum used to produce, arrived at from the other end. Hold that time back from every probe instead. A probe is only started when the clock can still fund a handshake after the reserve, and its budget is what remains minus the reserve, so no probe can eat it however long the daemon takes to answer. Worst case is now the ceiling by construction rather than by addition. The reserve has a test asserting it is large enough for what it covers, which failed on its first run and caught that ten seconds was not. Co-authored-by: Orca <[email protected]> * fix(daemon): ask the wedged daemon a question it can actually answer Round nine found the re-verification was stricter than the check that triaged the daemon onto this path. The launcher gets here because a three-second health check — one socket, one hello — timed out. It then re-asked with two sockets and two hellos inside four shared seconds, and repeated that identical question up to twelve times. A daemon that consistently needs five seconds fails every one of them, so the retries could only ever agree with the check that sent it here. main re-asked with five seconds per connection step and thirty for the answer, and kept the sessions this branch destroyed. Retries and patience solve different problems. Keep the cheap probes, which catch a daemon that recovers on its own, then spend what is left of the clock on one tolerant ask — the only question that can disagree with the triage. It is skipped when the endpoint is provably gone, since a cold start arrives here too and has nothing to wait for. Two more from the same review. The clock claimed to cover the launcher's own adoption connect and started after it, so the fourth term that went missing from the sum was still uncounted; it now starts above that connect and bounds it. And Windows was holding back twelve seconds for an identity check and a process-table read it never performs — the reserve is zero where the steps it reserves for do not run. Retuned the ceiling to leave the kill ladder and fork real margin rather than half a second, with the packaged-Windows host copy named as what the margin is for. Co-authored-by: Orca <[email protected]> * fix(daemon): ask the tolerant question while the clock can still fund the answer The launcher asked the cheap question first and the patient one last. That is backwards. This path is only reached because a 3s health check timed out, so every 4s probe re-asks on a stricter budget than the one that triaged the daemon here — it can only ever agree. The one ask that could disagree ran last, by which point the clock could fund its handshake but not its answer, and a daemon that answered in 12s was read as dead and replaced along with its agents. Three changes, one idea: never make an ask you cannot afford to hear out. - The patient ask goes first, with every millisecond the answer does not need. - Cheap retries follow it, and stop once the clock cannot fund both halves. Funded to knock but not to listen is not an ask. - The adoption connect is capped. It is not a classification step — it acquires a lease preserveDaemon() re-establishes anyway — but on a daemon that accepts the socket and never completes hello it would spend the entire classification budget, leaving nothing for the probes that protect that daemon's sessions. The test double now forwards the connect budget instead of dropping it, so what the launcher was willing to wait for is observable at all. * fix(daemon): stop three follow-ups rotting where review already found them A truncated paste now says so. A routing throw partway through a paste was not a PtyWriteUnavailableError, so no pty:writeUnavailable reached the renderer and the pane never re-attached — the remaining chunks simply vanished with nothing to attribute the gap to. It stays deliberately distinct from SessionNotFoundError, which isPtyAlreadyGoneError matches and synthesizes into an exit the session never had; a test now pins both directions so neither drifts. The launch-budget spec no longer fails on Windows. The evidence reserve is zero there by design — neither guarded step runs without a session-leader signal — but the assertion demanded eleven seconds of it unconditionally, so `pnpm test` broke on any Windows dev machine. PR CI never saw it: only the WSL boundary spec runs on windows-2022. The identity ceiling it reserves against is imported now instead of being a 3_000 someone would have to remember to change. And the grace-retry comment described the design that preceded the clock: ~5s probes, ~60s of grace, a number worth raising. The clock binds first and usually permits far fewer, so raising it alone buys nothing. * fix(daemon): stop killing a daemon we merely failed to observe Ten review rounds each found a different band where this branch replaced a daemon that origin/main would have kept, and every fix bought a new one. The reason is arithmetic, not carelessness: matching the old tolerance for a single probe costs about 25s, the classification clock has 15s to give, and funding the difference puts startup past the 60s fail-open once the kill ladder and the fork are paid. No assignment of those numbers is safe. So the residual stops being lethal. daemon-occupancy.ts always said it — "'unknown' is the residual, and it is not permission" — while daemon-init.ts fell through from unknown to killStaleDaemon. That fall-through is what made every millisecond of budget a correctness parameter. Now an unclassifiable daemon is held in degraded mode: existing terminals keep working, fresh ones run locally, and being wrong costs a degraded session instead of somebody's agent. Two exclusions, both about never holding something unrecoverable. A proven-dead endpoint is a cold start or a corpse, and holding one would hand every first launch a provider pointed at no daemon. 'rejected' answered and refused, so it can never be adopted and its sessions can never be reattached. The cost is real and deliberate: a wedged-but-empty daemon is no longer replaced at launch, so #8689 degrades to "restart it from Manage Sessions". Which only works if the user knows — and degraded mode was computed, plumbed through preload, and read by nothing. It now renders where the Restart button already lives, and says what it actually costs: new terminals close when you quit, and restarting ends whatever the host is still holding. Rejected on the way here: a background reclassifier (a permanently wedged daemon never answers, and recovery is already handled by degraded-daemon-fresh-spawn- routing.ts), letting accumulated process-table reads license a kill (its errors are systematic, so more samples agree rather than converge), and sidelining the daemon onto a renamed socket (verified working at the syscall level, then abandoned: the daemon's own endpoint-ownership watch reads the moved entry as lost and retires itself, precisely when it recovers). * test(daemon): pin the hold that no longer depends on a clock The repro proved the launcher holds a daemon it can see is occupied. The protection that now matters most is the one for a daemon it cannot see at all, and nothing asserted it. Adds the unknown-hold to the static assertions: that it exists, that it excludes 'rejected' and a proven-dead endpoint, and that every killStaleDaemon call site in the file is downstream of it. Verified by mutation — dropping either exclusion fails the assertion. * fix(daemon): repair what round eleven found, including a fix that did nothing The patient ask was not patient. With twelve seconds reserved for the evidence read, `max(CONNECT, probeBudget - REQUEST)` resolved to exactly CONNECT — the tolerant ask got the cheap ask's four seconds, and the grace loop's gate needed 19s of a budget that only ever held 11s, so it never ran at all. Both shipped green because mocked probes consume no wall clock, so the budget never binds in a test. Two arithmetic tests now compute against realistic elapsed time, which is where the defect actually lived. The reservation was backwards anyway. Evidence can only raise 'unknown' to an uncounted 'occupied', and both now hold the daemon, so the read changes a log line and nothing else — while starving the one probe whose counted answer still reaches preserveDaemon() and full daemon mode. It is opportunistic now: if the probes spent the clock, it is skipped and the verdict stays 'unknown', which holds exactly as an evidence-raised 'occupied' would have. Recovery was a one-way flip on a two-way condition. Once a health check promoted fresh spawns back to the daemon, nothing ever demoted them, so a daemon that wedged again cost a hello timeout plus a full launcher re-classification for every new terminal, for the rest of the session. A failed spawn now routes back and re-arms the cooldown. The class had no tests at all; it has six. The notice was wrong twice. It claimed terminals already open keep working — in held mode discovery runs over the same IPC the daemon is failing, so its sessions are never routed and attach refuses rather than answering on its behalf. They are running, but unreachable. And it named half the cost of Restart: runRestartDaemon shuts down the local fallback sessions too, so the terminals it had just called safe die as well. Also fixed: the amber-on-amber body text failed AA at 3.94:1, the keys were in a namespace no sibling uses, and the scale did not match the notice it renders beside. The banner armed a destructive button with state that never refreshed. It now refetches on focus, like the sibling notice that solved this first. Also: the launch mode type in the test harness omitted 'held', so no test could describe the launch the hold produces; held mode's routing through the degraded provider was unpinned, and deleting it left every test green; and pty:signal kept a try/catch for a synchronous throw that async routing cannot produce. * fix(daemon): stop offering a remedy that cannot work, and say why two modules stay The degraded warning told the user to restart the daemon. When something other than an Orca daemon holds the endpoint, restarting clears nothing: killStaleDaemon only kills a process whose identity matches the pid record, and a foreign holder matches none, so the next launch is identical. The message now says the daemon is unreachable rather than asserting what it owns, and names the second remedy. The notice says "usually clears this" for the same reason. That case is also now written down as a known residual: an endpoint that accepts connections but never speaks the protocol reads as an incumbent on every launch, so it stays degraded with no auto-recovery, where before it was replaced. The rest is comments, because three separate deletion proposals landed on this code in one review cycle and each was a regression. The evidence read is not redundant with the unknown hold: the occupied branch has no proven-dead check and the unknown hold does, so it is the only thing between a kill and a daemon whose socket entry vanished while it still hosts agents. Its children scan is not redundant with pid verification either — a verified-live pid alone would also hold a childless daemon, which is the one #8689 case still safe to replace. And grace retries are worth more since 'unknown' stopped killing, not less: a counted 'occupied' reaches full adoption where the alternative is a degraded hold. Each now says which case dies if it is removed. Reviewers reaching for the delete key three times in a row is the code failing to explain itself, not excess. * docs(daemon): record what a budget raise would owe before it is safe The classification budget serves two verdicts with opposite time-costs. Reaching "don't kill" slowly is free — the daemon survives however long it took. Reaching 'empty' slowly is not, because the kill ladder and the fork still have to fit before the fail-open. At 34s that case cannot arise; at 44s it can, and an overrun there is the worst branch on offer: daemon killed, replacement forked then discarded, no provider installed, Restart broken. So the raise is not a number change, it is a number change plus a guard: hold rather than replace when the headroom left cannot fund the ladder and the fork. Safe precisely because that path has proven the daemon empty, so holding costs no agents. Written down next to the warning against tuning the budget, because the next person to want a bigger number will read that warning and need this one. Also recorded: the launcher closure has no access to the startup abort signal, so the cheap version of that guard is not available without threading it through the spawner. * fix(daemon): delete a retry loop that could never run, at any budget Round twelve proved the loop unreachable by algebra rather than by tracing: remaining = B - E - max(CONNECT, (B - E) - REQUEST) = REQUEST, whenever B - E > CONNECT + REQUEST The patient connect takes every millisecond the answer does not need, so what survives it is always exactly OCCUPANCY_REQUEST_BUDGET_MS — and the gate wanted CONNECT + REQUEST. That holds for every ceiling, which also settles the raise I had been holding open: at 44s the remainder is still exactly the request budget, so ten more seconds of worst-case startup would have funded zero retries. Funding one honestly needs ~71s against a 60s fail-open. So WEDGED_DAEMON_GRACE_RETRIES = 11 documented patience the launcher did not have, and no number could give it. Deleted, with the derivation left where the loop was so the next person does not re-derive it from scratch. Little is lost. A 4s retry cannot reach a daemon needing longer than 4s to answer, which is the entire wedge population, while the one patient ask waits ~12s. The only case retries caught and this does not is a daemon recovering within seconds of being asked — and DegradedDaemonFreshSpawnRouter.recover() already returns it to full daemon service on the next spawn, off the startup clock. The budget tests could not have caught any of this: they recompute the expression from imported constants and never execute the launcher, so collapsing the patient connect back to the cheap constant — the round-eleven defect exactly — left all 1475 green. There is now a test that watches the launcher spend it, verified by mutation, and the arithmetic ones say plainly that they are not the guard. Also corrected: the evidence-read comment claimed the read only affects a log line. It decides the verdict wherever the unknown hold declines to — it has neither the proven-dead check nor the rejected check — so it is what holds a daemon whose socket vanished, and what holds a hello-rejected daemon still hosting agents. * docs(daemon): cost the deferred guard honestly, and say why it is unreachable Two corrections to the note, both of which change what it tells the next person. The reason the guard's case cannot arise at 34s is structural, not a lucky margin: an `empty` verdict means the daemon answered, so it resolved fast by construction, and proven-dead means nothing is listening, so the probe and the ladder both short-circuit. The path that actually spends the budget is the wedge that never answers — and that one now ends in a hold, paying neither the ladder nor the fork. Long path and expensive tail are disjoint. Raising the budget is precisely what re-couples them, by extending how late an `empty` may arrive. And the guard was costed as a signature change through DaemonSpawner, which is wrong. createOutOfProcessLauncher is a factory called where `signal` is already in scope; a third parameter closed over there leaves the launcher's call signature untouched. Overstating the price invites skipping the guard rather than paying it. Also recorded: two terms this budget does not bound at all — the healthy branch, which never consults the clock and still ends in a cleanup and a fork, and the unbounded daemon-host copy on packaged Windows. * docs(daemon): correct an overstated claim about the deleted retry loop The deletion was justified as "the loop could never run, at any budget." That is true of three wedge shapes and false of a fourth: a connect that fails fast leaves the budget nearly whole, and while refused and missing endpoints are caught by the proven-dead guard, the EPERM/EMFILE class reads 'unknown' and would have passed the gate. The deletion still stands — retrying an fd-exhausted or permission-denied connect fails identically the second time, and recover() restores full daemon service on the next spawn once the condition clears — but a comment that overstates its own reach is how the next person concludes the reasoning was never checked. * test(daemon): restore two guards a range deletion swallowed Deleting the obsolete grace-loop test took out the two tests either side of it — the ones pinning that the hold declines a proven-dead endpoint and a rejected daemon. Both exclusions went unpinned in the same commit that removed the loop, and the suite stayed green, because nothing else covers either path. Found by mutation rather than by reading: removing `health !== 'rejected'` from the hold left all 1472 passing. The pre-existing rejected test does not cover it — its second client answers listSessions, so occupancy resolves to 'empty' and the replace path is reached without the exclusion ever being consulted. The restored test keeps the daemon unreachable so the verdict stays 'unknown', which is the only state where the exclusion decides anything. Also pins the evidence gate, the other survivor: the threshold must cover an identity ps plus two ownership probes, or a read started at the last moment the gate allows finishes past the ceiling the kill ladder and fork are sized against. Mutation results now: patient connect collapsed -> caught; evidence gate -> caught; hold removed -> caught; proven-dead exclusion -> caught; rejected exclusion -> caught; fresh-spawn revert -> caught. * fix(settings): make the degraded copy the copy users actually see Two user-facing fixes were no-ops. translate() resolves from en.json, and the catalog only ever gained the string it was first synced with — the sync script adds missing keys and never updates changed defaults, which the extraction gate reports as "inline defaults differ" and then passes anyway. So editing the inline default changed the source and nothing else. Caught by rendering the component and reading what came out, not by reading the diff. What was stale in the catalog, and is now corrected there: The notice promised the panes reconnect on their own once the host recovers. They do not. TerminalErrorToast already tells the user "Reopen this pane to retry", because nothing re-attaches a pane whose owner could not be verified — the session is left untouched, which is the point, but recovery is a user action. Third claim of mine in this PR that was stronger than the code. And "Restarting the host clears this" still overstated the foreign-endpoint case, where killStaleDaemon matches no pid record and clears nothing. Also removes the components.settings.DaemonDegradedNotice.* namespace, left behind when the keys were renamed to the auto.* convention every sibling uses. It was dead weight carrying the oldest copy of all three strings. * docs(daemon): 'held' no longer means what its type said it meant The mode was introduced for a daemon that demonstrably owns live terminals and cannot answer a handshake. It is now also what an unclassifiable daemon gets, where the whole point is that we could not establish what it owns. A type whose comment asserts the one fact the branch could not determine is the same overclaim this PR has been correcting elsewhere. Also un-exports ENDPOINT_PROBE_TIMEOUT_MS: it was widened for a test that no longer references it, and nothing outside the module reads it. * fix(daemon): stop a lost spawn reply from shadowing a live agent `!mapped` was standing in for "this is a fresh spawn," and it is not the same question. The mapping is only recorded after a reply arrives, so a spawn that names a session and then loses its reply — the daemon created it, the answer timed out — is indistinguishable from a genuinely new one. Demoting there sent the retry to the fallback, which answers with a fresh local shell under the same id while the agent keeps running on the daemon. The pane binds to the shell; the agent is orphaned. That is the symptom this PR exists to remove, arriving through a door the PR opened itself. Reachability today looks nil — the only sessionId-bearing spawn in ipc/pty.ts carries attachOnly, which routes elsewhere — but the guard was unsound rather than merely unused, and "no caller does that yet" is not a property anyone maintains. Now an identified session pins to the provider that may already own it, and only an anonymous spawn moves the shared route. Anonymous spawns are what demotion was for: nothing can shadow them, and they are the ones paying a hello timeout plus a full re-classification per terminal. Found by GPT-5.6-Sol reviewing this file in isolation. Two tests added; reverting to the old guard fails one. * docs(daemon): name the three paths that can still kill a daemon Adversarial review found all three; none is a regression against the pre-hold behaviour, and none should be closed by weakening the evidence rules. 'unknown' plus a proven-dead endpoint still kills when process evidence cannot answer. The probe proves the directory entry is gone, not the process — a socket entry can vanish while the daemon still hosts agents. Evidence covers that on POSIX because it runs for any 'unknown' rather than only a live endpoint, so the gap is the blind cases: clock spent, pid unverifiable, ps unreadable. It is not reachable on Windows at all, where a named pipe vanishes with its process, so a dead endpoint there implies no agents to lose. 'unknown' plus 'rejected' still kills, and the reviewer is right that inability to adopt is not inability to preserve — those agents keep running, unreachable. Killing stays the choice because a daemon that can never be adopted and is never replaced leaves the app permanently degraded with no route back, but that is a judgement, not a proof, and it is now written as one. And the verdict is not atomic with the kill: an 'empty' answer can go stale if another instance creates a session first. Pre-existing, and narrowed rather than widened here — the window now opens only after the daemon has reported zero sessions itself. * docs(daemon): record the TOCTOU fix that was built, tested and reverted shutdownIfIdle is the right instrument and the daemon already implements it atomically: sole authenticated client, nothing in flight, zero sessions, listener closed before the acknowledgement. Asking it immediately before the kill closes the window that a re-read of listSessions can only move. It is not landing here. Gating every empty-verdict replacement on a new round trip means every failure of that round trip has to mean hold, which trades a rare race for a common failure mode and makes #8689 worse whenever the call is merely slow. It also flipped two endpoint-identity tests from rejecting to resolving, and an unexplained behaviour change is not something to merge at commit forty-two of a change whose whole subject is unintended consequences. Written down with the mechanism intact so the next person starts from a working design rather than rediscovering it. * fix(repro): restore the 91 lines a bad deletion took out of the repro Removing readSourceConstant matched a docblock far earlier in the file and deleted everything between, taking the imports and three functions with it. The script still parsed, still linted, and still passed `node --check` — it failed only when run, with `existsSync is not defined`, which is why it went unnoticed for two commits. The only end-to-end proof in this PR had been dead that whole time. Restored from before the deletion and the intended edit re-applied by itself. Now runs green: phase 1 kills a wedged daemon with real agents attached and confirms they die; phase 2 puts the identical wedge through the decision and shows the daemon unsignalled, both agents alive, and everything back with sessions intact on SIGCONT; phase 3 asserts the launcher holds — now including the unknown-hold, which is the branch this PR turns on. Lesson worth keeping: a syntax check is not a test. Running it is. * fix(daemon): stop the emptiness confirmation reading the same snapshot twice The second sample exists because one snapshot cannot tell a login(1) wrapper whose shell has not appeared yet from a wrapper whose shell has gone. But when the fresh read misses its deadline — the busy host this evidence exists to protect — both attempts fell through to the same TTL-cached table. Two agreeing samples, one observation, and the window being excluded is shorter than the cache. The confirming read is now denied the cached fallback. If it cannot get a fresh table it answers 'unknown', which holds. The first sample keeps the fallback, because there the cache protects the answer worth protecting: a stale table still shows that a daemon has children, and going blind there is what got them killed. Also records three limits of this evidence that review surfaced and that no code change should paper over — a reparented orphan outside the descendant tree, the Windows abstention, and an argv match that cannot establish executable identity. Each only fails to raise a verdict, so each costs a hold not taken rather than a kill licensed. * fix(daemon): stop discarding Linux terminals to solve a macOS problem The stranded-login(1) exclusion ran on every POSIX host. Orca only wraps terminals in login(1) for TCC attribution on macOS, so off darwin the pattern can only match a user's own login — and one still prompting for credentials has no child yet, which is precisely the shape the exclusion throws away. A Linux daemon hosting that terminal read as childless, and a childless daemon is one nothing protects from the endpoint-dead path. Now scoped to darwin, where the problem it solves lives. And a count that is not a count is no longer read as emptiness. `counted > 0` maps NaN, -1 and 1.5 to 'empty', which is the single verdict that licenses a kill; the listSessions dep is injectable, so reaching it never required asking a daemon anything. Non-integers and negatives now resolve to 'unknown'. Both mutation-verified. Noting for whoever runs the next mutation pass: the first attempt at the login mutation silently failed to apply because the pattern had been reflowed by the formatter, and a mutation that does not apply looks exactly like a test suite that caught it. Assert the pattern matched. * docs(daemon): bound what the degraded owner check actually covers Review confirmed the five destructive operations are guarded and that the error taxonomy holds — TerminalSessionOwnerUnverifiedError cannot be reclassified as a gone session anywhere in production, so no fake exit is ever synthesized from it. It also found six methods that still route raw, and they are worth naming rather than leaving for the next reader to rediscover: flow control, background state, buffer clear, startup authority and the per-session queries. For an unresolved daemon id those reach the fallback silently. None can destroy a session, which is why they are not being changed at this point in this branch, but a buffer clear that reports success while the daemon's history survives is a real lie. Recorded with the reason not to fix them casually: acknowledgeDataEvent is invoked directly from an ipcMain.on listener and setPtyBackgrounded from a synchronous callback, so a throwing owner check added there without changing the call sites turns a silent misroute into an escaping exception. * fix(daemon): restore the demotion my shadow fix made unreachable The review is right. Gating demotion on the absence of a sessionId assumed fresh spawns are anonymous, and they are not: every production fresh spawn mints an id before reaching the provider (ipc/pty.ts assigns spawnOptions.sessionId on all three paths). So the branch only ever ran in tests, and a daemon that recovered and wedged again kept every later terminal pointed at itself — each paying a hello timeout plus a full launcher re-classification, each failing anyway. That is the cost the demotion existed to remove, reintroduced while fixing something else. The mistake was treating one condition as two questions. Pinning protects THIS id, which the daemon may already have created before losing the reply, so a retry must never be answered locally under the same name. Demoting protects the NEXT terminal, which is a different session and cannot be shadowed by this one. They are independent, and both now happen. `attachOnly` is the honest discriminator for the second: an attach that names a session never reaches this router, so anything arriving here without it is a fresh terminal whatever id it carries. Both halves mutation-verified separately — restoring the sessionId guard fails three tests, dropping the pin fails two — including a test shaped like what ipc/pty.ts actually sends, which is what the old test suite never had. * fix(repro): stop the script doing the exact thing it exists to warn about Both findings are right, and the first is pointed: this script demonstrates that signalling a pid you have not re-verified can kill someone else's work, and its own teardown did that twice. The staged daemon is killed on purpose in phase 1. Once Node reaps that child its pid is free for reuse, and teardown signalled the remembered number anyway; it now signals only while the child object still reports no exit. The markers were half-verified. Each proves its own identity by tag before being signalled, but its session leader was killed on a number remembered from staging a minute earlier — and the leader is the one pid here that can be recycled while its child lives on under a new parent. The leader is now re-read from the live marker and signalled only when the marker still claims it. Second finding: isRealUserDaemon matched a hardcoded macOS userData path, so on Linux a real daemon could never be recognised — the assertion that this run harmed nothing was inert on the platform where nobody would notice. Now matched per platform, with a loose fallback rather than a silent false. Repro re-run end to end: all three phases pass, pre-existing daemons still running, real userData daemon untouched. * fix(daemon): only demote and only pin when the failure earns it Both guards in the fresh-spawn catch were too broad, and narrowing them is the one thing worth keeping from the restart-ownership branch. Demotion fired on any spawn failure. A rejected cwd or a bad profile says nothing about whether the daemon is reachable, and costing the whole session its daemon persistence over one of those degrades terminals the daemon would have served fine. It now requires the failure to look like an unreachable daemon. Pinning fired on any failure too. The pin exists for a request that was sent and whose answer was lost — that is the only shape that can hide a session the daemon already created. A failure that never reached it created nothing, so pinning that id would strand later attempts on a host holding nothing of theirs. It now requires an error that could have been dispatched. The distinction is sharper than the code it replaces: a hello timeout demotes but does not pin, because a handshake that never completed cannot have created a session. The old code pinned it anyway. Test doubles now raise DaemonProtocolError rather than plain Errors, which is what the client actually produces and what these predicates are written against. Both narrowings mutation-verified. * test(daemon): prove the recovery the degraded notice promises The readiness review flagged one claim it could neither confirm nor refute: the notice tells the user "reopening a pane retries, and works once it does", and nothing pinned that. It mattered because held mode is exactly the case where no route was ever recorded — discovery ran over the same IPC the daemon was failing — so recovery cannot come from a cached route. It has to come from the next attach re-inventorying a provider whose failure cooldown has expired. It does. While wedged the resolver refuses rather than letting the fallback answer with a fresh shell, and once the daemon answers again the same attach reattaches the original session. Verified by mutation: with the daemon left wedged, the test fails. Fourth user-facing claim in this branch checked against the code rather than assumed. The previous three were wrong. --------- Co-authored-by: Orca <[email protected]>
…oses every tab (stablyai#14361) * Revert "fix(daemon): stop killing live coding agents when the daemon can't report its sessions (stablyai#13928)" This reverts commit 73db6c8. Reverted together with stablyai#13326: the 1.4.182-daily.202608131439 build carrying both loses every tab on an SSH disconnect/reconnect cycle. Reverting first so main stays releasable and the P0 fixes in the wild remain cherry-pickable, rather than fixing forward on a shipped regression. * Revert "fix(ssh): stop SSH reconnect from multiplying terminals and resuming agents twice (STA-3077)" (stablyai#13326) This reverts commit 4cc0e9c. Reported on 1.4.182-daily.202608131439: connect to an SSH worktree, disconnect the host from the hosts popup, reconnect — every tab is gone. That is worse than the behaviour this PR set out to fix, where most tabs were retained. Reverting rather than fixing forward, so main stays releasable and the P0 fixes already out in the wild stay cherry-pickable. STA-3077 stays open.
…nce stranding moved panes (stablyai#14384) * Reapply stablyai#13326 and stablyai#13928 (un-revert stablyai#14361) Restores the SSH reattach-identity and daemon-occupancy fixes. Reverting them reintroduced their P0s, filed as STA-4224, STA-4225, STA-4227, STA-4230, STA-4232, STA-4233 and STA-4234 against stablyai#14361. The tab loss that motivated the revert is fixed in the commits that follow, so this reapplication is not a straight redo. * fix(relay): stop the fallback attach fence refusing a pane that moved tabs The primary fence was moved to the shell's own incarnation precisely because paneKey/tabId froze the pane's LOCATION at spawn and refused panes that had merely moved. The fallback that older clients fall into kept the old rule, so the correction never reached it — the same 'the rule exists, but this path does not ask it' leak this work has hit repeatedly. A refusal here is not recoverable: an identity mismatch never grounds a respawn, so the pane keeps a live shell it can no longer reach and renders blank. Narrowed to paneKey, which is the identity; the tab is a location. Restoring the tabId comparison reddens the new test.
What broke, in plain terms
Orca doesn't run your terminals inside the app. It runs them inside a separate helper process called the daemon. That's deliberate — it's why you can quit and reopen Orca and your agents are still there.
The catch is that the daemon owns those terminals completely. The file handles for every PTY live inside that one process, and there is no mechanism to hand them to a different process. So the rule is simple:
Now, sometimes Orca does need to replace the daemon. Before it does, it asks the daemon a reasonable question: "how many live sessions do you have?" If the answer is "more than zero", it backs off, because replacing it would destroy your work.
That question can come back three ways:
50nullThe bug is what happened on
null. The code was:nullfell through into the kill.Why that's wrong: "I couldn't ask you how many terminals you have" is not the same as "you have no terminals." A daemon that's too busy to answer is still busy hosting. It's the difference between someone not picking up the phone and someone being dead — and we were holding a funeral either way.
And this is not hypothetical. To even reach this code, the daemon has to have already failed a health check — which mostly happens when the machine is under heavy load. Heavy load is also exactly when a busy daemon can't answer within its 3-second budget. The condition that triggers the check is the same condition that makes the check come back blank.
How it looked to the user
You click into a worktree. Your agent is either gone entirely, or it "comes back" by typing
claude --resume <id>into a fresh shell. It looks like a restore. It isn't — the original process was killed and everything it hadn't written down is gone.From a real incident:
Every line says
session-created, neversession-attached— brand-new shells. The daemon died in the same second as asidebar_worktree_activatebreadcrumb, i.e. the moment the user clicked into the worktree. The app itself was never restarted; the new daemon is a child of the already-running app process.Two more details that made this hard to catch:
probeSockethas a 1-second timeout. If it misses, the 11-retry grace loop is skipped entirely and the kill lands in ~4 seconds instead of ~60.if (liveSessionCount !== null || graceRetry > 0 || health === 'rejected')— all three false. The daemon was killed silently, which is why nothing in the logs explained it.Which change introduced this
Two commits, and it's a trade-off resolved the wrong way rather than a careless slip.
Origin —
0b19195fd9b(#5230), 2026-06-11. This wrote the predicate, with its reasoning in the comment:The first half is the error. A daemon that can't list sessions is still hosting them — listing and serving are different capabilities. The same author had written the two sibling branches two weeks earlier (
1371402bc6f#2974,5bfa1413a53#4330) and both preserve onnull, with the comment "live session state could not be verified". This branch diverged from the codebase's own convention.Reintroduction —
840d3277d1d(#8697, fixing #8689), 2026-07-14. A blanket preserve-on-nullhad been added four days earlier by #7214 (to stop a Windows update-relaunch killing live terminals) and was masking the defect. #8689 replaced it with the bounded 11-retry grace loop — correctly stopping a permanently wedged daemon from being preserved forever — but that restored kill-on-unknown for anything still unverifiable after ~60s. It left the weak predicate verbatim; it did not author it.This history is why the fix needed a new signal rather than a flipped boolean. From the launcher's vantage point, "wedged with live agents" and "wedged with nothing" are literally identical:
nullcount, connectable socket. Flippingnullto preserve would just re-break #8689.The fix, in one line
A daemon we cannot classify is held, not killed.
Why it isn't a timing fix
The launcher decides whether to kill a health-check-failing daemon before the app can start, so the decision was bounded by a budget. Ten review rounds each found a different band where this branch replaced a daemon
origin/mainwould have kept, and each fix bought a new band. The reason is arithmetic, not carelessness:main's toleranceThere is no assignment of those numbers that is both bounded and as safe as
main. So the residual stopped being lethal instead.daemon-occupancy.tsalways said it —— while
daemon-init.tsfell through fromunknowntokillStaleDaemon. That fall-through is what made every millisecond of budget a correctness parameter. Being wrong now costs a degraded session, not somebody's agent.Two exclusions, both about never holding something unrecoverable:
rejected— it answered and refused, so it can never be adopted and its sessions can never be reattached.What it costs, deliberately
A wedged-but-empty daemon is no longer replaced at launch, so #8689 degrades to "restart it from Manage Sessions". That only works if the user knows — and degraded mode was computed, plumbed through preload, and read by nothing. It now renders where the Restart button already lives, and states its real cost: new terminals close when you quit, and restarting ends whatever the host is still holding.
Rejected on the way here
degraded-daemon-fresh-spawn-routing.ts.Proof
killStaleDaemoncall site is downstream of it; mutation-verified.origin/mainworktree.pnpm run test:repro:daemon-replacement-live-agent-pty-preservation— real daemon, real PTYs,SIGSTOPas the wedge (socket still accepting, no RPC ever answered — the case the code itself calls out).Phase 1, the danger is real:
Phase 2, the decision protects it:
That last line is the whole argument: the wedge was transient. Given the chance, the daemon came back healthy with both sessions intact. Under the old code those agents were already dead.
Phase 3 statically pins that the launcher raises evidence only from a verified pid and returns a held handle before any kill — and says explicitly that it proves source ordering, not execution.
src/main/daemon: 1461 passing.tsc --noEmit: 0 errors. oxlint + oxfmt clean.What fourteen rounds of adversarial review caught
Recorded because the near-misses are the useful part, and because several were mine.
unknownnever licenses one. Mutation testing also found four survivors, including one where the whole fix could ship as a no-op.heldhad been added as a fifth branch rather than the classification the others route through. Also: the grace budget was a comment with aDate.now()beside it — one probe could cost 50s against a 5s assumption.pty:killtreats "Session not found" as proof the pty is gone and synthesizes an exit, so the obvious error would have reproduced the lie one layer down.mainkept. Round 10 also found the ordering defect behind the last one: the launcher asked the cheap question first and the tolerant one last, by which point the clock could fund a handshake but not an answer. Fixing the order was right, but working the numbers through afterwards showed the budget could not close at all — which is what produced the design change above.0there by design, and the assertion demanded ≥11s unconditionally, sopnpm testwas broken on any Windows dev machine. PR CI never saw it: only the WSL boundary spec runs onwindows-2022.isDaemonDegraded()was computed and plumbed through preload — and no renderer read it. Makingunknownhold would have turned a rare, loud failure into a common, silent, permanent one. The notice is part of this change for that reason.max(CONNECT, probeBudget − REQUEST)resolved to exactlyCONNECT: the "patient" ask got the cheap ask's four seconds, and the grace loop's gate needed 19s of a budget that only ever held 11s, so it never ran. Every test passed, because mocked probes consume no wall clock and the budget never binds. The reservation was backwards regardless — evidence can only raiseunknownto an uncountedoccupied, and both hold, so it bought a log line while starving the one probe whose counted answer reachespreserveDaemon(). It is opportunistic now.OCCUPANCY_REQUEST_BUDGET_MS, and the gate wantedCONNECT + REQUEST— soWEDGED_DAEMON_GRACE_RETRIES = 11documented patience no ceiling could buy (44s leaves the same remainder). Deleted. The one shape where it was reachable is a fast connect error in the EPERM/EMFILE class, andDegradedDaemonFreshSpawnRouter.recover()returns that daemon to full service on the next spawn anyway, off the startup clock.!mappedwas standing in for "this is a fresh spawn", but the mapping is only recorded after a reply arrives — so a spawn that names a session and loses its reply is indistinguishable from a new one. Demoting there sent the retry to the local fallback, which answers with a fresh shell under the same id while the agent keeps running on the daemon: the pane binds to the shell, the agent is orphaned. That is this bug's own symptom, arriving through a door the fix opened.translate()resolves fromen.json, and the sync script only adds missing keys — it never updates a changed default. Editing the inline default changed the source and nothing a user would see. Caught by rendering the component, not by reading the diff.runRestartDaemonshuts down the local fallback sessions too). The banner also never refreshed, so it could recommend a session-ending Restart after the daemon had already recovered.Behaviour changes worth knowing about
Both follow from the change being honest where it previously was not.
Known residuals
src/main/daemon/AGENTS.mdrecords that it must stay that way, and why tuning it is not the fix.unknownis indistinguishable from "never tried" in the field. A silently broken probe reports the same value as a genuinely blind one, with no telemetry separating them.heldfor existing sessions within a process lifetime; recovery comes on the next launch or via Restart.test:repro:*, yet it is the only thing exercising the production wiring end to end — and it is what caught the first two defects above.SIGSTOP, a total wedge, so it only exercises the process-table path. The class of bug that produced rounds 7-10 is invisible to CI; the hold is what makes it non-fatal, not test coverage.heldfallback as the failed-health path. That path arrives with occupancyunknownorempty, so holding there would swallow a real launch failure to protect nothing — I implemented it, watched it hide a fork error, and reverted.respawn('daemon_died')→ full re-ensure, which is what runs this decision mid-session.daemon-init.tsalready concedes the app cannot tell wedged from dead there.Alignment with existing doctrine
src/main/daemon/AGENTS.mdalready states the rule this branch broke:That was written about the socket path. The session-count gate broke the same principle one layer up, with the same consequence. The codebase also already had the correct three-valued primitive —
probeSocketConnect, whose own doc says "absence of proof is not proof of death" — and this file was using a lossy boolean copy of it that returnedfalseon timeout, and unconditionally on Windows named pipes.