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.

fix(host): say when a mentioned group member is busy elsewhere

leepokaib9549ead1983
diff --git a/docs/features/groups-and-replies.md b/docs/features/groups-and-replies.md
index f6cd69f8..e5b13633 100644
--- a/docs/features/groups-and-replies.md
+++ b/docs/features/groups-and-replies.md
@@ -57,10 +57,17 @@ quotes itself.
react to someone's message (`react(emoji, to?)`), so it can agree with a reaction and pass.
Room lines carry their reactions: `Ann: Shipped. (reactions: User 👍, Ben 🎉)`, and a reply
its quote: `User: [Codync: this replies to Ann's message: "…"] text`.
-- A new message in the group, or Stop, ends a running room turn before its next speaker;
- a member still busy elsewhere skips the old room turn's queued request.
+- A member busy with a turn outside the room isn't waited for: the room shows "<name> is busy
+ in another chat and will answer here when it's done.", moves on, and the member answers in
+ the room once its other turn ends (with its own "done" push), on a prompt built then, so it
+ sees what the room said meanwhile. It isn't asked again in later rounds of that room turn.
+ Newer messages in the group, and Stop in the member's own chat, don't drop that late answer;
+ the group's Stop or removing the member from the group does, and a newer room turn that asks
+ the member again replaces it.
+- A new message in the group, or Stop, ends a running room turn before its next speaker.
- Tool calls, thoughts and permission cards of a member's group turn are written to the
- group (with `author`), not to the member's own chat. One "done" push per room turn.
+ group (with `author`), not to the member's own chat. One "done" push per room turn, plus
+ one per late answer from a busy member.
- Files sent to a group are kept in the group's data folder (`~/.codync/bots/<group>/uploads`);
each member's prompt lists their paths under the user's line.
- Voice calls work in a group: each final reply is read with its speaker's name, a member's
diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rs
index ce98583d..dab3b100 100644
--- a/host/src/agent/bot/queue.rs
+++ b/host/src/agent/bot/queue.rs
@@ -30,6 +30,8 @@ impl Actor {
}
}
Cmd::Group(turn) => {
+ // The room asks again: this turn answers for any still waiting there.
+ self.queue.retain(|q| !matches!(q, Queued::Group(g) if g.lane == turn.lane));
self.queue.push_back(Queued::Group(turn));
if self.turn.is_none() {
self.next_in_queue(done_tx).await;
@@ -137,12 +139,18 @@ impl Actor {
if self.active_routine.is_none() {
self.hub.routines.release(&self.cfg.id);
}
- // Queued messages are dropped too: Stop means "stop everything".
- for queued in self.queue.drain(..) {
- let Queued::User { entry_id, .. } = queued else { continue };
- if let Some(mut e) = self.hub.store.entry(&entry_id) {
- e.data["status"] = "cancelled".into();
- self.hub.set_entry(&entry_id, &e.data);
+ // Queued messages are dropped too: Stop means "stop everything". A room's late turn stays: the room was
+ // told this member answers there once free, and only the group's Stop drops it.
+ for queued in std::mem::take(&mut self.queue) {
+ match queued {
+ Queued::Group(turn) if turn.late => self.queue.push_back(Queued::Group(turn)),
+ Queued::User { entry_id, .. } => {
+ if let Some(mut e) = self.hub.store.entry(&entry_id) {
+ e.data["status"] = "cancelled".into();
+ self.hub.set_entry(&entry_id, &e.data);
+ }
+ }
+ _ => {}
}
}
self.cancel_turn().await;
@@ -228,11 +236,18 @@ impl Actor {
continue;
}
Some(Queued::Group(_)) => {
- let Some(Queued::Group(turn)) = self.queue.pop_front() else {
+ let Some(Queued::Group(mut turn)) = self.queue.pop_front() else {
unreachable!("front is a group turn")
};
- // A newer message in the room (or Stop) ended the room turn that queued this.
- if turn.reply.is_closed() || !self.hub.groups.current(&turn.lane, turn.epoch) {
+ // A newer message in the room (or Stop) ended the room turn that queued this; a late turn
+ // answers anyway (see `GroupTurn::late`).
+ if turn.reply.is_closed() || !(turn.late || self.hub.groups.current(&turn.lane, turn.epoch)) {
+ continue;
+ }
+ if turn.late
+ && let Err(error) = crate::chat::group::refresh(&self.hub, &mut turn, &self.cfg)
+ {
+ tracing::warn!(bot = self.cfg.id, error = format!("{error:#}"), "late room turn dropped");
continue;
}
let (lane, prompt) = (turn.lane.clone(), turn.prompt.clone());
diff --git a/host/src/chat/group.rs b/host/src/chat/group.rs
index 0fc98821..ee809c54 100644
--- a/host/src/chat/group.rs
+++ b/host/src/chat/group.rs
@@ -10,8 +10,8 @@
//! moves the lane's epoch, which ends a running room turn before its next speaker.
use crate::LockExt;
-use crate::agent::bot::Cmd;
-use crate::hub::Hub;
+use crate::agent::bot::{Cmd, NoticeStyle};
+use crate::hub::{BotStatus, Hub};
use crate::remote::push::{self, AlertKind};
use crate::store::{BotConfig, BotKind, Entry, EntryKind, Lane, Store};
use anyhow::{Result, anyhow, bail};
@@ -34,8 +34,12 @@ pub struct GroupTurn {
pub prompt: String,
/// The newest message `prompt` shows (its `seq`): a reaction goes on what the member saw.
pub shown: i64,
- /// The room turn that asked; a member skips it once a newer one started (see [`Rooms::current`]).
+ /// The room turn that asked; a member skips it once a newer one started (see [`Rooms::current`]), unless `late`.
pub epoch: u64,
+ /// Queued while the member was busy elsewhere: it answers once free whatever the room did since, on a
+ /// prompt built when it starts ([`refresh`]). Only the group's Stop, the room asking the member again, or the
+ /// member leaving the group drops it (Stop in the member's own chat doesn't).
+ pub late: bool,
/// The reply the room sees, or `None` for a pass.
pub reply: oneshot::Sender<Result<Option<String>>>,
}
@@ -113,8 +117,10 @@ pub fn start(hub: &Arc<Hub>, group: &BotConfig, lane: Lane) {
async fn run(hub: &Arc<Hub>, group_id: &str, lane: &Lane, epoch: u64) -> Result<()> {
let mut replies = 0;
let mut last_reply: Option<(String, String, String)> = None;
+ // Members busy elsewhere: their turn waits in their queue, and they answer on their own once free.
+ let mut later: Vec<String> = vec![];
'rounds: for round in 0..MAX_ROUNDS {
- let group = hub.store.bot(group_id)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("group deleted"))?.config;
+ let group = group(hub, group_id)?;
let members = members(hub, &group);
let since_user = since_last_user_message(hub, lane)?;
let mut speakers = responders(&members, &since_user);
@@ -132,13 +138,26 @@ async fn run(hub: &Arc<Hub>, group_id: &str, lane: &Lane, epoch: u64) -> Result<
if replies >= MAX_REPLIES {
break 'rounds;
}
- let shown = hub.store.messages_after(lane, 0, 1)?.last().map_or(0, |e| e.seq);
- let prompt = member_prompt(hub, &group, &members, member, lane)?;
+ if later.contains(&member.id) {
+ continue;
+ }
+ let (prompt, shown) = ask(hub, &group, &members, member, lane)?;
let (reply, answer) = oneshot::channel();
- let turn = GroupTurn { lane: lane.clone(), prompt, shown, epoch, reply };
+ let busy = busy_elsewhere(hub, &member.id, lane);
+ let turn = GroupTurn { lane: lane.clone(), prompt, shown, epoch, late: busy, reply };
if hub.send_cmd(&member.id, Cmd::Group(turn)).is_err() {
continue;
}
+ // The room doesn't wait on a turn elsewhere (it can run for hours): it says so, and the member
+ // answers here when it's done.
+ if busy {
+ let text = format!("{} is busy in another chat and will answer here when it's done.", member.name);
+ let data = serde_json::json!({"text": text, "style": NoticeStyle::Info});
+ hub.add_entry(lane, EntryKind::Notice, hub.store.max_turn(group_id), &data);
+ later.push(member.id.clone());
+ tokio::spawn(answer_later(hub.clone(), group_id.to_owned(), (*member).clone(), answer));
+ continue;
+ }
// A failed, cancelled or overdue member turn counts as a pass; its error shows in the room.
if let Ok(Ok(Ok(Some(text)))) = tokio::time::timeout(crate::chat::team::ASK_TIMEOUT, answer).await {
spoke += 1;
@@ -150,14 +169,61 @@ async fn run(hub: &Arc<Hub>, group_id: &str, lane: &Lane, epoch: u64) -> Result<
break;
}
}
- if let Some((from, name, text)) = last_reply
- && let Some(group) = hub.store.bot(group_id)?.map(|r| r.config)
+ if let Some((from, name, text)) = last_reply {
+ alert(hub, group_id, &from, &name, &text)?;
+ }
+ Ok(())
+}
+
+/// A busy member's reply, after the room turn moved on: it alerts like the room's last reply. Dropping the member's
+/// queued turn (see [`GroupTurn::late`]) ends this wait.
+async fn answer_later(
+ hub: Arc<Hub>,
+ group_id: String,
+ member: BotConfig,
+ answer: oneshot::Receiver<Result<Option<String>>>,
+) {
+ if let Ok(Ok(Some(text))) = answer.await
+ && let Err(error) = alert(&hub, &group_id, &member.id, &member.name, &text)
{
- push::notify(hub, &group, Some(&from), &format!("{name} in {}", group.name), &text, AlertKind::Done);
+ tracing::warn!(group = group_id, error = format!("{error:#}"), "late room reply not pushed");
+ }
+}
+
+/// The "done" push for `name`'s reply in the group.
+fn alert(hub: &Hub, group_id: &str, from: &str, name: &str, text: &str) -> Result<()> {
+ if let Some(group) = hub.store.bot(group_id)?.map(|r| r.config) {
+ push::notify(hub, &group, Some(from), &format!("{name} in {}", group.name), text, AlertKind::Done);
}
Ok(())
}
+/// `member` runs a turn outside this room, so a room turn would queue behind it.
+fn busy_elsewhere(hub: &Hub, member: &str, lane: &Lane) -> bool {
+ let r = hub.runtime(member);
+ matches!(r.status, BotStatus::Working | BotStatus::NeedsInput) && r.lane.as_ref() != Some(lane)
+}
+
+/// A late turn starts: it shows the room as it is now, not as it was when the turn was queued.
+pub fn refresh(hub: &Hub, turn: &mut GroupTurn, me: &BotConfig) -> Result<()> {
+ let group = group(hub, &turn.lane.chat)?;
+ if !group.members.contains(&me.id) {
+ bail!("no longer in the group");
+ }
+ (turn.prompt, turn.shown) = ask(hub, &group, &members(hub, &group), me, &turn.lane)?;
+ Ok(())
+}
+
+fn group(hub: &Hub, id: &str) -> Result<BotConfig> {
+ Ok(hub.store.bot(id)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("group deleted"))?.config)
+}
+
+/// `me`'s prompt for a turn in the room, and the newest message it shows (its `seq`).
+fn ask(hub: &Hub, group: &BotConfig, members: &[BotConfig], me: &BotConfig, lane: &Lane) -> Result<(String, i64)> {
+ let shown = hub.store.messages_after(lane, 0, 1)?.last().map_or(0, |e| e.seq);
+ Ok((member_prompt(hub, group, members, me, lane)?, shown))
+}
+
fn members(hub: &Hub, group: &BotConfig) -> Vec<BotConfig> {
group
.members
diff --git a/host/src/chat/group/tests.rs b/host/src/chat/group/tests.rs
index 7459afe7..80808edb 100644
--- a/host/src/chat/group/tests.rs
+++ b/host/src/chat/group/tests.rs
@@ -259,6 +259,91 @@ async fn stop_ends_the_room_turn_before_the_next_speaker() {
room.shutdown().await;
}
+/// `a` runs a turn in its own chat, and the room asks it: returns the room's notice.
+async fn ask_busy_a(room: &Room) -> Entry {
+ crate::api::dispatch(&room.hub, &Caller::Local, "send", json!({"botId": "a", "text": "BLOCK long work"}))
+ .await
+ .unwrap();
+ let hub = room.hub.clone();
+ tokio::time::timeout(Duration::from_secs(10), async {
+ while hub.runtime("a").status != BotStatus::Working {
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ })
+ .await
+ .expect("a starts its own turn");
+
+ room.send("@a are you there", None).await;
+ tokio::time::timeout(Duration::from_secs(5), async {
+ loop {
+ let entries = hub.store.history(&room.group, i64::MAX, 100).unwrap();
+ if let Some(e) = entries.into_iter().find(|e| e.kind == "notice") {
+ break e;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ })
+ .await
+ .expect("a busy notice in the room")
+}
+
+#[tokio::test]
+async fn a_member_busy_in_its_own_chat_is_announced_and_answers_once_free() {
+ let room = Room::new();
+ let main = Lane::main(&room.group);
+ // The room says why `a` is quiet right away instead of waiting out the ask timeout in silence.
+ let notice = ask_busy_a(&room).await;
+ assert_eq!(notice.data["text"], "a is busy in another chat and will answer here when it's done.");
+ assert_eq!(room.replies(&main), [] as [(String, String); 0]);
+
+ // Its own turn ends, then it answers the room.
+ std::fs::write(room.dir.join("a/release"), "").unwrap();
+ room.settle().await;
+ assert_eq!(room.replies(&main), [("a".to_owned(), "reply: group".to_owned())]);
+ room.shutdown().await;
+}
+
+#[tokio::test]
+async fn stopping_a_busy_member_in_its_own_chat_keeps_its_room_answer() {
+ let room = Room::new();
+ let main = Lane::main(&room.group);
+ ask_busy_a(&room).await;
+ // The user frees `a` from its own chat: the answer the room was promised still comes.
+ crate::api::dispatch(&room.hub, &Caller::Local, "stop", json!({"botId": "a"})).await.unwrap();
+ tokio::time::timeout(Duration::from_secs(10), async {
+ while room.replies(&main).is_empty() {
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ })
+ .await
+ .expect("a answers the room after its own Stop");
+ assert_eq!(room.replies(&main), [("a".to_owned(), "reply: group".to_owned())]);
+ room.shutdown().await;
+}
+
+#[tokio::test]
+async fn a_late_answer_survives_newer_messages_and_sees_them() {
+ let room = Room::new();
+ let main = Lane::main(&room.group);
+ ask_busy_a(&room).await;
+ room.send("@b meanwhile check CI", None).await;
+ tokio::time::timeout(Duration::from_secs(10), async {
+ while room.replies(&main).is_empty() {
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ })
+ .await
+ .expect("b answers while a is busy");
+
+ std::fs::write(room.dir.join("a/release"), "").unwrap();
+ room.settle().await;
+ // `a` still takes its room turn, on a prompt built when it starts: it sees b's reply.
+ let prompts = std::fs::read_to_string(room.dir.join("a/prompts.jsonl")).unwrap();
+ let late = prompts.lines().last().unwrap();
+ assert!(late.contains("User: @b meanwhile check CI") && late.contains("b: reply: group"), "{prompts}");
+ room.shutdown().await;
+}
+
#[test]
fn pass_is_recognized_loosely() {
for t in ["(pass)", " (pass) ", "\"(pass)\"", "pass.", ""] {