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.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
fix(host): answer background work after a bot's turn
leepokai84f92069d12f
diff --git a/docs/architecture/conversation-runtime.md b/docs/architecture/conversation-runtime.mdindex 4c857c20..7f579a66 100644--- a/docs/architecture/conversation-runtime.md+++ b/docs/architecture/conversation-runtime.md@@ -8,4 +8,4 @@- **Lead bot**: the host makes the first one per computer (`chat/lead.rs`), and the user may pick another (`setLead`) or delete it; on top of every roster, never hidden; its instructions ask for initiative, the *Check in* routine made with the first runs twice a day, and it opens a call with a turn of its own (`Cmd::Prompt`, no user message): [docs/features/lead-bot.md](../features/lead-bot.md).- Bot collaboration: built-in `team` MCP (`chat/team.rs`) lists visible bots and sends one a request through its actor queue (`message_bot`); nothing waits, and the reply comes back to the sender as a turn of its own in its main chat. Requests and replies are separate turns, bounded by the chain's hop count; native subagents stay with the harness. See [docs/features/bot-collaboration.md](../features/bot-collaboration.md).- **Context & memory**: frozen instruction snapshot per session + compaction epoch (Claude gets it as a system prompt), profile edits as update blocks, memory in the host (a layer shared by all bots and one per bot, written by the user, the bots' tools and dreaming), busy-time messages folded into one turn, interrupted turns resumed: [docs/features/context-and-memory.md](../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, unless it reacted to the user's message instead or passed), permission cards, notices. Nothing streams into a bubble; narration, thoughts, tool calls, plans are trace entries (Full conversation sheet; with [Show thinking details](../features/chat-messages.md#while-it-works) on (Settings › Chat), the live activity also unfolds the running turn's steps, without the bot's `bookkeeping` tool calls): [docs/features/chat-messages.md](../features/chat-messages.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, also between turns from work the agent goes on with in the background, into the bot's own chat with a *done* alert, unless the user stopped the bot since; a turn that sent none falls back to its last text, unless it reacted to the user's message instead or passed), permission cards, notices. Nothing streams into a bubble; narration, thoughts, tool calls, plans are trace entries (Full conversation sheet; with [Show thinking details](../features/chat-messages.md#while-it-works) on (Settings › Chat), the live activity also unfolds the running turn's steps, without the bot's `bookkeeping` tool calls): [docs/features/chat-messages.md](../features/chat-messages.md).diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rsindex 0152dfe1..17807b70 100644--- a/host/src/agent/bot/mod.rs+++ b/host/src/agent/bot/mod.rs@@ -352,7 +352,11 @@ impl Actor {Some(done) = done_rx.recv() => {// Updates sent before the prompt response are already queued; apply them first.while let Some(inc) = self.conn.as_mut().and_then(|c| c.rx.try_recv().ok()) {- self.on_incoming(Some(inc)).await;+ match inc {+ // No agent ends a turn it waits on: a request queued here is for work after it.+ Incoming::Request { id, method, params } => self.answer_outside_turn(id, &method, ¶ms).await,+ inc => self.on_incoming(Some(inc)).await,+ }}if let Err(error) = &done && self.fall_back(error, &done_tx).await {continue;diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rsindex 842585c4..6208d8a3 100644--- a/host/src/agent/bot/turn.rs+++ b/host/src/agent/bot/turn.rs@@ -206,13 +206,18 @@ impl Actor {if self.session_fresh {tokio::time::sleep(Duration::from_millis(400)).await;}+ let mut waiting = vec![];if let Some(conn) = self.conn.as_mut() {while let Ok(inc) = conn.rx.try_recv() {- if let Incoming::Request { id, .. } = inc {- let _ = conn.acp.respond_error(id, -32601, "not supported").await;+ if let Incoming::Request { id, method, params } = inc {+ waiting.push((id, method, params));}}}+ // Requests that came in before this turn: a permission gets the answer it would have had a moment ago.+ for (id, method, params) in waiting {+ self.answer_outside_turn(id, &method, ¶ms).await;+ }let sid = self.turn_session.clone().ok_or_else(|| anyhow!("no session"))?;let prompt =if std::mem::take(&mut self.raw_prompt) { text.to_owned() } else { self.compose(&sid, text).await? };@@ -414,12 +419,16 @@ impl Actor {self.files.cancel();self.flush(true);self.seg = Seg::None;- let ids: Vec<String> = self.perms.drain().map(|(k, _)| k).collect();- for id in ids {+ let acp = self.conn.as_ref().map(|c| c.acp.clone());+ for (id, answer) in self.perms.drain() {if let Some(mut e) = self.hub.store.entry(&id) {e.data["status"] = "expired".into();self.hub.set_entry(&id, &e.data);}+ // The agent would wait on a card no one can answer any more.+ if let (super::updates::Answer::Agent(rpc_id), Some(acp)) = (answer, acp.clone()) {+ tokio::spawn(async move { acp.respond(rpc_id, json!({"outcome": {"outcome": "cancelled"}})).await });+ }}for entry_id in self.tools.values() {if let Some(mut e) = self.hub.store.entry(entry_id)diff --git a/host/src/agent/bot/updates.rs b/host/src/agent/bot/updates.rsindex 425c6143..af64c58d 100644--- a/host/src/agent/bot/updates.rs+++ b/host/src/agent/bot/updates.rs@@ -6,7 +6,7 @@ use super::{Actor, Reacted, Seg, SegKind};use crate::agent::acp::{self, Incoming};use crate::hub::BotStatus;use crate::remote::push::{self, AlertKind};-use crate::store::{EntryKind, Permission};+use crate::store::{EntryKind, Lane, Permission};use serde_json::{Value, json};use std::time::{Duration, Instant};use tokio::sync::oneshot;@@ -51,17 +51,24 @@ impl Actor {}}Some(Incoming::Request { id, method, params }) => {- let Some(conn) = &self.conn else { return };- let acp = conn.acp.clone();if method == "session/request_permission" && self.turn.is_some() {self.on_permission(id, params).await;} else {- let _ = acp.respond_error(id, -32601, &format!("{method} is not supported by Codync")).await;+ self.answer_outside_turn(id, &method, ¶ms).await;}}}}+ /// A request no turn handles: a permission gets `answer_background`, anything else isn't supported.+ pub(super) async fn answer_outside_turn(&self, rpc_id: Value, method: &str, params: &Value) {+ if method == "session/request_permission" {+ self.answer_background(rpc_id, params).await;+ } else if let Some(conn) = &self.conn {+ let _ = conn.acp.respond_error(rpc_id, -32601, &format!("{method} is not supported by Codync")).await;+ }+ }+pub(super) fn on_update(&mut self, u: &Value) {let turn = self.turn.unwrap_or(0);match u["sessionUpdate"].as_str().unwrap_or_default() {@@ -159,18 +166,11 @@ impl Actor {pub(super) async fn on_permission(&mut self, rpc_id: Value, params: Value) {let options = params["options"].as_array().cloned().unwrap_or_default();let tool = ¶ms["toolCall"];- if self.cfg.permission == Permission::Auto {- let pick = ["allow_once", "allow_always"]- .iter()- .find_map(|k| options.iter().find(|o| o["kind"] == *k))- .or_else(|| options.first());- if let (Some(o), Some(conn)) = (pick, &self.conn) {- let _ = conn- .acp- .respond(rpc_id, json!({"outcome": {"outcome": "selected", "optionId": o["optionId"]}}))- .await;- return;- }+ if self.cfg.permission == Permission::Auto+ && let (Some(answer), Some(conn)) = (auto_answer(&options), &self.conn)+ {+ let _ = conn.acp.respond(rpc_id, answer).await;+ return;}let title = tool["title"].as_str()@@ -201,6 +201,20 @@ impl Actor {self.show_card(&title, data, Answer::Agent(rpc_id));}+ /// A permission request from work the agent goes on with after its turn ended (a background subagent): no turn+ /// shows a card for it, so it gets what a turn would answer without asking, under the bot's Approve automatically,+ /// for one of this bot's own sessions, unless the user stopped the bot since. Anything else is declined.+ pub(super) async fn answer_background(&self, rpc_id: Value, params: &Value) {+ let Some(conn) = &self.conn else { return };+ let own = params["sessionId"].as_str().is_some_and(|sid| conn.loaded.contains_key(sid));+ let options = params["options"].as_array().cloned().unwrap_or_default();+ let answer = (self.cfg.permission == Permission::Auto && own && !self.stop_requested)+ .then(|| auto_answer(&options))+ .flatten();+ tracing::info!(bot = %self.id(), approved = answer.is_some(), title = params["toolCall"]["title"].as_str(), "permission asked outside a turn");+ let _ = conn.acp.respond(rpc_id, answer.unwrap_or_else(|| json!({"outcome": {"outcome": "cancelled"}}))).await;+ }+/// `Cmd::Approve`: Allow or Deny on a card, with what the tool will do in its details.pub(super) fn ask_approval(&mut self, title: &str, detail: &str, reply: oneshot::Sender<bool>) {if self.turn.is_none() {@@ -287,7 +301,7 @@ impl Actor {/// A `send_message`: the user's next bubble, in the turn's lane, right away. Only in the/// bot's own chat; a room, a bot request 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") };+ let Some(turn) = self.turn else { return self.send_between_turns(&text) };if self.active_request.is_some() {anyhow::bail!("send_message isn't available in a bot request: your final reply goes to the requesting bot, so put your answer there"@@ -304,6 +318,20 @@ impl Actor {Ok(())}+ /// A `send_message` from work the agent goes on with after its turn ended (a background subagent's result): a+ /// message in the bot's own chat, with the alert a finished turn sends, unless the user stopped the bot since.+ fn send_between_turns(&self, text: &str) -> anyhow::Result<()> {+ anyhow::ensure!(self.conn.is_some(), "no turn is running");+ anyhow::ensure!(!self.stop_requested, "the user stopped you: send nothing until they write again");+ let data = json!({"text": text, "final": true, "author": self.cfg.id});+ let turn = self.hub.store.max_turn(&self.cfg.id);+ self.hub+ .add_entry(&Lane::main(&self.cfg.id), EntryKind::Agent, turn, &data)+ .ok_or_else(|| anyhow::anyhow!("couldn't save the message"))?;+ push::notify(&self.hub, &self.cfg, None, &self.cfg.name, text, AlertKind::Done);+ Ok(())+ }+/// `react`: the emoji goes on the user's message this turn answers, or in a room on a message the bot was shown.pub(super) fn react(&mut self, emoji: &str, to: Option<&str>) -> anyhow::Result<()> {if self.turn.is_none() {@@ -380,3 +408,12 @@ impl Actor {self.seg = Seg::None;}}++/// What Approve automatically answers a permission request: allow once, else allow always, else its first option.+fn auto_answer(options: &[Value]) -> Option<Value> {+ let pick = ["allow_once", "allow_always"]+ .iter()+ .find_map(|k| options.iter().find(|o| o["kind"] == *k))+ .or_else(|| options.first())?;+ Some(json!({"outcome": {"outcome": "selected", "optionId": pick["optionId"]}}))+}diff --git a/host/tests/background_work_e2e.rs b/host/tests/background_work_e2e.rsnew file mode 100644index 00000000..09c0bd7b--- /dev/null+++ b/host/tests/background_work_e2e.rs@@ -0,0 +1,44 @@+//! Work an agent goes on with after its turn ended (like Hermes' background subagents), through a real host and a+//! fixture agent: a permission request it makes then gets the answer the bot's permission setting gives without a+//! card, and only for the bot's own session.++#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]++mod common;++use common::host::Host;+use serde_json::{Value, json};+use std::time::{Duration, Instant};++/// The host's answer to the permission request the agent makes after answering `text`, the `nth` it got.+async fn answer_after(host: &Host, bot: &str, text: &str, nth: usize) -> Value {+ host.reply(bot, text).await;+ let file = host.home.join("bots").join(bot).join("workspace").join("responses.jsonl");+ let deadline = Instant::now() + Duration::from_secs(20);+ loop {+ if let Some(line) = std::fs::read_to_string(&file).ok().and_then(|log| log.lines().nth(nth).map(str::to_owned))+ {+ return serde_json::from_str(&line).unwrap();+ }+ assert!(Instant::now() < deadline, "the host never answered the permission request");+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+}++#[tokio::test]+async fn a_permission_asked_after_the_turn_gets_the_bots_automatic_answer() {+ let host = Host::start().await;+ let bot = host.fixture_bot("Hermes", "late_permission_agent.py", "").await;++ // A bot that asks first: no card waits for it, so it's declined (the way ACP says it), not refused as unsupported.+ let asked = answer_after(&host, &bot, "write the notes", 0).await;+ assert_eq!(asked["result"]["outcome"]["outcome"], "cancelled", "{asked}");++ host.call("updateBot", json!({"id": bot, "permission": "auto"})).await;+ let approved = answer_after(&host, &bot, "write the notes", 1).await;+ assert_eq!(approved["result"]["outcome"], json!({"outcome": "selected", "optionId": "yes"}), "{approved}");++ // Never for a session the host didn't open for this bot.+ let elsewhere = answer_after(&host, &bot, "write the notes elsewhere", 2).await;+ assert_eq!(elsewhere["result"]["outcome"]["outcome"], "cancelled", "{elsewhere}");+}diff --git a/host/tests/e2e.rs b/host/tests/e2e.rsindex 36ecd154..20617c06 100644--- a/host/tests/e2e.rs+++ b/host/tests/e2e.rs@@ -236,6 +236,12 @@ async fn sent_messages_are_the_reply() {.map(|e| e["data"]["text"].as_str().unwrap()).collect();assert_eq!(finals, ["Found it.", "Fixing the typo now."]);++ // Work the agent goes on with after its turn (a background subagent) still reaches the user.+ host.call("chatCall", send("The background check passed.")).await;+ let late =+ host.wait_for(&bot, |e| e["kind"] == "agent" && e["data"]["text"] == "The background check passed.").await;+ assert_eq!((&late["data"]["final"], &late["data"]["author"]), (&json!(true), &json!(bot)));}#[tokio::test]diff --git a/host/tests/fixtures/late_permission_agent.py b/host/tests/fixtures/late_permission_agent.pynew file mode 100644index 00000000..6f309ba8--- /dev/null+++ b/host/tests/fixtures/late_permission_agent.py@@ -0,0 +1,44 @@+"""ACP agent whose work goes on after its turn (like Hermes' background subagents): it answers each prompt, ends the+turn, then asks permission to edit a file, for its own session `s1`, or for a session the host never opened when the+prompt says "elsewhere". It logs each answer the host gives to responses.jsonl in its folder."""++import json+import sys+import time++asked = 900+++def send(value):+ print(json.dumps({"jsonrpc": "2.0", **value}), flush=True)+++for line in sys.stdin:+ message = json.loads(line)+ method, rid = message.get("method"), message.get("id")+ if method is None and rid is not None:+ with open("responses.jsonl", "a", encoding="utf-8") as f:+ f.write(json.dumps(message) + "\n")+ continue+ if method is None or rid is None:+ continue+ params = message.get("params", {})+ if method == "initialize":+ send({"id": rid, "result": {"protocolVersion": 1, "agentCapabilities": {"loadSession": True}}})+ elif method in ("session/new", "session/load"):+ send({"id": rid, "result": {"sessionId": "s1"}})+ elif method == "session/prompt":+ text = " ".join(b.get("text", "") for b in params.get("prompt", []))+ update = {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": "Started it in the background."}}+ send({"method": "session/update", "params": {"sessionId": "s1", "update": update}})+ send({"id": rid, "result": {"stopReason": "end_turn"}})+ time.sleep(0.5) # the background work takes a while+ asked += 1+ session = "s9" if "elsewhere" in text else "s1"+ options = [{"optionId": "yes", "name": "Allow", "kind": "allow_once"},+ {"optionId": "no", "name": "Reject", "kind": "reject_once"}]+ tool = {"toolCallId": f"t{asked}", "title": "Write notes.md", "kind": "edit"}+ send({"id": asked, "method": "session/request_permission",+ "params": {"sessionId": session, "toolCall": tool, "options": options}})+ else:+ send({"id": rid, "result": {}})diff --git a/web/content/docs/conversations.mdx b/web/content/docs/conversations.mdxindex 3bc132de..75c7fa2e 100644--- a/web/content/docs/conversations.mdx+++ b/web/content/docs/conversations.mdx@@ -75,6 +75,8 @@ The agent waits for your answer. If the turn ends before you answer, for exampleWith **Approve automatically**, no cards appear: Codync allows each request for you. Your agent's own permission rules still apply under any setting. To change the setting, see [Bots](/docs/bots#permissions).+Some agents keep working after their reply, for example a background helper that finishes a long job. With **Approve automatically**, what that work asks is allowed too, until you stop the bot; under any other setting it's declined, since no card can wait for you. When that work is done, the bot can still send you its result as a message in its chat.+## Stopping a turn- **Desktop and iPhone:** while the bot works and the box is empty, the send button turns into **Stop**.