diff --git a/rustcode/engine/src/acp.rs b/rustcode/engine/src/acp.rs index 910103601..29c47e590 100644 --- a/rustcode/engine/src/acp.rs +++ b/rustcode/engine/src/acp.rs @@ -36,6 +36,7 @@ mod session_repair; mod session_replay; mod session_transfer; pub(crate) mod settings; +mod share; pub(crate) mod steer; mod stop; mod streaming; diff --git a/rustcode/engine/src/acp/builtin.rs b/rustcode/engine/src/acp/builtin.rs index 23a6105f2..a7b13f6db 100644 --- a/rustcode/engine/src/acp/builtin.rs +++ b/rustcode/engine/src/acp/builtin.rs @@ -150,6 +150,53 @@ pub(crate) trait BuiltinAgent: Send + Sync { /// Whether a queued prompt waits and no turn is running. fn has_queued_work(&self) -> AgentFuture<'_, bool>; + /// Start sharing `session_id` with the remote gateway under + /// `registration`: the publisher and the message that opens the link. + /// `None` when the thread no longer shows that session. + fn share<'a>( + &'a self, + session_id: &'a str, + registration: crate::remote::SessionRegistration, + ) -> AgentFuture< + 'a, + Option<( + Box, + crate::remote::owner::OwnerMessage, + )>, + >; + + /// Apply a device's mutation (prompt, cancel, answer, settings) to the + /// shared thread. + fn remote_mutation<'a>( + &'a self, + cancel_token: &'a mut tokio_util::sync::CancellationToken, + registration: &'a crate::remote::SessionRegistration, + request: &'a crate::remote::RemoteRequest, + ) -> AgentFuture<'a, Result>; + + /// Answer a device's read of the shared thread. + fn remote_read<'a>( + &'a self, + registration: &'a crate::remote::SessionRegistration, + request: &'a crate::remote::RemoteRequest, + ) -> AgentFuture<'a, Result>; + + /// The workspace a device's `get_changes` reads, checked like any read. + fn remote_changes_workspace<'a>( + &'a self, + registration: &'a crate::remote::SessionRegistration, + request: &'a crate::remote::RemoteRequest, + ) -> AgentFuture<'a, Result>; + + /// The thread's model, read without waiting: `None` while a turn holds + /// the thread. + fn selected_model(&self) -> Option; + + /// The thread's state, for the agent tests that still live in the + /// engine until the agent gets its own crate. + #[cfg(test)] + fn test_state(&self) -> Arc>; + /// The thread's transcript. fn history(&self) -> AgentFuture<'_, rustcode_core::History>; @@ -164,3 +211,29 @@ pub(crate) struct AttachSnapshot { pub(crate) config_options: Vec, pub(crate) usage: agent_client_protocol::schema::v1::SessionUpdate, } + +/// Publishes a shared built-in thread to the remote gateway. +pub(crate) trait BuiltinPublisher: Send { + /// Note an agent event the thread has applied. + fn observe(&mut self, event: &crate::controller::AgentUiEvent); + + /// Send a full snapshot on the next publish. + fn request_snapshot(&mut self); + + /// Drop events until the next resync snapshot: the link fell behind. + fn mark_lagging(&mut self); + + /// Sequence of the last event published. + fn sequence(&self) -> u64; + + /// What changed since the last publish. `None` when the thread no longer + /// shows the shared session. + fn publish(&mut self, room_for_resync: bool) -> AgentFuture<'_, Option>; +} + +/// One publish pass of a shared built-in thread. +pub(crate) struct Published { + pub(crate) messages: Vec, + /// A prompt is queued and no turn runs, so the turn loop should start. + pub(crate) queued_while_idle: bool, +} diff --git a/rustcode/engine/src/acp/prompt.rs b/rustcode/engine/src/acp/prompt.rs index 6926d7e4f..6debbfdbf 100644 --- a/rustcode/engine/src/acp/prompt.rs +++ b/rustcode/engine/src/acp/prompt.rs @@ -396,6 +396,70 @@ impl super::builtin::BuiltinAgent for StateAgent { }) } + fn share<'a>( + &'a self, + session_id: &'a str, + registration: crate::remote::SessionRegistration, + ) -> super::builtin::AgentFuture< + 'a, + Option<( + Box, + crate::remote::owner::OwnerMessage, + )>, + > { + Box::pin(super::share::share(&self.state, session_id, registration)) + } + + fn remote_mutation<'a>( + &'a self, + cancel_token: &'a mut tokio_util::sync::CancellationToken, + registration: &'a crate::remote::SessionRegistration, + request: &'a crate::remote::RemoteRequest, + ) -> super::builtin::AgentFuture< + 'a, + Result, + > { + Box::pin(super::share::mutate( + &self.state, + cancel_token, + registration, + request, + )) + } + + fn remote_read<'a>( + &'a self, + registration: &'a crate::remote::SessionRegistration, + request: &'a crate::remote::RemoteRequest, + ) -> super::builtin::AgentFuture< + 'a, + Result, + > { + Box::pin(super::share::read(&self.state, registration, request)) + } + + fn remote_changes_workspace<'a>( + &'a self, + registration: &'a crate::remote::SessionRegistration, + request: &'a crate::remote::RemoteRequest, + ) -> super::builtin::AgentFuture<'a, Result> + { + Box::pin(super::share::changes_workspace( + &self.state, + registration, + request, + )) + } + + fn selected_model(&self) -> Option { + super::share::selected_model(&self.state) + } + + #[cfg(test)] + fn test_state(&self) -> Arc> { + Arc::clone(&self.state) + } + fn last_active(&self) -> Option { self.state.try_lock().ok().and_then(|state| { state diff --git a/rustcode/engine/src/acp/remote.rs b/rustcode/engine/src/acp/remote.rs index 3264ee2ed..1a7278143 100644 --- a/rustcode/engine/src/acp/remote.rs +++ b/rustcode/engine/src/acp/remote.rs @@ -22,7 +22,6 @@ use tokio::sync::Mutex; use super::AcpSession; use super::session::{KnownTaskIds, SessionTurnState}; -use crate::app::AppState; use crate::controller::AgentUiEvent; use crate::harness::session::PermissionFuture; use crate::harness::session::{ClientSink, ExternalSession}; @@ -43,8 +42,8 @@ use crate::remote::owner::{ }; use crate::remote::{ OwnerFollowUp, ProjectionLimits, PromptDisposition, ReceiptState, RemoteErrorCode, - RemoteOperation, RemoteRequest, RemoteResponse, RemoteResult, RemoteSnapshot, SessionPublisher, - SessionRegistration, apply_session_mutation, read_session, + RemoteOperation, RemoteRequest, RemoteResponse, RemoteResult, RemoteSnapshot, + SessionRegistration, }; use crate::remote_gateway::address::ConnectionPath; use crate::remote_gateway::control::{ @@ -136,7 +135,6 @@ pub(crate) struct RemoteRevokeRequest { /// `/remote` starts and stays valid while the share exists. pub(crate) struct RemoteSession { pub session_id: String, - pub state: Arc>, pub agent: Arc, pub cwd: PathBuf, pub turns: Arc, @@ -167,7 +165,6 @@ impl RemoteSession { ) -> Arc { Arc::new(Self { session_id, - state: Arc::clone(&session.state), agent: Arc::clone(&session.agent), cwd: session.cwd.clone(), turns: Arc::clone(&session.turns), @@ -363,7 +360,7 @@ struct ShareState { /// from its state; a thread on an external harness publishes a snapshot /// whenever its mirror changed. enum Publisher { - Acp(SessionPublisher), + Acp(Box), Harness { sequence: u64, /// Asked for by the gateway, or owed after a lagging link. @@ -393,17 +390,13 @@ impl Publisher { } } - fn owns(&self, state: &AppState) -> bool { + async fn publish(&mut self, room_for_resync: bool) -> Option { match self { - Publisher::Acp(publisher) => publisher.owns(state), - Publisher::Harness { .. } => true, - } - } - - fn publish(&mut self, state: &AppState, room_for_resync: bool) -> Vec { - match self { - Publisher::Acp(publisher) => publisher.publish(state, room_for_resync), - Publisher::Harness { .. } => Vec::new(), + Publisher::Acp(publisher) => publisher.publish(room_for_resync).await, + Publisher::Harness { .. } => Some(super::builtin::Published { + messages: Vec::new(), + queued_while_idle: false, + }), } } @@ -694,12 +687,7 @@ impl RemoteManager { ); } let session = share.acp()?; - let model = session - .state - .try_lock() - .ok() - .map(|state| crate::remote::projection::project_settings(&state).selected_model) - .unwrap_or_default(); + let model = session.agent.selected_model().unwrap_or_default(); Some(RemoteSessionInfo { session_id: session_id.to_owned(), registration_epoch: epoch, @@ -866,16 +854,16 @@ impl RemoteManager { let (events, receiver) = mpsc::unbounded_channel(); let share_state = { - let state = session.state.lock().await; - if state.active_session_id != session.session_id { + let Some((publisher, register)) = session + .agent + .share(&session.session_id, registration.clone()) + .await + else { return Err(StartError::Refused( "the ACP session is no longer active".to_owned(), )); - } - let (publisher, register) = - SessionPublisher::register(&state, registration.clone(), state.has_active_turn()); + }; let publisher = Publisher::Acp(publisher); - drop(state); if let Err(error) = link.outbound.try_send(register) { return Err(StartError::Link(format!( "could not register the remote session: {error}" @@ -1819,13 +1807,10 @@ impl Share { .active_token() .unwrap_or_else(CancellationToken::new); if request.operation.is_mutation() { - match apply_session_mutation( - &session.state, - &mut cancel_token, - &self.registration, - &request, - ) - .await + match session + .agent + .remote_mutation(&mut cancel_token, &self.registration, &request) + .await { Ok(mutation) => { let follow_up = mutation.follow_up; @@ -1850,13 +1835,10 @@ impl Share { ) { // Git may take a moment: read it off the owner's // loop, with no lock held. - let app = session.state.lock().await; - let workspace = crate::remote::ops::changes_workspace( - &app, - &self.registration, - &request, - ); - drop(app); + let workspace = session + .agent + .remote_changes_workspace(&self.registration, &request) + .await; match workspace { Ok(root) => { tokio::spawn(async move { @@ -1874,14 +1856,10 @@ impl Share { Err(error) => reply.send(RemoteResponse::error(request_id, error)), } } else { - let app = session.state.lock().await; - let result = read_session( - &app, - &self.registration, - &request, - &ProjectionLimits::default(), - ); - drop(app); + let result = session + .agent + .remote_read(&self.registration, &request) + .await; match result { Ok(result) => reply.send(RemoteResponse::new(request_id, result)), Err(error) => reply.send(RemoteResponse::error(request_id, error)), @@ -1900,12 +1878,11 @@ impl Share { } } - let app = session.state.lock().await; - if !state.publisher.owns(&app) { - return false; - } let room_for_resync = state.link.outbound.capacity() > 1; - let mut messages = state.publisher.publish(&app, room_for_resync); + let Some(published) = state.publisher.publish(room_for_resync).await else { + return false; + }; + let mut messages = published.messages; if manager.can_host_threads() { for message in &mut messages { if let OwnerMessage::Snapshot { snapshot, .. } = message { @@ -1913,10 +1890,7 @@ impl Share { } } } - start_runner |= !session.runner.load(Ordering::Acquire) - && !app.has_active_turn() - && !app.pending_queue.is_empty(); - drop(app); + start_runner |= !session.runner.load(Ordering::Acquire) && published.queued_while_idle; for message in messages { match state.link.outbound.try_send(message) { diff --git a/rustcode/engine/src/acp/session.rs b/rustcode/engine/src/acp/session.rs index 5a3ae7aca..3c3697617 100644 --- a/rustcode/engine/src/acp/session.rs +++ b/rustcode/engine/src/acp/session.rs @@ -172,8 +172,7 @@ impl Drop for SessionTurnGuard { } pub(crate) struct AcpSession { - pub(crate) state: Arc>, - /// The agent that runs the thread's prompts, over the same state. + /// The agent that runs the thread's prompts. pub(crate) agent: Arc, pub(crate) cwd: PathBuf, pub(crate) turns: Arc, diff --git a/rustcode/engine/src/acp/session_load.rs b/rustcode/engine/src/acp/session_load.rs index f3c1750d2..ecf074cbd 100644 --- a/rustcode/engine/src/acp/session_load.rs +++ b/rustcode/engine/src/acp/session_load.rs @@ -570,7 +570,6 @@ pub(super) async fn create_builtin_session( session_id.clone(), AcpSession { agent, - state: Arc::clone(&state), cwd, turns: Arc::new(SessionTurnState::new()), task_events: Arc::new(std::sync::Mutex::new(task_receiver)), @@ -705,7 +704,6 @@ pub(super) async fn acp_load_session( session_id.clone(), AcpSession { agent, - state, cwd: cwd.clone(), turns: Arc::new(SessionTurnState::new()), task_events: Arc::new(std::sync::Mutex::new(task_receiver)), diff --git a/rustcode/engine/src/acp/share.rs b/rustcode/engine/src/acp/share.rs new file mode 100644 index 000000000..da86a31e5 --- /dev/null +++ b/rustcode/engine/src/acp/share.rs @@ -0,0 +1,104 @@ +//! The built-in agent's side of a remote share: it publishes the thread's +//! state to the gateway and answers device reads and mutations from it. + +use std::sync::Arc; + +use tokio::sync::Mutex; +use tokio_util::sync::CancellationToken; + +use super::builtin::{AgentFuture, BuiltinPublisher, Published}; +use crate::app::AppState; +use crate::controller::AgentUiEvent; +use crate::remote::owner::OwnerMessage; +use crate::remote::{ + ProjectionLimits, RemoteError, RemoteRequest, RemoteResult, SessionMutation, SessionPublisher, + SessionRegistration, +}; + +struct StatePublisher { + state: Arc>, + inner: SessionPublisher, +} + +impl BuiltinPublisher for StatePublisher { + fn observe(&mut self, event: &AgentUiEvent) { + self.inner.observe(event); + } + + fn request_snapshot(&mut self) { + self.inner.request_snapshot(); + } + + fn mark_lagging(&mut self) { + self.inner.mark_lagging(); + } + + fn sequence(&self) -> u64 { + self.inner.sequence() + } + + fn publish(&mut self, room_for_resync: bool) -> AgentFuture<'_, Option> { + Box::pin(async move { + let state = self.state.lock().await; + if !self.inner.owns(&state) { + return None; + } + let messages = self.inner.publish(&state, room_for_resync); + Some(Published { + messages, + queued_while_idle: !state.has_active_turn() && !state.pending_queue.is_empty(), + }) + }) + } +} + +pub(super) async fn share( + state: &Arc>, + session_id: &str, + registration: SessionRegistration, +) -> Option<(Box, OwnerMessage)> { + let guard = state.lock().await; + if guard.active_session_id != session_id { + return None; + } + let (inner, register) = + SessionPublisher::register(&guard, registration, guard.has_active_turn()); + drop(guard); + let publisher = StatePublisher { + state: Arc::clone(state), + inner, + }; + Some((Box::new(publisher), register)) +} + +pub(super) async fn mutate( + state: &Arc>, + cancel_token: &mut CancellationToken, + registration: &SessionRegistration, + request: &RemoteRequest, +) -> Result { + crate::remote::apply_session_mutation(state, cancel_token, registration, request).await +} + +pub(super) async fn read( + state: &Mutex, + registration: &SessionRegistration, + request: &RemoteRequest, +) -> Result { + let state = state.lock().await; + crate::remote::read_session(&state, registration, request, &ProjectionLimits::default()) +} + +pub(super) async fn changes_workspace( + state: &Mutex, + registration: &SessionRegistration, + request: &RemoteRequest, +) -> Result { + let state = state.lock().await; + crate::remote::ops::changes_workspace(&state, registration, request) +} + +pub(super) fn selected_model(state: &Mutex) -> Option { + let state = state.try_lock().ok()?; + Some(crate::remote::projection::project_settings(&state).selected_model) +} diff --git a/rustcode/engine/src/acp_tests.rs b/rustcode/engine/src/acp_tests.rs index d9be910e9..061b0009b 100644 --- a/rustcode/engine/src/acp_tests.rs +++ b/rustcode/engine/src/acp_tests.rs @@ -211,8 +211,7 @@ fn loading_an_already_active_session_is_rejected() { sessions.insert( "active-session".into(), AcpSession { - agent: prompt::builtin_agent(Arc::clone(&state)), - state, + agent: prompt::builtin_agent(state), cwd: PathBuf::from("/tmp"), turns: Arc::new(SessionTurnState::new()), task_events: Arc::new(std::sync::Mutex::new(receiver)), @@ -255,8 +254,7 @@ async fn unregistering_failed_session_load_removes_registry_and_task_route() { server.sessions.lock().await.insert( session_id.into(), AcpSession { - agent: prompt::builtin_agent(Arc::clone(&state)), - state, + agent: prompt::builtin_agent(state), cwd: PathBuf::from("/tmp"), turns: Arc::new(SessionTurnState::new()), task_events: Arc::new(std::sync::Mutex::new(task_receiver)), @@ -2325,8 +2323,8 @@ async fn two_connections() { let (a_state, b_state) = { let sessions = server.sessions.lock().await; ( - Arc::clone(&sessions[&a_session].state), - Arc::clone(&sessions[&b_session].state), + sessions[&a_session].agent.test_state(), + sessions[&b_session].agent.test_state(), ) }; let a_preview = { @@ -2532,7 +2530,7 @@ fn serve_on_thread( /// Point a session at `endpoint`, with an earlier exchange in its history. async fn use_provider(server: &AcpServer, session_id: &str, endpoint: &str) { use crate::config::{ApiProtocol, ModelProfile}; - let state = Arc::clone(&server.sessions.lock().await[session_id].state); + let state = server.sessions.lock().await[session_id].agent.test_state(); let mut state = state.lock().await; state.api_base_url = endpoint.to_owned(); state.model_name = "held-test".to_owned(); @@ -2806,7 +2804,7 @@ async fn turn_outlives_client() { }) .await; let answer = { - let state = Arc::clone(&server.sessions.lock().await[&session_id].state); + let state = server.sessions.lock().await[&session_id].agent.test_state(); let state = state.lock().await; state.history.last().map(|message| message.content.clone()) };