Repository navigation
feat: ACP session state machine and orchestration (closes #1004) - #1029
Conversation
Code Review: PR #1029 — ACP Session State Machine and OrchestrationVerdict: 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 AssessmentThe 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 FindingsCritical Issues1. [Critical] TOCTOU race in
The duplicate-session check acquires the mutex, checks // 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 2. [Critical]
The This creates two contradictory state machine enforcement paths and could mask logic errors in callers. Fix: Route 3. [Critical]
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 Fix: Extract the session from the map (or use a per-session Suggested Improvements4. [Improvement]
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 5. [Improvement] MCP server URL is hardcoded
"url": "http://localhost:3100/mcp"The MCP server port (3100) is hardcoded in the 6. [Improvement] Missing acceptance criterion: "Integration test with a simple test agent subprocess (echo server)" Issue #1004 specifies:
The tests use a bash one-liner echo agent ( 7. [Improvement] Agent environment variables from
let config = StdioTransportConfig {
binary: self.agent_info.binary.clone(),
args: self.agent_info.args.clone(),
env: HashMap::new(), // always empty
working_dir: None,
};The Nitpicks8. Nit: Session ID generation uses 9. Nit: The 10. Nit: Test Coverage AssessmentStrengths:
Gaps:
Summary
Recommendation: Address items 1-3 (TOCTOU, |
malibio
left a comment
There was a problem hiding this comment.
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.
…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]>
Review Feedback Addressed✅ Fixed TOCTOU race: reserve session slot atomically before async initialization |
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]>
0442bd5 to
ccaf272
Compare
* 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]>
Summary
AcpSessionwith enforced state machine transitions (Idle -> Initializing -> Active -> Completing -> Completed, with failure transitions to Failed)initializerequest with 30s timeout,session/newwith MCP server configAcpClientServicefacade managing concurrent sessions with one-per-agent-type enforcementTechnical Details
New file:
packages/desktop-app/src-tauri/src/acp/session.rsAcpSession: Owns the transport connection and enforces state transitions with match guards. Initialization spawns a
StdioTransport, sendsinitialize+session/newhandshake 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
pub mod local_agentin lib.rsunwrap_errrequiring Debug on StdioTransportTest plan
cargo check -p nodespace-app-- clean compile, zero warningscargo test -p nodespace-app --lib -- session-- 29/29 tests passCloses #1004