Skip to content

Implement PtySessionManager and PtySession in packages/agent #1118

Closed

Description

@malibio

Overview

Build the core PTY session infrastructure: PtySessionManager that owns all active agent sessions, and PtySession that represents one running agent process attached to a pseudo-terminal. This is the Rust-side engine for ADR-032 — everything else (gRPC handler, Tauri UI, CLI) depends on this layer working correctly.

Problem Statement

PTY-based agent sessions require managing OS-level pseudo-terminals across their full lifecycle: creation, I/O streaming, resize, and termination. This cannot be done ad hoc in a gRPC handler or Tauri command — it needs a dedicated manager with clean ownership semantics, session IDs, and safe concurrent access.

Proposed Solution

Implement PtySessionManager as an Arc<Mutex<HashMap<SessionId, PtySession>>> held in nodespaced's shared state. PtySession wraps portable-pty to spawn the agent binary in a temp directory, streaming stdout/stderr through a broadcast channel and accepting stdin writes. The session lifecycle: create temp dir → write context file → spawn PTY → stream output → dispose temp dir on termination.

Acceptance Criteria

  • PtySessionManager holds all active sessions; supports concurrent access
  • PtySession::launch() creates a temp directory, writes the context file via GraphContextAssembler, and spawns the agent binary in a PTY
  • stdout/stderr from the agent are streamed through a broadcast::Sender<OutputChunk>
  • write_input(data: &[u8]) sends bytes to the PTY stdin
  • resize(cols: u16, rows: u16) resizes the PTY
  • terminate() sends SIGTERM to the process and cleans up the temp directory
  • Session exits naturally (agent process exits) also triggers temp dir cleanup
  • list_sessions() 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 agent passes
  • Code passes bun run quality:fix

Technical Specifications

Files to create

  • packages/agent/src/pty/mod.rs — module root
  • packages/agent/src/pty/session.rs — PtySession struct and impl
  • packages/agent/src/pty/manager.rs — PtySessionManager struct and impl
  • packages/agent/src/lib.rs — expose pty module

Cargo dependency

# packages/agent/Cargo.toml
[dependencies]
portable-pty = "0.8"
uuid = { version = "1", features = ["v4"] }
tokio = { version = "1", features = ["full"] }
tempfile = "3"

PtySession structure

pub struct PtySession {
    pub id:         Uuid,
    pub agent_type: AgentType,
    pub started_at: chrono::DateTime<chrono::Utc>,
    master:         Box<dyn portable_pty::MasterPty + Send>,
    child:          Box<dyn portable_pty::Child + Send>,
    output_tx:      broadcast::Sender<OutputChunk>,
    session_dir:    tempfile::TempDir, // dropped on session end → auto-cleanup
}

impl PtySession {
    pub async fn launch(
        agent_type: AgentType,
        initial_prompt: Option<String>,
        assembler: &GraphContextAssembler,
    ) -> anyhow::Result<Self> { ... }

    pub fn subscribe_output(&self) -> broadcast::Receiver<OutputChunk> { ... }
    pub fn write_input(&self, data: &[u8]) -> anyhow::Result<()> { ... }
    pub fn resize(&self, cols: u16, rows: u16) -> anyhow::Result<()> { ... }
    pub async fn terminate(self) -> anyhow::Result<()> { ... }
}

Session launch sequence

  1. tempfile::TempDir::new() — creates temp directory; stored in session so drop cleans it up
  2. assembler.write_context_file(temp_dir.path(), agent_type) — writes CLAUDE.md or AGENTS.md
  3. Resolve binary path via which::which(agent_type.binary_name())
  4. portable_pty::native_pty_system().openpty(PtySize { rows, cols, .. })
  5. Build CommandBuilder with binary + optional initial prompt argument + cwd = temp dir
  6. Spawn child; start background task reading stdout → broadcast::send(OutputChunk { data, timestamp })

PtySessionManager

pub struct PtySessionManager {
    sessions: Arc<Mutex<HashMap<Uuid, PtySession>>>,
}
impl PtySessionManager {
    pub async fn launch(&self, agent_type: AgentType, prompt: Option<String>, assembler: &GraphContextAssembler) -> anyhow::Result<Uuid> { ... }
    pub fn get(&self, id: &Uuid) -> Option</* ref */> { ... }
    pub async fn terminate(&self, id: &Uuid) -> anyhow::Result<()> { ... }
    pub fn list(&self) -> Vec<SessionMetadata> { ... }
}

Reference files

Dependencies

Non-Goals

  • gRPC handler for session operations (next issue)
  • Tauri UI for sessions (later issue)
  • Session capture / ai-chat node creation (later issue)
  • Windows PTY support (portable-pty handles it; verify but not required for initial implementation)

Activity

  1. malibio commented on May 17, 2026

    @malibio
    CollaboratorAuthor

    Baseline (worktree, fresh): Frontend tests 3918/3918 passed (128 files, 39.68s). Branch: worktree-issue-1118-pty-session

  2. self-assigned this
    on May 17, 2026
  3. added 2 commits that reference this issue on May 18, 2026
    656377b
    7507779
  4. added 2 commits that reference this issue on Jun 22, 2026
    dd198a6
    337f89c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions