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
Merge origin/dev into dev
leepokaif32f3d61d6e3
diff --cc apps/ios/WhatsNew.mdindex 933a13cb,a52ef21b..6d2052ff--- a/apps/ios/WhatsNew.md+++ b/apps/ios/WhatsNew.md@@@ -9,14 -9,14 +9,22 @@@ a version without one gets a generic "B### zh-Hant+ - Bot 改成像 Grok 一樣傳訊息:工作途中一小段一小段發給你,每則都是完整的訊息,不再逐字跳動。+ - Bot 正在寫訊息時會顯示「Typing…」;新訊息會輕輕彈入。+ - 對話捲動與送出訊息更順暢,「思考中」的狀態不會再被輸入框擋住。+ - 輸入框不再跳出「貼上圖片」提示;要貼上圖片請用「+」選單裡的「貼上」。+- Live Activity 與動態島更生動:bot 的表情會跟著狀態變,需要你時文字轉成琥珀色並出現「Review」按鈕,工作時間會自己往上數。+- 新增「Team」小工具:用 2×2 角色格一眼看四個 bot,需要你的排在最前面。+- Bots 小工具每一列右側直接顯示上色的狀態。+- 新增控制中心按鈕:顯示最需要你的 bot,一點就打開。### en-US+ - Bots now message you the way Grok does: short, complete messages as they work, instead of text typing itself out.+ - You see "Typing…" while a bot writes, and new messages pop in gently.+ - Scrolling and sending feel smoother, and the thinking indicator no longer hides behind the message box.+ - The message box no longer pops up a "Paste image" chip; use Paste in the + menu instead.+- Livelier Live Activities and Dynamic Island: the bot's face follows its state, the text turns amber with a Review button when it needs you, and the elapsed time counts up on its own.+- New Team widget: four bots as characters in a 2×2 grid, the ones that need you first.+- Each row of the Bots widget shows its state in color.+- New Control Center control: the bot that needs you most, one tap to open it.diff --cc host/src/agent/bot/mod.rsindex 52742d2c,00000000..7e02998bmode 100644,000000..100644--- a/host/src/agent/bot/mod.rs+++ b/host/src/agent/bot/mod.rs@@@ -1,330 -1,0 +1,343 @@@+//! One actor per bot. It owns the bot's ACP process and session, runs turns one+//! at a time, and maps ACP `session/update`s onto transcript entries.+//!+//! Chat model (from Grok Bot): the thread only shows user messages, the *final*+//! agent message of each turn, permission cards and notices. Narration between+//! tool calls, thoughts, tool calls and plans are trace entries shown in the+//! "full conversation" sheet, and surface live as the roster activity line.+//!+//! Context (from Grok Bot too): the bot's instructions and memory are a frozen+//! snapshot per session and compaction epoch (`context`), finished exchanges feed+//! its memory keeper (`memory`), messages sent while it works are folded into+//! its next turn, and a turn cut off by a host restart is resumed.+//!+//! Lanes: besides its own chat, a bot talks in threads (each a session of its own,+//! forked from the main one when the agent can fork) and in group chats (turns in+//! its main session, written to the group's transcript; see `group`).++mod queue;+mod session;+mod turn;+mod updates;++pub(crate) use session::{launch_commands, select_model, start_agent};++use crate::agent::acp::{Acp, Incoming};+use crate::chat::context::{Identity, Snapshot};+use crate::chat::group::GroupTurn;+use crate::chat::memory;+use crate::hub::{BotStatus, Hub};+use crate::store::{BotConfig, Entry, EntryKind, Lane, now_ms};+use anyhow::{Result, anyhow};+use serde::Serialize;+use serde_json::{Value, json};+use std::collections::{HashMap, HashSet, VecDeque};+use std::sync::Arc;+use std::time::{Duration, Instant};+use tokio::sync::mpsc;++/// How a notice renders in the chat (wire values: `info` / `error` / `divider`).+#[derive(Clone, Copy, Debug, Serialize)]+#[serde(rename_all = "lowercase")]+pub enum NoticeStyle {+ Info,+ Error,+ Divider,+}++pub enum Cmd {+ RefreshTools,+ Routine(String),+ /// The user wrote in the bot's chat or one of its threads.+ Send {+ lane: Lane,+ entry_id: String,+ 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,+ },+ /// Its turn in a group's room turn.+ Group(GroupTurn),+ /// The group's room turns stopped: drop its queued turns, stop a running one.+ CancelGroup {+ chat: String,+ },+ Stop,+ Permission {+ entry_id: String,+ option_id: Option<String>,+ },+ NewSession,+ Reconfigure(Box<BotConfig>),+ Shutdown,+}++enum Queued {+ Routine(String),+ User { lane: Lane, entry_id: String, text: String },+ Ask(crate::chat::team::Ask),+ Group(GroupTurn),+}++pub struct BotHandle {+ pub tx: mpsc::UnboundedSender<Cmd>,+ /// The actor task; it kills its agent process on the way out.+ pub task: tokio::task::JoinHandle<()>,+}++pub fn spawn(hub: Arc<Hub>, cfg: BotConfig) -> BotHandle {+ let (tx, rx) = mpsc::unbounded_channel();+ let session_id = hub.store.bot(&cfg.id).ok().flatten().and_then(|b| b.session_id);+ // A turn the previous host process never finished (crash, update, restart), unless+ // it's stale: an hour-old task is more likely unwanted than awaited (gawkbot's rule).+ let interrupted = hub.store.kv_get(&inflight_key(&cfg.id)).and_then(|v| {+ let (started, thread) = v.split_once('\t').unwrap_or((&v, ""));+ let started: i64 = started.parse().ok()?;+ (now_ms() - started < STALE_RESUME_MS)+ .then(|| Lane { chat: cfg.id.clone(), thread: (!thread.is_empty()).then(|| thread.to_owned()) })+ });+ let keeper = memory::spawn_keeper(hub.clone(), cfg.id.clone());+ let lane = Lane::main(&cfg.id);+ let actor = Actor {+ hub,+ cfg,+ conn: None,+ session_id,+ thread_sessions: HashMap::new(),+ lane,+ turn_session: None,+ thread_intro: None,+ active_group: None,+ active_routine: None,+ routine_deadline: None,+ routine_timed_out: false,+ routine_completion: None,+ session_fresh: false,+ applied_system: None,+ keeper,+ turn_text: None,+ announce: None,+ turn: None,+ queue: VecDeque::new(),+ active_ask: None,+ seg: Seg::None,+ tools: HashMap::new(),+ plan_entry: None,+ last_text: None,++ sent: Vec::new(),+ perms: HashMap::new(),+ stop_requested: false,+ exit_tail: None,+ tools_changed: false,+ };+ let task = tokio::spawn(actor.run(rx, interrupted));+ 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 {+ /// `session/load`: resume a session after a restart.+ load: bool,+ /// `session/fork`: a thread starts as a copy of the main session.+ fork: bool,+}++pub(crate) struct Conn {+ pub(crate) acp: Arc<Acp>,+ pub(crate) rx: mpsc::UnboundedReceiver<Incoming>,+ sessions: SessionCaps,+ /// Claude's adapter: takes `_meta.systemPrompt` and `_meta.claudeCode.options`.+ pub(crate) claude: bool,+ /// Sessions already created or loaded in this process.+ loaded: HashSet<String>,+}++#[derive(Clone, Copy, PartialEq)]+enum SegKind {+ Text,+ Thought,+}++enum Seg {+ None,+ Open { kind: SegKind, entry_id: String, buf: String, flushed: Instant, dirty: bool },+}++// These flags describe independent actor concerns, not interchangeable states.+#[allow(clippy::struct_excessive_bools)]+struct Actor {+ hub: Arc<Hub>,+ cfg: BotConfig,+ conn: Option<Conn>,+ /// The main session: the bot's own chat and its group turns.+ session_id: Option<String>,+ /// Thread root -> the thread's session (loaded from kv on first use).+ thread_sessions: HashMap<String, String>,+ /// Where the current (or last) turn talks; entries go there.+ lane: Lane,+ /// The session the current turn prompts.+ turn_session: Option<String>,+ /// Told on the first message of a new thread session: what the thread is about.+ thread_intro: Option<String>,+ active_group: Option<GroupTurn>,+ active_routine: Option<String>,+ routine_deadline: Option<Instant>,+ routine_timed_out: bool,+ routine_completion: Option<RoutineCompletion>,+ /// True until the first prompt of a new ACP session has been sent.+ session_fresh: bool,+ /// (session, instructions) last handed to Claude as its system prompt by this process.+ applied_system: Option<(String, String)>,+ keeper: mpsc::UnboundedSender<memory::Exchange>,+ /// The user's words for this turn (None for a hidden turn); feeds memory.+ turn_text: Option<String>,+ /// A profile update this turn carried, recorded once the agent got it.+ announce: Option<(Snapshot, Identity)>,+ turn: Option<i64>,+ queue: VecDeque<Queued>,+ active_ask: Option<crate::chat::team::Ask>,+ seg: Seg,+ 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 id+ perms: HashMap<String, Value>,+ stop_requested: bool,+ /// Last stderr lines of an agent process that just exited.+ exit_tail: Option<String>,+ /// Connectors changed: restart the agent before the next turn so the+ /// session is resumed with the new MCP servers.+ tools_changed: bool,+}++struct RoutineCompletion {+ id: String,+ status: crate::routines::Status,+ detail: Option<String>,+ text: Option<String>,+}++type Done = Result<Value>;++impl Actor {+ /// `interrupted`: the previous host process stopped a turn in this lane (the bot's+ /// chat or one of its threads); resume it first.+ async fn run(mut self, mut rx: mpsc::UnboundedReceiver<Cmd>, interrupted: Option<Lane>) {+ let (done_tx, mut done_rx) = mpsc::unbounded_channel::<Done>();+ let mut flush_tick = tokio::time::interval(Duration::from_millis(300));+ if let Some(run) = self.hub.routines.recovery(&self.cfg.id) {+ self.active_routine = Some(run.id.clone());+ self.routine_deadline = Some(Instant::now() + self.hub.routines.timeout(&run.id));+ if let Some(root) = run.root_id {+ self.resume_interrupted(Lane::in_thread(&self.cfg.id, &root), &done_tx).await;+ } else {+ self.finish_routine(+ crate::routines::Status::Interrupted,+ Some("Routine has no saved session; inspect before retrying".into()),+ None,+ );+ }+ } else if let Some(lane) = interrupted {+ self.resume_interrupted(lane, &done_tx).await;+ }+ loop {+ tokio::select! {+ cmd = rx.recv() => {+ let Some(cmd) = cmd else { break };+ if !self.on_cmd(cmd, &done_tx).await { break }+ }+ inc = recv_incoming(&mut self.conn) => self.on_incoming(inc).await,+ 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;+ }+ self.finish_turn(&done);+ self.next_in_queue(&done_tx).await;+ }+ _ = flush_tick.tick() => {+ self.flush(false);+ if self.routine_completion.is_some() && self.retry_routine_completion() {+ self.set_inflight(false);+ self.next_in_queue(&done_tx).await;+ }+ if self.active_routine.is_some() && self.turn.is_some() && self.routine_deadline.is_some_and(|deadline| Instant::now() >= deadline) && !self.routine_timed_out {+ self.routine_timed_out = true;+ self.stop_requested = true;+ if let Some(c) = self.conn.take() { c.acp.kill().await; }+ }+ },+ }+ }+ self.hub.team.cancel_from(&self.cfg.id);+ self.complete_ask(Err(anyhow!("recipient shut down")));+ self.complete_group(Err(anyhow!("bot shut down")));+ if let Some(c) = self.conn.take() {+ c.acp.kill().await;+ }+ }++ fn id(&self) -> String {+ self.cfg.id.clone()+ }++ fn set_activity(&self, a: &str) {+ if self.hub.runtime(&self.cfg.id).activity != a {+ let a = a.to_owned();+ self.hub.set_runtime(&self.cfg.id, |r| {+ if r.status == BotStatus::Working {+ r.activity = a;+ }+ });+ }+ }++ /// Adds an entry to the current lane, signed by this bot (a group shows who said it).+ fn add(&self, kind: EntryKind, turn: i64, mut data: Value) -> Option<Entry> {+ data["author"] = self.cfg.id.clone().into();+ self.hub.add_entry(&self.lane, kind, turn, &data)+ }++ /// A notice in the running turn's lane (or the bot's own chat between turns).+ fn notice(&self, text: &str, style: NoticeStyle) {+ let Some(turn) = self.turn else {+ let main = Lane::main(&self.cfg.id);+ let turn = self.hub.store.max_turn(&self.cfg.id);+ self.hub.add_entry(&main, EntryKind::Notice, turn, &json!({"text": text, "style": style}));+ return;+ };+ self.add(EntryKind::Notice, turn, json!({"text": text, "style": style}));+ }+}++/// Told to a bot whose turn the previous host process cut off (Grok Bot's upgrade resume).+const RESUME_PROMPT: &str = "[Codync restarted on this computer and interrupted you mid-task. You've been resumed with your full conversation intact. Continue exactly where you left off and finish what you were doing. If your previous step already completed an action, do NOT repeat it — just carry on from there.]";++/// An interrupted turn older than this isn't resumed.+const STALE_RESUME_MS: i64 = 60 * 60 * 1000;++fn inflight_key(bot_id: &str) -> String {+ format!("turn.inflight.{bot_id}")+}++async fn recv_incoming(conn: &mut Option<Conn>) -> Option<Incoming> {+ match conn {+ Some(c) => c.rx.recv().await,+ None => std::future::pending().await,+ }+}diff --cc host/src/agent/bot/queue.rsindex 144492b7,00000000..8366e21bmode 100644,000000..100644--- a/host/src/agent/bot/queue.rs+++ b/host/src/agent/bot/queue.rs@@@ -1,339 -1,0 +1,342 @@@+//! Commands from clients and the queue of turns waiting for the bot.++use super::{Actor, Cmd, Done, NoticeStyle, Queued, RESUME_PROMPT, RoutineCompletion, inflight_key};+use crate::chat::memory;+use crate::hub::BotStatus;+use crate::store::{Lane, now_ms};+use anyhow::{Result, anyhow};+use serde_json::json;+use std::time::Instant;+use tokio::sync::mpsc;++impl Actor {+ pub(super) async fn on_cmd(&mut self, cmd: Cmd, done_tx: &mpsc::UnboundedSender<Done>) -> bool {+ match cmd {+ Cmd::RefreshTools => {+ self.tools_changed = true;+ }+ Cmd::Routine(id) => {+ self.queue.push_back(Queued::Routine(id));+ if self.turn.is_none() {+ self.next_in_queue(done_tx).await;+ }+ }+ Cmd::Send { lane, entry_id, text } => {+ self.queue.push_back(Queued::User { lane, entry_id, text });+ if self.turn.is_none() {+ self.next_in_queue(done_tx).await;+ }+ }+ Cmd::Group(turn) => {+ self.queue.push_back(Queued::Group(turn));+ if self.turn.is_none() {+ self.next_in_queue(done_tx).await;+ }+ }+ Cmd::CancelGroup { chat } => {+ // Dropping a queued turn's reply tells the room it won't come.+ self.queue.retain(|q| !matches!(q, Queued::Group(g) if g.lane.chat == chat));+ if self.active_group.as_ref().is_some_and(|g| g.lane.chat == chat) {+ self.cancel_turn().await;+ }+ }+ Cmd::Ask(ask) => {+ self.queue.push_back(Queued::Ask(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.hub.team.cancel_from(&self.cfg.id);+ self.stop_requested = true;+ // The request has expired. Kill only its process so a harness+ // ignoring cooperative cancellation cannot block the queue.+ if let Some(c) = self.conn.take() {+ c.acp.kill().await;+ }+ }+ }++ 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 => {+ if self.turn.is_some() {+ self.stop().await;+ }+ self.forget_session();+ // Like Grok Bot's clearConversation: the half-written episode goes too; memory stays.+ if let Err(error) = memory::set_pending_episode(&self.hub.store, &self.cfg.id, &[]) {+ tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't clear the pending episode");+ }+ self.notice("New session — the agent starts with a fresh context.", NoticeStyle::Divider);+ }+ Cmd::Reconfigure(cfg) => {+ let cfg = *cfg;+ let restart = cfg.backend != self.cfg.backend+ || cfg.command != self.cfg.command+ || cfg.cwd != self.cfg.cwd+ || cfg.model != self.cfg.model;+ self.tools_changed |= cfg.connectors != self.cfg.connectors || cfg.computer != self.cfg.computer;+ // Name, description and skill changes reach the agent as a profile update+ // on the next message (see `context`).+ self.cfg = cfg;+ if restart {+ if let Some(c) = self.conn.take() {+ c.acp.kill().await;+ }+ for root in self.thread_roots() {+ self.set_session(Some(&root), None);+ }+ if self.session_id.is_some() {+ self.forget_session();+ self.notice(+ "The agent, model, command or folder changed — the agent starts with a fresh context.",+ NoticeStyle::Divider,+ );+ }+ // A running prompt now fails; finish_turn reports it.+ }+ }+ Cmd::Shutdown => return false,+ }+ true+ }++ pub(super) async fn stop(&mut self) {+ self.hub.team.cancel_from(&self.cfg.id);+ if let Err(error) = self.hub.routines.cancel_queued(&self.hub.store, &self.cfg.id) {+ tracing::error!(error = format!("{error:#}"), "couldn't cancel queued routines");+ }+ 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);+ }+ }+ self.cancel_turn().await;+ }++ /// Stops the running turn only (queued ones stay).+ pub(super) async fn cancel_turn(&mut self) {+ if self.turn.is_none() {+ return;+ }+ self.stop_requested = true;+ let ids: Vec<String> = self.perms.keys().cloned().collect();+ for id in ids {+ self.answer_permission(&id, None).await;+ }+ if let (Some(c), Some(sid)) = (&self.conn, &self.turn_session) {+ let _ = c.acp.notify("session/cancel", json!({"sessionId": sid})).await;+ }+ }++ pub(super) async fn next_in_queue(&mut self, done_tx: &mpsc::UnboundedSender<Done>) {+ let main = Lane::main(&self.cfg.id);+ while self.turn.is_none() && self.routine_completion.is_none() && !self.queue.is_empty() {+ match self.queue.front() {+ Some(Queued::Routine(_)) => {+ let Some(Queued::Routine(id)) = self.queue.pop_front() else { unreachable!("front is a routine") };+ self.active_routine = Some(id.clone());+ self.routine_timed_out = false;+ match self.hub.routines.begin(&self.hub, &self.cfg.id, &id) {+ Ok(Some(prepared)) => {+ self.routine_deadline = Some(Instant::now() + prepared.timeout);+ let result = self.start_turn(prepared.lane, &[], &prepared.prompt, false, done_tx).await;+ self.turn_text = None;+ if let Err(error) = result {+ self.start_failed(&error);+ }+ }+ Ok(None) => {+ self.active_routine = None;+ self.hub.routines.release(&self.cfg.id);+ }+ Err(error) => {+ self.finish_routine(+ crate::routines::Status::Failed,+ Some(format!("Could not start routine: {error:#}")),+ None,+ );+ }+ }+ continue;+ }+ Some(Queued::Ask(_)) => {+ let Some(Queued::Ask(ask)) = self.queue.pop_front() else { unreachable!("front is an ask") };+ if ask.reply.is_closed() {+ continue;+ }+ let ids = [ask.entry_id.clone()];+ let prompt = ask.prompt.clone();+ self.active_ask = 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;+ if let Err(e) = result {+ self.start_failed(&e);+ }+ continue;+ }+ Some(Queued::Group(_)) => {+ let Some(Queued::Group(turn)) = self.queue.pop_front() else {+ unreachable!("front is a group turn")+ };+ if turn.reply.is_closed() {+ continue;+ }+ let (lane, prompt) = (turn.lane.clone(), turn.prompt.clone());+ self.active_group = Some(turn);+ let result = self.start_turn(lane, &[], &prompt, false, done_tx).await;+ // The room is not the user's private chat: nothing here feeds memory.+ self.turn_text = None;+ if let Err(e) = result {+ self.start_failed(&e);+ }+ continue;+ }+ _ => {}+ }+ // Messages sent while the agent worked go out together as its next turn+ // without crossing a bot request or another lane: each gets its own reply.+ let Some(Queued::User { lane, .. }) = self.queue.front() else { continue };+ let lane = lane.clone();+ let mut batch = Vec::new();+ while let Some(Queued::User { lane: l, .. }) = self.queue.front()+ && *l == lane+ {+ if let Some(Queued::User { entry_id, text, .. }) = self.queue.pop_front() {+ batch.push((entry_id, text));+ }+ }+ let ids: Vec<String> = batch.iter().map(|(id, _)| id.clone()).collect();+ let text = batch.iter().map(|(_, t)| t.as_str()).collect::<Vec<_>>().join("\n\n");+ if let Err(e) = self.start_turn(lane, &ids, &text, false, done_tx).await {+ self.start_failed(&e);+ }+ }+ }++ 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_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")+ && let Some(h) = crate::agent::backends::harness(&self.cfg.backend)+ {+ msg = format!("{0} needs you to sign in. Open {0} in Marketplace to sign in.", h.name);+ }+ self.notice(&msg, NoticeStyle::Error);+ self.turn = None;+ if self.routine_completion.is_none() {+ self.set_inflight(false);+ }+ self.hub.set_runtime(&self.id(), |r| {+ r.status = BotStatus::Error;+ r.activity = "Couldn't start".into();+ r.started_at = None;+ r.lane = None;+ });+ 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_group(&mut self, result: Result<Option<String>>) {+ if let Some(turn) = self.active_group.take() {+ let _ = turn.reply.send(result);+ }+ }++ pub(super) fn finish_routine(+ &mut self,+ status: crate::routines::Status,+ detail: Option<String>,+ text: Option<String>,+ ) {+ if let Some(id) = self.active_routine.take() {+ self.routine_completion = Some(RoutineCompletion { id, status, detail, text });+ self.routine_deadline = None;+ self.retry_routine_completion();+ }+ }++ /// If SQLite is temporarily unavailable, keep the result and block this+ /// actor's next turn until the durable completion has been saved.+ pub(super) fn retry_routine_completion(&mut self) -> bool {+ let Some(completion) = &self.routine_completion else {+ return true;+ };+ match self.hub.routines.complete(+ &self.hub,+ &completion.id,+ completion.status,+ completion.detail.clone(),+ completion.text.clone(),+ ) {+ Ok(()) => {+ self.routine_completion = None;+ true+ }+ Err(error) => {+ tracing::error!(+ error = format!("{error:#}"),+ run = completion.id,+ "couldn't save routine result; will retry"+ );+ false+ }+ }+ }++ /// Grok Bot's upgrade resume: the previous host process stopped mid-turn, so+ /// the agent is told, in the same session, to finish without redoing steps.+ pub(super) async fn resume_interrupted(&mut self, lane: Lane, done_tx: &mpsc::UnboundedSender<Done>) {+ self.set_inflight(false);+ if self.session_for(lane.thread.as_deref()).is_none() {+ self.finish_routine(+ crate::routines::Status::Interrupted,+ Some("No saved agent session is available; inspect this run before retrying".into()),+ None,+ );+ return;+ }+ let prompt = if self.active_routine.is_some() {+ format!(+ "{RESUME_PROMPT} This is still a scheduled routine run. If its instruction permits silence and there is nothing to report, return exactly (pass)."+ )+ } else {+ RESUME_PROMPT.to_owned()+ };+ if let Err(e) = self.start_turn(lane, &[], &prompt, true, done_tx).await {+ self.start_failed(&e);+ }+ }++ /// Marks a turn in the bot's own chat or a thread as running across host restarts+ /// (see [`Self::resume_interrupted`]); the thread root rides along.+ pub(super) fn set_inflight(&self, on: bool) {+ let value = match (&self.lane.thread, on) {+ (_, false) => String::new(),+ (Some(root), true) => format!("{}\t{root}", now_ms()),+ (None, true) => now_ms().to_string(),+ };+ if let Err(error) = self.hub.store.kv_set(&inflight_key(&self.cfg.id), &value) {+ tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't record the running turn");+ }+ }+}diff --cc host/src/agent/bot/session.rsindex f9d62ca5,00000000..87e4d6d0mode 100644,000000..100644--- a/host/src/agent/bot/session.rs+++ b/host/src/agent/bot/session.rs@@@ -1,352 -1,0 +1,353 @@@+//! The agent process and its ACP sessions: launch, handshake, new/load/fork, thread sessions.++use super::{Actor, Conn, NoticeStyle, SessionCaps};+use crate::agent::acp::{self, Acp, Incoming};+use crate::chat::context;+use crate::store::{BotConfig, Entry, EntryKind, Lane, lane_key};+use anyhow::{Result, anyhow, bail};+use serde_json::{Value, json};+use std::collections::HashSet;+use std::time::Duration;++impl Actor {+ /// Which session a lane's turns use: a thread of the bot's own chat has its own+ /// (by root); its chat and every group lane use the main one.+ pub(super) fn slot(&self, lane: &Lane) -> Option<String> {+ (lane.chat == self.cfg.id).then(|| lane.thread.clone()).flatten()+ }++ pub(super) fn session_for(&mut self, slot: Option<&str>) -> Option<String> {+ let Some(root) = slot else { return self.session_id.clone() };+ if let Some(sid) = self.thread_sessions.get(root) {+ return Some(sid.clone());+ }+ let sid = self.hub.store.kv_get(&lane_key("session", &self.cfg.id, &Lane::in_thread(&self.cfg.id, root)));+ let sid = sid.filter(|s| !s.is_empty())?;+ self.thread_sessions.insert(root.to_owned(), sid.clone());+ Some(sid)+ }++ pub(super) fn set_session(&mut self, slot: Option<&str>, sid: Option<&str>) {+ let Some(root) = slot else {+ self.session_id = sid.map(str::to_owned);+ if let Err(error) = self.hub.store.set_session(&self.cfg.id, sid) {+ tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't store the session");+ }+ return;+ };+ match sid {+ Some(s) => self.thread_sessions.insert(root.to_owned(), s.to_owned()),+ None => self.thread_sessions.remove(root),+ };+ let key = lane_key("session", &self.cfg.id, &Lane::in_thread(&self.cfg.id, root));+ if let Err(error) = self.hub.store.kv_set(&key, sid.unwrap_or_default()) {+ tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't store the thread session");+ }+ }++ /// Roots of the threads that have a session (stored or loaded).+ pub(super) fn thread_roots(&self) -> Vec<String> {+ let prefix = lane_key("session", &self.cfg.id, &Lane::main(&self.cfg.id)) + "/";+ let mut roots: Vec<String> = self.thread_sessions.keys().cloned().collect();+ roots.extend(+ self.hub.store.kv_prefix(&prefix).into_iter().filter_map(|k| k.strip_prefix(&prefix).map(str::to_owned)),+ );+ roots.sort();+ roots.dedup();+ roots+ }++ /// What a new thread session is told first: where the thread branches off.+ pub(super) fn thread_intro(&self, root: &str, forked: bool) -> String {+ let quote = |e: &Entry| {+ let who = if e.kind == EntryKind::User.as_str() { "the user" } else { "you" };+ format!("{who}: \"{}\"", acp::truncate(e.data["text"].as_str().unwrap_or_default(), 1500))+ };+ let Some(root_entry) = self.hub.store.entry(root) else {+ return "[Thread] The user opened a thread off your main chat. It is a separate branch of the conversation.".into();+ };+ if forked {+ return format!(+ "[Thread] The user opened a thread on this message from your main chat — {}. This thread is its own \+ branch: it starts from everything said so far, and nothing said here reaches the main chat. \+ Just continue the conversation; there's no need to mention this.",+ quote(&root_entry)+ );+ }+ // A fresh session: bring the lines leading up to the message along.+ let before = self.hub.store.history(&self.cfg.id, root_entry.seq, 12).unwrap_or_default();+ let lines: Vec<String> = before+ .iter()+ .chain(std::iter::once(&root_entry))+ .filter(|e| {+ e.kind == EntryKind::User.as_str() || (e.kind == EntryKind::Agent.as_str() && e.data["final"] == true)+ })+ .map(quote)+ .collect();+ format!(+ "[Thread] The user opened a thread on the last of these messages from your main chat (oldest first):\n{}\n\+ This thread is its own branch of the conversation; nothing said here reaches the main chat. \+ Just continue the conversation; there's no need to mention this.",+ lines.join("\n")+ )+ }++ /// ACP connectors, team collaboration, and optional computer control.+ pub(super) fn mcp_servers(&self) -> Result<Value> {+ let Ok(exe) = std::env::current_exe() else {+ tracing::warn!("can't locate codync-host for MCP servers");+ return Ok(json!([]));+ };+ let port = self.hub.port;+ let mut servers: Vec<Value> =+ (if self.cfg.connectors.is_empty() { Vec::new() } else { crate::market::connectors(&self.hub.store)? })+ .iter()+ .filter(|c| self.cfg.connectors.contains(&c.id))+ .filter_map(|c| c.acp(&exe, port))+ .collect();+ 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"),+ self.cfg.computer.then_some("computer"),+ composio.then_some("composio"),+ ];+ for name in builtin.into_iter().flatten() {+ servers.push(json!({+ "name": name, "command": exe,+ "args": ["mcp", name, "--bot", self.cfg.id, "--port", port.to_string()],+ "env": [],+ }));+ }+ Ok(Value::Array(servers))+ }++ /// Makes sure the agent runs and `slot`'s session (main, or a thread's) is live;+ /// sets `turn_session`. A thread without one forks the main session when it can.+ pub(super) async fn ensure_session(&mut self, slot: Option<&str>) -> Result<()> {+ if !self.cfg.connectors.is_empty()+ || self.hub.store.kv_read(&format!("agent-env:{}", self.cfg.backend))?.is_some()+ {+ crate::market::vault::unlock(self.hub.clone()).await?;+ }+ if self.tools_changed && self.turn.is_none() {+ self.tools_changed = false;+ if let Some(c) = self.conn.take() {+ c.acp.kill().await;+ }+ }+ if self.conn.is_none() {+ let (hub, id) = (self.hub.clone(), self.cfg.id.clone());+ let candidates = launch_commands(&self.cfg, move |msg: &str| {+ let msg = msg.to_owned();+ hub.set_runtime(&id, |r| r.activity = msg);+ })+ .await?;+ self.hub.set_runtime(&self.id(), |r| r.activity = "Starting agent…".into());+ // Keys saved from an "environment variable" sign-in.+ let env = crate::agent::auth::env(&self.hub.store, &self.cfg.backend)?;+ let mut last_err = None;+ for (i, command) in candidates.iter().enumerate() {+ let fallback_left = i + 1 < candidates.len();+ // A local CLI too old for ACP just hangs; don't make the user wait long before the fallback.+ let budget = Duration::from_secs(if fallback_left { 20 } else { 180 });+ match start_agent(command, &self.cfg.cwd, &env, budget).await {+ Ok(conn) => {+ self.conn = Some(conn);+ break;+ }+ Err(e) => {+ tracing::info!(command, error = format!("{e:#}"), "agent failed to start");+ last_err = Some(e);+ }+ }+ }+ if self.conn.is_none() {+ return Err(last_err.unwrap_or_else(|| anyhow!("agent failed to start")));+ }+ }+ let servers = self.mcp_servers()?;+ let claude = self.conn.as_ref().is_some_and(|c| c.claude);+ let mut forked = false;+ if let Some(root) = slot+ && self.session_for(slot).is_none()+ && let Some(main) = self.session_id.clone()+ && self.conn.as_ref().is_some_and(|c| c.sessions.fork)+ {+ self.hub.set_runtime(&self.cfg.id, |r| r.activity = "Opening the thread…".into());+ let conn = self.conn.as_ref().ok_or_else(|| anyhow!("agent not running"))?;+ let res = conn+ .acp+ .request("session/fork", json!({"sessionId": main, "cwd": self.cfg.cwd, "mcpServers": servers}))+ .await;+ if let Some(sid) = res.ok().and_then(|r| r["sessionId"].as_str().map(str::to_owned)) {+ self.set_session(slot, Some(&sid));+ forked = true;+ } else {+ tracing::warn!(bot = %self.cfg.id, "session/fork failed; the thread starts fresh");+ }+ if forked {+ self.thread_intro = Some(self.thread_intro(root, true));+ }+ }+ // Claude gets the frozen instructions as its system prompt. When a compaction+ // re-rendered them, loading the session again swaps the prompt in (the adapter+ // rebuilds its query and resumes the same conversation).+ let current = self.session_for(slot);+ let snapshot = match (¤t, claude) {+ (Some(sid), true) => Some(self.snapshot(sid).await?),+ _ => None,+ };+ let Some(conn) = self.conn.as_mut() else { bail!("agent not running") };+ if let Some(sid) = current {+ let prompt_current = snapshot+ .as_ref()+ .is_none_or(|s| self.applied_system.as_ref().is_some_and(|(a, t)| *a == sid && *t == s.system));+ if conn.loaded.contains(&sid) && prompt_current {+ self.turn_session = Some(sid);+ return Ok(());+ }+ if !conn.sessions.load {+ self.notice(+ "This agent can't resume sessions after a restart — starting a fresh one.",+ NoticeStyle::Divider,+ );+ self.set_session(slot, None);+ return Box::pin(self.ensure_session(slot)).await;+ }+ self.hub.set_runtime(&self.cfg.id, |r| r.activity = "Resuming session…".into());+ let mut params = json!({"sessionId": sid, "cwd": self.cfg.cwd, "mcpServers": servers});+ if let Some(s) = &snapshot {+ params["_meta"] = system_meta(&s.system);+ }+ let res = conn.acp.request("session/load", params).await;+ // The agent replays history as session/update before answering; drop it.+ while let Ok(inc) = conn.rx.try_recv() {+ if let Incoming::Request { id, .. } = inc {+ let _ = conn.acp.respond_error(id, -32601, "not supported").await;+ }+ }+ match res {+ Ok(_) => {+ conn.loaded.insert(sid.clone());+ if let Some(s) = snapshot {+ self.applied_system = Some((sid.clone(), s.system));+ }+ self.turn_session = Some(sid);+ return Ok(());+ }+ Err(e) => {+ tracing::warn!(error = format!("{e:#}"), "session/load failed; starting fresh");+ self.thread_intro = None;+ self.notice("Couldn't resume the previous session — starting a fresh one.", NoticeStyle::Divider);+ }+ }+ }+ let system = {+ let (hub, cfg) = (self.hub.clone(), self.cfg.clone());+ tokio::task::spawn_blocking(move || context::render(&hub.store, &cfg)).await?+ };+ let Some(conn) = self.conn.as_mut() else { bail!("agent not running") };+ let mut params = json!({"cwd": self.cfg.cwd, "mcpServers": servers});+ if claude {+ params["_meta"] = system_meta(&system);+ }+ let res = conn.acp.request("session/new", params).await?;+ let sid = res["sessionId"].as_str().ok_or_else(|| anyhow!("agent returned no sessionId"))?.to_owned();+ conn.loaded.insert(sid.clone());+ select_model(&conn.acp, &res, &sid, &self.cfg).await?;+ self.set_session(slot, Some(&sid));+ self.session_fresh = true;+ self.turn_session = Some(sid.clone());+ if let Some(root) = slot {+ self.thread_intro = Some(self.thread_intro(root, false));+ }+ context::adopt(&self.hub.store, &self.cfg, &sid, system.clone())?;+ if claude {+ self.applied_system = Some((sid, system));+ }+ Ok(())+ }++ /// Drops the main ACP session so the next turn starts a fresh one.+ pub(super) fn forget_session(&mut self) {+ self.set_session(None, None);+ }+}++/// Claude's `_meta`: the bot's instructions appended to Claude Code's own system prompt.+fn system_meta(system: &str) -> Value {+ json!({"systemPrompt": {"append": system}})+}++/// Shell commands that may start the bot's agent over ACP, best first.+/// `progress` receives short status lines ("Downloading Cursor…").+pub(crate) async fn launch_commands(cfg: &BotConfig, progress: impl Fn(&str)) -> Result<Vec<String>> {+ Ok(match cfg.command.as_deref().map(str::trim) {+ Some(c) if !c.is_empty() => vec![c.to_owned()],+ _ => crate::agent::backends::launch_candidates(&cfg.backend, progress)+ .await?+ .iter()+ .map(crate::agent::registry::Cmd::acp)+ .collect(),+ })+}++/// Switches a new session (`session/new` answered `res`) to the bot's chosen model.+pub(crate) async fn select_model(acp: &Acp, res: &Value, sid: &str, cfg: &BotConfig) -> Result<()> {+ let Some(model) = cfg.model.as_deref().filter(|m| !m.is_empty()) else { return Ok(()) };+ let r = match crate::agent::auth::model_config(res).and_then(|c| c["id"].as_str()) {+ Some(config_id) => {+ acp.request("session/set_config_option", json!({"sessionId": sid, "configId": config_id, "value": model}))+ .await+ }+ None => acp.request("session/set_model", json!({"sessionId": sid, "modelId": model})).await,+ };+ if let Err(e) = r {+ tracing::warn!(model, error = format!("{e:#}"), "couldn't set model");+ bail!("Couldn't select model {model}: {e:#}");+ }+ Ok(())+}++/// Spawns an ACP agent and completes the `initialize` handshake.+pub(crate) async fn start_agent(command: &str, cwd: &str, env: &[(String, String)], budget: Duration) -> Result<Conn> {+ let (acp, rx) = Acp::spawn(command, cwd, env)?;+ let init = tokio::time::timeout(+ budget,+ acp.request(+ "initialize",+ json!({+ "protocolVersion": 1,+ // `session.compaction`: tell us when the agent summarizes its context.+ "clientCapabilities": {+ "fs": {"readTextFile": false, "writeTextFile": false},+ "terminal": false,+ "session": {"compaction": {}},+ },+ "clientInfo": {"name": "codync", "title": "Codync", "version": env!("CARGO_PKG_VERSION")},+ }),+ ),+ )+ .await;+ let init = match init {+ Ok(Ok(v)) => v,+ Ok(Err(e)) => {+ acp.kill().await;+ return Err(e);+ }+ Err(_) => {+ acp.kill().await;+ return Err(anyhow!("the agent didn't answer the ACP handshake within {}s", budget.as_secs()));+ }+ };+ let sessions = SessionCaps {+ load: init["agentCapabilities"]["loadSession"].as_bool().unwrap_or(false),+ fork: init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object(),+ };+ let claude = init["agentCapabilities"]["_meta"]["claudeCode"].is_object();+ Ok(Conn { acp, rx, sessions, claude, loaded: HashSet::new() })+}diff --cc host/src/agent/bot/turn.rsindex 67c58331,00000000..cbe4d4femode 100644,000000..100644--- a/host/src/agent/bot/turn.rs+++ b/host/src/agent/bot/turn.rs@@@ -1,292 -1,0 +1,299 @@@+//! Starting a turn and wrapping it up: final reply, notices, replies to waiters, alerts and memory.++use super::{Actor, Done, NoticeStyle, Queued, Seg};+use crate::agent::acp::{self, Incoming};+use crate::chat::context::{self, Snapshot};+use crate::chat::memory;+use crate::hub::BotStatus;+use crate::remote::push::{self, AlertKind};+use crate::store::{Lane, now_ms};+use anyhow::{Context, Result, anyhow};+use serde_json::json;+use std::time::Duration;+use tokio::sync::mpsc;++impl Actor {+ /// This session's frozen instructions (reads memory files when re-rendering).+ pub(super) async fn snapshot(&self, session: &str) -> Result<Snapshot> {+ let (hub, cfg, session) = (self.hub.clone(), self.cfg.clone(), session.to_owned());+ tokio::task::spawn_blocking(move || context::resolve(&hub.store, &cfg, &session)).await?+ }++ /// Starts a turn in `lane` for the given user entries (none for a hidden turn).+ pub(super) async fn start_turn(+ &mut self,+ lane: Lane,+ entry_ids: &[String],+ text: &str,+ hidden: bool,+ done_tx: &mpsc::UnboundedSender<Done>,+ ) -> Result<()> {+ let turn = entry_ids.last().and_then(|id| self.hub.store.entry(id)).map_or_else(+ || {+ self.hub.store.max_turn(&lane.chat)+ + i64::from(self.active_group.is_some() || self.active_routine.is_some())+ },+ |e| e.turn,+ );+ for id in entry_ids {+ if let Some(mut e) = self.hub.store.entry(id) {+ e.data["status"] = "sent".into();+ self.hub.set_entry(id, &e.data);+ }+ }+ self.lane = lane.clone();+ self.turn = Some(turn);+ self.turn_text = (!hidden).then(|| text.to_owned());+ self.announce = None;+ self.stop_requested = false;+ self.hub.team.start_turn(&self.cfg.id);+ self.exit_tail = None;+ self.seg = Seg::None;+ 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());+ self.hub.set_runtime(&self.id(), |r| {+ r.status = BotStatus::Working;+ r.activity = if hidden { "Picking up where it left off…" } else { "Starting…" }.into();+ r.started_at = Some(now_ms());+ r.lane = Some(lane.clone());+ });++ let slot = self.slot(&lane);+ if let Some(deadline) = self.routine_deadline {+ tokio::time::timeout_at(tokio::time::Instant::from_std(deadline), self.ensure_session(slot.as_deref()))+ .await+ .context("routine session setup timed out")??;+ } else {+ self.ensure_session(slot.as_deref()).await?;+ }+ if hidden && self.session_fresh {+ // A new session must never silently repeat an interrupted routine.+ self.finish_routine(+ crate::routines::Status::Interrupted,+ Some("The agent could not reload this run's saved session; inspect before retrying".into()),+ None,+ );+ self.turn = None;+ if self.routine_completion.is_none() {+ self.set_inflight(false);+ }+ self.hub.team.cancel_from(&self.cfg.id);+ self.hub.set_runtime(&self.id(), |r| {+ r.status = BotStatus::Idle;+ r.activity = String::new();+ r.started_at = None;+ r.lane = None;+ });+ return Ok(());+ }+ // Session-start chatter (banners, command lists) isn't part of the reply.+ // Some adapters (pi-acp) send it on a timer right after session/new.+ if self.session_fresh {+ tokio::time::sleep(Duration::from_millis(400)).await;+ }+ 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;+ }+ }+ }+ let claude = self.conn.as_ref().is_some_and(|c| c.claude);+ let sid = self.turn_session.clone().ok_or_else(|| anyhow!("no session"))?;+ let snapshot = self.snapshot(&sid).await?;+ let mut prompt = text.to_owned();+ if let Some(intro) = self.thread_intro.take() {+ prompt = format!("{intro}\n\n{prompt}");+ }+ if self.session_fresh {+ self.session_fresh = false;+ // Claude already has the instructions as its system prompt.+ if !claude {+ prompt = format!("<bot-profile>\n{}\n</bot-profile>\n\n{prompt}", snapshot.system);+ }+ }+ if let Some((update, identity)) = context::profile_update(&self.hub.store, &snapshot, &self.cfg) {+ prompt = format!("{prompt}\n\n{update}");+ self.announce = Some((snapshot, identity));+ }+ self.hub.set_runtime(&self.id(), |r| r.activity = "Thinking…".into());+ let acp = self.conn.as_ref().ok_or_else(|| anyhow!("agent not running"))?.acp.clone();+ let params = json!({+ "sessionId": sid,+ "prompt": [{"type": "text", "text": prompt}],+ });+ if let Some(id) = &self.active_routine {+ self.hub.routines.mark_started(&self.hub.store, id)?;+ self.set_inflight(true);+ }+ // Written before this returns, so a Stop right after is sent after the prompt.+ let answer = acp.send("session/prompt", params).await?;+ let done_tx = done_tx.clone();+ tokio::spawn(async move {+ let _ = done_tx.send(answer.response().await);+ });+ Ok(())+ }++ pub(super) fn finish_turn(&mut self, done: &Done) {+ if self.turn.is_none() {+ return;+ }+ self.flush(true);+ self.seg = Seg::None;+ // Unanswered permission cards can't be answered after the turn.+ let ids: Vec<String> = self.perms.drain().map(|(k, _)| k).collect();+ for id in ids {+ if let Some(mut e) = self.hub.store.entry(&id) {+ e.data["status"] = "expired".into();+ self.hub.set_entry(&id, &e.data);+ }+ }+ let stopped = self.stop_requested || matches!(&done, Ok(v) if v["stopReason"] == "cancelled");+ // Tool calls the agent never closed out would spin forever in the trace.+ for entry_id in self.tools.values() {+ if let Some(mut e) = self.hub.store.entry(entry_id)+ && matches!(e.data["status"].as_str(), Some("pending" | "in_progress"))+ {+ e.data["status"] = if stopped || done.is_err() { "failed" } else { "completed" }.into();+ self.hub.set_entry(entry_id, &e.data);+ }+ }+ 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)+ {+ let text = e.data["text"].as_str().map(str::to_owned);+ // A pass in a room stays in the trace; the room doesn't see it.+ if !(grouped && text.as_deref().is_none_or(crate::chat::group::is_pass)) {+ e.data["final"] = true.into();+ self.hub.set_entry(&id, &e.data);+ final_text = text;+ }+ }+ let stop_reason = match &done {+ Ok(v) => v["stopReason"].as_str().unwrap_or("end_turn").to_owned(),+ Err(_) => "error".into(),+ };+ match (&done, stop_reason.as_str()) {+ (Err(e), _) if !self.stop_requested => {+ let tail = self.exit_tail.take().filter(|t| !t.is_empty());+ let detail = tail.map(|t| format!("\n\n{}", acp::truncate(&t, 1200))).unwrap_or_default();+ self.notice(&format!("The agent failed: {e}{detail}"), NoticeStyle::Error);+ }+ (_, "cancelled") | (Err(_), _) => self.notice("Stopped.", NoticeStyle::Info),+ (_, "max_tokens") => self.notice("The agent hit its output limit.", NoticeStyle::Info),+ (_, "max_turn_requests") => self.notice("The agent hit its step limit for this turn.", NoticeStyle::Info),+ (_, "refusal") => self.notice("The agent declined to continue.", NoticeStyle::Info),+ _ => {}+ }+ let failed = done.is_err() && !self.stop_requested;+ let delegated = self.active_ask.is_some();+ let reply = if stopped {+ Err(anyhow!("recipient was stopped; partial work may have happened"))+ } else if stop_reason != "end_turn" {+ Err(anyhow!("recipient did not finish ({stop_reason}); partial work may have happened"))+ } else {+ final_text+ .clone()+ .filter(|s| !s.trim().is_empty())+ .ok_or_else(|| anyhow!("recipient finished without a text reply"))+ };+ if routine {+ let (status, detail) = if self.routine_timed_out {+ (+ crate::routines::Status::Failed,+ Some("Routine exceeded its execution time limit; its agent process was stopped".into()),+ )+ } else if stopped {+ (crate::routines::Status::Cancelled, Some("Stopped by user".into()))+ } else if failed || stop_reason != "end_turn" {+ (+ crate::routines::Status::Failed,+ Some(format!("Routine did not finish ({stop_reason}); inspect the run conversation")),+ )+ } else {+ (crate::routines::Status::Succeeded, None)+ };+ let text = (status == crate::routines::Status::Succeeded).then(|| final_text.clone()).flatten();+ self.finish_routine(status, detail, text);+ }+ self.complete_ask(reply);+ self.complete_group(if stopped || failed || stop_reason != "end_turn" {+ Err(anyhow!("turn did not complete ({stop_reason})"))+ } else {+ Ok(final_text.clone())+ });+ self.turn = None;+ if self.routine_completion.is_none() {+ self.set_inflight(false);+ }+ // The message reached the agent: the profile update it carried is now known to it.+ if let (Ok(_), Some((snapshot, identity))) = (&done, self.announce.take())+ && let Err(error) = context::mark_announced(&self.hub.store, &self.cfg.id, &snapshot, identity)+ {+ tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't record the profile update");+ }+ if let (Some(user), Some(agent), "end_turn") = (self.turn_text.take(), &final_text, stop_reason.as_str())+ && memory::is_memorable(&user)+ {+ let _ = self.keeper.send(memory::Exchange { user, agent: agent.clone(), at: now_ms() });+ }+ self.hub.set_runtime(&self.id(), |r| {+ r.status = if failed { BotStatus::Error } else { BotStatus::Idle };+ r.activity = String::new();+ r.started_at = None;+ r.lane = None;+ });+ self.hub.team.cancel_from(&self.cfg.id);+ // A room turn's news comes from the group once the room is done (see `group`).+ let more = self.queue.iter().any(|q| matches!(q, Queued::User { .. }));+ if !self.stop_requested+ && !delegated+ && !grouped+ && let Some(kind) = turn_alert(failed, &stop_reason, more)+ {+ let body = final_text.unwrap_or_else(|| match kind {+ AlertKind::Done => "Finished.".into(),+ _ => "The agent didn't finish.".into(),+ });+ push::notify(&self.hub, &self.cfg, None, &self.cfg.name, &body, kind);+ }+ }+}++/// A finished turn alerts once the user's work is done: not while their next message+/// is already queued. A turn that ended short of `end_turn` always reports the failure.+fn turn_alert(failed: bool, stop_reason: &str, more: bool) -> Option<AlertKind> {+ if failed || !matches!(stop_reason, "end_turn" | "cancelled") {+ return Some(AlertKind::Failed);+ }+ (stop_reason == "end_turn" && !more).then_some(AlertKind::Done)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn only_finished_tasks_alert() {+ assert_eq!(turn_alert(false, "end_turn", false), Some(AlertKind::Done));+ assert_eq!(turn_alert(false, "end_turn", true), None, "next message queued");+ assert_eq!(turn_alert(false, "cancelled", false), None);+ assert_eq!(turn_alert(false, "max_turn_requests", false), Some(AlertKind::Failed));+ assert_eq!(turn_alert(true, "error", true), Some(AlertKind::Failed));+ }+}diff --cc host/src/agent/bot/updates.rsindex fa421819,00000000..43de3d81mode 100644,000000..100644--- a/host/src/agent/bot/updates.rs+++ b/host/src/agent/bot/updates.rs@@@ -1,352 -1,0 +1,367 @@@+//! Agent → client: `session/update`s, permission requests and streamed text mapped onto entries.++use super::{Actor, NoticeStyle, Seg, SegKind};+use crate::agent::acp::{self, Incoming};+use crate::chat::context;+use crate::hub::BotStatus;+use crate::remote::push::{self, AlertKind};+use crate::store::{EntryKind, Permission};+use serde_json::{Value, json};+use std::time::{Duration, Instant};++impl Actor {+ pub(super) async fn on_incoming(&mut self, inc: Option<Incoming>) {+ match inc {+ None | Some(Incoming::Closed { .. }) => {+ let tail = match inc {+ Some(Incoming::Closed { stderr_tail }) => stderr_tail,+ _ => String::new(),+ };+ self.conn = None;+ // The in-flight prompt request resolves with an error; finish_turn reports it with this output.+ self.exit_tail = Some(tail);+ }+ Some(Incoming::Notification { method, params }) => {+ if method == "session/update"+ && params["sessionId"].as_str() == self.turn_session.as_deref()+ && self.turn.is_some()+ {+ self.on_update(¶ms["update"]);+ }+ }+ 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;+ }+ }+ }+ }++ pub(super) fn on_update(&mut self, u: &Value) {+ let turn = self.turn.unwrap_or(0);+ match u["sessionUpdate"].as_str().unwrap_or_default() {+ "agent_message_chunk" => {+ let t = acp::content_text(&u["content"]);+ self.append(SegKind::Text, &t);+ self.set_activity("Writing a reply…");+ }+ "agent_thought_chunk" => {+ let t = acp::content_text(&u["content"]);+ self.append(SegKind::Thought, &t);+ self.set_activity("Thinking…");+ }+ "tool_call" => {+ self.close_seg();+ let tool_id = u["toolCallId"].as_str().unwrap_or_default().to_owned();+ let mut data = json!({+ "toolCallId": tool_id,+ "title": u["title"].as_str().unwrap_or("Tool"),+ "toolKind": u["kind"].as_str().unwrap_or("other"),+ "status": u["status"].as_str().unwrap_or("pending"),+ "output": "",+ "diffs": [],+ "locations": u["locations"].clone(),+ });+ merge_tool_content(&mut data, &u["content"]);+ let title = data["title"].as_str().unwrap_or("Tool").to_owned();+ if let Some(e) = self.add(EntryKind::Tool, turn, data) {+ self.tools.insert(tool_id, e.id);+ }- self.set_activity(&title);++ self.set_activity(super::activity(&title));+ }+ "tool_call_update" => {+ let tool_id = u["toolCallId"].as_str().unwrap_or_default();+ let Some(entry_id) = self.tools.get(tool_id).cloned() else { return };+ let Some(mut e) = self.hub.store.entry(&entry_id) else { return };+ for (k, key) in [("title", "title"), ("kind", "toolKind"), ("status", "status")] {+ if let Some(v) = u[k].as_str() {+ e.data[key] = v.into();+ }+ }+ if !u["locations"].is_null() {+ e.data["locations"] = u["locations"].clone();+ }+ merge_tool_content(&mut e.data, &u["content"]);+ let status = e.data["status"].as_str().unwrap_or_default().to_owned();+ 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(super::activity(&title));+ }+ }+ // The agent summarized its context: the next turn gets freshly rendered+ // instructions and memory (see `context`).+ "compaction_update" if u["status"] == "completed" => {+ let Some(sid) = &self.turn_session else { return };+ let id = u["compactionId"].as_str().unwrap_or_default();+ match context::bump_epoch(&self.hub.store, &self.cfg.id, sid, id) {+ Ok(true) => self.notice("Earlier context was summarized to make room.", NoticeStyle::Info),+ Ok(false) => {}+ Err(error) => {+ tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't record the compaction");+ }+ }+ }+ "usage_update" => {+ let info = &u["_meta"]["_claude/rateLimit"];+ if info.is_object() {+ crate::usage::ingest_claude_rate_limit(&self.hub, info);+ }+ }+ "plan" => {+ let data = json!({"entries": u["entries"].clone(), "author": self.cfg.id});+ match &self.plan_entry {+ Some(id) => {+ self.hub.set_entry(id, &data);+ }+ None => {+ if let Some(e) = self.add(EntryKind::Plan, turn, data) {+ self.plan_entry = Some(e.id);+ }+ }+ }+ }+ _ => {}+ }+ }++ 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;+ }+ }+ let title = tool["title"]+ .as_str()+ .filter(|t| !t.is_empty())+ .map(str::to_owned)+ .or_else(|| {+ let eid = self.tools.get(tool["toolCallId"].as_str()?)?;+ self.hub.store.entry(eid)?.data["title"].as_str().map(str::to_owned)+ })+ .unwrap_or_else(|| "Use a tool".into());+ let mut detail = json!({"output": "", "diffs": []});+ merge_tool_content(&mut detail, &tool["content"]);+ let raw = &tool["rawInput"];+ let command = raw["command"].as_str().map(str::to_owned).or_else(|| {+ raw["command"].as_array().map(|a| a.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(" "))+ });+ let data = json!({+ "title": title,+ "toolKind": tool["kind"].as_str().unwrap_or("other"),+ "command": command,+ "detail": detail["output"],+ "diffs": detail["diffs"],+ "cwd": self.cfg.cwd,+ "options": options.iter().map(|o| json!({"optionId": o["optionId"], "name": o["name"], "kind": o["kind"]})).collect::<Vec<_>>(),+ "status": "pending",+ "selected": Value::Null,+ });+ let turn = self.turn.unwrap_or(0);+ self.close_seg();+ if let Some(e) = self.add(EntryKind::Permission, turn, data) {+ self.perms.insert(e.id, rpc_id);+ }+ self.hub.set_runtime(&self.cfg.id, |r| {+ r.status = BotStatus::NeedsInput;+ r.activity = format!("Needs approval: {title}");+ });+ // Tapping it opens where the card is: the group, for a room turn.+ let target = self.hub.store.bot(&self.lane.chat).ok().flatten().map_or_else(|| self.cfg.clone(), |r| r.config);+ push::notify(+ &self.hub,+ &target,+ Some(&self.cfg.id),+ &format!("{} needs you", self.cfg.name),+ &title,+ AlertKind::NeedsInput,+ );+ }++ pub(super) async fn answer_permission(&mut self, entry_id: &str, option_id: Option<String>) {+ let Some(rpc_id) = self.perms.remove(entry_id) else { return };+ let outcome = match &option_id {+ Some(o) => json!({"outcome": {"outcome": "selected", "optionId": o}}),+ None => json!({"outcome": {"outcome": "cancelled"}}),+ };+ if let Some(conn) = &self.conn {+ let _ = conn.acp.respond(rpc_id, outcome).await;+ }+ if let Some(mut e) = self.hub.store.entry(entry_id) {+ e.data["status"] = if option_id.is_some() { "answered" } else { "cancelled" }.into();+ e.data["selected"] = option_id.into();+ self.hub.set_entry(entry_id, &e.data);+ }+ if self.perms.is_empty() && self.turn.is_some() {+ self.hub.set_runtime(&self.cfg.id, |r| {+ r.status = BotStatus::Working;+ r.activity = "Continuing…".into();+ });+ }+ }+++ /// 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.++ 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() {++ anyhow::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::anyhow!("couldn't save the message"))?;++ self.sent.push(text);++ self.set_activity("Working…");++ Ok(())++ }+++ // MARK: streaming text segments++ pub(super) fn append(&mut self, kind: SegKind, text: &str) {+ if text.is_empty() {+ return;+ }+ let same = matches!(&self.seg, Seg::Open { kind: k, .. } if *k == kind);+ if !same {+ self.close_seg();+ let (k, data) = match kind {+ SegKind::Text => (EntryKind::Agent, json!({"text": text, "final": false})),+ SegKind::Thought => (EntryKind::Thought, json!({"text": text})),+ };+ if let Some(e) = self.add(k, self.turn.unwrap_or(0), data) {+ if kind == SegKind::Text {+ self.last_text = Some(e.id.clone());+ }+ self.seg =+ Seg::Open { kind, entry_id: e.id, buf: text.to_owned(), flushed: Instant::now(), dirty: false };+ }+ return;+ }+ if let Seg::Open { buf, dirty, .. } = &mut self.seg {+ buf.push_str(text);+ *dirty = true;+ }+ }++ /// Persists streamed text at most every 300 ms (or immediately with `force`).+ pub(super) fn flush(&mut self, force: bool) {+ if let Seg::Open { kind, entry_id, buf, flushed, dirty } = &mut self.seg+ && *dirty+ && (force || flushed.elapsed() >= Duration::from_millis(300))+ {+ let data = match kind {+ SegKind::Text => json!({"text": buf, "final": false, "author": self.cfg.id}),+ SegKind::Thought => json!({"text": buf, "author": self.cfg.id}),+ };+ self.hub.set_entry(entry_id, &data);+ *flushed = Instant::now();+ *dirty = false;+ }+ }++ pub(super) fn close_seg(&mut self) {+ self.flush(true);+ self.seg = Seg::None;+ }+}++/// Folds ACP tool-call `content` into `{output, diffs}` on an entry's data.+pub fn merge_tool_content(data: &mut Value, content: &Value) {+ let Some(items) = content.as_array() else { return };+ let mut out = String::new();+ let mut diffs = vec![];+ for item in items {+ match item["type"].as_str() {+ Some("diff") => {+ let path = item["path"].as_str().unwrap_or_default();+ let old = item["oldText"].as_str().unwrap_or_default();+ let new = item["newText"].as_str().unwrap_or_default();+ diffs.push(diff_summary(path, old, new));+ }+ Some("terminal") => {}+ _ => {+ let t = acp::content_text(item);+ if !t.is_empty() {+ if !out.is_empty() {+ out.push('\n');+ }+ out.push_str(&t);+ }+ }+ }+ }+ if !out.is_empty() {+ data["output"] = acp::truncate(&out, 6000).into();+ }+ if !diffs.is_empty() {+ data["diffs"] = diffs.into();+ }+}++/// Changed-region summary: trims the common prefix/suffix and reports the middle.+pub fn diff_summary(path: &str, old: &str, new: &str) -> Value {+ let a: Vec<&str> = old.lines().collect();+ let b: Vec<&str> = new.lines().collect();+ let prefix = a.iter().zip(&b).take_while(|(x, y)| x == y).count();+ let suffix = a[prefix..].iter().rev().zip(b[prefix..].iter().rev()).take_while(|(x, y)| x == y).count();+ let removed = &a[prefix..a.len() - suffix];+ let added = &b[prefix..b.len() - suffix];+ let mut unified = String::new();+ for (sign, lines) in [('-', removed), ('+', added)] {+ for l in lines {+ unified.push(sign);+ unified.push_str(l);+ unified.push('\n');+ }+ }+ json!({+ "path": path,+ "added": added.len(),+ "removed": removed.len(),+ "isNew": old.is_empty(),+ "startLine": prefix + 1,+ "patch": acp::truncate(&unified, 6000),+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn diff_counts_changed_middle() {+ let d = diff_summary("f", "a\nb\nc\n", "a\nB\nB2\nc\n");+ assert_eq!(d["added"], 2);+ assert_eq!(d["removed"], 1);+ assert_eq!(d["startLine"], 2);+ assert_eq!(d["patch"], "-b\n+B\n+B2\n");+ }++ #[test]+ fn tool_content_merges_text_and_diffs() {+ let mut data = json!({"output": "", "diffs": []});+ merge_tool_content(+ &mut data,+ &json!([+ {"type": "content", "content": {"type": "text", "text": "ok"}},+ {"type": "diff", "path": "/a.rs", "oldText": "", "newText": "x\n"}+ ]),+ );+ assert_eq!(data["output"], "ok");+ assert_eq!(data["diffs"][0]["isNew"], true);+ }+}diff --cc host/src/api/bots.rsindex 000363f7,00000000..147acf0amode 100644,000000..100644--- a/host/src/api/bots.rs+++ b/host/src/api/bots.rs@@@ -1,240 -1,0 +1,243 @@@+//! Bot and chat methods: roster, messages, uploads, memory, routines and the bots' own MCP calls.++use super::marketplace::connector_ids;+use super::str_arg;+use crate::agent::bot::Cmd;+use crate::hub::Hub;+use crate::market;+use crate::store::{BotConfig, EntryKind, Lane, ReadScope};+use anyhow::{Context, Result, anyhow, bail};+use serde_json::{Value, json};+use std::ops::ControlFlow;+use std::sync::Arc;++pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<ControlFlow<Value, Value>> {+ Ok(ControlFlow::Break(match method {+ "routineSchedule" => crate::routines::schedule_preview(&b, crate::store::now_ms())?,+ "routines" => hub.routines.list(str_arg(&b, "botId")?),+ "saveRoutine" => hub.routines.save(hub, str_arg(&b, "botId")?, &b)?,+ "setRoutineEnabled" => hub.routines.set_enabled(+ &hub.store,+ str_arg(&b, "botId")?,+ str_arg(&b, "id")?,+ b["enabled"].as_bool().context("enabled is required")?,+ )?,+ "deleteRoutine" => hub.routines.remove(&hub.store, str_arg(&b, "botId")?, str_arg(&b, "id")?)?,+ "runRoutine" => hub.routines.enqueue(+ &hub.store,+ str_arg(&b, "botId")?,+ str_arg(&b, "id")?,+ json!({"source":"test"}),+ None,+ true,+ )?,+ "routineWebhook" => hub.routines.credentials(+ hub,+ str_arg(&b, "botId")?,+ str_arg(&b, "id")?,+ b["rotate"].as_bool().unwrap_or(false),+ )?,+ "routineCall" => crate::routines::call(hub, str_arg(&b, "botId")?, str_arg(&b, "name")?, &b["arguments"])?,+ "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?+ }+ "history" => {+ let bot = str_arg(&b, "botId")?;+ let before = b["beforeSeq"].as_i64().unwrap_or(i64::MAX);+ let limit = b["limit"].as_i64().unwrap_or(100).clamp(1, 500);+ json!({"entries": hub.store.history(bot, before, limit)?})+ }+ // A thread's replies (its newest 500); the root is in the main chat.+ "thread" => json!({"entries": hub.store.thread(str_arg(&b, "botId")?, str_arg(&b, "rootId")?, 500)?}),+ "createBot" => {+ let mut b = b;+ b["id"] = "".into();+ // Connectors are on for a new bot unless the client picked them.+ // Without a credential store (headless Linux) no connector can run, so the bot starts with none.+ if b["connectors"].is_null() && b["kind"] != "group" {+ b["connectors"] = match market::vault::unlock(hub.clone()).await {+ Ok(()) => json!(connector_ids(&hub.store)?),+ Err(e) => {+ tracing::warn!(+ error = format!("{e:#}"),+ "credential store unavailable; new bot starts without connectors"+ );+ json!([])+ }+ };+ }+ let cfg: BotConfig = serde_json::from_value(b).context("invalid bot")?;+ let hub = hub.clone();+ json!({"bot": tokio::task::spawn_blocking(move || hub.create_bot(cfg)).await??})+ }+ "updateBot" => {+ let hub = hub.clone();+ json!({"bot": tokio::task::spawn_blocking(move || hub.update_bot(&b)).await??})+ }+ "deleteBot" => {+ hub.delete_bot(str_arg(&b, "botId")?)?;+ json!({})+ }+ // The main chat, one thread (`threadId`), or everything (`all`, the roster's "Mark as read").+ "markRead" => {+ let scope = match b["threadId"].as_str().filter(|t| !t.is_empty()) {+ Some(root) => ReadScope::Thread(root),+ None if b["all"] == true => ReadScope::All,+ None => ReadScope::Chat,+ };+ hub.mark_read(str_arg(&b, "botId")?, scope)?;+ json!({})+ }+ // One chunk of a file for a later `send` (`attachments`); base64 `data` at `offset`.+ "upload" => {+ use base64::Engine as _;+ let row = hub.store.bot(str_arg(&b, "botId")?)?.filter(|r| !r.deleted && !r.config.is_group());+ let root = crate::chat::uploads::root(&row.ok_or_else(|| anyhow!("unknown bot"))?.config);+ let (id, name) = (str_arg(&b, "uploadId")?.to_owned(), str_arg(&b, "name")?.to_owned());+ let data =+ base64::engine::general_purpose::STANDARD.decode(str_arg(&b, "data")?).context("invalid data")?;+ let (offset, done) = (b["offset"].as_u64().unwrap_or(0), b["done"] == true);+ let attachment = tokio::task::spawn_blocking(move || {+ crate::chat::uploads::append(&root, &id, &name, offset, &data, done)+ })+ .await??;+ json!({"attachment": attachment})+ }+ // A sent file, back in chunks (chat previews on other devices).+ "readUpload" => {+ use base64::Engine as _;+ let row = hub.store.bot(str_arg(&b, "botId")?)?.filter(|r| !r.deleted && !r.config.is_group());+ let root = crate::chat::uploads::root(&row.ok_or_else(|| anyhow!("unknown bot"))?.config);+ let id = str_arg(&b, "uploadId")?.to_owned();+ let offset = b["offset"].as_u64().unwrap_or(0);+ let (data, size) =+ tokio::task::spawn_blocking(move || crate::chat::uploads::read(&root, &id, offset, 384 * 1024))+ .await??;+ json!({"data": base64::engine::general_purpose::STANDARD.encode(data), "size": size})+ }+ "send" => {+ let bot = str_arg(&b, "botId")?;+ let text = b["text"].as_str().unwrap_or_default().trim();+ let uploads: Vec<&str> =+ b["attachments"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();+ if text.is_empty() && uploads.is_empty() {+ bail!("empty message");+ }+ let nonce = b["clientNonce"].as_str().unwrap_or_default();+ if !nonce.is_empty()+ && let Some(e) = hub.store.find_by_nonce(bot, nonce)+ {+ return Ok(ControlFlow::Break(json!({"entry": e})));+ }+ let row = hub.store.bot(bot)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("unknown bot"))?;+ // `threadId`: reply in the thread on that message of the main chat (threads are flat).+ let thread = match b["threadId"].as_str().filter(|t| !t.is_empty()) {+ Some(root) => {+ let r = hub.store.entry(root).ok_or_else(|| anyhow!("unknown message"))?;+ if r.bot_id != bot || r.thread_id.is_some() {+ bail!("threads start from a message in the main chat");+ }+ Some(root.to_owned())+ }+ None => None,+ };+ let lane = Lane { chat: bot.to_owned(), thread };+ let (mut paths, mut attachments) = (Vec::new(), Vec::new());+ if !uploads.is_empty() {+ if row.config.is_group() {+ bail!("files can't be sent to a group");+ }+ let root = crate::chat::uploads::root(&row.config);+ for id in uploads {+ let (path, meta) = crate::chat::uploads::resolve(&root, id)?;+ paths.push(path);+ attachments.push(meta);+ }+ }+ let prompt = if paths.is_empty() {+ text.to_owned()+ } else {+ format!("{text}{}", crate::chat::uploads::prompt_suffix(&paths))+ };+ let turn = hub.store.max_turn(bot) + 1;+ // A group has no agent of its own to queue behind: its message is simply sent.+ let status = if row.config.is_group() { "sent" } else { "queued" };+ let e = hub+ .add_entry(+ &lane,+ EntryKind::User,+ turn,+ &json!({"text": text, "clientNonce": nonce, "status": status, "attachments": attachments}),+ )+ .ok_or_else(|| anyhow!("couldn't save the message"))?;+ // Before the turn starts, so its reply lands unread.+ let scope = lane.thread.as_deref().map_or(ReadScope::Chat, ReadScope::Thread);+ if let Err(error) = hub.mark_read(bot, scope) {+ tracing::warn!(%error, bot, "couldn't mark bot read after send");+ }+ if row.config.is_group() {+ crate::chat::group::start(hub, &row.config, lane);+ } else {+ hub.send_cmd(bot, Cmd::Send { lane, entry_id: e.id.clone(), text: prompt })?;+ }+ json!({"entry": e})+ }+ // A finished voice call, as a line in the chat ("Voice chat · 0:16").+ "logCall" => {+ let bot = str_arg(&b, "botId")?;+ hub.store.bot(bot)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("unknown bot"))?;+ let seconds = b["seconds"].as_u64().unwrap_or(0);+ let data = json!({"text": "Voice chat", "callSeconds": seconds});+ let e = hub.add_entry(&Lane::main(bot), EntryKind::Notice, hub.store.max_turn(bot), &data);+ json!({"entry": e})+ }+ "stop" => {+ let bot = str_arg(&b, "botId")?;+ match hub.store.bot(bot)? {+ Some(row) if row.config.is_group() => hub.groups.stop(hub, bot),+ _ => hub.send_cmd(bot, Cmd::Stop)?,+ }+ json!({})+ }+ "newSession" => {+ hub.send_cmd(str_arg(&b, "botId")?, Cmd::NewSession)?;+ json!({})+ }+ "memory" => {+ let bot = str_arg(&b, "botId")?.to_owned();+ tokio::task::spawn_blocking(move || crate::chat::memory::describe(&bot)).await??+ }+ "forgetMemory" => {+ let bot = str_arg(&b, "botId")?.to_owned();+ let id = str_arg(&b, "id")?.to_owned();+ let removed =+ tokio::task::spawn_blocking(move || crate::chat::memory::Memory::for_bot(&bot)?.remove(&id)).await??;+ json!({"removed": removed})+ }+ "clearMemory" => {+ let bot = str_arg(&b, "botId")?.to_owned();+ tokio::task::spawn_blocking(move || crate::chat::memory::Memory::for_bot(&bot)?.clear()).await??;+ json!({})+ }+ "react" => {+ let e = hub.react(str_arg(&b, "entryId")?, str_arg(&b, "emoji")?)?;+ json!({"entry": e})+ }+ "respondPermission" => {+ let entry_id = str_arg(&b, "entryId")?;+ let e = hub.store.entry(entry_id).ok_or_else(|| anyhow!("unknown card"))?;+ let option_id = b["optionId"].as_str().map(str::to_owned);+ // A card in a group belongs to the bot that asked.+ let bot = e.data["author"].as_str().unwrap_or(&e.bot_id);+ hub.send_cmd(bot, Cmd::Permission { entry_id: entry_id.to_owned(), option_id })?;+ json!({})+ }+ _ => return Ok(ControlFlow::Continue(b)),+ }))+}diff --cc host/src/api/devices.rsindex aecf61ca,aecf61ca..2a79d92b--- a/host/src/api/devices.rs+++ b/host/src/api/devices.rs@@@ -39,6 -39,6 +39,7 @@@ const LOCAL_ONLY: &[&str] = &"setVoiceKey","pairing","computerCall",++ "chatCall","teamCall","memoryCall","routineCall",diff --cc host/src/tui/view/transcript.rsindex 780ccf48,00000000..6a69bc81mode 100644,000000..100644--- a/host/src/tui/view/transcript.rs+++ b/host/src/tui/view/transcript.rs@@@ -1,408 -1,0 +1,366 @@@+//! A chat's lines: messages, turns, threads and reactions.++use ratatui::style::{Modifier, Style};+use ratatui::text::{Line, Span};+use std::collections::{BTreeSet, HashMap};++use super::super::app::{App, Bot, Click, Entry, Kind, Status};+use super::super::md::{self, truncate, width as w};+use super::buffer::u;+use super::chat::with_bg;+use super::permission::{decided_line, permission_card};+use super::style::{FACE, bot_color, face_style, person, spin, theme};+use super::time::{clock, when};++pub(super) struct Built {+ pub(super) lines: Vec<Line<'static>>,+ /// (line index, x offset, width, click)+ pub(super) buttons: Vec<(usize, u16, u16, Click)>,+ /// Each message's (entry id, first line, end line), for picking one to reply to.+ pub(super) messages: Vec<(String, usize, usize)>,+}++struct 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;+ for d in e.data["diffs"].as_array().into_iter().flatten() {+ if let Some(p) = d["path"].as_str() {+ ti.files.insert(p.to_owned());+ }+ }+ }- Kind::Agent if e.is_final() => ti.has_final = true,++ Kind::Agent if e.is_final() => ti.last_message = Some(e.id.clone()),+ _ => {}+ }+ }+ m+}++pub(super) fn gap(out: &mut Built) {+ if !out.lines.is_empty() {+ out.lines.push(Line::default());+ }+}++pub(super) fn name_style(color: &str) -> Style {+ let t = theme();+ if t.color { Style::default().fg(bot_color(color)).add_modifier(Modifier::BOLD) } else { t.bold }+}++/// "3 replies", "1 reply".+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())- }-+pub(super) fn build_chat(app: &App, b: &Bot, width: usize) -> Built {+ let t = theme();+ let mut out = Built { lines: vec![], buttons: vec![], messages: vec![] };+ let thread = app.thread.as_deref();+ let entries = app.lane(&b.id);+ let info = turn_info(&entries);+ if entries.is_empty() && thread.is_none() {+ intro(&mut out, app, b, width);+ return out;+ }+ if thread.is_none() && !app.history_complete(&b.id) {+ out.lines.push(Line::from(Span::styled(" ↑ older messages load when you scroll up", t.dim)));+ }+ if let Some(root) = thread {+ // The message the thread is on, then its replies.+ if let Some(e) = app.entries.get(&b.id).and_then(|m| m.values().find(|e| e.id == root)) {+ entry_lines(&mut out, app, b, e, &HashMap::new(), false, width);+ }+ let n = entries.iter().filter(|e| e.is_message()).count();+ let label = if n == 0 {+ " No replies yet ".to_owned()+ } else {+ format!(" {} ", replies(i64::try_from(n).unwrap_or(0)))+ };+ gap(&mut out);+ 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() };+ out.lines.push(Line::from(vec![+ Span::styled(format!(" {} ", spin(app)), t.secondary),+ Span::styled(truncate(&act, width.saturating_sub(4)), t.secondary),+ ]));+ let steps = info.get(&last_turn).map_or(0, |ti| ti.steps);+ if steps > 0 {+ out.lines.push(Line::from(Span::styled(+ format!(" {steps} step{} so far · t shows them live", if steps == 1 { "" } else { "s" }),+ t.dim,+ )));+ }+ } else if matches!(b.status, Status::Working | Status::NeedsInput) && !b.works_in(thread) {+ // Busy somewhere else: another thread here, or a group it's in.+ let place = match b.away() {+ Some(g) => app.author_name(Some(g)),+ None if b.working_thread.is_some() => "a thread".to_owned(),+ None => "the chat".to_owned(),+ };+ gap(&mut out);+ let line = if b.status == Status::NeedsInput {+ Span::styled(format!(" ◆ Needs you in {place} · ! opens it"), t.amber)+ } else {+ Span::styled(format!(" {} Working in {place}", spin(app)), t.secondary)+ };+ out.lines.push(Line::from(line));+ }+ out+}++/// An empty chat: who this is and how it works.+fn intro(out: &mut Built, app: &App, b: &Bot, width: usize) {+ let t = theme();+ out.lines.push(Line::default());+ if !b.group {+ for row in FACE {+ out.lines.push(Line::from(vec![Span::raw(" "), Span::styled(row, face_style(&b.color))]));+ }+ out.lines.push(Line::default());+ }+ out.lines.push(Line::from(vec![Span::raw(" "), Span::styled(b.name.clone(), t.bold)]));+ let (meta, hello) = if b.group {+ let names: Vec<String> = b.members.iter().map(|m| app.author_name(Some(m))).collect();+ (+ format!("group · {}", names.join(", ")),+ "Everyone answers in turn unless you @mention someone. Each bot works in its own folder with its own tools."+ .to_owned(),+ )+ } else {+ (+ format!("{} · {}", b.backend, b.folder(&app.home)),+ format!("Say what you need. {} works in the background and pings you when it's done or needs you.", b.name),+ )+ };+ out.lines.push(Line::from(vec![Span::raw(" "), Span::styled(meta, t.secondary)]));+ if b.group && !b.description.is_empty() {+ out.lines.extend(md::wrap(+ &[Span::styled(b.description.clone(), t.text)],+ width,+ &[Span::raw(" ")],+ &[Span::raw(" ")],+ ));+ }+ out.lines.push(Line::default());+ out.lines.extend(md::wrap(&[Span::styled(hello, t.dim)], width, &[Span::raw(" ")], &[Span::raw(" ")]));+}++/// One chat entry. `main`: the main chat, where a message shows its thread's replies line.+fn entry_lines(+ out: &mut Built,+ app: &App,+ b: &Bot,+ e: &Entry,+ info: &HashMap<i64, TurnInfo>,+ main: bool,+ width: usize,+) {+ let t = theme();+ // In a group each reply is its author's; elsewhere the bot's own.+ let author = if b.group { app.bots.get(e.data["author"].as_str().unwrap_or_default()) } else { Some(b) };+ match e.kind {+ Kind::User => {+ gap(out);+ let from = out.lines.len();+ let mut head = vec![+ Span::styled(" you", t.secondary.add_modifier(Modifier::BOLD)),+ Span::styled(format!(" {}", clock(e.created_at)), t.dim),+ ];+ match e.data["status"].as_str() {+ Some("queued") => head.push(Span::styled(" · queued", t.dim)),+ Some("cancelled") => head.push(Span::styled(" · not sent", t.red)),+ _ => {}+ }+ out.lines.push(Line::from(head));+ let mut body = if e.text().is_empty() {+ vec![]+ } else {+ md::wrap(+ &[Span::styled(e.text().to_owned(), t.text)],+ width.saturating_sub(1),+ &[Span::raw(" › ")],+ &[Span::raw(" ")],+ )+ };+ for (name, size) in e.attachments() {+ body.push(Line::from(vec![+ Span::styled(" ▤ ", t.dim),+ Span::styled(truncate(name, width.saturating_sub(14)), t.text),+ Span::styled(format!(" {}", file_size(size)), t.dim),+ ]));+ }+ out.lines.extend(with_bg(body, width, t.band));+ reactions(out, e);+ out.messages.push((e.id.clone(), from, out.lines.len()));+ if main {+ thread_line(out, app, e);+ }+ }+ Kind::Agent if e.is_final() => {+ gap(out);+ let from = out.lines.len();+ let (name, color) = match author {+ Some(a) => (a.name.clone(), a.color.as_str()),+ None => ("A deleted bot".to_owned(), "gray"),+ };+ out.lines.push(Line::from(vec![+ Span::styled(format!(" {name}"), name_style(color)),+ Span::styled(format!(" {}", clock(e.created_at)), t.dim),+ ]));+ 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 {+ format!(" · {} file{} changed", ti.files.len(), if ti.files.len() == 1 { "" } else { "s" })+ };+ out.lines.push(Line::from(Span::styled(+ format!(" ↳ {} step{}{files} · o opens them", ti.steps, if ti.steps == 1 { "" } else { "s" }),+ t.dim,+ )));+ }+ if main {+ thread_line(out, app, e);+ }+ }+ Kind::Permission => {+ gap(out);+ if e.pending() {+ // A card in a group is its asking bot's.+ permission_card(out, app, e, author.unwrap_or(b), width);+ } else {+ decided_line(out, e);+ }+ }+ Kind::Notice => {+ let from = out.lines.len();+ let text = if let Some(status) = e.data["connectionRequest"]["status"].as_str() {+ format!(+ "{} · {} · {}",+ e.data["connectionRequest"]["title"].as_str().unwrap_or("Connect service"),+ e.notice_text(),+ if status == "pending" { "C connects / cancels" } else { status }+ )+ } else {+ e.notice_text()+ };+ gap(out);+ match e.data["style"].as_str() {+ Some("divider") => {+ let label = format!(" {text} · {} ", clock(e.created_at));+ let side = width.saturating_sub(w(&label) + 4);+ out.lines.push(Line::from(Span::styled(format!(" ───{label}{}", "─".repeat(side)), t.dim)));+ }+ Some("error") => out.lines.extend(md::wrap(+ &[Span::styled(text, t.red)],+ width,+ &[Span::styled(" × ", t.red)],+ &[Span::raw(" ")],+ )),+ _ => out.lines.extend(md::wrap(+ &[Span::styled(text, t.dim)],+ width,+ &[Span::styled(" · ", t.dim)],+ &[Span::raw(" ")],+ )),+ }+ if e.data["connectionRequest"].is_object() {+ out.messages.push((e.id.clone(), from, out.lines.len()));+ }+ }+ _ => {}+ }+}++/// A message's reactions, under it.+fn reactions(out: &mut Built, e: &Entry) {+ let r: Vec<&str> = e.data["reactions"].as_array().into_iter().flatten().filter_map(|r| r.as_str()).collect();+ if !r.is_empty() {+ out.lines.push(Line::from(Span::raw(format!(" {}", r.join(" ")))));+ }+}++/// A user message on one line: its text, then its files.+pub(super) fn user_line(e: &Entry) -> String {+ let files = e.attachments().iter().map(|(n, _)| format!("▤ {n}")).collect::<Vec<_>>().join(" ");+ [e.text(), files.as_str()].iter().filter(|s| !s.is_empty()).copied().collect::<Vec<_>>().join(" ")+}++fn file_size(bytes: u64) -> String {+ match bytes {+ 0..1024 => format!("{bytes} B"),+ 1024..1_048_576 => format!("{} KB", bytes / 1024),+ _ => format!("{}.{} MB", bytes / 1_048_576, bytes % 1_048_576 * 10 / 1_048_576),+ }+}++/// Under a message with a thread: how many replies, how recently (click opens it).+fn thread_line(out: &mut Built, app: &App, e: &Entry) {+ let Some(text) = thread_summary(&e.data["thread"]) else { return };+ let mut line = vec![Span::raw(" "), Span::styled(text, theme().secondary)];+ // Who replied: one cell each, first reply first (the host keeps them distinct).+ let authors: Vec<&str> =+ e.data["thread"]["authors"].as_array().into_iter().flatten().filter_map(|a| a.as_str()).collect();+ for a in authors.iter().take(5) {+ line.push(Span::raw(" "));+ line.push(person(app, a));+ }+ if authors.len() > 5 {+ line.push(Span::styled(format!(" +{}", authors.len() - 5), theme().dim));+ }+ let width = u(line.iter().skip(1).map(|s| w(&s.content)).sum());+ out.buttons.push((out.lines.len(), 3, width, Click::Thread(e.id.clone())));+ out.lines.push(Line::from(line));+}++/// "↳ 3 replies · 12:31" (or "· 1 new") from the host's `data.thread`, or nothing without replies.+fn thread_summary(v: &serde_json::Value) -> Option<String> {+ let n = v["count"].as_i64().filter(|&n| n > 0)?;+ let at = match v["unread"].as_i64().unwrap_or(0) {+ 0 => when(v["lastAt"].as_i64().unwrap_or(0)),+ unread => format!("{unread} new"),+ };+ Some(if at.is_empty() { format!("↳ {}", replies(n)) } else { format!("↳ {} · {at}", replies(n)) })+}++#[cfg(test)]+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::super::net::Client::new("http://127.0.0.1:1", None), tx, String::new());- app.on_msg(super::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 thread_summary_counts_replies() {+ assert_eq!(thread_summary(&serde_json::json!({"count": 0})), None);+ assert_eq!(thread_summary(&serde_json::Value::Null), None);+ assert_eq!(thread_summary(&serde_json::json!({"count": 1})).as_deref(), Some("↳ 1 reply"));+ assert_eq!(thread_summary(&serde_json::json!({"count": 3, "lastAt": 0})).as_deref(), Some("↳ 3 replies"));+ assert_eq!(+ thread_summary(&serde_json::json!({"count": 3, "lastAt": 0, "unread": 1})).as_deref(),+ Some("↳ 3 replies · 1 new")+ );+ }+}