Skip to content

fix(relay): stop advertising an agent session for a pane whose tab is gone (#12447) - #17012

Merged
nwparker merged 1 commit into
mainfrom
nwparker/relay-retire-closed-pane-agent-session
Aug 28, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/relay-retire-closed-pane-agent-session

Conversation

@nwparker

@nwparker nwparker commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​487 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​487
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​307 $\color{#cf222e}{\Huge{\mathbf{−}}}$​28 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​279

Closes the server-side half of #12447 — @chanmuzi's relay dataset. Relay-side only; no wire change.

ELI5

Orca runs a small helper — the relay — on your SSH host. It owns your remote terminals, and it also runs a tiny web server that your agent (claude, codex, …) posts status updates to: "I'm working", "I'm waiting for you", "I'm done". The relay forwards those to every connected Orca so the sidebar can show a live agent.

When you close an agent tab, Orca asks the relay to kill that terminal. Usually it dies. Sometimes it doesn't — an interactive shell ignores the polite signal, or the forceful one only reaches the shell and not the agent inside it. When that happens, the agent is still alive and still posting status updates, and the relay had no idea it should stop listening. It kept forwarding them. So every Orca on that host kept being told there was a live agent in a pane that no longer had a tab — and the next time you opened the project, Orca did what you'd want it to do for a live agent it had lost track of: it opened a terminal and typed claude --resume <that session>.

Now you have two claude processes writing into one conversation transcript. That is not recoverable.

The relay's mistake was believing the kill worked. It never asked again, and it never wrote down the one thing it did know for certain: you closed the tab.

After this change the relay writes that down. The moment pty.shutdown arrives, the pane is retired:

  • its cached agent status is dropped, so a reconnecting Orca is never replayed a live agent for it;
  • anything that pane posts afterwards is thrown away, not forwarded — an orphan can no longer advertise itself;
  • the relay comes back a few seconds later and checks whether the shell actually died, and force-kills again if it didn't, instead of assuming;
  • if it can prove the process is gone, it retires the whole record — even when the terminal library never reported the exit.

And one deliberate non-action: if the relay cannot prove the process died, it keeps the agent-session ownership claim. That sounds backwards, but it is the safety property. That claim is what makes the next terminal you open adopt the surviving pane instead of starting a second agent on the same transcript. An honest "I can't verify this" keeps you at one agent; forgetting would take you to two.


Root cause

PtyHandler.shutdown() — src/relay/pty-handler.ts:1939 (pre-change).

const managed = this.ptys.get(id)
if (!managed) { return }
if (immediate) { … requestForceKill … } else { … requestGracefulKill … }

pty.shutdown is the only authoritative statement the relay ever receives that a tab has closed, and it retired nothing. It requested a kill and returned. Every retirement path in the relay keys on proof of process death, and there are exactly three:

site trigger
pty-handler.ts:872 (onExit) node-pty reported the child exited
pty-handler.ts:1785 (attach) an attach probed isProcessAlive and found the pid gone
pty-handler.ts:2406 (disposePtyForRelayShutdown) the whole daemon is going down

Client disconnect retires nothing either (relay-reconnect-listener.ts:120 → dispatcher.ts:185 only close the writer), and the shipped grace is unlimited (DEFAULT_SSH_RELAY_GRACE_PERIOD_SECONDS = 0, src/shared/ssh-types.ts:7), so with ≥1 live PTY nothing is ever armed.

So when the kill did not actually reap the pane shell — SIGTERM ignored by an interactive shell, or forceKillPosixPtyProcessGroups degrading to a root-pid kill when getPosixPtyProcessGroups returns null (src/main/pty/posix-pty-process-groups.ts:99-108) — two advertisements survived the tab:

  1. src/relay/agent-hook-server.ts:301 (applyEvent). The orphaned agent keeps POSTing to the relay's loopback hook listener with the closed pane's ORCA_PANE_KEY. applyEvent cached it in lastStatusByPaneKey and forwarded it to every connected client as an agent.hook notification — with no check whatsoever that the relay still serves a PTY for that paneKey. replayCachedPayloadsForPanes (:200) then re-published it on the next agent_hook.requestReplay, i.e. on every reconnect. The only eviction was clearPaneState, reachable solely through notifyExitListener — the exit that never came.

  2. src/relay/pty-handler.ts:2114 (listProcesses). This is what publishes agentSessionOwners, the host's "there is a live agent session here you can adopt". It iterated this.ptys and emitted the registry entry with no liveness verification at all — while attach() fourteen hundred lines earlier does exactly that probe and reaps ("verify liveness because shells can exit without node-pty onExit", :1812).

That is the loop @chanmuzi reported, and it needs no lost kill RPC to close: close → shell survives → orphan advertises → reopen resumes → two agents, one transcript.

The fix

All hunks are relay-side. Per SSH-v3 P2 the host is the authoritative liveness source, so it has to look, and it must not advertise what it has not verified.

1. pty.shutdown retires the pane surface (pty-handler.ts, retired-pane-surfaces.ts). A new RetiredPaneSurfaceRegistry records paneKeys whose tab the client has said is gone. Retirement is deliberately not a liveness verdict — the vocabulary stays live / unverifiable / exited and this asserts none of them about the process. It records only that no client tab can own this pane any more, which is knowable without guessing because the client stated it. A new setSurfaceRetiredListener seam is kept separate from PtyExitListener for exactly that reason: retirement must never read as an exit. A PTY that later binds the same paneKey — a reopened pane, a revive, or an accepted pty.attach — clears the retirement.

2. A retired pane cannot advertise (agent-hook-server.ts, agent-hook-cached-pane-status.ts, relay-agent-hook-runtime.ts). applyEvent drops — does not cache, does not forward — a post from a retired pane, and drops the pane's stale cache with it. replayCachedPayloadsForPanes re-checks at replay time, because retirement can be recorded after the status was cached. The runtime routes the predicate to ptyHandler.isPaneSurfaceRetired and clears the cache eagerly on the retirement edge.

3. The kill is verified, not assumed (armShutdownReapSweep). A bounded, unref'd sweep (3 escalations, ~6s apart) re-probes isProcessAlive. Gone → run the full retirement even though node-pty never produced onExit. Still alive → re-issue the force kill, because a SIGKILL that returned success is not proof of death. POSIX only: on Windows ConPTY's kill is already force-final and re-closing the handle is the hazard disposeManagedPty guards against.

4. listProcesses verifies before it advertises. A PTY that is disposed, or whose pid probes dead, is reaped (shared reapExitedPty, now used by all three probes so they cannot drift) instead of being published with its agentSessionOwners.

The deliberate non-fix, and why it is the safety property

When the sweep exhausts its attempts, the agent-session ownership claim is retained, not released. Releasing a claim the host cannot prove dead is precisely what authorises a reopened project to spawn a second agent: reconcileAgentSessionOwnerListings (src/main/ipc/pty/pane/agent-session-owners.ts:105) treats the relay's listing as authoritative and releases any claim missing from it, after which ensure() creates rather than adopts. Keeping the claim makes the next pty.spawn adopt this PTY — one process, one transcript. unverifiable is the honest verdict and it is also the safe one.

This is why the fix is not "withhold agentSessionOwners for a retired pane". That would have read as a fix and caused the corruption it was meant to prevent.

Remote wire compatibility

Checked against docs/reference/remote-wire-compatibility.md. No wire change: no new RPC method, no new request or response field, no new stream opcode, no RUNTIME_PROTOCOL_VERSION bump. pty.shutdown params and result are byte-identical; PtyProcessSummary is unchanged. isPaneSurfaceRetired is a host-internal constructor option.

Two Rule-3 projections (content the host stops publishing), stated explicitly:

Old client → new relay.

  • It stops receiving agent.hook notifications for a pane it asked the host to shut down. Previously those refreshed a live-agent record for a tab that no longer existed; now nothing arrives and the client's own record ages out via AGENT_STATUS_STALE_AFTER_MS. No client requires these frames: the desktop already clears its own records for a user-closed tab (removeSleepingAgentSessionsForTab, src/renderer/src/store/terminals/terminal-tab-close.ts:154), so nothing is stranded waiting for a final host hook. Strictly fewer false live-agent records; no path hangs on absence.
  • It stops seeing pty.listProcesses rows whose process is provably dead. Old clients treat listing absence as an authoritative release — which is the correct verdict for a dead process, and already the outcome the moment attach() reaped the same entry. A live pane is never withheld, so no old client loses a claim it still needs.

New client → old relay. Identical to today. Nothing in this change asks the host for anything new or reads a new field, so a client on this build against a pre-fix relay gets exactly the pre-fix behaviour: orphan hook events still forwarded, dead rows still listed. The fix is a pure host-side narrowing with no client-side dependence, so there is no new-client-requires-new-host skew to negotiate.

Not on the enforcement harness. tests/e2e/cross-version-wire/… covers the terminal stream only, not the agent-hook channel or pty.listProcesses. Run anyway and green (5 passed) — it proves nothing here, and this section is the reasoning the doc asks for in its place.

Relationship to #16989 (STA-5698)

Adjacent, not overlapping, and not conflicting. I read it before starting.

Fix evidence

Failing-first, full production revert

src/relay/{pty-handler,agent-hook-server,relay-agent-hook-runtime,agent-hook-cached-pane-status}.ts reverted, new tests kept:

 FAIL  agent-hook-retired-pane-suppression.test.ts > does not advertise an orphan agent whose tab was closed
AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times
 FAIL  agent-hook-retired-pane-suppression.test.ts > does not replay a cached status for a pane retired after it was cached
AssertionError: expected 1 to be +0 // Object.is equality
 FAIL  agent-hook-retired-pane-suppression.test.ts > forwards again once the pane key is bound by a new PTY
AssertionError: expected "vi.fn()" to not be called at all, but actually been called 1 times
 FAIL  agent-hook-retired-pane-suppression.test.ts > RelayAgentHookRuntime wiring > routes hook admission through the PTY handler …
AssertionError: expected null not to be null
 FAIL  pty-handler-retired-pane-surface.test.ts > marks the pane surface retired as soon as its tab is closed
TypeError: handler.setSurfaceRetiredListener is not a function
 FAIL  pty-handler-retired-pane-surface.test.ts > retires the surface even when the shell survives the kill request
TypeError: handler.isPaneSurfaceRetired is not a function
 FAIL  pty-handler-retired-pane-surface.test.ts > re-issues the force kill instead of letting a detached shell outlive its tab
AssertionError: expected +0 to be undefined // Object.is equality
 FAIL  pty-handler-retired-pane-surface.test.ts > retires the relay session once the sweep proves the process is gone
AssertionError: expected [ { id: 'pty-1', …(4) } ] to deeply equal []
 FAIL  pty-handler-retired-pane-surface.test.ts > stops advertising an agent session whose process died without a node-pty exit
AssertionError: expected [ { id: 'pty-1', …(4) } ] to deeply equal []
 FAIL  pty-handler-retired-pane-surface.test.ts > restores the surface when a new PTY binds the same pane key
TypeError: handler.isPaneSurfaceRetired is not a function
 FAIL  pty-handler-retired-pane-surface.test.ts > shutting down a pane with no pane key retires nothing
TypeError: handler.setSurfaceRetiredListener is not a function
 Test Files  2 failed (2)
      Tests  11 failed | 2 passed (13)

Honest note on that run. Several of those are TypeError, not assertion failures — the retirement API does not exist on the unfixed relay, so the suite cannot express the pre-fix behaviour without it. A whole-file revert is therefore weak evidence. The ablation table below is the real proof, and one test — "shutting down a pane with no pane key retires nothing" — pins that behaviour is unchanged for a paneless PTY and by construction cannot fail before the change. I am not claiming failing-first for it.

Post-fix: 19 passed (19).

Ablation table — every production hunk reverted individually

# Hunk Result
H1 applyEvent retirement gate RED — 3 failed / 16 passed
H2 replay retirement gate RED — 1 failed / 18 passed
H3 shutdown() retires the surface RED — 4 failed / 15 passed
H4 shutdown() arms the reap sweep RED — 2 failed / 17 passed
H5 listProcesses liveness verification RED — 1 failed / 18 passed
H6 wireAndStore restores a rebound pane RED — 1 failed / 18 passed
H7 runtime routes the retirement predicate RED — 1 failed / 18 passed
H8 runtime clears the cache on retirement RED — 1 failed / 18 passed
H9 sweep reaps a proven-dead pid RED — 1 failed / 18 passed
H10 sweep re-issues the force kill RED — 1 failed / 18 passed
H11 attach() restores a reattached pane RED — 1 failed / 18 passed
H12 sweep skips the ConPTY re-close on Windows RED — 1 failed / 18 passed

No uncovered hunk. H7 was mutated to a permissive predicate (() => false) rather than deleted, since deletion only restores the default — a weak mutation would have made the table lie.

Requested coverage

requirement test
a closed agent tab retires its relay session marks the pane surface retired as soon as its tab is closed; retires the relay session once the sweep proves the process is gone
a detached shell does not outlive its tab re-issues the force kill instead of letting a detached shell outlive its tab
a stale resumable-active advertisement cannot drive an auto-resume does not advertise an orphan agent whose tab was closed; does not replay a cached status for a pane retired after it was cached; stops advertising an agent session whose process died without a node-pty exit
mixed version — old client / new relay the two above are exactly what an old client stops receiving; an embedder that supplies no retirement source keeps forwarding everything pins the unchanged default (this is also the WSL relay's wiring, wsl-agent-hook-relay.ts:67)
mixed version — new client / old relay no client change in this PR; tests/e2e/cross-version-wire green

Gates

  • pnpm tc — exit 0
  • oxlint (incl. the react-doctor config, via the commit hook) on all changed files — clean. No max-lines disable added: agent-hook-server.ts crossed 300 counted lines, so replayCachedPayloadsForPanes's body and the cached-pane cap eviction were extracted into agent-hook-cached-pane-status.ts rather than suppressed.
  • pnpm exec oxfmt --write on changed paths only
  • git diff --check — clean
  • pnpm test src/relay — 147 files, 1519 passed, 2 skipped, 0 failed
  • src/relay + src/main/ipc/pty + src/main/providers + src/main/daemon — 429 files, 4573 passed, 0 failed
  • tests/e2e/cross-version-wire/cross-version-terminal-wire.unit.test.ts — 5 passed

Identity-space findings — verified, deliberately left

Three findings landed mid-review. This fix keys on neither incarnation identifier, so none of them apply to it; I verified all three in the code and am reporting rather than fixing, so they can be filed separately.

What this fix keys on, and why. Retirement is keyed on paneKey (ORCA_PANE_KEY, pty-handler.ts:1623) and liveness on managed.pty.pid. Both are relay-local and host-owned: paneKey is the identity the agent-hook payload already carries (it is how clearPaneState has always worked), and the pid is what the host can probe directly. Neither ptyIncarnation nor incarnationId is read, compared, or used as a key anywhere in this diff. listProcesses still emits incarnationId exactly as before.

Consequently there is no no-semantic-incarnation degradation to handle here. A PTY with no semantic incarnationId — an old relay, a legacy: pin, a paired runtime — retires and reaps identically, because retirement never consults an incarnation. The one place this diff touches an incarnation-adjacent contract is listProcesses omitting a row for a provably dead PTY, and that is unambiguous in both directions of skew.

Verified and not fixed:

  1. ptyIncarnation ≠ incarnationId. SshPtyExitCallback (src/main/providers/ssh-pty-provider-contract.ts:34-40) carries both — ptyIncarnation: string always present, incarnationId?: PtyIncarnationId optional — and resolvePtyIncarnation (src/main/providers/ssh-pty-provider-output-state.ts:131-139) synthesizes legacy:${providerGeneration}:${serial}:${relayPtyId} first-write-wins per relayPtyId when the wire omits one. A legacy: pin can never equal a real incarnationId.
  2. findExactPendingExit compares across that boundary (src/main/ssh/ssh-relay-session.ts:2530-2542): it matches exit.ptyIncarnation (transport) against callers' attachResult.incarnationId (semantic — :2433-2435 and :2458). Under a legacy: pin the exact match can never succeed, falling through to the coarser "any pending exit for this ptyId" clauses. Real, in adjacent territory, untouched here.
  3. ptyIncarnationById has two uncoordinated last-write-wins writers (src/main/ipc/pty/provider/ownership-state.ts:5), with no generation fencing: renderer-driven spawn/reattach and connection-level bulk reattach-on-reconnect. A stale last write makes isCurrentPtyExit (:7-10) silently reject a real exit. Untouched here.

What I did NOT verify

  • No live SSH reproduction. I did not stand up a real host, close a tab, leave claude alive under relay.js --detached, and watch the advertisement stop. All evidence is unit-level against PtyHandler and a real RelayAgentHookServer over loopback HTTP.
  • No Electron/CDP run. Nothing renders differently by design — the change is the absence of a notification.
  • Retirement is in-memory only. A relay restart forgets every retirement. A pane closed before a restart whose shell survived would have its hooks forwarded again. Persisting it needs an on-disk ledger and is out of scope; in practice a closed tab is not in the client's serialized state, so pty.revive will not re-list it either.
  • Pid-recycling window widened. The sweep re-issues a force kill on managed.pty.pid for up to ~24s. If node-pty missed the child's exit and the host recycled the pid inside that window, the sweep would signal an unrelated process group. The identical shape already exists in armForceKillFallback's retry (+5.25s); this widens it. Note that a recycled pid normally implies the child was reaped, which implies onExit fired, which removes the entry and stops the sweep — so the exposure is confined to the missed-onExit case the feature exists for. Not measured on a real host.
  • The SHUTDOWN_REAP_VERIFY_DELAY_MS = 6_000 / SHUTDOWN_REAP_MAX_SWEEPS = 3 budget is reasoned, not tuned. 6s sits just past the existing 5s armed fallback so the first sweep observes post-kill state; three escalations bound it at ~24s. I did not measure how often a real host needs more than one.
  • Not the whole of [Bug]: Closed SSH terminal tabs resurrect: reattach re-creates persisted tabs, erases close tombstones, and auto-runs claude --resume on old sessions #12447. Item 1 of the earlier triage — the lost pty.kill with no pending-kill journal (src/main/ipc/pty/runtime/kill.ts) — is untouched, as is persistPtyBinding's unconditional tombstone delete. This PR closes the server-side advertisement loop, not the client-side lost kill.

Refs #12447. Adjacent to #16989 (STA-5698); neither blocks the other.

… gone (#12447)

`pty.shutdown` was the only signal the relay ever got that a tab had closed,
and it retired nothing: it requested a kill and returned. Every retirement path
in the relay keys on proof of process death, so when the kill did not reap the
pane shell the relay kept forwarding the orphaned agent's hook events as a live
agent pane with no tab, and kept publishing its `agentSessionOwners` from
`pty.listProcesses` with no liveness check at all.

The relay now records the retirement the client stated, drops the pane's cached
agent status with it, refuses to forward or replay posts from a retired pane,
verifies the kill actually landed instead of assuming it, and reaps any PTY
whose pid it can prove is gone before listing it.

No wire change: no new RPC, field or stream opcode.
@coderabbitai

coderabbitai Bot commented Aug 28, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The relay now tracks pane surfaces retired by PTY shutdown. PtyHandler notifies listeners, restores pane keys on reattachment, and performs bounded liveness checks. RelayAgentHookServer suppresses events and cached replays for retired panes and evicts cached panes through shared helpers. RelayAgentHookRuntime connects PTY retirement events to hook-cache cleanup. Tests cover registry limits, PTY lifecycle behavior, hook suppression, replay, and runtime wiring.

Merge Risk: 🟡 Moderate · up to 5fb96

The change suppresses updates from closed panes, but delayed retries, stale shutdown cleanup, and retirement-record eviction can still cause stale agent state or terminate a legitimately restored terminal. These bounded correctness and availability risks should be fixed or explicitly accepted before merging.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 8 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: preventing agent-session advertisements for panes whose tabs are gone.
Description check ✅ Passed The description is substantially complete. It explains the problem, implementation, rationale, compatibility impact, limitations, linked issue, and extensive test results. It does not explicitly compl…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Description check

Explanation

The description is substantially complete. It explains the problem, implementation, rationale, compatibility impact, limitations, linked issue, and extensive test results. It does not explicitly complete every template heading or checklist item, but the missing sections are non-critical because the relevant information is provided elsewhere.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 9500145e-564b-427c-a4d6-9f51f57675d8

📥 Commits

Reviewing files that changed from the base of the PR and between 65dd06a and 5fb9613.

📒 Files selected for processing (8)
  • src/relay/agent-hook-cached-pane-status.ts
  • src/relay/agent-hook-retired-pane-suppression.test.ts
  • src/relay/agent-hook-server.ts
  • src/relay/pty-handler-retired-pane-surface.test.ts
  • src/relay/pty-handler.ts
  • src/relay/relay-agent-hook-runtime.ts
  • src/relay/retired-pane-surfaces.test.ts
  • src/relay/retired-pane-surfaces.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.

Comment on lines +318 to +320
if (this.isPaneSurfaceRetired(event.paneKey)) {
this.clearPaneState(event.paneKey)
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect whether retry scheduling can re-enter applyEvent after a retired post.
rg -n -C 10 '\bscheduleAssistantMessageRetry\s*\(|\bscheduleCodexSubagentPoll\s*\(|\bapplyEvent\s*\(' src/relay

Repository: stablyai/orca

Length of output: 12088


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- repository conventions ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print \
  -exec sh -c 'echo "--- $1"; head -80 "$1"' _ {} \;

printf '%s\n' '--- agent hook server ---'
sed -n '300,355p' src/relay/agent-hook-server.ts

printf '%s\n' '--- retry scheduler ---'
sed -n '1,215p' src/relay/agent-hook-result-retry-scheduler.ts

printf '%s\n' '--- pane-state cleanup and scheduler clearing ---'
rg -n -C 8 '\bclearPaneState\b|\bclearAssistantMessageRetry\b|\bclearCodexSubagentPoll\b|new AgentHookResultRetryScheduler' src/relay src

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -euo pipefail
log=/tmp/coderabbit-shell-logs/shell-output-Q1J5hU

for marker in '--- agent hook server ---' '--- retry scheduler ---' '--- pane-state cleanup and scheduler clearing ---'; do
  echo "$marker"
  line=$(rg -n -F -- "$marker" "$log" | head -1 | cut -d: -f1 || true)
  if [ -n "$line" ]; then
    end=$((line + 230))
    sed -n "${line},${end}p" "$log"
  else
    echo "marker not found"
  fi
done

Repository: stablyai/orca

Length of output: 35310


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- cache cleanup ---'
rg -n -C 12 'function clearPaneCacheState|const clearPaneCacheState|export .*clearPaneCacheState|clearPaneCacheState' src/shared src/relay

printf '%s\n' '--- codex subagent predicate ---'
rg -n -C 16 'function hasCodexTranscriptSubagents|const hasCodexTranscriptSubagents|export .*hasCodexTranscriptSubagents|hasCodexTranscriptSubagents' src/shared src/relay

printf '%s\n' '--- request admission and scheduler calls ---'
sed -n '270,292p' src/relay/agent-hook-server.ts
sed -n '220,233p' src/relay/agent-hook-server.ts

Repository: stablyai/orca

Length of output: 40887


Stop assistant retry scheduling for retired panes.

applyEvent() clears the pane state and returns, but handleRequest() still calls scheduleAssistantMessageRetry(). That method can arm a timer from the request body. If the pane key is restored before the callback, the callback can apply the orphan event. Skip this scheduler call when the pane is retired.

Comment thread src/relay/pty-handler.ts
Comment on lines +2031 to +2034
if (attemptsRemaining <= 0) {
process.stderr.write(
`[pty-handler] retired pane PTY ${managed.id} still alive after force kill; ownership retained as unverifiable\n`
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use unverifiable, not “still alive”. isProcessAlive() treats errors other than ESRCH as alive, so this log can report an unverified remote process as live. As per coding guidelines: SSH verdicts must use live, unverifiable, or exited, with no synonyms.

Source: Coding guidelines

@nwparker
nwparker merged commit 94e7586 into main Aug 28, 2026
54 of 56 checks passed
brennanb2025 added a commit that referenced this pull request Aug 28, 2026
…base

#17012 landed on main spying on ptyShellUtils.isProcessAlive while this branch
moved the probe into pty-process-probes. The rebase merges textually clean but
breaks 6 of the file's 9 tests and the node typecheck.
brennanb2025 added a commit that referenced this pull request Aug 28, 2026
Resolves src/relay/agent-hook-server.ts against #17012, which landed on main
after this branch extracted applyEvent/handleRequest into their own modules.

Main's retired-pane-surface gate lived in the extracted body, so a plain
'keep ours' resolution would have dropped it: applyRelayEvent now takes
isPaneSurfaceRetired and drops a retired pane before caching or forwarding,
and agent-hook-event-application.test.ts pins it at its new home.

Options types move to agent-hook-server-options.ts to keep the server file
under max-lines.
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 30, 2026
… gone (stablyai#12447) (stablyai#17012)

`pty.shutdown` was the only signal the relay ever got that a tab had closed,
and it retired nothing: it requested a kill and returned. Every retirement path
in the relay keys on proof of process death, so when the kill did not reap the
pane shell the relay kept forwarding the orphaned agent's hook events as a live
agent pane with no tab, and kept publishing its `agentSessionOwners` from
`pty.listProcesses` with no liveness check at all.

The relay now records the retirement the client stated, drops the pane's cached
agent status with it, refuses to forward or replay posts from a retired pane,
verifies the kill actually landed instead of assuming it, and reaps any PTY
whose pid it can prove is gone before listing it.

No wire change: no new RPC, field or stream opcode.

(cherry picked from commit 94e7586)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… gone (stablyai#12447) (stablyai#17012)

`pty.shutdown` was the only signal the relay ever got that a tab had closed,
and it retired nothing: it requested a kill and returned. Every retirement path
in the relay keys on proof of process death, so when the kill did not reap the
pane shell the relay kept forwarding the orphaned agent's hook events as a live
agent pane with no tab, and kept publishing its `agentSessionOwners` from
`pty.listProcesses` with no liveness check at all.

The relay now records the retirement the client stated, drops the pane's cached
agent status with it, refuses to forward or replay posts from a retired pane,
verifies the kill actually landed instead of assuming it, and reaps any PTY
whose pid it can prove is gone before listing it.

No wire change: no new RPC, field or stream opcode.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant