Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat(host): let bots message each other without waiting for a reply (#33)

Sean Ferguson15356a5de83c
diff --git a/CLAUDE.md b/CLAUDE.md
index d3e188b6..5583ed52 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -26,7 +26,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess
- `host/` — **codync-host** (Rust, macOS + Linux + Windows; platform differences in `service/` and `shell.rs`). Detects installed harnesses (`agent/backends.rs`: login-shell PATH + known dirs) and the ACP registry (`agent/registry.rs`, cached in `~/.codync/registry.json`, binaries under `~/.codync/agents`). Drives agents over **ACP** (JSON-RPC on stdio, hand-rolled in `agent/acp.rs`, updates kept as `serde_json::Value` so new adapter variants never break parsing). One actor per bot (`agent/bot/`) owns the agent process + session and maps `session/update` onto transcript entries.
- **Chat ≠ session**: a bot is one endless transcript (SQLite `entries`, ordered by `seq`); the ACP session underneath is resumed with `session/load` or replaced by *New session*.
- **Group chats and threads** are host features every client drives through the same methods (`send` with `threadId`, `thread`, `createBot {kind: group}`); clients never route, parse mentions or count replies themselves. A group is a roster row whose members answer in their own sessions (Grok Bot's room turns); a thread on a bot's message is a forked session: [docs/features/groups-and-threads.md](docs/features/groups-and-threads.md).
-- Bot collaboration: built-in `team` MCP (`chat/team.rs`) lists visible bots and asks one for a reply through its actor queue. Requests are separate turns, cycle-checked and cancellable; native subagents stay with the harness. See [docs/features/bot-collaboration.md](docs/features/bot-collaboration.md).
+- Bot collaboration: built-in `team` MCP (`chat/team.rs`) lists visible bots and asks one for a reply or sends it an independent message through its actor queue. Asks are separate turns, cycle-checked and cancellable; native subagents stay with the harness. See [docs/features/bot-collaboration.md](docs/features/bot-collaboration.md).
- **Context & memory** (Grok Bot's design): frozen instruction snapshot per session + compaction epoch (Claude gets it as a system prompt), profile edits as update blocks, per-bot memory files written by a keeper agent, busy-time messages folded into one turn, interrupted turns resumed: [docs/features/context-and-memory.md](docs/features/context-and-memory.md).
- **Chat shows only**: user messages, the bot's messages (`data.final`: each `send_message` call from the built-in `chat` MCP, Grok Bot's way; a turn that sent none falls back to its last text), permission cards, notices. Nothing streams into a bubble; narration, thoughts, tool calls, plans are trace entries (Full conversation sheet): [docs/features/chat-messages.md](docs/features/chat-messages.md).
- **Sync**: every mutation stamps a global `rev`. Clients call `GET /events?since=<rev>` (catch-up in rev order, then live). Emission happens under `Hub::emit_lock` so events leave in rev order. Clients upsert by id; never skip undecodable events (the iOS app rewinds to rev 0).
diff --git a/docs/features/bot-collaboration.md b/docs/features/bot-collaboration.md
index c3ad1302..738eac4e 100644
--- a/docs/features/bot-collaboration.md
+++ b/docs/features/bot-collaboration.md
@@ -4,11 +4,11 @@ Create two or more bots normally, giving each a clear name, description, project
> Ask Reviewer to inspect the changes in /path/to/project. Have it report bugs without editing files, then summarize its findings for me.
-Every bot receives the built-in `team` MCP server. `list_bots` returns the other visible bots' IDs, descriptions, agents, folders and status. `ask_bot(botId, message)` sends a self-contained request and waits for the recipient's final text reply. The requesting bot incorporates that answer into its response to you. The same tools work across ACP backends that support MCP servers.
+Every bot receives the built-in `team` MCP server. `list_bots` returns the other visible bots' IDs, descriptions, agents, folders and status. `ask_bot(botId, message)` sends a self-contained request and waits for the recipient's final text reply. The requesting bot incorporates that answer into its response to you. `message_bot(botId, message)` queues a request and returns immediately; the recipient reports to you in its own chat. The same tools work across ACP backends that support MCP servers.
The host records the request and its outcome in both chats using existing notice entries, so the current iOS, desktop and terminal clients can display them. Tool details also remain in the trace. There is no additional team setup screen.
-## Execution
+## Ask execution
- Each bot still owns an ACP process with main/reply-thread sessions and runs one turn at a time. A busy recipient queues the request. Different bots can work concurrently.
- Requests have their own reply channel and never merge with user messages or another request. Contiguous user messages keep the existing batching behavior.
@@ -16,7 +16,7 @@ The host records the request and its outcome in both chats using existing notice
- The host rejects self-delegation, duplicate outstanding requests to the same recipient, and direct or indirect wait cycles, including queued requests. Up to 64 requests can be outstanding host-wide.
- Native Claude Code/Codex subagents remain managed by the harness. Codync does not turn them into permanent bots or override their delegation settings.
-## Stops, failures and restart
+## Ask stops, failures and restart
- The wait limit is ten minutes, including queue and approval time. Failure is a tool error, not a fabricated successful reply. `ask_bot` is not automatically retried.
- Stopping the requesting bot cancels its outgoing requests. A queued request is removed; a running delegated turn's ACP process is stopped. Unrelated queued messages on the recipient remain. Stopping the recipient also releases its requesters once its turn stops.
@@ -24,11 +24,24 @@ The host records the request and its outcome in both chats using existing notice
- Pending request notices are persisted with IDs and statuses. After host restart they become interrupted errors; delegated turns are not automatically replayed. Check partial work before retrying. Ordinary user turns retain their existing session-resume behavior.
- Completion push notifications come from the requesting bot; delegated replies do not send a second “done” push. Recipient permission requests still use the usual “needs you” notifications.
-This first version uses synchronous request/reply over MCP and does not introduce a task scheduler or isolated worktrees. Give bots explicit file ownership when they share a working directory. Rebuild and restart the host to load the new built-in MCP server; phone clients need no protocol upgrade.
+`ask_bot` uses synchronous request/reply over MCP; neither tool adds a task scheduler or isolated worktrees. Give bots explicit file ownership when they share a working directory. Rebuild and restart the host to load the new built-in MCP server; phone clients need no protocol upgrade.
+
+## Independent messages
+
+`message_bot(botId, message)` queues a bot request and returns immediately, without waiting for a reply. The recipient reports to you in its own chat. Messages use the same queue as asks, run one turn at a time, and never merge with user messages or other requests. Both chats show bot-attributed notices rather than user messages. Up to 64 messages can be outstanding host-wide, with at most 16 from any one sender, separately from asks. Queued and running messages both count. A slot is freed when the recipient finishes, fails or cancels the request, or admission fails. Stopping, restarting or deleting the sender does not free slots for its already accepted messages.
+
+Accepted messages survive sender completion, Stop, disconnection and deletion. Recipient Stop or deletion cancels queued messages and stops running work; started work may have left partial changes. Outcomes update both notices; failures mark them as failed. The recipient uses its normal completion notifications. Messages have no ask timeout or automatic retry and are not replayed after host restart.
+
+Bot request chains can make at most eight handoffs. Both `message_bot` and
+`ask_bot` carry the count into the recipient's turn, including queued work;
+finishing an earlier request does not reset it. This bounds repeated A → B → A
+messages even when few requests are outstanding. At the limit, the tool reports
+an error without queuing more work. A new user turn starts a fresh allowance.
## Code and verification
-- `host/src/chat/team.rs`: discovery, wait graph, request lifetime and persisted notices.
+- `host/src/chat/team.rs`: discovery, request lifetime and persisted notices.
+- `host/src/chat/team/requests.rs`: admission, wait graph, capacity and chain hop limit.
- `host/src/agent/bot/` (`queue.rs`, `turn.rs`): queue boundaries, recipient execution, completion and targeted cancellation.
- `host/src/mcp.rs`: the authenticated local MCP → HTTP bridge.
- `host/tests/team_e2e.rs`: a real host and MCP subprocess, with scripted ACP agents, covering discovery → delegation → recipient approval → reply → client sync. No paid provider calls.
diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rs
index 7e02998b..fe096df7 100644
--- a/host/src/agent/bot/mod.rs
+++ b/host/src/agent/bot/mod.rs
@@ -54,7 +54,7 @@ pub enum Cmd {
entry_id: String,
text: String,
},
- Ask(crate::chat::team::Ask),
+ BotRequest(crate::chat::team::BotRequest),
/// `send_message` from the bot's `chat` MCP server: a message for the user, now.
SendToUser {
text: String,
@@ -82,7 +82,7 @@ pub enum Cmd {
enum Queued {
Routine(String),
User { lane: Lane, entry_id: String, text: String },
- Ask(crate::chat::team::Ask),
+ BotRequest(crate::chat::team::BotRequest),
Group(GroupTurn),
}
@@ -126,7 +126,7 @@ pub fn spawn(hub: Arc<Hub>, cfg: BotConfig) -> BotHandle {
announce: None,
turn: None,
queue: VecDeque::new(),
- active_ask: None,
+ active_request: None,
seg: Seg::None,
tools: HashMap::new(),
plan_entry: None,
@@ -208,7 +208,7 @@ struct Actor {
announce: Option<(Snapshot, Identity)>,
turn: Option<i64>,
queue: VecDeque<Queued>,
- active_ask: Option<crate::chat::team::Ask>,
+ active_request: Option<crate::chat::team::BotRequest>,
seg: Seg,
tools: HashMap<String, String>,
plan_entry: Option<String>,
@@ -285,7 +285,7 @@ impl Actor {
}
}
self.hub.team.cancel_from(&self.cfg.id);
- self.complete_ask(Err(anyhow!("recipient shut down")));
+ self.complete_request(Err(anyhow!("recipient shut down")), true);
self.complete_group(Err(anyhow!("bot shut down")));
if let Some(c) = self.conn.take() {
c.acp.kill().await;
diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rs
index 8366e21b..18a8c738 100644
--- a/host/src/agent/bot/queue.rs
+++ b/host/src/agent/bot/queue.rs
@@ -40,15 +40,15 @@ impl Actor {
self.cancel_turn().await;
}
}
- Cmd::Ask(ask) => {
- self.queue.push_back(Queued::Ask(ask));
+ Cmd::BotRequest(ask) => {
+ self.queue.push_back(Queued::BotRequest(ask));
if self.turn.is_none() {
self.next_in_queue(done_tx).await;
}
}
Cmd::CancelAsk { id } => {
- self.queue.retain(|q| !matches!(q, Queued::Ask(a) if a.id == id));
- if self.active_ask.as_ref().is_some_and(|a| a.id == id) {
+ self.queue.retain(|q| !matches!(q, Queued::BotRequest(a) if a.expects_reply() && a.id == id));
+ if self.active_request.as_ref().is_some_and(|a| a.expects_reply() && a.id == id) {
self.hub.team.cancel_from(&self.cfg.id);
self.stop_requested = true;
// The request has expired. Kill only its process so a harness
@@ -171,14 +171,17 @@ impl Actor {
}
continue;
}
- Some(Queued::Ask(_)) => {
- let Some(Queued::Ask(ask)) = self.queue.pop_front() else { unreachable!("front is an ask") };
- if ask.reply.is_closed() {
+ Some(Queued::BotRequest(_)) => {
+ let Some(Queued::BotRequest(mut ask)) = self.queue.pop_front() else {
+ unreachable!("front is an ask")
+ };
+ if ask.reply_closed() {
continue;
}
let ids = [ask.entry_id.clone()];
let prompt = ask.prompt.clone();
- self.active_ask = Some(ask);
+ ask.mark_started();
+ self.active_request = Some(ask);
let result = self.start_turn(main.clone(), &ids, &prompt, false, done_tx).await;
// Another bot's words are not facts learned from the user.
self.turn_text = None;
@@ -228,7 +231,7 @@ impl Actor {
pub(super) fn start_failed(&mut self, e: &anyhow::Error) {
self.finish_routine(crate::routines::Status::Failed, Some(format!("Could not start routine: {e:#}")), None);
- self.complete_ask(Err(anyhow!("couldn't start recipient: {e:#}")));
+ self.complete_request(Err(anyhow!("couldn't start recipient: {e:#}")), false);
self.complete_group(Err(anyhow!("couldn't start: {e:#}")));
let mut msg = format!("Couldn't start the agent: {e}");
if e.to_string().to_lowercase().contains("auth")
@@ -250,9 +253,9 @@ impl Actor {
self.hub.team.cancel_from(&self.cfg.id);
}
- pub(super) fn complete_ask(&mut self, result: Result<String>) {
- if let Some(ask) = self.active_ask.take() {
- let _ = ask.reply.send(result);
+ pub(super) fn complete_request(&mut self, result: Result<String>, cancelled: bool) {
+ if let Some(ask) = self.active_request.take() {
+ ask.complete(result, cancelled);
}
}
diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rs
index cbe4d4fe..3735ebc3 100644
--- a/host/src/agent/bot/turn.rs
+++ b/host/src/agent/bot/turn.rs
@@ -37,7 +37,7 @@ impl Actor {
);
for id in entry_ids {
if let Some(mut e) = self.hub.store.entry(id) {
- e.data["status"] = "sent".into();
+ e.data["status"] = json!(crate::chat::team::RequestStatus::Sent);
self.hub.set_entry(id, &e.data);
}
}
@@ -46,7 +46,7 @@ impl Actor {
self.turn_text = (!hidden).then(|| text.to_owned());
self.announce = None;
self.stop_requested = false;
- self.hub.team.start_turn(&self.cfg.id);
+ self.hub.team.start_turn(&self.cfg.id, self.active_request.as_ref());
self.exit_tail = None;
self.seg = Seg::None;
self.tools.clear();
@@ -55,7 +55,9 @@ impl Actor {
self.sent.clear();
// A delegated or group turn has no live waiter after a host restart. Its persisted
// notices are marked interrupted instead of silently repeating work.
- self.set_inflight(self.active_ask.is_none() && self.active_group.is_none() && self.active_routine.is_none());
+ self.set_inflight(
+ self.active_request.is_none() && self.active_group.is_none() && self.active_routine.is_none(),
+ );
self.hub.set_runtime(&self.id(), |r| {
r.status = BotStatus::Working;
r.activity = if hidden { "Picking up where it left off…" } else { "Starting…" }.into();
@@ -201,7 +203,7 @@ impl Actor {
_ => {}
}
let failed = done.is_err() && !self.stop_requested;
- let delegated = self.active_ask.is_some();
+ let delegated = self.active_request.as_ref().is_some_and(crate::chat::team::BotRequest::expects_reply);
let reply = if stopped {
Err(anyhow!("recipient was stopped; partial work may have happened"))
} else if stop_reason != "end_turn" {
@@ -231,7 +233,9 @@ impl Actor {
let text = (status == crate::routines::Status::Succeeded).then(|| final_text.clone()).flatten();
self.finish_routine(status, detail, text);
}
- self.complete_ask(reply);
+ let message_failed =
+ !stopped && reply.is_err() && self.active_request.as_ref().is_some_and(|r| !r.expects_reply());
+ self.complete_request(reply, stopped);
self.complete_group(if stopped || failed || stop_reason != "end_turn" {
Err(anyhow!("turn did not complete ({stop_reason})"))
} else {
@@ -264,7 +268,7 @@ impl Actor {
if !self.stop_requested
&& !delegated
&& !grouped
- && let Some(kind) = turn_alert(failed, &stop_reason, more)
+ && let Some(kind) = turn_alert(failed || message_failed, &stop_reason, more)
{
let body = final_text.unwrap_or_else(|| match kind {
AlertKind::Done => "Finished.".into(),
diff --git a/host/src/agent/bot/updates.rs b/host/src/agent/bot/updates.rs
index 43de3d81..88b05f5f 100644
--- a/host/src/agent/bot/updates.rs
+++ b/host/src/agent/bot/updates.rs
@@ -218,7 +218,7 @@ impl Actor {
/// bot's own chat and threads; a room, a teammate or a routine reads the turn's reply.
pub(super) fn send_to_user(&mut self, text: String) -> anyhow::Result<()> {
let Some(turn) = self.turn else { anyhow::bail!("no turn is running") };
- if self.active_group.is_some() || self.active_ask.is_some() || self.active_routine.is_some() {
+ if self.active_group.is_some() || self.active_request.is_some() || self.active_routine.is_some() {
anyhow::bail!("send_message isn't available in this turn: write your answer as your reply");
}
self.close_seg();
diff --git a/host/src/chat/team.rs b/host/src/chat/team.rs
index ffc6297e..fd550f4d 100644
--- a/host/src/chat/team.rs
+++ b/host/src/chat/team.rs
@@ -8,18 +8,23 @@ use crate::store::{BotConfig, EntryKind};
use anyhow::{Result, anyhow, bail};
use serde::Serialize;
use serde_json::{Value, json};
-use std::collections::{HashMap, HashSet};
-use std::sync::{Arc, Mutex};
+use std::sync::Arc;
use std::time::Duration;
-use tokio::sync::{oneshot, watch};
+use tokio::sync::oneshot;
+
+mod requests;
+pub use requests::Requests;
pub const ASK_TIMEOUT: Duration = Duration::from_secs(600);
const MAX_MESSAGE_BYTES: usize = 32_000;
+const MAX_PENDING_MESSAGES: usize = 64;
pub const INSTRUCTIONS: &str = "Use list_bots to find the user's other Codync bots. \
Use ask_bot when the user requests another bot's help or its specialty is useful. \
+Use message_bot for a handoff that should continue independently: it returns when queued, \
+and the recipient reports the outcome to the user in its own chat. Stopping you does not cancel it. \
Provide a self-contained request: the recipient has its own conversation, working directory, \
-tools and permissions, not your context. It returns its final reply to you. \
+tools and permissions, not your context. ask_bot returns its final reply to you. \
Coordinate file ownership before asking for edits in a shared project. \
Do not ask a bot that is waiting for you. Native subagents are managed by your own harness; \
these tools are for collaborating with the user's existing bots.";
@@ -44,91 +49,87 @@ pub fn tools() -> Value {
"required": ["botId", "message"],
},
"annotations": {"readOnlyHint": false, "idempotentHint": false},
+ },
+ {
+ "name": "message_bot",
+ "description": "Queue a self-contained request for another Codync bot and return immediately. The recipient reports the outcome to the user in its own chat; no reply is returned to you. It uses its own tools, folder and permissions. Stopping you does not cancel accepted work. Stopping the recipient cancels its queued requests and stops its running turn. No automatic retry or replay after host restart; check the chats before retrying an uncertain result.",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "botId": {"type": "string", "description": "Recipient ID from list_bots."},
+ "message": {"type": "string", "description": "Task, relevant context, file paths and expected outcome for the user."},
+ },
+ "required": ["botId", "message"],
+ },
+ "annotations": {"readOnlyHint": false, "idempotentHint": false},
}
])
}
-struct Request {
- from: String,
- to: String,
- cancel: watch::Sender<bool>,
+/// Sent through the recipient's normal actor queue, but never merged with user
+/// messages or another request. Its completion mode owns reply delivery or the
+/// independent message's notice lifetime.
+pub struct BotRequest {
+ pub id: String,
+ pub entry_id: String,
+ pub prompt: String,
+ /// Bound the whole chain, including independent handoffs after their sender finishes.
+ hops: u8,
+ completion: Completion,
}
-/// The wait graph includes queued requests, not only running recipients.
-/// Reserving an edge and checking for cycles happen under the same lock.
-#[derive(Default)]
-pub struct Requests(Mutex<RequestState>);
-
-#[derive(Default)]
-struct RequestState {
- pending: HashMap<String, Request>,
- active: HashSet<String>,
+enum Completion {
+ ReplyToSender(oneshot::Sender<Result<String>>),
+ ReportInRecipientChat(MessageLifetime),
}
-impl Requests {
- fn begin(&self, id: &str, from: &str, to: &str) -> Result<watch::Receiver<bool>> {
- let mut state = self.0.locked();
- if !state.active.contains(from) {
- bail!("the requesting bot is no longer working");
- }
- let requests = &mut state.pending;
- if from == to {
- bail!("a bot cannot ask itself");
- }
- if requests.len() >= 64 {
- bail!("too many pending bot requests");
- }
- if requests.values().any(|r| r.from == from && r.to == to) {
- bail!("already waiting for this bot");
- }
- let mut pending = vec![to];
- let mut seen = HashSet::new();
- while let Some(bot) = pending.pop() {
- if bot == from {
- bail!("this request would make bots wait for each other; finish the current request first");
- }
- if seen.insert(bot) {
- pending.extend(requests.values().filter(|r| r.from == bot).map(|r| r.to.as_str()));
- }
- }
- let (cancel, rx) = watch::channel(false);
- requests.insert(id.to_owned(), Request { from: from.to_owned(), to: to.to_owned(), cancel });
- Ok(rx)
+impl BotRequest {
+ pub fn expects_reply(&self) -> bool {
+ matches!(self.completion, Completion::ReplyToSender(_))
}
- pub fn cancel_from(&self, bot: &str) {
- let mut state = self.0.locked();
- state.active.remove(bot);
- for request in state.pending.values().filter(|r| r.from == bot) {
- request.cancel.send_replace(true);
- }
+ pub fn reply_closed(&self) -> bool {
+ matches!(&self.completion, Completion::ReplyToSender(reply) if reply.is_closed())
}
- pub fn start_turn(&self, bot: &str) {
- self.0.locked().active.insert(bot.to_owned());
+ pub fn mark_started(&mut self) {
+ if let Completion::ReportInRecipientChat(message) = &mut self.completion {
+ message.started = true;
+ for id in &message.entries {
+ if let Some(mut e) = message.hub.store.entry(id) {
+ let heading = e.data["heading"].as_str().unwrap_or("Bot request");
+ e.data["text"] = format!("{heading}\nRunning in {}'s chat…", message.target_name).into();
+ e.data["status"] = json!(RequestStatus::Sent);
+ message.hub.set_entry(id, &e.data);
+ }
+ }
+ }
}
- pub fn cancel_bot(&self, bot: &str) {
- let mut state = self.0.locked();
- state.active.remove(bot);
- for request in state.pending.values().filter(|r| r.from == bot || r.to == bot) {
- request.cancel.send_replace(true);
+ pub fn complete(self, result: Result<String>, cancelled: bool) {
+ match self.completion {
+ Completion::ReplyToSender(reply) => {
+ let _ = reply.send(result);
+ }
+ Completion::ReportInRecipientChat(mut message) => {
+ if cancelled {
+ message.finish(RequestStatus::Cancelled, "Recipient stopped. Partial work may have happened.");
+ } else {
+ match result {
+ Ok(_) => message.finish(RequestStatus::Completed, "Completed."),
+ Err(error) => message.finish(RequestStatus::Failed, &format!("{error:#}")),
+ }
+ }
+ }
}
}
}
-/// Sent through the recipient's normal actor queue, but never merged with user
-/// messages or another request. Only this turn can resolve its reply channel.
-pub struct Ask {
- pub id: String,
- pub entry_id: String,
- pub prompt: String,
- pub reply: oneshot::Sender<Result<String>>,
-}
-
#[derive(Clone, Copy, Serialize)]
#[serde(rename_all = "lowercase")]
-enum Status {
+pub(crate) enum RequestStatus {
+ Queued,
+ Sent,
Completed,
Failed,
Cancelled,
@@ -143,26 +144,62 @@ struct Pending {
}
impl Pending {
- fn finish(&mut self, status: Status, detail: &str) {
- for id in &self.entries {
- if let Some(mut e) = self.hub.store.entry(id) {
- e.data["status"] = json!(status);
- let heading = e.data["heading"].as_str().unwrap_or("Bot request");
- e.data["text"] = format!("{heading}\n{detail}").into();
- if !matches!(status, Status::Completed) {
- e.data["style"] = "error".into();
- }
- self.hub.set_entry(id, &e.data);
+ fn finish(&mut self, status: RequestStatus, detail: &str) {
+ finish_notices(&self.hub, &self.entries, status, detail);
+ self.finished = true;
+ }
+}
+
+fn finish_notices(hub: &Hub, entries: &[String], status: RequestStatus, detail: &str) {
+ for id in entries {
+ if let Some(mut e) = hub.store.entry(id) {
+ e.data["status"] = json!(status);
+ let heading = e.data["heading"].as_str().unwrap_or("Bot request");
+ e.data["text"] = format!("{heading}\n{detail}").into();
+ if !matches!(status, RequestStatus::Completed) {
+ e.data["style"] = "error".into();
}
+ hub.set_entry(id, &e.data);
}
+ }
+}
+
+/// Owned by the recipient's command/queue/turn after admission, never by a
+/// waiting sender. Drop also covers commands discarded during actor shutdown.
+struct MessageLifetime {
+ hub: Arc<Hub>,
+ sender: String,
+ entries: Vec<String>,
+ target_name: String,
+ started: bool,
+ finished: bool,
+}
+
+impl MessageLifetime {
+ fn finish(&mut self, status: RequestStatus, detail: &str) {
+ finish_notices(&self.hub, &self.entries, status, detail);
self.finished = true;
}
}
+impl Drop for MessageLifetime {
+ fn drop(&mut self) {
+ if !self.finished {
+ let detail = if self.started {
+ "Recipient stopped. Partial work may have happened."
+ } else {
+ "Cancelled before execution."
+ };
+ self.finish(RequestStatus::Cancelled, detail);
+ }
+ self.hub.team.release_message(&self.sender);
+ }
+}
+
impl Drop for Pending {
fn drop(&mut self) {
if !self.finished {
- self.finish(Status::Cancelled, "Request cancelled. Partial work may have happened.");
+ self.finish(RequestStatus::Cancelled, "Request cancelled. Partial work may have happened.");
}
self.hub.team.0.locked().pending.remove(&self.id);
// Targeted cancellation never clears unrelated user messages or turns.
@@ -202,10 +239,60 @@ pub async fn call(hub: &Arc<Hub>, from: &str, name: &str, args: &Value) -> Resul
let message = args["message"].as_str().unwrap_or_default().trim();
ask(hub, &source, to, message, ASK_TIMEOUT).await
}
+ "message_bot" => {
+ let to = args["botId"].as_str().ok_or_else(|| anyhow!("botId is required"))?;
+ let message = args["message"].as_str().unwrap_or_default().trim();
+ message_bot(hub, &source, to, message)
+ }
_ => bail!("unknown team tool: {name}"),
}
}
+fn message_bot(hub: &Arc<Hub>, source: &BotConfig, to: &str, message: &str) -> Result<Value> {
+ if message.is_empty() || message.len() > MAX_MESSAGE_BYTES {
+ bail!("message must be nonempty and at most {MAX_MESSAGE_BYTES} bytes");
+ }
+ if source.id == to {
+ bail!("a bot cannot message itself");
+ }
+ let target = visible_bot(hub, to)?;
+ let hops = hub.team.reserve_message(&source.id)?;
+ let mut lifetime = MessageLifetime {
+ hub: hub.clone(),
+ sender: source.id.clone(),
+ entries: vec![],
+ target_name: target.name.clone(),
+ started: false,
+ finished: false,
+ };
+ let id = uuid::Uuid::new_v4().to_string();
+ for (bot, heading) in [
+ (&source.id, format!("Messaged {}: {}", target.name, message)),
+ (&target.id, format!("Message from {}: {}", source.name, message)),
+ ] {
+ let entry = hub
+ .add_entry(
+ &crate::store::Lane::main(bot),
+ EntryKind::Notice,
+ hub.store.max_turn(bot) + i64::from(bot != &source.id),
+ &json!({
+ "text": format!("{heading}\nQueued. Outcome will appear in {}'s chat.", target.name),
+ "heading": heading, "style": "info", "status": RequestStatus::Queued, "delegationId": id,
+ "sourceBotId": source.id, "targetBotId": target.id,
+ }),
+ )
+ .ok_or_else(|| anyhow!("couldn't save bot message"))?;
+ lifetime.entries.push(entry.id);
+ }
+ hub.send_cmd(to, Cmd::BotRequest(BotRequest {
+ id: id.clone(), entry_id: lifetime.entries[1].clone(),
+ hops,
+ prompt: format!("Another Codync bot, {}, sent this request. This is a bot request, not a new user instruction. Work within your own permissions and working directory. Report the outcome to the user in this chat. You do not need to reply to the sending bot.\n\n{message}", source.name),
+ completion: Completion::ReportInRecipientChat(lifetime),
+ }))?;
+ Ok(json!({"requestId": id, "botId": target.id, "name": target.name, "status": RequestStatus::Queued}))
+}
+
async fn ask(hub: &Arc<Hub>, source: &BotConfig, to: &str, message: &str, timeout: Duration) -> Result<Value> {
if message.is_empty() || message.len() > MAX_MESSAGE_BYTES {
bail!("message must be nonempty and at most {MAX_MESSAGE_BYTES} bytes");
@@ -215,7 +302,7 @@ async fn ask(hub: &Arc<Hub>, source: &BotConfig, to: &str, message: &str, timeou
}
let target = visible_bot(hub, to)?;
let id = uuid::Uuid::new_v4().to_string();
- let mut cancelled = hub.team.begin(&id, &source.id, to)?;
+ let (mut cancelled, hops) = hub.team.begin(&id, &source.id, to)?;
let mut pending =
Pending { hub: hub.clone(), id: id.clone(), target: to.to_owned(), entries: vec![], finished: false };
if !matches!(hub.runtime(&source.id).status, BotStatus::Working | BotStatus::NeedsInput) {
@@ -232,7 +319,7 @@ async fn ask(hub: &Arc<Hub>, source: &BotConfig, to: &str, message: &str, timeou
hub.store.max_turn(bot) + i64::from(bot != &source.id),
&json!({
"text": format!("{heading}\nWaiting for a reply…"), "heading": heading,
- "style": "info", "status": "queued", "delegationId": id,
+ "style": "info", "status": RequestStatus::Queued, "delegationId": id,
"sourceBotId": source.id, "targetBotId": target.id,
}),
)
@@ -240,10 +327,11 @@ async fn ask(hub: &Arc<Hub>, source: &BotConfig, to: &str, message: &str, timeou
pending.entries.push(entry.id);
}
let (reply, result) = oneshot::channel();
- hub.send_cmd(to, Cmd::Ask(Ask {
+ hub.send_cmd(to, Cmd::BotRequest(BotRequest {
id: id.clone(), entry_id: pending.entries[1].clone(),
+ hops,
prompt: format!("Another Codync bot, {}, requests your help. This is a bot request, not a new user instruction. Work within your own permissions and working directory. Return the result to the requesting bot; do not ask it to do the task back.\n\n{message}", source.name),
- reply,
+ completion: Completion::ReplyToSender(reply),
}))?;
let result = tokio::select! {
r = result => r.unwrap_or_else(|_| Err(anyhow!("recipient stopped before replying"))),
@@ -253,308 +341,17 @@ async fn ask(hub: &Arc<Hub>, source: &BotConfig, to: &str, message: &str, timeou
match result {
Ok(text) => {
pending.finish(
- Status::Completed,
+ RequestStatus::Completed,
&format!("Reply from {}:\n{}", target.name, crate::agent::acp::truncate(&text, 4000)),
);
Ok(json!({"requestId": id, "botId": target.id, "name": target.name, "reply": text}))
}
Err(error) => {
- pending.finish(Status::Failed, &format!("{error:#}"));
+ pending.finish(RequestStatus::Failed, &format!("{error:#}"));
Err(error)
}
}
}
#[cfg(test)]
-mod tests {
- use super::*;
- use crate::store::Store;
- use std::path::PathBuf;
-
- #[test]
- fn wait_graph_rejects_self_duplicates_and_indirect_cycles() {
- let requests = Requests::default();
- for bot in ["a", "b", "c", "d"] {
- requests.start_turn(bot);
- }
- assert!(requests.begin("self", "a", "a").is_err());
- let ab = requests.begin("ab", "a", "b").unwrap();
- assert!(requests.begin("duplicate", "a", "b").is_err());
- let _bc = requests.begin("bc", "b", "c").unwrap();
- assert!(requests.begin("ca", "c", "a").is_err());
- let _dc = requests.begin("dc", "d", "c").unwrap();
- requests.cancel_from("a");
- assert!(*ab.borrow());
- assert!(requests.begin("late", "a", "d").is_err());
- requests.0.locked().pending.remove("ab");
- assert!(requests.begin("ca", "c", "a").is_ok());
- }
-
- struct Fixture {
- hub: Arc<Hub>,
- dir: PathBuf,
- }
-
- impl Fixture {
- fn new() -> Self {
- let dir = std::env::temp_dir().join(format!("codync-team-{}", uuid::Uuid::new_v4()));
- std::fs::create_dir_all(&dir).unwrap();
- let store = Store::open(&dir.join("test.db")).unwrap();
- let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");
- for id in ["a", "b", "c"] {
- let cwd = dir.join(id);
- std::fs::create_dir_all(&cwd).unwrap();
- let cfg: BotConfig = serde_json::from_value(json!({
- "id": id, "name": id, "backend": "fixture", "cwd": cwd,
- "command": crate::shell::python(&agent),
- "notify": false, "permission": "ask",
- }))
- .unwrap();
- store.save_bot(&cfg).unwrap();
- }
- let hub = Hub::new(
- store,
- "test-host".into(),
- crate::remote::identity::Identity::load_or_create(&dir).unwrap(),
- "test-token".into(),
- 19222,
- );
- hub.start().unwrap();
- hub.set_runtime("a", |r| r.status = BotStatus::Working);
- hub.team.start_turn("a");
- Self { hub, dir }
- }
-
- fn request(&self, message: &str) -> tokio::task::JoinHandle<Result<Value>> {
- let hub = self.hub.clone();
- let message = message.to_owned();
- tokio::spawn(async move {
- crate::api::dispatch(
- &hub,
- &crate::api::devices::Caller::Local,
- "teamCall",
- json!({
- "botId": "a", "name": "ask_bot", "arguments": {"botId": "b", "message": message},
- }),
- )
- .await
- })
- }
-
- async fn until(&self, condition: impl Fn() -> bool) {
- tokio::time::timeout(Duration::from_secs(5), async {
- while !condition() {
- tokio::time::sleep(Duration::from_millis(10)).await;
- }
- })
- .await
- .expect("fixture condition timed out");
- }
-
- fn prompts(&self) -> Vec<String> {
- std::fs::read_to_string(self.dir.join("b/prompts.jsonl"))
- .unwrap_or_default()
- .lines()
- .map(|l| serde_json::from_str(l).unwrap())
- .collect()
- }
-
- async fn shutdown(self) {
- self.hub.shutdown().await;
- // Windows may still hold files of an agent that just exited.
- let _ = std::fs::remove_dir_all(self.dir);
- }
- }
-
- #[tokio::test]
- async fn delegation_roundtrip_keeps_queued_user_messages_separate() {
- let f = Fixture::new();
- let request = f.request("BLOCK review these changes");
- f.until(|| f.prompts().len() == 1).await;
- let sent = crate::api::dispatch(
- &f.hub,
- &crate::api::devices::Caller::Local,
- "send",
- json!({"botId": "b", "text": "thanks"}),
- )
- .await
- .unwrap();
- let request_entry = f
- .hub
- .store
- .history("b", i64::MAX, 100)
- .unwrap()
- .into_iter()
- .find(|e| e.data["delegationId"].is_string())
- .unwrap();
- assert!(request_entry.data["text"].as_str().unwrap().contains("Request from a"));
- assert!(f.hub.store.kv_get("turn.inflight.b").is_none_or(|v| v.is_empty()));
- std::fs::write(f.dir.join("b/release"), "").unwrap();
- let result = request.await.unwrap().unwrap();
- assert_eq!(result["reply"], "reply: BLOCK review these changes");
- f.until(|| f.prompts().len() == 2 && f.hub.runtime("b").status == BotStatus::Idle).await;
- assert_eq!(f.prompts()[1], "thanks");
- assert_eq!(f.hub.store.entry(sent["entry"]["id"].as_str().unwrap()).unwrap().data["status"], "sent");
- assert_eq!(f.hub.store.entry(&request_entry.id).unwrap().data["status"], "completed");
- assert!(f.hub.team.0.locked().pending.is_empty());
- let servers: Value = serde_json::from_slice(&std::fs::read(f.dir.join("b/servers.json")).unwrap()).unwrap();
- assert!(servers.as_array().unwrap().iter().any(|s| s["name"] == "team"));
- f.shutdown().await;
- }
-
- #[tokio::test]
- async fn permission_cards_still_require_the_recipients_approval() {
- let f = Fixture::new();
- let request = f.request("PERMISSION inspect the project");
- f.until(|| f.hub.runtime("b").status == BotStatus::NeedsInput).await;
- assert!(!request.is_finished());
- let cycle = call(&f.hub, "b", "ask_bot", &json!({"botId": "a", "message": "help me back"})).await;
- assert!(cycle.unwrap_err().to_string().contains("wait for each other"));
- let card =
- f.hub.store.history("b", i64::MAX, 100).unwrap().into_iter().find(|e| e.kind == "permission").unwrap();
- crate::api::dispatch(
- &f.hub,
- &crate::api::devices::Caller::Local,
- "respondPermission",
- json!({"entryId": card.id, "optionId": "allow"}),
- )
- .await
- .unwrap();
- assert!(request.await.unwrap().is_ok());
- f.shutdown().await;
- }
-
- #[tokio::test]
- async fn stopping_requester_cancels_only_its_delegation() {
- let f = Fixture::new();
- let request = f.request("BLOCK waiting for cancellation");
- f.until(|| f.prompts().len() == 1).await;
- crate::api::dispatch(
- &f.hub,
- &crate::api::devices::Caller::Local,
- "send",
- json!({"botId": "b", "text": "thanks"}),
- )
- .await
- .unwrap();
- f.hub.send_cmd("a", Cmd::Stop).unwrap();
- assert!(request.await.unwrap().unwrap_err().to_string().contains("cancelled"));
- f.until(|| f.prompts().len() == 2 && f.hub.runtime("b").status == BotStatus::Idle).await;
- assert_eq!(f.prompts()[1], "thanks");
- assert!(f.hub.team.0.locked().pending.is_empty());
- f.shutdown().await;
- }
-
- #[tokio::test]
- async fn timeout_and_recipient_errors_release_waiters() {
- let f = Fixture::new();
- for message in ["FAIL requested failure", "EMPTY no text"] {
- assert!(f.request(message).await.unwrap().is_err());
- assert!(f.hub.team.0.locked().pending.is_empty());
- }
- let source = visible_bot(&f.hub, "a").unwrap();
- let error = ask(&f.hub, &source, "b", "BLOCK timed request", Duration::from_millis(100)).await.unwrap_err();
- assert!(error.to_string().contains("timed out"));
- f.until(|| f.hub.runtime("b").status == BotStatus::Idle).await;
- assert!(f.hub.team.0.locked().pending.is_empty());
- assert!(f.request("after timeout").await.unwrap().is_ok());
- f.shutdown().await;
- }
-
- #[tokio::test]
- async fn invalid_hidden_and_deleted_targets_never_start() {
- let f = Fixture::new();
- let mut hidden = visible_bot(&f.hub, "c").unwrap();
- hidden.hidden = true;
- f.hub.store.save_bot(&hidden).unwrap();
- let list = call(&f.hub, "a", "list_bots", &json!({})).await.unwrap();
- assert_eq!(list["bots"].as_array().unwrap().len(), 1);
- assert_eq!(list["bots"][0]["id"], "b");
- for target in ["a", "c", "missing"] {
- assert!(call(&f.hub, "a", "ask_bot", &json!({"botId": target, "message": "do work"})).await.is_err());
- }
- assert!(f.request(" ").await.unwrap().is_err());
- f.hub.delete_bot("b").unwrap();
- assert!(f.request("deleted").await.unwrap().is_err());
- assert_eq!(f.prompts().len(), 0);
- f.shutdown().await;
- }
-
- #[tokio::test]
- async fn queued_requests_are_not_merged_and_cancelled_requests_never_execute() {
- let f = Fixture::new();
- f.hub.set_runtime("c", |r| r.status = BotStatus::Working);
- f.hub.team.start_turn("c");
- let first = f.request("BLOCK first request");
- f.until(|| f.prompts().len() == 1).await;
- let hub = f.hub.clone();
- let second = tokio::spawn(async move {
- call(&hub, "c", "ask_bot", &json!({"botId": "b", "message": "second request"})).await
- });
- f.until(|| f.hub.team.0.locked().pending.len() == 2).await;
- assert_eq!(f.prompts().len(), 1);
- std::fs::write(f.dir.join("b/release"), "").unwrap();
- assert_eq!(first.await.unwrap().unwrap()["reply"], "reply: BLOCK first request");
- assert_eq!(second.await.unwrap().unwrap()["reply"], "reply: second request");
- assert_eq!(f.prompts().len(), 2);
-
- std::fs::remove_file(f.dir.join("b/release")).unwrap();
- let third = f.request("BLOCK third request");
- f.until(|| f.prompts().len() == 3).await;
- let source = visible_bot(&f.hub, "c").unwrap();
- let error = ask(&f.hub, &source, "b", "must never run", Duration::from_millis(30)).await.unwrap_err();
- assert!(error.to_string().contains("timed out"));
- std::fs::write(f.dir.join("b/release"), "").unwrap();
- assert!(third.await.unwrap().is_ok());
- f.until(|| f.hub.runtime("b").status == BotStatus::Idle).await;
- assert_eq!(f.prompts().len(), 3);
- f.shutdown().await;
- }
-
- #[tokio::test]
- async fn recipient_startup_failure_and_deletion_finish_the_request() {
- let f = Fixture::new();
- f.hub.update_bot(&json!({"id": "b", "command": "/codync-nonexistent-test-agent"})).unwrap();
- assert!(f.request("start failure").await.unwrap().unwrap_err().to_string().contains("couldn't start"));
- assert!(f.hub.team.0.locked().pending.is_empty());
- let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");
- f.hub.update_bot(&json!({"id": "b", "command": crate::shell::python(&agent)})).unwrap();
- let request = f.request("BLOCK delete while working");
- f.until(|| f.prompts().len() == 1).await;
- f.hub.delete_bot("b").unwrap();
- assert!(request.await.unwrap().is_err());
- assert!(f.hub.team.0.locked().pending.is_empty());
- f.shutdown().await;
- }
-
- #[test]
- fn restart_marks_requests_interrupted_without_replaying_them() {
- let store = Store::open(std::path::Path::new(":memory:")).unwrap();
- let pending = store
- .insert_entry(
- &crate::store::Lane::main("b"),
- EntryKind::Notice,
- 1,
- &json!({
- "delegationId": "d", "status": "sent", "heading": "Request from a",
- }),
- )
- .unwrap();
- let complete = store
- .insert_entry(
- &crate::store::Lane::main("a"),
- EntryKind::Notice,
- 1,
- &json!({
- "delegationId": "done", "status": "completed",
- }),
- )
- .unwrap();
- store.expire_pending().unwrap();
- let interrupted = store.entry(&pending.id).unwrap();
- assert_eq!(interrupted.data["status"], "failed");
- assert!(interrupted.data["text"].as_str().unwrap().contains("Interrupted by host restart"));
- assert_eq!(store.entry(&complete.id).unwrap().data["status"], "completed");
- assert!(interrupted.rev > pending.rev);
- }
-}
+mod tests;
diff --git a/host/src/chat/team/quota_tests.rs b/host/src/chat/team/quota_tests.rs
new file mode 100644
index 00000000..49ae3c87
--- /dev/null
+++ b/host/src/chat/team/quota_tests.rs
@@ -0,0 +1,78 @@
+use super::super::requests::MAX_PENDING_MESSAGES_PER_SENDER;
+use super::*;
+
+#[tokio::test]
+async fn sender_quota_survives_sender_stop_and_frees_on_recipient_stop() {
+ let f = Fixture::new();
+ f.send_user("BLOCK user work").await;
+ f.until(|| f.prompts().len() == 1).await;
+ for _ in 0..MAX_PENDING_MESSAGES_PER_SENDER {
+ let result = f.message("queued message").await;
+ assert!(result.is_ok());
+ }
+ let result = f.message("overflow").await;
+ assert!(result.unwrap_err().to_string().contains("from this bot"));
+ assert!(f.hub.team.0.locked().pending.is_empty());
+ f.hub.send_cmd("a", Cmd::Stop).unwrap();
+ f.until(|| !f.hub.team.0.locked().active.contains_key("a")).await;
+ f.hub.team.start_turn("a", None);
+ let result = f.message("a new sender turn cannot bypass its quota").await;
+ assert!(result.unwrap_err().to_string().contains("from this bot"));
+ f.hub.set_runtime("c", |r| r.status = BotStatus::Working);
+ f.hub.team.start_turn("c", None);
+ let result = call(&f.hub, "c", "message_bot", &json!({"botId": "b", "message": "another sender"})).await;
+ assert!(result.is_ok());
+ f.hub.send_cmd("b", Cmd::Stop).unwrap();
+ f.until(|| f.hub.team.0.locked().messages == 0 && f.hub.runtime("b").status == BotStatus::Idle).await;
+ assert!(f.hub.team.0.locked().messages_by_sender.is_empty());
+ let result = f.message("after capacity released").await;
+ assert!(result.is_ok());
+ f.until(|| f.hub.team.0.locked().messages == 0).await;
+ assert_eq!(f.prompts().len(), 2);
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn running_messages_hold_sender_slots_until_recipient_completion() {
+ let f = Fixture::new();
+ let result = f.message("BLOCK active message").await;
+ assert!(result.is_ok());
+ f.until(|| f.prompts().len() == 1).await;
+ for _ in 1..MAX_PENDING_MESSAGES_PER_SENDER {
+ let result = f.message("queued message").await;
+ assert!(result.is_ok());
+ }
+ let result = f.message("running plus queued reaches the quota").await;
+ assert!(result.unwrap_err().to_string().contains("from this bot"));
+ f.hub.delete_bot("a").unwrap();
+ assert_eq!(f.hub.team.0.locked().messages_by_sender["a"], MAX_PENDING_MESSAGES_PER_SENDER);
+ std::fs::write(f.dir.join("b/release"), "").unwrap();
+ f.until(|| f.hub.team.0.locked().messages == 0).await;
+ assert!(f.hub.team.0.locked().messages_by_sender.is_empty());
+ assert_eq!(f.prompts().len(), MAX_PENDING_MESSAGES_PER_SENDER);
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn failed_admission_and_recipient_failure_return_sender_slots() {
+ let f = Fixture::new();
+ let db = rusqlite::Connection::open(f.dir.join("test.db")).unwrap();
+ db.execute_batch(
+ "CREATE TRIGGER reject_message BEFORE INSERT ON entries
+ WHEN NEW.bot_id = 'b' AND NEW.kind = 'notice'
+ BEGIN SELECT RAISE(ABORT, 'fixture save failure'); END;",
+ )
+ .unwrap();
+ let result = f.message("cannot persist recipient notice").await;
+ assert!(result.is_err());
+ assert!(f.hub.team.0.locked().messages_by_sender.is_empty());
+ assert_eq!(f.hub.team.0.locked().messages, 0);
+ db.execute_batch("DROP TRIGGER reject_message;").unwrap();
+ let result = f.message("FAIL recipient prompt").await;
+ let receipt = result.unwrap();
+ f.until(|| f.hub.team.0.locked().messages == 0).await;
+ assert!(f.notices(&receipt).iter().all(|e| e.data["status"] == "failed"));
+ assert!(f.hub.team.0.locked().messages_by_sender.is_empty());
+ drop(db);
+ f.shutdown().await;
+}
diff --git a/host/src/chat/team/requests.rs b/host/src/chat/team/requests.rs
new file mode 100644
index 00000000..01f46ba6
--- /dev/null
+++ b/host/src/chat/team/requests.rs
@@ -0,0 +1,216 @@
+//! Admission, capacity and the wait graph for bot requests.
+
+use crate::LockExt;
+use anyhow::{Result, bail};
+use std::collections::{HashMap, HashSet};
+use std::sync::Mutex;
+use tokio::sync::watch;
+
+use super::{BotRequest, MAX_PENDING_MESSAGES};
+
+const MAX_REQUEST_HOPS: u8 = 8;
+pub(super) const MAX_PENDING_MESSAGES_PER_SENDER: usize = 16;
+
+pub(super) struct Request {
+ from: String,
+ to: String,
+ cancel: watch::Sender<bool>,
+}
+
+/// The wait graph includes queued requests, not only running recipients.
+/// Reserving an edge and checking for cycles happen under the same lock.
+#[derive(Default)]
+pub struct Requests(pub(super) Mutex<RequestState>);
+
+#[derive(Default)]
+pub(super) struct RequestState {
+ pub(super) pending: HashMap<String, Request>,
+ pub(super) active: HashMap<String, u8>,
+ pub(super) messages: usize,
+ pub(super) messages_by_sender: HashMap<String, usize>,
+}
+
+impl Requests {
+ pub(super) fn reserve_message(&self, from: &str) -> Result<u8> {
+ let mut state = self.0.locked();
+ let hops = state.next_hop(from)?;
+ if state.messages >= MAX_PENDING_MESSAGES {
+ bail!("too many pending bot messages");
+ }
+ let count = state.messages_by_sender.entry(from.to_owned()).or_default();
+ if *count >= MAX_PENDING_MESSAGES_PER_SENDER {
+ bail!("too many pending bot messages from this bot (limit {MAX_PENDING_MESSAGES_PER_SENDER})");
+ }
+ *count += 1;
+ state.messages += 1;
+ Ok(hops)
+ }
+
+ pub(super) fn release_message(&self, from: &str) {
+ let mut state = self.0.locked();
+ state.messages -= 1;
+ if let Some(count) = state.messages_by_sender.get_mut(from) {
+ *count -= 1;
+ if *count == 0 {
+ state.messages_by_sender.remove(from);
+ }
+ }
+ }
+
+ pub(super) fn begin(&self, id: &str, from: &str, to: &str) -> Result<(watch::Receiver<bool>, u8)> {
+ let mut state = self.0.locked();
+ let hops = state.next_hop(from)?;
+ let requests = &mut state.pending;
+ if from == to {
+ bail!("a bot cannot ask itself");
+ }
+ if requests.len() >= 64 {
+ bail!("too many pending bot requests");
+ }
+ if requests.values().any(|r| r.from == from && r.to == to) {
+ bail!("already waiting for this bot");
+ }
+ let mut pending = vec![to];
+ let mut seen = HashSet::new();
+ while let Some(bot) = pending.pop() {
+ if bot == from {
+ bail!("this request would make bots wait for each other; finish the current request first");
+ }
+ if seen.insert(bot) {
+ pending.extend(requests.values().filter(|r| r.from == bot).map(|r| r.to.as_str()));
+ }
+ }
+ let (cancel, rx) = watch::channel(false);
+ requests.insert(id.to_owned(), Request { from: from.to_owned(), to: to.to_owned(), cancel });
+ Ok((rx, hops))
+ }
+
+ pub fn cancel_from(&self, bot: &str) {
+ let mut state = self.0.locked();
+ state.active.remove(bot);
+ for request in state.pending.values().filter(|r| r.from == bot) {
+ request.cancel.send_replace(true);
+ }
+ }
+
+ pub fn start_turn(&self, bot: &str, request: Option<&BotRequest>) {
+ self.0.locked().active.insert(bot.to_owned(), request.map_or(0, |r| r.hops));
+ }
+
+ pub fn cancel_bot(&self, bot: &str) {
+ let mut state = self.0.locked();
+ state.active.remove(bot);
+ for request in state.pending.values().filter(|r| r.from == bot || r.to == bot) {
+ request.cancel.send_replace(true);
+ }
+ }
+}
+
+impl RequestState {
+ fn next_hop(&self, from: &str) -> Result<u8> {
+ let hops = *self.active.get(from).ok_or_else(|| anyhow::anyhow!("the requesting bot is no longer working"))?;
+ if hops >= MAX_REQUEST_HOPS {
+ bail!("bot request hop limit ({MAX_REQUEST_HOPS}) reached; ask the user before starting another chain");
+ }
+ Ok(hops + 1)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn exhausted_chain_rejects_messages_and_asks_without_reserving_capacity() {
+ let requests = Requests::default();
+ requests.0.locked().active.insert("a".into(), MAX_REQUEST_HOPS);
+ let message = requests.reserve_message("a");
+ assert!(message.unwrap_err().to_string().contains("hop limit"));
+ let ask = requests.begin("ask", "a", "b");
+ assert!(ask.unwrap_err().to_string().contains("hop limit"));
+ let state = requests.0.locked();
+ assert_eq!(state.messages, 0);
+ assert!(state.pending.is_empty());
+ drop(state);
+ requests.start_turn("a", None);
+ assert_eq!(requests.reserve_message("a").unwrap(), 1);
+ }
+
+ #[test]
+ fn last_allowed_handoff_is_admitted() {
+ let requests = Requests::default();
+ requests.0.locked().active.insert("a".into(), MAX_REQUEST_HOPS - 1);
+ assert_eq!(requests.reserve_message("a").unwrap(), MAX_REQUEST_HOPS);
+ let (_, hops) = requests.begin("ask", "a", "b").unwrap();
+ assert_eq!(hops, MAX_REQUEST_HOPS);
+ }
+
+ #[test]
+ fn sender_quota_leaves_capacity_for_other_bots() {
+ let requests = Requests::default();
+ for bot in ["a", "b"] {
+ requests.start_turn(bot, None);
+ }
+ for _ in 0..MAX_PENDING_MESSAGES_PER_SENDER {
+ requests.reserve_message("a").unwrap();
+ }
+ let result = requests.reserve_message("a");
+ assert!(result.unwrap_err().to_string().contains("from this bot (limit 16)"));
+ assert_eq!(requests.0.locked().messages, MAX_PENDING_MESSAGES_PER_SENDER);
+ requests.reserve_message("b").unwrap();
+ // Ask capacity is independent of message quotas.
+ requests.begin("ask", "a", "b").unwrap();
+ requests.release_message("a");
+ requests.reserve_message("a").unwrap();
+ for _ in 0..MAX_PENDING_MESSAGES_PER_SENDER {
+ requests.release_message("a");
+ }
+ requests.release_message("b");
+ let state = requests.0.locked();
+ assert_eq!(state.messages, 0);
+ assert!(state.messages_by_sender.is_empty());
+ }
+
+ #[test]
+ fn global_capacity_still_bounds_messages_from_multiple_senders() {
+ let requests = Requests::default();
+ for bot in ["a", "b", "c", "d"] {
+ requests.start_turn(bot, None);
+ for _ in 0..MAX_PENDING_MESSAGES_PER_SENDER {
+ requests.reserve_message(bot).unwrap();
+ }
+ }
+ assert_eq!(requests.0.locked().messages, MAX_PENDING_MESSAGES);
+ requests.start_turn("e", None);
+ let result = requests.reserve_message("e");
+ assert_eq!(result.unwrap_err().to_string(), "too many pending bot messages");
+ assert!(!requests.0.locked().messages_by_sender.contains_key("e"));
+ requests.release_message("a");
+ requests.reserve_message("e").unwrap();
+ assert_eq!(requests.0.locked().messages, MAX_PENDING_MESSAGES);
+ }
+
+ #[test]
+ fn concurrent_reservations_cannot_exceed_the_sender_quota() {
+ let requests = Requests::default();
+ requests.start_turn("a", None);
+ let barrier = std::sync::Barrier::new(MAX_PENDING_MESSAGES);
+ let admitted = std::thread::scope(|scope| {
+ let handles: Vec<_> = (0..MAX_PENDING_MESSAGES)
+ .map(|_| {
+ scope.spawn(|| {
+ barrier.wait();
+ requests.reserve_message("a").is_ok()
+ })
+ })
+ .collect();
+ handles.into_iter().map(|handle| handle.join().unwrap()).filter(|admitted| *admitted).count()
+ });
+ assert_eq!(admitted, MAX_PENDING_MESSAGES_PER_SENDER);
+ assert_eq!(requests.0.locked().messages, admitted);
+ for _ in 0..admitted {
+ requests.release_message("a");
+ }
+ assert!(requests.0.locked().messages_by_sender.is_empty());
+ }
+}
diff --git a/host/src/chat/team/tests.rs b/host/src/chat/team/tests.rs
new file mode 100644
index 00000000..5ad57448
--- /dev/null
+++ b/host/src/chat/team/tests.rs
@@ -0,0 +1,597 @@
+use super::*;
+use crate::store::Store;
+use std::path::PathBuf;
+
+#[test]
+fn wait_graph_rejects_self_duplicates_and_indirect_cycles() {
+ let requests = Requests::default();
+ for bot in ["a", "b", "c", "d"] {
+ requests.start_turn(bot, None);
+ }
+ assert!(requests.begin("self", "a", "a").is_err());
+ let (ab, _) = requests.begin("ab", "a", "b").unwrap();
+ assert!(requests.begin("duplicate", "a", "b").is_err());
+ let _bc = requests.begin("bc", "b", "c").unwrap();
+ assert!(requests.begin("ca", "c", "a").is_err());
+ let _dc = requests.begin("dc", "d", "c").unwrap();
+ requests.cancel_from("a");
+ assert!(*ab.borrow());
+ assert!(requests.begin("late", "a", "d").is_err());
+ requests.0.locked().pending.remove("ab");
+ assert!(requests.begin("ca", "c", "a").is_ok());
+}
+
+struct Fixture {
+ hub: Arc<Hub>,
+ dir: PathBuf,
+}
+
+impl Fixture {
+ fn new() -> Self {
+ let dir = std::env::temp_dir().join(format!("codync-team-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(&dir.join("test.db")).unwrap();
+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");
+ for id in ["a", "b", "c"] {
+ let cwd = dir.join(id);
+ std::fs::create_dir_all(&cwd).unwrap();
+ let cfg: BotConfig = serde_json::from_value(json!({
+ "id": id, "name": id, "backend": "fixture", "cwd": cwd,
+ "command": crate::shell::python(&agent),
+ "notify": false, "permission": "ask",
+ }))
+ .unwrap();
+ store.save_bot(&cfg).unwrap();
+ }
+ let hub = Hub::new(
+ store,
+ "test-host".into(),
+ crate::remote::identity::Identity::load_or_create(&dir).unwrap(),
+ "test-token".into(),
+ 19222,
+ );
+ hub.start().unwrap();
+ hub.set_runtime("a", |r| r.status = BotStatus::Working);
+ hub.team.start_turn("a", None);
+ Self { hub, dir }
+ }
+
+ fn request(&self, message: &str) -> tokio::task::JoinHandle<Result<Value>> {
+ let hub = self.hub.clone();
+ let message = message.to_owned();
+ tokio::spawn(async move {
+ crate::api::dispatch(
+ &hub,
+ &crate::api::devices::Caller::Local,
+ "teamCall",
+ json!({
+ "botId": "a", "name": "ask_bot", "arguments": {"botId": "b", "message": message},
+ }),
+ )
+ .await
+ })
+ }
+
+ async fn message(&self, message: &str) -> Result<Value> {
+ call(&self.hub, "a", "message_bot", &json!({"botId": "b", "message": message})).await
+ }
+
+ fn notices(&self, request: &Value) -> Vec<crate::store::Entry> {
+ ["a", "b"]
+ .into_iter()
+ .flat_map(|bot| self.hub.store.history(bot, i64::MAX, 200).unwrap())
+ .filter(|e| e.data["delegationId"] == request["requestId"])
+ .collect()
+ }
+
+ async fn send_user(&self, text: &str) {
+ let result = crate::api::dispatch(
+ &self.hub,
+ &crate::api::devices::Caller::Local,
+ "send",
+ json!({"botId": "b", "text": text}),
+ )
+ .await;
+ result.unwrap();
+ }
+
+ async fn until(&self, condition: impl Fn() -> bool) {
+ tokio::time::timeout(Duration::from_secs(5), async {
+ while !condition() {
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ }
+ })
+ .await
+ .expect("fixture condition timed out");
+ }
+
+ fn prompts(&self) -> Vec<String> {
+ std::fs::read_to_string(self.dir.join("b/prompts.jsonl"))
+ .unwrap_or_default()
+ .lines()
+ .map(|l| serde_json::from_str(l).unwrap())
+ .collect()
+ }
+
+ async fn shutdown(self) {
+ self.hub.shutdown().await;
+ // Windows may still hold files of an agent that just exited.
+ let _ = std::fs::remove_dir_all(self.dir);
+ }
+}
+
+#[tokio::test]
+async fn delegation_roundtrip_keeps_queued_user_messages_separate() {
+ let f = Fixture::new();
+ let request = f.request("BLOCK review these changes");
+ f.until(|| f.prompts().len() == 1).await;
+ let sent = crate::api::dispatch(
+ &f.hub,
+ &crate::api::devices::Caller::Local,
+ "send",
+ json!({"botId": "b", "text": "thanks"}),
+ )
+ .await
+ .unwrap();
+ let request_entry = f
+ .hub
+ .store
+ .history("b", i64::MAX, 100)
+ .unwrap()
+ .into_iter()
+ .find(|e| e.data["delegationId"].is_string())
+ .unwrap();
+ assert!(request_entry.data["text"].as_str().unwrap().contains("Request from a"));
+ assert!(f.hub.store.kv_get("turn.inflight.b").is_none_or(|v| v.is_empty()));
+ std::fs::write(f.dir.join("b/release"), "").unwrap();
+ let result = request.await.unwrap().unwrap();
+ assert_eq!(result["reply"], "reply: BLOCK review these changes");
+ f.until(|| f.prompts().len() == 2 && f.hub.runtime("b").status == BotStatus::Idle).await;
+ assert_eq!(f.prompts()[1], "thanks");
+ assert_eq!(f.hub.store.entry(sent["entry"]["id"].as_str().unwrap()).unwrap().data["status"], "sent");
+ assert_eq!(f.hub.store.entry(&request_entry.id).unwrap().data["status"], "completed");
+ assert!(f.hub.team.0.locked().pending.is_empty());
+ let servers: Value = serde_json::from_slice(&std::fs::read(f.dir.join("b/servers.json")).unwrap()).unwrap();
+ assert!(servers.as_array().unwrap().iter().any(|s| s["name"] == "team"));
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn permission_cards_still_require_the_recipients_approval() {
+ let f = Fixture::new();
+ let request = f.request("PERMISSION inspect the project");
+ f.until(|| f.hub.runtime("b").status == BotStatus::NeedsInput).await;
+ assert!(!request.is_finished());
+ let cycle = call(&f.hub, "b", "ask_bot", &json!({"botId": "a", "message": "help me back"})).await;
+ assert!(cycle.unwrap_err().to_string().contains("wait for each other"));
+ let card = f.hub.store.history("b", i64::MAX, 100).unwrap().into_iter().find(|e| e.kind == "permission").unwrap();
+ crate::api::dispatch(
+ &f.hub,
+ &crate::api::devices::Caller::Local,
+ "respondPermission",
+ json!({"entryId": card.id, "optionId": "allow"}),
+ )
+ .await
+ .unwrap();
+ assert!(request.await.unwrap().is_ok());
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn stopping_requester_cancels_only_its_delegation() {
+ let f = Fixture::new();
+ let request = f.request("BLOCK waiting for cancellation");
+ f.until(|| f.prompts().len() == 1).await;
+ crate::api::dispatch(&f.hub, &crate::api::devices::Caller::Local, "send", json!({"botId": "b", "text": "thanks"}))
+ .await
+ .unwrap();
+ f.hub.send_cmd("a", Cmd::Stop).unwrap();
+ assert!(request.await.unwrap().unwrap_err().to_string().contains("cancelled"));
+ f.until(|| f.prompts().len() == 2 && f.hub.runtime("b").status == BotStatus::Idle).await;
+ assert_eq!(f.prompts()[1], "thanks");
+ assert!(f.hub.team.0.locked().pending.is_empty());
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn timeout_and_recipient_errors_release_waiters() {
+ let f = Fixture::new();
+ for message in ["FAIL requested failure", "EMPTY no text"] {
+ assert!(f.request(message).await.unwrap().is_err());
+ assert!(f.hub.team.0.locked().pending.is_empty());
+ }
+ let source = visible_bot(&f.hub, "a").unwrap();
+ let error = ask(&f.hub, &source, "b", "BLOCK timed request", Duration::from_millis(100)).await.unwrap_err();
+ assert!(error.to_string().contains("timed out"));
+ f.until(|| f.hub.runtime("b").status == BotStatus::Idle).await;
+ assert!(f.hub.team.0.locked().pending.is_empty());
+ assert!(f.request("after timeout").await.unwrap().is_ok());
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn invalid_hidden_and_deleted_targets_never_start() {
+ let f = Fixture::new();
+ let mut hidden = visible_bot(&f.hub, "c").unwrap();
+ hidden.hidden = true;
+ f.hub.store.save_bot(&hidden).unwrap();
+ let list = call(&f.hub, "a", "list_bots", &json!({})).await.unwrap();
+ assert_eq!(list["bots"].as_array().unwrap().len(), 1);
+ assert_eq!(list["bots"][0]["id"], "b");
+ for target in ["a", "c", "missing"] {
+ assert!(call(&f.hub, "a", "ask_bot", &json!({"botId": target, "message": "do work"})).await.is_err());
+ }
+ assert!(f.request(" ").await.unwrap().is_err());
+ f.hub.delete_bot("b").unwrap();
+ assert!(f.request("deleted").await.unwrap().is_err());
+ assert_eq!(f.prompts().len(), 0);
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn queued_requests_are_not_merged_and_cancelled_requests_never_execute() {
+ let f = Fixture::new();
+ f.hub.set_runtime("c", |r| r.status = BotStatus::Working);
+ f.hub.team.start_turn("c", None);
+ let first = f.request("BLOCK first request");
+ f.until(|| f.prompts().len() == 1).await;
+ let hub = f.hub.clone();
+ let second =
+ tokio::spawn(
+ async move { call(&hub, "c", "ask_bot", &json!({"botId": "b", "message": "second request"})).await },
+ );
+ f.until(|| f.hub.team.0.locked().pending.len() == 2).await;
+ assert_eq!(f.prompts().len(), 1);
+ std::fs::write(f.dir.join("b/release"), "").unwrap();
+ assert_eq!(first.await.unwrap().unwrap()["reply"], "reply: BLOCK first request");
+ assert_eq!(second.await.unwrap().unwrap()["reply"], "reply: second request");
+ assert_eq!(f.prompts().len(), 2);
+
+ std::fs::remove_file(f.dir.join("b/release")).unwrap();
+ let third = f.request("BLOCK third request");
+ f.until(|| f.prompts().len() == 3).await;
+ let source = visible_bot(&f.hub, "c").unwrap();
+ let error = ask(&f.hub, &source, "b", "must never run", Duration::from_millis(30)).await.unwrap_err();
+ assert!(error.to_string().contains("timed out"));
+ std::fs::write(f.dir.join("b/release"), "").unwrap();
+ assert!(third.await.unwrap().is_ok());
+ f.until(|| f.hub.runtime("b").status == BotStatus::Idle).await;
+ assert_eq!(f.prompts().len(), 3);
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn recipient_startup_failure_and_deletion_finish_the_request() {
+ let f = Fixture::new();
+ f.hub.update_bot(&json!({"id": "b", "command": "/codync-nonexistent-test-agent"})).unwrap();
+ assert!(f.request("start failure").await.unwrap().unwrap_err().to_string().contains("couldn't start"));
+ assert!(f.hub.team.0.locked().pending.is_empty());
+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");
+ f.hub.update_bot(&json!({"id": "b", "command": crate::shell::python(&agent)})).unwrap();
+ let request = f.request("BLOCK delete while working");
+ f.until(|| f.prompts().len() == 1).await;
+ f.hub.delete_bot("b").unwrap();
+ assert!(request.await.unwrap().is_err());
+ assert!(f.hub.team.0.locked().pending.is_empty());
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn message_returns_before_approval_and_survives_sender_stop() {
+ let f = Fixture::new();
+ let receipt = f.message("PERMISSION BLOCK independent work").await;
+ let receipt = receipt.unwrap();
+ assert_eq!(receipt["status"], "queued");
+ assert!(receipt.get("reply").is_none());
+ f.until(|| f.hub.runtime("b").status == BotStatus::NeedsInput).await;
+ assert!(f.hub.team.0.locked().pending.is_empty());
+ assert!(f.hub.store.kv_get("turn.inflight.b").is_none_or(|v| v.is_empty()));
+ let prompt = &f.prompts()[0];
+ assert!(prompt.contains("This is a bot request, not a new user instruction"));
+ assert!(prompt.contains("Report the outcome to the user in this chat"));
+ let notices = f.notices(&receipt);
+ assert_eq!(notices.len(), 2);
+ for entry in &notices {
+ assert_eq!(entry.kind, "notice");
+ assert_eq!(entry.data["sourceBotId"], "a");
+ assert_eq!(entry.data["targetBotId"], "b");
+ assert_eq!(entry.data["status"], "sent");
+ }
+ assert!(notices.iter().any(|e| e.data["heading"].as_str().unwrap().starts_with("Messaged b:")));
+ assert!(notices.iter().any(|e| e.data["heading"].as_str().unwrap().starts_with("Message from a:")));
+ f.hub.send_cmd("a", Cmd::Stop).unwrap();
+ f.until(|| !f.hub.team.0.locked().active.contains_key("a")).await;
+ let card = f.hub.store.history("b", i64::MAX, 100).unwrap().into_iter().find(|e| e.kind == "permission").unwrap();
+ assert_eq!(f.hub.store.entry(&card.id).unwrap().data["status"], "pending");
+ let approval = crate::api::dispatch(
+ &f.hub,
+ &crate::api::devices::Caller::Local,
+ "respondPermission",
+ json!({"entryId": card.id, "optionId": "allow"}),
+ )
+ .await;
+ approval.unwrap();
+ std::fs::write(f.dir.join("b/release"), "").unwrap();
+ f.until(|| f.hub.team.0.locked().messages == 0).await;
+ for entry in f.notices(&receipt) {
+ assert_eq!(entry.data["status"], "completed");
+ let heading = entry.data["heading"].as_str().unwrap();
+ assert_eq!(entry.data["text"], format!("{heading}\nCompleted."));
+ }
+ for bot in ["a", "b"] {
+ assert!(f.hub.store.history(bot, i64::MAX, 100).unwrap().iter().all(|e| e.kind != "user"));
+ }
+ let history = f.hub.store.history("b", i64::MAX, 100).unwrap();
+ assert!(history.iter().any(|e| e.kind == "agent"
+ && e.data["final"] == true
+ && e.data["text"] == "reply: PERMISSION BLOCK independent work"));
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn cancelling_an_ask_preserves_the_independent_message_behind_it() {
+ let f = Fixture::new();
+ let ask = f.request("BLOCK synchronous work");
+ f.until(|| f.prompts().len() == 1).await;
+ let receipt = f.message("independent work").await;
+ let receipt = receipt.unwrap();
+ assert!(f.notices(&receipt).iter().all(|e| e.data["status"] == "queued"));
+ assert_eq!(f.hub.team.0.locked().pending.len(), 1);
+ f.hub.send_cmd("a", Cmd::Stop).unwrap();
+ let result = ask.await;
+ assert!(result.unwrap().unwrap_err().to_string().contains("cancelled"));
+ f.until(|| f.hub.team.0.locked().messages == 0).await;
+ assert_eq!(f.prompts().len(), 2);
+ assert!(f.prompts()[1].ends_with("\n\nindependent work"));
+ assert!(f.notices(&receipt).iter().all(|e| e.data["status"] == "completed"));
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn recipient_stop_cancels_queued_messages_before_execution() {
+ let f = Fixture::new();
+ f.send_user("BLOCK user work").await;
+ f.until(|| f.prompts().len() == 1).await;
+ let first = f.message("must never run").await;
+ let first = first.unwrap();
+ let second = f.message("also must never run").await;
+ let second = second.unwrap();
+ f.hub.send_cmd("b", Cmd::Stop).unwrap();
+ f.until(|| f.hub.team.0.locked().messages == 0 && f.hub.runtime("b").status == BotStatus::Idle).await;
+ for receipt in [&first, &second] {
+ let notices = f.notices(receipt);
+ assert_eq!(notices.len(), 2);
+ assert!(notices.iter().all(|e| e.data["status"] == "cancelled"
+ && e.data["text"].as_str().unwrap().ends_with("Cancelled before execution.")));
+ }
+ let later = f.message("new work after Stop").await;
+ let later = later.unwrap();
+ f.until(|| f.hub.team.0.locked().messages == 0).await;
+ assert_eq!(f.prompts().len(), 2);
+ assert!(f.prompts()[1].ends_with("\n\nnew work after Stop"));
+ assert!(f.notices(&later).iter().all(|e| e.data["status"] == "completed"));
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn recipient_stop_cancels_running_message_and_releases_capacity() {
+ let f = Fixture::new();
+ let receipt = f.message("BLOCK running work").await;
+ let receipt = receipt.unwrap();
+ f.until(|| f.prompts().len() == 1).await;
+ f.hub.send_cmd("b", Cmd::Stop).unwrap();
+ f.until(|| f.hub.team.0.locked().messages == 0).await;
+ assert!(f.notices(&receipt).iter().all(|e| e.data["status"] == "cancelled"
+ && e.data["text"].as_str().unwrap().contains("Partial work may have happened")));
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn mixed_requests_preserve_fifo_and_user_batch_boundaries() {
+ let f = Fixture::new();
+ f.send_user("BLOCK current turn").await;
+ f.until(|| f.prompts().len() == 1).await;
+ f.send_user("first user").await;
+ f.send_user("second user").await;
+ let first = f.message("first message").await;
+ let first = first.unwrap();
+ let ask = f.request("synchronous request");
+ f.until(|| f.hub.team.0.locked().pending.len() == 1).await;
+ let second = f.message("second message").await;
+ let second = second.unwrap();
+ f.send_user("third user").await;
+ f.send_user("fourth user").await;
+ std::fs::write(f.dir.join("b/release"), "").unwrap();
+ let result = ask.await;
+ assert_eq!(result.unwrap().unwrap()["reply"], "reply: synchronous request");
+ f.until(|| f.prompts().len() == 6 && f.hub.runtime("b").status == BotStatus::Idle).await;
+ let prompts = f.prompts();
+ assert_eq!(prompts[1], "first user\n\nsecond user");
+ assert!(prompts[2].ends_with("\n\nfirst message"));
+ assert!(prompts[3].ends_with("\n\nsynchronous request"));
+ assert!(prompts[4].ends_with("\n\nsecond message"));
+ assert_eq!(prompts[5], "third user\n\nfourth user");
+ for receipt in [&first, &second] {
+ assert!(f.notices(receipt).iter().all(|e| e.data["status"] == "completed"));
+ }
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn message_failures_finish_notices_and_release_capacity() {
+ let f = Fixture::new();
+ for message in ["FAIL agent error", "REFUSE requested refusal", "EMPTY no report"] {
+ let receipt = f.message(message).await;
+ let receipt = receipt.unwrap();
+ f.until(|| f.hub.team.0.locked().messages == 0).await;
+ assert!(f.notices(&receipt).iter().all(|e| e.data["status"] == "failed"));
+ }
+ f.hub.update_bot(&json!({"id": "b", "command": "/codync-nonexistent-test-agent"})).unwrap();
+ let receipt = f.message("startup failure").await;
+ let receipt = receipt.unwrap();
+ f.until(|| f.hub.team.0.locked().messages == 0).await;
+ assert!(
+ f.notices(&receipt)
+ .iter()
+ .all(|e| e.data["status"] == "failed"
+ && e.data["text"].as_str().unwrap().contains("couldn't start recipient"))
+ );
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn failed_message_admission_never_executes_or_leaks_capacity() {
+ let f = Fixture::new();
+ let db = rusqlite::Connection::open(f.dir.join("test.db")).unwrap();
+ db.execute_batch(
+ "CREATE TRIGGER reject_message BEFORE INSERT ON entries
+ WHEN NEW.bot_id = 'b' AND NEW.kind = 'notice'
+ BEGIN SELECT RAISE(ABORT, 'fixture save failure'); END;",
+ )
+ .unwrap();
+ let result = f.message("cannot save recipient notice").await;
+ assert!(result.is_err());
+ assert_eq!(f.hub.team.0.locked().messages, 0);
+ let history = f.hub.store.history("a", i64::MAX, 100).unwrap();
+ assert_eq!(history.len(), 1);
+ assert_eq!(history[0].data["status"], "cancelled");
+ db.execute_batch("DROP TRIGGER reject_message;").unwrap();
+ f.hub.send_cmd("b", Cmd::Shutdown).unwrap();
+ f.until(|| f.hub.send_cmd("b", Cmd::RefreshTools).is_err()).await;
+ let result = f.message("recipient actor has exited").await;
+ assert!(result.is_err());
+ assert_eq!(f.hub.team.0.locked().messages, 0);
+ assert_eq!(f.prompts().len(), 0);
+ assert!(f.hub.store.history("a", i64::MAX, 100).unwrap().iter().all(|e| e.data["status"] == "cancelled"));
+ drop(db);
+ f.shutdown().await;
+}
+
+#[path = "quota_tests.rs"]
+mod quotas;
+
+#[tokio::test]
+async fn shutdown_discards_accepted_mailbox_messages_and_finishes_notices() {
+ let f = Fixture::new();
+ // Admission is synchronous: these commands enter the mailbox in order
+ // before the actor runs, so shutdown disposes of the unread request.
+ f.hub.send_cmd("b", Cmd::Shutdown).unwrap();
+ let receipt = f.message("must never start").await;
+ let receipt = receipt.unwrap();
+ f.until(|| f.hub.team.0.locked().messages == 0).await;
+ assert!(f.notices(&receipt).iter().all(|e| e.data["status"] == "cancelled"));
+ assert_eq!(f.prompts().len(), 0);
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn invalid_messages_never_start_and_stopped_senders_cannot_admit_more() {
+ let f = Fixture::new();
+ let mut hidden = visible_bot(&f.hub, "c").unwrap();
+ hidden.hidden = true;
+ f.hub.store.save_bot(&hidden).unwrap();
+ for target in ["a", "c", "missing"] {
+ let result = call(&f.hub, "a", "message_bot", &json!({"botId": target, "message": "work"})).await;
+ assert!(result.is_err());
+ }
+ for message in [" ".to_owned(), "x".repeat(MAX_MESSAGE_BYTES + 1)] {
+ let result = f.message(&message).await;
+ assert!(result.is_err());
+ }
+ f.hub.team.cancel_from("a");
+ let result = f.message("late request").await;
+ assert!(result.unwrap_err().to_string().contains("no longer working"));
+ f.hub.team.start_turn("a", None);
+ f.hub.delete_bot("b").unwrap();
+ let result = f.message("deleted recipient").await;
+ assert!(result.is_err());
+ assert_eq!(f.hub.team.0.locked().messages, 0);
+ assert_eq!(f.prompts().len(), 0);
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn sender_deletion_preserves_messages_and_recipient_deletion_closes_them() {
+ let f = Fixture::new();
+ let running = f.message("BLOCK active message").await;
+ let running = running.unwrap();
+ f.until(|| f.prompts().len() == 1).await;
+ let queued = f.message("queued message").await;
+ let queued = queued.unwrap();
+ f.hub.delete_bot("a").unwrap();
+ assert_eq!(f.hub.team.0.locked().messages, 2);
+ assert_eq!(f.hub.runtime("b").status, BotStatus::Working);
+ std::fs::write(f.dir.join("b/release"), "").unwrap();
+ f.until(|| f.hub.team.0.locked().messages == 0).await;
+ for receipt in [&running, &queued] {
+ assert!(f.notices(receipt).iter().all(|e| e.data["status"] == "completed"));
+ }
+ f.shutdown().await;
+
+ let f = Fixture::new();
+ let running = f.message("BLOCK active message").await;
+ let running = running.unwrap();
+ f.until(|| f.prompts().len() == 1).await;
+ let queued = f.message("queued message").await;
+ let queued = queued.unwrap();
+ f.hub.delete_bot("b").unwrap();
+ f.until(|| f.hub.team.0.locked().messages == 0).await;
+ for receipt in [&running, &queued] {
+ assert!(f.notices(receipt).iter().all(|e| e.data["status"] == "cancelled"));
+ }
+ assert_eq!(f.prompts().len(), 1);
+ f.shutdown().await;
+}
+
+#[tokio::test]
+async fn message_turns_have_no_resume_marker_and_restart_expires_both_notices() {
+ let f = Fixture::new();
+ let running = f.message("BLOCK active message").await;
+ let running = running.unwrap();
+ f.until(|| f.prompts().len() == 1).await;
+ let queued = f.message("queued message").await;
+ let queued = queued.unwrap();
+ assert!(f.hub.store.kv_get("turn.inflight.b").is_none_or(|v| v.is_empty()));
+ // A new store connection applies the same startup cleanup to the
+ // persisted queued and running notices, without replaying a prompt.
+ let store = Store::open(&f.dir.join("test.db")).unwrap();
+ assert_eq!(store.expire_pending().unwrap(), 4);
+ for receipt in [&running, &queued] {
+ assert!(f.notices(receipt).iter().all(|e| e.data["status"] == "failed"
+ && e.data["text"].as_str().unwrap().contains("Interrupted by host restart")));
+ }
+ assert_eq!(f.prompts().len(), 1);
+ drop(store);
+ f.shutdown().await;
+}
+
+#[test]
+fn restart_marks_requests_interrupted_without_replaying_them() {
+ let store = Store::open(std::path::Path::new(":memory:")).unwrap();
+ let pending = store
+ .insert_entry(
+ &crate::store::Lane::main("b"),
+ EntryKind::Notice,
+ 1,
+ &json!({
+ "delegationId": "d", "status": "sent", "heading": "Request from a",
+ }),
+ )
+ .unwrap();
+ let complete = store
+ .insert_entry(
+ &crate::store::Lane::main("a"),
+ EntryKind::Notice,
+ 1,
+ &json!({
+ "delegationId": "done", "status": "completed",
+ }),
+ )
+ .unwrap();
+ store.expire_pending().unwrap();
+ let interrupted = store.entry(&pending.id).unwrap();
+ assert_eq!(interrupted.data["status"], "failed");
+ assert!(interrupted.data["text"].as_str().unwrap().contains("Interrupted by host restart"));
+ assert_eq!(store.entry(&complete.id).unwrap().data["status"], "completed");
+ assert!(interrupted.rev > pending.rev);
+}
diff --git a/host/tests/fixtures/team_agent.py b/host/tests/fixtures/team_agent.py
index f0ca5cf2..c56957ac 100644
--- a/host/tests/fixtures/team_agent.py
+++ b/host/tests/fixtures/team_agent.py
@@ -23,35 +23,57 @@ def update(value):
send({"method": "session/update", "params": {"sessionId": "session", "update": value}})
+def team_call(target, tool, message):
+ server = next(s for s in servers if s["name"] == "team")
+ with subprocess.Popen([server["command"], *server["args"]], stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE, text=True) as mcp:
+ def rpc(identifier, method, params):
+ mcp.stdin.write(json.dumps({"jsonrpc": "2.0", "id": identifier, "method": method, "params": params}) + "\n")
+ mcp.stdin.flush()
+ return json.loads(mcp.stdout.readline())
+
+ initialized = rpc(1, "initialize", {"protocolVersion": "2025-06-18"})
+ assert initialized["result"]["serverInfo"]["name"] == "codync-team"
+ tools = rpc(2, "tools/list", {})
+ assert {t["name"] for t in tools["result"]["tools"]} == {"list_bots", "ask_bot", "message_bot"}
+ roster = rpc(3, "tools/call", {"name": "list_bots", "arguments": {}})
+ assert any(b["id"] == target for b in json.loads(roster["result"]["content"][0]["text"])["bots"])
+ response = rpc(4, "tools/call", {"name": tool, "arguments": {
+ "botId": target, "message": message,
+ }})
+ mcp.stdin.close()
+ return response["result"]
+
+
def prompt(request):
text = request["params"]["prompt"][0]["text"]
with open("prompts.jsonl", "a") as log:
log.write(json.dumps(text) + "\n")
- if text.startswith("DELEGATE "):
+ if text.startswith(("DELEGATE ", "MESSAGE ")):
+ independent = text.startswith("MESSAGE ")
target = text.split()[1]
- server = next(s for s in servers if s["name"] == "team")
update({"sessionUpdate": "tool_call", "toolCallId": "delegate", "title": "Ask reviewer", "status": "in_progress"})
- with subprocess.Popen([server["command"], *server["args"]], stdin=subprocess.PIPE,
- stdout=subprocess.PIPE, text=True) as mcp:
- def rpc(identifier, method, params):
- mcp.stdin.write(json.dumps({"jsonrpc": "2.0", "id": identifier, "method": method, "params": params}) + "\n")
- mcp.stdin.flush()
- return json.loads(mcp.stdout.readline())
-
- initialized = rpc(1, "initialize", {"protocolVersion": "2025-06-18"})
- assert initialized["result"]["serverInfo"]["name"] == "codync-team"
- tools = rpc(2, "tools/list", {})
- assert {t["name"] for t in tools["result"]["tools"]} == {"list_bots", "ask_bot"}
- roster = rpc(3, "tools/call", {"name": "list_bots", "arguments": {}})
- assert any(b["id"] == target for b in json.loads(roster["result"]["content"][0]["text"])["bots"])
- response = rpc(4, "tools/call", {"name": "ask_bot", "arguments": {
- "botId": target, "message": "PERMISSION review the changes",
- }})
- assert not response["result"].get("isError"), response
- text = json.loads(response["result"]["content"][0]["text"])["reply"]
- mcp.stdin.close()
+ response = team_call(target, "message_bot" if independent else "ask_bot", "PERMISSION review the changes")
+ assert not response.get("isError"), response
+ result = json.loads(response["content"][0]["text"])
+ if independent:
+ assert result["status"] == "queued" and "reply" not in result
+ text = "Message queued"
+ else:
+ text = "Team reply: " + result["reply"]
update({"sessionUpdate": "tool_call_update", "toolCallId": "delegate", "status": "completed"})
- update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "Team reply: " + text}})
+ update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": text}})
+ send({"id": request["id"], "result": {"stopReason": "end_turn"}})
+ return
+ if text.split("\n\n")[-1] == "CHAIN":
+ route = json.loads(pathlib.Path("handoff.json").read_text())
+ response = team_call(route["target"], route["tool"], "CHAIN")
+ if response.get("isError"):
+ reply = "Chain stopped: " + response["content"][0]["text"]
+ else:
+ result = json.loads(response["content"][0]["text"])
+ reply = result.get("reply", "Chain forwarded")
+ update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": reply}})
send({"id": request["id"], "result": {"stopReason": "end_turn"}})
return
if "PERMISSION" in text:
@@ -83,6 +105,8 @@ def prompt(request):
send({"id": request["id"], "result": {"stopReason": "cancelled"}})
elif "FAIL" in text:
send({"id": request["id"], "error": {"code": -32000, "message": "fixture failure"}})
+ elif "REFUSE" in text:
+ send({"id": request["id"], "result": {"stopReason": "refusal"}})
else:
if "EMPTY" not in text:
update({"sessionUpdate": "agent_message_chunk", "content": {
diff --git a/host/tests/team_e2e.rs b/host/tests/team_e2e.rs
index b905d0b2..d8b4cb44 100644
--- a/host/tests/team_e2e.rs
+++ b/host/tests/team_e2e.rs
@@ -68,17 +68,16 @@ impl Host {
let cwd = self.home.join(name);
std::fs::create_dir_all(&cwd).unwrap();
let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");
- self.call(
- "createBot",
- json!({
- "name": name, "backend": "custom", "cwd": cwd, "permission": "ask", "notify": false,
- "command": common::python_agent(&agent),
- }),
- )
- .await["bot"]["id"]
- .as_str()
- .unwrap()
- .to_owned()
+ let result = self
+ .call(
+ "createBot",
+ json!({
+ "name": name, "backend": "custom", "cwd": cwd, "permission": "ask", "notify": false,
+ "command": common::python_agent(&agent),
+ }),
+ )
+ .await;
+ result["bot"]["id"].as_str().unwrap().to_owned()
}
async fn wait_for(&self, bot: &str, predicate: impl Fn(&Value) -> bool) -> Value {
@@ -116,3 +115,92 @@ async fn agent_uses_team_mcp_and_returns_the_reviewers_answer() {
assert_eq!(requests[0]["data"]["delegationId"], requests[1]["data"]["delegationId"]);
assert!(sync["bots"].as_array().unwrap().iter().all(|b| b["status"] == "idle"));
}
+
+#[tokio::test]
+async fn agent_messages_another_bot_then_finishes_before_recipient_approval() {
+ let host = Host::start().await;
+ let lead = host.bot("lead").await;
+ let reviewer = host.bot("reviewer").await;
+ host.call("send", json!({"botId": lead, "text": format!("MESSAGE {reviewer}")})).await;
+ let permission = host.wait_for(&reviewer, |e| e["kind"] == "permission" && e["data"]["status"] == "pending").await;
+ let final_reply = host.wait_for(&lead, |e| e["kind"] == "agent" && e["data"]["final"] == true).await;
+ assert_eq!(final_reply["data"]["text"], "Message queued");
+ let history = host.call("history", json!({"botId": reviewer})).await;
+ assert!(!history["entries"].as_array().unwrap().iter().any(|e| e["data"]["final"] == true));
+ assert!(history["entries"].as_array().unwrap().iter().all(|e| e["kind"] != "user"));
+ // The sender's turn and MCP subprocess have finished; Stop must still leave
+ // the recipient's approval and admitted message intact.
+ host.call("stop", json!({"botId": lead})).await;
+ host.call("respondPermission", json!({"entryId": permission["id"], "optionId": "allow"})).await;
+ let report = host.wait_for(&reviewer, |e| e["kind"] == "agent" && e["data"]["final"] == true).await;
+ assert_eq!(report["data"]["text"], "reply: PERMISSION review the changes");
+ host.wait_for(&reviewer, |e| e["kind"] == "notice" && e["data"]["status"] == "completed").await;
+ let sync = host.call("sync", json!({"since": 0})).await;
+ let notices: Vec<_> =
+ sync["entries"].as_array().unwrap().iter().filter(|e| e["data"]["delegationId"].is_string()).collect();
+ assert_eq!(notices.len(), 2);
+ for entry in &notices {
+ assert_eq!(entry["kind"], "notice");
+ assert_eq!(entry["data"]["sourceBotId"], lead);
+ assert_eq!(entry["data"]["targetBotId"], reviewer);
+ assert_eq!(entry["data"]["status"], "completed");
+ assert!(!entry["data"]["text"].as_str().unwrap().contains("reply: PERMISSION"));
+ }
+ assert_eq!(notices[0]["data"]["delegationId"], notices[1]["data"]["delegationId"]);
+ let history = host.call("history", json!({"botId": lead})).await;
+ assert_eq!(history["entries"].as_array().unwrap().iter().filter(|e| e["data"]["final"] == true).count(), 1);
+}
+
+async fn exercise_bounded_chain(second_tool: &str) {
+ let host = Host::start().await;
+ let first = host.bot("first").await;
+ let second = host.bot("second").await;
+ for (name, target, tool) in [("first", &second, "message_bot"), ("second", &first, second_tool)] {
+ std::fs::write(host.home.join(name).join("handoff.json"), json!({"target": target, "tool": tool}).to_string())
+ .unwrap();
+ }
+ let mut previous_rev = 0;
+ // The second user turn must start a fresh budget after the first chain ends.
+ for chain in 1..=2 {
+ host.call("send", json!({"botId": first, "text": "CHAIN"})).await;
+ let stopped = host
+ .wait_for(&first, |e| {
+ e["rev"].as_i64().unwrap_or(0) > previous_rev
+ && e["data"]["final"] == true
+ && e["data"]["text"].as_str().is_some_and(|s| s.contains("hop limit (8)"))
+ })
+ .await;
+ assert!(stopped["data"]["text"].as_str().unwrap().contains("Chain stopped"));
+ let sync = tokio::time::timeout(Duration::from_secs(10), async {
+ loop {
+ let sync = host.call("sync", json!({"since": 0})).await;
+ let notices: Vec<_> = sync["entries"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter(|e| e["data"]["delegationId"].is_string())
+ .collect();
+ if sync["bots"].as_array().unwrap().iter().all(|b| b["status"] == "idle")
+ && notices.iter().all(|e| e["data"]["status"] == "completed")
+ {
+ assert_eq!(notices.len(), chain * 8 * 2, "the ninth handoff must never be queued");
+ return sync;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ })
+ .await
+ .expect("bounded chain did not release its turns and notices");
+ previous_rev = sync["rev"].as_i64().unwrap();
+ }
+}
+
+#[tokio::test]
+async fn independent_message_ping_pong_stops_and_a_new_user_turn_can_delegate() {
+ exercise_bounded_chain("message_bot").await;
+}
+
+#[tokio::test]
+async fn asking_between_independent_handoffs_cannot_reset_the_hop_limit() {
+ exercise_bounded_chain("ask_bot").await;
+}