Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions rustcode/engine/src/acp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
73 changes: 73 additions & 0 deletions rustcode/engine/src/acp/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<dyn BuiltinPublisher>,
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<crate::remote::SessionMutation, crate::remote::RemoteError>>;

/// 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<crate::remote::RemoteResult, crate::remote::RemoteError>>;

/// 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<PathBuf, crate::remote::RemoteError>>;

/// The thread's model, read without waiting: `None` while a turn holds
/// the thread.
fn selected_model(&self) -> Option<String>;

/// 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<tokio::sync::Mutex<crate::app::AppState>>;

/// The thread's transcript.
fn history(&self) -> AgentFuture<'_, rustcode_core::History>;

Expand All @@ -164,3 +211,29 @@ pub(crate) struct AttachSnapshot {
pub(crate) config_options: Vec<SessionConfigOption>,
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<Published>>;
}

/// One publish pass of a shared built-in thread.
pub(crate) struct Published {
pub(crate) messages: Vec<crate::remote::owner::OwnerMessage>,
/// A prompt is queued and no turn runs, so the turn loop should start.
pub(crate) queued_while_idle: bool,
}
64 changes: 64 additions & 0 deletions rustcode/engine/src/acp/prompt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<dyn super::builtin::BuiltinPublisher>,
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<crate::remote::SessionMutation, crate::remote::RemoteError>,
> {
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<crate::remote::RemoteResult, crate::remote::RemoteError>,
> {
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<std::path::PathBuf, crate::remote::RemoteError>>
{
Box::pin(super::share::changes_workspace(
&self.state,
registration,
request,
))
}

fn selected_model(&self) -> Option<String> {
super::share::selected_model(&self.state)
}

#[cfg(test)]
fn test_state(&self) -> Arc<Mutex<crate::app::AppState>> {
Arc::clone(&self.state)
}

fn last_active(&self) -> Option<String> {
self.state.try_lock().ok().and_then(|state| {
state
Expand Down
92 changes: 33 additions & 59 deletions rustcode/engine/src/acp/remote.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand All @@ -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::{
Expand Down Expand Up @@ -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<Mutex<AppState>>,
pub agent: Arc<dyn super::builtin::BuiltinAgent>,
pub cwd: PathBuf,
pub turns: Arc<SessionTurnState>,
Expand Down Expand Up @@ -167,7 +165,6 @@ impl RemoteSession {
) -> Arc<Self> {
Arc::new(Self {
session_id,
state: Arc::clone(&session.state),
agent: Arc::clone(&session.agent),
cwd: session.cwd.clone(),
turns: Arc::clone(&session.turns),
Expand Down Expand Up @@ -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<dyn super::builtin::BuiltinPublisher>),
Harness {
sequence: u64,
/// Asked for by the gateway, or owed after a lagging link.
Expand Down Expand Up @@ -393,17 +390,13 @@ impl Publisher {
}
}

fn owns(&self, state: &AppState) -> bool {
async fn publish(&mut self, room_for_resync: bool) -> Option<super::builtin::Published> {
match self {
Publisher::Acp(publisher) => publisher.owns(state),
Publisher::Harness { .. } => true,
}
}

fn publish(&mut self, state: &AppState, room_for_resync: bool) -> Vec<OwnerMessage> {
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,
}),
}
}

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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}"
Expand Down Expand Up @@ -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;
Expand All @@ -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 {
Expand All @@ -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)),
Expand All @@ -1900,23 +1878,19 @@ 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 {
advertise_host_threads(snapshot);
}
}
}
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) {
Expand Down
3 changes: 1 addition & 2 deletions rustcode/engine/src/acp/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,8 +172,7 @@ impl Drop for SessionTurnGuard {
}

pub(crate) struct AcpSession {
pub(crate) state: Arc<Mutex<crate::app::AppState>>,
/// The agent that runs the thread's prompts, over the same state.
/// The agent that runs the thread's prompts.
pub(crate) agent: Arc<dyn super::builtin::BuiltinAgent>,
pub(crate) cwd: PathBuf,
pub(crate) turns: Arc<SessionTurnState>,
Expand Down
2 changes: 0 additions & 2 deletions rustcode/engine/src/acp/session_load.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
Expand Down Expand Up @@ -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)),
Expand Down
Loading