diff --git a/.agents/skills/slop-audit/PATTERNS.md b/.agents/skills/slop-audit/PATTERNS.md index e462d33aa..44d7fedf4 100644 --- a/.agents/skills/slop-audit/PATTERNS.md +++ b/.agents/skills/slop-audit/PATTERNS.md @@ -341,6 +341,46 @@ the windows that draw its calls): lead and so itself; what a rule incidentally holds up is found before it goes. +From the round over machine groups (#1199, the pull request's diff only): + +- **A host's verdict rebuilt for a thread elsewhere**: the host gave no agent + status for a thread another machine started, so the window rebuilt the + host's precedence from activity flags; the copy had already lost + *Interrupted*. The host now reports it. +- **An outcome inferred from a disappearance**: how a move ended was worked + out from an entry leaving a list, the index and the last phase seen. A move + that ended while the client was away stayed "departing" for good. The host + says how each move ended. +- **A command overloaded, with made-up arguments**: starting a move was reused + to resume one, so Try again sent an empty path and a `false` the host + ignored. Resuming is its own command. +- **A fallback that moves the work**: a thread whose worktree was not carried + arrived at the project's root and continued there. It is a reason the move + cannot start. +- **A field written and never read**, filled by a lookup ending in + `unwrap_or_default()`, so a thread's stored log could name an empty machine. +- **Closing whatever is on top**: a dialog closed "the topmost dialog" when + its move ended, trusting a mark cleared by `on_close`, which the alert's + footer Cancel never calls. The question is asked inside the view now. +- **A copy of a switch's effective value**: the settings page drew + `operate && switch`, the rule the host applies to what it announces. The + host reports what is in effect. +- **Text the host wrote, split again by the window**: `thread@machine` was + rewritten into a callback header by one crate and cut apart by another. The + module that owns the header format writes and reads it. +- **A router standing in for the transport** while the same file's last test + already ran two real hosts over real endpoints. The tests moved to the real + peer; one now waits out the transport's 20-second dial to a stopped machine, + the only real proof that a kept cancel reaches it later. +- **A race turned into a step the test decides**: a 48 MB transfer the test + had to interrupt in time became a commit the target refuses (a folder + planted where an attachment lands) and a staged file cut to half, which is + what an interrupted send leaves. Each test went from 6–17 s to about 2. +- **A permission ceiling of Tcode's own between machines**: a thread started + from another machine was held to its starter's permission class. Deleted + under the `tcode_control` ruling below; admission between machines stays + (Principle 5). + ## What the audit did wrong - **It added tests by symptom before finding the contract's owner** (#1096). @@ -428,6 +468,18 @@ the windows that draw its calls): judged and brought to the bar, and what it meets beyond the diff is listed for a later round, not changed. +- **Two lanes shared a test harness, and one pruned what the other used.** + The move lane deleted the stop and restart of a machine's endpoint once its + own tests no longer needed them; the dispatch lane had just started using + them. Taking the lanes in one by one with the workspace built after each + caught it. A shared test file belongs to one lane, and the others list what + they need from it. +- **A lane's change failed a test elsewhere, and the cause was the change.** + A query failure now raised a warning; on a cold start a dropped link failed + that query, so the user would be warned about a thread they never asked + for. The test's window had no root for the warning, which is how it showed. + It was not the driver. + ## Families beyond the defence Named by the maintainer, not yet inventoried: @@ -474,6 +526,25 @@ What is known without an inventory: never opened interactively. Kept; the maintainer was unsure, and a run comparing both seeds has not been done. +- **Admission between the machines of a group**: a member is admitted on + `tcode/1` under its machine key; every request passes the protocol version + and this machine's switches by kind; on the target a machine reaches only + the threads its own machine started there; the allow-list of tools is an + exhaustive match. Principle 5 and the maintainer's word. +- **Hand-written peers in admission tests**: an endpoint speaking the wire by + hand to prove a device opens no machine stream, or a removed member is + refused. Only a test can be the hostile peer for a security check; this is + not the misbehaving peer only a test can be. +- **A move's retry, 5 seconds doubling to 2 minutes**: a move is long and its + link drops; the retry only continues what the user started, who can press + Try again or cancel. No maintainer word on the numbers. +- **1 MiB chunks of a moved project**: the protocol line limit is 16 MiB and + a chunk goes as base64 on one line. +- **The machine probe's 5 seconds**: the listing waits on it and the user has + no cancel for it. It stays until one exists. +- **A fixed identity on snapshot commits**: `commit-tree` fails on a machine + with no git identity. + ## Where the inventory was wrong The rewrite round overturned or corrected these. They are the reason every @@ -624,6 +695,18 @@ On checks before a push: > Add Clippy to your own checks. — the maintainer, and then: there is no > need to run all three platforms here; this machine runs its own. +On what the group's other devices may do on a machine, when a single switch +was proposed: + +> Split it into whether they can look and, on top of looking, whether they +> can operate. That is necessary: if a bug left it so that a device cannot +> look but can still operate, say a conversation left open from before, that +> is a problem. — the maintainer + +So the level is one choice of three that has no state for "cannot look, can +operate", the host decides it on every request, and a change closes the +connections it affects. + ## Defects met on the way Not defences; fixed or reported as their own entries. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 20c91f83c..8ee30a334 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,10 +20,18 @@ is derived from it. **Process** is how to build, check and submit work. (Principle 3) whose only protocol is standard ACP, which today is Antigravity alone. For such a harness Tcode synthesizes the features it lacks instead of staying a thin wrapper. An agent that merely connects - over ACP gets none of this. + over ACP gets none of this. Hosts, projects and threads are Tcode's own: + operating them, on one host or between the hosts of a group, is not a + harness capability, even where a harness has something similar between its + own sessions. 2. **Host and client.** A Tcode host owns all of its state: providers, threads, - terminals, projects. Every client — the desktop window, a phone, a tablet, a + terminals, projects. A thread belongs to exactly one host at a time. The + hosts of a group work with each other directly: a thread on one may start a + thread on another and hear back from it, and a host may hand a project and + its threads over to another, after which they are that host's. What a host + keeps of another host's thread is a reference and its last known status, + never its content. Every client — the desktop window, a phone, a tablet, a browser tab — is a screen for one or more hosts and speaks the same protocol to each, whether it runs on the same machine or across a network; it shows their state side by side and never merges it. Layers depend strictly @@ -48,7 +56,14 @@ is derived from it. **Process** is how to build, check and submit work. machine and does not use iroh. There is no automatic discovery: a device's first contact with a machine, or with a group of machines, is always an invitation, scanned or pasted; a machine admits only devices it paired or - that a machine in its group admitted. An official service, **Traverse**, + that a machine in its group admitted. The machines of a group reach each + other over the same transport, each under its own key. A machine's user + decides, by a switch for each, whether its threads may start threads on the + machines of its group, whether it takes the threads they start on it, and + whether it takes the projects they move to it; the last is off until + switched on. What a machine itself sent out comes back to it whatever those + switches say. + An official service, **Traverse**, provides lookup and relay fallback: no accounts, on by default, self-hostable, sees only ciphertext, and never required — on a LAN, direct connections give the full product without it. Abuse is limited without diff --git a/crates/agent/src/lib.rs b/crates/agent/src/lib.rs index 4c8d40d32..51055ce87 100644 --- a/crates/agent/src/lib.rs +++ b/crates/agent/src/lib.rs @@ -3157,6 +3157,12 @@ pub enum AgentEvent { #[serde(default, skip_serializing_if = "Option::is_none")] parent_item_id: Option, }, + /// The thread came to this machine with its project from the machine of the + /// group called `from_machine_name`. Never emitted by an adapter; the runtime + /// records it when the move is committed here. + ThreadMoved { + from_machine_name: String, + }, /// The harness waits for the host to create or remove a git worktree, as /// Claude Code does through its `WorktreeCreate` and `WorktreeRemove` hooks /// for every worktree it works in. Answered by @@ -3998,6 +4004,9 @@ pub enum ChildRequestAnswer { pub struct ControlAction { pub actor_thread_id: String, pub actor_title: String, + /// The machine of the group the actor thread is on, when it is not this one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub actor_machine: Option, /// A semantic key from `tcode_core::control::action`, which clients put in words. pub action: String, /// Data only (a title, an id, a name, a count, someone's own words), never a sentence. diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 20bd4bc39..6f695de25 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -197,16 +197,21 @@ fn start_local( store: SessionStore, login_shell_unread: Option, ) -> std::io::Result<(SpawnedHost, HostMux)> { + // The machine this window starts while hosting serves the host's way + // to the other machines of its group. + let machines = tcode_client::machines::MachineLink::new(); let mut host_services = HostServices { background_startup_probes: true, ai_title_generation: true, login_shell_unread, + machines: Some(machines.clone()), ..HostServices::default() }; host_services.start_mcp_servers(true); let host = spawn_host(store, host_services)?; let mux = HostMux::new(host.attachments.clone(), host.from_host.clone()) - .with_original_backend(std::sync::Arc::new(host.clone())); + .with_original_backend(std::sync::Arc::new(host.clone())) + .with_machine_link(machines); Ok((host, mux)) } diff --git a/crates/client/src/lib.rs b/crates/client/src/lib.rs index 9078d7556..f33d76783 100644 --- a/crates/client/src/lib.rs +++ b/crates/client/src/lib.rs @@ -3,6 +3,7 @@ pub mod attachment; pub mod heartbeat; pub mod host; +pub mod machines; pub mod original; pub mod outbox; pub use original::OriginalTransfer; @@ -60,11 +61,20 @@ pub enum ConnectionFailure { AuthenticationRejected, ProtocolMismatch, HostClosed, + /// The device is still paired, but the machine admits none of its + /// group's other devices now. + AccessClosed, } impl ConnectionFailure { + /// Whether dialling again cannot help until something changes on either + /// side. A machine closed to its group's devices stays closed until its + /// user opens it. pub fn is_terminal(&self) -> bool { - matches!(self, Self::AuthenticationRejected | Self::ProtocolMismatch) + matches!( + self, + Self::AuthenticationRejected | Self::ProtocolMismatch | Self::AccessClosed + ) } /// Older hosts did not send machine-readable rejection reasons. diff --git a/crates/client/src/machines.rs b/crates/client/src/machines.rs new file mode 100644 index 000000000..c2abaa850 --- /dev/null +++ b/crates/client/src/machines.rs @@ -0,0 +1,150 @@ +//! How a machine's host reaches the other machines of its group. The host +//! asks through a [`MachineLink`]; the transport that keeps the group serves +//! the link for as long as it runs, so a call made while this machine hosts +//! nothing, or is in no group, fails at once instead of waiting. +use std::sync::{Arc, Mutex}; + +use tcode_protocol::{MachineRequest, MachineResponse, ProtocolError}; + +/// One machine of this machine's group, this one included. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MachineInfo { + pub id: String, + pub name: String, + /// What the group calls it, when anyone gave it a label. + pub label: Option, + pub this_machine: bool, + /// What the machine says it takes; `None` while it has not said. + pub accepts_threads: Option, + pub accepts_projects: Option, + /// Filled by a probe: whether it answered, whether its protocol is this + /// machine's, and whether a relay carried the answer. + pub reachable: Option, + pub protocol_ok: Option, + pub relayed: Option, +} + +impl MachineInfo { + /// What the group calls the machine: its label, else its own name. + pub fn title(&self) -> &str { + self.label.as_deref().unwrap_or(&self.name) + } +} + +/// What the transport serving a [`MachineLink`] is asked. +pub enum MachineCall { + Request { + machine: String, + request: Box, + reply: async_channel::Sender>, + }, + Machines { + probe: bool, + reply: async_channel::Sender, ProtocolError>>, + }, +} + +/// The host's way to the other machines of its group. Clones share whoever +/// serves it. +#[derive(Clone, Default)] +pub struct MachineLink { + serving: Arc>>>, + served: Arc>>>, +} + +impl MachineLink { + pub fn new() -> Self { + Self::default() + } + + /// Serve this link's calls from the returned receiver from now on, in + /// place of whatever served them. Once it is dropped, calls fail with + /// [`NO_GROUP`] until the next one serves. + pub fn serve(&self) -> async_channel::Receiver { + let (sender, receiver) = async_channel::unbounded(); + *self.serving.lock().unwrap() = Some(sender); + self.served + .lock() + .unwrap() + .retain(|served| served.try_send(()).is_ok() || !served.is_closed()); + receiver + } + + /// Hears once each time something starts serving this link, and at once + /// when something serves it now: when what this machine could not send + /// its group may go. + pub fn serves(&self) -> async_channel::Receiver<()> { + let (sender, receiver) = async_channel::unbounded(); + let mut served = self.served.lock().unwrap(); + if self + .serving + .lock() + .unwrap() + .as_ref() + .is_some_and(|serving| !serving.is_closed()) + { + let _ = sender.try_send(()); + } + served.push(sender); + receiver + } + + /// Send `request` to `machine` of the group and wait for its answer. A + /// machine that cannot be reached answers [`MACHINE_UNREACHABLE`]. + pub fn call( + &self, + machine: &str, + request: MachineRequest, + ) -> impl Future> + Send + 'static { + let (reply, answer) = async_channel::bounded(1); + let sent = self.send(MachineCall::Request { + machine: machine.to_owned(), + request: Box::new(request), + reply, + }); + async move { + sent?; + answer.recv().await.unwrap_or_else(|_| Err(stopped())) + } + } + + /// The machines of the group; with `probe`, each other one is pinged + /// first and its answer filled in. + pub fn machines( + &self, + probe: bool, + ) -> impl Future, ProtocolError>> + Send + 'static { + let (reply, answer) = async_channel::bounded(1); + let sent = self.send(MachineCall::Machines { probe, reply }); + async move { + sent?; + answer.recv().await.unwrap_or_else(|_| Err(stopped())) + } + } + + fn send(&self, call: MachineCall) -> Result<(), ProtocolError> { + let serving = self.serving.lock().unwrap().clone(); + match serving { + Some(serving) => serving.try_send(call).map_err(|_| stopped()), + None => Err(stopped()), + } + } +} + +/// This machine is in no group, or hosts nothing that reaches one. +pub const NO_GROUP: &str = "no_group"; +/// The other machine could not be reached, or the connection to it failed. +pub const MACHINE_UNREACHABLE: &str = "machine_unreachable"; +/// The other machine is not a member of this machine's group. +pub const NOT_MEMBER: &str = "not_member"; +/// The other machine runs another protocol version. +pub const PROTOCOL_MISMATCH: &str = "protocol_mismatch"; +/// The other machine's switches do not take this kind of request. +pub const MACHINE_REFUSES: &str = "machine_refuses"; + +fn stopped() -> ProtocolError { + ProtocolError { + code: NO_GROUP.into(), + message: "this machine is not hosting a machine group".into(), + } +} diff --git a/crates/client/src/pairing.rs b/crates/client/src/pairing.rs index 6d54990f5..a37d7cda0 100644 --- a/crates/client/src/pairing.rs +++ b/crates/client/src/pairing.rs @@ -44,6 +44,17 @@ pub struct PairedHost { /// The group's name as that machine last reported it. #[serde(default, skip_serializing_if = "Option::is_none")] pub group_name: Option, + /// What the machine's group calls it, as a machine of the group last + /// told this device. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, +} + +impl PairedHost { + /// What to call the machine: its group's label for it, else its name. + pub fn title(&self) -> &str { + self.label.as_deref().unwrap_or(&self.name) + } } /// `traverse` as a list, or as the single optional value older records @@ -166,6 +177,7 @@ impl PairInvite { last_connected_unix: None, group_id: None, group_name: None, + label: None, } } } @@ -333,6 +345,7 @@ mod tests { last_connected_unix: None, group_id: None, group_name: None, + label: None, }; let mut hosts = vec![host("desk", "first"), host("laptop", "laptop")]; remember_host(&mut hosts, host("desk", "second")); diff --git a/crates/control-mcp/src/lib.rs b/crates/control-mcp/src/lib.rs index 948d8abf6..31d753ceb 100644 --- a/crates/control-mcp/src/lib.rs +++ b/crates/control-mcp/src/lib.rs @@ -53,16 +53,20 @@ pub enum ControlOp { Rewind(RewindParams), PatchSettings(PatchSettingsParams), SetModelGuide(SetModelGuideParams), + ListMachines(ListMachinesParams), + StartThreadOnMachine(StartThreadOnMachineParams), } /// What decides which tools a thread is offered: whether threads are given `tcode_control` -/// at all, whether another thread started this one as a subagent, and whether the user -/// opened it to research a model's guide. +/// at all, whether another thread started this one as a subagent, whether the user opened +/// it to research a model's guide, and whether its machine lets it start threads on the +/// other machines of its group. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct ThreadAccess { pub enabled: bool, pub subagent: bool, pub model_guide: bool, + pub machines: bool, } impl ThreadAccess { @@ -71,16 +75,20 @@ impl ThreadAccess { enabled: false, subagent: false, model_guide: false, + machines: false, } } /// Every tool, but `report_result` only for a subagent, its one channel to the thread - /// that started it, and `set_model_guide` only for the thread that researches a guide. + /// that started it, `set_model_guide` only for the thread that researches a guide, and + /// the tools about the group's machines only where the machine lets its threads reach + /// them. pub fn offers(&self, tool: &str) -> bool { self.enabled && match tool { REPORT_RESULT => self.subagent, SET_MODEL_GUIDE => self.model_guide, + LIST_MACHINES | START_THREAD_ON_MACHINE => self.machines, _ => true, } } @@ -88,8 +96,97 @@ impl ThreadAccess { const REPORT_RESULT: &str = "report_result"; const SET_MODEL_GUIDE: &str = "set_model_guide"; +const LIST_MACHINES: &str = "list_machines"; +const START_THREAD_ON_MACHINE: &str = "start_thread_on_machine"; impl ControlOp { + /// The call of `tool` with `args`, read as the server reads a call's arguments. + pub fn parse(tool: &str, args: serde_json::Value) -> Result { + fn read(args: serde_json::Value) -> Result { + serde_json::from_value(args).map_err(|error| format!("invalid arguments: {error}")) + } + Ok(match tool { + "list_projects" => Self::ListProjects(read(args)?), + "list_threads" => Self::ListThreads(read(args)?), + "get_thread" => Self::GetThread(read(args)?), + "search" => Self::Search(read(args)?), + "outline" => Self::Outline(read(args)?), + "read" => Self::Read(read(args)?), + "search_in_item" => Self::SearchInItem(read(args)?), + "file_history" => Self::FileHistory(read(args)?), + "get_git" => Self::GetGit(read(args)?), + "get_pull_request" => Self::GetPullRequest(read(args)?), + "list_providers" => Self::ListProviders(read(args)?), + "get_settings" => Self::GetSettings(read(args)?), + "read_terminal" => Self::ReadTerminal(read(args)?), + "review_candidates" => Self::ReviewCandidates(read(args)?), + "update_threads" => Self::UpdateThreads(read(args)?), + "settle_self" => Self::SettleSelf(read(args)?), + "start_thread" => Self::StartThread(read(args)?), + "send_message" => Self::SendMessage(read(args)?), + "control_thread" => Self::ControlThread(read(args)?), + "pull_request" => Self::PullRequest(read(args)?), + "git" => Self::Git(read(args)?), + "create_project" => Self::CreateProject(read(args)?), + "move_thread" => Self::MoveThread(read(args)?), + "notify_when" => Self::NotifyWhen(read(args)?), + "cancel_notify" => Self::CancelNotify(read(args)?), + "respond_input" => Self::RespondInput(read(args)?), + "respond_approval" => Self::RespondApproval(read(args)?), + REPORT_RESULT => Self::ReportResult(read(args)?), + "terminal" => Self::Terminal(read(args)?), + "delete_threads" => Self::DeleteThreads(read(args)?), + "rewind" => Self::Rewind(read(args)?), + "patch_settings" => Self::PatchSettings(read(args)?), + SET_MODEL_GUIDE => Self::SetModelGuide(read(args)?), + LIST_MACHINES => Self::ListMachines(read(args)?), + START_THREAD_ON_MACHINE => Self::StartThreadOnMachine(read(args)?), + other => return Err(format!("unknown tool: {other}")), + }) + } + + /// The call's arguments, as [`Self::parse`] reads them back. + pub fn args(&self) -> serde_json::Value { + let args = match self { + Self::ListProjects(p) => serde_json::to_value(p), + Self::ListThreads(p) => serde_json::to_value(p), + Self::GetThread(p) => serde_json::to_value(p), + Self::Search(p) => serde_json::to_value(p), + Self::Outline(p) => serde_json::to_value(p), + Self::Read(p) => serde_json::to_value(p), + Self::SearchInItem(p) => serde_json::to_value(p), + Self::FileHistory(p) => serde_json::to_value(p), + Self::GetGit(p) => serde_json::to_value(p), + Self::GetPullRequest(p) => serde_json::to_value(p), + Self::ListProviders(p) => serde_json::to_value(p), + Self::GetSettings(p) => serde_json::to_value(p), + Self::ReadTerminal(p) => serde_json::to_value(p), + Self::ReviewCandidates(p) => serde_json::to_value(p), + Self::UpdateThreads(p) => serde_json::to_value(p), + Self::SettleSelf(p) => serde_json::to_value(p), + Self::StartThread(p) => serde_json::to_value(p), + Self::SendMessage(p) => serde_json::to_value(p), + Self::ControlThread(p) => serde_json::to_value(p), + Self::PullRequest(p) => serde_json::to_value(p), + Self::Git(p) => serde_json::to_value(p), + Self::CreateProject(p) => serde_json::to_value(p), + Self::MoveThread(p) => serde_json::to_value(p), + Self::NotifyWhen(p) => serde_json::to_value(p), + Self::CancelNotify(p) => serde_json::to_value(p), + Self::RespondInput(p) => serde_json::to_value(p), + Self::RespondApproval(p) => serde_json::to_value(p), + Self::ReportResult(p) => serde_json::to_value(p), + Self::Terminal(p) => serde_json::to_value(p), + Self::DeleteThreads(p) => serde_json::to_value(p), + Self::Rewind(p) => serde_json::to_value(p), + Self::PatchSettings(p) => serde_json::to_value(p), + Self::SetModelGuide(p) => serde_json::to_value(p), + Self::ListMachines(p) => serde_json::to_value(p), + Self::StartThreadOnMachine(p) => serde_json::to_value(p), + }; + args.expect("tool parameters serialize") + } + pub fn tool_name(&self) -> &'static str { match self { Self::ListProjects(_) => "list_projects", @@ -125,6 +222,8 @@ impl ControlOp { Self::Rewind(_) => "rewind", Self::PatchSettings(_) => "patch_settings", Self::SetModelGuide(_) => SET_MODEL_GUIDE, + Self::ListMachines(_) => LIST_MACHINES, + Self::StartThreadOnMachine(_) => START_THREAD_ON_MACHINE, } } @@ -192,7 +291,9 @@ impl ControlOp { | Self::CancelNotify(_) | Self::PatchSettings(_) | Self::SetModelGuide(_) - | Self::ReportResult(_) => Vec::new(), + | Self::ReportResult(_) + | Self::ListMachines(_) + | Self::StartThreadOnMachine(_) => Vec::new(), } } @@ -231,7 +332,9 @@ impl ControlOp { | Self::CancelNotify(_) | Self::PatchSettings(_) | Self::SetModelGuide(_) - | Self::ReportResult(_) => Vec::new(), + | Self::ReportResult(_) + | Self::ListMachines(_) + | Self::StartThreadOnMachine(_) => Vec::new(), }; for id in ids { if id == OWN_THREAD { @@ -246,6 +349,8 @@ pub struct BrokerRequest { /// The calling thread, baked into its bearer token. pub thread_id: String, pub op: ControlOp, + /// The machine of the group the call is for; `None` for this one. + pub machine: Option, pub reply: async_channel::Sender>, } diff --git a/crates/control-mcp/src/params.rs b/crates/control-mcp/src/params.rs index dc0658422..f98177b28 100644 --- a/crates/control-mcp/src/params.rs +++ b/crates/control-mcp/src/params.rs @@ -75,6 +75,21 @@ pub enum ItemKind { const SCOPE: &str = "Which projects the call covers: the caller's own (project), named ones ({\"projects\": [ids]}) or the whole host (host). Omit for the caller's own project."; +const MACHINE: &str = "Another machine of this machine's group, by the id list_machines gives, to run the call there: the thread, project and anchor ids it names are that machine's, and the answer names the machine. There you reach its projects and models, and of its threads only those this machine started there. Omit for this machine."; + +/// A tool's parameters with the machine of the group the call is for. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +pub struct OnMachine

{ + #[serde(default)] + #[schemars(description = MACHINE)] + pub machine: Option, + #[serde(flatten)] + pub params: P, +} + +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +pub struct ListMachinesParams {} + #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] pub struct ListProjectsParams {} @@ -401,6 +416,85 @@ pub struct StartThreadParams { pub request_id: String, } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] +pub struct StartThreadOnMachineParams { + #[schemars( + description = "The machine of the group to start it on, by the id list_machines gives." + )] + pub machine: String, + #[schemars( + description = "A project on that machine, as list_projects with that machine lists it." + )] + pub project_id: String, + #[serde(default)] + #[schemars( + description = "Working directory relative to the project root on that machine, inside it; default the root." + )] + pub cwd: Option, + #[serde(default)] + #[schemars( + description = "local (the checkout) or worktree, as for start_thread: worktree only for a subagent; omitted, a subagent follows that machine's subagent worktree isolation." + )] + pub workspace: Option, + #[serde(default)] + #[schemars( + description = "Start the thread as this thread's subagent (default false): its report_result, approval requests and questions reach you as messages here; it is an ordinary thread on that machine." + )] + pub subagent: Option, + #[schemars( + description = "Provider name as list_providers with that machine lists it, for example claude, codex or acp." + )] + pub provider: String, + #[serde(default)] + #[schemars(description = "Installed ACP agent id on that machine; only when provider is acp.")] + pub acp_agent: Option, + #[serde(default)] + #[schemars( + description = "Model id from list_providers with that machine; omit for the provider's default. Refused when provider is acp." + )] + pub model: Option, + #[serde(default)] + #[schemars(description = "Provider profile id from list_providers with that machine.")] + pub profile: Option, + #[serde(default)] + #[schemars( + description = "Provider option id → value, as list_providers with that machine describes them; never the permission mode." + )] + pub options: Option>, + #[serde(default)] + #[schemars(description = "Thread title; omit to let that machine title it.")] + pub title: Option, + #[schemars( + description = "The first message of the thread, sent as from this thread (origin agent)." + )] + pub message: String, + #[schemars( + description = "Idempotency key: a retry with the same key returns the same thread and starts nothing." + )] + pub request_id: String, +} + +impl StartThreadOnMachineParams { + /// What the other machine's `start_thread` is asked. + pub fn start_thread(self) -> StartThreadParams { + StartThreadParams { + project_id: Some(self.project_id), + cwd: self.cwd, + workspace: self.workspace, + subagent: self.subagent, + provider: self.provider, + acp_agent: self.acp_agent, + model: self.model, + profile: self.profile, + options: self.options, + title: self.title, + message: self.message, + attachments: None, + request_id: self.request_id, + } + } +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)] #[serde(rename_all = "snake_case")] pub enum SendMode { diff --git a/crates/control-mcp/src/tools.rs b/crates/control-mcp/src/tools.rs index af1c968df..a31ef8207 100644 --- a/crates/control-mcp/src/tools.rs +++ b/crates/control-mcp/src/tools.rs @@ -18,12 +18,20 @@ const INSTRUCTIONS: &str = "tcode_control lets you observe and operate Tcode: it /// What a subagent's connection adds to [`INSTRUCTIONS`]. const SUBAGENT_INSTRUCTIONS: &str = "Another thread started you as its subagent: report this thread's final result to it with report_result; besides that it sees only your approval requests and questions, and your final message if you never report."; +/// What a connection of a thread that may reach the other machines of its group adds to +/// [`INSTRUCTIONS`]. +const MACHINES_INSTRUCTIONS: &str = "This machine is one of a group of machines: list_machines lists the others. A tool that takes machine runs on that machine when you pass its id: the thread, project and anchor ids in the call and in its answer are that machine's, and the answer names it. On another machine you reach its projects and models, and the threads this machine started there; its other threads are not listed and are refused as unknown. Cite an anchor from another machine as tcode-thread://@# and a thread as tcode-thread://@; the form without @ is always this machine's, and a link with one in a message from the user names a thread on that machine. start_thread_on_machine starts a thread there; it leaves this machine and is the user's to ask for."; + /// The `instructions` a thread's connection reads. -pub fn instructions(subagent: bool) -> String { +pub fn instructions(subagent: bool, machines: bool) -> String { let mut text = format!( "{INSTRUCTIONS} Pass \"{}\" as the thread id wherever a tool asks about your own thread; get_thread on it answers with its id.", crate::OWN_THREAD ); + if machines { + text.push(' '); + text.push_str(MACHINES_INSTRUCTIONS); + } if subagent { text.push(' '); text.push_str(SUBAGENT_INSTRUCTIONS); @@ -36,6 +44,7 @@ pub struct ControlTools { broker: Broker, thread_id: String, subagent: bool, + machines: bool, tool_router: ToolRouter, } @@ -57,6 +66,7 @@ impl ControlTools { broker, thread_id, subagent: access.subagent, + machines: access.machines, tool_router, } } @@ -66,13 +76,26 @@ impl ControlTools { described(self.tool_router.list_all()) } - /// Route one op through the broker. A call the harness cancels drops its - /// request, and the host stops working on it. - async fn run(&self, ct: &CancellationToken, mut op: ControlOp) -> CallToolResult { - op.name_caller(&self.thread_id); + async fn run(&self, ct: &CancellationToken, op: ControlOp) -> CallToolResult { + self.run_on(ct, None, op).await + } + + /// Route one op, for `machine` of the group or this one, through the broker. A call the + /// harness cancels drops its request, and the host stops working on it. + async fn run_on( + &self, + ct: &CancellationToken, + machine: Option, + mut op: ControlOp, + ) -> CallToolResult { + // "self" names this thread, which is on no other machine. + if machine.is_none() { + op.name_caller(&self.thread_id); + } let reply = ct.run_until_cancelled(self.broker.invoke(|reply| crate::BrokerRequest { thread_id: self.thread_id.clone(), op, + machine, reply, })); match reply.await { @@ -88,9 +111,9 @@ impl ControlTools { async fn list_projects( &self, ct: CancellationToken, - Parameters(p): Parameters, + Parameters(OnMachine { machine, params: p }): Parameters>, ) -> CallToolResult { - self.run(&ct, ControlOp::ListProjects(p)).await + self.run_on(&ct, machine, ControlOp::ListProjects(p)).await } #[tool( @@ -99,9 +122,9 @@ impl ControlTools { async fn list_threads( &self, ct: CancellationToken, - Parameters(p): Parameters, + Parameters(OnMachine { machine, params: p }): Parameters>, ) -> CallToolResult { - self.run(&ct, ControlOp::ListThreads(p)).await + self.run_on(&ct, machine, ControlOp::ListThreads(p)).await } #[tool( @@ -110,9 +133,9 @@ impl ControlTools { async fn get_thread( &self, ct: CancellationToken, - Parameters(p): Parameters, + Parameters(OnMachine { machine, params: p }): Parameters>, ) -> CallToolResult { - self.run(&ct, ControlOp::GetThread(p)).await + self.run_on(&ct, machine, ControlOp::GetThread(p)).await } #[tool( @@ -132,9 +155,9 @@ impl ControlTools { async fn outline( &self, ct: CancellationToken, - Parameters(p): Parameters, + Parameters(OnMachine { machine, params: p }): Parameters>, ) -> CallToolResult { - self.run(&ct, ControlOp::Outline(p)).await + self.run_on(&ct, machine, ControlOp::Outline(p)).await } #[tool( @@ -143,9 +166,9 @@ impl ControlTools { async fn read( &self, ct: CancellationToken, - Parameters(p): Parameters, + Parameters(OnMachine { machine, params: p }): Parameters>, ) -> CallToolResult { - self.run(&ct, ControlOp::Read(p)).await + self.run_on(&ct, machine, ControlOp::Read(p)).await } #[tool( @@ -154,9 +177,9 @@ impl ControlTools { async fn search_in_item( &self, ct: CancellationToken, - Parameters(p): Parameters, + Parameters(OnMachine { machine, params: p }): Parameters>, ) -> CallToolResult { - self.run(&ct, ControlOp::SearchInItem(p)).await + self.run_on(&ct, machine, ControlOp::SearchInItem(p)).await } #[tool( @@ -198,9 +221,9 @@ impl ControlTools { async fn list_providers( &self, ct: CancellationToken, - Parameters(p): Parameters, + Parameters(OnMachine { machine, params: p }): Parameters>, ) -> CallToolResult { - self.run(&ct, ControlOp::ListProviders(p)).await + self.run_on(&ct, machine, ControlOp::ListProviders(p)).await } #[tool( @@ -273,9 +296,9 @@ impl ControlTools { async fn send_message( &self, ct: CancellationToken, - Parameters(p): Parameters, + Parameters(OnMachine { machine, params: p }): Parameters>, ) -> CallToolResult { - self.run(&ct, ControlOp::SendMessage(p)).await + self.run_on(&ct, machine, ControlOp::SendMessage(p)).await } #[tool( @@ -284,9 +307,9 @@ impl ControlTools { async fn control_thread( &self, ct: CancellationToken, - Parameters(p): Parameters, + Parameters(OnMachine { machine, params: p }): Parameters>, ) -> CallToolResult { - self.run(&ct, ControlOp::ControlThread(p)).await + self.run_on(&ct, machine, ControlOp::ControlThread(p)).await } #[tool( @@ -339,18 +362,18 @@ impl ControlTools { async fn notify_when( &self, ct: CancellationToken, - Parameters(p): Parameters, + Parameters(OnMachine { machine, params: p }): Parameters>, ) -> CallToolResult { - self.run(&ct, ControlOp::NotifyWhen(p)).await + self.run_on(&ct, machine, ControlOp::NotifyWhen(p)).await } #[tool(description = "Remove watches notify_when registered, by id.")] async fn cancel_notify( &self, ct: CancellationToken, - Parameters(p): Parameters, + Parameters(OnMachine { machine, params: p }): Parameters>, ) -> CallToolResult { - self.run(&ct, ControlOp::CancelNotify(p)).await + self.run_on(&ct, machine, ControlOp::CancelNotify(p)).await } #[tool( @@ -359,9 +382,9 @@ impl ControlTools { async fn respond_input( &self, ct: CancellationToken, - Parameters(p): Parameters, + Parameters(OnMachine { machine, params: p }): Parameters>, ) -> CallToolResult { - self.run(&ct, ControlOp::RespondInput(p)).await + self.run_on(&ct, machine, ControlOp::RespondInput(p)).await } #[tool( @@ -370,9 +393,10 @@ impl ControlTools { async fn respond_approval( &self, ct: CancellationToken, - Parameters(p): Parameters, + Parameters(OnMachine { machine, params: p }): Parameters>, ) -> CallToolResult { - self.run(&ct, ControlOp::RespondApproval(p)).await + self.run_on(&ct, machine, ControlOp::RespondApproval(p)) + .await } #[tool( @@ -440,6 +464,28 @@ impl ControlTools { ) -> CallToolResult { self.run(&ct, ControlOp::SetModelGuide(p)).await } + + #[tool( + description = "The machines of this machine's group, asked just now: each with its id (pass it as machine), name (the group's label for it, else its own name), host_name, whether it answered (reachable), whether it takes threads (accepts_threads) and projects (accepts_projects) from the group's machines, and whether it runs this machine's protocol (same_version). This machine is listed with this_machine. Reads only." + )] + async fn list_machines( + &self, + ct: CancellationToken, + Parameters(p): Parameters, + ) -> CallToolResult { + self.run(&ct, ControlOp::ListMachines(p)).await + } + + #[tool( + description = "Start a new thread with a first message on another machine of this machine's group, recorded as started by this thread and never blocking you. It leaves this machine: the message goes to that machine, the thread runs on that machine's code as it is there and carries no files from here, and that machine's harnesses, models, permission defaults and Settings → Control apply. It is the user's to ask for: where their wish to run work on that machine is unclear, ask before you call. Find the machine with list_machines, its project with list_projects and what it may start with list_providers, each passing machine; the parameters are start_thread's, about that machine. By default it is an ordinary thread on that machine. With subagent: true it is this thread's subagent: an ordinary thread there, whose report_result reaches you here as a message when its turn ends, as do its approval requests and questions, which you answer with respond_approval or respond_input passing machine. Cancel or interrupt it with control_thread passing machine; while the machine cannot be reached that is kept and sent when it can. A thread running under a collaboration starts no subagent on another machine: a collaboration's members are on one machine. Attachments do not go with it. The answer names the thread, its machine and its link, tcode-thread://@. request_id makes a retry, after a failure or a restart of either machine, return the same thread." + )] + async fn start_thread_on_machine( + &self, + ct: CancellationToken, + Parameters(p): Parameters, + ) -> CallToolResult { + self.run(&ct, ControlOp::StartThreadOnMachine(p)).await + } } /// Every tool `access` offers, with the description its model reads, in name order. @@ -471,7 +517,7 @@ impl ServerHandler for ControlTools { ServerConfig::new(ServerCapabilities::builder().enable_tools().build()) .with_protocol_version(ProtocolVersion::LATEST) .with_server_info(Implementation::from_build_env()) - .with_instructions(instructions(self.subagent)) + .with_instructions(instructions(self.subagent, self.machines)) } } diff --git a/crates/core/src/control.rs b/crates/core/src/control.rs index 79c56327e..8c6ee5926 100644 --- a/crates/core/src/control.rs +++ b/crates/core/src/control.rs @@ -114,6 +114,13 @@ pub struct ControlSettings { pub enabled: bool, #[serde(default, skip_serializing_if = "AgentScope::is_every")] pub agents: AgentScope, + /// Whether this machine's threads may start threads on the other machines of its group. + #[serde(default = "default_true", skip_serializing_if = "is_true")] + pub machines: bool, +} + +fn is_true(value: &bool) -> bool { + *value } const fn default_true() -> bool { @@ -125,6 +132,7 @@ impl Default for ControlSettings { Self { enabled: true, agents: AgentScope::Every, + machines: true, } } } @@ -181,6 +189,79 @@ pub struct SelfSettleGrant { pub struct StartedBy { pub thread_id: String, pub request_id: String, + /// The machine of the group `thread_id` is on, when it is not this one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub machine: Option, +} + +/// The thread on another machine of the group that started this one as its subagent. This +/// thread is an ordinary root thread here; only its report goes back. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RemoteParent { + pub machine: String, + pub thread_id: String, + pub title: String, +} + +/// A thread this thread started on another machine of the group: a reference and its last +/// known state, never its content. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RemoteChild { + pub machine: String, + pub thread_id: String, + pub title: String, + pub request_id: String, + /// Started as a subagent, which owes a report. + pub subagent: bool, + pub state: RemoteChildState, + /// Unix seconds of the last change to `state`. + pub updated_at: u64, + /// What this machine still has to tell the other one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub pending: Option, + /// The id of the child's report the lead's harness took last, so the same report sent + /// again is known as taken. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub report_taken: Option, + /// The other machine has not yet heard that `report_taken` was taken, and keeps the + /// report until it does. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub report_taken_unsent: bool, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RemoteChildState { + Running, + Reported, + Failed, + Cancelled, + /// Its lead settled it. + Settled, + /// The machine left the group. + MachineLeft, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum RemoteChildOp { + Interrupt, + Cancel, + Settle, +} + +/// A wake a thread on another machine of the group asked for on this thread's events, kept +/// on this thread. It fires once, and its firing is kept until that machine has it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RemoteWatch { + pub id: String, + pub machine: String, + /// The watching thread, on `machine`. + pub thread_id: String, + pub events: BTreeSet, + /// The message its firing sends, until `machine` has it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub fired: Option, } #[derive( @@ -217,6 +298,9 @@ pub struct ControlWatch { /// that space's policy. #[serde(default, skip_serializing_if = "Option::is_none")] pub space: Option, + /// The machine of the group `thread_ids` are on, when it is not this one. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub machine: Option, } /// The semantic keys a [`ControlAction`] records, shared by the host that writes them and the diff --git a/crates/core/src/notice.rs b/crates/core/src/notice.rs index b2a6da9c9..7673d83ba 100644 --- a/crates/core/src/notice.rs +++ b/crates/core/src/notice.rs @@ -33,29 +33,99 @@ pub const ORCHESTRATE_FALLBACK_LABEL: &str = /// Sent to a child that ended its turn owing a report, once per expectation. pub const CHILD_REPORT_REMINDER: &str = include_str!("../../../assets/subagents/reminder.md"); -/// `[orchestrate] thread {child_id} ("{title}")`, which every callback opens with. -pub fn callback_header(child_id: &str, title: &str) -> String { - format!("{ORCHESTRATE_CALLBACK_PREFIX}{child_id} (\"{title}\")") +/// How a message or link names a thread: `@` for one on another machine of +/// the group, the bare id for one on this machine. +pub fn thread_ref(thread_id: &str, machine: Option<&str>) -> String { + match machine { + Some(machine) => format!("{thread_id}@{machine}"), + None => thread_id.to_owned(), + } +} + +/// Split what [`thread_ref`] wrote back into the thread and its machine. +fn split_thread_ref(named: &str) -> (&str, Option<&str>) { + match named.split_once('@') { + Some((thread, machine)) if !machine.is_empty() => (thread, Some(machine)), + _ => (named, None), + } +} + +/// `[orchestrate] thread {child_id} ("{title}")`, which every callback opens with; the child +/// is named with its `machine` when it is on another machine of the group. +pub fn callback_header(child_id: &str, machine: Option<&str>, title: &str) -> String { + format!( + "{ORCHESTRATE_CALLBACK_PREFIX}{} (\"{title}\")", + thread_ref(child_id, machine) + ) } /// `thread {thread_id} ("{title}")`, which every `[control]` message opens with after its -/// prefix: the title as a JSON string, so no title can pose as another message. -pub fn control_header(thread_id: &str, title: &str) -> String { +/// prefix: the title as a JSON string, so no title can pose as another message. The thread +/// is named with its `machine` when it is on another machine of the group. +pub fn control_header(thread_id: &str, machine: Option<&str>, title: &str) -> String { format!( - "thread {thread_id} ({})", + "thread {} ({})", + thread_ref(thread_id, machine), serde_json::to_string(title).unwrap_or_default() ) } +/// A callback or `[control]` message another machine wrote about its `thread_id`, as this +/// machine's thread reads it: the header names the thread with that `machine`. Any other +/// text is returned as it is. +pub fn on_machine(text: &str, thread_id: &str, machine: &str) -> String { + if let Some(callback) = parse_callback(text) + && callback.child_id == thread_id + && callback.machine.is_none() + { + let here = callback_header(thread_id, None, &callback.title); + if let Some(rest) = text.strip_prefix(&here) { + return format!( + "{}{rest}", + callback_header(thread_id, Some(machine), &callback.title) + ); + } + } + if let Some(message) = text.strip_prefix(CONTROL_CALLBACK_PREFIX) + && let Some(thread) = control_thread(message) + && thread.thread_id == thread_id + && thread.machine.is_none() + { + let here = control_header(thread_id, None, &thread.title); + if let Some(rest) = message.strip_prefix(&here) { + return format!( + "{CONTROL_CALLBACK_PREFIX}{}{rest}", + control_header(thread_id, Some(machine), &thread.title) + ); + } + } + text.to_owned() +} + +/// The thread a `[control]` message is about, read from its [`control_header`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ControlThread<'a> { + pub thread_id: &'a str, + /// The machine of the group the thread is on, when it is not this one. + pub machine: Option<&'a str>, + pub title: String, +} + /// The thread a `[control]` message (one of [`HostNotice::Control`]'s) is about, read from -/// its [`control_header`]: its id and title. -pub fn control_thread(message: &str) -> Option<(&str, String)> { - let (thread_id, rest) = message.strip_prefix("thread ")?.split_once(" (")?; +/// its [`control_header`]. +pub fn control_thread(message: &str) -> Option> { + let (named, rest) = message.strip_prefix("thread ")?.split_once(" (")?; let mut titles = serde_json::Deserializer::from_str(rest).into_iter::(); let title = titles.next()?.ok()?; - rest[titles.byte_offset()..] - .starts_with(')') - .then_some((thread_id, title)) + if !rest[titles.byte_offset()..].starts_with(')') { + return None; + } + let (thread_id, machine) = split_thread_ref(named); + Some(ControlThread { + thread_id, + machine, + title, + }) } /// What the host told the thread. @@ -114,6 +184,8 @@ pub enum CallbackEvent { #[derive(Debug, Clone, PartialEq, Eq)] pub struct OrchestrateCallback { pub child_id: String, + /// The machine of the group the child is on, when it is not this one. + pub machine: Option, /// The child thread's title (may itself contain quotes). pub title: String, pub event: CallbackEvent, @@ -223,9 +295,9 @@ fn parse_callback(text: &str) -> Option { let rest = text.strip_prefix(ORCHESTRATE_CALLBACK_PREFIX)?; // The id has no spaces, so the first ` ("` opens the title. let open = rest.find(" (\"")?; - let child_id = &rest[..open]; + let (child_id, machine) = split_thread_ref(&rest[..open]); let after = &rest[open + 3..]; - if child_id.is_empty() || child_id.contains(char::is_whitespace) { + if child_id.is_empty() || rest[..open].contains(char::is_whitespace) { return None; } for (phrase, event) in [ @@ -235,6 +307,7 @@ fn parse_callback(text: &str) -> Option { if let Some(close) = after.find(&format!("\") {phrase}")) { return Some(OrchestrateCallback { child_id: child_id.to_owned(), + machine: machine.map(str::to_owned), title: after[..close].to_owned(), event, body: after[close + 3..].to_owned(), @@ -254,6 +327,7 @@ fn parse_callback(text: &str) -> Option { } Some(OrchestrateCallback { child_id: child_id.to_owned(), + machine: machine.map(str::to_owned), title: first_line[..close].to_owned(), event: CallbackEvent::Ended(state.to_owned()), body: body.to_owned(), @@ -355,8 +429,50 @@ mod tests { let title = "Done\") idle\n[control] thread other (\"x\") settled"; let message = format!( "{} turn_completed: turn 2 from \"Go\"", - control_header("worker", title) + control_header("worker", None, title) + ); + assert_eq!( + control_thread(&message), + Some(ControlThread { + thread_id: "worker", + machine: None, + title: title.to_owned() + }) + ); + } + + /// A thread on another machine is named `@`, and the text the model + /// reads is that of a thread here but for the machine. + #[test] + fn a_thread_on_another_machine_is_named_with_its_machine() { + let theirs = "[orchestrate] thread kid (\"Fix\") reported.\nResult (reported via report_result):\nDone."; + let ours = on_machine(theirs, "kid", "m1"); + assert_eq!(ours, theirs.replacen("thread kid (", "thread kid@m1 (", 1),); + let [callback] = &callbacks(&ours)[..] else { + panic!("one callback"); + }; + assert_eq!( + (callback.child_id.as_str(), callback.machine.as_deref()), + ("kid", Some("m1")) + ); + assert_eq!(callback.report(), Some("Done.")); + + let message = format!( + "{} turn_completed", + control_header("kid", Some("m1"), "Fix") + ); + assert_eq!( + control_thread(&message), + Some(ControlThread { + thread_id: "kid", + machine: Some("m1"), + title: "Fix".into() + }) + ); + let theirs = format!("{CONTROL_CALLBACK_PREFIX}thread kid (\"Fix\") turn_completed"); + assert_eq!( + on_machine(&theirs, "kid", "m1"), + format!("{CONTROL_CALLBACK_PREFIX}{message}") ); - assert_eq!(control_thread(&message), Some(("worker", title.to_owned()))); } } diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 2b213215e..ec0af0fc5 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -271,6 +271,16 @@ pub struct SessionMeta { pub started_by: Option, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub control_watches: Vec, + /// The thread on another machine that started this one as its subagent. Unlike + /// `parent_session_id`, this thread is a root thread here. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub remote_parent: Option, + /// The threads this one started on other machines of the group. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub remote_children: Vec, + /// What threads on other machines of the group asked to hear of this thread. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub remote_watches: Vec, pub created_at: u64, pub updated_at: u64, } @@ -293,6 +303,10 @@ pub struct ChildExpectation { /// outlive the host, and the next start sends it again. #[serde(default, skip_serializing_if = "Option::is_none")] pub undelivered: Option, + /// The id a lead on another machine of the group names `undelivered` by when its + /// harness has taken it. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub undelivered_id: Option, } impl ChildExpectation { @@ -303,6 +317,7 @@ impl ChildExpectation { delivered_item: None, reminded: false, undelivered: None, + undelivered_id: None, } } } @@ -400,6 +415,12 @@ impl SessionMeta { self.parent_session_id.is_some() && self.native_subagent.is_none() } + /// A subagent its lead started, here or on another machine of the group: it owes that + /// lead its report. + pub fn has_lead(&self) -> bool { + self.is_dispatched() || self.remote_parent.is_some() + } + pub fn migrate_lifecycle(&mut self) { if self.settled_override.is_none() && self.settled_at.is_some() { self.settled_override = Some(SettledOverride::Settled); @@ -487,6 +508,9 @@ impl SessionMeta { self_settle: None, started_by: None, control_watches: Vec::new(), + remote_parent: None, + remote_children: Vec::new(), + remote_watches: Vec::new(), created_at: now, updated_at: now, } @@ -799,11 +823,15 @@ mod tests { "id": "legacy", "title": "Legacy", "provider": "codex", "cwd": "/work", "forked_from": "source", "created_at": 1, "updated_at": 2, "checkpoints": [{"turn": 2, "commit": "deadbeef", "event_offset": 7}], - "approval_mode": "read_only" + "approval_mode": "read_only", + "started_by": {"thread_id": "lead", "request_id": "start-1"} }); let meta: SessionMeta = serde_json::from_value(legacy).unwrap(); assert_eq!(meta.pending_fork, None); assert_eq!(meta.parent_session_id, None); + assert_eq!(meta.remote_parent, None); + assert!(meta.remote_children.is_empty()); + assert_eq!(meta.started_by.as_ref().unwrap().machine, None); assert_eq!(meta.native_subagent, None); assert_eq!(meta.archived_at, None); assert_eq!(meta.worktree, None); @@ -817,6 +845,8 @@ mod tests { "native_subagent", "archived_at", "worktree", + "remote_parent", + "remote_children", ] { assert!(json.get(omitted).is_none(), "unexpected field: {omitted}"); } diff --git a/crates/core/src/relay.rs b/crates/core/src/relay.rs index d3bb14024..7e813ad26 100644 --- a/crates/core/src/relay.rs +++ b/crates/core/src/relay.rs @@ -50,6 +50,7 @@ fn is_provider_work(content: &EntryContent) -> bool { | EntryContent::ContextWindowChanged { .. } | EntryContent::SettingsKept | EntryContent::SessionMoved { .. } + | EntryContent::ThreadMoved { .. } | EntryContent::Worktree { .. } | EntryContent::ControlAction(_) | EntryContent::Rewound(_) @@ -328,6 +329,14 @@ fn render_turn(number: usize, entries: &[&TimelineEntry]) -> String { "thread", &format!("moved from `{}` to `{}`", from.display(), to.display()), ), + EntryContent::ThreadMoved { + from_machine_name, .. + } => activity( + &mut body, + "move", + "thread", + &format!("moved to this machine from `{from_machine_name}`"), + ), EntryContent::Worktree { request, answer } => activity( &mut body, "worktree", diff --git a/crates/core/src/session.rs b/crates/core/src/session.rs index e7a91e4e8..c17868053 100644 --- a/crates/core/src/session.rs +++ b/crates/core/src/session.rs @@ -595,6 +595,11 @@ pub enum EntryContent { from: std::path::PathBuf, to: std::path::PathBuf, }, + /// The thread came to this machine with its project from another machine of + /// the group. + ThreadMoved { + from_machine_name: String, + }, /// What Tcode did with a git worktree the harness asked it for. Worktree { request: agent::WorktreeRequest, @@ -1919,6 +1924,20 @@ impl Timeline { turn, })); } + AgentEvent::ThreadMoved { from_machine_name } => { + let turn = self.ensure_turn(); + let id = self.synthetic_id("thread-moved", ts); + self.entries.push(Arc::new(TimelineEntry { + id, + content: EntryContent::ThreadMoved { + from_machine_name: from_machine_name.clone(), + }, + ts, + finished_ts: None, + background: false, + turn, + })); + } AgentEvent::WorktreeResolved { request, answer, .. } => { diff --git a/crates/core/src/session/boundaries.rs b/crates/core/src/session/boundaries.rs index d68b84d63..242496119 100644 --- a/crates/core/src/session/boundaries.rs +++ b/crates/core/src/session/boundaries.rs @@ -362,6 +362,7 @@ impl TurnBoundaries { | AgentEvent::ContextWindowChanged { .. } | AgentEvent::SettingsKept | AgentEvent::SessionMoved { .. } + | AgentEvent::ThreadMoved { .. } | AgentEvent::WorktreeResolved { .. } | AgentEvent::ControlAction(_) | AgentEvent::UnreadableRecord { .. } diff --git a/crates/core/src/settings.rs b/crates/core/src/settings.rs index 170bfe056..dda2d1aa1 100644 --- a/crates/core/src/settings.rs +++ b/crates/core/src/settings.rs @@ -692,6 +692,8 @@ pub enum SettingsPatch { BrowserHomeUrl(Option), BrowserAllowEvaluate(bool), ControlEnabled(bool), + /// Whether this machine's threads may start threads on the other machines of its group. + ControlMachines(bool), /// The accounts and models a thread `tcode_control` starts may run. ControlAgents(crate::control::AgentScope), VisualizeEnabled(bool), @@ -1309,6 +1311,7 @@ impl Settings { SettingsPatch::BrowserHomeUrl(value) => self.browser.home_url = value, SettingsPatch::BrowserAllowEvaluate(value) => self.browser.allow_evaluate = value, SettingsPatch::ControlEnabled(value) => self.control.enabled = value, + SettingsPatch::ControlMachines(value) => self.control.machines = value, SettingsPatch::ControlAgents(value) => self.control.agents = value, SettingsPatch::VisualizeEnabled(value) => self.visualize.enabled = value, SettingsPatch::SaveCollaboration(collaboration) => { diff --git a/crates/headless/src/main.rs b/crates/headless/src/main.rs index 104587afe..750659210 100644 --- a/crates/headless/src/main.rs +++ b/crates/headless/src/main.rs @@ -161,9 +161,11 @@ fn serve_command(args: &[String]) -> Result<(), String> { } // Nothing else starts for a bind the listener would refuse anyway. check_bind(browser_listen, &remote_data_dir).map_err(|error| error.to_string())?; + let machines = tcode_client::machines::MachineLink::new(); let mut services = HostServices { background_startup_probes: true, ai_title_generation: true, + machines: Some(machines.clone()), ..HostServices::default() }; services.start_mcp_servers(false); @@ -173,7 +175,8 @@ fn serve_command(args: &[String]) -> Result<(), String> { let host = spawn_host(store, services).map_err(|error| format!("machine startup failed: {error}"))?; let mux = HostMux::new(host.attachments.clone(), host.from_host.clone()) - .with_original_backend(std::sync::Arc::new(host.clone())); + .with_original_backend(std::sync::Arc::new(host.clone())) + .with_machine_link(machines); let relayed = !traverse.is_empty(); let traverse_host = Arc::new( TraverseHost::start( diff --git a/crates/protocol/src/command.rs b/crates/protocol/src/command.rs index 2277060dd..3349e523c 100644 --- a/crates/protocol/src/command.rs +++ b/crates/protocol/src/command.rs @@ -458,6 +458,15 @@ pub enum Command { CancelAgent { session_id: String, }, + /// `op` for `thread_id`, a subagent the thread `session_id` started on + /// machine `machine` of the group, through this host: sent now, or kept + /// and sent once that machine can be reached. + ControlRemoteChild { + session_id: String, + machine: String, + thread_id: String, + op: tcode_core::control::RemoteChildOp, + }, SetAutoSettle { session_id: String, enabled: bool, @@ -524,6 +533,27 @@ pub enum Command { DeleteProject { project_id: String, }, + /// Move the project and all its threads to another machine of the group, + /// to `root` there; `include_ignored` takes the files git ignores along. + /// Refused while a move of the project is under way. + MoveProject { + project_id: String, + machine: String, + root: String, + include_ignored: bool, + }, + /// Try a project's paused move again now, where it stopped. + ResumeProjectMove { + project_id: String, + }, + /// Stop a project's move before it is committed on the other machine. + /// With `force` the move ends here whatever the other machine did with + /// it, which may then hold the project too. + CancelProjectMove { + project_id: String, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + force: bool, + }, MarkSessionUnread { session_id: String, }, @@ -825,6 +855,7 @@ impl Command { | Self::RevokeSelfSettle { session_id } | Self::StopWatchingThreads { session_id, .. } | Self::CancelAgent { session_id } + | Self::ControlRemoteChild { session_id, .. } | Self::UnsettleSession { session_id, .. } | Self::PinSession { session_id, .. } | Self::UnpinSession { session_id } diff --git a/crates/protocol/src/event.rs b/crates/protocol/src/event.rs index a1012fdf4..518bee256 100644 --- a/crates/protocol/src/event.rs +++ b/crates/protocol/src/event.rs @@ -81,6 +81,10 @@ pub enum Topic { /// device: answered on subscribe with the last measurement, and pushed /// when one starts or ends. The first subscription measures. DiskUsage, + /// The projects moving from this machine to another, and how each move + /// that ended in the host's run ended: answered on subscribe and pushed + /// after every change. + ProjectMoves, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -212,6 +216,9 @@ pub enum ServerEvent { scope: Scope, /// Unix milliseconds. host_unix_ms: u64, + /// The subscriber may read and change nothing. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + view_only: bool, }, SettingsSnapshot(Settings), /// The current (or latest) external-import run for one project. `None` @@ -229,6 +236,8 @@ pub enum ServerEvent { /// A [`Topic::DiskUsage`]'s state: the answer to subscribing, and a push /// when a measurement starts or ends. DiskUsageReplaced(DiskUsageState), + /// A [`Topic::ProjectMoves`]'s whole state. + ProjectMovesReplaced(crate::ProjectMovesState), } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -1439,6 +1448,13 @@ pub enum RuntimeError { OrphansLeft { left: Vec, }, + /// What a project move left that could not be removed: its parts and + /// snapshot refs on the machine the project left, or its staging on the + /// machine it came to. `error` says what is left where, in the words of the + /// system or of git. + MoveLeftBehind { + error: String, + }, DeleteSession { error: String, }, diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs index ca7d31834..6959e44ea 100644 --- a/crates/protocol/src/lib.rs +++ b/crates/protocol/src/lib.rs @@ -8,6 +8,12 @@ mod command; mod event; mod index; pub use index::index_fingerprint; +mod machine; +pub use machine::{ + EndedProjectMove, MachineCaller, MachineRequest, MachineRequestKind, MachineResponse, + MoveBlocker, MoveOutcome, MovePart, MovePause, MovePhase, MoveState, ProjectMovePreview, + ProjectMoveStatus, ProjectMovesState, +}; mod original; pub use original::{OriginalMetadata, OriginalReply, OriginalRequest, OriginalTarget}; mod preview; @@ -57,12 +63,12 @@ pub use event::{ pub use query::{ AgentAccess, AgentGrant, AgentScope, ControlActivityFilter, ControlActivityPage, ControlActivityThread, DeviceAccess, DirectoryListing, ExternalHistory, ExternalThread, - GitDiffResult, GitDiffScope, GitFileText, GroupAction, GroupInfo, GroupMachineInfo, - HostedDevice, HostingAction, HostingState, IconImageEntry, MAX_STORED_OUTPUT_COLS, - MAX_THREAD_EXPORT_BYTES, ModelGrant, OUTPUT_PREVIEW_BYTES, PathEntry, PathInfo, PathKind, - Query, QueryResponse, RecentDir, SESSION_HISTORY_RECORDS, SESSION_WINDOW_BYTES, - STORED_OUTPUT_ROWS, SessionContentHits, SessionSearchHit, SourceTool, SpaceAction, - SpaceApproval, SpaceInfo, SpacePolicy, TraverseLookupState, TraverseLookupStatus, + GitDiffResult, GitDiffScope, GitFileText, GroupAction, GroupDeviceAccess, GroupInfo, + GroupMachineInfo, HostedDevice, HostingAction, HostingState, IconImageEntry, + MAX_STORED_OUTPUT_COLS, MAX_THREAD_EXPORT_BYTES, ModelGrant, OUTPUT_PREVIEW_BYTES, PathEntry, + PathInfo, PathKind, Query, QueryResponse, RecentDir, SESSION_HISTORY_RECORDS, + SESSION_WINDOW_BYTES, STORED_OUTPUT_ROWS, SessionContentHits, SessionSearchHit, SourceTool, + SpaceAction, SpaceApproval, SpaceInfo, SpacePolicy, TraverseLookupState, TraverseLookupStatus, TraverseManifestState, TraverseManifestStatus, TraverseRelayStatus, TraverseSourceStatus, WorkspaceListing, }; @@ -408,6 +414,30 @@ pub use wire::{ // user through the thread; the agent event stream's user_input_requested and // PendingUserInput gain parent_item_id. Settings loses sidebar_provider_marks, // and SettingsPatch its sidebar_provider_marks patch. +// +// Unreleased: the machines of a group talk over `tcode/1`: Principal gains +// Machine (another machine of the group, which may send only Query::Machine +// with its MachineRequest and MachineResponse) and Viewer (a full device +// while the machine's group devices may only view). GroupAction gains +// SetLabel, SetAcceptThreads, SetAcceptProjects and SetDeviceAccess +// (GroupDeviceAccess); GroupInfo carries accept_threads and accept_projects, +// what the machine takes now, and device_access; GroupMachineInfo carries +// label, accepts_threads and accepts_projects; the group's roster carries each +// machine's label, and the state the members exchange over `tcode/group/1` +// each machine's label and what it accepts. Project moves: the MoveProject, +// ResumeProjectMove and CancelProjectMove (with force) commands, the +// ProjectMovePreview and MovedThread queries, the ProjectMoves topic with +// ProjectMovesReplaced, which carries the moves under way (ProjectMoveStatus) +// and how each move that ended in the host's run ended (EndedProjectMove with +// its MoveOutcome), and RuntimeError's move_left_behind. +// ScopeSnapshot carries view_only. Thread metadata carries remote_parent, +// remote_children and remote_watches, and started_by its machine; a +// ControlAction its actor_machine, and a ControlWatch its machine; Settings' +// control carries machines, with the ControlMachines patch. The command +// ControlRemoteChild reaches a thread's subagent on another machine. The agent +// event stream and the timeline gain thread_moved. The native transport gains +// the machine stream (the machine line and its machine_reply), the closed +// hello rejection and close code 5, access changed. pub const PROTOCOL_VERSION: u32 = 33; #[cfg(test)] diff --git a/crates/protocol/src/machine.rs b/crates/protocol/src/machine.rs new file mode 100644 index 000000000..db968e9b2 --- /dev/null +++ b/crates/protocol/src/machine.rs @@ -0,0 +1,290 @@ +//! What the machines of a group ask each other over `tcode/1`, and what a +//! client sees of a project moving to another machine. +use serde::{Deserialize, Serialize}; + +/// One request from another machine of the group, answered by one +/// [`MachineResponse`]. Only a [`crate::Principal::Machine`] may send it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", content = "content", rename_all = "snake_case")] +pub enum MachineRequest { + Ping, + /// Run one `tcode_control` tool here for a thread on the calling machine. + Control { + caller: MachineCaller, + tool: String, + args: serde_json::Value, + }, + /// Text for a thread here from a thread this machine started on the + /// calling machine. + Callback { + thread_id: String, + from_thread_id: String, + from_title: String, + text: String, + /// The id of the report the text carries, by which a report sent again is known; + /// `None` for a question, an approval or a watch firing. + #[serde(default, skip_serializing_if = "Option::is_none")] + report: Option, + /// What became of the subagent, when the text says it finished. + #[serde(default, skip_serializing_if = "Option::is_none")] + state: Option, + /// The id of the watch the text is the firing of. + #[serde(default, skip_serializing_if = "Option::is_none")] + watch: Option, + }, + /// The calling machine's lead took the report of this machine's child. + ReportTaken { + child_thread_id: String, + }, + /// Whether a project called `project_name` with these threads could + /// move here, to `root` when one is given; answered with + /// [`MachineResponse::MovePreflight`], or refused as `MoveBegin` would + /// refuse it. + MovePreflight { + project_name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + root: Option, + thread_ids: Vec, + }, + /// Stage a move here: the threads it brings, by id, so one this machine + /// already has is refused before any bytes, and the parts it sends. + MoveBegin { + move_id: String, + project_name: String, + root: String, + git: bool, + thread_ids: Vec, + parts: Vec, + }, + MoveChunk { + move_id: String, + part: String, + offset: u64, + #[serde(with = "crate::wire::base64_bytes")] + bytes: Vec, + }, + MoveCommit { + move_id: String, + }, + MoveAbort { + move_id: String, + }, + MoveStatus { + move_id: String, + }, +} + +/// Which of a machine's switches a [`MachineRequest`] falls under. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum MachineRequestKind { + Ping, + /// A thread of the calling machine works here: **accept threads**. + Thread, + /// The answer to something this machine sent out, which comes back + /// whatever the switches say. + Reply, + /// A project moves here: **accept projects**. + Project, +} + +impl MachineRequest { + pub fn kind(&self) -> MachineRequestKind { + match self { + Self::Ping => MachineRequestKind::Ping, + Self::Control { .. } => MachineRequestKind::Thread, + Self::Callback { .. } | Self::ReportTaken { .. } => MachineRequestKind::Reply, + Self::MovePreflight { .. } + | Self::MoveBegin { .. } + | Self::MoveChunk { .. } + | Self::MoveCommit { .. } + | Self::MoveAbort { .. } + | Self::MoveStatus { .. } => MachineRequestKind::Project, + } + } +} + +/// The thread on the calling machine a [`MachineRequest::Control`] acts for. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct MachineCaller { + pub thread_id: String, + pub title: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub request_id: Option, +} + +/// One file a move sends, staged under its name until the commit. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct MovePart { + pub name: String, + pub size: u64, + pub sha256: String, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", content = "content", rename_all = "snake_case")] +pub enum MachineResponse { + Pong, + Control(serde_json::Value), + Done, + MovePreflight { + /// Where the project would go here: this machine's folder for new + /// projects joined with the project's name, made unique. + default_root: String, + }, + /// The bytes already staged of each part, for a move that resumes. + MoveBegun { + received: Vec<(String, u64)>, + }, + MoveProgress { + received: u64, + }, + MoveCommitted { + project_id: String, + }, + MoveState(MoveState), +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", content = "content", rename_all = "snake_case")] +pub enum MoveState { + Unknown, + Staging, + Committed { project_id: String }, +} + +/// What moving a project to another machine would take, and what stands in +/// its way. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProjectMovePreview { + /// Where the project would go on the other machine unless another root + /// is chosen. + pub default_root: String, + pub git: bool, + pub branches: u32, + pub bytes: u64, + pub dirty_checkouts: u32, + pub threads: u32, + pub archived_threads: u32, + /// Files git ignores that a move leaves behind unless they are included. + pub ignored_files: Vec, + pub blockers: Vec, + /// The other machine is reached through a relay. + pub relayed: bool, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", content = "content", rename_all = "snake_case")] +pub enum MoveBlocker { + /// The project holds the quick chats, which stay with their machine. + QuickChat, + /// The project's folder lies inside a larger repository: its history and its threads' + /// worktrees belong to that repository, which is not this project's to move. + InsideRepository, + ThreadsRunning(u32), + /// Approvals and questions waiting for an answer. + PendingApprovals(u32), + /// Threads with messages queued. + QueuedMessages(u32), + TerminalsOpen(u32), + MergeInProgress { + path: String, + }, + /// A thread works in `path`, which the move would not carry: a worktree + /// that is gone or no longer a checkout of this project's repository, or + /// a place outside the project. `thread` is its title. + MissingCheckout { + thread: String, + path: String, + }, + TargetRefuses, + TargetUnreachable, + TargetVersion, +} + +/// What [`crate::Topic::ProjectMoves`] holds: the moves under way, and how each +/// move that ended in this host's run ended, so a client that attaches or +/// reconnects late still learns it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProjectMovesState { + pub moving: Vec, + pub ended: Vec, +} + +/// A move that ended on this machine. The host keeps it until it stops: a move +/// is rare and the record is a few strings, so nothing counts or ages it out. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct EndedProjectMove { + pub move_id: String, + pub project_id: String, + pub project_name: String, + /// The machine the project was moving to. + pub machine: String, + /// The threads that went with it, or would have gone. + pub thread_ids: Vec, + pub outcome: MoveOutcome, +} + +/// How a move ended. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", content = "content", rename_all = "snake_case")] +pub enum MoveOutcome { + /// The other machine has the project and its threads; this machine let go + /// of them, and is letting go of the rest of what the move left. + Moved, + Cancelled { + /// Cancelled once the commit had gone out with no answer, so the + /// project may be on both machines. + forced: bool, + }, +} + +/// One project moving away from this machine, as +/// [`crate::Topic::ProjectMoves`] lists it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProjectMoveStatus { + pub move_id: String, + pub project_id: String, + pub machine: String, + pub phase: MovePhase, + /// Bytes the other machine holds of all the parts, and their sum; both 0 + /// while the parts are being built. + pub done: u64, + pub total: u64, + /// The commit was sent and its outcome is not known yet: the move can + /// only be cancelled with `force`. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub commit_unknown: bool, + /// Why the move waits, while it is paused. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub paused: Option, +} + +/// Why a move is paused. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", content = "content", rename_all = "snake_case")] +pub enum MovePause { + /// The other machine cannot be reached; the move tries again by itself. + Unreachable, + /// The other machine no longer takes projects; the move tries again by + /// itself. + Refused, + /// This machine reaches no group now; the move tries again by itself. + NoGroup, + /// The other machine runs another protocol version. + Version, + /// The other machine is no longer in this machine's group. + NotMember, + /// Something else failed, here or on the other machine, as it said. + Failed { message: String }, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum MovePhase { + Preparing, + SendingCode, + SendingThreads, + Committing, + Paused, + Cancelling, +} diff --git a/crates/protocol/src/query.rs b/crates/protocol/src/query.rs index d3fdd75a8..cd66f8456 100644 --- a/crates/protocol/src/query.rs +++ b/crates/protocol/src/query.rs @@ -208,6 +208,18 @@ pub enum Query { key: tcode_core::pull_request::PullRequestKey, read: crate::PullRequestRead, }, + /// A request from another machine of the group; refused from anyone else. + Machine(crate::MachineRequest), + /// What moving a project to `machine` would take. + ProjectMovePreview { + project_id: String, + machine: String, + }, + /// The machine of the group a thread that was here moved to, with its + /// project; `None` for a thread that never moved away. + MovedThread { + thread_id: String, + }, } /// The widest the host renders command output: a client asks for any width up @@ -284,6 +296,9 @@ pub enum QueryResponse { /// its own clock's idea of the host's. fresh_for: u64, }, + Machine(crate::MachineResponse), + ProjectMovePreview(crate::ProjectMovePreview), + MovedThread(Option), } /// A content search's matches, and the sessions it could not search. @@ -494,6 +509,33 @@ pub enum GroupAction { RemoveMachine(String), /// Admit here a group member declined while new devices were refused. Admit(String), + /// What the whole group calls `machine`, any member's included; `None` + /// or blank clears it. + SetLabel { + machine: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + label: Option, + }, + /// Whether this machine takes the threads other members start on it. + SetAcceptThreads(bool), + /// Whether this machine takes the projects other members move to it. + SetAcceptProjects(bool), + /// What the group's other devices may do on this machine. + SetDeviceAccess(GroupDeviceAccess), +} + +/// What a full-access device may do on a machine of its group. The machine's +/// own window and space members are unaffected. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum GroupDeviceAccess { + /// Everything this machine's own window may do. + #[default] + Operate, + /// Read, and nothing that changes anything. + View, + /// Not admitted at all. + None, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -506,6 +548,12 @@ pub struct GroupInfo { /// refused when they arrived. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub declined: Vec, + /// What this machine takes from the group's other machines now: its + /// switch for each, while the group's devices may operate it, and + /// nothing below that. + pub accept_threads: bool, + pub accept_projects: bool, + pub device_access: GroupDeviceAccess, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -514,6 +562,21 @@ pub struct GroupMachineInfo { pub name: String, #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub this_machine: bool, + /// What the group calls the machine, when anyone gave it a label. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub label: Option, + /// What the machine says it takes; `None` while it has not said. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub accepts_threads: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub accepts_projects: Option, +} + +impl GroupMachineInfo { + /// What the group calls the machine: its label, else its own name. + pub fn title(&self) -> &str { + self.label.as_deref().unwrap_or(&self.name) + } } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/protocol/src/tests.rs b/crates/protocol/src/tests.rs index 6f04ce155..4b61b8697 100644 --- a/crates/protocol/src/tests.rs +++ b/crates/protocol/src/tests.rs @@ -180,6 +180,15 @@ fn binary_payloads_use_base64() { }, "/content/bytes", ); + assert_binary_wire( + Query::Machine(crate::MachineRequest::MoveChunk { + move_id: "move".into(), + part: "code".into(), + offset: 0, + bytes: bytes.clone(), + }), + "/content/content/bytes", + ); assert_binary_wire(QueryResponse::FileBytes(bytes), "/content"); } @@ -651,6 +660,7 @@ fn scope_subscriptions_and_provider_choices_have_literal_wire_contracts() { ServerEvent::ScopeSnapshot { scope: Scope::Full, host_unix_ms: 1_700_000_000_000, + view_only: false, }, json!({"type":"scope_snapshot","content":{"scope":{"type":"full"},"host_unix_ms":1_700_000_000_000_u64}}), ), @@ -658,6 +668,7 @@ fn scope_subscriptions_and_provider_choices_have_literal_wire_contracts() { ServerEvent::ScopeSnapshot { scope: scope.clone(), host_unix_ms: 1_700_000_000_000, + view_only: false, }, json!({"type":"scope_snapshot","content":{"scope":scope_wire.clone(),"host_unix_ms":1_700_000_000_000_u64}}), ), diff --git a/crates/protocol/src/wire.rs b/crates/protocol/src/wire.rs index 9bfbb46d6..77173db26 100644 --- a/crates/protocol/src/wire.rs +++ b/crates/protocol/src/wire.rs @@ -54,6 +54,18 @@ pub enum Principal { device_name: String, policy: crate::SpacePolicy, }, + /// Another machine of this machine's group. It may send only + /// [`crate::Query::Machine`]. + Machine { + machine_id: String, + machine_name: String, + }, + /// A full-access device of the group while this machine lets the group's + /// devices only view: it reads, and changes nothing. + Viewer { + device_id: String, + device_name: String, + }, } #[allow(clippy::large_enum_variant)] // Boxing would complicate the public contract. diff --git a/crates/runtime/src/app/active_session.rs b/crates/runtime/src/app/active_session.rs index 8add83527..34744d50b 100644 --- a/crates/runtime/src/app/active_session.rs +++ b/crates/runtime/src/app/active_session.rs @@ -47,11 +47,13 @@ pub struct QueuedMessage { /// A child's report callback on its way to the lead: the child's /// [`tcode_core::project::ChildExpectation::undelivered`] clears once the lead's -/// provider takes this text. +/// provider takes this text. A child on another machine of the group hears of it there. #[derive(Debug, Clone, PartialEq)] pub(super) struct ReportHandover { pub(super) child: String, pub(super) text: String, + /// The child's machine and the report's id, for a child on another machine. + pub(super) remote: Option<(String, String)>, } #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/crates/runtime/src/app/authorization.rs b/crates/runtime/src/app/authorization.rs index 5bfe85450..900988d03 100644 --- a/crates/runtime/src/app/authorization.rs +++ b/crates/runtime/src/app/authorization.rs @@ -45,7 +45,8 @@ impl AppState { pub(crate) fn session_in_scope(&self, id: &str, principal: &Principal) -> bool { match principal { - Principal::Full => true, + Principal::Full | Principal::Viewer { .. } => true, + Principal::Machine { .. } => false, Principal::Space { project_ids, .. } => self.find_meta(id).is_some_and(|meta| { meta.project_id .as_ref() @@ -96,15 +97,38 @@ impl AppState { payload: &ClientPayload, cx: &HostCx, ) -> Result<(), ProtocolError> { - let Principal::Space { - project_ids, - space_id, - policy, - .. - } = principal - else { - return Ok(()); - }; + match principal { + Principal::Full => match payload { + ClientPayload::Query(Query::Machine(_)) => Err(ProtocolError::out_of_scope( + "only another machine of the group sends machine requests", + )), + _ => Ok(()), + }, + Principal::Machine { .. } => match payload { + ClientPayload::Query(Query::Machine(_)) => Ok(()), + _ => Err(ProtocolError::out_of_scope( + "a machine of the group sends only machine requests", + )), + }, + Principal::Viewer { .. } => authorize_viewer(payload), + Principal::Space { + project_ids, + space_id, + policy, + .. + } => self.authorize_space(principal, project_ids, space_id, policy, payload, cx), + } + } + + fn authorize_space( + &self, + principal: &Principal, + project_ids: &[String], + space_id: &str, + policy: &tcode_protocol::SpacePolicy, + payload: &ClientPayload, + cx: &HostCx, + ) -> Result<(), ProtocolError> { // The newest policy the host has seen: a line from a connection made // before a change can still arrive while the machine closes it. let policy = self.space_policies.get(space_id).unwrap_or(policy); @@ -161,6 +185,7 @@ impl AppState { | Topic::Hosting | Topic::StorageMigration | Topic::DiskUsage + | Topic::ProjectMoves | Topic::ExternalImport { .. } => Err(refusal("subscription")), }, ClientPayload::Command(command) => match command { @@ -467,12 +492,17 @@ impl AppState { .ok_or_else(|| refusal("project")) } // Read marks are the host owner's, kept in their settings like the sidebar - // and favourite marks below. + // and favourite marks below. A turn in a space reaches no other machine, and + // neither does its member. Command::DeleteSession { .. } + | Command::ControlRemoteChild { .. } | Command::RestoreDraft { .. } | Command::MarkSessionRead { .. } | Command::MarkSessionUnread { .. } | Command::DeleteProject { .. } + | Command::MoveProject { .. } + | Command::ResumeProjectMove { .. } + | Command::CancelProjectMove { .. } | Command::CreateProject { .. } | Command::CreateNewProject { .. } | Command::StartScratchDraft @@ -587,6 +617,9 @@ impl AppState { | Query::CollaborationTemplates | Query::NativeMcpServers { .. } | Query::ScanExternalHistory + | Query::Machine(_) + | Query::ProjectMovePreview { .. } + | Query::MovedThread { .. } | Query::BrowseDirectories { .. } => Err(refusal("query")), }, } @@ -661,6 +694,86 @@ impl AppState { } } +fn view_only(kind: &str) -> ProtocolError { + ProtocolError::out_of_scope(format!( + "this machine lets the group's devices only view; {kind} is refused" + )) +} + +/// What a device may do while this machine lets the group's devices only view: read what +/// a full device reads, and change nothing. Every variant is decided here, so one added +/// later is refused until it is listed. +fn authorize_viewer(payload: &ClientPayload) -> Result<(), ProtocolError> { + match payload { + ClientPayload::Unsubscribe(_) => Ok(()), + ClientPayload::Command(_) => Err(view_only("every command")), + ClientPayload::Subscribe(subscription) => match &subscription.topic { + Topic::SessionEvents { .. } + | Topic::SessionStatus { .. } + | Topic::SessionPlan { .. } + | Topic::Index + | Topic::Scope + | Topic::Settings + | Topic::Providers + | Topic::GitStatus { .. } + | Topic::RuntimeEvents + | Topic::CommandOutput { .. } + | Topic::PreviewSession { .. } + | Topic::DevServers { .. } + | Topic::StorageMigration + | Topic::ProjectMoves => Ok(()), + // A preview client answers the agents' requests, the hosting topic is the + // transport's, for full devices, and the last two follow work a viewer cannot + // start: an import, and a measurement that the first subscription starts. + Topic::Terminal { .. } + | Topic::ExternalImport { .. } + | Topic::DiskUsage + | Topic::Preview { .. } + | Topic::SpaceIndex { .. } + | Topic::Hosting => Err(view_only("this subscription")), + }, + ClientPayload::Query(query) => match query { + Query::Ping + | Query::ComputerUsePermissions + | Query::SessionHistoryPage { .. } + | Query::ListActiveWorkspace { .. } + | Query::LoadGitDiff { .. } + | Query::ReadIconImage { .. } + | Query::ReadImagePreview { .. } + | Query::ReadProjectIcon { .. } + | Query::ReadFileBytes { .. } + | Query::ReadFilePreview { .. } + | Query::RenderThreadExport { .. } + | Query::SearchSessionContent { .. } + | Query::ReadItemOutput { .. } + | Query::ThreadAnchorTurn { .. } + | Query::ThreadTurnMarks { .. } + | Query::ReadItemImage { .. } + | Query::ReadItemImagePreview { .. } + | Query::ArchivedSessions + | Query::ControlActivity { .. } + | Query::CollaborationTemplates + | Query::NativeMcpServers { .. } + | Query::MovedThread { .. } + | Query::PullRequest { .. } => Ok(()), + // Each of these writes, runs a model, is another principal's, or walks the + // machine's folders for a dialog that adds or changes something. + Query::Hosting { .. } + | Query::ScanExternalHistory + | Query::BrowseIconImages { .. } + | Query::BrowseDirectories { .. } + | Query::GenerateCommitMessage { .. } + | Query::SaveAttachment { .. } + | Query::RemoveUserFile { .. } + | Query::BeginUpload { .. } + | Query::WriteUpload { .. } + | Query::DiscardUpload { .. } + | Query::Machine(_) + | Query::ProjectMovePreview { .. } => Err(view_only("this query")), + }, + } +} + #[derive(Clone, Copy)] enum PathAccess { Descendant, diff --git a/crates/runtime/src/app/command_validation.rs b/crates/runtime/src/app/command_validation.rs index ec65a6360..d2cc3e801 100644 --- a/crates/runtime/src/app/command_validation.rs +++ b/crates/runtime/src/app/command_validation.rs @@ -35,6 +35,9 @@ impl AppState { code: code.into(), message: message.into(), }; + if let Some(refused) = self.move_refusal(command) { + return Err(refused); + } self.validate_plugin_command(command)?; if let Command::RegenerateSessionTitle { session_id } = command && let Some(thread) = self.sessions.iter().find(|meta| &meta.id == session_id) @@ -131,6 +134,22 @@ impl AppState { "This thread is not an agent dispatched by another thread.", )); } + Command::ControlRemoteChild { + session_id, + machine, + thread_id, + .. + } if !self.find_meta(session_id).is_some_and(|meta| { + meta.remote_children + .iter() + .any(|child| &child.machine == machine && &child.thread_id == thread_id) + }) => + { + return Err(error( + "not_a_remote_child", + "This thread did not start that thread on that machine.", + )); + } Command::ToggleProjectCollapsed { project_id } | Command::MoveSession { project_id, .. } | Command::SetProjectIcon { project_id, .. } @@ -295,6 +314,7 @@ impl AppState { Command::SettleChildren { .. } | Command::SettleSession { .. } | Command::CancelAgent { .. } + | Command::ControlRemoteChild { .. } | Command::UnsettleSession { .. } | Command::SetAutoSettle { .. } | Command::PinSession { .. } diff --git a/crates/runtime/src/app/control/content_tests.rs b/crates/runtime/src/app/control/content_tests.rs index 6c977c1e8..a0ca73868 100644 --- a/crates/runtime/src/app/control/content_tests.rs +++ b/crates/runtime/src/app/control/content_tests.rs @@ -125,7 +125,7 @@ fn call( }; let (reply, answer) = smol::channel::bounded(1); state.update(cx, |state, cx| { - state.handle_control_op(caller.into(), op, reply, cx) + state.handle_control_call(caller.into(), op, None, reply, cx) }); cx.run_until_recv(&answer) } diff --git a/crates/runtime/src/app/control/mod.rs b/crates/runtime/src/app/control/mod.rs index a24cbff93..33229d2f3 100644 --- a/crates/runtime/src/app/control/mod.rs +++ b/crates/runtime/src/app/control/mod.rs @@ -56,7 +56,7 @@ impl ControlState { /// A call's answer: ready on the host thread, or computed off it because it runs git, reads /// the store or waits for work the call started, which would stall every client if awaited /// on the host thread. A `Later` task is dropped once its caller goes. -pub(super) enum Answer { +pub(in crate::app) enum Answer { Now(Result), Later(HostTask>), } @@ -64,7 +64,7 @@ pub(super) enum Answer { /// The part of a call that needs the host state, run on the host thread once the call's /// off-thread work has finished; its result is the call's answer. It runs in `call_cx`, the /// context the call was given: the host's own carries no author, origin or space. -async fn finish_on_host( +pub(in crate::app) async fn finish_on_host( call_cx: HostCx, finish: impl FnOnce(&mut AppState, &mut HostCx) -> Result + Send @@ -87,16 +87,26 @@ fn refusal(error: tcode_protocol::ProtocolError) -> String { /// The thread behind a `tcode_control` call. #[derive(Clone)] -pub(super) struct Caller { - pub(super) thread_id: String, - pub(super) project_id: Option, +pub(in crate::app) struct Caller { + /// The calling thread: this machine's, or `machine`'s when that is set, which then + /// names no thread here. + pub(in crate::app) thread_id: String, + pub(in crate::app) project_id: Option, /// The space whose member's turn makes the call, which confines it to that space's /// projects and policy. - pub(super) space: Option, + pub(in crate::app) space: Option, + pub(in crate::app) machine: Option, } +/// The machine of the group a calling thread is on, when it is not this one. #[derive(Clone)] -pub(super) struct CallerSpace { +pub(in crate::app) struct RemoteCaller { + pub(in crate::app) peer: super::machines::MachinePeer, + pub(in crate::app) title: String, +} + +#[derive(Clone)] +pub(in crate::app) struct CallerSpace { pub(super) projects: BTreeSet, pub(super) policy: tcode_protocol::SpacePolicy, } @@ -146,27 +156,41 @@ impl AppState { let control_mcp::BrokerRequest { thread_id, op, + machine, reply, } = request; - host_cx.enqueue(move |state, cx| state.handle_control_op(thread_id, op, reply, cx)); + host_cx.enqueue(move |state, cx| { + state.handle_control_call(thread_id, op, machine, reply, cx) + }); } }); } /// What the control server offers `meta`'s thread: nothing with the feature off, - /// otherwise every tool and, for a subagent, `report_result`, and for the thread the - /// user opened to research a model's guide, `set_model_guide`. + /// otherwise every tool and, for a subagent, `report_result`, for the thread the + /// user opened to research a model's guide, `set_model_guide`, and the tools about the + /// group's machines where this machine reaches a group and lets its threads do so. pub(super) fn control_access(&self, meta: &SessionMeta) -> ThreadAccess { ThreadAccess { enabled: self.settings.control.enabled, - subagent: meta.is_dispatched(), + subagent: meta.has_lead(), model_guide: meta.guide_for.is_some(), + machines: self.settings.control.machines && self.machine_link().is_ok(), } } - /// Whether `target` is a subagent `caller` started. - pub(super) fn own_subagent(&self, caller: &Caller, target: &SessionMeta) -> bool { - target.is_dispatched() && target.parent_session_id.as_deref() == Some(&caller.thread_id) + /// Whether `target` is a subagent `caller` started: here, or, for a caller on another + /// machine, on this machine for that thread. + pub(in crate::app) fn own_subagent(&self, caller: &Caller, target: &SessionMeta) -> bool { + match &caller.machine { + None => { + target.is_dispatched() + && target.parent_session_id.as_deref() == Some(&caller.thread_id) + } + Some(remote) => target.remote_parent.as_ref().is_some_and(|parent| { + parent.machine == remote.peer.id && parent.thread_id == caller.thread_id + }), + } } /// Whether the thread's provider is given the `tcode_control` server when it starts. @@ -222,7 +246,7 @@ impl AppState { /// Re-read every registered thread's access after the setting changed, so the next /// connection lists the right tools; with the feature off a registered thread is offered /// none. - pub(super) fn refresh_control_access(&mut self) { + pub(in crate::app) fn refresh_control_access(&mut self) { let registered: Vec = self.mcp.control_registrations.keys().cloned().collect(); let access: Vec<(String, ThreadAccess)> = registered .into_iter() @@ -260,16 +284,24 @@ impl AppState { thread_id: meta.id.clone(), project_id: meta.project_id.clone(), space, + machine: None, } } - /// Whether a call may name `target`: any thread on the host, or, in a member's turn, - /// one inside the space. + /// Whether a call may name `target`: any thread on the host; in a member's turn, one + /// inside the space; for a thread on another machine of the group, one that machine + /// started here. pub(super) fn open_to(&self, caller: &Caller, target: &SessionMeta) -> bool { caller .space .as_ref() .is_none_or(|space| space.holds(target.project_id.as_deref())) + && caller.machine.as_ref().is_none_or(|remote| { + target + .started_by + .as_ref() + .is_some_and(|started| started.machine.as_ref() == Some(&remote.peer.id)) + }) } /// Whether a listing or search covering `scope` includes `target`. @@ -283,11 +315,13 @@ impl AppState { && self.open_to(caller, target) } - /// Resolve one `tcode_control` call on the host thread. - pub(crate) fn handle_control_op( + /// Resolve one `tcode_control` call on the host thread, for `machine` of the group when + /// it names one. + pub(crate) fn handle_control_call( &mut self, thread_id: String, op: ControlOp, + machine: Option, reply: smol::channel::Sender>, cx: &mut HostCx, ) { @@ -305,13 +339,27 @@ impl AppState { } Some(meta) => { let caller = self.caller_of(&meta); - match self.authorize_control(&caller, &op) { - Ok(()) => self.dispatch_control_op(&caller, op, cx), - Err(refusal) => Answer::Now(Err(refusal)), + match machine { + // The ids it names are the other machine's, which this one does not + // check. + Some(machine) => self.forward_control_op(&caller, machine, op, cx), + None => match self.authorize_control(&caller, &op) { + Ok(()) => self.dispatch_control_op(&caller, op, cx), + Err(refusal) => Answer::Now(Err(refusal)), + }, } } None => Answer::Now(Err("unknown thread".into())), }; + self.answer_control_call(answer, reply, cx); + } + + pub(in crate::app) fn answer_control_call( + &mut self, + answer: Answer, + reply: smol::channel::Sender>, + cx: &mut HostCx, + ) { match answer { Answer::Now(result) => { let _ = reply.try_send(result); @@ -349,7 +397,11 @@ impl AppState { /// go: what a space withholds from its members' turns, the settings no agent changes, and /// a target that is unknown, the caller's own Orchestrate ancestor or outside its space. /// Whether a call that is open should be made is the harness's permission mode to settle. - pub(super) fn authorize_control(&self, caller: &Caller, op: &ControlOp) -> Result<(), String> { + pub(in crate::app) fn authorize_control( + &self, + caller: &Caller, + op: &ControlOp, + ) -> Result<(), String> { if let Some(space) = &caller.space { self.authorize_space_control(space, op)?; } @@ -383,10 +435,17 @@ impl AppState { /// Why `target` is closed to `caller`, or its meta when it is open. fn check_target(&self, caller: &Caller, target: &str) -> Result { let Some(meta) = self.find_meta(target) else { - return Err(TargetRefusal::Unknown); + return Err(match self.moved_thread_machine(target) { + Some(machine) => TargetRefusal::Moved(machine.to_owned()), + None => TargetRefusal::Unknown, + }); }; if !self.open_to(caller, &meta) { - return Err(TargetRefusal::OutsideSpace); + // Another machine is not told which threads it did not start exist here. + return Err(match caller.machine { + Some(_) => TargetRefusal::Unknown, + None => TargetRefusal::OutsideSpace, + }); } Ok(meta) } @@ -402,7 +461,12 @@ impl AppState { .map_err(|refusal| refusal.per_item()) } - fn dispatch_control_op(&mut self, caller: &Caller, op: ControlOp, cx: &mut HostCx) -> Answer { + pub(in crate::app) fn dispatch_control_op( + &mut self, + caller: &Caller, + op: ControlOp, + cx: &mut HostCx, + ) -> Answer { let now = match op { ControlOp::ListThreads(p) => return self.op_list_threads(caller, p, cx), ControlOp::Search(p) => return self.op_search(caller, p, cx), @@ -437,12 +501,18 @@ impl AppState { ControlOp::Rewind(p) => return self.op_rewind(caller, p, cx), ControlOp::PatchSettings(p) => self.op_patch_settings(caller, p, cx), ControlOp::SetModelGuide(p) => self.op_set_model_guide(caller, p, cx), + ControlOp::ListMachines(p) => return self.op_list_machines(caller, p, cx), + ControlOp::StartThreadOnMachine(p) => { + return self.op_start_thread_on_machine(caller, p, cx); + } }; Answer::Now(now) } /// Record a write in the target thread, as the actor's thread, and in the activity list. - pub(super) fn audit( + /// A caller on another machine is named with its machine here, and its own log is that + /// machine's to write. + pub(in crate::app) fn audit( &mut self, caller: &Caller, target: &str, @@ -450,10 +520,13 @@ impl AppState { detail: Option, cx: &mut HostCx, ) { - let actor_title = self - .find_meta(&caller.thread_id) - .map(|meta| meta.title) - .unwrap_or_default(); + let actor_title = match &caller.machine { + Some(remote) => remote.title.clone(), + None => self + .find_meta(&caller.thread_id) + .map(|meta| meta.title) + .unwrap_or_default(), + }; let target_title = self .find_meta(target) .map(|meta| meta.title) @@ -461,12 +534,13 @@ impl AppState { let action = ControlAction { actor_thread_id: caller.thread_id.clone(), actor_title, + actor_machine: caller.machine.as_ref().map(|remote| remote.peer.id.clone()), action: action.to_owned(), detail, }; let at = cx.clock().unix_millis(); self.record_event(target, &AgentEvent::ControlAction(action.clone()), cx); - if target != caller.thread_id { + if caller.machine.is_none() && target != caller.thread_id { let in_caller = ControlAction { detail: Some(match &action.detail { Some(detail) => format!("{target_title} — {detail}"), @@ -527,7 +601,7 @@ impl AppState { } /// Write a changed meta through to the resident copy, the index and the store. - pub(super) fn store_meta(&mut self, meta: SessionMeta, cx: &mut HostCx) { + pub(in crate::app) fn store_meta(&mut self, meta: SessionMeta, cx: &mut HostCx) { if let Some(live) = self.meta_mut(&meta.id) { *live = meta.clone(); } @@ -539,12 +613,17 @@ impl AppState { enum TargetRefusal { Unknown, OutsideSpace, + /// The thread moved with its project to this machine of the group. + Moved(String), } impl TargetRefusal { fn whole_call(&self, target: &str) -> String { match self { Self::Unknown => format!("unknown thread: {target}"), + Self::Moved(machine) => { + format!("thread {target} moved to machine {machine} of the group") + } Self::OutsideSpace => { format!("refused: thread {target} is outside the space this turn runs in") } @@ -554,6 +633,7 @@ impl TargetRefusal { fn per_item(&self) -> String { match self { Self::Unknown => "unknown_thread".to_owned(), + Self::Moved(machine) => format!("thread_moved: to machine {machine}"), Self::OutsideSpace => "outside_space: this turn runs in a space".to_owned(), } } @@ -573,6 +653,10 @@ impl AppState { | ControlOp::SetModelGuide(_) | ControlOp::CreateProject(_) | ControlOp::DeleteThreads(_) => refused("is not available"), + // Spaces are this machine's: a member's turn reaches no other machine. + ControlOp::ListMachines(_) | ControlOp::StartThreadOnMachine(_) => { + refused("reaches no other machine") + } ControlOp::Terminal(_) | ControlOp::ReadTerminal(_) if !policy.terminals => { refused("needs terminals, which the space does not allow") } diff --git a/crates/runtime/src/app/control/observe.rs b/crates/runtime/src/app/control/observe.rs index 4c6a430cc..9030e979f 100644 --- a/crates/runtime/src/app/control/observe.rs +++ b/crates/runtime/src/app/control/observe.rs @@ -99,6 +99,10 @@ pub(super) struct SettlementExplanation { due_at: Option, /// Every fact that keeps automatic settlement from applying, as `settlement_reason` keys. reasons: Vec<&'static str>, + /// The subagents on other machines that still run and so hold it, as + /// `@`. + #[serde(skip_serializing_if = "Vec::is_empty")] + running_on_machines: Vec, rule: SettlementRuleFacts, } @@ -139,6 +143,12 @@ struct Lineage { forked_from: Option, imported_from: Option, native_subagent: bool, + /// The thread on another machine that started this one as its subagent. + #[serde(skip_serializing_if = "Option::is_none")] + remote_parent: Option, + /// The threads this one started on other machines, with what it last heard of them. + #[serde(skip_serializing_if = "Vec::is_empty")] + remote_children: Vec, } #[derive(Debug, Serialize)] @@ -162,6 +172,9 @@ struct ThreadDetail { /// its delivery is in `activity.agent`. #[serde(skip_serializing_if = "Option::is_none")] report: Option, + /// The wakes notify_when registered for this thread, by their ids. + #[serde(skip_serializing_if = "Vec::is_empty")] + watches: Vec, terminals: Vec, omitted: Vec, } @@ -804,6 +817,9 @@ impl AppState { would_auto_settle, due_at: due.filter(|_| would_auto_settle).map(|due| due.due_at), reasons, + running_on_machines: crate::app::machines::running_remote_children(meta) + .map(|child| format!("{}@{}", child.thread_id, child.machine)) + .collect(), rule: SettlementRuleFacts { after_days: rule.after_days, after_days_source: source(rule.after_days_from_project), @@ -987,8 +1003,11 @@ impl AppState { .map(|origin| origin.thread_id.clone()), imported_from: meta.imported_from.clone(), native_subagent: meta.native_subagent.is_some(), + remote_parent: meta.remote_parent.clone(), + remote_children: meta.remote_children.clone(), }, - report: meta.is_dispatched().then(|| meta.report()), + report: meta.has_lead().then(|| meta.report()), + watches: meta.control_watches.clone(), terminals, omitted: vec![ "worktree.dirty: read it live with get_git or list_threads include_worktree".into(), diff --git a/crates/runtime/src/app/control/observe_tests.rs b/crates/runtime/src/app/control/observe_tests.rs index 862f160b6..5d37afeba 100644 --- a/crates/runtime/src/app/control/observe_tests.rs +++ b/crates/runtime/src/app/control/observe_tests.rs @@ -78,7 +78,7 @@ fn call( ) -> Result { let (reply, response) = smol::channel::bounded(1); state.update(cx, |state, cx| { - state.handle_control_op("caller".into(), op, reply, cx) + state.handle_control_call("caller".into(), op, None, reply, cx) }); cx.run_until_recv(&response) } diff --git a/crates/runtime/src/app/control/operate.rs b/crates/runtime/src/app/control/operate.rs index 9ad03071a..f177defe3 100644 --- a/crates/runtime/src/app/control/operate.rs +++ b/crates/runtime/src/app/control/operate.rs @@ -46,7 +46,13 @@ fn to_json(value: impl serde::Serialize) -> Result { } fn request_key(caller: &Caller, tool: &str, request_id: &str) -> String { - format!("{}/{tool}/{request_id}", caller.thread_id) + match &caller.machine { + Some(remote) => format!( + "{}@{}/{tool}/{request_id}", + caller.thread_id, remote.peer.id + ), + None => format!("{}/{tool}/{request_id}", caller.thread_id), + } } fn action_now(thread_id: &str, outcome: Outcome, reason: impl Into) -> Answer { @@ -139,6 +145,7 @@ pub(super) fn settings_patch_never_exposed(patch: &SettingsPatch) -> bool { | SettingsPatch::BrowserHomeUrl(_) | SettingsPatch::BrowserAllowEvaluate(_) | SettingsPatch::ControlEnabled(_) + | SettingsPatch::ControlMachines(_) | SettingsPatch::ControlAgents(_) | SettingsPatch::VisualizeEnabled(_) | SettingsPatch::ModelGuide(_) @@ -327,6 +334,9 @@ impl AppState { return Ok(StartPlan::Started(started)); } let subagent = params.subagent.unwrap_or(false); + if caller.machine.is_some() && params.attachments.is_some() { + return Err("refused: attachments do not go from one machine to another".into()); + } let attachment_paths = self.agent_attachments(caller, params.attachments, cx)?; if params.message.trim().is_empty() && attachment_paths.is_empty() { return Err("message is empty".into()); @@ -408,7 +418,9 @@ impl AppState { } let caller_cwd = self .find_meta(&caller.thread_id) - .filter(|meta| meta.project_id.as_deref() == Some(project.id.as_str())) + .filter(|meta| { + caller.machine.is_none() && meta.project_id.as_deref() == Some(project.id.as_str()) + }) .map(|meta| meta.cwd); let cwd = match params.cwd { None => caller_cwd @@ -445,7 +457,7 @@ impl AppState { acp_agent_id.as_deref(), model.as_deref(), )?; - if subagent { + if subagent && caller.machine.is_none() { self.collaboration_allows_collaborator( caller, provider, @@ -470,7 +482,17 @@ impl AppState { .map(|(id, value)| OptionSelection { id, value }) .collect(); if subagent { - meta.parent_session_id = Some(caller.thread_id.clone()); + match &caller.machine { + // An ordinary root thread here: only its report goes back. + Some(remote) => { + meta.remote_parent = Some(tcode_core::control::RemoteParent { + machine: remote.peer.id.clone(), + thread_id: caller.thread_id.clone(), + title: remote.title.clone(), + }); + } + None => meta.parent_session_id = Some(caller.thread_id.clone()), + } meta.option_selections.extend(resolve_child_permission( permission_control(provider), self.settings.subagents.child_approval, @@ -486,6 +508,7 @@ impl AppState { meta.started_by = Some(StartedBy { thread_id: caller.thread_id.clone(), request_id: params.request_id, + machine: caller.machine.as_ref().map(|remote| remote.peer.id.clone()), }); Ok(StartPlan::Install { meta: Box::new(meta), @@ -568,17 +591,20 @@ impl AppState { /// The thread an earlier `start_thread` call with this `request_id` started. fn started_by_request(&self, caller: &Caller, request_id: &str) -> Option { + let machine = caller.machine.as_ref().map(|remote| &remote.peer.id); let meta = self.sessions.iter().find(|meta| { - meta.started_by - .as_ref() - .is_some_and(|by| by.thread_id == caller.thread_id && by.request_id == request_id) + meta.started_by.as_ref().is_some_and(|by| { + by.thread_id == caller.thread_id + && by.request_id == request_id + && by.machine.as_ref() == machine + }) })?; Some(StartThreadResponse { thread_id: meta.id.clone(), created: false, title: meta.title.clone(), cwd: meta.cwd.display().to_string(), - subagent: meta.is_dispatched(), + subagent: meta.has_lead(), worktree_branch: meta .worktree .as_ref() @@ -601,9 +627,10 @@ impl AppState { { return to_json(started); } - if !self - .find_meta(&caller.thread_id) - .is_some_and(|meta| meta.archived_at.is_none()) + if caller.machine.is_none() + && !self + .find_meta(&caller.thread_id) + .is_some_and(|meta| meta.archived_at.is_none()) { return Err("this thread was archived before its subagent could start".into()); } @@ -612,13 +639,13 @@ impl AppState { created: true, title: meta.title.clone(), cwd: meta.cwd.display().to_string(), - subagent: meta.is_dispatched(), + subagent: meta.has_lead(), worktree_branch: meta .worktree .as_ref() .map(|worktree| worktree.branch.clone()), }; - let id = if meta.is_dispatched() { + let id = if meta.has_lead() { self.install_subagent(meta, message, attachments, cx) } else { self.install_background_thread(meta, message, attachments, cx) @@ -896,8 +923,11 @@ impl AppState { "not your subagent: cancel stops only your own".into(), )); } - self.validate_command_target(&Command::CancelAgent { session_id }) - .map_err(|error| skipped(error.message))?; + // A thread another machine's thread started is no agent of a thread here. + if caller.machine.is_none() { + self.validate_command_target(&Command::CancelAgent { session_id }) + .map_err(|error| skipped(error.message))?; + } self.cancel_child(target, cx); self.audit(caller, target, action::CANCEL, None, cx); return Ok(("cancelled; its result is not delivered", None)); diff --git a/crates/runtime/src/app/control/operate_tests.rs b/crates/runtime/src/app/control/operate_tests.rs index 7589db057..9768b7a9c 100644 --- a/crates/runtime/src/app/control/operate_tests.rs +++ b/crates/runtime/src/app/control/operate_tests.rs @@ -16,7 +16,7 @@ fn call( ) -> Result { let (reply, answer) = smol::channel::bounded(1); state.update(cx, |state, cx| { - state.handle_control_op(caller.into(), op, reply, cx) + state.handle_control_call(caller.into(), op, None, reply, cx) }); cx.run_until_recv(&answer) } diff --git a/crates/runtime/src/app/control/organize.rs b/crates/runtime/src/app/control/organize.rs index 7a9a8db55..0428b1e28 100644 --- a/crates/runtime/src/app/control/organize.rs +++ b/crates/runtime/src/app/control/organize.rs @@ -506,7 +506,7 @@ impl AppState { /// Apply `change` to a stored thread's meta and persist it when it changed anything; /// persisting re-evaluates the thread's settlement. - pub(super) fn change_meta( + pub(in crate::app) fn change_meta( &mut self, session_id: &str, cx: &mut HostCx, diff --git a/crates/runtime/src/app/control/organize_tests.rs b/crates/runtime/src/app/control/organize_tests.rs index d969a8859..0ae9a4f23 100644 --- a/crates/runtime/src/app/control/organize_tests.rs +++ b/crates/runtime/src/app/control/organize_tests.rs @@ -22,7 +22,7 @@ fn call( ) -> Result { let (reply, answer) = smol::channel::bounded(1); state.update(cx, |state, cx| { - state.handle_control_op(caller.into(), op, reply, cx) + state.handle_control_call(caller.into(), op, None, reply, cx) }); cx.run_until_recv(&answer) } diff --git a/crates/runtime/src/app/control/tests.rs b/crates/runtime/src/app/control/tests.rs index b8e470e7a..8cc441cf6 100644 --- a/crates/runtime/src/app/control/tests.rs +++ b/crates/runtime/src/app/control/tests.rs @@ -29,12 +29,14 @@ fn stored(store: &TestStore, threads: &[(&str, &str)]) { } } -/// Every `tcode_control` tool but the subagent's `report_result`, in name order. +/// Every `tcode_control` tool but the subagent's `report_result` and those about a group's +/// machines, which a host without a way to them does not offer, in name order. fn every_tool() -> Vec { control_mcp::tool_descriptions(&control_mcp::ThreadAccess { enabled: true, subagent: false, model_guide: false, + machines: false, }) .into_iter() .map(|(name, _)| name) @@ -144,6 +146,7 @@ fn activity_filters_by_thread_or_kind_and_offers_the_whole_log() { action: ControlAction { actor_thread_id: actor.into(), actor_title: actor.to_uppercase(), + actor_machine: None, action: action.into(), detail: None, }, @@ -199,7 +202,7 @@ fn call( cx: &mut HostCx, ) -> Result { let (reply, response) = smol::channel::bounded(1); - state.handle_control_op(thread_id.into(), op, reply, cx); + state.handle_control_call(thread_id.into(), op, None, reply, cx); response.try_recv().unwrap() } @@ -711,7 +714,7 @@ fn delete_threads_previews_then_deletes_the_tree() { cx.run_until_parked(); assert_eq!(cx.seen().sessions().count(), 3, "a preview deletes nothing"); state.update(cx, |state, cx| { - state.handle_control_op("caller".into(), delete, reply, cx) + state.handle_control_call("caller".into(), delete, None, reply, cx) }); // The answer waits for the deleted threads' uploads to be removed. let deleted = cx.run_until_recv(&response).unwrap(); diff --git a/crates/runtime/src/app/control/watches.rs b/crates/runtime/src/app/control/watches.rs index 9b830f6ff..9111d6f2b 100644 --- a/crates/runtime/src/app/control/watches.rs +++ b/crates/runtime/src/app/control/watches.rs @@ -102,6 +102,9 @@ impl AppState { if params.events.is_empty() { return Err("notify_when needs at least one event".into()); } + if let Some(remote) = &caller.machine { + return Ok(self.watch_for_machine(caller, &remote.peer.id, params, cx)); + } let mut meta = self.find_meta(&caller.thread_id).ok_or("unknown thread")?; // A retried call finds the watch its first attempt stored under the same key. if let Some(watch) = params.request_id.as_deref().and_then(|request_id| { @@ -137,6 +140,7 @@ impl AppState { thread_ids, events: params.events.into_iter().collect(), space: cx.space.clone(), + machine: None, }; let answer = serde_json::json!(WatchAnswer { skipped, @@ -158,21 +162,139 @@ impl AppState { Ok(answer) } + /// `notify_when` for a thread on another machine: each watched thread here keeps the + /// watch, which a restart keeps, and its firing goes back to that machine. + fn watch_for_machine( + &mut self, + caller: &Caller, + machine: &str, + params: NotifyWhenParams, + cx: &mut HostCx, + ) -> serde_json::Value { + let id = params + .request_id + .unwrap_or_else(|| uuid::Uuid::new_v4().to_string()); + let mut thread_ids = params.thread_ids; + thread_ids.sort(); + thread_ids.dedup(); + let events: BTreeSet = params.events.into_iter().collect(); + let mut skipped = Vec::new(); + let mut watched = Vec::new(); + for target in thread_ids { + let mut meta = match self.batch_target(caller, &target) { + Ok(meta) => meta, + Err(reason) => { + skipped.push(BatchResult { + target, + outcome: Outcome::Skipped, + reason: Some(reason), + side_effects: None, + }); + continue; + } + }; + // A retried call finds the watch its first attempt stored under the same key. + let held = meta.remote_watches.iter().any(|watch| { + watch.id == id && watch.machine == machine && watch.thread_id == caller.thread_id + }); + if !held { + meta.remote_watches.push(tcode_core::control::RemoteWatch { + id: id.clone(), + machine: machine.to_owned(), + thread_id: caller.thread_id.clone(), + events: events.clone(), + fired: None, + }); + self.store_meta(meta, cx); + self.audit(caller, &target, action::NOTIFY_WHEN, Some(id.clone()), cx); + } + watched.push(target); + } + if watched.is_empty() { + return serde_json::json!({ "skipped": skipped }); + } + serde_json::json!(WatchAnswer { + id: &id, + thread_ids: &watched, + events: &events, + skipped, + }) + } + + /// `cancel_notify` for a thread on another machine: the watches it keeps here go. + fn unwatch_for_machine( + &mut self, + caller: &Caller, + machine: &str, + ids: Vec, + cx: &mut HostCx, + ) -> serde_json::Value { + let ours = |watch: &tcode_core::control::RemoteWatch| { + watch.machine == machine && watch.thread_id == caller.thread_id + }; + let held: Vec = self + .sessions + .iter() + .filter(|meta| { + meta.remote_watches + .iter() + .any(|watch| ours(watch) && ids.contains(&watch.id)) + }) + .cloned() + .collect(); + let mut removed = BTreeSet::new(); + for mut meta in held { + let mut here = Vec::new(); + meta.remote_watches.retain(|watch| { + let gone = ours(watch) && ids.contains(&watch.id); + if gone { + here.push(watch.id.clone()); + } + !gone + }); + let target = meta.id.clone(); + self.store_meta(meta, cx); + self.audit( + caller, + &target, + action::CANCEL_NOTIFY, + Some(here.join(", ")), + cx, + ); + removed.extend(here); + } + let (removed, unknown): (Vec, Vec) = + ids.into_iter().partition(|id| removed.contains(id)); + serde_json::json!(CancelNotifyAnswer { removed, unknown }) + } + pub(super) fn op_cancel_notify( &mut self, caller: &Caller, params: CancelNotifyParams, cx: &mut HostCx, ) -> Result { + if let Some(remote) = &caller.machine { + return Ok(self.unwatch_for_machine(caller, &remote.peer.id.clone(), params.ids, cx)); + } let mut meta = self.find_meta(&caller.thread_id).ok_or("unknown thread")?; let (removed, unknown): (Vec, Vec) = params .ids .into_iter() .partition(|id| meta.control_watches.iter().any(|watch| &watch.id == id)); if !removed.is_empty() { + let elsewhere: Vec = meta + .control_watches + .iter() + .filter(|watch| watch.machine.is_some() && removed.contains(&watch.id)) + .cloned() + .collect(); meta.control_watches .retain(|watch| !removed.contains(&watch.id)); self.store_meta(meta, cx); + for watch in elsewhere { + self.unwatch_on_machine(&caller.thread_id, watch, cx); + } let detail = removed.join(", "); self.audit( caller, @@ -200,7 +322,9 @@ impl AppState { return; } let fires = |watch: &ControlWatch| { - watch.events.contains(&event) && watch.thread_ids.iter().any(|id| id == target_id) + watch.machine.is_none() + && watch.events.contains(&event) + && watch.thread_ids.iter().any(|id| id == target_id) }; let watchers: Vec = self .sessions @@ -208,18 +332,31 @@ impl AppState { .filter(|meta| meta.control_watches.iter().any(fires)) .map(|meta| meta.id.clone()) .collect(); - if watchers.is_empty() { - return; - } - let Some(target) = self.find_meta(target_id) else { + let Some(mut target) = self.find_meta(target_id) else { return; }; + let remote = target + .remote_watches + .iter() + .any(|watch| watch.fired.is_none() && watch.events.contains(&event)); + if watchers.is_empty() && !remote { + return; + } let text = format!( "{CONTROL_CALLBACK_PREFIX}{} {}{}", - control_header(target_id, &target.title), + control_header(target_id, None, &target.title), wire_name(event), self.watch_event_detail(&target, event) ); + if remote { + for watch in &mut target.remote_watches { + if watch.fired.is_none() && watch.events.contains(&event) { + watch.fired = Some(text.clone()); + } + } + self.store_meta(target.clone(), cx); + self.send_watch_firings(Some(target_id), cx); + } for watcher in watchers { let Some(mut meta) = self.find_meta(&watcher) else { continue; diff --git a/crates/runtime/src/app/events.rs b/crates/runtime/src/app/events.rs index 8a396e0dc..aafdae89b 100644 --- a/crates/runtime/src/app/events.rs +++ b/crates/runtime/src/app/events.rs @@ -139,10 +139,11 @@ impl AppState { !parked.queue.is_empty() }); self.repair_orphaned_turn(session_id, cx); - let is_child = self - .sessions - .iter() - .any(|meta| meta.id == session_id && meta.parent_session_id.is_some()); + let is_child = self.sessions.iter().any(|meta| { + meta.id == session_id + && (meta.parent_session_id.is_some() + || meta.remote_parent.is_some()) + }); if is_child && !has_queued { self.fail_child_expectation( session_id, @@ -537,6 +538,7 @@ impl AppState { | AgentEvent::ContextCompacted(_) | AgentEvent::ContextWindowChanged { .. } | AgentEvent::SettingsKept + | AgentEvent::ThreadMoved { .. } | AgentEvent::WorktreeResolved { .. } | AgentEvent::PlanUpdated { .. } | AgentEvent::GoalUpdated { .. } @@ -713,6 +715,7 @@ impl AppState { } self.adopt_meta(meta, cx); } + self.reports_taken(reports, cx); } pub(super) fn record_event_at( diff --git a/crates/runtime/src/app/lifecycle.rs b/crates/runtime/src/app/lifecycle.rs index d109d8b91..44c0dfa8a 100644 --- a/crates/runtime/src/app/lifecycle.rs +++ b/crates/runtime/src/app/lifecycle.rs @@ -30,6 +30,10 @@ impl AppState { /// Spawn a provider for either the foreground session or a parked child. pub(super) fn ensure_session_started(&mut self, session_id: &str, cx: &mut HostCx) { + // Nothing works in a thread whose project is moving away. + if self.thread_moving(session_id) { + return; + } let idle = self .residents .live @@ -346,7 +350,7 @@ impl AppState { }; state.record_event(&session_id, &error_event, cx); let is_child = state.sessions.iter().any(|meta| { - meta.id == session_id && meta.parent_session_id.is_some() + meta.id == session_id && (meta.parent_session_id.is_some() || meta.remote_parent.is_some()) }); if is_child { if let Some(child) = state.resident_mut(&session_id) { diff --git a/crates/runtime/src/app/machines/arrivals.rs b/crates/runtime/src/app/machines/arrivals.rs new file mode 100644 index 000000000..71bc08924 --- /dev/null +++ b/crates/runtime/src/app/machines/arrivals.rs @@ -0,0 +1,342 @@ +//! A project and its threads moving to this machine from another of the +//! group: staged as the parts arrive, invisible until `MoveCommit` makes the +//! project and every thread at once. The transport has already checked that +//! the caller is a member on this protocol and that this machine takes +//! projects. +use std::path::{Path, PathBuf}; + +use tcode_protocol::{MachineRequest, MachineResponse, MoveState}; +use tcode_services::project_move as disk; + +use super::MachinePeer; +use crate::app::*; + +fn refusal(code: &str, message: impl Into) -> ProtocolError { + ProtocolError { + code: code.into(), + message: message.into(), + } +} + +fn io_refusal(error: std::io::Error) -> ProtocolError { + refusal("move_failed", error.to_string()) +} + +impl AppState { + /// One step of a move from `peer` to this machine. + pub(super) fn machine_move( + &mut self, + peer: &MachinePeer, + request: MachineRequest, + cx: &mut HostCx, + ) -> HostTask> { + let data_dir = self.store.root().clone(); + if matches!( + request, + MachineRequest::MoveBegin { .. } | MachineRequest::MoveCommit { .. } + ) && let Some(error) = self.move_records_refusal(cx) + { + return cx.spawn_background(async move { Err(error) }); + } + let now = |result| cx.spawn_background(async move { result }); + match request { + MachineRequest::MovePreflight { + project_name, + root, + thread_ids, + } => { + if let Err(error) = self.arriving_threads(&thread_ids) { + return now(Err(error)); + } + if let Some(Err(error)) = root.map(|root| self.arrival_root(&root)) { + return now(Err(error)); + } + let parent = self + .user_directories + .resolve_host_path(Path::new(self.settings.new_project_dir())); + let taken: Vec = self.projects.iter().map(|p| p.root.clone()).collect(); + cx.unblock(move || { + let default_root = match parent { + Ok(parent) => unique_root(&parent, &project_name, &taken), + Err(error) => return Err(io_refusal(error)), + }; + Ok(MachineResponse::MovePreflight { + default_root: default_root.display().to_string(), + }) + }) + } + MachineRequest::MoveBegin { + move_id, + project_name, + root, + git, + thread_ids, + parts, + } => { + if !disk::safe_name(&move_id) { + return now(Err(refusal("invalid_move", "That move id names no file."))); + } + if self.moves.arrived.contains_key(&move_id) { + return now(Ok(MachineResponse::MoveBegun { + received: parts + .iter() + .map(|part| (part.name.clone(), part.size)) + .collect(), + })); + } + if let Err(error) = self + .arriving_threads(&thread_ids) + .and_then(|()| self.arrival_root(&root).map(drop)) + { + return now(Err(error)); + } + let staged = disk::Staged { + project_name, + root, + git, + thread_ids, + parts, + }; + cx.unblock(move || { + disk::stage_begin(&data_dir, &move_id, &staged) + .map(|received| MachineResponse::MoveBegun { received }) + .map_err(io_refusal) + }) + } + MachineRequest::MoveChunk { + move_id, + part, + offset, + bytes, + } => cx.unblock(move || { + disk::stage_chunk(&data_dir, &move_id, &part, offset, &bytes) + .map(|received| MachineResponse::MoveProgress { received }) + .map_err(io_refusal) + }), + MachineRequest::MoveAbort { move_id } => { + if self.moves.committing.contains(&move_id) { + return now(Err(refusal( + "move_busy", + "This move is being committed here.", + ))); + } + if self.moves.arrived.contains_key(&move_id) { + return now(Ok(MachineResponse::Done)); + } + cx.unblock(move || { + disk::discard_staging(&data_dir, &move_id) + .map(|()| MachineResponse::Done) + .map_err(io_refusal) + }) + } + MachineRequest::MoveStatus { move_id } => { + if let Some(project_id) = self.moves.arrived.get(&move_id) { + return now(Ok(MachineResponse::MoveState(MoveState::Committed { + project_id: project_id.clone(), + }))); + } + if self.moves.committing.contains(&move_id) { + return now(Ok(MachineResponse::MoveState(MoveState::Staging))); + } + cx.unblock(move || { + disk::staged(&data_dir, &move_id) + .map(|staged| { + MachineResponse::MoveState(match staged { + Some(_) => MoveState::Staging, + None => MoveState::Unknown, + }) + }) + .map_err(io_refusal) + }) + } + MachineRequest::MoveCommit { move_id } => self.commit_arrival(peer, move_id, cx), + other => now(Err(refusal( + "unexpected_request", + format!("{other:?} is no step of a move"), + ))), + } + } + + /// None of `ids` is a thread here. + fn arriving_threads(&self, ids: &[String]) -> Result<(), ProtocolError> { + if let Some(id) = ids.iter().find(|id| !disk::safe_name(id)) { + return Err(refusal( + "invalid_move", + format!("thread id {id:?} names no file"), + )); + } + match ids.iter().find(|id| self.current_meta(id).is_some()) { + Some(id) => Err(refusal( + "thread_exists", + format!("This machine already has thread {id}."), + )), + None => Ok(()), + } + } + + /// `root` as a project root here: absolute once `~` is this machine's + /// home, absent or an empty directory, and inside no project. + fn arrival_root(&self, root: &str) -> Result { + let invalid = |message: String| refusal("invalid_move_root", message); + let path = self + .user_directories + .resolve_host_path(Path::new(root.trim())) + .map_err(|_| invalid(format!("{root} is not an absolute path on this machine")))?; + if let Some(project) = self + .projects + .iter() + .find(|project| path.starts_with(&project.root)) + { + return Err(invalid(format!( + "{} is inside the project {}", + path.display(), + project.name + ))); + } + match std::fs::read_dir(&path).map(|mut entries| entries.next().is_none()) { + Ok(false) => Err(invalid(format!("{} is not empty", path.display()))), + Ok(true) => Ok(path), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(path), + Err(error) => Err(invalid(format!("{}: {error}", path.display()))), + } + } + + /// Make the project staged by `move_id` and every thread it brings, once. + fn commit_arrival( + &mut self, + peer: &MachinePeer, + move_id: String, + cx: &mut HostCx, + ) -> HostTask> { + let now = |result| cx.spawn_background(async move { result }); + if let Some(project_id) = self.moves.arrived.get(&move_id) { + return now(Ok(MachineResponse::MoveCommitted { + project_id: project_id.clone(), + })); + } + if self.moves.committing.contains(&move_id) { + return now(Err(refusal( + "move_busy", + "This move is being committed here.", + ))); + } + let data_dir = self.store.root().clone(); + let staged = match disk::staged(&data_dir, &move_id) { + Ok(Some(staged)) => staged, + Ok(None) => { + return now(Err(refusal( + "move_not_staged", + "Nothing of this move is staged here.", + ))); + } + Err(error) => return now(Err(io_refusal(error))), + }; + let root = match self + .arriving_threads(&staged.thread_ids) + .and_then(|()| self.arrival_root(&staged.root)) + { + Ok(root) => root, + Err(error) => return now(Err(error)), + }; + if let Err(error) = self.machine_link() { + return now(Err(error)); + } + self.moves.committing.insert(move_id.clone()); + let project = Project { + id: uuid::Uuid::new_v4().to_string(), + name: staged.project_name.clone(), + root: root.clone(), + quick_chat: false, + icon_path: None, + permission_defaults: Default::default(), + created_at: cx.clock().unix_secs(), + }; + let settings = self.settings.clone(); + let store = self.store.clone(); + let peer = peer.clone(); + let now_ms = cx.clock().unix_millis(); + let host = cx.clone(); + cx.spawn_background(async move { + let arrived = { + let (project, move_id) = (project.clone(), move_id.clone()); + host.unblock(move || { + // A thread keeps its profile where this machine has it for + // the same harness, and else takes the harness's own. + let profile = |meta: &SessionMeta| { + meta.profile_id.clone().filter(|id| { + settings + .resolved_profile(id) + .is_some_and(|profile| profile.kind == meta.provider) + }) + }; + disk::arrive( + &store, + &disk::Arrival { + move_id: &move_id, + root: &root, + project, + from_machine_name: &peer.name, + profile: &profile, + now_ms, + }, + ) + }) + .await + }; + host.enqueue_and_wait(move |app, cx| { + app.moves.committing.remove(&move_id); + let arrived = arrived.map_err(|message| refusal("move_failed", message))?; + if let Some(error) = arrived.staging_left { + app.report_error(RuntimeError::MoveLeftBehind { error }, cx); + } + let metas = arrived.threads; + app.moves.arrived.insert(move_id, project.id.clone()); + let project_id = project.id.clone(); + app.projects.push(project); + for meta in &metas { + app.moves.moved_threads.remove(&meta.id); + } + let archived = app.archived_sessions(); + for meta in metas { + let id = meta.id.clone(); + app.upsert_session_in_memory(meta); + app.queue_activity_load(&id, cx); + } + if app.archived_sessions() != archived { + app.archived_revision += 1; + } + Ok(MachineResponse::MoveCommitted { project_id }) + }) + .await + .unwrap_or_else(|()| { + Err(refusal( + "transport_closed", + "Host stopped before the move was committed.", + )) + }) + }) + } +} + +/// `parent/name`, or `parent/name-2` and on when that is taken by a file or +/// a project. +fn unique_root(parent: &Path, name: &str, taken: &[PathBuf]) -> PathBuf { + let name = Path::new(name) + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .filter(|name| !name.is_empty() && name != "..") + .unwrap_or_else(|| "project".into()); + (1..) + .map(|n| match n { + 1 => parent.join(&name), + n => parent.join(format!("{name}-{n}")), + }) + .find(|candidate| { + !taken.iter().any(|root| candidate.starts_with(root)) + && std::fs::read_dir(candidate).map_or_else( + |error| error.kind() == std::io::ErrorKind::NotFound, + |mut entries| entries.next().is_none(), + ) + }) + .expect("an unused name is found") +} diff --git a/crates/runtime/src/app/machines/leads.rs b/crates/runtime/src/app/machines/leads.rs new file mode 100644 index 000000000..95501e54e --- /dev/null +++ b/crates/runtime/src/app/machines/leads.rs @@ -0,0 +1,246 @@ +//! What a thread here owes a thread on another machine of the group: the report and the +//! requests of a subagent that thread started here, and the firings of the watches it put +//! on threads here. +use tcode_core::control::{RemoteChildState, RemoteParent, RemoteWatch}; +use tcode_core::settlement::AgentReport; +use tcode_protocol::MachineRequest; + +use crate::app::*; + +/// What names the sending of report `report` of `child_id`. +pub(super) fn report_key(child_id: &str, report: &str) -> String { + format!("report:{child_id}:{report}") +} + +/// The other machine no longer takes it: its thread is gone, archived, or no longer waits +/// on this one. +fn not_taken(error: &ProtocolError) -> bool { + error.code == "out_of_scope" +} + +impl AppState { + /// Send the report `child_id` keeps for its lead on another machine, which keeps it + /// until that lead's harness has taken it. + pub(in crate::app) fn send_report_to_lead(&mut self, child_id: &str, cx: &mut HostCx) { + let Some(meta) = self.find_meta(child_id) else { + return; + }; + let Some(parent) = meta.remote_parent.clone() else { + return; + }; + let Some(expectation) = meta.expectation.as_ref() else { + return; + }; + let (Some(text), Some(report)) = ( + expectation.undelivered.clone(), + expectation.undelivered_id.clone(), + ) else { + return; + }; + let state = match expectation.state { + AgentReport::Failed => RemoteChildState::Failed, + _ => RemoteChildState::Reported, + }; + let key = report_key(child_id, &report); + let request = MachineRequest::Callback { + thread_id: parent.thread_id, + from_thread_id: child_id.to_owned(), + from_title: meta.title, + text, + report: Some(report.clone()), + state: Some(state), + watch: None, + }; + let child_id = child_id.to_owned(); + self.machine_work + .reports_sent + .insert(child_id.clone(), report.clone()); + self.call_machine( + &parent.machine, + Some(key.clone()), + request, + false, + cx, + move |state, answer, cx| match answer { + Ok(_) => { + state.machine_work.queued_there.insert(key); + } + Err(error) if not_taken(&error) => { + state.change_meta(&child_id, cx, |meta| { + if let Some(expectation) = meta.expectation.as_mut().filter(|expectation| { + expectation.undelivered_id.as_deref() == Some(report.as_str()) + }) { + expectation.undelivered = None; + expectation.undelivered_id = None; + } + }); + } + // Kept, and sent again on the next contact with that machine. + Err(_) => {} + }, + ); + } + + /// The reports this machine's threads keep for leads on `machine`, or on every machine, + /// that the lead's machine has not queued yet. + pub(super) fn send_reports_to_leads(&mut self, machine: Option<&str>, cx: &mut HostCx) { + let due: Vec = self + .sessions + .iter() + .filter(|meta| { + meta.remote_parent + .as_ref() + .is_some_and(|parent| machine.is_none_or(|machine| parent.machine == machine)) + }) + .filter(|meta| { + meta.expectation.as_ref().is_some_and(|expectation| { + expectation.undelivered.is_some() + && expectation.undelivered_id.as_ref().is_some_and(|report| { + !self + .machine_work + .queued_there + .contains(&report_key(&meta.id, report)) + }) + }) + }) + .map(|meta| meta.id.clone()) + .collect(); + for child in due { + self.send_report_to_lead(&child, cx); + } + } + + /// A subagent's approval request or question for its lead on another machine, sent + /// once: it lives no longer than the subagent's provider. + pub(in crate::app) fn send_callback_to_lead( + &mut self, + child: &SessionMeta, + parent: &RemoteParent, + text: String, + cx: &mut HostCx, + ) { + let request = MachineRequest::Callback { + thread_id: parent.thread_id.clone(), + from_thread_id: child.id.clone(), + from_title: child.title.clone(), + text, + report: None, + state: None, + watch: None, + }; + self.call_machine(&parent.machine, None, request, false, cx, |_, _, _| {}); + } + + /// Threads `ids` here are archived or deleted: the leads elsewhere of those that still + /// owed a report hear they will get none, once, and no longer wait on them. + pub(in crate::app) fn remote_children_gone<'a>( + &mut self, + ids: impl IntoIterator, + cx: &mut HostCx, + ) { + let gone: Vec<(SessionMeta, RemoteParent)> = ids + .into_iter() + .filter_map(|id| self.find_meta(id)) + .filter(|meta| { + meta.cancelled_at.is_none() + && meta + .expectation + .as_ref() + .is_some_and(|expectation| expectation.state.pending()) + }) + .filter_map(|meta| { + let parent = meta.remote_parent.clone()?; + Some((meta, parent)) + }) + .collect(); + for (child, parent) in gone { + let request = MachineRequest::Callback { + thread_id: parent.thread_id.clone(), + from_thread_id: child.id.clone(), + from_title: child.title.clone(), + text: String::new(), + report: None, + state: Some(RemoteChildState::Cancelled), + watch: None, + }; + self.call_machine(&parent.machine, None, request, false, cx, |_, _, _| {}); + } + } + + /// Send the watch firings `thread` keeps for threads on other machines. + pub(in crate::app) fn send_watch_firings(&mut self, thread: Option<&str>, cx: &mut HostCx) { + self.send_watch_firings_where(thread, None, cx); + } + + /// Send the watch firings kept for threads on `machine`, or on every machine. + pub(super) fn send_watch_firings_to(&mut self, machine: Option<&str>, cx: &mut HostCx) { + self.send_watch_firings_where(None, machine, cx); + } + + fn send_watch_firings_where( + &mut self, + thread: Option<&str>, + machine: Option<&str>, + cx: &mut HostCx, + ) { + let due: Vec<(String, String, RemoteWatch, String)> = self + .sessions + .iter() + .filter(|meta| thread.is_none_or(|thread| meta.id == thread)) + .flat_map(|meta| { + meta.remote_watches + .iter() + .filter(|watch| { + watch.fired.is_some() + && machine.is_none_or(|machine| watch.machine == machine) + }) + .map(|watch| { + ( + meta.id.clone(), + meta.title.clone(), + watch.clone(), + watch.fired.clone().unwrap_or_default(), + ) + }) + }) + .collect(); + for (target, title, watch, text) in due { + let key = format!( + "watch:{target}:{}:{}:{}", + watch.machine, watch.thread_id, watch.id + ); + let request = MachineRequest::Callback { + thread_id: watch.thread_id.clone(), + from_thread_id: target.clone(), + from_title: title, + text, + report: None, + state: None, + watch: Some(watch.id.clone()), + }; + self.call_machine( + &watch.machine.clone(), + Some(key), + request, + false, + cx, + move |state, answer, cx| { + let delivered = match &answer { + Ok(_) => true, + Err(error) => not_taken(error), + }; + if delivered { + state.change_meta(&target, cx, |meta| { + meta.remote_watches.retain(|kept| { + !(kept.id == watch.id + && kept.machine == watch.machine + && kept.thread_id == watch.thread_id + && kept.fired.is_some()) + }); + }); + } + }, + ); + } + } +} diff --git a/crates/runtime/src/app/machines/mod.rs b/crates/runtime/src/app/machines/mod.rs new file mode 100644 index 000000000..a5d679000 --- /dev/null +++ b/crates/runtime/src/app/machines/mod.rs @@ -0,0 +1,371 @@ +//! What this machine answers the other machines of its group, and its way to +//! them. Requests arrive as [`tcode_protocol::Query::Machine`] from a +//! [`tcode_protocol::Principal::Machine`], after the transport has checked +//! the machine is a member and that this machine's switches take the kind of +//! request; requests go out through the [`MachineLink`] the composition root +//! gave the host. +mod arrivals; +mod leads; +#[cfg(test)] +mod move_tests; +pub(crate) mod moves; +#[cfg(test)] +mod real_group; +mod remote; +#[cfg(test)] +mod tests; +mod threads; + +use tcode_client::machines::{MachineLink, NO_GROUP, NOT_MEMBER}; +use tcode_core::control::{RemoteChild, RemoteChildState}; +use tcode_protocol::{MachineRequest, MachineResponse}; + +use super::*; + +/// The machine of the group a request came from, as the transport admitted it. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct MachinePeer { + pub id: String, + pub name: String, +} + +/// How often this machine sends again what the other machines of its group have not taken. +/// A machine may be asleep or away for days, and nothing else would tell this one it is +/// back when neither side has anything new for the other; a machine that comes back sooner +/// hears it on the first exchange with this one, in either direction. +const SEND_AGAIN_EVERY: Duration = Duration::from_secs(10 * 60); + +/// What this machine still sends the other machines of its group, beyond what thread +/// metadata keeps of it. +#[derive(Default)] +pub(crate) struct MachineWork { + /// What is being sent now, by what it is, so a second reason to send it does not send + /// it twice; with whether such a reason came meanwhile, which looks again once the + /// first send is answered: the machine may have come back while that send was failing. + in_flight: HashMap, + /// The reports of this machine's children that their lead's machine has queued since + /// this host started. They wait there for the lead's harness to take them, so only the + /// slow check sends them again, in case that machine stopped before its lead took them. + queued_there: HashSet, + /// The report of each child here this host last sent its lead on another machine. + reports_sent: HashMap, + check: Option>, + watching: bool, +} + +/// The subagents `lead` started on other machines that still run. +pub(crate) fn running_remote_children(lead: &SessionMeta) -> impl Iterator { + lead.remote_children + .iter() + .filter(|child| child.subagent && child.state == RemoteChildState::Running) +} + +impl AppState { + pub(crate) fn attach_machine_link(&mut self, link: Option) { + self.machine_link = link; + } + + /// This machine's way to the other machines of its group; [`NO_GROUP`] + /// where the composition gave the host none. + pub(crate) fn machine_link(&self) -> Result<&MachineLink, ProtocolError> { + self.machine_link.as_ref().ok_or_else(|| ProtocolError { + code: NO_GROUP.into(), + message: "this machine has no way to the machines of a group".into(), + }) + } + + pub(crate) fn handle_machine_request( + &mut self, + peer: &MachinePeer, + request: MachineRequest, + cx: &mut HostCx, + ) -> HostTask> { + // A machine pings this one as it starts and on its slow check: what it had queued of + // this machine's reports may have gone with a restart, so they go again. + if matches!(request, MachineRequest::Ping) { + self.forget_reports_queued_on(&peer.id); + } + self.send_machine_work(Some(&peer.id), false, cx); + match request { + MachineRequest::Ping => cx.spawn_background(async { Ok(MachineResponse::Pong) }), + MachineRequest::Control { caller, tool, args } => { + self.machine_control(peer, caller, tool, args, cx) + } + request @ (MachineRequest::Callback { .. } | MachineRequest::ReportTaken { .. }) => { + self.machine_reply(peer, request, cx) + } + request @ (MachineRequest::MovePreflight { .. } + | MachineRequest::MoveBegin { .. } + | MachineRequest::MoveChunk { .. } + | MachineRequest::MoveCommit { .. } + | MachineRequest::MoveAbort { .. } + | MachineRequest::MoveStatus { .. }) => self.machine_move(peer, request, cx), + } + } + + /// Send `request` to `machine` and hand its answer to `done` on the host thread. `key` + /// names what is sent, so it is not sent twice at once. An answer from a machine that + /// counts as contact with it (`contact`) sends what waits for that machine; what that + /// sending sends does not count, so nothing goes back and forth on its own. + pub(crate) fn call_machine( + &mut self, + machine: &str, + key: Option, + request: MachineRequest, + contact: bool, + cx: &mut HostCx, + done: impl FnOnce(&mut AppState, Result, &mut HostCx) + + Send + + 'static, + ) { + let link = match self.machine_link() { + Ok(link) => link.clone(), + Err(error) => return done(self, Err(error), cx), + }; + if let Some(key) = &key { + if let Some(again) = self.machine_work.in_flight.get_mut(key) { + *again = true; + return; + } + self.machine_work.in_flight.insert(key.clone(), false); + } + let host_cx = cx.clone(); + let machine = machine.to_owned(); + HostCx::spawn_detached(cx, async move { + let answer = link.call(&machine, request).await; + host_cx.enqueue(move |state, cx| { + let again = key + .and_then(|key| state.machine_work.in_flight.remove(&key)) + .unwrap_or(false); + let reached = answer.is_ok(); + let left = answer.as_ref().is_err_and(|error| error.code == NOT_MEMBER); + done(state, answer, cx); + state.machine_answered(&machine, reached, left, contact, cx); + if again && !left { + state.send_machine_work(Some(&machine), false, cx); + } + }); + }); + } + + /// What follows any answer from `machine`, or its refusal to answer. + pub(crate) fn machine_answered( + &mut self, + machine: &str, + reached: bool, + left: bool, + contact: bool, + cx: &mut HostCx, + ) { + if left { + self.machine_left(machine, cx); + } else if reached && contact { + self.send_machine_work(Some(machine), false, cx); + } + } + + /// From now on, send what this machine owes its group each time the transport starts + /// serving the link, which a host's start is followed by, and on the slow check. + pub(crate) fn start_machine_work(&mut self, cx: &mut HostCx) { + let Ok(link) = self.machine_link().cloned() else { + return; + }; + if std::mem::replace(&mut self.machine_work.watching, true) { + return; + } + let serves = link.serves(); + let host_cx = cx.clone(); + HostCx::spawn_detached(cx, async move { + while serves.recv().await.is_ok() { + host_cx.enqueue(|state, cx| state.send_machine_work(None, true, cx)); + } + }); + self.arm_machine_check(cx); + } + + fn arm_machine_check(&mut self, cx: &mut HostCx) { + let due = cx.clock().timer(SEND_AGAIN_EVERY); + let host_cx = cx.clone(); + self.machine_work.check = Some(cx.spawn_background(async move { + due.await; + host_cx.enqueue(|state, cx| { + state.check_group_membership(cx); + state.send_machine_work(None, true, cx); + state.arm_machine_check(cx); + }); + })); + } + + /// Send what waits for `machine`, or for every machine. `again` also sends the reports + /// the lead's machine has already queued, and asks each machine whose threads work with + /// threads here whether it has anything for this one: its sending what it holds follows + /// any request from here. + pub(crate) fn send_machine_work( + &mut self, + machine: Option<&str>, + again: bool, + cx: &mut HostCx, + ) { + if self.machine_link().is_err() { + return; + } + if again { + self.machine_work.queued_there.clear(); + self.ping_working_machines(machine, cx); + } + self.send_remote_child_work(machine, cx); + self.send_reports_to_leads(machine, cx); + self.send_watch_firings_to(machine, cx); + } + + /// The machines that run a subagent of a thread here, and those whose threads started + /// one here, hear from this one. + fn ping_working_machines(&mut self, only: Option<&str>, cx: &mut HostCx) { + let machines: BTreeSet = self + .sessions + .iter() + .filter(|meta| meta.archived_at.is_none()) + .flat_map(|meta| { + meta.remote_children + .iter() + .filter(|child| { + child.subagent + && !matches!( + child.state, + RemoteChildState::Cancelled + | RemoteChildState::Settled + | RemoteChildState::MachineLeft + ) + }) + .map(|child| child.machine.clone()) + .chain( + meta.remote_parent + .iter() + .map(|parent| parent.machine.clone()), + ) + }) + .filter(|machine| only.is_none_or(|only| only == machine)) + .collect(); + for machine in machines { + self.call_machine( + &machine.clone(), + Some(format!("ping:{machine}")), + MachineRequest::Ping, + false, + cx, + |_, _, _| {}, + ); + } + } + + fn forget_reports_queued_on(&mut self, machine: &str) { + let children: Vec = self + .sessions + .iter() + .filter(|meta| { + meta.remote_parent + .as_ref() + .is_some_and(|parent| parent.machine == machine) + }) + .map(|meta| format!("report:{}:", meta.id)) + .collect(); + self.machine_work + .queued_there + .retain(|key| !children.iter().any(|child| key.starts_with(child))); + } + + /// Whether the machines this one's threads deal with are still in its group. + fn check_group_membership(&mut self, cx: &mut HostCx) { + let Ok(link) = self.machine_link() else { + return; + }; + let machines = link.machines(false); + let host_cx = cx.clone(); + HostCx::spawn_detached(cx, async move { + let Ok(machines) = machines.await else { + return; + }; + let members: HashSet = machines.into_iter().map(|info| info.id).collect(); + host_cx.enqueue(move |state, cx| { + let known: BTreeSet = state + .sessions + .iter() + .flat_map(|meta| { + meta.remote_children + .iter() + .map(|child| child.machine.clone()) + .chain( + meta.remote_parent + .iter() + .map(|parent| parent.machine.clone()), + ) + }) + .collect(); + for machine in known.difference(&members.into_iter().collect()) { + state.machine_left(machine, cx); + } + }); + }); + } + + /// `machine` is no longer in this machine's group: its subagents of threads here are + /// gone from their leads' reach, and threads here it started carry on as ordinary + /// threads. + fn machine_left(&mut self, machine: &str, cx: &mut HostCx) { + let now = cx.clock().unix_secs(); + let leads: Vec = self + .sessions + .iter() + .filter(|meta| { + meta.remote_children.iter().any(|child| { + child.machine == machine && child.state != RemoteChildState::MachineLeft + }) + }) + .map(|meta| meta.id.clone()) + .collect(); + for lead in leads { + self.change_meta(&lead, cx, |meta| { + for child in &mut meta.remote_children { + if child.machine == machine { + child.state = RemoteChildState::MachineLeft; + child.pending = None; + child.report_taken_unsent = false; + child.updated_at = now; + } + } + }); + } + let children: Vec = self + .sessions + .iter() + .filter(|meta| { + meta.remote_parent + .as_ref() + .is_some_and(|parent| parent.machine == machine) + }) + .map(|meta| meta.id.clone()) + .collect(); + for child in children { + self.change_meta(&child, cx, |meta| { + meta.remote_parent = None; + meta.expectation = None; + }); + } + let watched: Vec = self + .sessions + .iter() + .filter(|meta| { + meta.remote_watches + .iter() + .any(|watch| watch.machine == machine) + }) + .map(|meta| meta.id.clone()) + .collect(); + for thread in watched { + self.change_meta(&thread, cx, |meta| { + meta.remote_watches.retain(|watch| watch.machine != machine); + }); + } + self.refresh_control_access(); + } +} diff --git a/crates/runtime/src/app/machines/move_tests.rs b/crates/runtime/src/app/machines/move_tests.rs new file mode 100644 index 000000000..fea01adb7 --- /dev/null +++ b/crates/runtime/src/app/machines/move_tests.rs @@ -0,0 +1,579 @@ +//! Projects moving between two machines of a group over real loopback +//! endpoints, each machine a real host on a store of its own as the binaries +//! compose it, driven by a client of each. +use std::path::{Path, PathBuf}; + +use agent::{AgentEvent, ProviderKind, TurnStatus}; +use tcode_core::project::{Project, SessionMeta, WorktreeInfo}; +use tcode_protocol::{ + Command, CommandResponse, EndedProjectMove, GroupAction, MachineRequest, MachineResponse, + MoveBlocker, MoveOutcome, MovePart, MovePause, MovePhase, ProjectMoveStatus, ProjectMovesState, + ProtocolError, Query, QueryResponse, ServerEvent, Subscription, Topic, +}; +use tcode_services::store::SessionStore; + +use super::real_group::{Machine, TestDir}; + +impl Machine { + /// The next list of moving projects this machine publishes that `wanted` + /// takes. + fn moves_until(&self, wanted: impl Fn(&[ProjectMoveStatus]) -> bool) -> Vec { + loop { + let envelope = self + .events + .recv_blocking() + .expect("the host stopped before the move did"); + if let ServerEvent::ProjectMovesReplaced(state) = envelope.event + && wanted(&state.moving) + { + return state.moving; + } + } + } + + /// What a client that attaches now, and so saw none of the moves, is told + /// first when it subscribes to them. + fn moves_told_to_a_late_client(&self) -> ProjectMovesState { + let connection = self.mux.attach( + tcode_protocol::Principal::Full, + tcode_client::attachment::AttachmentPolicy::LOCAL, + ); + let client = tcode_client::HostLink::new(connection.to_host, connection.from_host); + let pump = client.clone(); + smol::spawn(async move { pump.pump().await }).detach(); + let events = client.events(); + client + .subscribe(Subscription { + known_index: None, + topic: Topic::ProjectMoves, + after: None, + }) + .unwrap(); + let state = loop { + let envelope = events + .recv_blocking() + .expect("the host stopped before it told the moves"); + if let ServerEvent::ProjectMovesReplaced(state) = envelope.event { + break state; + } + }; + client.close(); + state + } + + /// The projects and threads this machine lists, archived ones included. + fn listed(&self) -> (Vec, Vec) { + self.subscribe(Topic::Index); + let index = loop { + let envelope = self.events.recv_blocking().unwrap(); + if let ServerEvent::IndexSnapshot(index) = envelope.event { + break index; + } + }; + self.client + .unsubscribe(Subscription { + known_index: None, + topic: Topic::Index, + after: None, + }) + .unwrap(); + let Ok(QueryResponse::ArchivedSessions(archived)) = self.query(Query::ArchivedSessions) + else { + panic!("no archived threads"); + }; + let mut sessions = index.sessions; + sessions.extend(archived.sessions); + (index.projects, sessions) + } +} + +fn git(dir: &Path, args: &[&str]) -> String { + let output = tcode_services::process::command("git") + .args(args) + .current_dir(dir) + .env("GIT_OPTIONAL_LOCKS", "0") + .env("GIT_AUTHOR_NAME", "tcode") + .env("GIT_AUTHOR_EMAIL", "tcode@localhost") + .env("GIT_COMMITTER_NAME", "tcode") + .env("GIT_COMMITTER_EMAIL", "tcode@localhost") + .output() + .unwrap(); + assert!( + output.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8_lossy(&output.stdout).into_owned() +} + +/// A project of the desk's: a repository with a change in it, a thread on +/// its root, one in a Tcode worktree and one archived, each with a turn. +struct Seeded { + project: Project, + threads: Vec, + worktree: PathBuf, +} + +/// Seed the desk's store before its host starts, with `bulk` bytes of +/// incompressible data committed. +fn seed(dir: &Path, bulk: usize) -> Seeded { + let root = dir.join("code").join("app"); + std::fs::create_dir_all(&root).unwrap(); + git( + &root, + &["-c", "init.templateDir=", "init", "--quiet", "-b", "main"], + ); + git(&root, &["config", "commit.gpgSign", "false"]); + std::fs::write(root.join("readme.md"), "app\n").unwrap(); + let mut state = 0x2545_f491_4f6c_dd1d_u64; + let bytes: Vec = (0..bulk) + .map(|_| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state as u8 + }) + .collect(); + std::fs::write(root.join("bulk.bin"), bytes).unwrap(); + git(&root, &["add", "."]); + git(&root, &["commit", "--quiet", "-m", "initial"]); + std::fs::write(root.join("readme.md"), "app, changed\n").unwrap(); + let data = dir.join("store"); + let worktree = tcode_services::worktree::provision(&root, "feature", None, &data).unwrap(); + let project = Project { + id: "desk-project".into(), + name: "app".into(), + root: root.clone(), + quick_chat: false, + icon_path: None, + permission_defaults: Default::default(), + created_at: 1, + }; + let mut on_root = SessionMeta::new(ProviderKind::Codex, root.clone(), None); + on_root.title = "On the root".into(); + let mut in_worktree = SessionMeta::new(ProviderKind::Codex, worktree.path.clone(), None); + in_worktree.title = "In a worktree".into(); + in_worktree.worktree = Some(WorktreeInfo { + root_project_path: root.clone(), + base: worktree.base.clone(), + branch: worktree.branch.clone(), + }); + let mut archived = SessionMeta::new(ProviderKind::ClaudeCode, root.clone(), None); + archived.title = "Archived".into(); + archived.archived_at = Some(2); + let mut threads = vec![on_root, in_worktree, archived]; + let attachments = tcode_services::user_files::attachment_dir(&data, &threads[0].id); + std::fs::create_dir_all(&attachments).unwrap(); + std::fs::write(attachments.join("note.txt"), "an attachment\n").unwrap(); + let store = SessionStore::open_at(data).unwrap(); + store.upsert_project(&project).unwrap(); + for meta in &mut threads { + meta.project_id = Some(project.id.clone()); + store.upsert_meta(meta).unwrap(); + for event in [ + AgentEvent::TurnStarted { + turn_id: "turn-1".into(), + }, + AgentEvent::TurnCompleted { + turn_id: "turn-1".into(), + status: TurnStatus::Completed, + usage: None, + }, + ] { + store.append_event(&meta.id, 1, &event).unwrap(); + } + } + store.close().unwrap(); + Seeded { + project, + threads, + worktree: worktree.path, + } +} + +/// The desk with `seeded`'s project and a laptop that takes projects, in one +/// group. +fn desk_and_laptop(desk_dir: &TestDir, laptop_dir: &TestDir) -> (Machine, Machine) { + let desk = Machine::start(&desk_dir.0, "Desk"); + let laptop = Machine::start(&laptop_dir.0, "Laptop"); + desk.group(GroupAction::Create { + name: "Home".into(), + }); + laptop.group(GroupAction::Join { + link: desk.endpoint.as_ref().unwrap().new_invitation().url(), + address: Some("127.0.0.1".into()), + }); + laptop.group(GroupAction::SetAcceptProjects(true)); + desk.subscribe(Topic::ProjectMoves); + desk.moves_until(|moves| moves.is_empty()); + (desk, laptop) +} + +fn move_to( + desk: &Machine, + laptop: &Machine, + root: &Path, +) -> Result { + desk.command(Command::MoveProject { + project_id: "desk-project".into(), + machine: laptop.id(), + root: root.display().to_string(), + include_ignored: false, + }) +} + +fn code(result: Result) -> String { + result.expect_err("the command was accepted").code +} + +fn rename(id: &str) -> Command { + Command::RenameSession { + session_id: id.into(), + title: "Renamed".into(), + } +} + +/// The project moves with every thread: the laptop lists it at the root it +/// was given with each thread, its history and a `thread_moved` entry, the +/// worktree thread in a worktree of the laptop's own; the desk lists neither, +/// says where each thread went, and keeps neither the move's parts nor its +/// refs. +#[test] +fn a_project_moves_with_its_threads_and_the_desk_says_where_they_went() { + let (desk_dir, laptop_dir) = (TestDir::new("desk"), TestDir::new("laptop")); + let seeded = seed(&desk_dir.0, 1024); + let (desk, laptop) = desk_and_laptop(&desk_dir, &laptop_dir); + let history: Vec<_> = seeded + .threads + .iter() + .map(|meta| desk.store.read_events(&meta.id).unwrap()) + .collect(); + let root = laptop_dir.0.join("code").join("app"); + + move_to(&desk, &laptop, &root).unwrap(); + let begun = desk.moves_until(|moves| !moves.is_empty()); + desk.moves_until(|moves| moves.is_empty()); + assert!( + !desk_dir + .0 + .join("store") + .join("moves") + .join("out") + .join(&begun[0].move_id) + .exists(), + "the desk keeps the move's parts" + ); + assert_eq!( + git(&seeded.project.root, &["for-each-ref", "refs/tcode/move"]), + "" + ); + + let (projects, threads) = laptop.listed(); + let [project] = projects.as_slice() else { + panic!("the laptop lists {projects:?}"); + }; + assert_eq!((project.name.as_str(), &project.root), ("app", &root)); + for (meta, before) in seeded.threads.iter().zip(&history) { + let arrived = threads + .iter() + .find(|arrived| arrived.id == meta.id) + .unwrap_or_else(|| panic!("{} did not arrive", meta.title)); + assert_eq!(arrived.project_id.as_deref(), Some(project.id.as_str())); + assert_eq!(arrived.archived_at, meta.archived_at); + let events = laptop.store.read_events(&meta.id).unwrap(); + let (moved, kept) = events.split_last().unwrap(); + assert_eq!( + kept.iter().map(|record| &record.event).collect::>(), + before + .iter() + .map(|record| &record.event) + .collect::>() + ); + assert_eq!( + moved.event, + AgentEvent::ThreadMoved { + from_machine_name: "Desk".into(), + } + ); + } + let in_worktree = threads + .iter() + .find(|meta| meta.id == seeded.threads[1].id) + .unwrap(); + assert!( + in_worktree + .cwd + .starts_with(laptop_dir.0.join("store").join("worktrees")) + ); + assert_eq!( + std::fs::read_to_string( + tcode_services::user_files::attachment_dir( + &laptop_dir.0.join("store"), + &seeded.threads[0].id + ) + .join("note.txt") + ) + .unwrap(), + "an attachment\n" + ); + + let (projects, threads) = desk.listed(); + assert!(projects.is_empty(), "{projects:?}"); + assert!(threads.is_empty(), "{threads:?}"); + assert!( + seeded.project.root.join("bulk.bin").exists(), + "the desk keeps the directory" + ); + let told = desk.moves_told_to_a_late_client(); + assert_eq!(told.moving, []); + let mut thread_ids: Vec<_> = seeded.threads.iter().map(|meta| meta.id.clone()).collect(); + thread_ids.sort(); + let [mut ended] = told.ended.try_into().expect("one move ended"); + ended.thread_ids.sort(); + assert_eq!( + ended, + EndedProjectMove { + move_id: begun[0].move_id.clone(), + project_id: seeded.project.id.clone(), + project_name: "app".into(), + machine: laptop.id(), + thread_ids, + outcome: MoveOutcome::Moved, + } + ); + let first = seeded.threads[0].id.clone(); + assert_eq!( + desk.query(Query::MovedThread { + thread_id: first.clone() + }), + Ok(QueryResponse::MovedThread(Some(laptop.id()))) + ); + assert_eq!( + code(desk.command(rename(&first))), + super::moves::THREAD_MOVED + ); +} + +/// The laptop's folder for the first thread's attachments, which a move +/// cannot put the desk's into while it is there: the laptop takes every part +/// and then refuses the commit, which leaves the move paused with all of it +/// staged. +fn laptop_refuses_the_commit(laptop_dir: &TestDir, seeded: &Seeded) -> PathBuf { + let taken = tcode_services::user_files::attachment_dir( + &laptop_dir.0.join("store"), + &seeded.threads[0].id, + ); + std::fs::create_dir_all(&taken).unwrap(); + taken +} + +/// The next list in which a move is paused for the laptop's refusal. +fn refused(desk: &Machine) -> ProjectMoveStatus { + desk.moves_until(|moves| { + moves + .iter() + .any(|status| matches!(status.paused, Some(MovePause::Failed { .. }))) + }) + .remove(0) +} + +/// A move the laptop refused at the end and then cancelled leaves the desk's +/// project, threads, repository and worktree as they were and the laptop with +/// nothing staged; while it waited the project's threads took no command, and +/// after it they do. +#[test] +fn a_cancelled_move_leaves_both_machines_as_they_were() { + let (desk_dir, laptop_dir) = (TestDir::new("desk"), TestDir::new("laptop")); + let seeded = seed(&desk_dir.0, 1024); + let (desk, laptop) = desk_and_laptop(&desk_dir, &laptop_dir); + laptop_refuses_the_commit(&laptop_dir, &seeded); + let root = &seeded.project.root; + let status = git(root, &["status", "--porcelain=v2", "--branch"]); + let refs = git(root, &["for-each-ref"]); + let listed = desk.listed(); + + move_to(&desk, &laptop, &laptop_dir.0.join("app")).unwrap(); + let waiting = refused(&desk); + let staged = laptop_dir + .0 + .join("store") + .join("moves") + .join("in") + .join(&waiting.move_id); + assert!(staged.exists(), "the laptop holds nothing of the move"); + let first = seeded.threads[0].id.clone(); + assert_eq!( + code(desk.command(rename(&first))), + super::moves::PROJECT_MOVING + ); + desk.command(Command::CancelProjectMove { + project_id: seeded.project.id.clone(), + force: false, + }) + .unwrap(); + + assert_eq!(desk.listed(), listed); + assert_eq!(git(root, &["status", "--porcelain=v2", "--branch"]), status); + assert_eq!(git(root, &["for-each-ref"]), refs); + assert!(seeded.worktree.join(".git").exists()); + assert!( + !desk_dir + .0 + .join("store") + .join("moves") + .join("out") + .join(&waiting.move_id) + .exists() + ); + assert!(!staged.exists(), "the laptop keeps what it staged"); + assert!(laptop.listed().0.is_empty()); + desk.command(rename(&first)).unwrap(); + let told = desk.moves_told_to_a_late_client(); + assert_eq!(told.moving, []); + let [ended] = told.ended.try_into().expect("one move ended"); + assert_eq!( + (ended.move_id, ended.project_id, ended.outcome), + ( + waiting.move_id.clone(), + seeded.project.id.clone(), + MoveOutcome::Cancelled { forced: false } + ) + ); +} + +/// A move tried again goes on from the bytes the laptop holds, not from the +/// start: the laptop here holds half of the code, as an interrupted send +/// leaves it, and the project arrives whole. +#[test] +fn a_move_tried_again_resumes_where_the_laptop_is() { + let (desk_dir, laptop_dir) = (TestDir::new("desk"), TestDir::new("laptop")); + let seeded = seed(&desk_dir.0, 1024); + let (desk, laptop) = desk_and_laptop(&desk_dir, &laptop_dir); + let taken = laptop_refuses_the_commit(&laptop_dir, &seeded); + let root = laptop_dir.0.join("app"); + + move_to(&desk, &laptop, &root).unwrap(); + let waiting = refused(&desk); + assert_eq!(waiting.done, waiting.total, "{waiting:?}"); + let code = laptop_dir + .0 + .join("store") + .join("moves") + .join("in") + .join(&waiting.move_id) + .join("code.bundle"); + let length = std::fs::metadata(&code).unwrap().len(); + std::fs::OpenOptions::new() + .write(true) + .open(&code) + .unwrap() + .set_len(length / 2) + .unwrap(); + std::fs::remove_dir_all(taken).unwrap(); + + desk.command(Command::ResumeProjectMove { + project_id: seeded.project.id.clone(), + }) + .unwrap(); + let resumed = desk.moves_until(|moves| { + moves + .iter() + .any(|status| status.phase == MovePhase::SendingCode) + }); + assert_eq!(resumed[0].paused, None); + assert_eq!( + resumed[0].done, + waiting.total - (length - length / 2), + "{resumed:?}" + ); + desk.moves_until(|moves| moves.is_empty()); + let (projects, threads) = laptop.listed(); + assert_eq!(projects.len(), 1); + assert_eq!(threads.len(), seeded.threads.len()); + assert_eq!( + std::fs::read(root.join("bulk.bin")).unwrap(), + std::fs::read(seeded.project.root.join("bulk.bin")).unwrap() + ); +} + +/// A commit asked again after the project arrived answers the same project +/// and makes no second one; a move bringing a thread the laptop already has +/// is refused before anything is staged. +#[test] +fn a_repeated_commit_makes_nothing_twice_and_a_known_thread_is_refused() { + let (desk_dir, laptop_dir) = (TestDir::new("desk"), TestDir::new("laptop")); + let seeded = seed(&desk_dir.0, 1024); + let (desk, laptop) = desk_and_laptop(&desk_dir, &laptop_dir); + move_to(&desk, &laptop, &laptop_dir.0.join("app")).unwrap(); + let begun = desk.moves_until(|moves| !moves.is_empty()); + desk.moves_until(|moves| moves.is_empty()); + let (projects, threads) = laptop.listed(); + + let again = smol::block_on(desk.link.call( + &laptop.id(), + MachineRequest::MoveCommit { + move_id: begun[0].move_id.clone(), + }, + )); + assert_eq!( + again, + Ok(MachineResponse::MoveCommitted { + project_id: projects[0].id.clone() + }) + ); + assert_eq!(laptop.listed(), (projects, threads)); + + let known = smol::block_on(desk.link.call( + &laptop.id(), + MachineRequest::MoveBegin { + move_id: "another".into(), + project_name: "app".into(), + root: laptop_dir.0.join("elsewhere").display().to_string(), + git: true, + thread_ids: vec![seeded.threads[0].id.clone()], + parts: vec![MovePart { + name: "manifest.json".into(), + size: 1, + sha256: String::new(), + }], + }, + )); + assert_eq!( + known.map_err(|error| error.code), + Err("thread_exists".into()) + ); + assert!( + !laptop_dir + .0 + .join("store") + .join("moves") + .join("in") + .join("another") + .exists() + ); +} + +/// A thread whose worktree is gone would have nowhere to continue on the +/// laptop: the move is refused naming the thread and the path before the +/// laptop is asked for anything, and the project stays unfrozen. +#[test] +fn a_thread_whose_worktree_is_gone_blocks_the_move_before_anything_is_sent() { + let (desk_dir, laptop_dir) = (TestDir::new("desk"), TestDir::new("laptop")); + let seeded = seed(&desk_dir.0, 1024); + let (desk, laptop) = desk_and_laptop(&desk_dir, &laptop_dir); + std::fs::remove_dir_all(&seeded.worktree).unwrap(); + + let refused = move_to(&desk, &laptop, &laptop_dir.0.join("app")).expect_err("the move began"); + + assert_eq!(refused.code, "move_blocked"); + assert_eq!( + refused.message, + serde_json::to_string(&[MoveBlocker::MissingCheckout { + thread: "In a worktree".into(), + path: seeded.worktree.display().to_string(), + }]) + .unwrap() + ); + assert!(!laptop_dir.0.join("store").join("moves").exists()); + desk.command(rename(&seeded.threads[0].id)).unwrap(); +} diff --git a/crates/runtime/src/app/machines/moves.rs b/crates/runtime/src/app/machines/moves.rs new file mode 100644 index 000000000..33e0abbdc --- /dev/null +++ b/crates/runtime/src/app/machines/moves.rs @@ -0,0 +1,1453 @@ +//! A project and its threads moving from this machine to another of the +//! group: the commands, the preview, the `ProjectMoves` topic, and the +//! driver that sends the parts and commits them. +//! +//! While a move runs this machine deletes nothing: the project is frozen +//! ([`AppState::move_refusal`]), every part is staged on the other machine, +//! and only once it has answered `MoveCommitted` are the threads and the +//! project removed here, each thread leaving a redirect to the machine it went +//! to. Every move is journalled before anything else happens, so a restart +//! resumes it from where its journal says it was. +use std::collections::{BTreeMap, HashMap, HashSet}; +use std::path::PathBuf; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use tcode_client::machines::{ + MACHINE_REFUSES, MACHINE_UNREACHABLE, MachineLink, NO_GROUP, NOT_MEMBER, PROTOCOL_MISMATCH, +}; +use tcode_core::ui::ConversationDestination; +use tcode_protocol::{ + Command, EndedProjectMove, MachineRequest, MachineResponse, MoveBlocker, MoveOutcome, MovePart, + MovePause, MovePhase, MoveState, ProjectMovePreview, ProjectMoveStatus, ProjectMovesState, +}; +use tcode_services::project_move as disk; +use tcode_services::store::Mutation; + +use crate::app::*; + +/// The project is moving to another machine and takes no work until the move +/// ends or is cancelled. +pub(crate) const PROJECT_MOVING: &str = "project_moving"; +/// The thread moved to another machine of the group, which the message names. +pub(crate) const THREAD_MOVED: &str = "thread_moved"; + +fn refusal(code: &str, message: impl Into) -> ProtocolError { + ProtocolError { + code: code.into(), + message: message.into(), + } +} + +fn host_stopped() -> ProtocolError { + refusal("transport_closed", "Host stopped before the move was done.") +} + +/// What this machine keeps of moving projects, both ways. +#[derive(Default)] +pub(crate) struct Moves { + /// Moves leaving this machine, by the project that moves. + outgoing: BTreeMap, + /// Cancelled moves whose other machine has yet to hear it, by move id. + aborting: HashMap, + /// A wait to tell them again is running. + aborts_waiting: bool, + /// Threads that moved away, and the machine each went to. + pub(super) moved_threads: HashMap, + /// Moves that arrived here, and the project each made. + pub(super) arrived: HashMap, + /// Moves being committed here now. + pub(super) committing: HashSet, + /// How each move that ended in this run ended, kept until the host stops: + /// a move is rare and a record is a few strings, so no count or timer + /// forgets one, and a client that attaches later reads from it how a move + /// it never saw ended. + ended: Vec, + next_run: u64, + /// The records of moves could not be read at start, so this machine does + /// not know which projects are moving or which moves arrived: it begins and + /// takes none, and says why. + unreadable: Option, +} + +struct Outgoing { + journal: Journal, + phase: MovePhase, + done: u64, + total: u64, + paused: Option, + commit_unknown: bool, + /// Which driver may act for the move: a cancel moves it on, so a driver + /// still running stops at its next step. + run: u64, + driver: Option>, + /// Waits since the move last got anywhere, for the next one's length. + waits: u32, +} + +/// What survives a restart of a move leaving this machine. +#[derive(Debug, Clone, Serialize, Deserialize)] +struct Journal { + move_id: String, + project_id: String, + machine: String, + root: String, + include_ignored: bool, + project_name: String, + project_root: PathBuf, + thread_ids: Vec, + stage: Stage, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +enum Stage { + /// Building or sending the parts. + Sending, + /// `MoveCommit` went out and its answer has not come back. + CommitSent, + /// The other machine made the project; what is left here goes. + Committed { project_id: String }, + /// Cancelled; the other machine has yet to discard its staging. + Aborting, +} + +impl Journal { + fn ended(&self, outcome: MoveOutcome) -> EndedProjectMove { + EndedProjectMove { + move_id: self.move_id.clone(), + project_id: self.project_id.clone(), + project_name: self.project_name.clone(), + machine: self.machine.clone(), + thread_ids: self.thread_ids.clone(), + outcome, + } + } + + fn record(&self) -> Mutation { + Mutation::put_move_record( + &self.move_id, + serde_json::to_vec(self).expect("a move journal serializes"), + ) + } +} + +/// How long a move whose other machine cannot be reached waits before it +/// tries again: longer after each wait, up to two minutes. +fn wait_after(waits: u32) -> Duration { + Duration::from_secs(5u64.saturating_mul(1 << waits.min(5)).min(120)) +} + +/// Why a driver stopped short of the end. +enum Stop { + /// A cancel took the move over. + Superseded, + /// The other machine could not be reached or does not take projects now: + /// the move waits and tries again. + Unreachable(MovePause), + /// The other machine refused or something failed here: the move waits + /// for the user to try again or cancel. + Failed(MovePause), +} + +fn failed(message: String) -> Stop { + Stop::Failed(MovePause::Failed { message }) +} + +fn stop_for(error: ProtocolError) -> Stop { + match error.code.as_str() { + MACHINE_UNREACHABLE => Stop::Unreachable(MovePause::Unreachable), + NO_GROUP => Stop::Unreachable(MovePause::NoGroup), + MACHINE_REFUSES => Stop::Unreachable(MovePause::Refused), + PROTOCOL_MISMATCH => Stop::Failed(MovePause::Version), + NOT_MEMBER => Stop::Failed(MovePause::NotMember), + _ => failed(format!("{}: {}", error.code, error.message)), + } +} + +impl AppState { + /// Take up the moves the store journalled, and what it keeps of the moves + /// that ended, at host start. Read here rather than off the host so the + /// freeze holds before the first command. + pub(crate) fn resume_project_moves(&mut self, cx: &mut HostCx) { + let named = |what: &'static str| { + move |error: std::io::Error| { + std::io::Error::new(error.kind(), format!("{what}: {error}")) + } + }; + let (moved, moved_unreadable) = UnreadableFile::read( + self.store + .moved_threads() + .map_err(named("where moved threads went")), + ); + let (arrived, arrived_unreadable) = UnreadableFile::read( + self.store + .moves_in() + .map_err(named("the moves that arrived")), + ); + let (records, records_unreadable) = UnreadableFile::read( + self.store + .project_moves() + .map_err(named("the projects moving away")), + ); + let mut journals = Vec::new(); + let mut journal_unreadable = None; + for body in records { + match serde_json::from_slice::(&body) { + Ok(journal) => journals.push(journal), + Err(error) => { + journal_unreadable = UnreadableFile::read::<()>(Err(std::io::Error::new( + std::io::ErrorKind::InvalidData, + format!("a project move this build cannot read: {error}"), + ))) + .1; + } + } + } + self.moves.moved_threads = moved; + self.moves.arrived = arrived; + self.moves.unreadable = moved_unreadable + .or(arrived_unreadable) + .or(records_unreadable) + .or(journal_unreadable); + for journal in journals { + if journal.stage == Stage::Aborting { + self.moves.aborting.insert(journal.move_id.clone(), journal); + continue; + } + let phase = match journal.stage { + Stage::Sending => MovePhase::Preparing, + _ => MovePhase::Committing, + }; + let project_id = journal.project_id.clone(); + self.insert_outgoing(journal, phase); + self.start_move_driver(&project_id, cx); + } + if !self.moves.aborting.is_empty() { + self.retry_aborts(0, cx); + } + } + + /// Why no move may begin or arrive here while its records are unreadable. + /// The first refusal is also told to the user; each is the answer to the + /// one asking. + pub(super) fn move_records_refusal(&mut self, cx: &mut HostCx) -> Option { + let unreadable = self.moves.unreadable.as_mut()?; + let first = unreadable.first_refusal().is_some(); + let error = unreadable.refusal(); + if first { + self.report_error( + RuntimeError::FileUnreadable { + error: error.clone(), + }, + cx, + ); + } + Some(refusal("move_records_unreadable", error)) + } + + fn insert_outgoing(&mut self, journal: Journal, phase: MovePhase) -> u64 { + self.moves.next_run += 1; + let run = self.moves.next_run; + self.moves.outgoing.insert( + journal.project_id.clone(), + Outgoing { + commit_unknown: journal.stage == Stage::CommitSent, + journal, + phase, + done: 0, + total: 0, + paused: None, + run, + driver: None, + waits: 0, + }, + ); + run + } + + /// Whether `project_id` is moving away now. + pub(crate) fn project_moving(&self, project_id: &str) -> bool { + self.moves.outgoing.contains_key(project_id) + } + + /// Whether the thread `id` belongs to a project moving away now. + pub(crate) fn thread_moving(&self, id: &str) -> bool { + self.moves.outgoing.values().any(|outgoing| { + outgoing + .journal + .thread_ids + .iter() + .any(|moving| moving == id) + }) || self + .current_meta(id) + .and_then(|meta| meta.project_id.as_deref()) + .is_some_and(|project| self.project_moving(project)) + } + + /// The machine the thread `id` moved to, when it moved away. + pub(crate) fn moved_thread_machine(&self, id: &str) -> Option<&str> { + self.moves.moved_threads.get(id).map(String::as_str) + } + + /// Why `command` may not run while its project moves away, or names a + /// thread that already did. Reading stays open; everything else that + /// would change the project's threads or start work in it is refused. + pub(crate) fn move_refusal(&self, command: &Command) -> Option { + let project = match command { + Command::MoveSession { project_id, .. } + | Command::SetProjectIcon { project_id, .. } + | Command::SetProjectRoot { project_id, .. } + | Command::DeleteProject { project_id } + | Command::StartDraft { project_id, .. } + | Command::StartExternalImport { project_id, .. } => Some(project_id), + _ => None, + }; + if project.is_some_and(|project| self.project_moving(project)) { + return Some(moving()); + } + let id = command.session_id()?; + if matches!( + command, + Command::MarkSessionRead { .. } + | Command::MarkSessionUnread { .. } + | Command::LoadBranches { .. } + | Command::SetTerminalHeight { .. } + | Command::ToggleTerminalPanel { .. } + | Command::CloseTerminalPanel { .. } + ) { + return None; + } + if self.thread_moving(id) { + return Some(moving()); + } + if self.current_meta(id).is_none() + && let Some(machine) = self.moved_thread_machine(id) + { + return Some(moved_away(id, machine)); + } + None + } + + /// Every thread that goes with `project_id`: its own, and the threads + /// under them. + fn moving_threads(&self, project_id: &str) -> Vec { + let mut ids = Vec::new(); + let mut seen = HashSet::new(); + for meta in self.sessions.iter() { + if meta.project_id.as_deref() != Some(project_id) { + continue; + } + for id in descendant_session_ids(self.sessions.iter(), &meta.id) { + if seen.insert(id.clone()) { + ids.push(id); + } + } + } + ids.iter().filter_map(|id| self.find_meta(id)).collect() + } + + /// What stands in the way of moving `project` with `threads` on this + /// machine. + fn local_blockers(&self, project: &Project, threads: &[SessionMeta]) -> Vec { + let mut blockers = Vec::new(); + if project.quick_chat { + blockers.push(MoveBlocker::QuickChat); + } + let (mut running, mut pending, mut queued, mut terminals) = (0, 0, 0, 0); + let parked = |destination: ConversationDestination| { + self.terminal_workspaces + .get(&destination) + .map_or(0, |workspace| workspace.terminals.len()) + }; + for meta in threads { + terminals += parked(ConversationDestination::Thread(meta.id.clone())); + pending += self.approval_requests(&meta.id).len(); + let Some(active) = self.resident(&meta.id) else { + continue; + }; + if active.turn_in_flight + || active.delivery_in_flight.is_some() + || active.background_task_count > 0 + || active.preparing_turn() + || active.timeline.turn_running + { + running += 1; + } + if active.timeline.pending_user_input.is_some() { + pending += 1; + } + if !active.queue.is_empty() { + queued += 1; + } + terminals += active.terminal_workspace.terminals.len(); + } + terminals += parked(ConversationDestination::ProjectDraft(project.id.clone())); + let count = |n: usize| u32::try_from(n).unwrap_or(u32::MAX); + if running > 0 { + blockers.push(MoveBlocker::ThreadsRunning(count(running))); + } + if pending > 0 { + blockers.push(MoveBlocker::PendingApprovals(count(pending))); + } + if queued > 0 { + blockers.push(MoveBlocker::QueuedMessages(count(queued))); + } + if terminals > 0 { + blockers.push(MoveBlocker::TerminalsOpen(count(terminals))); + } + blockers + } + + fn move_target(&self, project_id: &str) -> Result<(MachineLink, Project), ProtocolError> { + let link = self.machine_link()?.clone(); + let project = self + .projects + .iter() + .find(|project| project.id == project_id) + .cloned() + .ok_or_else(|| refusal("unknown_project", "This project is no longer available."))?; + Ok((link, project)) + } + + /// Start moving `project_id` to `machine`, at `root` there. Answers once + /// the project is frozen and its move journalled; the move goes on from + /// there. + pub(crate) fn move_project( + &mut self, + project_id: &str, + machine: &str, + root: &str, + include_ignored: bool, + cx: &mut HostCx, + ) -> HostTask> { + if let Some(error) = self.move_records_refusal(cx) { + return cx.spawn_background(async move { Err(error) }); + } + if self.project_moving(project_id) { + return cx.spawn_background(async move { Err(already_moving()) }); + } + let prepared = self.move_target(project_id).and_then(|(link, project)| { + let threads = self.moving_threads(project_id); + blocked(self.local_blockers(&project, &threads))?; + Ok((link, project, threads)) + }); + let host = cx.clone(); + let (machine, root, project_id) = + (machine.to_owned(), root.to_owned(), project_id.to_owned()); + cx.spawn_background(async move { + let (link, project, threads) = prepared?; + let checkouts = { + let (root, threads) = (project.root.clone(), threads.clone()); + host.unblock(move || code_blockers(&root, &threads)).await + }; + blocked(checkouts.map_err(|message| refusal("move_preview_failed", message))?)?; + let thread_ids: Vec = threads.iter().map(|meta| meta.id.clone()).collect(); + match link + .call( + &machine, + MachineRequest::MovePreflight { + project_name: project.name.clone(), + root: Some(root.clone()), + thread_ids: thread_ids.clone(), + }, + ) + .await? + { + MachineResponse::MovePreflight { .. } => {} + other => return Err(unexpected(&other)), + } + host.enqueue_and_wait(move |app, cx| { + if app.project_moving(&project.id) { + return Err(already_moving()); + } + let threads = app.moving_threads(&project.id); + blocked(app.local_blockers(&project, &threads))?; + let journal = Journal { + move_id: uuid::Uuid::new_v4().to_string(), + project_id: project.id.clone(), + machine, + root, + include_ignored, + project_name: project.name.clone(), + project_root: project.root.clone(), + thread_ids: threads.iter().map(|meta| meta.id.clone()).collect(), + stage: Stage::Sending, + }; + app.stop_moving_providers(&journal.thread_ids, cx); + app.insert_outgoing(journal, MovePhase::Preparing); + app.start_move_driver(&project_id, cx); + Ok(()) + }) + .await + .map_err(|()| host_stopped())? + }) + } + + /// Try `project_id`'s move again now, where it waits. + pub(crate) fn resume_project_move( + &mut self, + project_id: &str, + cx: &mut HostCx, + ) -> HostTask> { + let result = match self.moves.outgoing.get(project_id) { + None => Err(refusal("no_project_move", "This project is not moving.")), + Some(outgoing) if outgoing.phase == MovePhase::Cancelling => { + Err(refusal("move_cancelling", "This move is being cancelled.")) + } + Some(outgoing) => { + if outgoing.phase == MovePhase::Paused && outgoing.driver.is_none() { + self.start_move_driver(project_id, cx); + } + Ok(()) + } + }; + cx.spawn_background(async move { result }) + } + + /// Stop the providers of threads that are about to move, so nothing works + /// in them while their history leaves. + fn stop_moving_providers(&mut self, ids: &[String], cx: &mut HostCx) { + for id in ids { + if self.residents.live.contains_key(id) { + self.shutdown_active(id, cx); + } else if let Some(parked) = self.residents.evict(id) { + parked.stop_provider(); + } + } + } + + /// Run the move of `project_id` from where its journal is. + fn start_move_driver(&mut self, project_id: &str, cx: &mut HostCx) { + let Ok(link) = self.machine_link().cloned() else { + // Nothing reaches the group yet; the wait tries again. + self.pause_move(project_id, None, Stop::Unreachable(MovePause::NoGroup), cx); + return; + }; + let Some(outgoing) = self.moves.outgoing.get_mut(project_id) else { + return; + }; + // A paused move stays paused, and says why, until the other machine + // answers the driver. + let driver = Driver { + host: cx.clone(), + link, + store: self.store.clone(), + project_id: project_id.to_owned(), + run: outgoing.run, + }; + outgoing.driver = Some(cx.spawn_background(driver.drive())); + self.publish_project_moves(cx); + } + + /// The move's driver stopped for `stop`: it waits, trying again by itself + /// when the other machine could not be reached. + fn pause_move(&mut self, project_id: &str, run: Option, stop: Stop, cx: &mut HostCx) { + let Some(outgoing) = self + .moves + .outgoing + .get_mut(project_id) + .filter(|outgoing| run.is_none_or(|run| run == outgoing.run)) + else { + return; + }; + outgoing.driver = None; + let retry = match stop { + Stop::Superseded => return, + Stop::Unreachable(pause) => { + outgoing.paused = Some(pause); + true + } + Stop::Failed(pause) => { + outgoing.paused = Some(pause); + false + } + }; + outgoing.phase = MovePhase::Paused; + if retry { + let (wait, run) = (wait_after(outgoing.waits), outgoing.run); + outgoing.waits += 1; + let timer = cx.clock().timer(wait); + let host = cx.clone(); + let project_id = project_id.to_owned(); + cx.spawn_detached(async move { + timer.await; + host.enqueue(move |app, cx| { + if app.moves.outgoing.get(&project_id).is_some_and(|outgoing| { + outgoing.run == run + && outgoing.phase == MovePhase::Paused + && outgoing.driver.is_none() + }) { + app.start_move_driver(&project_id, cx); + } + }); + }); + } + self.publish_project_moves(cx); + } + + /// Stop the move of `project_id` before the other machine commits it: + /// the other machine discards what it staged and the project here is as + /// it was. Once the commit went out with no answer, only `force` ends it, + /// leaving the other machine with whatever it did. + pub(crate) fn cancel_project_move( + &mut self, + project_id: &str, + force: bool, + cx: &mut HostCx, + ) -> HostTask> { + let refused = |error| cx.spawn_background(async move { Err(error) }); + let Some(outgoing) = self.moves.outgoing.get_mut(project_id) else { + return refused(refusal("no_project_move", "This project is not moving.")); + }; + if outgoing.phase == MovePhase::Cancelling { + return refused(refusal("move_cancelling", "This move is being cancelled.")); + } + match outgoing.journal.stage { + Stage::Committed { .. } => { + return refused(refusal( + "move_committed", + "The other machine has the project now; this machine is letting it go.", + )); + } + Stage::CommitSent if !force => { + return refused(refusal( + "move_commit_unknown", + "The other machine was asked to take the project and has not said whether \ + it did; the move can only be cancelled by accepting that it may have.", + )); + } + _ => {} + } + let forced = outgoing.journal.stage == Stage::CommitSent; + self.moves.next_run += 1; + outgoing.run = self.moves.next_run; + outgoing.phase = MovePhase::Cancelling; + outgoing.paused = None; + let driver = outgoing.driver.take(); + let mut journal = outgoing.journal.clone(); + journal.stage = Stage::Aborting; + let ended = journal.ended(MoveOutcome::Cancelled { forced }); + self.publish_project_moves(cx); + let link = self.machine_link().ok().cloned(); + let store = self.store.clone(); + let host = cx.clone(); + let project_id = project_id.to_owned(); + cx.spawn_background(async move { + // A request the driver has in flight lands before the abort, so + // the abort is the last the other machine hears of the move. + if let Some(driver) = driver { + driver.await; + } + let recorded = { + let (store, record) = (store.clone(), journal.record()); + host.unblock(move || store.apply(&[record])).await + }; + let aborted = match &link { + Some(link) => abort(link, &journal).await, + None => false, + }; + let data_dir = store.root().clone(); + let left = { + let journal = journal.clone(); + host.unblock(move || { + disk::end_outgoing(&data_dir, &journal.move_id, &journal.project_root) + }) + .await + .err() + }; + let keep_trying = !aborted && !force && recorded.is_ok(); + if !keep_trying { + let (store, id) = (store.clone(), journal.move_id.clone()); + if let Err(error) = host + .unblock(move || store.apply(&[Mutation::remove_move_record(&id)])) + .await + { + log::warn!("could not end the record of a cancelled move: {error}"); + } + } + host.enqueue_and_wait(move |app, cx| { + if let Some(error) = left { + app.report_error(RuntimeError::MoveLeftBehind { error }, cx); + } + app.moves.outgoing.remove(&project_id); + app.record_ended(ended); + if keep_trying { + app.moves.aborting.insert(journal.move_id.clone(), journal); + app.retry_aborts(0, cx); + } + app.publish_project_moves(cx); + }) + .await + .map_err(|()| host_stopped()) + }) + } + + /// Tell the other machines of cancelled moves that never heard it, after + /// a wait. + fn retry_aborts(&mut self, waits: u32, cx: &mut HostCx) { + if self.moves.aborts_waiting { + return; + } + let Ok(link) = self.machine_link().cloned() else { + return; + }; + self.moves.aborts_waiting = true; + let journals: Vec = self.moves.aborting.values().cloned().collect(); + let timer = cx.clock().timer(wait_after(waits)); + let host = cx.clone(); + let store = self.store.clone(); + cx.spawn_detached(async move { + timer.await; + let mut told = Vec::new(); + for journal in journals { + if abort(&link, &journal).await { + let (store, id) = (store.clone(), journal.move_id.clone()); + if host + .unblock(move || store.apply(&[Mutation::remove_move_record(&id)])) + .await + .is_ok() + { + told.push(journal.move_id); + } + } + } + host.enqueue(move |app, cx| { + app.moves.aborts_waiting = false; + for id in told { + app.moves.aborting.remove(&id); + } + if !app.moves.aborting.is_empty() { + app.retry_aborts(waits + 1, cx); + } + }); + }); + } + + /// What moving `project_id` to `machine` would take, and what stands in + /// its way, on this machine and on that one. + pub(crate) fn project_move_preview( + &mut self, + project_id: &str, + machine: &str, + cx: &mut HostCx, + ) -> HostTask> { + let prepared = self.move_target(project_id).map(|(link, project)| { + let threads = self.moving_threads(project_id); + let blockers = self.local_blockers(&project, &threads); + (link, project, threads, blockers) + }); + let host = cx.clone(); + let machine = machine.to_owned(); + cx.spawn_background(async move { + let (link, project, threads, mut blockers) = prepared?; + let code = { + let (root, threads) = (project.root.clone(), threads.clone()); + host.unblock(move || code_preview(&root, &threads)).await + }; + let mut code = code.map_err(|message| refusal("move_preview_failed", message))?; + blockers.append(&mut code.blockers); + let machines = link.machines(true).await?; + let target = machines + .iter() + .find(|candidate| candidate.id == machine && !candidate.this_machine); + let mut default_root = String::new(); + match target { + None => blockers.push(MoveBlocker::TargetUnreachable), + Some(target) if target.reachable != Some(true) => { + blockers.push(MoveBlocker::TargetUnreachable) + } + Some(target) if target.protocol_ok == Some(false) => { + blockers.push(MoveBlocker::TargetVersion) + } + Some(_) => match link + .call( + &machine, + MachineRequest::MovePreflight { + project_name: project.name.clone(), + root: None, + thread_ids: threads.iter().map(|meta| meta.id.clone()).collect(), + }, + ) + .await + { + Ok(MachineResponse::MovePreflight { default_root: root }) => { + default_root = root + } + Ok(other) => return Err(unexpected(&other)), + Err(error) => match error.code.as_str() { + MACHINE_REFUSES => blockers.push(MoveBlocker::TargetRefuses), + MACHINE_UNREACHABLE => blockers.push(MoveBlocker::TargetUnreachable), + tcode_client::machines::PROTOCOL_MISMATCH => { + blockers.push(MoveBlocker::TargetVersion) + } + _ => return Err(error), + }, + }, + } + Ok(ProjectMovePreview { + default_root, + git: code.git, + branches: code.branches, + bytes: code.bytes, + dirty_checkouts: code.dirty_checkouts, + threads: threads + .iter() + .filter(|meta| meta.archived_at.is_none()) + .count() as u32, + archived_threads: threads + .iter() + .filter(|meta| meta.archived_at.is_some()) + .count() as u32, + ignored_files: code.ignored_files, + blockers, + relayed: target.and_then(|target| target.relayed).unwrap_or(false), + }) + }) + } + + /// The projects moving from this machine and how the moves that ended + /// went, as [`tcode_protocol::Topic::ProjectMoves`] answers. + pub(crate) fn project_moves_snapshot(&self) -> ProjectMovesState { + ProjectMovesState { + moving: self + .moves + .outgoing + .values() + .map(|outgoing| ProjectMoveStatus { + move_id: outgoing.journal.move_id.clone(), + project_id: outgoing.journal.project_id.clone(), + machine: outgoing.journal.machine.clone(), + phase: outgoing.phase, + done: outgoing.done, + total: outgoing.total, + paused: outgoing.paused.clone(), + commit_unknown: outgoing.commit_unknown, + }) + .collect(), + ended: self.moves.ended.clone(), + } + } + + /// Keep how a move ended, once. + fn record_ended(&mut self, ended: EndedProjectMove) { + if !self + .moves + .ended + .iter() + .any(|known| known.move_id == ended.move_id) + { + self.moves.ended.push(ended); + } + } + + fn publish_project_moves(&self, cx: &mut HostCx) { + cx.emit(HostEvent::Domain(EventEnvelope { + request_id: None, + topic: Topic::ProjectMoves, + event: ServerEvent::ProjectMovesReplaced(self.project_moves_snapshot()), + })); + } + + /// The other machine has the project: remove it and its threads here, + /// their Tcode worktrees with them, leaving where each thread went. The + /// project's directory stays. The move itself ends with + /// [`Self::end_moved_project`], once what it left is cleared. + fn let_moved_project_go( + &mut self, + journal: &Journal, + cx: &mut HostCx, + ) -> Option>> { + for id in &journal.thread_ids { + self.moves + .moved_threads + .insert(id.clone(), journal.machine.clone()); + } + // Said before the project and its threads leave the index, so a client + // that sees them go already knows where. + self.record_ended(journal.ended(MoveOutcome::Moved)); + self.publish_project_moves(cx); + let mut ids = journal.thread_ids.clone(); + for meta in self.moving_threads(&journal.project_id) { + if !ids.contains(&meta.id) { + ids.push(meta.id); + } + } + self.projects + .iter() + .any(|project| project.id == journal.project_id) + .then(|| self.remove_project_and_threads(&journal.project_id, &ids, true, cx)) + } + + /// The move of `project_id` that `run` drives is over. + fn end_moved_project(&mut self, project_id: &str, run: u64, cx: &mut HostCx) { + if self + .moves + .outgoing + .get(project_id) + .is_none_or(|outgoing| outgoing.run != run) + { + return; + } + if let Some(driver) = self + .moves + .outgoing + .remove(project_id) + .and_then(|outgoing| outgoing.driver) + { + // This is the driver ending the move: dropping its handle would + // cancel it before it returns. + driver.detach(); + } + self.publish_project_moves(cx); + } +} + +fn moving() -> ProtocolError { + refusal( + PROJECT_MOVING, + "This project is moving to another machine; wait for the move to end or cancel it.", + ) +} + +fn already_moving() -> ProtocolError { + refusal( + "move_in_progress", + "This project is already moving to another machine.", + ) +} + +fn moved_away(id: &str, machine: &str) -> ProtocolError { + refusal( + THREAD_MOVED, + format!("Thread {id} moved to machine {machine} of the group."), + ) +} + +fn unexpected(answer: &MachineResponse) -> ProtocolError { + refusal( + "unexpected_reply", + format!("the other machine answered {answer:?}"), + ) +} + +/// `blockers` as the refusal of a move, when there are any. +fn blocked(blockers: Vec) -> Result<(), ProtocolError> { + if blockers.is_empty() { + return Ok(()); + } + Err(refusal( + "move_blocked", + serde_json::to_string(&blockers).expect("move blockers serialize"), + )) +} + +/// What stands in the way of moving the code at `root`: a root inside a +/// larger repository, a thread working where the move would not carry it, or +/// checkouts of the project that are mid-merge or mid-rebase, or have unmerged +/// entries. +fn code_blockers( + root: &std::path::Path, + threads: &[SessionMeta], +) -> Result, String> { + if disk::inside_larger_repository(root)? { + return Ok(vec![MoveBlocker::InsideRepository]); + } + let mut blockers: Vec = disk::uncarried_paths(root, threads) + .into_iter() + .map(|(thread, path)| MoveBlocker::MissingCheckout { + thread, + path: path.display().to_string(), + }) + .collect(); + if !disk::is_git_project(root) { + return Ok(blockers); + } + for (_, path) in disk::checkouts(root, threads) { + if disk::git::interrupted(&path)? { + blockers.push(MoveBlocker::MergeInProgress { + path: path.display().to_string(), + }); + } + } + Ok(blockers) +} + +#[derive(Default)] +struct CodePreview { + git: bool, + branches: u32, + bytes: u64, + dirty_checkouts: u32, + ignored_files: Vec, + blockers: Vec, +} + +/// What a move would carry of the code at `root`: for a repository its +/// objects, branches, checkouts with changes and the files +/// `.worktreeinclude` would add; for a directory, its files. +fn code_preview(root: &std::path::Path, threads: &[SessionMeta]) -> Result { + if !disk::is_git_project(root) { + return Ok(CodePreview { + bytes: directory_bytes(root).map_err(|error| format!("{}: {error}", root.display()))?, + blockers: code_blockers(root, threads)?, + ..CodePreview::default() + }); + } + let checkouts = disk::checkouts(root, threads); + let mut preview = CodePreview { + git: true, + branches: disk::git::branch_count(root)?, + bytes: disk::git::object_bytes(root)?, + blockers: code_blockers(root, threads)?, + ..CodePreview::default() + }; + for (_, path) in &checkouts { + if disk::git::dirty(path)? { + preview.dirty_checkouts += 1; + } + } + let mut seen = HashSet::new(); + for (_, files) in disk::ignored_files(&checkouts)? { + for file in files { + if seen.insert(file.clone()) { + preview.ignored_files.push(file); + } + } + } + Ok(preview) +} + +fn directory_bytes(root: &std::path::Path) -> std::io::Result { + let mut total = 0; + let mut pending = vec![root.to_path_buf()]; + while let Some(dir) = pending.pop() { + for entry in std::fs::read_dir(&dir)? { + let entry = entry?; + let kind = entry.file_type()?; + if kind.is_dir() { + pending.push(entry.path()); + } else if kind.is_file() { + total += entry.metadata()?.len(); + } + } + } + Ok(total) +} + +/// Tell the other machine of `journal`'s move to discard what it staged; +/// whether it heard. A machine that answers anything but a failure to reach +/// it has heard. +async fn abort(link: &MachineLink, journal: &Journal) -> bool { + match link + .call( + &journal.machine, + MachineRequest::MoveAbort { + move_id: journal.move_id.clone(), + }, + ) + .await + { + Ok(_) => true, + Err(error) => !matches!( + error.code.as_str(), + MACHINE_UNREACHABLE | NO_GROUP | MACHINE_REFUSES + ), + } +} + +/// One run of a move leaving this machine, off the host: it reads and +/// changes the move only through the host, and stops as soon as a cancel +/// has taken the move over. +struct Driver { + host: HostCx, + link: MachineLink, + store: tcode_services::store::SessionStore, + project_id: String, + run: u64, +} + +impl Driver { + async fn drive(self) { + let Some(journal) = self.journal().await else { + return; + }; + let outcome = match journal.stage.clone() { + Stage::Sending => self.send(journal).await, + Stage::CommitSent => self.settle_commit(journal).await, + Stage::Committed { .. } => self.finish(journal).await, + Stage::Aborting => Ok(()), + }; + if let Err(stop) = outcome { + let (project_id, run) = (self.project_id.clone(), self.run); + self.host + .enqueue(move |app, cx| app.pause_move(&project_id, Some(run), stop, cx)); + } + } + + /// The move's journal while this driver still acts for it. + async fn journal(&self) -> Option { + let (project_id, run) = (self.project_id.clone(), self.run); + self.host + .enqueue_and_wait(move |app, _| { + app.moves + .outgoing + .get(&project_id) + .filter(|outgoing| outgoing.run == run) + .map(|outgoing| outgoing.journal.clone()) + }) + .await + .ok() + .flatten() + } + + /// Change the move while this driver still acts for it, and publish it. + async fn update( + &self, + change: impl FnOnce(&mut Outgoing) + Send + 'static, + ) -> Result<(), Stop> { + let (project_id, run) = (self.project_id.clone(), self.run); + let current = self + .host + .enqueue_and_wait(move |app, cx| { + let Some(outgoing) = app + .moves + .outgoing + .get_mut(&project_id) + .filter(|outgoing| outgoing.run == run) + else { + return false; + }; + change(outgoing); + app.publish_project_moves(cx); + true + }) + .await + .unwrap_or(false); + if current { + Ok(()) + } else { + Err(Stop::Superseded) + } + } + + /// Write `journal` as the move's record, and keep it as the move's. + async fn record(&self, journal: &Journal) -> Result<(), Stop> { + let (store, record) = (self.store.clone(), journal.record()); + self.host + .unblock(move || store.apply(&[record])) + .await + .map_err(|error| failed(format!("could not record the move: {error}")))?; + let journal = journal.clone(); + self.update(move |outgoing| outgoing.journal = journal) + .await + } + + async fn call( + &self, + journal: &Journal, + request: MachineRequest, + ) -> Result { + self.link + .call(&journal.machine, request) + .await + .map_err(stop_for) + } + + async fn send(&self, journal: Journal) -> Result<(), Stop> { + self.record(&journal).await?; + self.update(|outgoing| { + if outgoing.paused.is_none() { + outgoing.phase = MovePhase::Preparing; + } + }) + .await?; + let parts = self.parts(&journal).await?; + let total = parts.iter().map(|part| part.size).sum::(); + let begun = self + .call( + &journal, + MachineRequest::MoveBegin { + move_id: journal.move_id.clone(), + project_name: journal.project_name.clone(), + root: journal.root.clone(), + git: parts.iter().any(|part| part.name == disk::CODE_BUNDLE), + thread_ids: journal.thread_ids.clone(), + parts: parts.clone(), + }, + ) + .await?; + let MachineResponse::MoveBegun { received } = begun else { + return Err(failed(unexpected(&begun).message)); + }; + let held = |name: &str| { + received + .iter() + .find(|(part, _)| part == name) + .map_or(0, |(_, held)| *held) + }; + let mut done: u64 = parts + .iter() + .map(|part| held(&part.name).min(part.size)) + .sum(); + self.update(move |outgoing| { + outgoing.phase = MovePhase::SendingCode; + outgoing.paused = None; + outgoing.total = total; + outgoing.done = done; + outgoing.waits = 0; + }) + .await?; + let out = disk::outgoing_dir(self.store.root(), &journal.move_id); + for part in &parts { + let phase = if disk::is_code_part(&part.name) { + MovePhase::SendingCode + } else { + MovePhase::SendingThreads + }; + let mut offset = held(&part.name).min(part.size); + while offset < part.size { + let path = out.join(&part.name); + let length = (part.size - offset).min(disk::CHUNK_BYTES as u64); + let bytes = self + .host + .unblock(move || read_at(&path, offset, length as usize)) + .await + .map_err(|error| failed(format!("could not read a part: {error}")))?; + let answer = self + .call( + &journal, + MachineRequest::MoveChunk { + move_id: journal.move_id.clone(), + part: part.name.clone(), + offset, + bytes, + }, + ) + .await?; + let MachineResponse::MoveProgress { received } = answer else { + return Err(failed(unexpected(&answer).message)); + }; + let received = received.min(part.size); + done = (done + received).saturating_sub(offset); + offset = received; + self.update(move |outgoing| { + outgoing.phase = phase; + outgoing.done = done; + }) + .await?; + } + } + self.commit(journal).await + } + + /// The move's parts: those built before when they are intact, else built + /// now from the store as it holds every write made so far. + async fn parts(&self, journal: &Journal) -> Result, Stop> { + let out = disk::outgoing_dir(self.store.root(), &journal.move_id); + let reused = { + let out = out.clone(); + self.host.unblock(move || disk::built_parts(&out)).await + }; + if let Some(parts) = reused { + return Ok(parts); + } + let ids = journal.thread_ids.clone(); + let (barrier, threads) = self + .host + .enqueue_and_wait(move |app, cx| { + let threads: Vec = + ids.iter().filter_map(|id| app.find_meta(id)).collect(); + (app.store_write_barrier(cx), threads) + }) + .await + .map_err(|()| Stop::Superseded)?; + match barrier.recv().await { + Ok(Ok(())) => {} + Ok(Err(error)) => return Err(failed(format!("the store failed: {error}"))), + Err(_) => return Err(Stop::Superseded), + } + let store = self.store.clone(); + let journal = journal.clone(); + self.host + .unblock(move || { + disk::prepare( + &store, + &out, + &disk::Outgoing { + move_id: &journal.move_id, + project_name: &journal.project_name, + root: &journal.project_root, + include_ignored: journal.include_ignored, + threads: &threads, + }, + ) + }) + .await + .map_err(failed) + } + + /// Send `MoveCommit`, recorded as sent before it goes, and settle what it + /// answers. + async fn commit(&self, mut journal: Journal) -> Result<(), Stop> { + journal.stage = Stage::CommitSent; + self.update(|outgoing| outgoing.phase = MovePhase::Committing) + .await?; + self.record(&journal).await?; + let answer = self + .link + .call( + &journal.machine, + MachineRequest::MoveCommit { + move_id: journal.move_id.clone(), + }, + ) + .await; + self.settle(journal, answer).await + } + + async fn settle( + &self, + mut journal: Journal, + answer: Result, + ) -> Result<(), Stop> { + match answer { + Ok(MachineResponse::MoveCommitted { project_id }) => { + journal.stage = Stage::Committed { project_id }; + self.record(&journal).await?; + self.finish(journal).await + } + Ok(other) => Err(failed(unexpected(&other).message)), + Err(error) => match stop_for(error) { + Stop::Failed(pause) => { + // The other machine answered: it did not take the project. + journal.stage = Stage::Sending; + self.record(&journal).await?; + self.update(|outgoing| outgoing.commit_unknown = false) + .await?; + Err(Stop::Failed(pause)) + } + stop => { + self.update(|outgoing| outgoing.commit_unknown = true) + .await?; + Err(stop) + } + }, + } + } + + /// The commit went out and no answer came: ask the other machine what + /// became of it. + async fn settle_commit(&self, mut journal: Journal) -> Result<(), Stop> { + let state = self + .call( + &journal, + MachineRequest::MoveStatus { + move_id: journal.move_id.clone(), + }, + ) + .await?; + self.update(|outgoing| { + outgoing.phase = MovePhase::Committing; + outgoing.paused = None; + }) + .await?; + match state { + MachineResponse::MoveState(MoveState::Committed { project_id }) => { + self.settle(journal, Ok(MachineResponse::MoveCommitted { project_id })) + .await + } + MachineResponse::MoveState(MoveState::Staging) => { + let answer = self + .link + .call( + &journal.machine, + MachineRequest::MoveCommit { + move_id: journal.move_id.clone(), + }, + ) + .await; + self.settle(journal, answer).await + } + MachineResponse::MoveState(MoveState::Unknown) => { + // The other machine lost what it staged: everything goes again. + journal.stage = Stage::Sending; + self.update(|outgoing| outgoing.commit_unknown = false) + .await?; + self.send(journal).await + } + other => Err(failed(unexpected(&other).message)), + } + } + + /// Let the project go here now that the other machine has it, clear + /// what the move left, and only then forget the move: a restart before + /// that finds it committed and does this again. + async fn finish(&self, journal: Journal) -> Result<(), Stop> { + let redirects: Vec = journal + .thread_ids + .iter() + .map(|id| Mutation::redirect_thread(id, &journal.machine)) + .collect(); + let store = self.store.clone(); + self.host + .unblock(move || store.apply(&redirects)) + .await + .map_err(|error| failed(format!("could not record where the threads went: {error}")))?; + let let_go = journal.clone(); + let removed = self + .host + .enqueue_and_wait(move |app, cx| app.let_moved_project_go(&let_go, cx)) + .await + .map_err(|()| Stop::Superseded)?; + if let Some(removed) = removed + && let Err(error) = removed.await + { + log::warn!("{}", error.message); + } + // The project's and threads' removal is queued; the journal goes only + // once the store holds it. + let barrier = self + .host + .enqueue_and_wait(|app, cx| app.store_write_barrier(cx)) + .await + .map_err(|()| Stop::Superseded)?; + match barrier.recv().await { + Ok(Ok(())) => {} + Ok(Err(error)) => return Err(failed(format!("the store failed: {error}"))), + Err(_) => return Err(Stop::Superseded), + } + let (store, data_dir) = (self.store.clone(), self.store.root().clone()); + let move_id = journal.move_id.clone(); + let ended = self + .host + .unblock(move || { + disk::end_outgoing(&data_dir, &move_id, &journal.project_root)?; + store + .apply(&[Mutation::remove_move_record(&move_id)]) + .map_err(|error| error.to_string()) + }) + .await; + if let Err(error) = ended { + // The journal stays, so the next start finishes the move again and + // clears what is left. + self.host.enqueue(move |app, cx| { + app.report_error(RuntimeError::MoveLeftBehind { error }, cx) + }); + } + let (project_id, run) = (self.project_id.clone(), self.run); + self.host + .enqueue_and_wait(move |app, cx| app.end_moved_project(&project_id, run, cx)) + .await + .map_err(|()| Stop::Superseded) + } +} + +fn read_at(path: &std::path::Path, offset: u64, length: usize) -> std::io::Result> { + use std::io::{Read as _, Seek as _, SeekFrom}; + let mut file = std::fs::File::open(path)?; + file.seek(SeekFrom::Start(offset))?; + let mut bytes = vec![0; length]; + file.read_exact(&mut bytes)?; + Ok(bytes) +} diff --git a/crates/runtime/src/app/machines/real_group.rs b/crates/runtime/src/app/machines/real_group.rs new file mode 100644 index 000000000..c69f32c9f --- /dev/null +++ b/crates/runtime/src/app/machines/real_group.rs @@ -0,0 +1,158 @@ +//! Machines of a group over real loopback endpoints, each a real host on a store of its own +//! as the binaries compose it, with a client of its own. +use std::path::{Path, PathBuf}; + +use tcode_client::HostLink; +use tcode_client::machines::MachineLink; +use tcode_protocol::{ + Command, CommandResponse, EventEnvelope, GroupAction, HostingAction, ProtocolError, Query, + QueryResponse, Subscription, Topic, +}; +use tcode_services::store::SessionStore; +use tcode_traverse::{HostConfig, HostMux, TraverseHost}; + +use crate::pipe::{HostServices, SpawnedHost, spawn_host}; + +pub(super) struct TestDir(pub(super) PathBuf); + +impl TestDir { + pub(super) fn new(tag: &str) -> Self { + let path = + std::env::temp_dir().join(format!("tcode-machines-{tag}-{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&path).unwrap(); + Self(path) + } +} + +impl Drop for TestDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A machine as the binaries compose it: its host, the mux in front of it, +/// the endpoint, and a client of its own. +pub(super) struct Machine { + pub(super) endpoint: Option, + pub(super) runtime: Option, + pub(super) mux: HostMux, + pub(super) dir: PathBuf, + pub(super) name: String, + pub(super) client: HostLink, + pub(super) events: async_channel::Receiver, + pub(super) link: MachineLink, + pub(super) store: SessionStore, + /// The UDP port its endpoint last had, which it binds again when it + /// starts hosting again, as a machine on a fixed port does. + port: Option, +} + +impl Machine { + pub(super) fn start(dir: &Path, name: &str) -> Self { + Self::start_with(dir, name, HostServices::default()) + } + + /// The machine with `services` beside its way to the group. + pub(super) fn start_with(dir: &Path, name: &str, mut services: HostServices) -> Self { + let link = MachineLink::new(); + let store = SessionStore::open_at(dir.join("store")).unwrap(); + services.machines = Some(link.clone()); + let runtime = spawn_host(store.clone(), services).unwrap(); + let mux = HostMux::new(runtime.attachments.clone(), runtime.from_host.clone()) + .with_machine_link(link.clone()); + let endpoint = TraverseHost::start(mux.clone(), config(dir, name)).unwrap(); + let connection = mux.attach( + tcode_protocol::Principal::Full, + tcode_client::attachment::AttachmentPolicy::LOCAL, + ); + let client = HostLink::new(connection.to_host, connection.from_host); + let pump = client.clone(); + smol::spawn(async move { pump.pump().await }).detach(); + let events = client.events(); + Self { + endpoint: Some(endpoint), + runtime: Some(runtime), + mux, + dir: dir.to_path_buf(), + name: name.into(), + client, + events, + link, + store, + port: None, + } + } + + pub(super) fn id(&self) -> String { + self.endpoint.as_ref().unwrap().endpoint_id() + } + + pub(super) fn group(&self, action: GroupAction) { + self.endpoint + .as_ref() + .unwrap() + .hosting(HostingAction::Group(action)) + .unwrap(); + } + + pub(super) fn command(&self, command: Command) -> Result { + self.client.command_blocking(command) + } + + pub(super) fn query(&self, query: Query) -> Result { + smol::block_on(self.client.query(query)) + } + + pub(super) fn subscribe(&self, topic: Topic) { + self.client + .subscribe(Subscription { + known_index: None, + topic, + after: None, + }) + .unwrap(); + } + + pub(super) fn stop_hosting(&mut self) { + if let Some(endpoint) = self.endpoint.take() { + self.port = endpoint + .direct_addrs() + .iter() + .find(|addr| addr.is_ipv4()) + .map(|addr| addr.port()); + endpoint.shutdown(); + } + } + + pub(super) fn start_hosting(&mut self) { + let config = HostConfig { + bind_port: self.port, + ..config(&self.dir, &self.name) + }; + self.endpoint = Some(TraverseHost::start(self.mux.clone(), config).unwrap()); + } +} + +impl Drop for Machine { + fn drop(&mut self) { + self.stop_hosting(); + if let Some(runtime) = self.runtime.take() { + smol::block_on(async { + let _ = self.client.shutdown().await; + runtime.to_host.close(); + let _ = runtime.stopped.recv().await; + self.client.close(); + }); + } + } +} + +pub(super) fn config(dir: &Path, name: &str) -> HostConfig { + HostConfig { + host_name: name.into(), + data_dir: dir.to_path_buf(), + traverse: Vec::new(), + pairing_enabled: true, + bind_port: None, + } +} diff --git a/crates/runtime/src/app/machines/remote.rs b/crates/runtime/src/app/machines/remote.rs new file mode 100644 index 000000000..aa6f6e089 --- /dev/null +++ b/crates/runtime/src/app/machines/remote.rs @@ -0,0 +1,1132 @@ +//! A thread here working on another machine of the group: its `tcode_control` calls that +//! name that machine, the threads it starts there, and what comes back from them. +use control_mcp::params::RunOp; +use control_mcp::{ + BatchResponse, ControlOp, ControlThreadParams, ControlThreadResponse, ListMachinesParams, + Outcome, RunChange, RunResult, StartThreadOnMachineParams, StartThreadResponse, +}; +use tcode_client::machines::{MACHINE_UNREACHABLE, MachineInfo, MachineLink, NO_GROUP}; +use tcode_core::control::{ + ControlWatch, RemoteChild, RemoteChildOp, RemoteChildState, WatchEvent, action, +}; +use tcode_protocol::{MachineCaller, MachineRequest, MachineResponse}; + +use super::MachinePeer; +use crate::app::control::{Answer, Caller, finish_on_host}; +use crate::app::*; + +/// A [`MachineRequest::Callback`] as it arrives. +pub(super) struct Callback { + pub(super) thread_id: String, + pub(super) from_thread_id: String, + pub(super) from_title: String, + pub(super) text: String, + pub(super) report: Option, + pub(super) state: Option, + pub(super) watch: Option, +} + +/// What a call answered from another machine, and the machine. +type Forwarded = Result; + +/// The other machine's refusal or failure, as the calling thread reads it. +fn from_machine(info: &MachineInfo, error: ProtocolError) -> String { + format!( + "machine \"{}\" ({}): {} ({})", + info.title(), + info.id, + error.message, + error.code + ) +} + +/// `answer` with the machine that gave it named in it. +fn naming_machine(answer: serde_json::Value, info: &MachineInfo) -> serde_json::Value { + let machine = serde_json::json!({ "id": info.id, "name": info.title() }); + match answer { + serde_json::Value::Object(mut fields) => { + fields.insert("machine".into(), machine); + serde_json::Value::Object(fields) + } + other => serde_json::json!({ "machine": machine, "answer": other }), + } +} + +/// The action key a write records, by what it did. +fn run_action(op: &RunOp) -> &'static str { + match op { + RunOp::Interrupt => action::INTERRUPT, + RunOp::Cancel => action::CANCEL, + RunOp::SteerQueued { .. } => action::STEER_QUEUED, + RunOp::DropQueued { .. } => action::DROP_QUEUED, + RunOp::Retry { .. } => action::RETRY, + RunOp::Compact => action::COMPACT, + RunOp::SetModel { .. } => action::SET_MODEL, + RunOp::SetOption { .. } => action::SET_OPTION, + RunOp::Fork | RunOp::ForkAt { .. } => action::FORK, + } +} + +impl AppState { + /// Why `caller` may not reach another machine, if it may not. + fn may_reach_machines(&self, caller: &Caller) -> Result { + if !self.settings.control.machines { + return Err( + "refused: Settings → Control does not let this machine's threads reach the \ + other machines of its group" + .into(), + ); + } + if caller.space.is_some() { + return Err("refused: a turn in a space reaches no other machine".into()); + } + self.machine_link() + .cloned() + .map_err(|_| "refused: this machine is in no group".to_owned()) + } + + /// Run `op` on `machine` for `caller`, and `finish` with its answer on the host thread + /// whether or not the caller still waits: what the other machine did is recorded here + /// even when the call was cancelled meanwhile. + fn forward( + &mut self, + caller: &Caller, + machine: String, + op: ControlOp, + request_id: Option, + cx: &mut HostCx, + finish: impl FnOnce( + &mut AppState, + &MachineInfo, + Forwarded, + &mut HostCx, + ) -> Result + + Send + + 'static, + ) -> Answer { + let link = match self.may_reach_machines(caller) { + Ok(link) => link, + Err(refusal) => return Answer::Now(Err(refusal)), + }; + let request = MachineRequest::Control { + caller: self.machine_caller(&caller.thread_id, request_id), + tool: op.tool_name().to_owned(), + args: op.args(), + }; + let host_cx = cx.clone(); + let (sent, answer) = smol::channel::bounded(1); + HostCx::spawn_detached(cx, async move { + let info = match member(&link, &machine).await { + Ok(info) => info, + Err(refusal) => { + let _ = sent.send(Err(refusal)).await; + return; + } + }; + let answer = link.call(&info.id, request).await; + let finished = finish_on_host(host_cx, move |state, cx| { + let reached = answer.is_ok(); + let left = answer + .as_ref() + .is_err_and(|error| error.code == tcode_client::machines::NOT_MEMBER); + let answer = answer.and_then(|response| match response { + MachineResponse::Control(value) => Ok(value), + other => Err(ProtocolError { + code: "unexpected_reply".into(), + message: format!("the machine answered {other:?}"), + }), + }); + let finished = finish(state, &info, answer, cx); + state.machine_answered(&info.id, reached, left, true, cx); + finished.map(|value| naming_machine(value, &info)) + }) + .await; + let _ = sent.send(finished).await; + }); + Answer::Later(cx.spawn_background(async move { + answer + .recv() + .await + .unwrap_or_else(|_| Err("the host stopped before the call finished".into())) + })) + } + + /// One of the tools that take `machine`, run on that machine. + pub(in crate::app) fn forward_control_op( + &mut self, + caller: &Caller, + machine: String, + op: ControlOp, + cx: &mut HostCx, + ) -> Answer { + let plain = |_: &mut AppState, info: &MachineInfo, answer: Forwarded, _: &mut HostCx| { + answer.map_err(|error| from_machine(info, error)) + }; + let thread = caller.thread_id.clone(); + match op { + op @ (ControlOp::ListProjects(_) + | ControlOp::ListThreads(_) + | ControlOp::GetThread(_) + | ControlOp::Outline(_) + | ControlOp::Read(_) + | ControlOp::SearchInItem(_) + | ControlOp::ListProviders(_)) => self.forward(caller, machine, op, None, cx, plain), + ControlOp::SendMessage(params) => { + let request_id = params.request_id.clone(); + let queues = !matches!(params.mode, control_mcp::SendMode::Schedule { .. }); + let key = match params.mode { + control_mcp::SendMode::Queue => action::SEND_QUEUED, + control_mcp::SendMode::Steer => action::SEND_STEERED, + control_mcp::SendMode::Schedule { .. } => action::SEND_SCHEDULED, + }; + self.forward( + caller, + machine, + ControlOp::SendMessage(params), + request_id, + cx, + move |state, info, answer, cx| { + let value = answer.map_err(|error| from_machine(info, error))?; + if let Ok(batch) = serde_json::from_value::(value.clone()) { + for result in batch + .results + .iter() + .filter(|result| result.outcome == Outcome::Applied) + { + state.audit_elsewhere(&thread, info, &result.target, key, None, cx); + // A message to one's own subagent opens a new report it owes. + if queues { + state.remote_child_heard(&thread, &info.id, &result.target, cx); + } + } + } + Ok(value) + }, + ) + } + ControlOp::ControlThread(params) => { + self.forward_control_thread(caller, machine, params, cx) + } + ControlOp::NotifyWhen(params) => { + let request_id = params.request_id.clone(); + let events = params.events.clone(); + self.forward( + caller, + machine, + ControlOp::NotifyWhen(params), + request_id, + cx, + move |state, info, answer, cx| { + let value = answer.map_err(|error| from_machine(info, error))?; + state.watching_elsewhere(&thread, info, &value, events, cx); + Ok(value) + }, + ) + } + ControlOp::CancelNotify(params) => self.forward( + caller, + machine, + ControlOp::CancelNotify(params), + None, + cx, + move |state, info, answer, cx| { + let value = answer.map_err(|error| from_machine(info, error))?; + let removed: Vec = value["removed"] + .as_array() + .into_iter() + .flatten() + .filter_map(|id| id.as_str().map(str::to_owned)) + .collect(); + if !removed.is_empty() { + state.change_meta(&thread, cx, |meta| { + meta.control_watches.retain(|watch| { + watch.machine.as_deref() != Some(info.id.as_str()) + || !removed.contains(&watch.id) + }); + }); + let detail = removed.join(", "); + state.audit_elsewhere( + &thread, + info, + "", + action::CANCEL_NOTIFY, + Some(detail), + cx, + ); + } + Ok(value) + }, + ), + ControlOp::RespondInput(params) => { + let target = params.thread_id.clone(); + self.forward( + caller, + machine, + ControlOp::RespondInput(params), + None, + cx, + move |state, info, answer, cx| { + let value = answer.map_err(|error| from_machine(info, error))?; + let detail = value["request_id"].as_str().map(str::to_owned); + state.audit_elsewhere( + &thread, + info, + &target, + action::RESPOND_INPUT, + detail, + cx, + ); + Ok(value) + }, + ) + } + ControlOp::RespondApproval(params) => { + let target = params.thread_id.clone(); + self.forward( + caller, + machine, + ControlOp::RespondApproval(params), + None, + cx, + move |state, info, answer, cx| { + let value = answer.map_err(|error| from_machine(info, error))?; + let detail = value["approval_id"].as_str().map(str::to_owned); + state.audit_elsewhere( + &thread, + info, + &target, + action::RESPOND_APPROVAL, + detail, + cx, + ); + Ok(value) + }, + ) + } + other => Answer::Now(Err(format!( + "`{}` runs on this machine only: omit machine", + other.tool_name() + ))), + } + } + + /// `control_thread` on another machine. A cancel or interrupt of this thread's own + /// subagent there that cannot reach it now is kept and sent when it can. + fn forward_control_thread( + &mut self, + caller: &Caller, + machine: String, + params: ControlThreadParams, + cx: &mut HostCx, + ) -> Answer { + let thread = caller.thread_id.clone(); + let changes = params.changes.clone(); + let request_id = params.request_id.clone(); + self.forward( + caller, + machine, + ControlOp::ControlThread(params), + request_id, + cx, + move |state, info, answer, cx| match answer { + Ok(value) => { + if let Ok(response) = + serde_json::from_value::(value.clone()) + { + for (change, result) in changes.iter().zip(&response.results) { + if result.result.outcome != Outcome::Applied { + continue; + } + state.audit_elsewhere( + &thread, + info, + &change.thread_id, + run_action(&change.op), + None, + cx, + ); + if change.op == RunOp::Cancel { + state.remote_child_done( + &thread, + &info.id, + &change.thread_id, + RemoteChildOp::Cancel, + cx, + ); + } + } + } + Ok(value) + } + Err(error) if error.code == MACHINE_UNREACHABLE => { + let results = changes + .into_iter() + .map(|change| state.keep_for_later(&thread, info, change, &error, cx)) + .collect(); + serde_json::to_value(ControlThreadResponse { results }) + .map_err(|error| error.to_string()) + } + Err(error) => Err(from_machine(info, error)), + }, + ) + } + + /// One change of a `control_thread` call that could not reach `info`'s machine. + fn keep_for_later( + &mut self, + lead: &str, + info: &MachineInfo, + change: RunChange, + error: &ProtocolError, + cx: &mut HostCx, + ) -> RunResult { + let op = match change.op { + RunOp::Cancel => Some(RemoteChildOp::Cancel), + RunOp::Interrupt => Some(RemoteChildOp::Interrupt), + _ => None, + }; + let own = self.find_meta(lead).is_some_and(|meta| { + meta.remote_children + .iter() + .any(|child| child.machine == info.id && child.thread_id == change.thread_id) + }); + let result = |outcome, reason: String| RunResult { + result: control_mcp::BatchResult { + target: change.thread_id.clone(), + outcome, + reason: Some(reason), + side_effects: None, + }, + new_thread_id: None, + }; + match op { + Some(op) if own => { + self.change_meta(lead, cx, |meta| { + for child in &mut meta.remote_children { + if child.machine == info.id && child.thread_id == change.thread_id { + // A cancel stops it anyway: an interrupt asked later adds nothing. + if !(child.pending == Some(RemoteChildOp::Cancel) + && op == RemoteChildOp::Interrupt) + { + child.pending = Some(op); + } + } + } + }); + result( + Outcome::Applied, + format!( + "queued: machine \"{}\" cannot be reached now; it is sent when it can be", + info.title() + ), + ) + } + _ => result(Outcome::Failed, from_machine(info, error.clone())), + } + } + + pub(in crate::app) fn op_list_machines( + &mut self, + caller: &Caller, + _params: ListMachinesParams, + cx: &mut HostCx, + ) -> Answer { + let link = match self.may_reach_machines(caller) { + Ok(link) => link, + Err(refusal) => return Answer::Now(Err(refusal)), + }; + Answer::Later(cx.spawn_background(async move { + let machines = link.machines(true).await.map_err(no_group)?; + let machines: Vec = machines + .iter() + .map(|info| { + serde_json::json!({ + "id": info.id, + "name": info.title(), + "host_name": info.name, + "this_machine": info.this_machine, + "reachable": info.reachable, + "accepts_threads": info.accepts_threads, + "accepts_projects": info.accepts_projects, + "same_version": info.protocol_ok, + }) + }) + .collect(); + Ok(serde_json::json!({ "machines": machines })) + })) + } + + pub(in crate::app) fn op_start_thread_on_machine( + &mut self, + caller: &Caller, + params: StartThreadOnMachineParams, + cx: &mut HostCx, + ) -> Answer { + if params.request_id.trim().is_empty() { + return Answer::Now(Err("request_id must not be empty".into())); + } + let subagent = params.subagent.unwrap_or(false); + if subagent + && self + .find_meta(&caller.thread_id) + .is_some_and(|meta| meta.collaboration_id.is_some()) + { + return Answer::Now(Err( + "refused: this thread runs under a collaboration, whose members are all on \ + this machine; start its subagents here with start_thread" + .into(), + )); + } + let thread = caller.thread_id.clone(); + let request_id = params.request_id.clone(); + let machine = params.machine.clone(); + self.forward( + caller, + machine, + ControlOp::StartThread(params.start_thread()), + Some(request_id.clone()), + cx, + move |state, info, answer, cx| { + let value = answer.map_err(|error| from_machine(info, error))?; + let started: StartThreadResponse = serde_json::from_value(value) + .map_err(|error| format!("the machine's answer was not understood: {error}"))?; + if subagent { + state.remember_remote_child(&thread, info, &started, &request_id, cx); + } + if started.created { + state.audit_elsewhere( + &thread, + info, + &started.thread_id, + action::START_THREAD, + Some(started.title.clone()), + cx, + ); + } + Ok(serde_json::json!({ + "thread_id": started.thread_id, + "link": format!("tcode-thread://{}", tcode_core::notice::thread_ref(&started.thread_id, Some(&info.id))), + "created": started.created, + "title": started.title, + "cwd": started.cwd, + "subagent": started.subagent, + "worktree_branch": started.worktree_branch, + })) + }, + ) + } + + /// Keep on `lead` the subagent it started on `info`'s machine; once per request. + fn remember_remote_child( + &mut self, + lead: &str, + info: &MachineInfo, + started: &StartThreadResponse, + request_id: &str, + cx: &mut HostCx, + ) { + let now = cx.clock().unix_secs(); + self.change_meta(lead, cx, |meta| { + if meta.remote_children.iter().any(|child| { + child.machine == info.id + && (child.request_id == request_id || child.thread_id == started.thread_id) + }) { + return; + } + meta.remote_children.push(RemoteChild { + machine: info.id.clone(), + thread_id: started.thread_id.clone(), + title: started.title.clone(), + request_id: request_id.to_owned(), + subagent: true, + state: RemoteChildState::Running, + updated_at: now, + pending: None, + report_taken: None, + report_taken_unsent: false, + }); + }); + } + + /// Record in `lead`'s own log a write its call made on `info`'s machine, which records + /// it in the target thread there. + fn audit_elsewhere( + &mut self, + lead: &str, + info: &MachineInfo, + target: &str, + key: &str, + detail: Option, + cx: &mut HostCx, + ) { + let Some(meta) = self.find_meta(lead) else { + return; + }; + let target_title = meta + .remote_children + .iter() + .find(|child| child.machine == info.id && child.thread_id == target) + .map(|child| child.title.clone()) + .unwrap_or_else(|| target.to_owned()); + let on = if target.is_empty() { + info.title().to_owned() + } else { + format!("{target_title} — {}", info.title()) + }; + let action = tcode_core::control::ControlAction { + actor_thread_id: lead.to_owned(), + actor_title: meta.title, + actor_machine: None, + action: key.to_owned(), + detail: Some(match detail { + Some(detail) => format!("{on} — {detail}"), + None => on, + }), + }; + self.record_event(lead, &AgentEvent::ControlAction(action), cx); + } + + /// `lead`'s subagent on `machine` was sent a message: it runs again, and owes a report. + fn remote_child_heard(&mut self, lead: &str, machine: &str, thread: &str, cx: &mut HostCx) { + let now = cx.clock().unix_secs(); + self.change_meta(lead, cx, |meta| { + for child in &mut meta.remote_children { + if child.machine == machine + && child.thread_id == thread + && child.subagent + && child.state != RemoteChildState::MachineLeft + { + child.state = RemoteChildState::Running; + child.updated_at = now; + } + } + }); + } + + /// `op` on `lead`'s subagent on `machine` was carried out there. + fn remote_child_done( + &mut self, + lead: &str, + machine: &str, + thread: &str, + op: RemoteChildOp, + cx: &mut HostCx, + ) { + let now = cx.clock().unix_secs(); + self.change_meta(lead, cx, |meta| { + for child in &mut meta.remote_children { + if child.machine == machine && child.thread_id == thread { + if child.pending == Some(op) { + child.pending = None; + } + let state = match op { + RemoteChildOp::Cancel => Some(RemoteChildState::Cancelled), + RemoteChildOp::Settle => Some(RemoteChildState::Settled), + RemoteChildOp::Interrupt => None, + }; + if let Some(state) = state { + child.state = state; + child.updated_at = now; + } + } + } + }); + } + + /// The lead settles its children: those on other machines that reported are settled + /// there, now or when their machine can be reached. + pub(in crate::app) fn settle_remote_children(&mut self, lead: &str, cx: &mut HostCx) { + self.change_meta(lead, cx, |meta| { + for child in &mut meta.remote_children { + if child.subagent + && matches!( + child.state, + RemoteChildState::Reported | RemoteChildState::Failed + ) + && child.pending.is_none() + { + child.pending = Some(RemoteChildOp::Settle); + } + } + }); + let machines: BTreeSet = self + .find_meta(lead) + .into_iter() + .flat_map(|meta| meta.remote_children) + .filter(|child| child.pending == Some(RemoteChildOp::Settle)) + .map(|child| child.machine) + .collect(); + for machine in machines { + self.send_remote_child_work(Some(&machine), cx); + } + } + + /// A client asks for `op` on `lead`'s subagent `thread` on `machine`: it is kept as + /// owed and sent now, and answered once it was carried out there, refused there, or + /// kept for when that machine can be reached. + pub(crate) fn control_remote_child( + &mut self, + lead: &str, + machine: &str, + thread: &str, + op: RemoteChildOp, + cx: &mut HostCx, + ) -> HostTask> { + let refused = |message: &str| ProtocolError { + code: "remote_child_state".into(), + message: message.into(), + }; + let Some(mut child) = self.find_meta(lead).and_then(|meta| { + meta.remote_children + .into_iter() + .find(|child| child.machine == machine && child.thread_id == thread) + }) else { + let error = refused("This thread did not start that thread on that machine."); + return cx.spawn_background(async move { Err(error) }); + }; + let open = matches!( + child.state, + RemoteChildState::Reported | RemoteChildState::Failed + ); + let fits = match op { + RemoteChildOp::Interrupt => child.state == RemoteChildState::Running, + RemoteChildOp::Cancel => child.state == RemoteChildState::Running || open, + RemoteChildOp::Settle => child.subagent && open, + }; + match child.pending { + // A cancel stops it anyway: an interrupt asked after it adds nothing. + Some(RemoteChildOp::Cancel) + if matches!(op, RemoteChildOp::Cancel | RemoteChildOp::Interrupt) => + { + return cx.spawn_background(async { Ok(()) }); + } + Some(RemoteChildOp::Cancel) => { + let error = refused("A cancel of that thread is still to be sent."); + return cx.spawn_background(async move { Err(error) }); + } + _ if !fits => { + let error = refused("That thread is not in a state this asks of it."); + return cx.spawn_background(async move { Err(error) }); + } + _ => {} + } + child.pending = Some(op); + self.change_meta(lead, cx, |meta| { + for kept in &mut meta.remote_children { + if kept.machine == machine && kept.thread_id == thread { + kept.pending = Some(op); + } + } + }); + let (sent, answer) = smol::channel::bounded(1); + self.send_remote_child_op(lead, &child, op, cx, move |result| { + let _ = sent.try_send(result); + }); + // No answer is a send already under way for this child, which sends what is owed + // again once it is answered. + cx.spawn_background(async move { answer.recv().await.unwrap_or(Ok(())) }) + } + + /// What this machine's leads still owe their subagents on `machine`, or on every + /// machine: a cancel, interrupt or settle that could not reach it, and the word that a + /// report was taken. + pub(super) fn send_remote_child_work(&mut self, machine: Option<&str>, cx: &mut HostCx) { + let due: Vec<(String, RemoteChild)> = self + .sessions + .iter() + .flat_map(|meta| { + meta.remote_children + .iter() + .filter(|child| { + machine.is_none_or(|machine| child.machine == machine) + && child.state != RemoteChildState::MachineLeft + && (child.pending.is_some() || child.report_taken_unsent) + }) + .map(|child| (meta.id.clone(), child.clone())) + }) + .collect(); + for (lead, child) in due { + if child.report_taken_unsent + && let Some(report) = child.report_taken.clone() + { + self.send_report_taken(&lead, &child, report, cx); + } + if let Some(op) = child.pending { + self.send_remote_child_op(&lead, &child, op, cx, |_| {}); + } + } + } + + fn send_report_taken( + &mut self, + lead: &str, + child: &RemoteChild, + report: String, + cx: &mut HostCx, + ) { + let lead = lead.to_owned(); + let (machine, thread) = (child.machine.clone(), child.thread_id.clone()); + self.call_machine( + &child.machine, + Some(format!("taken:{machine}:{thread}:{report}")), + MachineRequest::ReportTaken { + child_thread_id: thread.clone(), + }, + false, + cx, + move |state, answer, cx| { + // Answered either way, the other machine has nothing more to keep for it. + let heard = match &answer { + Ok(_) => true, + Err(error) => error.code == "out_of_scope", + }; + if heard { + state.change_meta(&lead, cx, |meta| { + for child in &mut meta.remote_children { + if child.machine == machine + && child.thread_id == thread + && child.report_taken.as_deref() == Some(report.as_str()) + { + child.report_taken_unsent = false; + } + } + }); + } + }, + ); + } + + /// Send `op` for `child` to its machine, and tell `answered` how it went: carried out + /// or kept for when that machine can be reached, or refused. + fn send_remote_child_op( + &mut self, + lead: &str, + child: &RemoteChild, + op: RemoteChildOp, + cx: &mut HostCx, + answered: impl FnOnce(Result<(), ProtocolError>) + Send + 'static, + ) { + let (tool, args) = match op { + RemoteChildOp::Cancel | RemoteChildOp::Interrupt => ( + "control_thread", + serde_json::json!({ + "changes": [{ + "thread_id": child.thread_id, + "op": if op == RemoteChildOp::Cancel { "cancel" } else { "interrupt" }, + }], + }), + ), + RemoteChildOp::Settle => ( + "update_threads", + serde_json::json!({ + "changes": [{ "thread_id": child.thread_id, "op": "settle" }], + }), + ), + }; + let request = MachineRequest::Control { + caller: self.machine_caller(lead, None), + tool: tool.into(), + args, + }; + let lead = lead.to_owned(); + let (machine, thread) = (child.machine.clone(), child.thread_id.clone()); + self.call_machine( + &child.machine, + Some(format!("op:{machine}:{thread}")), + request, + false, + cx, + move |state, answer, cx| { + let result = answer.as_ref().ok().and_then(|response| match response { + MachineResponse::Control(value) => Some(value["results"][0].clone()), + _ => None, + }); + let refused = match (result.as_ref(), &answer) { + (Some(result), _) if result["outcome"] == "applied" => { + state.remote_child_done(&lead, &machine, &thread, op, cx); + None + } + // The other machine will not do it, now or later: nothing is kept. + (Some(result), _) => Some(ProtocolError { + code: "refused".into(), + message: result["reason"].as_str().unwrap_or_default().to_owned(), + }), + (None, Err(error)) if error.code != MACHINE_UNREACHABLE => Some(error.clone()), + (None, Ok(other)) => Some(ProtocolError { + code: "unexpected_reply".into(), + message: format!("the machine answered {other:?}"), + }), + // Kept, and sent again on the next contact with that machine. + (None, Err(_)) => None, + }; + if refused.is_some() { + state.change_meta(&lead, cx, |meta| { + for child in &mut meta.remote_children { + if child.machine == machine + && child.thread_id == thread + && child.pending == Some(op) + { + child.pending = None; + } + } + }); + } + answered(refused.map_or(Ok(()), Err)); + }, + ); + } + + /// Record on `lead` the watch `answer` says `info`'s machine keeps for it. + fn watching_elsewhere( + &mut self, + lead: &str, + info: &MachineInfo, + answer: &serde_json::Value, + events: Vec, + cx: &mut HostCx, + ) { + let (Some(id), Some(threads)) = (answer["id"].as_str(), answer["thread_ids"].as_array()) + else { + return; + }; + let thread_ids: Vec = threads + .iter() + .filter_map(|id| id.as_str().map(str::to_owned)) + .collect(); + let watch = ControlWatch { + id: id.to_owned(), + thread_ids: thread_ids.clone(), + events: events.into_iter().collect(), + space: None, + machine: Some(info.id.clone()), + }; + let mut added = false; + self.change_meta(lead, cx, |meta| { + if !meta + .control_watches + .iter() + .any(|held| held.id == watch.id && held.machine == watch.machine) + { + meta.control_watches.push(watch); + added = true; + } + }); + if added { + for target in &thread_ids { + self.audit_elsewhere( + lead, + info, + target, + action::NOTIFY_WHEN, + Some(id.to_owned()), + cx, + ); + } + } + } + + /// `lead` no longer keeps `watch`, which a machine of its group keeps for it: that + /// machine drops it when it can be reached now, and otherwise its firing finds no + /// watch here and is dropped then. + pub(in crate::app) fn unwatch_on_machine( + &mut self, + lead: &str, + watch: ControlWatch, + cx: &mut HostCx, + ) { + let Some(machine) = watch.machine.clone() else { + return; + }; + let request = MachineRequest::Control { + caller: self.machine_caller(lead, None), + tool: "cancel_notify".into(), + args: serde_json::json!({ "ids": [watch.id] }), + }; + self.call_machine(&machine, None, request, true, cx, |_, _, _| {}); + } + + /// Thread `thread` here as the other machine is told of it. + fn machine_caller(&self, thread: &str, request_id: Option) -> MachineCaller { + let meta = self.current_meta(thread); + MachineCaller { + thread_id: thread.to_owned(), + title: meta.map(|meta| meta.title.clone()).unwrap_or_default(), + request_id, + } + } + + /// The text a thread on `peer` sends a thread here: a report, approval request or + /// question of the subagent it started for that thread, or the firing of a watch that + /// thread put on it. + pub(super) fn receive_callback( + &mut self, + peer: &MachinePeer, + callback: Callback, + cx: &mut HostCx, + ) -> Result { + let out_of_scope = || { + Err(ProtocolError::out_of_scope( + "no thread here waits on that thread of yours", + )) + }; + let Some(lead) = self + .find_meta(&callback.thread_id) + .filter(|meta| meta.archived_at.is_none()) + else { + return out_of_scope(); + }; + let child = lead + .remote_children + .iter() + .find(|child| child.machine == peer.id && child.thread_id == callback.from_thread_id) + .cloned(); + // Its message names the thread as this machine names a thread there. + let text = + tcode_core::notice::on_machine(&callback.text, &callback.from_thread_id, &peer.id); + if let Some(id) = &callback.watch { + let watched = lead.control_watches.iter().any(|watch| { + watch.id == *id + && watch.machine.as_deref() == Some(peer.id.as_str()) + && watch.thread_ids.contains(&callback.from_thread_id) + }); + if !watched { + return out_of_scope(); + } + let space = lead + .control_watches + .iter() + .find(|watch| watch.id == *id) + .and_then(|watch| watch.space.clone()); + self.change_meta(&lead.id, cx, |meta| { + for watch in &mut meta.control_watches { + if watch.id == *id && watch.machine.as_deref() == Some(peer.id.as_str()) { + watch + .thread_ids + .retain(|thread| *thread != callback.from_thread_id); + } + } + meta.control_watches + .retain(|watch| !watch.thread_ids.is_empty()); + }); + let mut watch_cx = cx.clone(); + watch_cx.space = space; + self.deliver_orchestrate_callback_to_parent(&lead.id, text, &mut watch_cx); + return Ok(MachineResponse::Done); + } + let Some(child) = child else { + return out_of_scope(); + }; + let Some(report) = callback.report else { + // A subagent archived or deleted there says only that it will not report. + if let Some(state) = callback.state { + let now = cx.clock().unix_secs(); + self.change_meta(&lead.id, cx, |meta| { + for kept in &mut meta.remote_children { + if kept.machine == peer.id && kept.thread_id == child.thread_id { + kept.state = state; + kept.updated_at = now; + } + } + }); + } + if !text.is_empty() { + self.deliver_orchestrate_callback_to_parent(&lead.id, text, cx); + } + return Ok(MachineResponse::Done); + }; + if child.report_taken.as_deref() == Some(report.as_str()) { + // Its lead took it before: the other machine has yet to hear so. + self.change_meta(&lead.id, cx, |meta| { + for kept in &mut meta.remote_children { + if kept.machine == peer.id && kept.thread_id == child.thread_id { + kept.report_taken_unsent = true; + } + } + }); + self.send_remote_child_work(Some(&peer.id), cx); + return Ok(MachineResponse::Done); + } + let remote = Some((peer.id.clone(), report)); + let queued = self.resident(&lead.id).is_some_and(|session| { + session + .queue + .iter() + .flat_map(|message| &message.reports) + .chain( + session + .pending_steers + .iter() + .flat_map(|steer| &steer.reports), + ) + .any(|handover| { + handover.child == callback.from_thread_id && handover.remote == remote + }) + }); + if queued { + return Ok(MachineResponse::Done); + } + let now = cx.clock().unix_secs(); + self.change_meta(&lead.id, cx, |meta| { + for kept in &mut meta.remote_children { + if kept.machine == peer.id && kept.thread_id == child.thread_id { + if let Some(state) = callback.state { + kept.state = state; + } + kept.title = callback.from_title.clone(); + kept.updated_at = now; + } + } + }); + self.deliver_callback( + &lead.id, + text.clone(), + Some(ReportHandover { + child: callback.from_thread_id, + text, + remote, + }), + cx, + ); + Ok(MachineResponse::Done) + } + + /// The lead's harness took `reports`, or the user dropped them: the machines of those + /// that came from another machine hear so. + pub(in crate::app) fn reports_taken(&mut self, reports: &[ReportHandover], cx: &mut HostCx) { + let machines: BTreeSet = reports + .iter() + .filter_map(|report| report.remote.as_ref().map(|(machine, _)| machine.clone())) + .collect(); + for machine in machines { + self.send_remote_child_work(Some(&machine), cx); + } + } +} + +/// `machine` as a member of this machine's group, other than this machine. +async fn member(link: &MachineLink, machine: &str) -> Result { + let machines = link.machines(false).await.map_err(no_group)?; + let info = machines + .into_iter() + .find(|info| info.id == machine) + .ok_or_else(|| { + format!( + "refused: {machine} is not a machine of this machine's group; list_machines \ + lists them" + ) + })?; + if info.this_machine { + return Err(format!( + "{machine} is this machine: omit machine to run the call here" + )); + } + Ok(info) +} + +fn no_group(error: ProtocolError) -> String { + if error.code == NO_GROUP { + "refused: this machine is in no group".into() + } else { + error.message + } +} diff --git a/crates/runtime/src/app/machines/tests.rs b/crates/runtime/src/app/machines/tests.rs new file mode 100644 index 000000000..14a162e82 --- /dev/null +++ b/crates/runtime/src/app/machines/tests.rs @@ -0,0 +1,698 @@ +//! Two machines of a group, each a host as `spawn_host` starts it on a store of its own, +//! with `tcode_control` served and its harness played, joined over the group's real +//! transport on loopback (`real_group`). +use agent::{ItemContent, ItemStatus, SessionCommand, SessionOptions, ThreadItem}; +use tcode_client::machines::MACHINE_REFUSES; +use tcode_core::control::RemoteChildOp; +use tcode_protocol::{Command, EventEnvelope, MachineCaller, ServerEvent, Subscription, Topic}; + +use super::*; +use crate::app::test_support::rpc; +use crate::app::{ScriptedProvider, scripted_provider}; +use crate::pipe::HostServices; + +const LAPTOP_PROJECT: &str = "laptop-project"; + +struct Index { + link: tcode_client::HostLink, + events: smol::channel::Receiver, + threads: HashMap, +} + +impl Index { + /// What client `link` shows of its host's index. + fn of(link: tcode_client::HostLink) -> Self { + let events = link.events(); + link.subscribe(Subscription { + known_index: None, + topic: Topic::Index, + after: None, + }) + .unwrap(); + Self { + link, + events, + threads: HashMap::new(), + } + } + + /// The thread `id` once it is listed as `check` wants it. + fn thread(&mut self, id: &str, check: impl Fn(&SessionMeta) -> bool) -> SessionMeta { + self.until(|threads| threads.get(id).is_some_and(&check)); + self.threads[id].clone() + } + + /// Show thread `id`, as a client that selects it does, once its log has come. + fn show(&mut self, id: &str) { + for topic in [ + Topic::SessionStatus { + session_id: id.into(), + }, + Topic::SessionEvents { + session_id: id.into(), + }, + ] { + self.link + .subscribe(Subscription { + known_index: None, + topic, + after: None, + }) + .unwrap(); + } + loop { + let envelope = self.events.recv_blocking().expect("the host stopped"); + let shown = matches!( + (&envelope.topic, &envelope.event), + (Topic::SessionEvents { session_id }, ServerEvent::SessionSnapshot { .. }) + if session_id == id + ); + self.apply(envelope); + if shown { + return; + } + } + } + + fn until(&mut self, check: impl Fn(&HashMap) -> bool) { + while !check(&self.threads) { + let envelope = self.events.recv_blocking().expect("the host stopped"); + self.apply(envelope); + } + } + + fn apply(&mut self, envelope: EventEnvelope) { + { + match envelope.event { + ServerEvent::IndexSnapshot(snapshot) => { + self.threads = snapshot + .sessions + .into_iter() + .map(|meta| (meta.id.clone(), meta)) + .collect(); + } + ServerEvent::IndexUpsertSession(meta) => { + self.threads.insert(meta.id.clone(), *meta); + } + ServerEvent::IndexRemoveSession { session_id } => { + self.threads.remove(&session_id); + } + _ => {} + } + } + } +} + +/// The next command the played harness is sent that a test plays; the usage reads a +/// harness answers on its own are answered on the way. +fn next_command(provider: &ScriptedProvider) -> SessionCommand { + loop { + match provider + .commands + .recv_blocking() + .expect("the host holds the provider") + { + SessionCommand::ReadAccountUsage { reply } => { + let _ = reply.try_send(Err("the played harness has no account".into())); + } + other => return other, + } + } +} + +/// The next turn the harness is sent, taken and begun as an adapter does: its text. +fn begin_turn(provider: &ScriptedProvider, turn_id: &str) -> String { + loop { + if let SessionCommand::SendTurn { + delivery_id, text, .. + } = next_command(provider) + { + play( + provider, + [ + AgentEvent::TurnAccepted { delivery_id }, + AgentEvent::TurnStarted { + turn_id: turn_id.into(), + }, + ], + ); + return text; + } + } +} + +fn play(provider: &ScriptedProvider, events: impl IntoIterator) { + for event in events { + provider.events.try_send(event).unwrap(); + } +} + +fn completed(turn_id: &str) -> AgentEvent { + AgentEvent::TurnCompleted { + turn_id: turn_id.into(), + status: TurnStatus::Completed, + usage: None, + } +} + +/// The subagent's `report_result` call as its transcript records it. +fn reported(id: &str, text: &str) -> AgentEvent { + AgentEvent::ItemCompleted(ThreadItem { + id: id.into(), + parent_item_id: None, + content: ItemContent::ToolCall { + image_reads: Vec::new(), + name: "mcp__tcode_control__report_result".into(), + input: serde_json::json!({ "text": text }), + output: Some("{\"ok\":true}".into()), + status: ItemStatus::Completed, + family: None, + }, + }) +} + +/// The `tcode_control` server a thread's harness was given at launch, as the harness +/// reaches it. +struct Tools { + url: String, + token: String, + session: Option, +} + +impl Tools { + fn connect(options: &SessionOptions) -> Self { + let registration = options + .mcp_servers + .iter() + .find(|server| server.name == agent::McpRegistration::SERVER_NAME_CONTROL) + .expect("the harness was given tcode_control"); + let (url, token) = (registration.url.clone(), registration.bearer_token.clone()); + let (_, session) = rpc( + &url, + &token, + None, + serde_json::json!({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","capabilities":{},"clientInfo":{"name":"played-harness","version":"1"}}}), + ); + rpc( + &url, + &token, + session.as_deref(), + serde_json::json!({"jsonrpc":"2.0","method":"notifications/initialized"}), + ); + Self { + url, + token, + session, + } + } + + fn listed(&self) -> Vec { + let (listed, _) = rpc( + &self.url, + &self.token, + self.session.as_deref(), + serde_json::json!({"jsonrpc":"2.0","id":2,"method":"tools/list"}), + ); + listed["result"]["tools"] + .as_array() + .unwrap() + .iter() + .map(|tool| tool["name"].as_str().unwrap().to_owned()) + .collect() + } + + fn call(&self, tool: &str, arguments: serde_json::Value) -> Result { + let (reply, _) = rpc( + &self.url, + &self.token, + self.session.as_deref(), + serde_json::json!({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":tool,"arguments":arguments}}), + ); + if let Some(error) = reply.get("error") { + return Err(error["message"].as_str().unwrap_or_default().to_owned()); + } + let text = reply["result"]["content"][0]["text"] + .as_str() + .unwrap_or_default() + .to_owned(); + if reply["result"]["isError"] == true { + Err(text) + } else { + Ok(serde_json::from_str(&text).unwrap()) + } + } +} + +/// A machine of a real group over loopback, its host given `tcode_control` and a played +/// harness, and what its client shows of its index. +struct Site { + machine: super::real_group::Machine, + harness: ScriptedProvider, + index: Index, +} + +fn site(dir: &super::real_group::TestDir, name: &str) -> Site { + let harness = scripted_provider(ProviderKind::Codex); + let mut services = HostServices { + provider_launcher: harness.launcher.clone(), + ..Default::default() + }; + services.start_mcp_servers(false); + let machine = super::real_group::Machine::start_with(&dir.0, name, services); + let index = Index::of(machine.client.clone()); + Site { + machine, + harness, + index, + } +} + +/// A project `project` on the store a machine in `dir` opens, with thread `thread` in it +/// when one is named. +fn seed_real(dir: &super::real_group::TestDir, project: &str, thread: Option<&str>) { + let store = tcode_services::store::SessionStore::open_at(dir.0.join("store")).unwrap(); + let root = dir.0.join(project); + std::fs::create_dir_all(&root).unwrap(); + let mut seeded = Project::from_root(root.clone()); + seeded.id = project.into(); + store.upsert_project(&seeded).unwrap(); + if let Some(thread) = thread { + let mut meta = SessionMeta::new(ProviderKind::Codex, root, None); + meta.id = thread.into(); + meta.title = "Lead".into(); + meta.project_id = Some(project.into()); + store.upsert_meta(&meta).unwrap(); + } +} + +/// The desk, whose thread `lead` works with the laptop, and the laptop, with a project and +/// a thread of its own, in one group over the real transport; the lead's harness has run +/// one turn and was given its tools. +struct Pair { + desk: Site, + laptop: Site, + laptop_id: String, + tools: Tools, + lead_options: SessionOptions, + _dirs: (super::real_group::TestDir, super::real_group::TestDir), +} + +fn pair(tag: &str) -> Pair { + use tcode_protocol::GroupAction; + let desk_dir = super::real_group::TestDir::new(&format!("{tag}-desk")); + let laptop_dir = super::real_group::TestDir::new(&format!("{tag}-laptop")); + seed_real(&desk_dir, "desk-project", Some("lead")); + seed_real(&laptop_dir, LAPTOP_PROJECT, Some("laptop-own")); + let mut desk = site(&desk_dir, "Desk"); + let laptop = site(&laptop_dir, "Laptop"); + desk.machine.group(GroupAction::Create { + name: "Home".into(), + }); + laptop.machine.group(GroupAction::Join { + link: desk + .machine + .endpoint + .as_ref() + .unwrap() + .new_invitation() + .url(), + address: Some("127.0.0.1".into()), + }); + let laptop_id = laptop.machine.id(); + desk.index.show("lead"); + desk.machine + .command(Command::SendTurn { + session_id: "lead".into(), + text: "Work with the laptop".into(), + attachment_paths: Vec::new(), + }) + .unwrap(); + let lead_options = desk.harness.launches.recv_blocking().unwrap(); + begin_turn(&desk.harness, "lead-1"); + play(&desk.harness, [completed("lead-1")]); + let tools = Tools::connect(&lead_options); + Pair { + desk, + laptop, + laptop_id, + tools, + lead_options, + _dirs: (desk_dir, laptop_dir), + } +} + +fn start_subagent(pair: &Pair, request_id: &str) -> Result { + pair.tools.call( + "start_thread_on_machine", + serde_json::json!({ + "machine": pair.laptop_id, + "project_id": LAPTOP_PROJECT, + "provider": "codex", + "subagent": true, + "title": "Check the laptop build", + "message": "Build it here and report what fails.", + "request_id": request_id, + }), + ) +} + +/// The desk's lead as its own `get_thread` shows it. +fn lead_lineage(tools: &Tools) -> serde_json::Value { + tools + .call("get_thread", serde_json::json!({ "thread_id": "self" })) + .unwrap()["lineage"] + .clone() +} + +fn children(tools: &Tools) -> Vec { + lead_lineage(tools)["remote_children"] + .as_array() + .cloned() + .unwrap_or_default() +} + +/// A thread started on another machine is an ordinary root thread there that names its +/// starter, once per request; a machine whose threads may not reach the group is not +/// offered the tool and is refused, and a machine that takes no threads leaves nothing on +/// the caller's side. +#[test] +fn a_thread_started_on_another_machine_is_a_root_thread_there_once_per_request() { + use tcode_protocol::GroupAction; + let mut pair = pair("start"); + assert!( + pair.tools + .listed() + .contains(&"start_thread_on_machine".to_owned()) + ); + + let started = start_subagent(&pair, "build-1").unwrap(); + let child = started["thread_id"].as_str().unwrap().to_owned(); + assert_eq!(started["created"], true); + assert_eq!(started["machine"]["id"], pair.laptop_id.as_str()); + assert_eq!( + started["link"], + format!("tcode-thread://{child}@{}", pair.laptop_id).as_str() + ); + let there = pair.laptop.index.thread(&child, |_| true); + assert_eq!(there.parent_session_id, None); + let parent = there.remote_parent.clone().unwrap(); + assert_eq!( + (parent.machine, parent.thread_id.as_str()), + (pair.desk.machine.id(), "lead") + ); + let by = there.started_by.clone().unwrap(); + assert_eq!( + (by.machine, by.thread_id.as_str(), by.request_id.as_str()), + (Some(pair.desk.machine.id()), "lead", "build-1") + ); + + let again = start_subagent(&pair, "build-1").unwrap(); + assert_eq!(again["thread_id"], child.as_str()); + assert_eq!(again["created"], false); + let listed = pair + .tools + .call( + "list_threads", + serde_json::json!({ "machine": pair.laptop_id, "scope": "host" }), + ) + .unwrap(); + let started_there = listed["threads"] + .as_array() + .unwrap() + .iter() + .filter(|thread| thread["started_by"]["request_id"] == "build-1") + .count(); + assert_eq!(started_there, 1); + let kept = children(&pair.tools); + assert_eq!(kept.len(), 1); + assert_eq!(kept[0]["thread_id"], child.as_str()); + assert_eq!(kept[0]["state"], "running"); + + pair.laptop + .machine + .group(GroupAction::SetAcceptThreads(false)); + let refusal = start_subagent(&pair, "build-2").unwrap_err(); + assert!(refusal.contains(MACHINE_REFUSES), "{refusal}"); + assert_eq!(children(&pair.tools).len(), 1); + pair.laptop + .machine + .group(GroupAction::SetAcceptThreads(true)); + + pair.desk + .machine + .command(Command::PatchSettings { + patch: tcode_core::settings::SettingsPatch::ControlMachines(false), + }) + .unwrap(); + let reconnected = Tools::connect(&pair.lead_options); + let listed = reconnected.listed(); + assert!(!listed.contains(&"start_thread_on_machine".to_owned())); + assert!(!listed.contains(&"list_machines".to_owned())); + assert!( + reconnected + .call( + "list_projects", + serde_json::json!({ "machine": pair.laptop_id }) + ) + .unwrap_err() + .starts_with("refused") + ); +} + +/// A report made while the lead's machine is out of reach reaches the lead once that +/// machine is back, and the subagent's machine keeps it until the lead's harness took it. +#[test] +fn a_report_made_while_the_lead_s_machine_is_unreachable_reaches_the_lead_when_it_returns() { + let mut pair = pair("report"); + let started = start_subagent(&pair, "build-1").unwrap(); + let child = started["thread_id"].as_str().unwrap().to_owned(); + let brief = begin_turn(&pair.laptop.harness, "child-1"); + assert!(brief.starts_with("Build it here and report what fails.")); + pair.desk.machine.stop_hosting(); + + play( + &pair.laptop.harness, + [ + reported("report-1", "Two tests fail on the laptop."), + completed("child-1"), + ], + ); + pair.laptop.index.thread(&child, |meta| { + meta.expectation + .as_ref() + .is_some_and(|expectation| expectation.undelivered.is_some()) + }); + + pair.desk.machine.start_hosting(); + let taken = begin_turn(&pair.desk.harness, "lead-2"); + assert!(taken.contains("Two tests fail on the laptop."), "{taken}"); + assert!( + taken.contains(&format!("thread {child}@{} (", pair.laptop_id)), + "{taken}" + ); + pair.laptop.index.thread(&child, |meta| { + meta.expectation + .as_ref() + .is_some_and(|expectation| expectation.undelivered.is_none()) + }); + let lead = pair.desk.index.thread("lead", |meta| { + meta.remote_children + .iter() + .any(|kept| kept.report_taken.is_some() && !kept.report_taken_unsent) + }); + assert_eq!(lead.remote_children[0].state, RemoteChildState::Reported); +} + +/// A thread on another machine may not ask for what is not a machine's to ask, nor answer +/// the approvals of a thread it did not start. +#[test] +fn a_machine_is_refused_what_lies_outside_what_machines_may_ask() { + let pair = pair("refused"); + let caller = || MachineCaller { + thread_id: "lead".into(), + title: "Lead".into(), + request_id: None, + }; + for (tool, args) in [ + ( + "delete_threads", + serde_json::json!({ "thread_ids": ["laptop-own"] }), + ), + ( + "git", + serde_json::json!({ "thread_id": "laptop-own", "op": "push" }), + ), + ( + "respond_approval", + serde_json::json!({ "thread_id": "laptop-own", "cancel": true }), + ), + ] { + let answer = smol::block_on(pair.desk.machine.link.call( + &pair.laptop_id, + MachineRequest::Control { + caller: caller(), + tool: tool.into(), + args, + }, + )); + assert_eq!( + answer.map_err(|error| error.code), + Err("refused".to_owned()), + "{tool}" + ); + } + + // Of the laptop's threads the lead reaches only the one its machine started there: + // another is answered as no thread at all. + let child = start_subagent(&pair, "build-1").unwrap()["thread_id"] + .as_str() + .unwrap() + .to_owned(); + begin_turn(&pair.laptop.harness, "child-1"); + let on_laptop = |tool: &str, mut args: serde_json::Value| { + args["machine"] = pair.laptop_id.as_str().into(); + pair.tools.call(tool, args) + }; + let item = |answer: serde_json::Value| { + let result = &answer["results"][0]; + ( + result["outcome"].as_str().unwrap().to_owned(), + result["reason"].as_str().map(str::to_owned), + ) + }; + for (tool, args) in [ + ( + "get_thread", + serde_json::json!({ "thread_id": "laptop-own" }), + ), + ("outline", serde_json::json!({ "thread_id": "laptop-own" })), + ( + "respond_input", + serde_json::json!({ "thread_id": "laptop-own", "answers": {} }), + ), + ] { + let refusal = on_laptop(tool, args).unwrap_err(); + assert!(refusal.contains("unknown thread"), "{tool}: {refusal}"); + } + let message = |thread: &str| serde_json::json!({ "thread_ids": [thread], "text": "Status?", "mode": "queue" }); + let interrupt = |thread: &str| serde_json::json!({ "changes": [{ "thread_id": thread, "op": "interrupt" }] }); + for (tool, args) in [ + ("send_message", message("laptop-own")), + ("control_thread", interrupt("laptop-own")), + ] { + assert_eq!( + item(on_laptop(tool, args).unwrap()), + ("skipped".to_owned(), Some("unknown_thread".to_owned())), + "{tool}" + ); + } + let listed: Vec = on_laptop("list_threads", serde_json::json!({ "scope": "host" })) + .unwrap()["threads"] + .as_array() + .unwrap() + .iter() + .map(|thread| thread["id"].as_str().unwrap().to_owned()) + .collect(); + assert_eq!(listed, std::slice::from_ref(&child)); + + on_laptop("get_thread", serde_json::json!({ "thread_id": child })).unwrap(); + on_laptop("outline", serde_json::json!({ "thread_id": child })).unwrap(); + assert_eq!( + item(on_laptop("send_message", message(&child)).unwrap()).0, + "applied" + ); + assert_eq!( + item(on_laptop("control_thread", interrupt(&child)).unwrap()).0, + "applied" + ); +} + +/// Cancelling one's subagent on a machine that cannot be reached is kept, and reaches it +/// when the machine is back. +#[test] +fn a_cancel_issued_while_the_machine_is_unreachable_reaches_it_when_it_returns() { + let mut pair = pair("cancel"); + let child = start_subagent(&pair, "build-1").unwrap()["thread_id"] + .as_str() + .unwrap() + .to_owned(); + begin_turn(&pair.laptop.harness, "child-1"); + pair.laptop.machine.stop_hosting(); + + let cancelled = pair + .tools + .call( + "control_thread", + serde_json::json!({ + "machine": pair.laptop_id, + "changes": [{ "thread_id": child, "op": "cancel" }], + }), + ) + .unwrap(); + assert_eq!(cancelled["results"][0]["outcome"], "applied"); + assert!( + cancelled["results"][0]["reason"] + .as_str() + .unwrap() + .starts_with("queued") + ); + assert_eq!(children(&pair.tools)[0]["pending"], "cancel"); + + pair.laptop.machine.start_hosting(); + pair.laptop + .index + .thread(&child, |meta| meta.cancelled_at.is_some()); + pair.desk.index.thread("lead", |meta| { + meta.remote_children + .iter() + .any(|kept| kept.state == RemoteChildState::Cancelled && kept.pending.is_none()) + }); +} + +/// A client stops or cancels a lead's subagent on another machine through the lead's +/// host, and is refused for a thread the lead did not start there. +#[test] +fn a_client_reaches_a_subagent_on_another_machine_through_its_lead_s_host() { + let mut pair = pair("client-op"); + let child = start_subagent(&pair, "build-1").unwrap()["thread_id"] + .as_str() + .unwrap() + .to_owned(); + begin_turn(&pair.laptop.harness, "child-1"); + let laptop_id = pair.laptop_id.clone(); + let op = |thread: &str, op| Command::ControlRemoteChild { + session_id: "lead".into(), + machine: laptop_id.clone(), + thread_id: thread.into(), + op, + }; + assert_eq!( + pair.desk + .machine + .command(op("laptop-own", RemoteChildOp::Cancel)) + .map_err(|error| error.code), + Err("not_a_remote_child".to_owned()) + ); + + pair.desk + .machine + .command(op(&child, RemoteChildOp::Interrupt)) + .unwrap(); + while !matches!( + next_command(&pair.laptop.harness), + SessionCommand::Interrupt + ) {} + + pair.desk + .machine + .command(op(&child, RemoteChildOp::Cancel)) + .unwrap(); + pair.laptop + .index + .thread(&child, |meta| meta.cancelled_at.is_some()); + pair.desk.index.thread("lead", |meta| { + meta.remote_children + .first() + .is_some_and(|kept| kept.state == RemoteChildState::Cancelled && kept.pending.is_none()) + }); +} diff --git a/crates/runtime/src/app/machines/threads.rs b/crates/runtime/src/app/machines/threads.rs new file mode 100644 index 000000000..d22b80afd --- /dev/null +++ b/crates/runtime/src/app/machines/threads.rs @@ -0,0 +1,267 @@ +//! Threads one machine of the group starts on another, and the replies that +//! come back to the machine that started them. +use control_mcp::ControlOp; +use control_mcp::params::RunOp; +use tcode_core::control::ControlScope; +use tcode_protocol::{MachineCaller, MachineRequest, MachineResponse}; + +use super::MachinePeer; +use crate::app::control::{Answer, Caller, RemoteCaller}; +use crate::app::*; + +fn refused(message: impl Into) -> ProtocolError { + ProtocolError { + code: "refused".into(), + message: message.into(), + } +} + +fn failed(message: String) -> ProtocolError { + ProtocolError { + code: "control_failed".into(), + message, + } +} + +/// What another machine's thread brings about here is done under the host's authority and +/// as an agent's, never the user's: it answers no approval and is no human activity. +fn agent_cx(cx: &HostCx) -> HostCx { + let mut cx = cx.clone(); + cx.principal = tcode_protocol::Principal::Full; + cx.origin = Some(MessageOrigin::Agent); + cx.author = None; + cx.space = None; + cx +} + +impl AppState { + /// Run one `tcode_control` tool here for `caller`, a thread on `peer`. The transport + /// has let the request through this machine's switches; what a machine may ask is + /// decided here. + pub(super) fn machine_control( + &mut self, + peer: &MachinePeer, + caller: MachineCaller, + tool: String, + args: serde_json::Value, + cx: &mut HostCx, + ) -> HostTask> { + let answer = (|| { + if !self.settings.control.enabled { + return Err(refused( + "tcode_control is turned off in Settings → Control on this machine", + )); + } + let op = ControlOp::parse(&tool, args).map_err(failed)?; + let caller = Caller { + thread_id: caller.thread_id, + project_id: None, + space: None, + machine: Some(RemoteCaller { + peer: peer.clone(), + title: caller.title, + }), + }; + let op = self.machine_may_ask(&caller, op)?; + self.authorize_control(&caller, &op).map_err(failed)?; + // Decided above: the call runs as a thread's call here would. + Ok(self.dispatch_control_op(&caller, op, &mut agent_cx(cx))) + })(); + let answer = match answer { + Ok(answer) => answer, + Err(error) => return cx.spawn_background(async move { Err(error) }), + }; + cx.spawn_background(async move { + let result = match answer { + Answer::Now(result) => result, + Answer::Later(task) => task.await, + }; + result.map(MachineResponse::Control).map_err(failed) + }) + } + + /// What a thread on another machine may ask of this one: listing projects and models, + /// starting threads, reading and writing to the threads its machine started here + /// (`open_to` confines the threads), and what a lead does for its own subagent. + /// The match names every tool, so one added later is refused until it is decided here. + fn machine_may_ask(&self, caller: &Caller, op: ControlOp) -> Result { + let name = op.tool_name(); + let not_for_machines = || { + Err(refused(format!( + "a thread on another machine may not ask for `{name}` here" + ))) + }; + match op { + ControlOp::ListThreads(mut params) => { + // A caller elsewhere has no project here. + params.scope.get_or_insert(ControlScope::Host); + Ok(ControlOp::ListThreads(params)) + } + op @ (ControlOp::ListProjects(_) + | ControlOp::GetThread(_) + | ControlOp::Outline(_) + | ControlOp::Read(_) + | ControlOp::SearchInItem(_) + | ControlOp::ListProviders(_) + | ControlOp::StartThread(_) + | ControlOp::SendMessage(_) + | ControlOp::NotifyWhen(_) + | ControlOp::CancelNotify(_) + | ControlOp::RespondInput(_)) => Ok(op), + ControlOp::ControlThread(params) => { + if let Some(change) = params.changes.iter().find(|change| { + !matches!( + change.op, + RunOp::Interrupt + | RunOp::Cancel + | RunOp::SteerQueued { .. } + | RunOp::DropQueued { .. } + ) + }) { + return Err(refused(format!( + "a thread on another machine may only interrupt, cancel, steer a queued \ + message or drop one here; not {}", + serde_json::to_value(&change.op) + .ok() + .and_then(|op| match op { + serde_json::Value::String(name) => Some(name), + serde_json::Value::Object(map) => map.keys().next().cloned(), + _ => None, + }) + .unwrap_or_default() + ))); + } + Ok(ControlOp::ControlThread(params)) + } + ControlOp::RespondApproval(params) => { + if !self + .find_meta(¶ms.thread_id) + .is_some_and(|meta| self.own_subagent(caller, &meta)) + { + return Err(refused(format!( + "thread {} is not a subagent your thread started on this machine; its \ + approvals are the user's", + params.thread_id + ))); + } + Ok(ControlOp::RespondApproval(params)) + } + // Settling is what a lead does with its own subagent once it accepts the result. + ControlOp::UpdateThreads(params) => { + let own = params.changes.iter().all(|change| { + matches!(change.op, control_mcp::ThreadOp::Settle) + && self + .find_meta(&change.thread_id) + .is_some_and(|meta| self.own_subagent(caller, &meta)) + }); + if !own { + return not_for_machines(); + } + Ok(ControlOp::UpdateThreads(params)) + } + ControlOp::Search(_) + | ControlOp::FileHistory(_) + | ControlOp::GetGit(_) + | ControlOp::GetPullRequest(_) + | ControlOp::GetSettings(_) + | ControlOp::ReadTerminal(_) + | ControlOp::ReviewCandidates(_) + | ControlOp::SettleSelf(_) + | ControlOp::PullRequest(_) + | ControlOp::Git(_) + | ControlOp::CreateProject(_) + | ControlOp::MoveThread(_) + | ControlOp::ReportResult(_) + | ControlOp::Terminal(_) + | ControlOp::DeleteThreads(_) + | ControlOp::Rewind(_) + | ControlOp::PatchSettings(_) + | ControlOp::SetModelGuide(_) + | ControlOp::ListMachines(_) + | ControlOp::StartThreadOnMachine(_) => not_for_machines(), + } + } + + /// A [`MachineRequest::Callback`] or [`MachineRequest::ReportTaken`]: the + /// answer to something this machine sent `peer`. + pub(super) fn machine_reply( + &mut self, + peer: &MachinePeer, + request: MachineRequest, + cx: &mut HostCx, + ) -> HostTask> { + let host_cx = cx; + let cx = &mut agent_cx(host_cx); + let answer = match request { + MachineRequest::Callback { + thread_id, + from_thread_id, + from_title, + text, + report, + state, + watch, + } => self.receive_callback( + peer, + super::remote::Callback { + thread_id, + from_thread_id, + from_title, + text, + report, + state, + watch, + }, + cx, + ), + MachineRequest::ReportTaken { child_thread_id } => { + self.report_taken_by_lead(peer, &child_thread_id, cx) + } + other => Err(ProtocolError::out_of_scope(format!( + "{:?} is not a reply", + other.kind() + ))), + }; + host_cx.spawn_background(async move { answer }) + } + + /// `peer`'s lead took the report of `child_id`, a thread it started here: the report is + /// delivered. [`MachineRequest::ReportTaken`] does not say which report, so only one this + /// host has sent is taken; one kept from before a restart goes again first, and `peer` + /// answers that it took it. + fn report_taken_by_lead( + &mut self, + peer: &MachinePeer, + child_id: &str, + cx: &mut HostCx, + ) -> Result { + let Some(mut child) = self.find_meta(child_id).filter(|meta| { + meta.remote_parent + .as_ref() + .is_some_and(|parent| parent.machine == peer.id) + }) else { + return Err(ProtocolError::out_of_scope( + "no thread here was started by a thread on that machine", + )); + }; + let sent = self.machine_work.reports_sent.get(child_id).cloned(); + let Some(report) = child + .expectation + .as_ref() + .and_then(|expectation| expectation.undelivered_id.clone()) + .filter(|report| sent.as_ref() == Some(report)) + else { + return Ok(MachineResponse::Done); + }; + if let Some(expectation) = child.expectation.as_mut() { + expectation.undelivered = None; + expectation.undelivered_id = None; + } + child.updated_at = cx.clock().unix_secs(); + self.store_meta(child, cx); + self.machine_work + .queued_there + .remove(&super::leads::report_key(child_id, &report)); + Ok(MachineResponse::Done) + } +} diff --git a/crates/runtime/src/app/mod.rs b/crates/runtime/src/app/mod.rs index 03cf7553d..3b0d3348d 100644 --- a/crates/runtime/src/app/mod.rs +++ b/crates/runtime/src/app/mod.rs @@ -274,6 +274,7 @@ mod storage_pass; use history::{Hydration, SessionLog}; mod fork; mod lifecycle; +pub(crate) mod machines; mod options; mod orchestrate; mod plugins; @@ -407,6 +408,12 @@ pub struct AppState { space_scopes: HashMap>, space_policies: HashMap, space_policy_revisions: HashMap, + /// How this machine reaches the other machines of its group; `None` where the + /// composition has no transport for them. + machine_link: Option, + /// Projects moving to and from the other machines of the group. + moves: machines::moves::Moves, + machine_work: machines::MachineWork, space_archives_revision: Option, space_archives: HashMap, // Archive replies remain ordered after the last subscriber releases a projection. @@ -695,6 +702,9 @@ impl AppState { space_scopes: HashMap::new(), space_policies: HashMap::new(), space_policy_revisions: HashMap::new(), + machine_link: None, + moves: Default::default(), + machine_work: Default::default(), space_archives_revision: None, space_archives: HashMap::new(), space_archive_revisions: HashMap::new(), diff --git a/crates/runtime/src/app/orchestrate.rs b/crates/runtime/src/app/orchestrate.rs index e4896afdc..5316d6f1e 100644 --- a/crates/runtime/src/app/orchestrate.rs +++ b/crates/runtime/src/app/orchestrate.rs @@ -1,4 +1,5 @@ use super::*; +use tcode_core::control::RemoteParent; use tcode_core::notice::{ CHILD_REPORT_REMINDER, ORCHESTRATE_APPROVAL_ID_PHRASE, ORCHESTRATE_APPROVAL_PHRASE, ORCHESTRATE_FALLBACK_LABEL, ORCHESTRATE_QUESTION_ID_PHRASE, ORCHESTRATE_QUESTION_PHRASE, @@ -7,6 +8,22 @@ use tcode_core::notice::{ use tcode_core::project::ChildExpectation; use tcode_core::settlement::{AgentDelivery, AgentReport}; +/// The thread a child reports to: a thread here, or one on another machine of the group. +pub(super) enum Lead { + Here(String), + Elsewhere(RemoteParent), +} + +impl Lead { + pub(super) fn of(child: &SessionMeta) -> Option { + match (&child.remote_parent, &child.parent_session_id) { + (Some(parent), _) => Some(Self::Elsewhere(parent.clone())), + (None, Some(parent)) => Some(Self::Here(parent.clone())), + (None, None) => None, + } + } +} + /// Appended to every subagent's first message so the report contract reaches it /// regardless of what the thread that started it wrote. pub(super) const CHILD_REPORT_FOOTER: &str = "\n\n---\nThe tcode_control report_result tool is the only channel through which your work reaches the thread that started you as its subagent; it cannot see your transcript, and your own turns, waits, background tasks and wake-ups never reach it. When your work is complete, send your complete final report through it once, then end your turn. Make the report self-contained: for a discussion, give your reasoning, recommendations, disagreements, and open questions; for execution, include files changed and commands actually run with their outcomes. Include the evidence behind your conclusions. Only if the tool call fails, write that same complete report as your final message instead — it is sent back as the fallback."; @@ -155,11 +172,10 @@ impl AppState { self.mcp.visualize_registrations.contains_key(id), ), ]; - let control_instructions = self - .mcp - .control_registrations - .contains_key(id) - .then(|| control_mcp::instructions(meta.is_dispatched())); + let control_instructions = self.mcp.control_registrations.contains_key(id).then(|| { + let access = self.control_access(meta); + control_mcp::instructions(access.subagent, access.machines) + }); servers .into_iter() .filter(|(_, _, registered)| *registered) @@ -449,6 +465,7 @@ impl AppState { }); } } + self.settle_remote_children(parent_id, cx); result } @@ -603,23 +620,24 @@ impl AppState { } /// The child meta and its lead, when the child still owes or has owed a - /// report and both sides are current. - fn expectant_child(&self, child_id: &str) -> Option<(SessionMeta, String, ChildExpectation)> { + /// report and both sides are current as far as this machine knows. + fn expectant_child(&self, child_id: &str) -> Option<(SessionMeta, Lead, ChildExpectation)> { let child = self .sessions .iter() - .find(|meta| meta.id == child_id && meta.parent_session_id.is_some()) + .find(|meta| meta.id == child_id) .filter(|meta| meta.archived_at.is_none() && meta.cancelled_at.is_none())? .clone(); + let lead = Lead::of(&child)?; let expectation = child.expectation.clone()?; - let parent_id = child.parent_session_id.clone()?; - if !self - .find_meta(&parent_id) - .is_some_and(|meta| meta.archived_at.is_none()) + if let Lead::Here(parent_id) = &lead + && !self + .find_meta(parent_id) + .is_some_and(|meta| meta.archived_at.is_none()) { return None; } - Some((child, parent_id, expectation)) + Some((child, lead, expectation)) } /// A child's turn ended (or its background work did): decide whether the @@ -634,7 +652,7 @@ impl AppState { status: TurnStatus, cx: &mut HostCx, ) { - let Some((child, parent_id, mut expectation)) = self.expectant_child(child_id) else { + let Some((child, lead, mut expectation)) = self.expectant_child(child_id) else { return; }; let Some(resident) = self.resident(child_id) else { @@ -681,7 +699,7 @@ impl AppState { ); expectation.state = AgentReport::Reported; expectation.delivered_item = Some(item); - self.deliver_report_to_parent(child_id, &parent_id, text, expectation, cx); + self.deliver_report_to_parent(child_id, &lead, text, expectation, cx); return; } if !expectation.state.pending() { @@ -720,12 +738,12 @@ impl AppState { usage.as_ref(), ); expectation.state = AgentReport::Unreported; - self.deliver_report_to_parent(child_id, &parent_id, text, expectation, cx); + self.deliver_report_to_parent(child_id, &lead, text, expectation, cx); } /// The child can no longer deliver what it owes: its lead hears why, once. pub(super) fn fail_child_expectation(&mut self, child_id: &str, error: &str, cx: &mut HostCx) { - let Some((child, parent_id, mut expectation)) = self.expectant_child(child_id) else { + let Some((child, lead, mut expectation)) = self.expectant_child(child_id) else { return; }; if !expectation.state.pending() { @@ -742,7 +760,7 @@ impl AppState { usage.as_ref(), ); expectation.state = AgentReport::Failed; - self.deliver_report_to_parent(child_id, &parent_id, text, expectation, cx); + self.deliver_report_to_parent(child_id, &lead, text, expectation, cx); } pub(super) fn deliver_child_approval_callback( @@ -751,11 +769,11 @@ impl AppState { request_id: &str, cx: &mut HostCx, ) { - let Some(child) = self + let Some((child, lead)) = self .sessions .iter() - .find(|meta| meta.id == child_id && meta.parent_session_id.is_some()) - .cloned() + .find(|meta| meta.id == child_id) + .and_then(|meta| Some((meta.clone(), Lead::of(meta)?))) else { return; }; @@ -791,18 +809,21 @@ impl AppState { { return; } - let parent_id = child.parent_session_id.as_deref().unwrap(); let options = request.options.iter().map(|option| { serde_json::json!({ "id": option.id, "label": option.label, "kind": option.kind }) }).collect::>(); - let instruction = if self.settings.subagents.child_approval == ChildApprovalMode::Manual { - "The user answers it." - } else { - "You are the approver: answer with tcode_control respond_approval, passing this thread_id and approval_id with option: or cancel: true; reject anything outside the brief's scope." + let instruction = match (self.settings.subagents.child_approval, &lead) { + (ChildApprovalMode::Manual, _) => "The user answers it.", + (_, Lead::Here(_)) => { + "You are the approver: answer with tcode_control respond_approval, passing this thread_id and approval_id with option: or cancel: true; reject anything outside the brief's scope." + } + (_, Lead::Elsewhere(_)) => { + "You are the approver: answer with tcode_control respond_approval, passing this thread_id, the machine after its @ as machine, and approval_id with option: or cancel: true; reject anything outside the brief's scope." + } }; let text = format!( "{} {ORCHESTRATE_APPROVAL_PHRASE}{}{ORCHESTRATE_APPROVAL_ID_PHRASE}{}). Native options: {}. {}", - callback_header(child_id, &child.title), + callback_header(child_id, None, &child.title), approval_request_summary(&request), request.id, serde_json::to_string(&options).expect("approval options serialize"), @@ -810,7 +831,7 @@ impl AppState { ); let mut child_cx = cx.clone(); child_cx.space = self.turn_space_of(child_id).or(child_cx.space); - self.deliver_orchestrate_callback_to_parent(parent_id, text, &mut child_cx); + self.deliver_to_lead(&child, &lead, text, &mut child_cx); } /// A child's question goes to its lead, as an approval does; in Manual @@ -822,11 +843,11 @@ impl AppState { request_id: &str, cx: &mut HostCx, ) { - let Some(child) = self + let Some((child, lead)) = self .sessions .iter() - .find(|meta| meta.id == child_id && meta.parent_session_id.is_some()) - .cloned() + .find(|meta| meta.id == child_id) + .and_then(|meta| Some((meta.clone(), Lead::of(meta)?))) else { return; }; @@ -844,26 +865,41 @@ impl AppState { { return; } - let parent_id = child.parent_session_id.as_deref().unwrap(); let delivery = if pending.delivery.is_blocking() { "the child is blocked until it is answered" } else { "the child keeps working and reads the answer when it arrives; the question lapses when its turn ends" }; - let instruction = if self.settings.subagents.child_approval == ChildApprovalMode::Manual { - "The user answers it." - } else { - "You are the decider: answer with tcode_control respond_input, passing this thread_id and question_id with answers keyed by question id, a string (an option label or free text) for a single-choice question and an array of strings for a multi_select one, deciding from the brief and the user's instructions." + let instruction = match (self.settings.subagents.child_approval, &lead) { + (ChildApprovalMode::Manual, _) => "The user answers it.", + (_, Lead::Here(_)) => { + "You are the decider: answer with tcode_control respond_input, passing this thread_id and question_id with answers keyed by question id, a string (an option label or free text) for a single-choice question and an array of strings for a multi_select one, deciding from the brief and the user's instructions." + } + (_, Lead::Elsewhere(_)) => { + "You are the decider: answer with tcode_control respond_input, passing this thread_id, the machine after its @ as machine, and question_id with answers keyed by question id, a string (an option label or free text) for a single-choice question and an array of strings for a multi_select one, deciding from the brief and the user's instructions." + } }; let text = format!( "{} {ORCHESTRATE_QUESTION_PHRASE}{ORCHESTRATE_QUESTION_ID_PHRASE}{}; {delivery}{ORCHESTRATE_QUESTIONS_PHRASE}{}. {instruction}", - callback_header(child_id, &child.title), + callback_header(child_id, None, &child.title), pending.request_id, serde_json::to_string(&pending.questions).expect("questions serialize"), ); let mut child_cx = cx.clone(); child_cx.space = self.turn_space_of(child_id).or(child_cx.space); - self.deliver_orchestrate_callback_to_parent(parent_id, text, &mut child_cx); + self.deliver_to_lead(&child, &lead, text, &mut child_cx); + } + + /// A child's approval or question for its lead, wherever that is. One on another + /// machine hears it once, when it can be reached: a request lives only as long as the + /// child's provider does. + fn deliver_to_lead(&mut self, child: &SessionMeta, lead: &Lead, text: String, cx: &mut HostCx) { + match lead { + Lead::Here(parent_id) => { + self.deliver_orchestrate_callback_to_parent(parent_id, text, cx) + } + Lead::Elsewhere(parent) => self.send_callback_to_lead(child, parent, text, cx), + } } /// Deliver a child result into the orchestrator's current reasoning turn. @@ -887,14 +923,32 @@ impl AppState { fn deliver_report_to_parent( &mut self, child_id: &str, - parent_id: &str, + lead: &Lead, text: String, mut expectation: ChildExpectation, cx: &mut HostCx, ) { expectation.undelivered = Some(text.clone()); - self.set_child_expectation(child_id, Some(expectation), cx); - self.deliver_callback(parent_id, text, Some(child_id), cx); + match lead { + Lead::Here(parent_id) => { + self.set_child_expectation(child_id, Some(expectation), cx); + self.deliver_callback( + parent_id, + text.clone(), + Some(ReportHandover { + child: child_id.to_owned(), + text, + remote: None, + }), + cx, + ); + } + Lead::Elsewhere(_) => { + expectation.undelivered_id = Some(uuid::Uuid::new_v4().to_string()); + self.set_child_expectation(child_id, Some(expectation), cx); + self.send_report_to_lead(child_id, cx); + } + } } /// A report the user dropped from the lead's queue: the next start owes @@ -903,13 +957,44 @@ impl AppState { for meta in self.settle_reports(reports, cx.clock().unix_secs()) { self.persist_meta(&meta, cx); } + self.reports_taken(reports, cx); } - /// The metas of the children that owe `reports` no more, for the caller - /// to save. + /// The metas of the children that owe `reports` no more, and of the leads that took + /// reports of children on other machines, for the caller to save. pub(super) fn settle_reports(&self, reports: &[ReportHandover], now: u64) -> Vec { let mut settled: Vec = Vec::new(); for report in reports { + if let Some((machine, id)) = &report.remote { + let holds = |meta: &SessionMeta| { + meta.remote_children + .iter() + .any(|child| child.machine == *machine && child.thread_id == report.child) + }; + let lead = match settled.iter().position(holds) { + Some(index) => &mut settled[index], + None => { + let Some(meta) = self + .sessions + .iter() + .find(|meta| holds(meta)) + .and_then(|meta| self.find_meta(&meta.id)) + else { + continue; + }; + settled.push(meta); + settled.last_mut().unwrap() + } + }; + for child in &mut lead.remote_children { + if child.machine == *machine && child.thread_id == report.child { + child.report_taken = Some(id.clone()); + child.report_taken_unsent = true; + } + } + lead.updated_at = now; + continue; + } if settled.iter().any(|meta| meta.id == report.child) { continue; } @@ -930,7 +1015,8 @@ impl AppState { settled } - /// After a restart: the reports a lead's queue held when the host stopped. + /// After a restart: the reports a lead's queue held when the host stopped, and what + /// this machine still owes the other machines of its group. pub fn resume_undelivered_reports(&mut self, cx: &mut HostCx) { let undelivered: Vec<_> = self .sessions @@ -941,15 +1027,27 @@ impl AppState { }) .collect(); for (child, parent, text) in undelivered { - self.deliver_callback(&parent, text, Some(&child), cx); + self.deliver_callback( + &parent, + text.clone(), + Some(ReportHandover { + child, + text, + remote: None, + }), + cx, + ); } + self.start_machine_work(cx); } - fn deliver_callback( + /// Text for the lead `parent_id`, steered into its running turn or queued as its next; + /// `report` is the child's report the text carries. + pub(super) fn deliver_callback( &mut self, parent_id: &str, text: String, - report: Option<&str>, + report: Option, cx: &mut HostCx, ) { if !self @@ -964,7 +1062,9 @@ impl AppState { // A report is the work of the turn that made it: the lead takes it up // under the space that turn ran for. callback_cx.space = report - .and_then(|child| self.turn_space_of(child)) + .as_ref() + .filter(|report| report.remote.is_none()) + .and_then(|report| self.turn_space_of(&report.child)) .or(callback_cx.space); let cx = &mut callback_cx; let space = cx.space.clone(); @@ -974,13 +1074,7 @@ impl AppState { // A steered callback is already part of this turn, so persist it just // like a user-triggered steer before handing it to the provider. With // the provider channel gone it waits for the next start instead. - let reports: Vec<_> = report - .map(|child| ReportHandover { - child: child.to_owned(), - text: text.clone(), - }) - .into_iter() - .collect(); + let reports: Vec<_> = report.into_iter().collect(); if can_steer && self.steer_host_message(parent_id, &text, reports.clone(), cx) { return; } @@ -1197,6 +1291,6 @@ pub(super) fn assemble_report_callback( }; format!( "{} {state}.{token_segment}\n{body}", - callback_header(child_id, title) + callback_header(child_id, None, title) ) } diff --git a/crates/runtime/src/app/rewind.rs b/crates/runtime/src/app/rewind.rs index cb6d67b64..eba1c55d1 100644 --- a/crates/runtime/src/app/rewind.rs +++ b/crates/runtime/src/app/rewind.rs @@ -275,10 +275,8 @@ impl AppState { } } - /// Where the thread's record of what its sessions wrote, as their agent reported it, is - /// kept ([`agent::write_journal`]): in Tcode's data, never the workspace. pub(super) fn write_journal_dir(&self, session_id: &str) -> PathBuf { - self.store.root().join("write-journals").join(session_id) + tcode_services::user_files::write_journal_dir(self.store.root(), session_id) } /// The restore points of turn `turn` and every turn after it, whose diff --git a/crates/runtime/src/app/rewind_tests.rs b/crates/runtime/src/app/rewind_tests.rs index d2f4d4abf..62e6e5e1a 100644 --- a/crates/runtime/src/app/rewind_tests.rs +++ b/crates/runtime/src/app/rewind_tests.rs @@ -378,13 +378,14 @@ fn a_control_rewind_answers_with_the_harness_outcome() { caller.id = "caller".into(); caller.project_id = Some("project".into()); state.sessions.push(caller); - state.handle_control_op( + state.handle_control_call( "caller".into(), control_mcp::ControlOp::Rewind(control_mcp::RewindParams { thread_id: "rewound-thread".into(), turn: 1, mode: control_mcp::RewindScope::Conversation, }), + None, reply, cx, ); diff --git a/crates/runtime/src/app/sessions.rs b/crates/runtime/src/app/sessions.rs index 26a64d033..a4e66bc88 100644 --- a/crates/runtime/src/app/sessions.rs +++ b/crates/runtime/src/app/sessions.rs @@ -920,7 +920,8 @@ impl AppState { .sessions .iter() .filter(|meta| match &executor.principal { - tcode_protocol::Principal::Full => true, + tcode_protocol::Principal::Full | tcode_protocol::Principal::Viewer { .. } => true, + tcode_protocol::Principal::Machine { .. } => false, tcode_protocol::Principal::Space { project_ids, .. } => meta .project_id .as_ref() @@ -1582,6 +1583,7 @@ impl AppState { for id in &ids { self.close_orchestrator_children(id, cx); } + self.remote_children_gone(ids.iter().map(|id| &**id), cx); let changed: Vec<_> = self .sessions .iter() @@ -1672,6 +1674,7 @@ impl AppState { .filter(|meta| deleted.contains(meta.id.as_str())) .cloned() .collect(); + self.remote_children_gone(ids.iter().map(String::as_str), cx); for id in ids { if let Some(draft) = self.resident(id).filter(|active| active.holds_draft_text()) { self.deleted_drafts.push(draft.meta.clone()); @@ -1822,6 +1825,18 @@ impl AppState { .filter(|meta| meta.project_id.as_deref() == Some(project_id)) .map(|meta| meta.id.clone()) .collect(); + self.remove_project_and_threads(project_id, &session_ids, false, cx) + } + + /// Remove a project, its drafts and the threads `session_ids` with every + /// thread under them; with `remove_worktrees`, their worktrees too. + pub(super) fn remove_project_and_threads( + &mut self, + project_id: &str, + session_ids: &[String], + remove_worktrees: bool, + cx: &mut HostCx, + ) -> HostTask> { let drafts: Vec<_> = self .residents .live @@ -1849,16 +1864,16 @@ impl AppState { let mut ids = Vec::new(); let mut seen = HashSet::new(); for session_id in session_ids { - if seen.contains(&session_id) { + if seen.contains(session_id) { continue; } - for id in descendant_session_ids(&self.sessions, &session_id) { + for id in descendant_session_ids(&self.sessions, session_id) { if seen.insert(id.clone()) { ids.push(id); } } } - let uploads = self.delete_session_ids(&ids, false, cx); + let uploads = self.delete_session_ids(&ids, remove_worktrees, cx); self.enqueue_store_write(StoreWrite::RemoveProject(project_id.to_string()), cx); self.settings .collapsed_projects @@ -2307,7 +2322,9 @@ impl AppState { cx: &mut HostCx, ) -> Result { let device_id = match &cx.principal { - tcode_protocol::Principal::Full => None, + tcode_protocol::Principal::Full + | tcode_protocol::Principal::Machine { .. } + | tcode_protocol::Principal::Viewer { .. } => None, tcode_protocol::Principal::Space { device_id, .. } => Some(device_id.clone()), }; let standing = self diff --git a/crates/runtime/src/app/settlement.rs b/crates/runtime/src/app/settlement.rs index 1f3aa4653..f12038d25 100644 --- a/crates/runtime/src/app/settlement.rs +++ b/crates/runtime/src/app/settlement.rs @@ -265,7 +265,10 @@ impl AppState { || session.timeline.turn_running }), background_work: resident.is_some_and(|session| session.background_task_count > 0), - unsettled_children: projection.children_hold(&meta.id), + unsettled_children: projection.children_hold(&meta.id) + || super::machines::running_remote_children(meta) + .next() + .is_some(), pull_request_watches: !meta.pull_request_watches_paused && tcode_core::pull_request::watched(&meta.pull_requests) .next() diff --git a/crates/runtime/src/app/snapshots.rs b/crates/runtime/src/app/snapshots.rs index c0b0f60db..2c6d26860 100644 --- a/crates/runtime/src/app/snapshots.rs +++ b/crates/runtime/src/app/snapshots.rs @@ -599,10 +599,10 @@ impl<'a> ActivityProjection<'a> { (running, unsettled) } - /// A dispatched orchestrate child's execution and delivery; `None` for - /// every other thread. + /// The execution and delivery of a child its lead started, here or on + /// another machine of the group; `None` for every other thread. pub(super) fn agent_status(&self, meta: &SessionMeta) -> Option { - if !meta.is_dispatched() { + if !meta.has_lead() { return None; } let resident = self.state.resident(&meta.id); @@ -973,7 +973,14 @@ impl AppState { principal: &tcode_protocol::Principal, ) -> ArchivedSessions { match principal { - tcode_protocol::Principal::Full => self.archived_sessions(), + tcode_protocol::Principal::Full | tcode_protocol::Principal::Viewer { .. } => { + self.archived_sessions() + } + tcode_protocol::Principal::Machine { .. } => ArchivedSessions { + sessions: Vec::new(), + worktree_shared: HashSet::new(), + revision: self.archived_revision, + }, tcode_protocol::Principal::Space { space_id, project_ids, @@ -1072,7 +1079,10 @@ impl AppState { fn scope_snapshot(&self, principal: &tcode_protocol::Principal) -> tcode_protocol::Scope { match principal { - tcode_protocol::Principal::Full => tcode_protocol::Scope::Full, + // A machine never subscribes; a viewer sees what a full device sees. + tcode_protocol::Principal::Full + | tcode_protocol::Principal::Viewer { .. } + | tcode_protocol::Principal::Machine { .. } => tcode_protocol::Scope::Full, tcode_protocol::Principal::Space { space_id, space_name, @@ -1180,6 +1190,7 @@ impl AppState { Topic::Scope => ServerEvent::ScopeSnapshot { scope: self.scope_snapshot(principal), host_unix_ms: now_ms, + view_only: matches!(principal, tcode_protocol::Principal::Viewer { .. }), }, Topic::SpaceIndex { space_id } => { ServerEvent::IndexSnapshot(self.space_index_snapshot( @@ -1218,6 +1229,7 @@ impl AppState { ServerEvent::StorageMigrationReplaced(self.storage_migration.clone()) } Topic::DiskUsage => ServerEvent::DiskUsageReplaced(self.disk_usage.clone()), + Topic::ProjectMoves => ServerEvent::ProjectMovesReplaced(self.project_moves_snapshot()), // Retained latest-run status, so a client that subscribes after a // fast completion still recovers the outcome. `None` means no run // has ever started for this project. diff --git a/crates/runtime/src/app/tests/settlement.rs b/crates/runtime/src/app/tests/settlement.rs index 222e225f2..ed8046511 100644 --- a/crates/runtime/src/app/tests/settlement.rs +++ b/crates/runtime/src/app/tests/settlement.rs @@ -807,7 +807,7 @@ fn a_finished_child_holds_its_lead_until_settled_and_cancel_never_delivers() { let op = |state: &TestEntity, cx: &mut TestAppContext, op| { let (reply, response) = smol::channel::bounded(1); state.update(cx, |state, cx| { - state.handle_control_op("lead".into(), op, reply, cx) + state.handle_control_call("lead".into(), op, None, reply, cx) }); cx.run_until_recv(&response) }; diff --git a/crates/runtime/src/pipe.rs b/crates/runtime/src/pipe.rs index 46b60e175..a8d633d8d 100644 --- a/crates/runtime/src/pipe.rs +++ b/crates/runtime/src/pipe.rs @@ -46,6 +46,9 @@ pub struct HostServices { /// How the host starts a provider's adapter: [`agent::start_session`] /// unless a test plays the adapter's half of the canonical stream. pub provider_launcher: crate::app::ProviderLauncher, + /// How the host reaches the other machines of its group: the composition root hands + /// the same link to the transport that serves it. + pub machines: Option, } impl HostServices { @@ -291,7 +294,9 @@ pub fn spawn_host(store: SessionStore, mut services: HostServices) -> std::io::R state.mcp_unavailable(services.mcp_unavailable.take()); state.login_shell_unread(services.login_shell_unread.take()); state.set_provider_launcher(services.provider_launcher); + state.attach_machine_link(services.machines.take()); let mut cx = HostCx::new(mailbox_tx, event_tx, services.clock.clone()); + state.resume_project_moves(&mut cx); state.pump_pull_request_requests(services.pull_requests.take(), &mut cx); state.start_pull_request_workers(&mut cx); state.pump_control_requests(&mut cx); @@ -429,12 +434,12 @@ pub(crate) fn handle_client_message( } = message; cx.principal = principal.unwrap_or(Principal::Full); cx.space = match &cx.principal { - Principal::Full => None, + Principal::Full | Principal::Machine { .. } | Principal::Viewer { .. } => None, Principal::Space { space_id, .. } => Some(space_id.clone()), }; cx.origin = Some(tcode_core::session::MessageOrigin::Human); cx.author = match &cx.principal { - Principal::Full => None, + Principal::Full | Principal::Machine { .. } | Principal::Viewer { .. } => None, Principal::Space { device_id, device_name, @@ -1010,6 +1015,17 @@ fn dispatch_command(app: &mut AppState, cx: &mut HostCx, command: Command) -> Co thread_ids, } => app.stop_watching_threads(&session_id, &thread_ids, cx), Command::CancelAgent { session_id } => app.cancel_child(&session_id, cx), + Command::ControlRemoteChild { + session_id, + machine, + thread_id, + op, + } => { + let task = app.control_remote_child(&session_id, &machine, &thread_id, op, cx); + return CommandOutcome::Pending( + cx.spawn_background(async move { task.await.map(|()| CommandResponse::Unit) }), + ); + } Command::SetAutoSettle { session_id, enabled, @@ -1077,6 +1093,29 @@ fn dispatch_command(app: &mut AppState, cx: &mut HostCx, command: Command) -> Co cx.spawn_background(async move { uploads.await.map(|()| CommandResponse::Unit) }), ); } + Command::MoveProject { + project_id, + machine, + root, + include_ignored, + } => { + let task = app.move_project(&project_id, &machine, &root, include_ignored, cx); + return CommandOutcome::Pending( + cx.spawn_background(async move { task.await.map(|()| CommandResponse::Unit) }), + ); + } + Command::ResumeProjectMove { project_id } => { + let task = app.resume_project_move(&project_id, cx); + return CommandOutcome::Pending( + cx.spawn_background(async move { task.await.map(|()| CommandResponse::Unit) }), + ); + } + Command::CancelProjectMove { project_id, force } => { + let task = app.cancel_project_move(&project_id, force, cx); + return CommandOutcome::Pending( + cx.spawn_background(async move { task.await.map(|()| CommandResponse::Unit) }), + ); + } Command::MarkSessionUnread { session_id } => app.mark_session_unread(&session_id, cx), Command::MarkSessionRead { session_id, @@ -1656,6 +1695,36 @@ fn dispatch_query( }) }) } + Query::Machine(request) => { + let Principal::Machine { + machine_id, + machine_name, + } = cx.principal.clone() + else { + return cx.spawn_background(async { + Err(ProtocolError::out_of_scope( + "only another machine of the group sends machine requests", + )) + }); + }; + let peer = crate::app::machines::MachinePeer { + id: machine_id, + name: machine_name, + }; + let task = app.handle_machine_request(&peer, request, cx); + cx.spawn_background(async move { task.await.map(QueryResponse::Machine) }) + } + Query::ProjectMovePreview { + project_id, + machine, + } => { + let task = app.project_move_preview(&project_id, &machine, cx); + cx.spawn_background(async move { task.await.map(QueryResponse::ProjectMovePreview) }) + } + Query::MovedThread { thread_id } => { + let machine = app.moved_thread_machine(&thread_id).map(str::to_owned); + cx.spawn_background(async move { Ok(QueryResponse::MovedThread(machine)) }) + } } } @@ -2240,6 +2309,7 @@ mod tests { ServerEvent::ScopeSnapshot { scope: tcode_protocol::Scope::Full, host_unix_ms: 0, + view_only: false, }, ), ( diff --git a/crates/services/src/lib.rs b/crates/services/src/lib.rs index 46e04fe66..7f561e501 100644 --- a/crates/services/src/lib.rs +++ b/crates/services/src/lib.rs @@ -20,6 +20,7 @@ pub mod listening; pub mod process; pub mod project_config; pub mod project_icons; +pub mod project_move; pub mod provider_auth; pub mod provider_login; pub mod provider_probe; diff --git a/crates/services/src/project_move/git.rs b/crates/services/src/project_move/git.rs new file mode 100644 index 000000000..feed7019e --- /dev/null +++ b/crates/services/src/project_move/git.rs @@ -0,0 +1,411 @@ +//! A repository's checkouts as a move carries them: each checkout's +//! uncommitted state kept as two commits under `refs/tcode/move//…` +//! without touching its index, HEAD, branch or stash; everything in one +//! bundle; and on the other machine a repository whose `git status` reads as +//! the source's did. +use std::ffi::OsStr; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +/// Where a move keeps its snapshot refs in the repository it leaves. +pub const REFS_ROOT: &str = "refs/tcode/move"; + +/// What a checkout had checked out. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", content = "content", rename_all = "snake_case")] +pub enum Head { + /// On a branch (its short name). + Branch(String), + /// On a commit, kept under the snapshot ref `head`. + Detached { head_ref: String }, + /// On a branch with no commit yet. + Unborn(String), +} + +/// One checkout's state as its two snapshot commits hold it. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct CheckoutSnapshot { + pub head: Head, + /// A commit on HEAD whose tree is the checkout's index. + pub index_ref: String, + /// A commit on HEAD whose tree is its working tree, untracked files Git + /// does not ignore included. + pub worktree_ref: String, +} + +/// One `git` in `cwd`, as a move runs it: no optional locks, so no status +/// refresh rewrites an index it only reads, and an identity of its own for the +/// commits it makes, so a machine without one configured can still make them. +fn git(cwd: &Path) -> std::process::Command { + let mut command = crate::process::command("git"); + command + .current_dir(cwd) + .env("GIT_OPTIONAL_LOCKS", "0") + .env("GIT_AUTHOR_NAME", "Tcode") + .env("GIT_AUTHOR_EMAIL", "tcode@localhost") + .env("GIT_COMMITTER_NAME", "Tcode") + .env("GIT_COMMITTER_EMAIL", "tcode@localhost") + // A fixed date makes the snapshot commits the same whenever they are + // made from the same state. + .env("GIT_AUTHOR_DATE", "@0 +0000") + .env("GIT_COMMITTER_DATE", "@0 +0000"); + command +} + +fn run(mut command: std::process::Command, what: &str) -> Result { + let output = command + .output() + .map_err(|error| format!("git {what}: {error}"))?; + if output.status.success() { + Ok(String::from_utf8_lossy(&output.stdout).into_owned()) + } else { + Err(format!( + "git {what} failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + )) + } +} + +fn run_args>(cwd: &Path, args: &[S]) -> Result { + let what = args + .iter() + .map(|arg| arg.as_ref().to_string_lossy().into_owned()) + .collect::>() + .join(" "); + let mut command = git(cwd); + command.args(args); + run(command, &what) +} + +/// The value `rev-parse` gives for `args`, or `None` where it names nothing. +fn verify(cwd: &Path, name: &str) -> Result, String> { + let output = git(cwd) + .args(["rev-parse", "--quiet", "--verify", name]) + .output() + .map_err(|error| format!("git rev-parse: {error}"))?; + Ok(output + .status + .success() + .then(|| String::from_utf8_lossy(&output.stdout).trim().to_owned())) +} + +/// A path Git reports for `dir`, made absolute. +fn git_path(dir: &Path, name: &str) -> Result { + let path = run_args(dir, &["rev-parse", "--git-path", name])?; + let path = PathBuf::from(path.trim()); + Ok(if path.is_absolute() { + path + } else { + dir.join(path) + }) +} + +/// Whether `dir` is the top level of a Git checkout: the main one or a linked +/// worktree. +pub fn is_checkout_root(dir: &Path) -> bool { + let Ok(top) = run_args(dir, &["rev-parse", "--show-toplevel"]) else { + return false; + }; + match (Path::new(top.trim()).canonicalize(), dir.canonicalize()) { + (Ok(top), Ok(dir)) => top == dir, + _ => false, + } +} + +/// Whether `dir` is in the middle of a merge, rebase, cherry-pick or revert, +/// or has unmerged index entries: a state its snapshot could not hold. +pub fn interrupted(dir: &Path) -> Result { + for head in ["MERGE_HEAD", "CHERRY_PICK_HEAD", "REVERT_HEAD"] { + if git_path(dir, head)?.exists() { + return Ok(true); + } + } + for state in ["rebase-merge", "rebase-apply"] { + if git_path(dir, state)?.exists() { + return Ok(true); + } + } + Ok(!run_args(dir, &["ls-files", "--unmerged"])? + .trim() + .is_empty()) +} + +/// Whether `dir`'s index or working tree differs from its HEAD. +pub fn dirty(dir: &Path) -> Result { + Ok(!run_args(dir, &["status", "--porcelain"])?.trim().is_empty()) +} + +/// How many local branches the repository of `dir` has. +pub fn branch_count(dir: &Path) -> Result { + Ok( + run_args(dir, &["for-each-ref", "--format=x", "refs/heads"])? + .lines() + .count() as u32, + ) +} + +/// The bytes the repository of `dir` keeps its objects in. +pub fn object_bytes(dir: &Path) -> Result { + let counts = run_args(dir, &["count-objects", "-v"])?; + Ok(counts + .lines() + .filter_map(|line| { + let (key, value) = line.split_once(": ")?; + matches!(key, "size" | "size-pack") + .then(|| value.trim().parse::().ok()) + .flatten() + }) + .sum::() + * 1024) +} + +/// Keep the state of the checkout `dir` under `prefix` (`refs/tcode/move//