Repository navigation
fix(relay): retire PTYs the host proves are gone, and stop two per-poll scan storms - #17832
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review. 📝 WalkthroughWalkthroughThe changes add remote transcript parse caching with host, mtime, and size validation, plus Codex title refresh from session indexes. They update relay PTY liveness checks, stale resize handling, process-tree lookup, and exit notifications. The node-pty patch adds file-descriptor retirement, Unix spawn cleanup and diagnostics, Windows job ownership, and socket error handling. New tests cover cache reuse, PTY descriptor reuse, stale PTYs, and process-child detection. The English locale adds activity controls and dashboard activity translations. Merge Risk: 🟡 Moderate · up to PTY cleanup can discard buffered output and the terminal-exit notification when relay delivery is under backpressure, leaving remote clients with inconsistent session state. This bounded reliability risk should be fixed or explicitly accepted before merging. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description is detailed and covers the problem, implementation, linked issues, testing, risks, and follow-ups. It does not include the template headings or an explicit Visual Proof Full details: Linked Issues checkExplanation The PR satisfies the primary coding objective for Full details: Out of Scope Changes checkExplanation The node-pty and relay lifecycle changes support Full details: Docstring CoverageExplanation Docstring coverage is 47.83% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 13 files. (1 skipped: 1 unsupported.)
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 |
Greptile SummaryThis PR adds host-proven stale-PTY retirement, replaces per-poll
Confidence Score: 3/5The PR should not merge until stale-PTY retirement publishes the expected exit and destructive child-process checks avoid acting on a stale snapshot. Resize-triggered reaping can leave a visible pane bound to an already removed PTY, while cached child detection can miss a newly launched process and permit closure or cleanup without warning. Files Needing Attention: src/relay/pty-handler.ts, src/relay/pty-shell-utils.ts
|
| Filename | Overview |
|---|---|
| src/relay/pty-handler.ts | Adds conservative resize-time stale-process retirement, but the new path can silently remove a PTY without publishing its client exit. |
| src/relay/pty-shell-utils.ts | Eliminates per-call pgrep forks, but cached process rows can be stale during event-driven close and cleanup safety checks. |
| src/main/ai-vault/remote-session-parse-cache.ts | Adds a host-scoped, metadata-validated 4096-entry LRU for completed remote session parses. |
| src/main/ai-vault/remote-session-scanner.ts | Routes remote transcript reads and parsing through the new cache while retaining cancellation checks. |
| src/relay/pty-handler-resize-stale-pty.test.ts | Covers stale, unverifiable, and live resize behavior but does not assert client exit publication after stale retirement. |
| src/relay/pty-shell-utils.test.ts | Verifies fork elimination and burst coalescing but does not cover a child starting during the snapshot TTL before a close decision. |
| src/main/ai-vault/remote-session-parse-cache.test.ts | Covers unchanged reuse, metadata invalidation, host isolation, and transient read failures. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A[Relay polling or client action] --> B{Operation}
B -->|Resize PTY| C[Probe owning-host PID]
C -->|Gone| D[Retire PTY record]
C -->|Live or unverifiable| E[Attempt resize]
B -->|Inspect process| F[Read cached process table]
F --> G[Look up direct children]
B -->|Scan AI Vault| H[Stat remote candidate]
H --> I{Host, mtime, and size match cache?}
I -->|Yes| J[Reuse parsed session]
I -->|No| K[Read and parse transcript]
Reviews (1): Last reviewed commit: "fix(relay): stop three CPU growth terms ..." | Re-trigger Greptile
| if (this.reapPtyProvenExited(managed)) { | ||
| return | ||
| } |
There was a problem hiding this comment.
Reaping skips PTY exit publication
When a shell exits without delivering onExit and its visible terminal subsequently resizes, this new probe removes the PTY through reapExitedPty without publishing pty.exit, leaving the pane mounted against a dead session until visibility reconciliation or reconnect.
Knowledge Base Used:
There was a problem hiding this comment.
Fixed — the finding is correct, and correct about the escalation too.
reapExitedPty only called notifyExitListener, which is relay-internal. Nothing reached the client, so a retired record left the pane mounted against a session the relay had already forgotten; the next attach answered PTY "<id>" not found with nothing before it to explain why. It was already reachable from the attach probe, the listing sweep and the post-shutdown sweep, but pty.resize made it user-triggered, so it is this PR's to fix.
reapExitedPty now publishes through the same pendingExitByPty + publishPendingExit path the natural onExit uses, carrying code: -1 — this wire's existing "gone, status unrecoverable" code (ssh-relay-session.ts already publishes it for a dropped lease). The pid is proven absent by ESRCH from the host that owns it, but nothing waited on the shell, so no status exists to report. A guard on exitListenerNotified / an already-queued pending exit keeps onExit's real code from being overwritten or duplicated when the sweep later reaps the same record.
Two tests in pty-handler-resize-stale-pty.test.ts: one asserts the pty.exit notification on the resize-reap path (fails on the pre-fix tree with Received: []), one asserts the listing sweep does not republish an exit onExit already reported with code 7.
| const rows = await getProcessTableSnapshot() | ||
| return (getProcessTableIndex(rows).childrenByPpid.get(pid)?.length ?? 0) > 0 |
There was a problem hiding this comment.
There was a problem hiding this comment.
Fixed, scoped to the paths that actually decide.
processHasChildren now takes { fresh }, and the pty.hasChildProcesses RPC passes it. That RPC exists only to gate destructive decisions — the window-close confirmation (use-terminal-editor-close-foundation.ts) and workspace cleanup's idle evidence (workspace-cleanup-local-evidence.ts) — each of which acts on the answer once. pgrep scanned per call, so anything that decides has to keep scanning per call.
pty.inspectProcess deliberately stays on the TTL-cached table. That is the polled RPC (750 ms/2000 ms per tracked pane, serialized through enqueueAgentProcessInspection), so its calls arrive in separate I/O turns; getFreshProcessTableSnapshot only coalesces same-turn callers, so making it fresh would run one ps per pane per tick — strictly worse than the pgrep fork this change removed, and it would give back the whole 3,501 ms → 65 ms result. A poll can read a 500 ms-old table because its next tick corrects it.
Residual, stated plainly: the tab-close guard (running-terminal-close-guard.ts:137) reaches the relay through inspectProcess, so for an SSH remote pane it can still read a table up to 500 ms old. Closing that needs a fresh flag threaded through the pty.inspectProcess wire, the provider contract, the daemon router and the preload — worth doing, but a different change from this one, and not one to land unreviewed here. Local and runtime-environment panes never touch processHasChildren at all (PtyHandler is relay-only).
Tests: pty-shell-utils.test.ts pins that two ordinary calls share one capture while a { fresh: true } call rescans and sees a child that started inside the TTL; pty-handler-spawn-admission.test.ts pins which RPC asks for which.
There was a problem hiding this comment.
Important
The PTY reaping and pgrep fork removal are solid, but the new remote parse cache drops the Codex-title refresh that the local scanner performs on every reuse — remote Codex sessions will serve stale titles for the sidecar's lifetime. See the inline comment.
Reviewed changes
- PTY liveness probe on resize —
PtyHandler.resizenow reaps entries whose pid the host proves gone before issuing the ioctl, and contains a still-live-but-failing ioctl with a stderr line instead of letting it escape as a parse error. - Unified liveness helper —
reapPtyProvenExitedroutes the three prior inlineisProcessAliveprobes (attach,listProcesses, shutdown reap sweep) through one ESRCH-based helper. - No-fork child check —
processHasChildrenanswers from the shared TTL-cachedpssnapshot (childrenByPpid) instead of forkingpgrep -Pper pane per poll; Windows short-circuits without spawning. - Remote transcript parse cache — a module-scope LRU keyed by path, validated on
(mtimeMs, sizeBytes, hostKey), so unchanged transcripts are never re-read on the 30s forced rescan.
ℹ️ Nitpicks
createRemoteSessionParseStats,RemoteSessionParseStats, and thestatsparameter ofparseRemoteSessionFileCachedare exported but never used — no caller passesstats. Wire it in or drop it.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…#17930) * fix(native-chat): keep the attachments on a Claude turn that pasted images (#17801) * fix(native-chat): keep the attachments on a Claude turn that pasted images A Claude turn carrying pasted images reached native chat with no images at all — no thumbnails on mobile, and not even an attachment chip on desktop. Nothing showed that the message had any. Both carriers were being dropped: - Claude records the paths in a companion turn marked `isMeta`, holding one `[Image: source: <path>]` text block per image. The decoder treats an `isMeta` user row as injected, filters it down to tool-result blocks, and returns null when none remain — so the whole row went away. - The prompt row's own `image` blocks are `{source: {type: 'base64'}}`, which carry no url or path, so `imageRefBlock` drops them too. With the companion gone, `isImageSourceUserTurn` could never fire and the fold in `normalizeImageTranscriptMessages` was unreachable on the Claude path. Surveying every transcript under `~/.claude/projects`: 238 of 241 image-source rows are `isMeta`, across every versioned release (2.1.220 through 2.1.237); the 3 that are not carry no version field at all. 38 of those rows hold more than one content block, which also defeated the single-block rule in `isImageSourceUserTurn`. Let image-source text survive the injected-turn filter, and recognize a turn whose blocks are *all* markers rather than only a lone one. An ordinary injected turn (a skill preamble, a compact summary) is still dropped, and a turn that mixes prose with a marker is still not an image-source turn. Carrying the paths keeps the payload small; decoding the base64 instead would put hundreds of KB per image on the wire to mobile. * fix(native-chat): preserve image companion ordering * fix(native-chat): keep image companions turn-local --------- Co-authored-by: Merge Sim <sim@local> * fix(native-chat): stop unjournaled provider frames from killing the session (#17813) A frame the classifier declines (status-chrome, suppressed-benign, stream-into-item) is deliberately not journaled. #17720 turned that null translation into `{accepted: false, reason: 'untranslated'}`, which is not `backpressure`, so the notification retry queue treated it as unreplayable and escalated through fail() -> forceCloseUnexpected -> connection.close(). The app-server latched `closing` and the create path's next model/list rejected with "codex app-server connection is closed (model/list)". The provider emits `remoteControl/status/changed` right after initialize, so every structured Codex session died on its first chrome frame. Admit the null translation instead, before any bookkeeping or publish. Also restore the error-frame exemption from the generic row cap, dropped by the same PR: the cap now runs after the classification check, so a noisy turn can no longer reduce provider errors to a suppression count. The test that pinned the capped behavior is inverted to assert the exemption. Co-authored-by: Merge Sim <sim@local> * refactor(mobile): split session and terminal surfaces (cherry picked from commit f129f29) * fix(mobile): restore session parity after extraction (cherry picked from commit 47706a5) * chore(mobile): prune stale max-lines overrides (cherry picked from commit be954c3663409116f34ba08658876262733b3f67) * fix(mobile): honor host-follow tab snapshots (cherry picked from commit a4a9c4da19d6967eceb8025dd01480a56261039f) * fix(mobile): keep split session hooks render-pure Documents the pre-existing render-time refs the split relocated onto changed lines, and drops a ref assignment the split added that the monolith never had. * fix(agent-send-target): acknowledge delivery even when picker closes bef (#17835) Delivery callbacks and telemetry belong to the completed send operation, not to the picker instance that launched it. Remove early returns that skipped delivery acknowledgment and success toast when the popover was already closed. * fix(mobile-native-chat): retire an image echo glued with the send beside it (#17783) * fix(mobile-native-chat): retire an image echo glued with the send beside it A message sent with images could render two or three times over, with the copy carrying the photos sorting below the reply that answered it — and it never cleared. A send issued while the agent is mid-turn is glued onto the agent's input line with any send adjacent to it, so the pair lands as one transcript row whose text is the concatenation. Every retirement path then declined the pair: - The image matcher wanted the whole row to equal the echo's text, so a glued row never bound. That also stranded the local preview: the phone's photo never reached the authoritative row. - The exact-count path skips image echoes by design. - The glue path excluded image echoes too, which made one a *barrier* — splitting the run so the text-only send beside it was left alone, and a lone match is rejected as an ordinary landing. So neither echo could ever retire, and the unmatched image echo fell through to the trailing bucket, which is what put it below the reply. Match a glued row in the image matcher, and let an image echo take part in the glue pass once its preview has been rebound. It stays a barrier while unbound, so the existing guarantee is kept: an image echo never retires before its local preview reaches the transcript row, or the photo would disappear. * fix(mobile-chat): require image provenance for glued prefix matches --------- Co-authored-by: Merge Sim <sim@local> * refactor(renderer): split oversized UI surfaces (cherry picked from commit da89be4) * fix(renderer): keep split imports lint-clean (cherry picked from commit c778ac7) * fix(renderer): preserve extracted lifecycle and retention behavior (cherry picked from commit 1731f2a) * chore(max-lines): prune refactored file suppressions (cherry picked from commit 787228e) * fix(status-bar): preserve Git refresh ordering after split (cherry picked from commit e65d298) * fix(lint): preserve TaskPage effect suppressions after split (cherry picked from commit 4a3bc23) * fix(status-bar): preserve workspace-space review and agent freshness (cherry picked from commit 9455e31) * fix(automations): preserve Escape drill-out behavior (cherry picked from commit 790680d) * fix(renderer): restore worktree palette behavior after split (cherry picked from commit 0b78c1c) * style(renderer): format palette project candidates (cherry picked from commit 1e93d66) * refactor(renderer): finish worktree palette extraction (cherry picked from commit ea8e6e5) * fix(renderer): document intentional render-time refs (cherry picked from commit 6fc78dd) * chore(max-lines): prune stale lifecycle baseline (cherry picked from commit 42bf3eb) * fix(renderer): preserve status localization parity (cherry picked from commit 0a802c7) * fix(renderer): preserve floating editor visibility (cherry picked from commit bcf715b) * fix(automations): preserve destination form save semantics (cherry picked from commit a793b07) * fix(renderer): preserve Codex sign-in behavior (cherry picked from commit 81f4803) * fix(renderer): preserve palette create telemetry (cherry picked from commit b13c2b1) * style(renderer): format extracted palette modules * refactor(automations): extract list toolbar and drop dead list projection * fix(lint): drop unused exhaustive-deps suppression after split The split's dependency list no longer trips the rule, so the directive is dead and the changed-code quality gate rejects it. * fix(renderer): document pre-split render-time refs in workspace search Both assignments are verbatim from the pre-split monolith; the split relocated them onto changed lines, which the React Doctor gate scans. * refactor(renderer): split runtime and store modules (cherry picked from commit 207bef0) * fix(renderer): merge split runtime imports (cherry picked from commit 90bf505) * chore(max-lines): prune runtime baseline entries (cherry picked from commit 08820a4) * fix(renderer): preserve accepted visibility snapshots (cherry picked from commit bc5f8a5ac5b8e8ad3fc59250795842e663bad0ee) * refactor(preload): split bridge API modules (cherry picked from commit b77e318) * test(preload): census split GitHub bridge owners (cherry picked from commit cd08e4e) * fix(preload): merge split plugin imports (cherry picked from commit 682ff4f) * chore(max-lines): prune preload baseline entry (cherry picked from commit aad2e1e) * fix(pty,remote): close the pty master fd leak and two remote-terminal defects #8362: node-pty leaves the forkpty()/posix_openpt() master without FD_CLOEXEC, so on Linux every later child of the process -- both later pty children and plain child_process spawns -- inherits it and keeps the /dev/pts device alive. Measured on Linux with stock node-pty 1.1.0: master fd flags 0404002 (cloexec=false), and 17 -> /dev/pts/ptmx present in both a later pty child's /proc/self/fd and a later child_process child's. Extend the existing node-pty patch with pty_cloexec() on both PtyFork spawn paths; after the patch the flags read 02404002 (cloexec=true) and neither child sees the master. This covers the app and terminal daemon only -- the SSH relay installs node-pty from npm on the remote host, so it stays exposed (see the report). #8414: the inspection queue's fire-and-forget `.finally()` chain re-raised a rejecting inspection as a renderer-global unhandledrejection, which an unreachable runtime produced on every cadence tick. #9194: `tab_not_found` is the host's definitive "no such tab", but the close path cleared the close intent for it exactly like a dropped connection, so a host that keeps republishing the dead surface re-materialized the pane the user just closed. Keep that intent and drop its TTL. Also route the banner's "Remote terminal was closed." line through translate() so it stops mixing English into a localized banner. * fix(pty): retire the node-pty master fd instead of probing around it node-pty hands the master to libuv, which closes it on EIO/EOF, but `_close()` never invalidated `_fd` and neither `resize()` nor the `process` getter consulted anything. A late ioctl therefore addressed whatever the kernel had since reissued that number to. On Linux the very next pty gets it: resizing an exited handle silently resized an unrelated live pane, with no error for #17832's probe-retry-classify to observe. Retire `_fd` in the same block that gives up the master and guard both fd-addressed syscalls on it, so a stale handle is unreachable by construction. The relay's resize keeps the isProcessAlive-proven retirement — still the only evidence of `exited` — and drops the re-probe-and-classify arm the ioctl no longer needs. Windows is unaffected: WindowsTerminal.resize goes through the conpty agent and reads no fd. * fix(pty): retire the write stream's fd copy too, and keep the resize re-probe Two gaps in the fd-retirement change. `CustomWriteStream` is the third fd-addressed surface and takes its own plain-number copy of the master at spawn, so `Terminal._fd = -1` never reaches it. Its `dispose()` only cleared a pending immediate, and it was called from `destroy()` alone — the EIO/EOF read-error path and the socket `'close'` path both reach `_close()` without it. A residual `_writeQueue` and an in-flight `fs.write` therefore kept addressing the number after libuv gave it up. Retire the copy and drop the queue in `dispose()`, and call it from `_close()`. Restore the relay's catch-block re-probe. It was never redundant with the patch: libuv closes the fd synchronously inside `uv_close`, before the JS `'close'` that runs `_close()`, so the reuse window opens ahead of any JS guard; and a relay host installs node-pty from npm, where the patch is not applied at all. The re-probe is a `process.kill(pid, 0)` on a path already inside an exception handler. Both existing resize tests pinned liveness with a constant mock, which is why the deletion passed CI invisibly; the new case is alive at the pre-probe and gone by the time the ioctl throws. Also adds the patch's first upstream reference: microsoft/node-pty#220 named this mechanism in 2018 and was closed 2025-12-19 as completed after only improving the error message; #827 is still open. Tracked as #18109. * test(pty): release the live pty before the next fd-reuse case The new Linux write case killed its live pty without awaiting the exit, so that master was still open when the next case spawned. Linux hands out the lowest free descriptor, so the retired pty got N+1 while the leaked N closed during the 400ms settle -- and `does not name a live pty foreground process off the retired descriptor` then saw its live pty take N, failing its own reuse premise by exactly one (`expected 22 to be 23` on CI, reproduced as 19/20 in a container). Test isolation, not a Linux behavior difference: with the descriptor released the case passes 8/8. Await the exit like the resize case above already does, and switch the payload command to `sleep 1` -- the line discipline echoes a leaked write back on its own, so nothing has to read it. Note the constraint on the block so the next case does not repeat it. The premise assertion stays as it is. It compares two observed descriptors, not a hardcoded number; relaxing it to "differs from the retired one" would let both reuse cases pass vacuously on a kernel that never reissues, which is the whole thing they exist to demonstrate. Verified with vitest under node:24-bookworm against a source-built patched node-pty: 7 passed, 8 runs, no flake. Negative check in the same container -- reverting the `_close()` -> `dispose()` hook fails the case with `expected 'leak\r\n' not to contain 'leak'`, so the rewritten assertion is still load-bearing. --------- Co-authored-by: Brennan Benson <[email protected]> Co-authored-by: Merge Sim <sim@local> Co-authored-by: Jinjing <[email protected]>
|
Too many files changed for review (771 files, 100 file limit). |
There was a problem hiding this comment.
⚠️ The pty delta is clean, but I'm withholding approval: the Codex-title staleness finding from the prior review (remote-session-parse-cache.ts:79) is still open and this commit does not touch the ai-vault scanner.
Reviewed changes
- node-pty fd retirement —
_close()now sets_fd = -1and disposesCustomWriteStream, and theresize/processgetter guard on the retired descriptor, so a stale handle is unreachable by construction rather than EBADF-or-reused. - Close-on-exec on pty masters —
pty_cloexec()setsFD_CLOEXECon both the forkpty and posix_spawn paths so later children stop inheriting the master (#8362). - macOS spawn error reporting —
pty_posix_spawnreturns a structuredpty_spawn_errorwith agoto donecleanup, which also fixes the pre-existing off-by-one in thelow_fdscleanup. - Load-bearing tests — fd-reuse and CLOEXEC cases in the pty tests, plus a resize re-probe race case that pins the catch-block retirement.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
ccd3b8d to
030916e
Compare
|
Rebased onto current The branch previously carried a squash of #17930 that had a stale What changed since the last push
|
There was a problem hiding this comment.
✅ No new issues found. The prior Codex-title staleness finding is addressed cleanly with the shared local/remote title-refresh helper, and the freed-relay changes are correct and well-tested.
Reviewed changes
- Remote codex-title refresh on reuse —
parseRemoteSessionFileCachedtakes arefreshReusedSessionhook; codex sources supply one that re-derives the title fromsession_index.jsonlon a cache hit, so an index-only rename surfaces within one scan without re-reading the transcript. - Shared title-refresh helper —
refreshCachedCodexTitle's body was extracted intorefreshCodexTitleFromIndex, so the local and remote reuse paths can't drift. - Reaped exits are published —
reapExitedPtynow emitspty.exit { code: -1 }for a proven-gone pid, guarded against double-publishing node-pty's natural exit. - Fresh rescan for close decisions —
pty.hasChildProcessespasses{ fresh: true }so a destructive close sees a child started inside the poll TTL; the polledpty.inspectProcessstays on the cached snapshot. - Tests — new cases pin the index-only title refresh, the reaped-exit publication, and the no-double-exit guarantee, plus the fresh-vs-cached scan split.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
pty.resize gated only on `managed.disposed`, which is bookkeeping rather than liveness. A shell that exits without node-pty's `onExit` leaves an undisposed entry holding a closed master fd, and UnixTerminal.resize has no fd guard, so the ioctl threw `ioctl(2) failed, EBADF` into the dispatcher's generic parse-error catch. Nothing retired the entry, so it stayed advertised and kept activePtyCount above zero -- which is what stops a relay with an unlimited grace from reaching its idle-no-ptys exit (#12423). Probe liveness with the same helper attach/listProcesses use, retire a provably dead pid, and contain an ioctl failure over a live-or-unverifiable process. processHasChildren forked `pgrep -P` per pane per inspection poll, uncached. procps-ng opens six procfs files per process to resolve one ppid, so each call cost O(host process count). Answer from the TTL-cached `ps` table the same RPC already captured for the foreground lookup (#13537). The remote AI Vault scanner had no parse cache at all, so every forced rescan re-read and re-parsed the whole transcript corpus, including files untouched for a month. Give it the mtime+size keyed memo the local scanner has (#13753).
The remote cache keys on the transcript's (mtime, size, host), but codex titles live in $CODEX_HOME/session_index.jsonl and are written after the rollout — so a cache hit froze the fallback title forever. Mirrors the local scanner's existing reuse-path refresh via a shared core.
…cisions
Two review findings on the CPU work.
reapExitedPty told only the relay-internal exit listener, so a retirement left
the client's pane mounted against a session the relay had already forgotten --
the next attach answered `PTY "<id>" not found` with nothing before it to
explain why. Pre-existing on three probe paths; resize made it user-triggered.
Publish the same pending-exit the natural onExit path publishes, carrying -1
("gone, status unrecoverable"), and skip it when onExit already reported the
real code.
processHasChildren now answers from a 500ms TTL-cached table. That is right for
pty.inspectProcess, which every tracked pane polls, but pty.hasChildProcesses
gates the window-close confirmation and workspace cleanup's idle evidence --
one destructive decision per answer, where a child started inside the window
would be killed unasked. Give that RPC a fresh scan; pgrep used to.
The publication is a verdict the client acts on by retiring the pane, so it must not be reachable from the disposed-record sweep, which retires off our own bookkeeping rather than the host's process table. Only ESRCH earns it.
030916e to
a5b70ff
Compare
|
Rebased onto current Two reasons beyond staying current:
One self-correction on the exit-publication fix. Publishing Re-verified on the rebased tree: Docker SSH lane: 10 passed, 2 skipped, 2 failed, and neither failure is this PR's.
|
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Evidence-gated exit publication —
reapExitedPtynow takes anevidence: 'exited' | 'record-torn-down'parameter, andpublishReapedExitonly runs on'exited'. The listing sweep splits themanaged.disposedbranch (our own bookkeeping, no shell-death verdict) out ofreapPtyProvenExited(proven ESRCH) so a torn-down record can never emit apty.exit { code: -1 }the host did not prove. - Documentation — the
publishReapedExitandreapPtyProvenExitedJSDoc plus the "does not republish" test comment now state the ssh-execution-boundary contract: only ESRCH earns anexitedverdict, and bookkeeping disposal stays silent on the wire while still reachingnotifyExitListener.
The disposition is correct: every disposeManagedPty site already calls notifyExitListener first, so the prior unconditional publish was gated off in practice — this change removes reliance on that invariant and separates the wire verdict from relay-internal bookkeeping, matching docs/reference/ssh-execution-boundary.md. Targeted tests pass (pty-handler-resize-stale-pty, pty-shell-utils: 41 passed).
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
config/patches/[email protected] (1)
58-58: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winPreserve the Windows native targets or remove their runtime paths.
binding.gypdeletesptyandconpty_console_list, butWindowsPtyAgentstill selectsptybelow build 18309 and the non-DLL cleanup agent still loadsconpty_console_list. A source rebuild emits neither addon. Retained prebuilds only mask this when a matching prebuild is available; otherwise WinPTY startup or non-DLL cleanup can fail.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: bc9eeee5-8486-48a2-b773-5c217d0a4ae8
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (14)
config/patches/[email protected]src/main/ai-vault/remote-session-parse-cache.test.tssrc/main/ai-vault/remote-session-parse-cache.tssrc/main/ai-vault/remote-session-scanner-codex-index.tssrc/main/ai-vault/remote-session-scanner-sources.tssrc/main/ai-vault/remote-session-scanner.tssrc/main/ai-vault/session-scanner-codex-cached-title.tssrc/main/ai-vault/session-scanner-parse-cache.tssrc/main/pty/node-pty-master-fd-retirement.test.tssrc/relay/pty-handler-resize-stale-pty.test.tssrc/relay/pty-handler-spawn-admission.test.tssrc/relay/pty-handler.tssrc/relay/pty-shell-utils.test.tssrc/relay/pty-shell-utils.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
| this.agentSessionOwners.release(managed.id) | ||
| disposeManagedPty(managed) | ||
| this.removePty(managed.id) | ||
| this.clearPtyFlowState(managed.id) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Preserve the synthetic exit until publication succeeds.
Line 2263 clears pendingOutputByPty and pendingExitByPty immediately after publishReapedExit. If output is queued due to source or legacy backpressure, publishPendingExit defers the code: -1 exit. This cleanup then deletes it before a capacity callback can retry publication. The client can remain mounted on a session that the relay has retired.
Keep pending output and the pending exit through normal drain, as the physical onExit path does. Clear only non-delivery state during reaping.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Restored dropped i18n key — the rebase had dropped the
activityOptionskey fromen.json, whichactivity-thread-options-menu.tsx:104still references; it is restored, and the missing trailing comma onshowChildAgentsis fixed.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Restored dropped i18n keys in
en.json— the rebase droppeddashboard.sidebar.openActivityanddashboard.sidebar.closeActivity, whichSidebarHeader.tsx:41still references; both are restored and the missing trailing comma ondashboardLabelis fixed, completing the rebase repair begun by the prioractivityOptionsrestore.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…ll scan storms (stablyai#17832) * fix(relay): stop three CPU growth terms in a long-running remote session pty.resize gated only on `managed.disposed`, which is bookkeeping rather than liveness. A shell that exits without node-pty's `onExit` leaves an undisposed entry holding a closed master fd, and UnixTerminal.resize has no fd guard, so the ioctl threw `ioctl(2) failed, EBADF` into the dispatcher's generic parse-error catch. Nothing retired the entry, so it stayed advertised and kept activePtyCount above zero -- which is what stops a relay with an unlimited grace from reaching its idle-no-ptys exit (stablyai#12423). Probe liveness with the same helper attach/listProcesses use, retire a provably dead pid, and contain an ioctl failure over a live-or-unverifiable process. processHasChildren forked `pgrep -P` per pane per inspection poll, uncached. procps-ng opens six procfs files per process to resolve one ppid, so each call cost O(host process count). Answer from the TTL-cached `ps` table the same RPC already captured for the foreground lookup (stablyai#13537). The remote AI Vault scanner had no parse cache at all, so every forced rescan re-read and re-parsed the whole transcript corpus, including files untouched for a month. Give it the mtime+size keyed memo the local scanner has (stablyai#13753). * fix(pty): invalidate the descriptor when node-pty gives up the handle (stablyai#17930) Carried forward from PR stablyai#17930, which merged into this branch. Rebased onto current main; main's newer node-pty-fd-leak test is kept as-is. * fix(ai-vault): refresh codex titles on the remote parse-cache reuse path The remote cache keys on the transcript's (mtime, size, host), but codex titles live in $CODEX_HOME/session_index.jsonl and are written after the rollout — so a cache hit froze the fallback title forever. Mirrors the local scanner's existing reuse-path refresh via a shared core. * fix(relay): publish the exit a reap performs, and rescan for close decisions Two review findings on the CPU work. reapExitedPty told only the relay-internal exit listener, so a retirement left the client's pane mounted against a session the relay had already forgotten -- the next attach answered `PTY "<id>" not found` with nothing before it to explain why. Pre-existing on three probe paths; resize made it user-triggered. Publish the same pending-exit the natural onExit path publishes, carrying -1 ("gone, status unrecoverable"), and skip it when onExit already reported the real code. processHasChildren now answers from a 500ms TTL-cached table. That is right for pty.inspectProcess, which every tracked pane polls, but pty.hasChildProcesses gates the window-close confirmation and workspace cleanup's idle evidence -- one destructive decision per answer, where a child started inside the window would be killed unasked. Give that RPC a fresh scan; pgrep used to. * fix(relay): publish a reap's exit only on proven-exited evidence The publication is a verdict the client acts on by retiring the pane, so it must not be reachable from the disposed-record sweep, which retires off our own bookkeeping rather than the host's process table. Only ESRCH earns it. * fix(i18n): restore the activity-options key the rebase dropped * fix(i18n): union en.json with main so the rebase cannot drop keys

Three long-session relay defects. Each has a test that fails before and passes after; both outputs below.
#12423 — a resize ioctl against a closed fd, and the entry that never dies
PtyHandler.resize(pty-handler.ts:2056) gated only onmanaged.disposed, which is bookkeeping ("we tore the record down"), not liveness. The relay's own code documents the gap twice —:1941"verify liveness because shells can exit without node-pty onExit" and:2377"an unverified entry advertised that session forever."When a shell exits without
onExit, the entry stays inthis.ptyswithdisposed === falsewhile node-pty has already closed the master fd.node-pty/lib/unixTerminal.js:253-259has no fd guard, so the ioctl throwsioctl(2) failed, EBADFout of the notification handler and into the dispatcher's generic catch (dispatcher-frame-codec.ts:29-35) — which is exactly why the reporter's log saysParse error: ioctl(2) failed, EBADF. That catch logs and does nothing.Nothing retires the entry, so it stays advertised as live and keeps
activePtyCount > 0. That is the load-bearing consequence:relay-grace-lifecycle.ts:65,88andrelay-grace-branch.ts:114-119key the idle-exit branch onactivePtyCount === 0, so withrelayGracePeriodSeconds: 0a relay pinned by dead entries never reaches its idle exit — the "wedged relay never exits" and "ptys=4stays at 4 no matter how many tabs I open" complaints.Fix:
reapPtyProvenExitedretires only onisProcessAlivereturning ESRCH-false — positive evidence of absence from the host that owns the process.resizeprobes before the ioctl and re-probes if it still throws; a provably dead pid is retired, anything else staysunverifiable, keeps its record and owner claim, and is contained with a stderr line. Perssh-execution-boundary.md, a failed ioctl observes the handle, not the host's process table, so it is never on its own treated asexited. The three other inline liveness probes were routed onto the same helper so the four cannot drift.Caveat, stated plainly: the use-after-free, the EBADF escape path and the never-retired entry are all proven. A literal 95%-CPU spin from this path was not reproduced, and the resize throw alone should not produce one —
FrameDecoder.drainTurnis bounded per turn andhandleFramecatches. The read is that the reporter's "spin" and "never exits" are the same stale-entry cause seen from two angles, plus #13537's separatepgrepstorm. Fixed at the lifecycle level; if a spin persists it is a different defect and needs re-measuring.#13537 — the title is a misnomer; the relay never scans ctty, it forks something that does
processHasChildren(pty-shell-utils.ts:177) forkedpgrep -P <pid>with no cache, no TTL, no in-flight coalescing, once perpty.inspectProcess— which every tracked pane polls at 750ms/2000ms up to a global 8/s cap. procps-ng opens six procfs files per process to resolve one ppid, including/proc/<pid>/ctty, which never exists on Linux. One call cost ~4,100 opens on the reporter's 690-process host.The sibling
psscan is already TTL-cached at 500ms; this fork was the one uncapped term riding alongside it. Fix: answer from the shared cached table the same RPC already captured —getProcessTableIndex(rows).childrenByPpid.get(pid). Zero forks; a burst of panes collapses to onepsper 500ms window. Windows returnsfalsewithout spawning, identical to before (where the fork always failed).#13753 — the relay scanner had no parse cache at all
session-scanner-parse-cache.ts(mtime+size keyed, 4096-entry LRU) is wired only into the local desktop scanner. The relay sidecar'sparseRemoteSessionCandidate(remote-session-scanner.ts:220-232) did an unconditionalreadFile+ full parse per candidate — up to 2000 whole-file reads per pass plus 1000 for scope backfill. Its only memo,titleCaches: new Map()at:60, is allocated per call and discarded on return. The 30s cadence is a renderer throttle whoseforce: truebypasses every result cache in between, and the sidecar survives 10 idle minutes — so a cache placed there would span every tick; there just wasn't one.Fix: a module-scope LRU keyed by path, validated on
(mtimeMs, sizeBytes, hostKey).(mtime, size)is sound because discovery already folds a source'scontentDependencyPathstat into both, so a metadata-only transcript whose companion changed still looks changed. The read is inside the cached parse, so an unchanged transcript is never pulled off disk. Only completed parses are stored, so a transient failure cannot pin a wrong answer. The 30s interval was not widened — the root fix is not re-reading, not polling less.Verification
pty-handler-revive.test.ts > scopes HISTFILE past the wsl.exe wrapperfailed once in a combined run; it is pre-existing flake, passing in isolation both with and without these changes, and the stashed-fix baseline showed it green.Follow-ups found, deliberately not done
FORCED_SCAN_PREEMPT_AFTER_MS = 5_000and the comment atsession-scanner-parse-cache.ts:172both still claim a ~5s forced rescan; it is 30s now.lstats every file in the corpus before any recency filter — so the per-pass syscall floor still grows with corpus size even though read/parse cost no longer does.Fixes #12423, #13537, #13753
ELI5
Three things made the remote helper burn CPU forever: resizing a terminal whose process had already died, forking a process-tree lookup on every poll, and re-reading every agent transcript on disk every 30 seconds.
User-facing regression risk