Repository navigation
Implement PtySessionManager and PtySession (closes #1118) - #1144
Conversation
Add the Rust-side engine for ADR-032: PTY-based agent sessions.
PtySession owns one external agent process attached to a pseudo-terminal,
and PtySessionManager owns the collection of active sessions.
packages/agent/src/pty/
- session.rs: PtySession with launch/subscribe_output/write_input/
resize/terminate. Uses portable-pty for cross-platform PTY support.
Each session gets a tempfile::TempDir, GraphContextAssembler writes
CLAUDE.md/AGENTS.md into it, the binary spawns with cwd = temp dir.
Stdout/stderr stream out through broadcast::Sender<OutputChunk>;
a separate broadcast::Sender<ExitStatus> fires on child exit.
The exit-watcher task owns the portable_pty::Child exclusively so
it can block in wait() without holding any lock terminate() needs;
terminate signals the kill through a separately-cloned ChildKiller.
This avoids the obvious deadlock of kill waiting on a mutex the
wait-loop already holds.
- manager.rs: PtySessionManager with launch/get/terminate/list,
backed by Arc<Mutex<HashMap<Uuid, Arc<PtySession>>>>. Each
insert spawns a small task that prunes the session out of the
map when the natural-exit broadcast fires, so the temp dir
cleans up on its own when the agent process exits.
Unit tests (10, all passing) cover launch, write_input echo via cat,
resize, terminate of a long-running sleep, natural-exit cleanup,
manager insert/list/get/terminate, and the natural-exit auto-prune
path. Tests use sh/cat from PATH so they do not depend on a real
agent binary being installed.
.gitignore: add **/src/pty/session.rs to the allowlist (the existing
`session*.rs` debug-artifact ignore rule was matching this file).
Cargo: add portable-pty 0.8 and promote tempfile 3 from dev-dep to
dep (PtySession holds a TempDir as a real field, not just in tests).
Verified:
- cargo test -p nodespace-agent --lib: 245 passed (235 prior + 10 new)
- cargo clippy -p nodespace-agent --all-targets -- -D warnings: clean
- cargo check --workspace: clean
- frontend test baseline unchanged: 3918/3918
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude <[email protected]>
malibio
left a comment
There was a problem hiding this comment.
Code Review Summary
Solid implementation of ADR-032's PTY engine. The core lifecycle (temp dir → context file → PTY spawn → broadcast → cleanup) is clean, the module boundary is right, and the documented deadlock-free design between terminate() and the exit-watcher checks out: the watcher uniquely owns Box<dyn Child> and blocks in wait() without touching any session lock, while terminate() signals through a separately-cloned ChildKiller. The 10 new tests cover the happy paths competently.
That said, there are two real concurrency bugs hiding in the exit-broadcast plumbing, both involving the single-shot broadcast::channel::<ExitStatus>(1) and the fact that a broadcast channel does not deliver values to subscribers that subscribed after the send. The current tests don't expose them because they all happen to subscribe before the send wins the race, but production usage will.
All listed acceptance criteria are met functionally. The author's two flagged spec deviations (terminate(&self) and the new subscribe_exit/ExitStatus types) are well-justified. One additional unflagged deviation: spec says terminate() sends SIGTERM; portable_pty::ChildKiller::kill() sends SIGHUP on Unix (and TerminateProcess on Windows). Worth knowing, probably not worth changing.
Findings
🔴 Critical / Blocker
packages/agent/src/pty/session.rs:270-296 — terminate() hangs forever if the child has already exited.
broadcast::channel::<ExitStatus>(1) is single-shot — the watcher calls exit_tx.send(status) exactly once. Per tokio::sync::broadcast semantics, subscribers created after a send() do not receive that value; they only receive subsequent sends. terminate() subscribes at line 275, then issues kill() at line 282 (no-op / Err if the child is already gone), then awaits exit_rx.recv() at line 290.
If the child has already exited naturally before terminate() is called:
- The watcher fired its single
send()some time ago; the value is gone. - The session still owns
exit_tx, so the receiver is notClosed. kill()returns an error which the code swallows.exit_rx.recv()blocks forever — no further send will ever come.
The manager's terminate(&self, id) removes the entry from the map first (line 100-102), so the typical caller path is safe (the natural-exit watcher will have removed it already, returning Ok(false) before PtySession::terminate is ever called). But any direct caller — and the next gRPC handler issue is almost certainly going to be such a caller — gets a hang. The test terminate_kills_long_running_process only covers the live-child case; there is no test for terminate-after-natural-exit.
Two reasonable fixes:
- Track exit state in an
Arc<tokio::sync::OnceCell<ExitStatus>>(orArc<Mutex<Option<ExitStatus>>>) populated by the watcher;terminate()checks the cell first and only awaits the broadcast if it's empty. Subscribers get the same guarantee. - Or: use
tokio::sync::watchinstead ofbroadcastfor exit (always delivers the latest value to new subscribers). This also fixes Finding #2 below.
packages/agent/src/pty/manager.rs:64-84 — auto-prune watcher can leak the session entry for short-lived processes (same root cause).
insert() calls session.subscribe_exit() at line 66, then moves the session into an Arc, then inserts and spawns the auto-prune task at line 77. The exit-watcher task started inside PtySession::spawn_in_pty is independent of all of this — it may have already called exit_tx.send() before line 66 runs (e.g. sh -c "echo bye" exits in microseconds; the watcher thread can win the race against the caller getting back from launch().await).
If that send happens before subscribe_exit() at line 66, the auto-prune task's receiver will never see a value. recv() only unblocks on Closed, which requires the session (and thus exit_tx) to be dropped — but the only thing that drops the session is the auto-prune itself removing the last Arc from the map. Circular: the task hangs forever, the session never leaves the map, the temp dir is never cleaned up.
The test natural_exit_auto_removes_session does hit this path with echo bye and currently passes — presumably the broadcast send loses the scheduling race in this configuration, but that's not something to rely on. The fix is the same as Finding #1: a watch channel or an explicit Option<ExitStatus> slot the watcher fills, so a late subscriber can still observe that the child has exited.
(There's also a smaller issue worth a comment if you don't redesign: let _ = exit_rx.recv().await; discards the result, so if the recv ever returns Closed for some legitimate reason in the future it'll silently no-op. Match the result and log.)
🟡 Improvement
packages/agent/src/pty/session.rs:122-218 — dropping a PtySession without calling terminate() leaks the child process.
PtySession::Drop is implicit: child_killer is dropped (no kill), the master is dropped (PTY half-closes), _session_dir is dropped (temp dir deleted while child may still have cwd in it), and the watcher task keeps wait()-ing on a child that's still alive. The reader task keeps trying to drain the PTY into a broadcast with no receivers. The child eventually exits on its own at some indeterminate time.
The PtySessionManager API funnels callers through terminate(&self, id), which is correct, but any code path that constructs a PtySession directly (launch_for_test, future code, the in-tree call sites if the manager is ever bypassed) is one early-return away from leaking a process. Two options:
- Implement
Dropthat fires the kill and detaches (best-effort, noawait). - Document this as a hard invariant on the type ("must be terminated before drop") and consider making the unique-owner pattern enforce it.
Given the manager is the only intended API surface, this is improvement-level not blocking, but it's a foot-gun for the gRPC handler implementer.
packages/agent/src/pty/session.rs:122-157 and manager.rs:52-60 — anyhow::Error collapses typed failure modes the gRPC layer will want back.
Three distinct failure classes here — ContextError (graph/IO writing the context file), which::Error (binary not on PATH), portable_pty::Error / io::Error (PTY spawn) — get flattened into anyhow::Error. The next issue (gRPC handler) is going to want to map these to different gRPC status codes (FAILED_PRECONDITION for missing binary, INTERNAL for PTY failure, etc.) and will have to string-match or downcast.
Recommendation: define a thiserror-based LaunchError enum in pty/mod.rs with variants for each failure class, and keep anyhow only for genuinely opaque errors. The crate already has thiserror as a workspace dep and uses it elsewhere (ContextError). Not blocking for this PR, but cheaper to do now than after callers proliferate.
packages/agent/src/pty/session.rs:329-389 — test-only launch_for_test duplicates 40 lines of spawn_in_pty.
launch_for_test and spawn_in_pty differ only in (a) skipping the assembler/registry steps and (b) hardcoding AgentType::ClaudeCode. The PTY open / spawn / channel-wire-up boilerplate is copy-pasted. If you keep this shape it's fine, but a tiny refactor — accept a pre-built CommandBuilder and TempDir in a private helper used by both — would prevent the two from drifting (e.g. if you later add a kill-on-drop fix to one, you have to remember the other).
🟢 Nits
-
packages/agent/src/pty/session.rs:270—terminate()docs say "sends SIGTERM";portable_pty::ChildKiller::kill()actually sends SIGHUP on Unix andTerminateProcesson Windows (verified in portable-pty 0.8.1 source). Issue #1118's spec also says SIGTERM. Either fix the doc/spec to say "sends a kill signal (SIGHUP on Unix)" or, if SIGTERM is actually desired (graceful shutdown), bypassChildKillerandlibc::kill(pid, SIGTERM)directly behindcfg(unix). Most agents will handle either fine, so I'd just fix the doc. -
packages/agent/src/pty/session.rs:438-550— all 5 session tests and 4 manager tests rely onwhich::which("sh")/which::which("cat"). Fine on Unix CI; tests will be skipped/fail on Windows runners. Issue #1118 explicitly lists Windows as a non-goal, so this is acceptable, but worth a#[cfg(unix)]attribute on the test module so the intent is explicit rather than implicit-by-PATH-failure. -
packages/agent/src/pty/session.rs:316-318— comment says "keep draining the PTY so the kernel buffer does not fill and block the child" — good comment, this is a real concern and easy to forget. No change needed. -
packages/agent/src/pty/manager.rs:117—.map(|s| SessionMetadata::from_session(s))could be.map(SessionMetadata::from_session)for one less line. Pure taste. -
packages/agent/src/pty/session.rs:108—_session_dir: tempfile::TempDir— the leading underscore disables the unused-warning, but the field is used (itsDropdoes the cleanup). Conventionally, this is fine for "lives only for its Drop side effect" but reading the type at line 108 then searching for usages misleads. A short comment// Held only for Drop-side-effect cleanupnext to the field would help future readers. (Currently the rationale is at lines 14-16 of the module docs, just not next to the field.) -
Missing tests worth adding now, all small:
terminate()after natural exit (would have caught Finding #1).subscribe_exit()after exit, no prior subscriber (would have caught Finding #2).terminate()called twice on the same session.- Concurrent
write_input+resize(just to lock in that the split betweenwriterlock andmasterlock is intentional).
Recommendation
Request changes on the two 🔴 findings before merge. They share a root cause (broadcast-of-1 with no late-delivery), so a single redesign — replace broadcast::Sender<ExitStatus> with tokio::sync::watch::Sender<Option<ExitStatus>>, or an Arc<OnceCell<ExitStatus>> plus a Notify — fixes both. Add the two corresponding tests. Everything else (🟡 / 🟢) can be follow-up PRs; the implementation is otherwise a net improvement and should ship soon.
Replaces `broadcast::Sender<ExitStatus>` with `watch::Sender<Option<ExitStatus>>` for the child-exit signal in `PtySession`. The previous design had two real concurrency bugs the reviewer caught (PR #1144 review findings 1 & 2): 1. `terminate()` could hang forever if the child had already exited before the call — the broadcast send had already happened, the late subscriber would never receive it, and the channel would not close while the session still held `exit_tx`. 2. The manager's auto-prune watcher had the same shape: for very short-lived processes, the exit watcher could send before `insert()` subscribed, leaving the entry pinned in the map until the session itself dropped (circular). The `watch` channel latches the final value, so subscribers always observe the exit status — whether they subscribed before or after the child died. `PtySession::terminate()` now fast-paths if the latched value is already `Some(_)`, and otherwise loops on `changed()` until the value transitions. New `exit_status()` accessor surfaces the latched value to callers that want a non-blocking check. Also addresses lower-severity review feedback: - Doc-fix: `terminate()` sends SIGHUP on Unix (not SIGTERM as the previous comment / issue spec said). Confirmed in portable-pty 0.8.1 source at src/lib.rs:316. Updated the doc; behaviour stays on `ChildKiller::kill()` since most agent CLIs treat either as a clean shutdown signal. - `#[cfg(unix)]` on both pty test modules — tests rely on `sh`/`cat`/ `true` from PATH, which is acceptable per ADR-032's "Windows is a non-goal for initial impl" note. Making the platform gate explicit is better than implicit-by-PATH-failure. - Field comment on `_session_dir: tempfile::TempDir` noting it lives only for its Drop side effect (rationale was previously only in module-level docs). New tests (5): - `terminate_after_natural_exit_returns_immediately` (regression #1) - `subscribe_exit_after_exit_observes_status` (regression #2) - `ultra_short_lived_processes_are_pruned` (manager-side #2 regression with 10x `true` to make the race more likely) - `terminate_is_idempotent` (terminate-twice safety) - `concurrent_write_and_resize_do_not_deadlock` (locks the intent of the separate writer-vs-master lock split) Total: pty test count 10 → 15, all passing. Crate total 245 → 250. Skipped review items, with reasoning: - 🟡 Drop impl for PtySession: manager is the only API surface; fire-and-forget from sync Drop adds complexity for a hypothetical caller. Revisit if/when a direct constructor emerges. - 🟡 thiserror LaunchError enum for gRPC mapping: speculative API design before the gRPC handler (next issue) exists. Let that issue's author shape the typed error around their actual tonic::Status mapping rather than guessing now. - 🟡 De-dup launch_for_test vs spawn_in_pty: ~25 real duplicate lines, test-only path. A shared helper saves little and adds an indirection. Skip until they actually drift. - 🟢 .map(SessionMetadata::from_session) vs |s| ...: tried it; the point-free form needs an extra `.as_ref()` because the iterator yields `&Arc<PtySession>` and the fn takes `&PtySession`. The closure version is cleaner; leaving it. Verified: - cargo test -p nodespace-agent --lib pty:: : 15 passed - cargo clippy -p nodespace-agent --all-targets -- -D warnings: clean 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]>
Review feedback addressed — commit 62a61f3Critical findings (both fixed)🔴 #1: Both shared a root cause —
Regression tests added:
Nits addressed
Additional tests (defensive, beyond the two regressions)
Skipped, with reasoning
Verified
|
malibio
left a comment
There was a problem hiding this comment.
Review Type: Re-Review
Previous Review Summary
- Prior findings: 2 critical, 3 improvements, 2 nits.
- Addressed: both critical (via single
tokio::sync::watchredesign), 3 nits (SIGHUP doc,cfg(all(test, unix)),_session_dircomment). - Skipped with justification: 3 improvements (
Dropimpl,thiserrorLaunchError, deduplaunch_for_test/spawn_in_pty) and 1 nit (point-freefrom_session). All skip rationales hold up —Dropis genuinely complex for sync-from-async fire-and-forget when the manager is the only API surface;LaunchErroris speculative until the gRPC handler issue lands; the test-only dedup is a wash at ~25 LOC; and the point-free closure form actually requires an extra.as_ref()because the iterator yields&Arc<PtySession>. - New issues introduced by the fix: none.
Verification of the Critical Fixes
Finding #1 (terminate hangs after natural exit): Fixed correctly. terminate() subscribes first, then fast-paths via borrow().is_some() (session.rs:297), then kills, then loops on changed() with a defensive borrow().is_some() check inside the loop. The watch channel latches the final Some(_), so a late subscriber always observes it.
Finding #2 (manager auto-prune misses fast exits): Fixed correctly. The new task in manager.rs:79-92 does the same fast-path-then-changed() pattern. Walked through the natural-exit-before-subscribe race mentally — there is no window where the value can transition unobserved, because watch::Receiver tracks its own version cursor from subscribe() time and changed() resolves immediately if the current value version is newer.
Sender-drop reasoning in terminate() is sound: self.exit_tx is owned by the PtySession struct, and terminate(&self) holds an exclusive borrow on the session, so the sender cannot be dropped mid-call. The if changed().await.is_err() { return Ok(()) } branch is defensive but provably unreachable through the public Arc<PtySession> API — the comment correctly notes this. Fine to keep as a safety net.
The inner if is_some() break in the manager loop is technically redundant because watch does not produce spurious changed() notifications and the value only ever transitions None → Some once. Harmless defense in depth — not worth flagging.
Test Quality
subscribe_exit_after_exit_observes_statusis a real regression test. Under the oldbroadcast::channel(1)design, aReceivercreated viasubscribe()after the singlesend()would start at the current tail position and not see the prior message — the test would hang/timeout. Thewatchredesign is exactly what makeslate_rx.borrow()returnSome(_)here.ultra_short_lived_processes_are_prunedis also a real regression test. With 10×trueand the old broadcast race, at least one entry would plausibly leak in the map. Thewait_for_len(0, 3s)would fail. The new latched-value design guarantees the auto-prune task sees the exit.terminate_after_natural_exit_returns_immediatelydirectly exercises finding #1's bug.terminate_is_idempotentandconcurrent_write_and_resize_do_not_deadlockare appropriate hardening additions.- The
await_exithelper cleanly factors the "loop onchanged()until latched" pattern across all tests.
Other Observations
The concurrent_write_and_resize_do_not_deadlock test constructs Arc::new(PtySession::launch_for_test(...)) directly, bypassing the manager. This is exactly the "direct constructor" shape the author cited when skipping the Drop impl. Since launch_for_test is pub(crate) and test-only, this is not a public-API hazard — just a test pattern — and the skip rationale still holds for production code.
Findings
None.
Final Recommendation
APPROVE (posted as comment because GitHub blocks self-approval on own PRs). Both critical findings are fixed by a clean architectural redesign (broadcast → watch). Regression tests demonstrably cover the original bugs. Documentation and platform gating nits addressed. Skip rationales for the deferred improvements are defensible for a pre-release codebase. Nothing else worth flagging in the new diff.
* Implement PtySessionManager and PtySession (closes #1118) Add the Rust-side engine for ADR-032: PTY-based agent sessions. PtySession owns one external agent process attached to a pseudo-terminal, and PtySessionManager owns the collection of active sessions. packages/agent/src/pty/ - session.rs: PtySession with launch/subscribe_output/write_input/ resize/terminate. Uses portable-pty for cross-platform PTY support. Each session gets a tempfile::TempDir, GraphContextAssembler writes CLAUDE.md/AGENTS.md into it, the binary spawns with cwd = temp dir. Stdout/stderr stream out through broadcast::Sender<OutputChunk>; a separate broadcast::Sender<ExitStatus> fires on child exit. The exit-watcher task owns the portable_pty::Child exclusively so it can block in wait() without holding any lock terminate() needs; terminate signals the kill through a separately-cloned ChildKiller. This avoids the obvious deadlock of kill waiting on a mutex the wait-loop already holds. - manager.rs: PtySessionManager with launch/get/terminate/list, backed by Arc<Mutex<HashMap<Uuid, Arc<PtySession>>>>. Each insert spawns a small task that prunes the session out of the map when the natural-exit broadcast fires, so the temp dir cleans up on its own when the agent process exits. Unit tests (10, all passing) cover launch, write_input echo via cat, resize, terminate of a long-running sleep, natural-exit cleanup, manager insert/list/get/terminate, and the natural-exit auto-prune path. Tests use sh/cat from PATH so they do not depend on a real agent binary being installed. .gitignore: add **/src/pty/session.rs to the allowlist (the existing `session*.rs` debug-artifact ignore rule was matching this file). Cargo: add portable-pty 0.8 and promote tempfile 3 from dev-dep to dep (PtySession holds a TempDir as a real field, not just in tests). Verified: - cargo test -p nodespace-agent --lib: 245 passed (235 prior + 10 new) - cargo clippy -p nodespace-agent --all-targets -- -D warnings: clean - cargo check --workspace: clean - frontend test baseline unchanged: 3918/3918 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> * Address review: latch exit status via tokio::sync::watch (PR #1144) Replaces `broadcast::Sender<ExitStatus>` with `watch::Sender<Option<ExitStatus>>` for the child-exit signal in `PtySession`. The previous design had two real concurrency bugs the reviewer caught (PR #1144 review findings 1 & 2): 1. `terminate()` could hang forever if the child had already exited before the call — the broadcast send had already happened, the late subscriber would never receive it, and the channel would not close while the session still held `exit_tx`. 2. The manager's auto-prune watcher had the same shape: for very short-lived processes, the exit watcher could send before `insert()` subscribed, leaving the entry pinned in the map until the session itself dropped (circular). The `watch` channel latches the final value, so subscribers always observe the exit status — whether they subscribed before or after the child died. `PtySession::terminate()` now fast-paths if the latched value is already `Some(_)`, and otherwise loops on `changed()` until the value transitions. New `exit_status()` accessor surfaces the latched value to callers that want a non-blocking check. Also addresses lower-severity review feedback: - Doc-fix: `terminate()` sends SIGHUP on Unix (not SIGTERM as the previous comment / issue spec said). Confirmed in portable-pty 0.8.1 source at src/lib.rs:316. Updated the doc; behaviour stays on `ChildKiller::kill()` since most agent CLIs treat either as a clean shutdown signal. - `#[cfg(unix)]` on both pty test modules — tests rely on `sh`/`cat`/ `true` from PATH, which is acceptable per ADR-032's "Windows is a non-goal for initial impl" note. Making the platform gate explicit is better than implicit-by-PATH-failure. - Field comment on `_session_dir: tempfile::TempDir` noting it lives only for its Drop side effect (rationale was previously only in module-level docs). New tests (5): - `terminate_after_natural_exit_returns_immediately` (regression #1) - `subscribe_exit_after_exit_observes_status` (regression #2) - `ultra_short_lived_processes_are_pruned` (manager-side #2 regression with 10x `true` to make the race more likely) - `terminate_is_idempotent` (terminate-twice safety) - `concurrent_write_and_resize_do_not_deadlock` (locks the intent of the separate writer-vs-master lock split) Total: pty test count 10 → 15, all passing. Crate total 245 → 250. Skipped review items, with reasoning: - 🟡 Drop impl for PtySession: manager is the only API surface; fire-and-forget from sync Drop adds complexity for a hypothetical caller. Revisit if/when a direct constructor emerges. - 🟡 thiserror LaunchError enum for gRPC mapping: speculative API design before the gRPC handler (next issue) exists. Let that issue's author shape the typed error around their actual tonic::Status mapping rather than guessing now. - 🟡 De-dup launch_for_test vs spawn_in_pty: ~25 real duplicate lines, test-only path. A shared helper saves little and adds an indirection. Skip until they actually drift. - 🟢 .map(SessionMetadata::from_session) vs |s| ...: tried it; the point-free form needs an extra `.as_ref()` because the iterator yields `&Arc<PtySession>` and the fn takes `&PtySession`. The closure version is cleaner; leaving it. Verified: - cargo test -p nodespace-agent --lib pty:: : 15 passed - cargo clippy -p nodespace-agent --all-targets -- -D warnings: clean 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <[email protected]> --------- Co-authored-by: Michael Libio <[email protected]> Co-authored-by: Claude <[email protected]>
Closes #1118.
Summary
Adds the Rust-side engine for ADR-032: PTY-based agent sessions. Everything else
(gRPC handler, Tauri UI, CLI) depends on this layer working correctly.
packages/agent/src/pty/session.rs—PtySessionowns one external agentprocess attached to a pseudo-terminal. Methods:
launch,subscribe_output,subscribe_exit,write_input,resize,terminate. Each session has itsown
tempfile::TempDir;GraphContextAssemblerwritesCLAUDE.md/AGENTS.mdinto it and the binary spawns with
cwd= temp dir. Stdout/stderr streamthrough
broadcast::Sender<OutputChunk>; child exit fans out through aseparate
broadcast::Sender<ExitStatus>.packages/agent/src/pty/manager.rs—PtySessionManagerowns the collection,backed by
Arc<Mutex<HashMap<Uuid, Arc<PtySession>>>>. Eachinsertspawns atask that prunes the session from the map when the exit broadcast fires, so
the temp dir cleans up on its own when the agent exits naturally.
Key design decisions
Bytes, not strings, on the output stream (
OutputChunk.data: Vec<u8>).PTY output can split UTF-8 sequences mid-byte and carries terminal escape
codes. Higher layers render the stream like a terminal would.
Deadlock-free terminate. The exit-watcher task owns the
portable_pty::Childexclusively so it can block in
wait()without holding any lockterminate()needs.
terminate()signals the kill through a separately-clonedChildKiller,avoiding the obvious deadlock where kill waits on a mutex the wait-loop holds.
Subscribe-before-kill in
terminateto avoid racing the watcher: if wesubscribed after sending the kill, a fast exit could broadcast and close
before we ever called
subscribe(), leaving us hanging on a closed channel.Temp dir lives in the session struct, so it auto-cleans on drop — both
paths (explicit
terminate, natural exit pruning) end with the managerreleasing its
Arc, which drops the session, which drops theTempDir.Test plan
cargo test -p nodespace-agent --lib— 245 passed (235 prior + 10 new pty tests)cargo clippy -p nodespace-agent --all-targets -- -D warnings— cleancargo check --workspace— cleanbun run test(frontend) — 3918/3918 passed (baseline unchanged)bun run quality:fix(eslint + svelte-check) — 0 errors, 0 warningsNew PTY tests (
packages/agent/src/pty/)Session tests use
sh/catfromPATHso they do not depend on a real agentbinary being installed.
launch_for_test_runs_command_and_emits_output—echoround-trips through the PTYwrite_input_is_echoed_back_through_pty—catechoes stdin back via the streamresize_does_not_error— resize before and during a running processterminate_kills_long_running_process—sleep 30ends within 3s of terminatenatural_exit_keeps_temp_dir_until_session_drops— temp dir lifetime matches session lifetime, not process lifetimeinsert_then_list_returns_metadata— manager round-trip withSessionMetadataterminate_removes_session_and_returns_true— explicit terminate pathterminate_unknown_returns_false— terminate on stale idnatural_exit_auto_removes_session— exit watcher prunes the mapget_returns_session_and_supports_write_resize—Arc<PtySession>fromget()is fully usableAcceptance criteria (from #1118)
PtySessionManagerholds all active sessions; supports concurrent accessPtySession::launch()creates a temp dir, writes context viaGraphContextAssembler, spawns the agent in a PTYbroadcast::Sender<OutputChunk>write_input(data: &[u8])sends bytes to PTY stdinresize(cols: u16, rows: u16)resizes the PTYterminate()signals the child and cleans up the temp directorylist_sessions()(namedlist()here) returns metadata for all active sessionscargo test -p nodespace-agentpasses (the issue body wrote-p agent, which is a typo — the crate name isnodespace-agent)bun run quality:fixDeviations from the spec
terminate()takes&selfinstead ofself. The manager hands outArc<PtySession>fromget(), so consumingselfwould require eitherArc::try_unwrap(fragile under concurrentget()callers) or a fallback path. Taking&selfis simpler and equivalent: the temp dir still drops when the lastArcis dropped — usually right afterterminate()returns, when the manager removes its entry.ExitStatusandsubscribe_exit()(not in the issue spec) because the manager needs them for auto-prune, and gRPC handlers in the follow-up issue will likely surface them too..gitignorecarried asession*.rsrule for debug artifacts; added!**/src/pty/session.rsto the existing allowlist (the rule already had!**/src/acp/session.rs).🤖 Generated with Claude Code