From cce0e583f1ee464b0fd809030d9a6ae06870859d Mon Sep 17 00:00:00 2001 From: LHagfoss Date: Sun, 22 Nov 2026 19:42:28 +0100 Subject: [PATCH 1/3] refactor(engine): run remote turns through the built-in agent trait Remote turns take queued prompts, run them and promote leftover steers through BuiltinAgent instead of locking AppState and calling run_prompt. --- rustcode/engine/src/acp/builtin.rs | 11 ++++++ rustcode/engine/src/acp/prompt.rs | 32 +++++++++++++++ rustcode/engine/src/acp/remote.rs | 63 ++++++++++++------------------ 3 files changed, 67 insertions(+), 39 deletions(-) diff --git a/rustcode/engine/src/acp/builtin.rs b/rustcode/engine/src/acp/builtin.rs index e4cf7350a..23a6105f2 100644 --- a/rustcode/engine/src/acp/builtin.rs +++ b/rustcode/engine/src/acp/builtin.rs @@ -139,6 +139,17 @@ pub(crate) trait BuiltinAgent: Send + Sync { approvals: Vec, ) -> AgentFuture<'_, ()>; + /// Take the next queued prompt of `session_id` to run, when it is the + /// thread's open session and no turn is running. + fn take_queued<'a>(&'a self, session_id: &'a str) -> AgentFuture<'a, Option>; + + /// Move the steers the last turn of `session_id` did not read onto the + /// prompt queue. + fn promote_steers<'a>(&'a self, session_id: &'a str) -> AgentFuture<'a, ()>; + + /// Whether a queued prompt waits and no turn is running. + fn has_queued_work(&self) -> AgentFuture<'_, bool>; + /// The thread's transcript. fn history(&self) -> AgentFuture<'_, rustcode_core::History>; diff --git a/rustcode/engine/src/acp/prompt.rs b/rustcode/engine/src/acp/prompt.rs index 1e1224a0a..6926d7e4f 100644 --- a/rustcode/engine/src/acp/prompt.rs +++ b/rustcode/engine/src/acp/prompt.rs @@ -364,6 +364,38 @@ impl super::builtin::BuiltinAgent for StateAgent { }) } + fn take_queued<'a>( + &'a self, + session_id: &'a str, + ) -> super::builtin::AgentFuture<'a, Option> { + Box::pin(async move { + let mut state = self.state.lock().await; + if state.active_session_id != session_id + || state.pending_queue.is_empty() + || state.has_active_turn() + { + return None; + } + Some(state.pending_queue.remove(0)) + }) + } + + fn promote_steers<'a>(&'a self, session_id: &'a str) -> super::builtin::AgentFuture<'a, ()> { + Box::pin(async move { + self.state + .lock() + .await + .promote_pending_steers_to_queue(session_id); + }) + } + + fn has_queued_work(&self) -> super::builtin::AgentFuture<'_, bool> { + Box::pin(async move { + let state = self.state.lock().await; + !state.pending_queue.is_empty() && !state.has_active_turn() + }) + } + 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 f52da9d24..3264ee2ed 100644 --- a/rustcode/engine/src/acp/remote.rs +++ b/rustcode/engine/src/acp/remote.rs @@ -137,6 +137,7 @@ pub(crate) struct RemoteRevokeRequest { pub(crate) struct RemoteSession { pub session_id: String, pub state: Arc>, + pub agent: Arc, pub cwd: PathBuf, pub turns: Arc, pub task_events: Arc>>, @@ -167,6 +168,7 @@ impl RemoteSession { Arc::new(Self { session_id, state: Arc::clone(&session.state), + agent: Arc::clone(&session.agent), cwd: session.cwd.clone(), turns: Arc::clone(&session.turns), task_events: Arc::clone(&session.task_events), @@ -208,18 +210,7 @@ async fn run_remote_turns(session: Arc) { if !session.sharing.load(Ordering::Acquire) { break; } - let prompt = { - let mut state = session.state.lock().await; - if state.active_session_id != session.session_id - || state.pending_queue.is_empty() - || state.has_active_turn() - { - None - } else { - Some(state.pending_queue.remove(0)) - } - }; - let Some(prompt) = prompt else { + let Some(prompt) = session.agent.take_queued(&session.session_id).await else { break; }; if prompt.starts_with("__task_wakeup__:") { @@ -237,24 +228,25 @@ async fn run_remote_turns(session: Arc) { session .presence .turn_started(&session.session_id, &session.cwd); - let result = super::prompt::run_prompt( - Arc::clone(&session.state), - session.cwd.clone(), - scheduled_turn, - session.session_id.clone(), - Arc::clone(&session.task_events), - Arc::clone(&session.known_task_ids), - Arc::clone(&session.terminal_backlog), - Arc::clone(&session.terminal_overflow), - prompt, - None, - session.clients.clone(), - Arc::clone(&session.client), - session.auto_approve, - Some(session.remote.clone()), - Arc::downgrade(&session.turns), - ) - .await; + let result = session + .agent + .prompt(super::builtin::BuiltinTurn { + session_id: session.session_id.clone(), + cwd: session.cwd.clone(), + text: prompt, + origin: None, + scheduled: scheduled_turn, + turns: Arc::downgrade(&session.turns), + task_events: Arc::clone(&session.task_events), + known_task_ids: Arc::clone(&session.known_task_ids), + terminal_backlog: Arc::clone(&session.terminal_backlog), + terminal_overflow: Arc::clone(&session.terminal_overflow), + clients: session.clients.clone(), + client: Arc::clone(&session.client), + auto_approve: session.auto_approve, + remote: Some(session.remote.clone()), + }) + .await; session .presence .turn_finished(&session.session_id, &session.cwd); @@ -264,20 +256,13 @@ async fn run_remote_turns(session: Arc) { ))); let _ = session.clients.update(update); } - { - let mut state = session.state.lock().await; - state.promote_pending_steers_to_queue(&session.session_id); - } + session.agent.promote_steers(&session.session_id).await; } session.runner.store(false, Ordering::Release); // A prompt queued between the last check and the flag clear would // otherwise sit until the next status poll. if session.sharing.load(Ordering::Acquire) { - let has_work = { - let state = session.state.lock().await; - !state.pending_queue.is_empty() && !state.has_active_turn() - }; - if has_work { + if session.agent.has_queued_work().await { session.ensure_runner(); } } From fca1a67a5e269886f67f847fa795a49922c11888 Mon Sep 17 00:00:00 2001 From: LHagfoss Date: Sun, 22 Nov 2026 19:45:55 +0100 Subject: [PATCH 2/3] refactor(engine): share built-in threads through the agent trait The remote share's publisher, device reads, mutations and changes workspace go through BuiltinAgent and a BuiltinPublisher trait object. RemoteSession and AcpSession no longer hold the thread's AppState. --- rustcode/engine/src/acp.rs | 1 + rustcode/engine/src/acp/builtin.rs | 73 +++++++++++++++++ rustcode/engine/src/acp/prompt.rs | 64 +++++++++++++++ rustcode/engine/src/acp/remote.rs | 92 ++++++++------------- rustcode/engine/src/acp/session.rs | 3 +- rustcode/engine/src/acp/session_load.rs | 2 - rustcode/engine/src/acp/share.rs | 104 ++++++++++++++++++++++++ rustcode/engine/src/acp_tests.rs | 14 ++-- 8 files changed, 282 insertions(+), 71 deletions(-) create mode 100644 rustcode/engine/src/acp/share.rs 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()) }; From bd82ff9a973b99a4f167e4d0e2a42e18da3315a0 Mon Sep 17 00:00:00 2001 From: LHagfoss Date: Sun, 22 Nov 2026 19:48:38 +0100 Subject: [PATCH 3/3] refactor(engine): open built-in threads through the agent The agent builds a new or loaded thread's state in acp/builtin_open.rs and hands the server the trait object, its clients and its opening snapshot; session_load no longer builds or reads AppState. --- rustcode/engine/src/acp.rs | 23 +--- rustcode/engine/src/acp/builtin_open.rs | 151 ++++++++++++++++++++++++ rustcode/engine/src/acp/session_load.rs | 132 +++++---------------- scripts/comment-baseline.txt | 3 +- scripts/rust-size-baseline.txt | 2 +- 5 files changed, 184 insertions(+), 127 deletions(-) create mode 100644 rustcode/engine/src/acp/builtin_open.rs diff --git a/rustcode/engine/src/acp.rs b/rustcode/engine/src/acp.rs index 29c47e590..76637e934 100644 --- a/rustcode/engine/src/acp.rs +++ b/rustcode/engine/src/acp.rs @@ -1,6 +1,7 @@ mod agents; mod attachments; pub(crate) mod builtin; +mod builtin_open; mod capabilities; pub(crate) mod clients; mod commands; @@ -44,6 +45,7 @@ mod telemetry; mod themes; pub(crate) mod usage; mod workflows; +pub(crate) use builtin_open::*; pub(crate) use session_load::*; mod extensions; pub(crate) use extensions::*; @@ -475,27 +477,6 @@ async fn close_builtin(server: &AcpServer, session_id: &str) -> Option agent_client_protocol::Error { agent_client_protocol::Error::invalid_params() .data(format!("unknown ACP session: {session_id}")) diff --git a/rustcode/engine/src/acp/builtin_open.rs b/rustcode/engine/src/acp/builtin_open.rs new file mode 100644 index 000000000..54cf41e49 --- /dev/null +++ b/rustcode/engine/src/acp/builtin_open.rs @@ -0,0 +1,151 @@ +//! Opening a built-in thread: the agent builds the state of a new or loaded +//! session and hands the server the trait object that runs it. + +use super::*; + +/// A built-in thread the agent opened, with what its first client gets. +pub(crate) struct OpenedThread { + pub(crate) session_id: String, + pub(crate) agent: Arc, + pub(crate) clients: clients::SessionClients, + pub(crate) snapshot: builtin::AttachSnapshot, +} + +/// Open a new thread in `cwd` with the model and effort `start` names. +/// `attach` gives the clients of the session id the agent picked. +pub(super) fn create_thread( + cwd: &std::path::Path, + start: &crate::harness::HarnessRequest, + info: clients::ClientInfo, + attach: impl FnOnce(&str) -> clients::SessionClients, +) -> OpenedThread { + let mut state = new_session_state(cwd); + let session_id = state.active_session_id.clone(); + let clients = attach(&session_id); + apply_client_info(&mut state, info, &clients); + state.raw_cli_mode = false; + state.task_working_directory = Some(cwd.to_path_buf()); + // ACP's requested cwd is both the task's initial location + // and its hard filesystem boundary, independent of the + // directory from which RustCode itself was launched. + state.workspace_root = Some(cwd.to_path_buf()); + apply_requested_model_and_effort(&mut state, start); + opened(state, clients) +} + +/// Open the saved thread `session_id` in `cwd` with `history`. +pub(super) fn load_thread( + session_id: &str, + cwd: &std::path::Path, + history: Vec, + info: clients::ClientInfo, + clients: clients::SessionClients, +) -> OpenedThread { + let mut state = build_loaded_app_state(session_id, cwd, history); + apply_client_info(&mut state, info, &clients); + opened(state, clients) +} + +fn opened(state: crate::app::AppState, clients: clients::SessionClients) -> OpenedThread { + let snapshot = builtin::AttachSnapshot { + compaction: state.last_compaction.clone(), + config_options: build_session_config_options(&state), + usage: usage::usage_update(&state), + }; + let session_id = state.active_session_id.clone(); + OpenedThread { + session_id, + agent: super::prompt::builtin_agent(Arc::new(Mutex::new(state))), + clients, + snapshot, + } +} + +pub(crate) fn build_loaded_app_state( + session_id: &str, + cwd: &std::path::Path, + history: Vec, +) -> crate::app::AppState { + let mut state = crate::app::AppState::new_with_workspace_session(cwd, Some(session_id)); + state.restore_session_model(); + state.restore_session_compaction(); + state.task_working_directory = Some(cwd.to_path_buf()); + state.workspace_root = Some(cwd.to_path_buf()); + // Reattach the session's recorded task worktree so resume reuses its + // writable roots and cwd instead of starting over in the source checkout + // (#1496). A missing or foreign worktree falls back to `cwd`. + if let Some(workspace) = crate::sessions::load_session_workspace(session_id) + && let Some(descriptor_id) = workspace.task_workspace_id + && let Some(manager) = crate::sessions::workspace_manager() + && let Ok(descriptor) = manager.resume(&descriptor_id) + { + state.workspace_root = Some(descriptor.workspace_path.clone()); + state.task_working_directory = Some(descriptor.workspace_path.clone()); + } + state.history.replace(history); + state +} + +/// State for `session/new`. The id is always fresh: reusing the shared +/// last-active session, as the TUI does when it is still empty, would hand two +/// ACP sessions (or two processes) the same history file. +pub(super) fn new_session_state(cwd: &std::path::Path) -> crate::app::AppState { + let session_id = crate::sessions::create_detached_session(); + let state = crate::app::AppState::new_with_workspace_session(cwd, Some(&session_id)); + if !session_id.is_empty() { + crate::sessions::record_session_settings(&session_id, &state.config); + state.record_session_model(); + } + state +} + +/// Give a session the client half of what its client advertised: how replies +/// are drawn, and the preview, desktop, orchestration and Smart UI requests. +/// Read once, from the client that created or loaded it, so its prompt never +/// changes mid-session; each request goes to whichever client has the +/// session then. +pub(super) fn apply_client_info( + state: &mut crate::app::AppState, + info: clients::ClientInfo, + clients: &clients::SessionClients, +) { + let secret_clients = clients.clone(); + state.secret_asker = Some(std::sync::Arc::new(move |request| { + let clients = secret_clients.clone(); + Box::pin(async move { clients.request(None, request).await.ok() }) + })); + state.visualization_level = info.visualization_level; + state.smart_ui = info.smart_ui; + state.preview_client = preview::preview_client_for(info.preview, clients); + state.desktop_client = preview::desktop_client_for(info.desktop, clients); + (state.orchestration_client, state.orchestration_version) = + preview::orchestration_for(info.orchestration, clients); + // No app hosting the tools: this engine serves the reads and names the app + // for the rest (#3422). An app that turned them off keeps them off. + state.local_orchestration = info.engine_hosts_orchestration(clients); + state.smart_ui_client = preview::smart_ui_client_for( + info.smart_ui == crate::app::SmartUi::On && info.smart_ui_preview, + clients, + ); +} + +/// A built-in `session/new` honours `_meta.rustcode.model` and `effort` the +/// same way external harnesses do (docs/harnesses.md). Model first, since +/// the effort choices depend on it; an unknown value is ignored and the +/// session keeps its default. +pub(super) fn apply_requested_model_and_effort( + state: &mut crate::app::AppState, + asked: &crate::harness::HarnessRequest, +) { + for (id, value) in [("model", &asked.model), ("effort", &asked.effort)] { + if let Some(value) = value { + let _ = handle_set_config_option( + state, + &agent_client_protocol::schema::v1::SessionConfigId::new(id), + &agent_client_protocol::schema::v1::SessionConfigOptionValue::value_id( + value.clone(), + ), + ); + } + } +} diff --git a/rustcode/engine/src/acp/session_load.rs b/rustcode/engine/src/acp/session_load.rs index ecf074cbd..8a53f875b 100644 --- a/rustcode/engine/src/acp/session_load.rs +++ b/rustcode/engine/src/acp/session_load.rs @@ -371,44 +371,6 @@ pub(super) fn replay_history_updates_with_compaction( updates } -pub(crate) fn build_loaded_app_state( - session_id: &str, - cwd: &std::path::Path, - history: Vec, -) -> crate::app::AppState { - let mut state = crate::app::AppState::new_with_workspace_session(cwd, Some(session_id)); - state.restore_session_model(); - state.restore_session_compaction(); - state.task_working_directory = Some(cwd.to_path_buf()); - state.workspace_root = Some(cwd.to_path_buf()); - // Reattach the session's recorded task worktree so resume reuses its - // writable roots and cwd instead of starting over in the source checkout - // (#1496). A missing or foreign worktree falls back to `cwd`. - if let Some(workspace) = crate::sessions::load_session_workspace(session_id) - && let Some(descriptor_id) = workspace.task_workspace_id - && let Some(manager) = crate::sessions::workspace_manager() - && let Ok(descriptor) = manager.resume(&descriptor_id) - { - state.workspace_root = Some(descriptor.workspace_path.clone()); - state.task_working_directory = Some(descriptor.workspace_path.clone()); - } - state.history.replace(history); - state -} - -/// State for `session/new`. The id is always fresh: reusing the shared -/// last-active session, as the TUI does when it is still empty, would hand two -/// ACP sessions (or two processes) the same history file. -pub(super) fn new_session_state(cwd: &std::path::Path) -> crate::app::AppState { - let session_id = crate::sessions::create_detached_session(); - let state = crate::app::AppState::new_with_workspace_session(cwd, Some(&session_id)); - if !session_id.is_empty() { - crate::sessions::record_session_settings(&session_id, &state.config); - state.record_session_model(); - } - state -} - pub(super) fn canonical_acp_cwd( cwd: &std::path::Path, operation: &str, @@ -466,36 +428,6 @@ pub(super) fn session_workspace( } } -/// Give a session the client half of what its client advertised: how replies -/// are drawn, and the preview, desktop, orchestration and Smart UI requests. -/// Read once, from the client that created or loaded it, so its prompt never -/// changes mid-session; each request goes to whichever client has the -/// session then. -pub(super) fn apply_client_info( - state: &mut crate::app::AppState, - info: clients::ClientInfo, - clients: &clients::SessionClients, -) { - let secret_clients = clients.clone(); - state.secret_asker = Some(std::sync::Arc::new(move |request| { - let clients = secret_clients.clone(); - Box::pin(async move { clients.request(None, request).await.ok() }) - })); - state.visualization_level = info.visualization_level; - state.smart_ui = info.smart_ui; - state.preview_client = preview::preview_client_for(info.preview, clients); - state.desktop_client = preview::desktop_client_for(info.desktop, clients); - (state.orchestration_client, state.orchestration_version) = - preview::orchestration_for(info.orchestration, clients); - // No app hosting the tools: this engine serves the reads and names the app - // for the rest (#3422). An app that turned them off keeps them off. - state.local_orchestration = info.engine_hosts_orchestration(clients); - state.smart_ui_client = preview::smart_ui_client_for( - info.smart_ui == crate::app::SmartUi::On && info.smart_ui_preview, - clients, - ); -} - /// The session `session/new` creates on the built-in harness: the engine's own /// chat state, its task route and the client it publishes to. Also what a /// thread a paired device asked for starts as (`super::hosted`), which is why @@ -506,8 +438,17 @@ pub(super) async fn create_builtin_session( request: NewSessionRequest, ) -> Result { let cwd = session_new_cwd(&request.cwd)?; - let mut state = new_session_state(&cwd); - let session_id = state.active_session_id.clone(); + // What the request asked for, else the built-in harness's + // remembered choice (docs/harnesses.md). + let start = crate::harness::builtin_start(&crate::harness::requested(request.meta.as_ref())); + let OpenedThread { + session_id, + agent, + clients: session_clients, + snapshot, + } = create_thread(&cwd, &start, peer.info(), |session_id| { + peer.attach(session_id) + }); // The name the thread was made with, from the app that made it (issue 3524). crate::sessions::save_requested_title(&session_id, request.meta.as_ref()); // Who started this thread, from the `_meta.rustcode.parent` its @@ -520,21 +461,6 @@ pub(super) async fn create_builtin_session( if let Some(job) = crate::sessions::requested_scheduled_job(request.meta.as_ref()) { crate::sessions::save_session_scheduled_job(&session_id, &job); } - let session_clients = peer.attach(&session_id); - apply_client_info(&mut state, peer.info(), &session_clients); - state.raw_cli_mode = false; - state.task_working_directory = Some(cwd.clone()); - // ACP's requested cwd is both the task's initial location - // and its hard filesystem boundary, independent of the - // directory from which RustCode itself was launched. - state.workspace_root = Some(cwd.clone()); - // What the request asked for, else the built-in harness's - // remembered choice (docs/harnesses.md). - apply_requested_model_and_effort( - &mut state, - &crate::harness::builtin_start(&crate::harness::requested(request.meta.as_ref())), - ); - let config_options = build_session_config_options(&state); let _ = crate::sessions::save_session_workspace( &session_id, &session_workspace(cwd.clone(), request.additional_directories.clone()), @@ -543,8 +469,6 @@ pub(super) async fn create_builtin_session( let known_task_ids = Arc::new(std::sync::Mutex::new(KnownTaskIds::default())); let terminal_backlog = Arc::new(std::sync::Mutex::new(VecDeque::new())); let terminal_overflow = Arc::new(AtomicBool::new(false)); - let state = Arc::new(Mutex::new(state)); - let agent = super::prompt::builtin_agent(Arc::clone(&state)); let task_sink = Arc::new(SessionTaskSink { agent: Arc::clone(&agent), clients: session_clients, @@ -581,18 +505,14 @@ pub(super) async fn create_builtin_session( // Commands, then the session's opening usage, so the client // shows its context meter from the start rather than only // after the first turn ends (#2414 follow-up). - let opening_usage = { - let state = state.lock().await; - usage::usage_update(&state) - }; - for update in [commands::available_commands_update(), opening_usage] { + for update in [commands::available_commands_update(), snapshot.usage] { if let Err(error) = peer.send_snapshot(&session_id, update) { unregister_acp_session(server, &session_id).await; return Err(agent_client_protocol::Error::internal_error().data(error.to_string())); } } Ok(NewSessionResponse::new(session_id) - .config_options(config_options) + .config_options(snapshot.config_options) .meta(crate::harness::builtin_session_meta())) } @@ -664,17 +584,21 @@ pub(super) async fn acp_load_session( agent_client_protocol::Error::invalid_params().data("session is already active") ); } - let mut state = build_loaded_app_state(&session_id, &cwd, history.clone()); // Not attached yet: the replay below attaches the loading client in // the same step that queues the transcript to it, so no live update // can land between its chunks. - let session_clients = peer.clients().session(&session_id); - apply_client_info(&mut state, peer.info(), &session_clients); - let config_options = build_session_config_options(&state); - let loaded_usage = usage::usage_update(&state); - let loaded_compaction = state.last_compaction.clone(); - let state = Arc::new(Mutex::new(state)); - let agent = super::prompt::builtin_agent(Arc::clone(&state)); + let OpenedThread { + agent, + clients: session_clients, + snapshot: loaded, + .. + } = load_thread( + &session_id, + &cwd, + history.clone(), + peer.info(), + peer.clients().session(&session_id), + ); let (task_sender, task_receiver) = std::sync::mpsc::sync_channel(64); let known_task_ids = Arc::new(std::sync::Mutex::new(KnownTaskIds::default())); let terminal_backlog = Arc::new(std::sync::Mutex::new(VecDeque::new())); @@ -716,7 +640,7 @@ pub(super) async fn acp_load_session( let replay = replay_history_updates_with_compaction( &history, Some(&cwd), - loaded_compaction.as_ref(), + loaded.compaction.as_ref(), ); let _ = crate::sessions::save_session_workspace( &session_id, @@ -732,7 +656,7 @@ pub(super) async fn acp_load_session( )); } snapshot.push(commands::available_commands_update()); - snapshot.push(loaded_usage); + snapshot.push(loaded.usage); load_pause::here(&session_id).await; // Queued and attached under one lock (see `Peer::attach_closed`): // the transcript, then what the session logged since `base`. @@ -750,7 +674,7 @@ pub(super) async fn acp_load_session( } return Ok(peer.position(&session_id, reset).finish( LoadSessionResponse::new() - .config_options(config_options) + .config_options(loaded.config_options) .meta(crate::harness::builtin_session_meta()), )); } diff --git a/scripts/comment-baseline.txt b/scripts/comment-baseline.txt index fd26b2a31..2a8aaf727 100644 --- a/scripts/comment-baseline.txt +++ b/scripts/comment-baseline.txt @@ -704,6 +704,7 @@ 12 rustcode/core/rustcode-tools/src/lib.rs 141 rustcode/engine/src/acp.rs 5 rustcode/engine/src/acp/agents.rs +8 rustcode/engine/src/acp/builtin_open.rs 38 rustcode/engine/src/acp/clients.rs 11 rustcode/engine/src/acp/commands.rs 7 rustcode/engine/src/acp/config.rs @@ -729,7 +730,7 @@ 1 rustcode/engine/src/acp/rewind.rs 3 rustcode/engine/src/acp/scheduled.rs 1 rustcode/engine/src/acp/session.rs -70 rustcode/engine/src/acp/session_load.rs +62 rustcode/engine/src/acp/session_load.rs 7 rustcode/engine/src/acp/session_move.rs 2 rustcode/engine/src/acp/session_repair.rs 2 rustcode/engine/src/acp/session_replay.rs diff --git a/scripts/rust-size-baseline.txt b/scripts/rust-size-baseline.txt index a9e83de49..798f06553 100644 --- a/scripts/rust-size-baseline.txt +++ b/scripts/rust-size-baseline.txt @@ -12,7 +12,7 @@ 2400 rustcode/client/src/registry.rs 3700 rustcode/core/rustcode-session/src/lib.rs 2300 rustcode/core/rustcode-tasks/src/lib.rs -4200 rustcode/engine/src/acp.rs +4100 rustcode/engine/src/acp.rs 2100 rustcode/engine/src/acp/clients.rs 3300 rustcode/engine/src/acp/remote.rs 3200 rustcode/engine/src/app/state.rs