From 7ddecfe2e1288352cef78c2e2011c8db955e9812 Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Mon, 23 Nov 2026 14:14:49 +0000 Subject: [PATCH 1/2] acp: list, fork and close sessions where the agent advertises them read sessionCapabilities.list/fork/close at initialize and send session/list, session/fork and session/close only when advertised. the harness maps listings to the session browser page, opens forks at the end of a session (no fork point in acp), and closes on release so the agent lets go (native release). the isolated harness refuses unadvertised list and fork before launching a process and hides its picker probes from listings. enables the vendored crate's unstable_session_fork feature; no vendored source change. --- Cargo.lock | 1 + crates/agent-driver-acp/Cargo.toml | 3 +- crates/agent-driver-acp/src/driver.rs | 191 ++++++ crates/agent-driver-acp/src/harness.rs | 158 ++++- .../agent-driver-acp/src/isolated_harness.rs | 48 +- crates/agent-driver-acp/src/lib.rs | 2 +- crates/agent-driver-acp/tests/session_ops.rs | 562 ++++++++++++++++++ 7 files changed, 937 insertions(+), 28 deletions(-) create mode 100644 crates/agent-driver-acp/tests/session_ops.rs diff --git a/Cargo.lock b/Cargo.lock index 06952c8a5..72a04c357 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1546,6 +1546,7 @@ version = "0.7.26" dependencies = [ "agent-client-protocol", "base64 0.22.1", + "chrono", "futures-util", "inline-agent-bridge", "log", diff --git a/crates/agent-driver-acp/Cargo.toml b/crates/agent-driver-acp/Cargo.toml index a1fed9acf..afdeed5ac 100644 --- a/crates/agent-driver-acp/Cargo.toml +++ b/crates/agent-driver-acp/Cargo.toml @@ -13,8 +13,9 @@ keywords = ["inline", "agent", "acp", "coding-agent"] categories = ["development-tools"] [dependencies] -agent-client-protocol = { workspace = true, features = ["unstable_elicitation"] } +agent-client-protocol = { workspace = true, features = ["unstable_elicitation", "unstable_session_fork"] } base64 = "0.22.1" +chrono = "0.4" futures-util.workspace = true inline-agent-bridge = { version = "0.7.26", path = "../agent-bridge" } log.workspace = true diff --git a/crates/agent-driver-acp/src/driver.rs b/crates/agent-driver-acp/src/driver.rs index 7e857425e..d60adb43b 100644 --- a/crates/agent-driver-acp/src/driver.rs +++ b/crates/agent-driver-acp/src/driver.rs @@ -375,6 +375,7 @@ pub struct AcpDriver { capabilities: DriverCapabilities, prompt_capabilities: acp::PromptCapabilities, resume_mode: ResumeMode, + session_ops: AcpSessionOps, default_permission_mode: Option>, active_turns: ActiveTurns, approvals: PendingApprovals, @@ -398,6 +399,35 @@ enum ResumeMode { Load, } +/// Session lifecycle methods the agent advertised in `initialize` +/// (`agentCapabilities.sessionCapabilities`). A method that is not advertised +/// is never sent. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct AcpSessionOps { + /// `session/list`. + pub list: bool, + /// `session/fork` (ACP unstable). + pub fork: bool, + /// `session/close`. + pub close: bool, +} + +/// One page of `session/list`, with unusable entries dropped. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct AcpSessionListing { + pub(crate) sessions: Vec, + pub(crate) next_cursor: Option, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct AcpListedSession { + pub(crate) id: ProviderSessionId, + pub(crate) cwd: PathBuf, + pub(crate) title: Option, + /// ISO 8601, as the agent sent it. + pub(crate) updated_at: Option, +} + impl std::fmt::Debug for AcpDriver { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter @@ -413,9 +443,17 @@ impl AcpDriver { self.agent_version.as_deref() } + /// Which of `session/list`, `session/fork` and `session/close` the agent advertised. + pub fn session_ops(&self) -> AcpSessionOps { + self.session_ops + } + pub(crate) fn disable_durable_session_resume(&mut self) { self.resume_mode = ResumeMode::Unsupported; self.capabilities.resume_session = false; + // A session that cannot be reopened is not worth listing or forking. + self.session_ops.list = false; + self.session_ops.fork = false; } pub(crate) fn set_stdio_mcp_servers( @@ -590,6 +628,7 @@ impl AcpDriver { ))); } let resume_mode = resume_mode(&response.agent_capabilities); + let session_ops = session_ops(&response.agent_capabilities); let capabilities = map_capabilities(&response.agent_capabilities); let prompt_capabilities = response.agent_capabilities.prompt_capabilities.clone(); log::trace!( @@ -610,6 +649,7 @@ impl AcpDriver { capabilities, prompt_capabilities, resume_mode, + session_ops, default_permission_mode: None, active_turns, approvals, @@ -855,6 +895,111 @@ impl AcpDriver { Ok(()) } + /// One page of the agent's sessions (`session/list`), newest first as the + /// agent orders them. Read-only: a timeout never ends the connection. + pub(crate) async fn list_sessions( + &self, + cwd: Option, + cursor: Option, + ) -> DriverResult { + if !self.session_ops.list { + return Err(DriverError::Unsupported("ACP session/list")); + } + let response = request_with_timeout( + "session/list", + &self.auth_methods, + self.connection + .send_request(acp::ListSessionsRequest::new().cwd(cwd).cursor(cursor)) + .block_task(), + ) + .await?; + let sessions = response + .sessions + .into_iter() + .filter_map(|info| { + let id = info.session_id.to_string(); + validate_provider_session_id(&id).ok()?; + Some(AcpListedSession { + id: ProviderSessionId::new(id).ok()?, + cwd: info.cwd, + title: info.title.filter(|title| !title.trim().is_empty()), + updated_at: info.updated_at, + }) + }) + .collect(); + Ok(AcpSessionListing { + sessions, + next_cursor: response.next_cursor, + }) + } + + /// Copies `source` into a new session (`session/fork`) rooted at `cwd`, + /// with this connection's MCP servers, and records it like a new session. + pub(crate) async fn fork_session( + &self, + source: &ProviderSessionId, + cwd: PathBuf, + ) -> DriverResult { + if !self.session_ops.fork { + return Err(DriverError::Unsupported("ACP session/fork")); + } + validate_provider_session_id(source.as_str())?; + let attachment = self.session_mcp_attachment()?; + let request = acp::ForkSessionRequest::new(source.to_string(), cwd.clone()) + .mcp_servers(self.session_servers(attachment.as_ref())); + let response = mutating_request_with_timeout( + &self.lifecycle, + REQUEST_TIMEOUT, + "session/fork", + self.connection.send_request(request).block_task(), + |error| acp_resume_error(error, &self.auth_methods), + ) + .await?; + let session_id = response.session_id.to_string(); + validate_provider_session_id(&session_id)?; + if session_id == source.as_str() { + return Err(DriverError::Protocol( + "ACP agent returned the source session as its fork".to_string(), + )); + } + let forked = ProviderSessionId::new(session_id.clone()) + .map_err(|error| DriverError::Protocol(error.to_string()))?; + if let Some(attachment) = attachment { + attachment.bind(forked.clone()); + } + // A fork continues the source's conversation and permission mode. + self.record_session( + session_id, + cwd, + response.config_options.unwrap_or_default(), + response.modes, + false, + ); + Ok(forked) + } + + /// Asks the agent to free a session (`session/close`), then forgets it + /// here. A failure leaves the session recorded: its state is unknown. + pub(crate) async fn close_session(&self, session: &ProviderSessionId) -> DriverResult<()> { + if !self.session_ops.close { + return Err(DriverError::Unsupported("ACP session/close")); + } + request_with_timeout( + "session/close", + &self.auth_methods, + self.connection + .send_request(acp::CloseSessionRequest::new(session.to_string())) + .block_task(), + ) + .await?; + cancel_pending_approvals(&self.approvals, Some(session.as_str())); + cancel_pending_elicitations(&self.elicitations, Some(session.as_str())); + let mut sessions = self.sessions.lock().expect("ACP session registry poisoned"); + sessions.sessions.remove(session.as_str()); + sessions.early_commands.remove(session.as_str()); + Ok(()) + } + async fn seed_permission_mode( &self, session_id: &str, @@ -1472,6 +1617,15 @@ fn map_capabilities(capabilities: &acp::AgentCapabilities) -> DriverCapabilities } } +fn session_ops(capabilities: &acp::AgentCapabilities) -> AcpSessionOps { + let session = &capabilities.session_capabilities; + AcpSessionOps { + list: session.list.is_some(), + fork: session.fork.is_some(), + close: session.close.is_some(), + } +} + fn resume_mode(capabilities: &acp::AgentCapabilities) -> ResumeMode { if capabilities.session_capabilities.resume.is_some() { ResumeMode::Resume @@ -2600,6 +2754,43 @@ mod tests { )); assert!(advertised.resume_session); assert!(map_capabilities(&acp::AgentCapabilities::new().load_session(true)).resume_session); + + // Resume and load do not imply any other session method. + assert_eq!( + session_ops( + &acp::AgentCapabilities::new() + .load_session(true) + .session_capabilities( + acp::SessionCapabilities::new() + .resume(acp::SessionResumeCapabilities::new()), + ) + ), + AcpSessionOps::default() + ); + assert_eq!( + session_ops(&acp::AgentCapabilities::new().session_capabilities( + acp::SessionCapabilities::new().close(acp::SessionCloseCapabilities::new()), + )), + AcpSessionOps { + list: false, + fork: false, + close: true, + } + ); + assert_eq!( + session_ops( + &acp::AgentCapabilities::new().session_capabilities( + acp::SessionCapabilities::new() + .list(acp::SessionListCapabilities::new()) + .fork(acp::SessionForkCapabilities::new()) + ) + ), + AcpSessionOps { + list: true, + fork: true, + close: false, + } + ); } #[tokio::test] diff --git a/crates/agent-driver-acp/src/harness.rs b/crates/agent-driver-acp/src/harness.rs index ab7d9e2d2..fa1844266 100644 --- a/crates/agent-driver-acp/src/harness.rs +++ b/crates/agent-driver-acp/src/harness.rs @@ -4,7 +4,9 @@ //! a Claude release breaks the Rust driver. It is turn-scoped underneath, so //! this adapter declares the reduced capability set: turns, steering where //! the agent supports it, stop, approvals, questions and compaction; no -//! native queue, passive context, fork or session browser. +//! native queue or passive context. The session browser, fork and close +//! follow what the agent advertised in `sessionCapabilities`: an agent that +//! does not advertise `list`, `fork` or `close` is never sent that method. use std::collections::{HashMap, HashSet}; use std::path::PathBuf; @@ -15,23 +17,29 @@ use inline_agent_bridge::harness::{ ApprovalSubject, Availability, AvailabilityMatrix, CapabilityManifest, Catalog, CatalogScope, ClosedBy, CompatTier, DEFAULT_HUB_CAPACITY, Decision, DecisionId, DecisionKind, Delivery, DeliveryKind, DeltaStream, Event, EventHub, EventStream, ExecutableInfo, FieldAnswer, FieldId, - FieldInput, FieldOption, FileChangeKind, FileDiff, FormField, HarnessDriver, HarnessFuture, - Input, InputDisposition, InputId, InputReceipt, Interaction, InteractionId, InteractionKind, - InteractionResponse, Item, ItemBody, ItemDelta, ItemId, ItemKind, ItemStatus, ItemUpdate, - LiveWork, MessageRole, Notice, NoticeLevel, Op, OpError, OpKind, OpOutcome, OpenError, - OpenMode, OpenSpec, QuestionForm, ReleaseOutcome, Released, RunState, RunStateTracker, - RuntimeHealth, RuntimeInfo, SendError, Session, SessionKey, SessionPage, SessionQuery, - SettingsScope, TokenUsage, TurnPhase, UsageUpdate, UserId, + FieldInput, FieldOption, FileChangeKind, FileDiff, ForkPoint, FormField, HarnessDriver, + HarnessFuture, Input, InputDisposition, InputId, InputReceipt, Interaction, InteractionId, + InteractionKind, InteractionResponse, Item, ItemBody, ItemDelta, ItemId, ItemKind, ItemStatus, + ItemUpdate, LiveWork, MessageRole, Notice, NoticeLevel, Op, OpError, OpKind, OpOutcome, + OpenError, OpenMode, OpenSpec, QuestionForm, ReleaseOutcome, Released, RunState, + RunStateTracker, RuntimeHealth, RuntimeInfo, SendError, Session, SessionKey, SessionPage, + SessionQuery, SessionSummary, SettingsScope, TokenUsage, TurnPhase, UsageUpdate, UserId, }; use inline_agent_bridge::{ ActivitySemanticKind, ActivityStatus, ActivityTextStream, AgentDriver, AgentEvent, AgentMessageUpdate, ApprovalDecision, ApprovalOption, ApprovalRequest, DriverError, DriverFuture, ProviderId, ProviderSessionId, QuestionAnswer, QuestionRequest, - ResumeSessionSpec, SessionReplay, SessionSpec, SteeringSupport, TurnId, TurnInput, TurnOptions, - TurnOutcome, + ResumeSessionSpec, SessionPageCursor, SessionReplay, SessionSpec, SteeringSupport, TurnId, + TurnInput, TurnOptions, TurnOutcome, }; use serde_json::{Value, json}; +use crate::AcpDriver; +use crate::driver::AcpSessionListing; + +/// Folder to the session the settings catalog reads commands from. +type CatalogSessions = Arc>>; + /// The reduced capability set ACP can honour for `driver`. pub fn acp_availability(driver: &dyn AgentDriver) -> AvailabilityMatrix { let capabilities = driver.capabilities(); @@ -93,17 +101,17 @@ pub fn acp_availability(driver: &dyn AgentDriver) -> AvailabilityMatrix { /// An ACP agent behind the session contract. pub struct AcpHarness { - driver: Arc, + driver: Arc, provider: ProviderId, executable: ExecutableInfo, driver_version: String, process_status: Option, - catalog_sessions: tokio::sync::Mutex>, + catalog_sessions: CatalogSessions, } impl AcpHarness { pub fn new( - driver: Arc, + driver: Arc, provider: ProviderId, executable: ExecutableInfo, driver_version: impl Into, @@ -114,7 +122,7 @@ impl AcpHarness { executable, driver_version: driver_version.into(), process_status: None, - catalog_sessions: tokio::sync::Mutex::new(HashMap::new()), + catalog_sessions: Arc::default(), } } @@ -131,7 +139,7 @@ impl AcpHarness { executable, driver_version: driver_version.into(), process_status: Some(spawned.process_status), - catalog_sessions: tokio::sync::Mutex::new(HashMap::new()), + catalog_sessions: Arc::default(), } } @@ -142,6 +150,11 @@ impl AcpHarness { pub async fn shutdown(&self) -> Result<(), DriverError> { self.driver.shutdown().await } + + /// The agent's advertised session lifecycle methods. + pub fn session_ops(&self) -> crate::AcpSessionOps { + self.driver.session_ops() + } } impl Drop for AcpHarness { @@ -224,9 +237,22 @@ impl HarnessDriver for AcpHarness { }) } - fn sessions<'a>(&'a self, _query: SessionQuery) -> DriverFuture<'a, SessionPage> { - // ACP lists no sessions; the native drivers own the session browser. - Box::pin(async { Ok(SessionPage::default()) }) + fn sessions<'a>(&'a self, query: SessionQuery) -> DriverFuture<'a, SessionPage> { + Box::pin(async move { + // An agent without `session/list` has no browser. ACP has no + // archive, so `archived` and the page size have nothing to change. + if !self.driver.session_ops().list { + return Ok(SessionPage::default()); + } + let listing = self + .driver + .list_sessions( + query.folder, + query.cursor.map(|cursor| cursor.as_str().to_owned()), + ) + .await?; + Ok(session_page(&self.provider, listing)) + }) } fn open<'a>(&'a self, spec: OpenSpec) -> HarnessFuture<'a, Arc, OpenError> { @@ -258,10 +284,17 @@ impl HarnessDriver for AcpHarness { })?; session.clone() } - OpenMode::Fork { .. } => { - return Err(OpenError::Unavailable(Availability::unavailable( - "fork is unsupported (reduced mode: ACP)", - ))); + OpenMode::Fork { session, at } => { + if let Some(unavailable) = fork_unavailable(self.driver.session_ops(), at) { + return Err(OpenError::Unavailable(unavailable)); + } + self.driver + .fork_session(session, spec.folder.clone()) + .await + .map_err(|error| match error { + DriverError::InvalidSession(_) => OpenError::NotFound, + other => OpenError::Driver(other), + })? } }; let key = SessionKey { @@ -284,6 +317,7 @@ impl HarnessDriver for AcpHarness { key, session, driver: self.driver.clone(), + catalog_sessions: self.catalog_sessions.clone(), instructions: spec.instructions.clone(), mutation: tokio::sync::Mutex::new(()), }); @@ -329,7 +363,8 @@ struct AcpState { struct AcpSessionInner { key: SessionKey, session: ProviderSessionId, - driver: Arc, + driver: Arc, + catalog_sessions: CatalogSessions, hub: EventHub, tracker: Mutex, state: Mutex, @@ -363,6 +398,61 @@ pub struct AcpSession { inner: Arc, } +/// Why a fork cannot be opened, if it cannot: the agent must advertise +/// `session/fork`, which copies the whole session and has no fork point. +pub(crate) fn fork_unavailable( + ops: crate::AcpSessionOps, + at: &Option, +) -> Option { + if !ops.fork { + Some(Availability::unavailable( + "fork is unsupported (reduced mode: ACP)", + )) + } else if at.is_some() { + Some(Availability::unavailable( + "this agent forks only at the end of a session (reduced mode: ACP)", + )) + } else { + None + } +} + +/// Maps one `session/list` page onto the session browser's page. +fn session_page(provider: &ProviderId, listing: AcpSessionListing) -> SessionPage { + SessionPage { + sessions: listing + .sessions + .into_iter() + .map(|session| SessionSummary { + key: SessionKey { + provider: provider.clone(), + session: session.id, + }, + title: session.title, + preview: None, + folder: Some(session.cwd), + updated_at: session.updated_at.as_deref().and_then(unix_seconds), + held_by: None, + archived: false, + }) + .collect(), + next: listing.next_cursor.and_then(|cursor| { + SessionPageCursor::new(cursor) + .inspect_err(|error| { + log::warn!(target: "inline_agent_driver_acp", "dropping unusable session/list cursor: {error}"); + }) + .ok() + }), + } +} + +/// ACP's `updatedAt` is ISO 8601; the browser wants Unix seconds. +fn unix_seconds(timestamp: &str) -> Option { + chrono::DateTime::parse_from_rfc3339(timestamp) + .ok() + .map(|time| time.timestamp()) +} + /// The prompt for an input: the author's text, and Inline's note for the /// assistant (the trusted guide on the first turn, since ACP has no system /// prompt slot every agent honours; who sent it; the untrusted thread). @@ -606,9 +696,29 @@ impl Session for AcpSession { complete_if_active(&self.inner, turn, TurnOutcome::Interrupted); } self.inner.state().released = true; + // `session/close` frees the session in the agent so another client + // can take it. Without it, or if it fails, the agent still holds it. + let closed = self.inner.driver.session_ops().close + && self + .inner + .driver + .close_session(&self.inner.session) + .await + .is_ok(); + if closed { + self.inner + .catalog_sessions + .lock() + .await + .retain(|_, session| session != &self.inner.session); + } Ok(Released { key: self.inner.key.clone(), - outcome: ReleaseOutcome::Unsubscribed, + outcome: if closed { + ReleaseOutcome::NativeReleased + } else { + ReleaseOutcome::Unsubscribed + }, cancelled_interactions: cancelled, pending_inputs: Vec::new(), stopped_children: Vec::new(), diff --git a/crates/agent-driver-acp/src/isolated_harness.rs b/crates/agent-driver-acp/src/isolated_harness.rs index a75d5c8a4..5cc1e7533 100644 --- a/crates/agent-driver-acp/src/isolated_harness.rs +++ b/crates/agent-driver-acp/src/isolated_harness.rs @@ -21,6 +21,8 @@ pub struct IsolatedAcpHarness { bridge_version: String, tools: Option, info: RuntimeInfo, + /// What the agent advertised at connect; gates work before a launch. + session_ops: crate::AcpSessionOps, epochs: Mutex>, opening: tokio::sync::Mutex<()>, catalog_epoch: tokio::sync::Mutex)>>, @@ -47,12 +49,14 @@ impl IsolatedAcpHarness { let bridge_version = bridge_version.into(); let epoch = launch(&descriptor, &bridge_version, None, &[]).await?; let info = epoch.describe(); + let session_ops = epoch.session_ops(); epoch.shutdown().await?; Ok(Self { descriptor, bridge_version, tools, info, + session_ops, epochs: Mutex::new(HashMap::new()), opening: tokio::sync::Mutex::new(()), catalog_epoch: tokio::sync::Mutex::new(None), @@ -346,8 +350,42 @@ impl HarnessDriver for IsolatedAcpHarness { }) } - fn sessions<'a>(&'a self, _query: SessionQuery) -> DriverFuture<'a, SessionPage> { - Box::pin(async { Ok(SessionPage::default()) }) + fn sessions<'a>(&'a self, query: SessionQuery) -> DriverFuture<'a, SessionPage> { + Box::pin(async move { + if !self.session_ops.list { + return Ok(SessionPage::default()); + } + if self.stopped.load(Ordering::SeqCst) { + return Err(DriverError::Unavailable("ACP harness stopped".into())); + } + // Listing reads the agent's store, so the tool-free picker probe + // can answer. Without one, a short-lived tool-free process does. + let probe = self + .catalog_epoch + .lock() + .await + .as_ref() + .map(|(_, epoch)| epoch.clone()) + .filter(|epoch| { + epoch + .process_status() + .is_none_or(|status| !status.is_finished()) + }); + let mut page = match probe { + Some(epoch) => epoch.sessions(query).await?, + None => { + let epoch = launch(&self.descriptor, &self.bridge_version, None, &[]).await?; + let page = epoch.sessions(query).await; + let _ = epoch.shutdown().await; + page? + } + }; + // Picker probes are this harness's own sessions, not the person's. + let probes = self.catalog_sessions.lock().unwrap(); + page.sessions + .retain(|summary| !probes.values().any(|probe| probe == &summary.key.session)); + Ok(page) + }) } fn open<'a>(&'a self, spec: OpenSpec) -> HarnessFuture<'a, Arc, OpenError> { @@ -358,6 +396,12 @@ impl HarnessDriver for IsolatedAcpHarness { "ACP harness stopped".into(), ))); } + // Refuse an unadvertised fork before launching a process for it. + if let OpenMode::Fork { at, .. } = &spec.mode + && let Some(unavailable) = crate::harness::fork_unavailable(self.session_ops, at) + { + return Err(OpenError::Unavailable(unavailable)); + } if let OpenMode::Resume { session } = &spec.mode { let held = self .epochs diff --git a/crates/agent-driver-acp/src/lib.rs b/crates/agent-driver-acp/src/lib.rs index 63a07c687..6e92f4fd2 100644 --- a/crates/agent-driver-acp/src/lib.rs +++ b/crates/agent-driver-acp/src/lib.rs @@ -12,7 +12,7 @@ mod process; mod support; pub use descriptor::{AcpDescriptorError, AcpLaunchDescriptor}; -pub use driver::AcpDriver; +pub use driver::{AcpDriver, AcpSessionOps}; pub use harness::{AcpHarness, AcpSession, acp_availability}; pub use host_tools::run_inline_tools_mcp; pub use isolated_harness::IsolatedAcpHarness; diff --git a/crates/agent-driver-acp/tests/session_ops.rs b/crates/agent-driver-acp/tests/session_ops.rs new file mode 100644 index 000000000..57490f368 --- /dev/null +++ b/crates/agent-driver-acp/tests/session_ops.rs @@ -0,0 +1,562 @@ +//! Session list, fork and close for ACP agents, gated on what each agent +//! advertises in `sessionCapabilities`. An agent that does not advertise a +//! method must never be sent it. +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use agent_client_protocol::{Agent, ConnectionTo, schema::v1 as acp}; +use futures_util::StreamExt; +use inline_agent_bridge::harness::*; +use inline_agent_bridge::{AgentDriver, DriverError, ProviderId, TurnOutcome}; +use inline_agent_driver_acp::{AcpDriver, AcpHarness, AcpSessionOps}; + +/// What the scripted agent advertises and how it misbehaves. +#[derive(Clone, Copy, Default)] +struct Script { + list: bool, + fork: bool, + close: bool, + fail_close: bool, +} + +impl Script { + fn all() -> Self { + Self { + list: true, + fork: true, + close: true, + fail_close: false, + } + } +} + +#[derive(Default)] +struct Seen { + lists: Vec<(Option, Option)>, + forks: Vec<(String, PathBuf, usize)>, + closes: Vec, + prompts: Vec<(String, String)>, +} + +struct Fixture { + harness: AcpHarness, + driver: Arc, + seen: Arc>, +} + +async fn fixture(script: Script) -> Fixture { + let seen = Arc::new(Mutex::new(Seen::default())); + let (lists, forks, closes, prompts) = (seen.clone(), seen.clone(), seen.clone(), seen.clone()); + let agent = Agent + .builder() + .on_receive_request( + async move |r: acp::InitializeRequest, responder, _| { + let mut session = + acp::SessionCapabilities::new().resume(acp::SessionResumeCapabilities::new()); + if script.list { + session = session.list(acp::SessionListCapabilities::new()); + } + if script.fork { + session = session.fork(acp::SessionForkCapabilities::new()); + } + if script.close { + session = session.close(acp::SessionCloseCapabilities::new()); + } + responder.respond( + acp::InitializeResponse::new(r.protocol_version) + .agent_info(acp::Implementation::new("opencode", "2.0.32")) + .agent_capabilities( + acp::AgentCapabilities::new().session_capabilities(session), + ), + ) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + async |_r: acp::NewSessionRequest, responder, _| { + responder.respond(acp::NewSessionResponse::new("ses_new")) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + async |_r: acp::ResumeSessionRequest, responder, _| { + responder.respond(acp::ResumeSessionResponse::new()) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + async move |r: acp::ListSessionsRequest, responder, _| { + lists + .lock() + .unwrap() + .lists + .push((r.cwd.clone(), r.cursor.clone())); + if r.cwd.as_deref() == Some(Path::new("/broken")) { + return responder + .respond_with_error(agent_client_protocol::Error::internal_error()); + } + if r.cursor.is_some() { + return responder.respond(acp::ListSessionsResponse::new(vec![ + acp::SessionInfo::new("ses_three", "/tmp"), + ])); + } + responder.respond( + acp::ListSessionsResponse::new(vec![ + acp::SessionInfo::new("ses_one", "/tmp") + .title("Fix the reconnect race") + .updated_at("2026-11-23T08:15:30.123Z"), + // Unusable identity: dropped, not fatal. + acp::SessionInfo::new("bad\nid", "/tmp"), + acp::SessionInfo::new("ses_two", "/tmp/other") + .title(" ") + .updated_at("yesterday"), + ]) + .next_cursor("page-2"), + ) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + async move |r: acp::ForkSessionRequest, responder, _| { + forks.lock().unwrap().forks.push(( + r.session_id.to_string(), + r.cwd.clone(), + r.mcp_servers.len(), + )); + if r.session_id.to_string() == "ses_missing" { + return responder.respond_with_error( + agent_client_protocol::Error::resource_not_found(None), + ); + } + responder.respond(acp::ForkSessionResponse::new("ses_fork")) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + async move |r: acp::CloseSessionRequest, responder, _| { + closes.lock().unwrap().closes.push(r.session_id.to_string()); + if script.fail_close { + return responder + .respond_with_error(agent_client_protocol::Error::internal_error()); + } + responder.respond(acp::CloseSessionResponse::new()) + }, + agent_client_protocol::on_receive_request!(), + ) + .on_receive_request( + async move |r: acp::PromptRequest, + responder, + _connection: ConnectionTo| { + let text = r + .prompt + .iter() + .filter_map(|part| match part { + acp::ContentBlock::Text(text) => Some(text.text.as_str()), + _ => None, + }) + .collect::>() + .join(" "); + prompts + .lock() + .unwrap() + .prompts + .push((r.session_id.to_string(), text)); + responder.respond(acp::PromptResponse::new(acp::StopReason::EndTurn)) + }, + agent_client_protocol::on_receive_request!(), + ); + let driver = Arc::new(AcpDriver::connect_transport(agent, "test").await.unwrap()); + let harness = AcpHarness::new( + driver.clone(), + ProviderId::new("opencode").unwrap(), + ExecutableInfo { + path: "opencode".into(), + source: ExecutableSource::Path, + version: Some("2.0.32".into()), + sha256: None, + other_installs: Vec::new(), + }, + "test", + ); + Fixture { + harness, + driver, + seen, + } +} + +fn spec(mode: OpenMode) -> OpenSpec { + OpenSpec { + mode, + folder: PathBuf::from("/tmp"), + settings: Default::default(), + instructions: None, + title: None, + after: None, + output_mode: OutputMode::Detailed, + } +} + +fn fork_of(session: &str) -> OpenMode { + OpenMode::Fork { + session: inline_agent_bridge::ProviderSessionId::new(session).unwrap(), + at: None, + } +} + +fn listing(folder: &str, cursor: Option<&str>) -> SessionQuery { + SessionQuery { + folder: Some(folder.into()), + cursor: cursor.map(|cursor| inline_agent_bridge::SessionPageCursor::new(cursor).unwrap()), + ..SessionQuery::default() + } +} + +async fn turn(session: &dyn Session, id: &str, text: &str) { + let mut events = session.events(); + session + .send(Input { + id: InputId::new(id).unwrap(), + content: InputContent::text(text), + origin: Origin::Owner { user: UserId(1) }, + delivery: Delivery::Turn, + }) + .await + .unwrap(); + tokio::time::timeout(Duration::from_secs(5), async { + while let Some(envelope) = events.next().await { + if let Event::Turn { + phase: TurnPhase::Completed { outcome, .. }, + .. + } = envelope.event + { + assert_eq!(outcome, TurnOutcome::Completed); + return; + } + } + panic!("stream ended before the turn completed"); + }) + .await + .expect("turn timed out"); +} + +#[tokio::test] +async fn advertised_list_pages_through_the_agents_sessions() { + let f = fixture(Script::all()).await; + assert_eq!( + f.harness.session_ops(), + AcpSessionOps { + list: true, + fork: true, + close: true + } + ); + let page = f.harness.sessions(listing("/tmp", None)).await.unwrap(); + let ids = page + .sessions + .iter() + .map(|summary| summary.key.session.as_str()) + .collect::>(); + assert_eq!(ids, ["ses_one", "ses_two"], "unusable ids are dropped"); + let first = &page.sessions[0]; + assert_eq!(first.key.provider.as_str(), "opencode"); + assert_eq!(first.title.as_deref(), Some("Fix the reconnect race")); + assert_eq!(first.folder.as_deref(), Some(Path::new("/tmp"))); + assert_eq!(first.updated_at, Some(1_795_421_730)); + assert!(!first.archived && first.held_by.is_none()); + let second = &page.sessions[1]; + assert_eq!(second.title, None, "a blank title is no title"); + assert_eq!(second.updated_at, None, "an unparseable time is omitted"); + assert_eq!(second.folder.as_deref(), Some(Path::new("/tmp/other"))); + let next = page.next.expect("the agent's cursor carries over"); + assert_eq!(next.as_str(), "page-2"); + + let older = f + .harness + .sessions(listing("/tmp", Some("page-2"))) + .await + .unwrap(); + assert_eq!(older.sessions.len(), 1); + assert!(older.next.is_none()); + assert_eq!( + f.seen.lock().unwrap().lists, + [ + (Some(PathBuf::from("/tmp")), None), + (Some(PathBuf::from("/tmp")), Some("page-2".to_owned())), + ] + ); + f.driver.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn list_errors_reach_the_caller() { + let f = fixture(Script::all()).await; + let error = f + .harness + .sessions(listing("/broken", None)) + .await + .unwrap_err(); + assert!(matches!(error, DriverError::Rejected(_)), "{error:?}"); + // A failed read does not end the connection: other sessions keep working. + let session = f.harness.open(spec(OpenMode::Start)).await.unwrap(); + turn(session.as_ref(), "after-list-error", "still here").await; + f.driver.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn advertised_fork_opens_the_copy_with_this_threads_guide() { + let f = fixture(Script::all()).await; + let mut fork = spec(fork_of("ses_source")); + fork.instructions = Some("fork thread guide".into()); + let session = f.harness.open(fork).await.unwrap(); + assert_eq!(session.key().session.as_str(), "ses_fork"); + turn(session.as_ref(), "fork-first", "carry on").await; + turn(session.as_ref(), "fork-second", "and again").await; + { + let seen = f.seen.lock().unwrap(); + assert_eq!( + seen.forks, + [("ses_source".to_owned(), PathBuf::from("/tmp"), 0)] + ); + // Turns go to the fork, and the fork's new thread gets its guide once. + assert!(seen.prompts.iter().all(|(id, _)| id == "ses_fork")); + assert!(seen.prompts[0].1.contains("fork thread guide")); + assert!(!seen.prompts[1].1.contains("fork thread guide")); + } + f.driver.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn fork_point_and_missing_source_are_typed() { + let f = fixture(Script::all()).await; + let at_turn = f + .harness + .open(spec(OpenMode::Fork { + session: inline_agent_bridge::ProviderSessionId::new("ses_source").unwrap(), + at: Some(ForkPoint::Turn { + turn: inline_agent_bridge::TurnId::new("turn-1").unwrap(), + }), + })) + .await; + assert!( + matches!(at_turn, Err(OpenError::Unavailable(_))), + "session/fork has no fork point" + ); + assert!(f.seen.lock().unwrap().forks.is_empty()); + let missing = f.harness.open(spec(fork_of("ses_missing"))).await; + assert!(matches!(missing, Err(OpenError::NotFound))); + f.driver.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn advertised_close_releases_the_session_natively() { + let f = fixture(Script::all()).await; + let session = f.harness.open(spec(OpenMode::Start)).await.unwrap(); + turn(session.as_ref(), "before-close", "hello").await; + let released = session.release().await.unwrap(); + assert_eq!(released.outcome, ReleaseOutcome::NativeReleased); + assert_eq!(f.seen.lock().unwrap().closes, ["ses_new"]); + // The closed session can be resumed again as usual. + let resumed = f + .harness + .open(spec(OpenMode::Resume { + session: session.key().session.clone(), + })) + .await + .unwrap(); + turn(resumed.as_ref(), "after-close", "back again").await; + f.driver.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn failed_close_leaves_the_session_held_by_the_agent() { + let f = fixture(Script { + fail_close: true, + ..Script::all() + }) + .await; + let session = f.harness.open(spec(OpenMode::Start)).await.unwrap(); + let released = session.release().await.unwrap(); + assert_eq!(released.outcome, ReleaseOutcome::Unsubscribed); + assert_eq!(f.seen.lock().unwrap().closes, ["ses_new"]); + f.driver.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn unadvertised_methods_are_never_sent() { + let f = fixture(Script::default()).await; + assert_eq!(f.harness.session_ops(), AcpSessionOps::default()); + let page = f.harness.sessions(listing("/tmp", None)).await.unwrap(); + assert_eq!(page, SessionPage::default()); + let fork = f.harness.open(spec(fork_of("ses_source"))).await; + assert!(matches!(fork, Err(OpenError::Unavailable(_)))); + let session = f.harness.open(spec(OpenMode::Start)).await.unwrap(); + turn(session.as_ref(), "plain", "hello").await; + let released = session.release().await.unwrap(); + assert_eq!(released.outcome, ReleaseOutcome::Unsubscribed); + { + let seen = f.seen.lock().unwrap(); + assert!(seen.lists.is_empty(), "session/list sent unadvertised"); + assert!(seen.forks.is_empty(), "session/fork sent unadvertised"); + assert!(seen.closes.is_empty(), "session/close sent unadvertised"); + } + f.driver.shutdown().await.unwrap(); +} + +/// The bridge's real ACP route: one private process per session. +#[cfg(unix)] +mod isolated { + use super::*; + use inline_agent_driver_acp::{AcpLaunchDescriptor, IsolatedAcpHarness}; + use std::os::unix::fs::PermissionsExt; + + fn agent(root: &Path, capabilities: &str) -> AcpLaunchDescriptor { + let script = root.join("session-ops-fixture"); + let source = r#"#!/usr/bin/env python3 +import json, sys, os +root = os.path.dirname(__file__) +session = 'ses_' + str(os.getpid()) +def record(method): + with open(os.path.join(root, 'requests'), 'a') as f: + f.write(str(os.getpid()) + ' ' + method + '\n') +for line in sys.stdin: + r = json.loads(line) + method, p = r.get('method'), r.get('params', {}) + if method: record(method) + if 'id' not in r: continue + if method == 'initialize': + value = {'protocolVersion':1, 'agentInfo':{'name':'opencode','version':'2.0.32'}, 'agentCapabilities':{'sessionCapabilities':CAPABILITIES}, 'authMethods':[]} + elif method in ['session/new', 'session/resume']: + session = p.get('sessionId', session) + value = {'sessionId':session, 'configOptions':[]} + elif method == 'session/list': + value = {'sessions':[{'sessionId':session,'cwd':p.get('cwd','/')},{'sessionId':'ses_old','cwd':p.get('cwd','/'),'title':'Earlier work'}]} + elif method == 'session/fork': + session = 'ses_fork_' + str(os.getpid()) + value = {'sessionId':session, 'configOptions':[]} + elif method == 'session/prompt': + value = {'stopReason':'end_turn'} + else: value = {} + print(json.dumps({'jsonrpc':'2.0','id':r['id'],'result':value}), flush=True) +"# + .replace("CAPABILITIES", capabilities); + std::fs::write(&script, source).unwrap(); + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap(); + AcpLaunchDescriptor::opencode(script) + } + + fn requests(root: &Path) -> Vec<(String, String)> { + std::fs::read_to_string(root.join("requests")) + .unwrap_or_default() + .lines() + .filter_map(|line| line.split_once(' ')) + .map(|(pid, method)| (pid.to_owned(), method.to_owned())) + .collect() + } + + fn count(root: &Path, method: &str) -> usize { + requests(root).iter().filter(|(_, m)| m == method).count() + } + + #[tokio::test] + async fn advertised_ops_run_in_the_right_process() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let harness = IsolatedAcpHarness::connect( + agent(&root, "{'resume':{},'list':{},'fork':{},'close':{}}"), + "test", + None, + ) + .await + .unwrap(); + // The tool-free picker probe answers listings; its own session is hidden. + harness + .catalog(CatalogScope { + folder: Some(root.clone()), + session: None, + }) + .await + .unwrap(); + let launched = count(&root, "initialize"); + let page = harness + .sessions(SessionQuery { + folder: Some(root.clone()), + ..SessionQuery::default() + }) + .await + .unwrap(); + let ids = page + .sessions + .iter() + .map(|summary| summary.key.session.as_str()) + .collect::>(); + assert_eq!(ids, ["ses_old"], "the probe's session is not listed"); + assert_eq!(count(&root, "initialize"), launched, "the probe listed"); + + let fork = harness + .open(OpenSpec { + folder: root.clone(), + ..spec(fork_of("ses_old")) + }) + .await + .unwrap(); + let (fork_pid, _) = requests(&root) + .into_iter() + .find(|(_, method)| method == "session/fork") + .expect("session/fork sent"); + assert_eq!(fork.key().session.as_str(), format!("ses_fork_{fork_pid}")); + turn(fork.as_ref(), "isolated-fork", "hello").await; + assert_eq!( + fork.release().await.unwrap().outcome, + ReleaseOutcome::NativeReleased + ); + assert!( + requests(&root).contains(&(fork_pid, "session/close".to_owned())), + "the fork's own process is asked to close it" + ); + harness.shutdown().await.unwrap(); + } + + #[tokio::test] + async fn unadvertised_ops_launch_nothing_and_send_nothing() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let harness = IsolatedAcpHarness::connect(agent(&root, "{'resume':{}}"), "test", None) + .await + .unwrap(); + assert_eq!(count(&root, "initialize"), 1); + let page = harness + .sessions(SessionQuery { + folder: Some(root.clone()), + ..SessionQuery::default() + }) + .await + .unwrap(); + assert!(page.sessions.is_empty()); + let fork = harness + .open(OpenSpec { + folder: root.clone(), + ..spec(fork_of("ses_old")) + }) + .await; + assert!(matches!(fork, Err(OpenError::Unavailable(_)))); + assert_eq!(count(&root, "initialize"), 1, "nothing was launched"); + let session = harness + .open(OpenSpec { + folder: root.clone(), + ..spec(OpenMode::Start) + }) + .await + .unwrap(); + assert_eq!( + session.release().await.unwrap().outcome, + ReleaseOutcome::NativeReleased, + "the private process is stopped either way" + ); + for method in ["session/list", "session/fork", "session/close"] { + assert_eq!(count(&root, method), 0, "{method} sent unadvertised"); + } + harness.shutdown().await.unwrap(); + } +} From a5469b5265aa069e88ac2177136c18d6e4602c68 Mon Sep 17 00:00:00 2001 From: Mo Rajabi Date: Mon, 23 Nov 2026 14:21:37 +0000 Subject: [PATCH 2/2] acp: give up on a stalled session/close after 2 s so release never waits on it --- crates/agent-driver-acp/src/driver.rs | 15 ++-- crates/agent-driver-acp/tests/session_ops.rs | 77 +++++++++++++++++++- 2 files changed, 86 insertions(+), 6 deletions(-) diff --git a/crates/agent-driver-acp/src/driver.rs b/crates/agent-driver-acp/src/driver.rs index d60adb43b..c60173df5 100644 --- a/crates/agent-driver-acp/src/driver.rs +++ b/crates/agent-driver-acp/src/driver.rs @@ -33,6 +33,9 @@ use crate::mapping::{ const CONNECTION_TIMEOUT: Duration = Duration::from_secs(15); const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); +/// Release waits on `session/close`; an agent that stalls must not hold the +/// chat. Past this, release goes on as if close were unsupported. +const CLOSE_TIMEOUT: Duration = Duration::from_secs(2); const MAX_FINAL_AGENT_TEXT_BYTES: usize = 64 * 1024; const TRUNCATED_AGENT_TEXT_MARKER: &str = "\n[additional agent output omitted]"; const MAX_PENDING_APPROVALS: usize = 32; @@ -979,19 +982,21 @@ impl AcpDriver { } /// Asks the agent to free a session (`session/close`), then forgets it - /// here. A failure leaves the session recorded: its state is unknown. + /// here. A failure or a reply slower than [`CLOSE_TIMEOUT`] leaves the + /// session recorded: its state is unknown. Never ends the connection. pub(crate) async fn close_session(&self, session: &ProviderSessionId) -> DriverResult<()> { if !self.session_ops.close { return Err(DriverError::Unsupported("ACP session/close")); } - request_with_timeout( - "session/close", - &self.auth_methods, + tokio::time::timeout( + CLOSE_TIMEOUT, self.connection .send_request(acp::CloseSessionRequest::new(session.to_string())) .block_task(), ) - .await?; + .await + .map_err(|_| DriverError::Transient("ACP session/close timed out".to_string()))? + .map_err(|error| acp_request_error(error, &self.auth_methods))?; cancel_pending_approvals(&self.approvals, Some(session.as_str())); cancel_pending_elicitations(&self.elicitations, Some(session.as_str())); let mut sessions = self.sessions.lock().expect("ACP session registry poisoned"); diff --git a/crates/agent-driver-acp/tests/session_ops.rs b/crates/agent-driver-acp/tests/session_ops.rs index 57490f368..1e19d53f9 100644 --- a/crates/agent-driver-acp/tests/session_ops.rs +++ b/crates/agent-driver-acp/tests/session_ops.rs @@ -18,6 +18,7 @@ struct Script { fork: bool, close: bool, fail_close: bool, + hang_close: bool, } impl Script { @@ -27,6 +28,7 @@ impl Script { fork: true, close: true, fail_close: false, + hang_close: false, } } } @@ -136,6 +138,14 @@ async fn fixture(script: Script) -> Fixture { .on_receive_request( async move |r: acp::CloseSessionRequest, responder, _| { closes.lock().unwrap().closes.push(r.session_id.to_string()); + if script.hang_close { + // Never answer, without blocking the agent's dispatch. + tokio::spawn(async move { + tokio::time::sleep(Duration::from_secs(3600)).await; + drop(responder); + }); + return Ok(()); + } if script.fail_close { return responder .respond_with_error(agent_client_protocol::Error::internal_error()); @@ -383,6 +393,32 @@ async fn failed_close_leaves_the_session_held_by_the_agent() { f.driver.shutdown().await.unwrap(); } +#[tokio::test] +async fn a_stalled_close_does_not_hold_the_release() { + let f = fixture(Script { + hang_close: true, + ..Script::all() + }) + .await; + let session = f.harness.open(spec(OpenMode::Start)).await.unwrap(); + let started = std::time::Instant::now(); + let released = tokio::time::timeout(Duration::from_secs(10), session.release()) + .await + .expect("release waited on the stalled close") + .unwrap(); + assert!( + started.elapsed() < Duration::from_secs(5), + "{:?}", + started.elapsed() + ); + assert_eq!(released.outcome, ReleaseOutcome::Unsubscribed); + assert_eq!(f.seen.lock().unwrap().closes, ["ses_new"]); + // The connection survives: another session still works. + let other = f.harness.open(spec(OpenMode::Start)).await.unwrap(); + turn(other.as_ref(), "after-stalled-close", "still here").await; + f.driver.shutdown().await.unwrap(); +} + #[tokio::test] async fn unadvertised_methods_are_never_sent() { let f = fixture(Script::default()).await; @@ -412,6 +448,10 @@ mod isolated { use std::os::unix::fs::PermissionsExt; fn agent(root: &Path, capabilities: &str) -> AcpLaunchDescriptor { + agent_with(root, capabilities, false) + } + + fn agent_with(root: &Path, capabilities: &str, hang_close: bool) -> AcpLaunchDescriptor { let script = root.join("session-ops-fixture"); let source = r#"#!/usr/bin/env python3 import json, sys, os @@ -425,6 +465,7 @@ for line in sys.stdin: method, p = r.get('method'), r.get('params', {}) if method: record(method) if 'id' not in r: continue + if method == 'session/close' and HANG_CLOSE: continue if method == 'initialize': value = {'protocolVersion':1, 'agentInfo':{'name':'opencode','version':'2.0.32'}, 'agentCapabilities':{'sessionCapabilities':CAPABILITIES}, 'authMethods':[]} elif method in ['session/new', 'session/resume']: @@ -440,7 +481,8 @@ for line in sys.stdin: else: value = {} print(json.dumps({'jsonrpc':'2.0','id':r['id'],'result':value}), flush=True) "# - .replace("CAPABILITIES", capabilities); + .replace("CAPABILITIES", capabilities) + .replace("HANG_CLOSE", if hang_close { "True" } else { "False" }); std::fs::write(&script, source).unwrap(); std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o700)).unwrap(); AcpLaunchDescriptor::opencode(script) @@ -518,6 +560,39 @@ for line in sys.stdin: harness.shutdown().await.unwrap(); } + #[tokio::test] + async fn a_stalled_close_still_stops_the_process_promptly() { + let temp = tempfile::tempdir().unwrap(); + let root = temp.path().canonicalize().unwrap(); + let harness = IsolatedAcpHarness::connect( + agent_with(&root, "{'resume':{},'close':{}}", true), + "test", + None, + ) + .await + .unwrap(); + let session = harness + .open(OpenSpec { + folder: root.clone(), + ..spec(OpenMode::Start) + }) + .await + .unwrap(); + let started = std::time::Instant::now(); + let released = tokio::time::timeout(Duration::from_secs(10), session.release()) + .await + .expect("release waited on the stalled close") + .unwrap(); + assert!( + started.elapsed() < Duration::from_secs(5), + "{:?}", + started.elapsed() + ); + assert_eq!(released.outcome, ReleaseOutcome::NativeReleased); + assert_eq!(count(&root, "session/close"), 1); + harness.shutdown().await.unwrap(); + } + #[tokio::test] async fn unadvertised_ops_launch_nothing_and_send_nothing() { let temp = tempfile::tempdir().unwrap();