Skip to content

Implement PtySessionManager and PtySession (closes #1118) - #1144

Merged
malibio merged 2 commits into
mainfrom
worktree-issue-1118-pty-session
May 18, 2026
Merged

malibio merged 2 commits into
mainfrom
worktree-issue-1118-pty-session

Conversation

@malibio

@malibio malibio commented May 17, 2026

Copy link
Copy Markdown
Collaborator

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 — PtySession owns one external agent
    process attached to a pseudo-terminal. Methods: launch, subscribe_output,
    subscribe_exit, write_input, resize, terminate. Each session has its
    own tempfile::TempDir; GraphContextAssembler writes CLAUDE.md/AGENTS.md
    into it and the binary spawns with cwd = temp dir. Stdout/stderr stream
    through broadcast::Sender<OutputChunk>; child exit fans out through a
    separate broadcast::Sender<ExitStatus>.

  • packages/agent/src/pty/manager.rs — PtySessionManager owns the collection,
    backed by Arc<Mutex<HashMap<Uuid, Arc<PtySession>>>>. Each insert spawns a
    task 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::Child
    exclusively so it can block in wait() without holding any lock terminate()
    needs. terminate() signals the kill through a separately-cloned ChildKiller,
    avoiding the obvious deadlock where kill waits on a mutex the wait-loop holds.

  • Subscribe-before-kill in terminate to avoid racing the watcher: if we
    subscribed 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 manager
    releasing its Arc, which drops the session, which drops the TempDir.

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 — clean
  • cargo check --workspace — clean
  • bun run test (frontend) — 3918/3918 passed (baseline unchanged)
  • bun run quality:fix (eslint + svelte-check) — 0 errors, 0 warnings

New PTY tests (packages/agent/src/pty/)

Session tests use sh/cat from PATH so they do not depend on a real agent
binary being installed.

  • launch_for_test_runs_command_and_emits_output — echo round-trips through the PTY
  • write_input_is_echoed_back_through_pty — cat echoes stdin back via the stream
  • resize_does_not_error — resize before and during a running process
  • terminate_kills_long_running_process — sleep 30 ends within 3s of terminate
  • natural_exit_keeps_temp_dir_until_session_drops — temp dir lifetime matches session lifetime, not process lifetime
  • insert_then_list_returns_metadata — manager round-trip with SessionMetadata
  • terminate_removes_session_and_returns_true — explicit terminate path
  • terminate_unknown_returns_false — terminate on stale id
  • natural_exit_auto_removes_session — exit watcher prunes the map
  • get_returns_session_and_supports_write_resize — Arc<PtySession> from get() is fully usable

Acceptance criteria (from #1118)

  • PtySessionManager holds all active sessions; supports concurrent access
  • PtySession::launch() creates a temp dir, writes context via GraphContextAssembler, spawns the agent in a PTY
  • stdout/stderr stream through broadcast::Sender<OutputChunk>
  • write_input(data: &[u8]) sends bytes to PTY stdin
  • resize(cols: u16, rows: u16) resizes the PTY
  • terminate() signals the child and cleans up the temp directory
  • Natural exit also triggers temp dir cleanup (via manager's auto-prune watcher)
  • list_sessions() (named list() here) returns metadata for all active sessions
  • Session IDs are UUIDs generated at launch time
  • Unit tests cover launch, write_input, resize, terminate, natural exit cleanup
  • cargo test -p nodespace-agent passes (the issue body wrote -p agent, which is a typo — the crate name is nodespace-agent)
  • Code passes bun run quality:fix

Deviations from the spec

  • terminate() takes &self instead of self. The manager hands out Arc<PtySession> from get(), so consuming self would require either Arc::try_unwrap (fragile under concurrent get() callers) or a fallback path. Taking &self is simpler and equivalent: the temp dir still drops when the last Arc is dropped — usually right after terminate() returns, when the manager removes its entry.
  • Added ExitStatus and subscribe_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.
  • .gitignore carried a session*.rs rule for debug artifacts; added !**/src/pty/session.rs to the existing allowlist (the rule already had !**/src/acp/session.rs).

🤖 Generated with Claude Code

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 malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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:

  1. The watcher fired its single send() some time ago; the value is gone.
  2. The session still owns exit_tx, so the receiver is not Closed.
  3. kill() returns an error which the code swallows.
  4. 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>> (or Arc<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::watch instead of broadcast for 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 Drop that fires the kill and detaches (best-effort, no await).
  • 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 and TerminateProcess on 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), bypass ChildKiller and libc::kill(pid, SIGTERM) directly behind cfg(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 on which::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 (its Drop does 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 cleanup next 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 between writer lock and master lock 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]>
@malibio

malibio commented May 18, 2026

Copy link
Copy Markdown
Collaborator Author

Review feedback addressed — commit 62a61f3

Critical findings (both fixed)

🔴 #1: terminate() could hang forever after natural exit
🔴 #2: Manager auto-prune could leak short-lived sessions

Both shared a root cause — broadcast::channel::<ExitStatus>(1) does not deliver values to subscribers that subscribed after the single send. Replaced with tokio::sync::watch::Sender<Option<ExitStatus>>, which latches the final value so late subscribers always observe it.

  • PtySession::terminate() now fast-paths on the latched value before calling kill, and loops on changed() until it transitions otherwise.
  • The manager's auto-prune task does the same fast-path-then-watch pattern.
  • New exit_status() accessor for non-blocking checks.

Regression tests added:

  • terminate_after_natural_exit_returns_immediately
  • subscribe_exit_after_exit_observes_status
  • ultra_short_lived_processes_are_pruned (10× true to stress the race)

Nits addressed

  • SIGHUP doc fix: confirmed in portable-pty 0.8.1 source (src/lib.rs:316); updated the terminate() doc to say SIGHUP on Unix / TerminateProcess on Windows. Behaviour unchanged.
  • #[cfg(unix)] on test modules: tests depend on sh/cat/true from PATH; per ADR-032 Windows is non-goal for initial impl, so making the gate explicit is better than implicit-by-PATH-failure.
  • Field comment on _session_dir: noted it lives only for Drop-side-effect cleanup.

Additional tests (defensive, beyond the two regressions)

  • terminate_is_idempotent — calling terminate twice on the same session is safe.
  • concurrent_write_and_resize_do_not_deadlock — locks the intent of the writer-vs-master split.

Skipped, with reasoning

Item Reason
🟡 Drop impl for PtySession Manager is the sole API surface; async fire-and-forget from sync Drop adds complexity for a hypothetical caller. Revisit if/when a direct constructor emerges.
🟡 thiserror LaunchError enum 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 duplicate lines, test-only path. A shared helper saves little and adds an indirection. Skip until they actually drift.
🟢 .map(SessionMetadata::from_session) point-free Iterator yields &Arc<PtySession>, the fn takes &PtySession. Point-free needs an extra .as_ref() that the closure version doesn't. Net: closure is cleaner.

Verified

  • cargo test -p nodespace-agent --lib pty:: — 15 passed (10 prior + 5 new)
  • cargo test -p nodespace-agent --lib — 250 passed (was 245)
  • cargo clippy -p nodespace-agent --all-targets -- -D warnings — clean

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Review Type: Re-Review

Previous Review Summary

  • Prior findings: 2 critical, 3 improvements, 2 nits.
  • Addressed: both critical (via single tokio::sync::watch redesign), 3 nits (SIGHUP doc, cfg(all(test, unix)), _session_dir comment).
  • Skipped with justification: 3 improvements (Drop impl, thiserror LaunchError, dedup launch_for_test/spawn_in_pty) and 1 nit (point-free from_session). All skip rationales hold up — Drop is genuinely complex for sync-from-async fire-and-forget when the manager is the only API surface; LaunchError is 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_status is a real regression test. Under the old broadcast::channel(1) design, a Receiver created via subscribe() after the single send() would start at the current tail position and not see the prior message — the test would hang/timeout. The watch redesign is exactly what makes late_rx.borrow() return Some(_) here.
  • ultra_short_lived_processes_are_pruned is also a real regression test. With 10× true and the old broadcast race, at least one entry would plausibly leak in the map. The wait_for_len(0, 3s) would fail. The new latched-value design guarantees the auto-prune task sees the exit.
  • terminate_after_natural_exit_returns_immediately directly exercises finding #1's bug.
  • terminate_is_idempotent and concurrent_write_and_resize_do_not_deadlock are appropriate hardening additions.
  • The await_exit helper cleanly factors the "loop on changed() 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.

@malibio
malibio merged commit 656377b into main May 18, 2026
@malibio
malibio deleted the worktree-issue-1118-pty-session branch May 18, 2026 01:20
malibio added a commit that referenced this pull request Jun 22, 2026
* 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]>
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.

Implement PtySessionManager and PtySession in packages/agent

1 participant