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
feat(host): let bots message the user with send_message
leepokaidb97ef9a9d4c
diff --git a/CLAUDE.md b/CLAUDE.mdindex dee8e43a..d0551c13 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -24,7 +24,7 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess- **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).- **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 *final* agent message of each turn (`data.final`), permission cards, notices. Narration, thoughts, tool calls, plans are trace entries (Full conversation sheet).+- **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).- API: `POST /api/<method>` + SSE with the bearer token (`~/.codync/token`) is **loopback only** (desktop app, SSH tunnel, local helpers). Phones and other remote clients use the E2E channel (`/channel` direct, or the Cloudflare relay). Default port **19222**.- Remote access (Cloudflare relay primary, direct LAN/Tailscale alternative, accounts, SSH, public routine webhooks queued in the relay §7.8): [docs/reference/remote-relay.md](docs/reference/remote-relay.md).diff --git a/docs/features/chat-messages.md b/docs/features/chat-messages.mdnew file mode 100644index 00000000..f39f445a--- /dev/null+++ b/docs/features/chat-messages.md@@ -0,0 +1,34 @@+# Chat messages++How a bot's work turns into what the user reads, copied from Grok Bot.++## Messages are sent, not streamed++- Every bot gets the built-in `chat` MCP server (`codync-host mcp chat`,+ `host/src/chat/outbox.rs`) with one tool, `send_message {text}`. In the bot's own chat and its+ threads, each call is one chat bubble, added to the turn's lane at once as an `agent` entry with+ `final: true`. A turn can send several.+- The agent's own reply text (`agent_message_chunk`) stays in the trace when the turn sent+ anything. A turn that sent nothing (an agent that ignores the tool, or has no MCP) falls back to+ the old rule: its last text becomes the turn's final message.+- Group room turns, `ask_bot` requests and routines reject `send_message`: their reply is the+ turn's last text, as before (`chat/group.rs`, `chat/team.rs`, `routines`).+- The rules reach the agent twice: the MCP server's instructions, and the frozen instruction+ snapshot (`chat/context.rs`).+- Clients never stream text into a bubble: the chat shows user messages, `final` agent entries,+ permission cards and notices (`isChat`). Nothing pops in and out while a turn runs.++## While it works++The working line under the last message shows the bot's activity; composing a `send_message`+reads as **Typing…** (`activity()` in `agent/bot.rs`). Thoughts and tool calls stay in the+Full conversation sheet.++## Motion and scrolling++- A message arriving while the list follows the newest pops in: 0.24 s,+ `cubic-bezier(.23, 1, .32, 1)`, from 12 pt lower at 94 % scale (iPhone: `ConversationLayout` in+ `ConversationList.swift`; desktop: `.row-in` in `thread.css`; reduced motion: a 0.12 s fade).+- The list stays pinned to the bottom while the reader is there; scrolling up releases it and the+ round "Jump to latest" button brings it back. Sending always returns to the bottom.+- The terminal UI lists the same messages; its steps line goes under the turn's last message.diff --git a/host/src/agent/bot.rs b/host/src/agent/bot.rsindex 53392e82..49be625f 100644--- a/host/src/agent/bot.rs+++ b/host/src/agent/bot.rs@@ -49,6 +49,11 @@ pub enum Cmd {text: String,},Ask(crate::chat::team::Ask),+ /// `send_message` from the bot's `chat` MCP server: a message for the user, now.+ SendToUser {+ text: String,+ reply: tokio::sync::oneshot::Sender<Result<()>>,+ },CancelAsk {id: String,},@@ -120,6 +125,7 @@ pub fn spawn(hub: Arc<Hub>, cfg: BotConfig) -> BotHandle {tools: HashMap::new(),plan_entry: None,last_text: None,+ sent: Vec::new(),perms: HashMap::new(),stop_requested: false,exit_tail: None,@@ -129,6 +135,11 @@ pub fn spawn(hub: Arc<Hub>, cfg: BotConfig) -> BotHandle {BotHandle { tx, task }}+/// The working line for a tool call: composing a message reads as typing.+fn activity(title: &str) -> &str {+ if title.contains("send_message") { "Typing…" } else { title }+}+/// What the agent can do with sessions besides creating them.#[derive(Clone, Copy)]struct SessionCaps {@@ -196,6 +207,8 @@ struct Actor {tools: HashMap<String, String>,plan_entry: Option<String>,last_text: Option<String>,+ /// Messages the bot sent the user this turn (`send_message`); none: its last text is the reply.+ sent: Vec<String>,/// permission entry id -> JSON-RPC request idperms: HashMap<String, Value>,stop_requested: bool,@@ -327,6 +340,9 @@ impl Actor {}}}+ Cmd::SendToUser { text, reply } => {+ let _ = reply.send(self.send_to_user(text));+ }Cmd::Stop => self.stop().await,Cmd::Permission { entry_id, option_id } => self.answer_permission(&entry_id, option_id).await,Cmd::NewSession => {@@ -640,6 +656,7 @@ impl Actor {self.tools.clear();self.plan_entry = None;self.last_text = None;+ 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());@@ -825,6 +842,7 @@ impl Actor {let composio = crate::market::composio::enabled_for(&self.hub.store, &self.cfg.connectors)?;let builtin = [Some("connectors"),+ Some("chat"),Some("team"),Some("memory"),Some("routines"),@@ -1015,6 +1033,12 @@ impl Actor {let mut final_text = None;let routine = self.active_routine.is_some();let grouped = self.active_group.is_some() || routine;+ let sent = std::mem::take(&mut self.sent);+ if !sent.is_empty() {+ // The bot talked through send_message: what it wrote as its reply stays in the trace.+ self.last_text = None;+ final_text = Some(sent.join("\n\n"));+ }if let Some(id) = self.last_text.take().filter(|_| !stopped)&& let Some(mut e) = self.hub.store.entry(&id){@@ -1179,7 +1203,7 @@ impl Actor {if let Some(e) = self.add(EntryKind::Tool, turn, data) {self.tools.insert(tool_id, e.id);}- self.set_activity(&title);+ self.set_activity(activity(&title));}"tool_call_update" => {let tool_id = u["toolCallId"].as_str().unwrap_or_default();@@ -1198,7 +1222,7 @@ impl Actor {let title = e.data["title"].as_str().unwrap_or_default().to_owned();self.hub.set_entry(&entry_id, &e.data);if status == "in_progress" {- self.set_activity(&title);+ self.set_activity(activity(&title));}}// The agent summarized its context: the next turn gets freshly rendered@@ -1322,6 +1346,21 @@ impl Actor {}}+ /// A `send_message`: the user's next bubble, in the turn's lane, right away. Only in the+ /// bot's own chat and threads; a room, a teammate or a routine reads the turn's reply.+ fn send_to_user(&mut self, text: String) -> Result<()> {+ let Some(turn) = self.turn else { bail!("no turn is running") };+ if self.active_group.is_some() || self.active_ask.is_some() || self.active_routine.is_some() {+ bail!("send_message isn't available in this turn: write your answer as your reply");+ }+ self.close_seg();+ self.add(EntryKind::Agent, turn, json!({"text": text, "final": true}))+ .ok_or_else(|| anyhow!("couldn't save the message"))?;+ self.sent.push(text);+ self.set_activity("Working…");+ Ok(())+ }+// MARK: streaming text segmentsfn append(&mut self, kind: SegKind, text: &str) {diff --git a/host/src/api/mod.rs b/host/src/api/mod.rsindex 5e395b2f..d5b74893 100644--- a/host/src/api/mod.rs+++ b/host/src/api/mod.rs@@ -420,6 +420,9 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -"memoryCall" => {crate::chat::memory::call(hub, str_arg(&b, "botId")?, str_arg(&b, "name")?, &b["arguments"]).await?}+ "chatCall" => {+ crate::chat::outbox::call(hub, str_arg(&b, "botId")?, str_arg(&b, "name")?, &b["arguments"]).await?+ }"teamCall" => {crate::chat::team::call(hub, str_arg(&b, "botId")?, str_arg(&b, "name")?, &b["arguments"]).await?}diff --git a/host/src/chat/context.rs b/host/src/chat/context.rsindex 25752953..0541e177 100644--- a/host/src/chat/context.rs+++ b/host/src/chat/context.rs@@ -126,10 +126,8 @@ pub fn render(store: &Store, cfg: &BotConfig) -> String {if !cfg.description.trim().is_empty() {lines.push(format!("Description: {}", cfg.description.trim()));}- lines.push(- "You are a persistent agent the user delegates work to from their phone through Codync. They see only your final reply of each turn, so keep it short and phone-friendly: say what you did and what needs the user."- .to_owned(),- );+ lines.push("You are a persistent agent the user delegates work to from their phone through Codync.".to_owned());+ lines.push(crate::chat::outbox::INSTRUCTIONS.to_owned());lines.push(format!("Your default execution directory is {}. {} Use this space for your own task files and outputs. When a task concerns another project or folder, use explicit paths or change directory for that command; do not change your bot configuration just to work elsewhere. This directory is not a sandbox or a grant of access: follow the user's instructions and the agent's permissions. Do not assume other bots' files belong to you.", cfg.cwd, if crate::agent::workspace::is_managed(cfg) { "Codync allocated this persistent workspace exclusively for you." } else { "The user selected this project folder." }));lines.push(crate::chat::team::INSTRUCTIONS.to_owned());lines.push(crate::routines::INSTRUCTIONS.to_owned());diff --git a/host/src/chat/mod.rs b/host/src/chat/mod.rsindex 820fd437..c6a05831 100644--- a/host/src/chat/mod.rs+++ b/host/src/chat/mod.rs@@ -1,9 +1,10 @@-//! Conversation features on top of bots: group room turns, bot-to-bot-//! requests, prompt snapshots, long-term memory and automatic bot names.+//! Conversation features on top of bots: messages to the user, group room turns,+//! bot-to-bot requests, prompt snapshots, long-term memory and automatic bot names.pub mod context;pub mod group;pub mod memory;pub mod naming;+pub mod outbox;pub mod team;pub mod uploads;diff --git a/host/src/chat/outbox.rs b/host/src/chat/outbox.rsnew file mode 100644index 00000000..f5dfedf0--- /dev/null+++ b/host/src/chat/outbox.rs@@ -0,0 +1,52 @@+//! How a bot talks to the user, Grok Bot's way: in its chat (and threads) the user sees+//! only the messages the bot sends with the built-in `chat` MCP server's `send_message`,+//! each one its own bubble. What the agent writes as its reply stays in the trace, unless+//! it sent nothing in the turn: then its last text becomes the reply, as before.++use crate::agent::bot::Cmd;+use crate::hub::Hub;+use anyhow::{Result, anyhow, bail};+use serde_json::{Value, json};+use std::sync::Arc;+use std::time::Duration;++pub const INSTRUCTIONS: &str = "In your chat with the user and its threads, the user sees only what you send with send_message; \+text you write as your reply never reaches them. Send a message whenever you have something worth telling them: \+short, plain and phone-friendly, a sentence or a few, each message one thought. Lead with the result, then what needs the user. \+Don't send just to acknowledge, to say you started or are still working, or to repeat yourself. \+In a group chat, a teammate's request or a routine, send_message isn't available: write your answer as your reply.";++/// Longest message accepted, in bytes.+const MAX_MESSAGE_BYTES: usize = 32 * 1024;+/// How long the bot's actor has to take the message.+const DELIVERY_TIMEOUT: Duration = Duration::from_secs(10);++pub fn tools() -> Value {+ json!([{+ "name": "send_message",+ "description": "Send the user one chat message (Markdown). It shows right away as its own bubble on their phone and computer; send several for several thoughts.",+ "inputSchema": {+ "type": "object",+ "properties": {"text": {"type": "string", "description": "The message, as the user should read it."}},+ "required": ["text"],+ },+ "annotations": {"readOnlyHint": false, "idempotentHint": false},+ }])+}++pub async fn call(hub: &Arc<Hub>, bot: &str, name: &str, args: &Value) -> Result<Value> {+ if name != "send_message" {+ bail!("unknown chat tool: {name}");+ }+ let text = args["text"].as_str().unwrap_or_default().trim();+ if text.is_empty() || text.len() > MAX_MESSAGE_BYTES {+ bail!("text must be nonempty and at most {MAX_MESSAGE_BYTES} bytes");+ }+ let (reply, delivered) = tokio::sync::oneshot::channel();+ hub.send_cmd(bot, Cmd::SendToUser { text: text.to_owned(), reply })?;+ tokio::time::timeout(DELIVERY_TIMEOUT, delivered)+ .await+ .map_err(|_| anyhow!("the bot didn't take the message in time"))?+ .map_err(|_| anyhow!("the bot shut down"))??;+ Ok(json!({"sent": true}))+}diff --git a/host/src/main.rs b/host/src/main.rsindex b9685626..0db7ebed 100644--- a/host/src/main.rs+++ b/host/src/main.rs@@ -226,6 +226,13 @@ enum McpServer {#[arg(long, default_value_t = service::DEFAULT_PORT)]port: u16,},+ /// Send the user chat messages.+ Chat {+ #[arg(long)]+ bot: String,+ #[arg(long, default_value_t = service::DEFAULT_PORT)]+ port: u16,+ },/// Discover and ask the user's other bots for help.Team {#[arg(long)]@@ -460,6 +467,7 @@ async fn main() -> Result<()> {}Sub::Mcp { server: McpServer::Computer { bot, port } } => mcp::serve(bot, port, mcp::Server::Computer).await,Sub::Mcp { server: McpServer::Routines { bot, port } } => mcp::serve(bot, port, mcp::Server::Routines).await,+ Sub::Mcp { server: McpServer::Chat { bot, port } } => mcp::serve(bot, port, mcp::Server::Chat).await,Sub::Mcp { server: McpServer::Team { bot, port } } => mcp::serve(bot, port, mcp::Server::Team).await,Sub::Mcp { server: McpServer::Memory { bot, port } } => mcp::serve(bot, port, mcp::Server::Memory).await,Sub::Mcp { server: McpServer::Composio { bot, port } } => mcp::serve(bot, port, mcp::Server::Composio).await,diff --git a/host/src/mcp.rs b/host/src/mcp.rsindex 87fa7761..c677cc5c 100644--- a/host/src/mcp.rs+++ b/host/src/mcp.rs@@ -1,4 +1,4 @@-//! Built-in stdio MCP servers: `team` discovers and asks other bots; `computer`+//! Built-in stdio MCP servers: `chat` sends the user messages; `team` discovers and asks other bots; `computer`//! operates the desktop when enabled. Calls go through authenticated loopback//! HTTP to the running host, which owns delegation and screen control.@@ -11,6 +11,7 @@ pub const PROTOCOL_VERSION: &str = "2025-06-18";#[derive(Clone, Copy)]pub enum Server {+ Chat,Connectors,Routines,Computer,@@ -125,6 +126,7 @@ pub async fn serve(bot: String, port: u16, server: Server) -> Result<()> {}Server::Computer => ("codync-computer", INSTRUCTIONS, tools()),Server::Routines => ("codync-routines", crate::routines::INSTRUCTIONS, crate::routines::tools()),+ Server::Chat => ("codync-chat", crate::chat::outbox::INSTRUCTIONS, crate::chat::outbox::tools()),Server::Team => ("codync-team", crate::chat::team::INSTRUCTIONS, crate::chat::team::tools()),Server::Memory => ("codync-memory", crate::chat::memory::INSTRUCTIONS, crate::chat::memory::tools()),Server::Composio => {@@ -172,6 +174,7 @@ async fn call(port: u16, token: &str, bot: &str, params: &Value, server: Server)Server::Connectors => ("connectorCall", Duration::from_secs(90)),Server::Routines => ("routineCall", Duration::from_secs(30)),Server::Computer => ("computerCall", Duration::from_secs(60)),+ Server::Chat => ("chatCall", Duration::from_secs(30)),Server::Team => ("teamCall", crate::chat::team::ASK_TIMEOUT + Duration::from_secs(30)),Server::Memory => ("memoryCall", Duration::from_secs(30)),Server::Composio => ("composioCall", Duration::from_secs(120)),@@ -190,7 +193,7 @@ async fn call(port: u16, token: &str, bot: &str, params: &Value, server: Server)Ok(v) if ok => {return match server {Server::Computer => json!({"content": v["content"]}),- Server::Team | Server::Memory | Server::Routines | Server::Connectors => {+ Server::Chat | Server::Team | Server::Memory | Server::Routines | Server::Connectors => {json!({"content": [{"type": "text", "text": v.to_string()}]})}Server::Composio => json!({"content": [{"type": "text", "text": v["result"].to_string()}]}),diff --git a/host/src/tui/view.rs b/host/src/tui/view.rsindex fd3f51cd..3608beb1 100644--- a/host/src/tui/view.rs+++ b/host/src/tui/view.rs@@ -915,13 +915,14 @@ fn with_bg(lines: Vec<Line<'static>>, width: usize, bg: Style) -> Vec<Line<'statstruct TurnInfo {steps: usize,files: BTreeSet<String>,- has_final: bool,+ /// The turn's last message to the user: the steps line goes under it.+ last_message: Option<String>,}fn turn_info(entries: &[&Entry]) -> HashMap<i64, TurnInfo> {let mut m: HashMap<i64, TurnInfo> = HashMap::new();for e in entries {- let ti = m.entry(e.turn).or_insert_with(|| TurnInfo { steps: 0, files: BTreeSet::new(), has_final: false });+ let ti = m.entry(e.turn).or_insert_with(|| TurnInfo { steps: 0, files: BTreeSet::new(), last_message: None });match e.kind {Kind::Tool => {ti.steps += 1;@@ -931,7 +932,7 @@ fn turn_info(entries: &[&Entry]) -> HashMap<i64, TurnInfo> {}}}- Kind::Agent if e.is_final() => ti.has_final = true,+ Kind::Agent if e.is_final() => ti.last_message = Some(e.id.clone()),_ => {}}}@@ -954,16 +955,6 @@ fn replies(n: i64) -> String {if n == 1 { "1 reply".into() } else { format!("{n} replies") }}-fn live_entry<'a>(app: &App, bot: &Bot, entries: &[&'a Entry]) -> Option<&'a str> {- if !app.online || bot.status != Status::Working || !bot.works_in(app.thread.as_deref()) {- return None;- }- entries- .last()- .filter(|e| e.kind == Kind::Agent && e.data["final"] == false && !e.text().is_empty() && e.text() != "(pass)")- .map(|e| e.id.as_str())-}-fn build_chat(app: &App, b: &Bot, width: usize) -> Built {let t = theme();let mut out = Built { lines: vec![], buttons: vec![], messages: vec![] };@@ -992,20 +983,14 @@ fn build_chat(app: &App, b: &Bot, width: usize) -> Built {let side = width.saturating_sub(w(&label) + 4);out.lines.push(Line::from(Span::styled(format!(" ───{label}{}", "─".repeat(side)), t.dim)));}- let live = live_entry(app, b, &entries);+ // A bot's messages arrive whole (Grok Bot's `send_message`); what it writes along the way is trace.for e in &entries {- let mut visible = (*e).clone();- if live == Some(e.id.as_str()) {- visible.data["final"] = true.into();- }- let e = &visible;entry_lines(&mut out, app, b, e, &info, thread.is_none(), width);}// A turn in flight: who's on it and what they're doing.let last_turn = entries.iter().map(|e| e.turn).max().unwrap_or(0);- // A group's members each reply in the room turn, so a reply doesn't end it.- let in_flight = b.group || info.get(&last_turn).is_none_or(|ti| !ti.has_final);- if b.status == Status::Working && b.works_in(thread) && in_flight {+ // A message doesn't end the turn: the bot may send several.+ if b.status == Status::Working && b.works_in(thread) {gap(&mut out);out.lines.push(Line::from(Span::styled(format!(" {}", b.name), name_style(&b.color))));let act = if b.activity.is_empty() { "Working…".to_owned() } else { b.activity.clone() };@@ -1140,7 +1125,7 @@ fn entry_lines(out.lines.extend(md::render(e.text(), width, 1));reactions(out, e);out.messages.push((e.id.clone(), from, out.lines.len()));- if let Some(ti) = info.get(&e.turn).filter(|ti| ti.steps > 0) {+ if let Some(ti) = info.get(&e.turn).filter(|ti| ti.steps > 0 && ti.last_message.as_ref() == Some(&e.id)) {let files = if ti.files.is_empty() {String::new()} else {@@ -2445,33 +2430,6 @@ fn toasts(buf: &mut Buffer, area: Rect, app: &App) {mod tests {use super::*;- #[test]- fn live_text_stays_in_its_lane_and_disappears_after_a_tool() {- use serde_json::json;- let (tx, _) = tokio::sync::mpsc::unbounded_channel();- let mut app = App::new(super::super::net::Client::new("http://127.0.0.1:1", None), tx, String::new());- app.on_msg(super::super::app::Msg::Event(json!({"type":"bot","bot":{"id":"b","status":"working"}})));- app.online = true;- let entry = Entry {- id: "live".into(),- seq: 1,- turn: 1,- kind: Kind::Agent,- data: json!({"text":"answer","final":false}),- created_at: 0,- thread_id: None,- };- let bot = &app.bots["b"];- assert_eq!(live_entry(&app, bot, &[&entry]), Some("live"));- let tool = Entry { kind: Kind::Tool, ..entry.clone() };- assert_eq!(live_entry(&app, bot, &[&entry, &tool]), None);- app.thread = Some("thread".into());- assert_eq!(live_entry(&app, &app.bots["b"], &[&entry]), None);- app.thread = None;- app.online = false;- assert_eq!(live_entry(&app, &app.bots["b"], &[&entry]), None);- }-#[test]fn civil_dates() {assert_eq!(month_day(0), (0, 1)); // 1970-01-01diff --git a/host/tests/e2e.rs b/host/tests/e2e.rsindex 865e7f5e..44e0de90 100644--- a/host/tests/e2e.rs+++ b/host/tests/e2e.rs@@ -160,6 +160,64 @@ async fn turn_with_approval_reaches_a_final_reply() {assert_eq!(synced["bots"][0]["unread"], 1);}+#[tokio::test]+async fn sent_messages_are_the_reply() {+ if Command::new("python3").arg("--version").output().is_err() {+ eprintln!("skipping: python3 not available");+ return;+ }+ let host = start_host().await;+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fake_agent.py");+ let bot = host+ .call(+ "createBot",+ json!({+ "name": "Tester", "backend": "custom", "command": format!("python3 '{}'", agent.display()),+ "cwd": host.home.to_string_lossy(), "permission": "ask",+ }),+ )+ .await["bot"]["id"]+ .as_str()+ .unwrap()+ .to_owned();+ let send = |text: &str| json!({"botId": bot, "name": "send_message", "arguments": {"text": text}});++ // Between turns there's no one to talk to.+ let idle = reqwest::Client::new()+ .post(format!("{}/api/chatCall", host.base))+ .bearer_auth(&host.token)+ .json(&send("hello?"))+ .send()+ .await+ .unwrap();+ assert!(!idle.status().is_success());++ host.call("send", json!({"botId": bot, "text": "go", "clientNonce": "n1"})).await;+ let card = host.wait_for(&bot, |e| e["kind"] == "permission" && e["data"]["status"] == "pending").await;+ // Mid-turn (the agent waits on the approval), each message is its own chat bubble at once.+ host.call("chatCall", send("Found it.")).await;+ host.call("chatCall", send("Fixing the typo now.")).await;+ let first = host.wait_for(&bot, |e| e["kind"] == "agent" && e["data"]["text"] == "Found it.").await;+ assert_eq!(first["data"]["final"], true);++ host.call("respondPermission", json!({"entryId": card["id"], "optionId": "allow"})).await;+ let deadline = Instant::now() + Duration::from_secs(20);+ while host.call("sync", json!({"since": 0})).await["bots"][0]["status"] != "idle" {+ assert!(Instant::now() < deadline, "turn didn't finish");+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ // What the agent wrote as its reply stays in the trace.+ let history = host.call("history", json!({"botId": bot})).await;+ let entries = history["entries"].as_array().unwrap();+ assert!(entries.iter().any(|e| e["data"]["text"].as_str().is_some_and(|t| t.starts_with("Done"))));+ let finals: Vec<&str> = entries+ .iter()+ .filter(|e| e["kind"] == "agent" && e["data"]["final"] == true)+ .map(|e| e["data"]["text"].as_str().unwrap())+ .collect();+ assert_eq!(finals, ["Found it.", "Fixing the typo now."]);+}+#[tokio::test]async fn rejects_requests_without_the_token() {let host = start_host().await;