Skip to content

feat: ACP session state machine and orchestration (closes #1004) - #1029

Merged
malibio merged 2 commits into
mainfrom
feature/issue-1004-acp-session
Apr 3, 2026
Merged

malibio merged 2 commits into
mainfrom
feature/issue-1004-acp-session

Conversation

@malibio

@malibio malibio commented Apr 3, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Implements AcpSession with enforced state machine transitions (Idle -> Initializing -> Active -> Completing -> Completed, with failure transitions to Failed)
  • Adds initialization handshake: initialize request with 30s timeout, session/new with MCP server config
  • Creates AcpClientService facade managing concurrent sessions with one-per-agent-type enforcement
  • Error recovery: transport failures transition to Failed with diagnostic reason
  • 29 unit tests covering all valid/invalid state transitions, full lifecycle with echo subprocess, concurrent sessions, and edge cases

Technical Details

New file: packages/desktop-app/src-tauri/src/acp/session.rs

AcpSession: Owns the transport connection and enforces state transitions with match guards. Initialization spawns a StdioTransport, sends initialize + session/new handshake messages, and waits for responses with 30s timeout.

AcpClientService: Thread-safe facade using Mutex<HashMap<String, AcpSession>>. Enforces one session per agent type. Methods: start_session, send_message, receive_message, end_session, fail_session, get_session_state, active_sessions.

Pre-existing fixes included

  • Resolved merge conflict in Cargo.toml (which + sysinfo/sha2/reqwest)
  • Removed duplicate pub mod local_agent in lib.rs
  • Fixed temporary value borrow in context_assembly test
  • Fixed unwrap_err requiring Debug on StdioTransport
  • Added tempfile dev-dependency for model_manager tests
  • Applied rustfmt formatting

Test plan

  • cargo check -p nodespace-app -- clean compile, zero warnings
  • cargo test -p nodespace-app --lib -- session -- 29/29 tests pass
  • State machine: all valid transitions (Idle->Initializing->Active->Completing->Completed)
  • State machine: all failure transitions (Initializing/Active/Completing -> Failed)
  • State machine: all invalid transitions rejected with error
  • Full lifecycle: initialize, send, receive, end with echo subprocess
  • Timeout: agent that exits immediately -> Failed state
  • AcpClientService: start, send/receive, end, concurrent different agents
  • AcpClientService: duplicate session rejected, not-found errors

Closes #1004

@malibio

malibio commented Apr 3, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review: PR #1029 — ACP Session State Machine and Orchestration

Verdict: Approve with improvements — This is a net-positive change that delivers a well-structured session state machine with strong test coverage. The issues identified below are substantive but none are blockers for a pre-release codebase with zero users. I recommend addressing the Critical and Improvement items before merge.


Overall Assessment

The implementation is clean, well-documented, and closely follows the architecture specified in issue #1004. The state machine transition logic is correct and exhaustively tested. The AcpClientService facade provides a reasonable multi-session API. The 29 tests cover all valid/invalid transitions, full lifecycle with a real echo subprocess, and service-level operations. The bundled formatting changes and merge-conflict resolution are harmless housekeeping.


Findings

Critical Issues

1. [Critical] TOCTOU race in AcpClientService::start_session — duplicate session check is released before insert

/packages/desktop-app/src-tauri/src/acp/session.rs (around the start_session method)

The duplicate-session check acquires the mutex, checks contains_key, then drops the lock before the session.initialize().await call. After initialization completes, it re-acquires the lock to insert. Between the check and the insert, a concurrent caller could also pass the check and start initializing the same agent — violating the one-session-per-agent invariant.

// Current: check → drop lock → initialize → re-acquire lock → insert
{
    let sessions = self.sessions.lock().await;
    if sessions.contains_key(agent_id) {
        return Err(SessionError::DuplicateSession(..));
    }
} // lock dropped here

let mut session = AcpSession::new(..);
session.initialize().await?; // slow I/O — another caller can pass the check

{
    let mut sessions = self.sessions.lock().await;
    sessions.insert(..); // second caller may also reach here
}

Fix: Insert a sentinel/placeholder into the map before releasing the lock (or hold the lock across initialization, though that blocks all other session operations). A common pattern is to insert the session in Idle state immediately, then initialize it while holding a per-session lock or by using an entry API. Alternatively, use a HashSet<String> of "initializing" agent IDs as a lightweight reservation.


2. [Critical] fail() bypasses the transition() state machine — can move to Failed from any state including Idle

/packages/desktop-app/src-tauri/src/acp/session.rs, fn fail(&mut self, reason: String)

The fail() method directly assigns self.state = AcpSessionState::Failed { reason } without going through transition(). This means it can transition from Idle to Failed, from Completed to Failed, or from Failed to Failed — all of which the transition() method correctly rejects. The test test_session_fail_marks_failed exercises exactly this: calling fail() on an Idle session succeeds, but transition(Failed) from Idle returns an error.

This creates two contradictory state machine enforcement paths and could mask logic errors in callers.

Fix: Route fail() through transition() for states that permit it, and for edge cases where the caller needs to force-fail from any state (e.g., Idle), either (a) add Idle → Failed as a valid transition (reasonable — the session could fail before initialization), or (b) keep the direct assignment but rename it to something like force_fail() with a doc comment explaining it bypasses validation intentionally.


3. [Critical] receive_message holds the sessions Mutex across an .await point (potential deadlock)

/packages/desktop-app/src-tauri/src/acp/session.rs, AcpClientService::receive_message

pub async fn receive_message(&self, agent_id: &str) -> Result<AcpMessage, SessionError> {
    let mut sessions = self.sessions.lock().await;
    let session = sessions.get_mut(agent_id) ...;
    session.receive_message().await  // blocks on transport I/O while holding lock
}

The tokio::sync::Mutex guard is held while awaiting session.receive_message(), which internally awaits transport.receive(). This blocks all other AcpClientService operations (including sends to different agents, session state queries, and new session creation) for the entire duration of the receive — which could be indefinite if the agent is slow to respond. The same issue applies to send_message, though sends are typically fast.

Fix: Extract the session from the map (or use a per-session Arc<Mutex<AcpSession>>) so the top-level sessions lock is released before awaiting transport I/O. A HashMap<String, Arc<Mutex<AcpSession>>> pattern would allow concurrent operations on different sessions.


Suggested Improvements

4. [Improvement] end() silently discards transport shutdown errors

/packages/desktop-app/src-tauri/src/acp/session.rs, fn end(&mut self)

if let Some(ref transport) = self.transport {
    let _final_response =
        tokio::time::timeout(COMPLETION_TIMEOUT, transport.shutdown()).await;
}

Both the timeout result and the shutdown result are discarded. If the transport fails to shut down, the session still transitions to Completed. Consider at minimum logging the error, or transitioning to Failed if shutdown fails (since a clean Completed state should mean resources were released).


5. [Improvement] MCP server URL is hardcoded

/packages/desktop-app/src-tauri/src/acp/session.rs, initialization handshake

"url": "http://localhost:3100/mcp"

The MCP server port (3100) is hardcoded in the session/new message. If the port is configurable elsewhere in the codebase (and it likely is, since MCP server initialization appears to use a configurable port), this should be injected rather than duplicated. For a pre-release codebase this is acceptable, but it is a maintenance footgun.


6. [Improvement] Missing acceptance criterion: "Integration test with a simple test agent subprocess (echo server)"

Issue #1004 specifies:

Integration test with a simple test agent subprocess (echo server)

The tests use a bash one-liner echo agent (while IFS= read -r line; do echo "$line"; done), which is a reasonable echo server. However, the issue seems to envision a separate test agent binary. The current approach is pragmatic and sufficient — just noting the gap for traceability. The tests marked "Full lifecycle integration tests (with echo agent subprocess)" satisfy the intent.


7. [Improvement] Agent environment variables from AcpAgentInfo are not forwarded to transport

/packages/desktop-app/src-tauri/src/acp/session.rs, fn initialize()

let config = StdioTransportConfig {
    binary: self.agent_info.binary.clone(),
    args: self.agent_info.args.clone(),
    env: HashMap::new(),  // always empty
    working_dir: None,
};

The AcpAgentInfo has an auth_method field (which can be EnvApiKey { var_name }) but the transport config always passes an empty env map. For agents that use EnvApiKey authentication, the required environment variable will not be set. This should be wired through based on auth_method when the feature is needed.


Nitpicks

8. Nit: Session ID generation uses uuid::Uuid::new_v4().to_string().split('-').next().unwrap_or("0") — this takes only the first 8 hex chars of a UUID, yielding 32 bits of entropy. For session IDs this is fine (collision probability is negligible for a desktop app with few concurrent sessions), but a cleaner approach would be &uuid[..8] on the formatted string, or just use the full UUID.

9. Nit: The created_at field on AcpSession is set but never exposed through AcpClientService. If it is needed for frontend display or diagnostics, a method should be added. If not, consider removing it to follow YAGNI.

10. Nit: context_assembly.rs diff includes only formatting changes (rustfmt). This is fine as housekeeping but ideally would be a separate commit to keep the feature commit atomic. Not a blocker.


Test Coverage Assessment

Strengths:

  • All 5 valid state transitions tested individually
  • All 3 failure transitions tested (Initializing/Active/Completing → Failed)
  • Terminal state immutability tested (Completed and Failed reject all transitions)
  • Invalid transitions from Idle tested (4 cases)
  • Full lifecycle integration test with real subprocess (initialize → send → receive → end)
  • AcpClientService tested for: start, duplicate rejection, not-found, unavailable, send/receive, end, concurrent agents, nonexistent operations

Gaps:

  • No test for the TOCTOU race condition in start_session (hard to test without injecting delays, but worth noting)
  • No test for end() when transport shutdown fails or times out
  • No test for fail_session at the service level followed by re-starting a new session for the same agent (the cleanup path)
  • The receive_message blocking behavior under the sessions lock is not tested with concurrent operations

Summary

Category Status
State machine correctness Pass — all transitions validated
Concurrency safety Issues found — TOCTOU race, mutex held across await
Error handling Mostly good — end() and fail() need attention
Test coverage Strong — 29 tests, minor gaps noted
Code quality Clean, well-documented, follows project patterns
Security No concerns — no user input, no secrets
Dependencies tempfile (dev-only) is appropriate

Recommendation: Address items 1-3 (TOCTOU, fail() bypass, mutex-across-await) before merge. Items 4-7 can be addressed in follow-up work.

@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 completed. 3 critical issues identified that should be addressed before merge: (1) TOCTOU race in start_session duplicate check, (2) fail() bypasses state machine validation, (3) sessions Mutex held across await in receive_message/send_message causing potential deadlock. See detailed review comment above for specifics and suggested fixes.

malibio pushed a commit that referenced this pull request Apr 3, 2026
…ention

- Fixed TOCTOU: reserve session slot before async initialization
- Fixed fail(): route through transition() with valid source states
- Fixed mutex: per-session Arc<Mutex> to avoid blocking concurrent agents

Addresses reviewer recommendations from PR #1029 review.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Apr 3, 2026

Copy link
Copy Markdown
Collaborator Author

Review Feedback Addressed

✅ Fixed TOCTOU race: reserve session slot atomically before async initialization
✅ Fixed fail(): routes through transition() — only valid from Initializing/Active/Completing
✅ Fixed mutex contention: per-session Arc prevents cross-agent blocking
✅ Added test for invalid fail() from Idle state
All 30 tests passing.

Michael Libio and others added 2 commits April 4, 2026 01:46
Implements the session lifecycle for external agent interactions:

- AcpSession with enforced state machine (Idle -> Initializing -> Active ->
  Completing -> Completed, with failure transitions to Failed)
- Initialization handshake: send `initialize`, wait for response with 30s
  timeout, send `session/new` with MCP server config
- AcpClientService facade managing concurrent sessions with one-per-agent
  enforcement
- Error recovery: transport failures transition to Failed with diagnostic reason
- 29 unit tests covering all state transitions, lifecycle, and edge cases

Also fixes pre-existing issues:
- Resolve merge conflict in Cargo.toml (which + sysinfo/sha2/reqwest)
- Remove duplicate `pub mod local_agent` in lib.rs
- Fix temporary value borrow in context_assembly test
- Fix unwrap_err requiring Debug on StdioTransport
- Add tempfile dev-dependency for model_manager tests
- Apply rustfmt formatting across modified files

Co-Authored-By: Claude <[email protected]>
…ention

- Fixed TOCTOU: reserve session slot before async initialization
- Fixed fail(): route through transition() with valid source states
- Fixed mutex: per-session Arc<Mutex> to avoid blocking concurrent agents

Addresses reviewer recommendations from PR #1029 review.

Co-Authored-By: Claude <[email protected]>
@malibio
malibio force-pushed the feature/issue-1004-acp-session branch from 0442bd5 to ccaf272 Compare April 3, 2026 23:46
@malibio
malibio merged commit 7127ede into main Apr 3, 2026
@malibio
malibio deleted the feature/issue-1004-acp-session branch April 3, 2026 23:47
malibio added a commit that referenced this pull request Jun 22, 2026
* feat: ACP session state machine and orchestration (closes #1004)

Implements the session lifecycle for external agent interactions:

- AcpSession with enforced state machine (Idle -> Initializing -> Active ->
  Completing -> Completed, with failure transitions to Failed)
- Initialization handshake: send `initialize`, wait for response with 30s
  timeout, send `session/new` with MCP server config
- AcpClientService facade managing concurrent sessions with one-per-agent
  enforcement
- Error recovery: transport failures transition to Failed with diagnostic reason
- 29 unit tests covering all state transitions, lifecycle, and edge cases

Also fixes pre-existing issues:
- Resolve merge conflict in Cargo.toml (which + sysinfo/sha2/reqwest)
- Remove duplicate `pub mod local_agent` in lib.rs
- Fix temporary value borrow in context_assembly test
- Fix unwrap_err requiring Debug on StdioTransport
- Add tempfile dev-dependency for model_manager tests
- Apply rustfmt formatting across modified files

Co-Authored-By: Claude <[email protected]>

* address review: fix TOCTOU race, state machine bypass, and mutex contention

- Fixed TOCTOU: reserve session slot before async initialization
- Fixed fail(): route through transition() with valid source states
- Fixed mutex: per-session Arc<Mutex> to avoid blocking concurrent agents

Addresses reviewer recommendations from PR #1029 review.

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.

ACP session state machine and orchestration

1 participant