Skip to content

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

Stopping a group stops it before the next bot speaks; the terminal app's threads, traces and group prompts match the other apps

leepokaia4ef2ae1ae3e
diff --git a/host/src/acp.rs b/host/src/acp.rs
index a1a1a830..16e1d35a 100644
--- a/host/src/acp.rs
+++ b/host/src/acp.rs
@@ -43,6 +43,29 @@ impl std::fmt::Display for RpcError {
impl std::error::Error for RpcError {}
+/// A request already written to the agent, waiting for its response.
+pub struct Answer {
+ method: String,
+ rx: oneshot::Receiver<std::result::Result<Value, Value>>,
+}
+
+impl Answer {
+ pub async fn response(self) -> Result<Value> {
+ match self.rx.await {
+ Ok(Ok(v)) => Ok(v),
+ Ok(Err(e)) => {
+ let msg = e["message"].as_str().map_or_else(|| e.to_string(), str::to_owned);
+ let message = match e["data"]["details"].as_str().or(e["data"].as_str()) {
+ Some(d) => format!("{msg} ({d})"),
+ None => msg,
+ };
+ Err(RpcError { code: e["code"].as_i64().unwrap_or_default(), message }.into())
+ }
+ Err(_) => bail!("{}: connection closed", self.method),
+ }
+ }
+}
+
pub struct Acp {
stdin: tokio::sync::Mutex<ChildStdin>,
next_id: AtomicI64,
@@ -152,22 +175,17 @@ impl Acp {
}
pub async fn request(&self, method: &str, params: Value) -> Result<Value> {
+ self.send(method, params).await?.response().await
+ }
+
+ /// Writes a request and returns its pending answer: anything written after this
+ /// (a `session/cancel`) reaches the agent after the request itself.
+ pub async fn send(&self, method: &str, params: Value) -> Result<Answer> {
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let (tx, rx) = oneshot::channel();
self.pending.locked().insert(id, tx);
self.write(json!({"jsonrpc": "2.0", "id": id, "method": method, "params": params})).await?;
- match rx.await {
- Ok(Ok(v)) => Ok(v),
- Ok(Err(e)) => {
- let msg = e["message"].as_str().map_or_else(|| e.to_string(), str::to_owned);
- let message = match e["data"]["details"].as_str().or(e["data"].as_str()) {
- Some(d) => format!("{msg} ({d})"),
- None => msg,
- };
- Err(RpcError { code: e["code"].as_i64().unwrap_or_default(), message }.into())
- }
- Err(_) => bail!("{method}: connection closed"),
- }
+ Ok(Answer { method: method.to_owned(), rx })
}
pub async fn notify(&self, method: &str, params: Value) -> Result<()> {
diff --git a/host/src/bot.rs b/host/src/bot.rs
index cdb6ff44..fe1ec7ce 100644
--- a/host/src/bot.rs
+++ b/host/src/bot.rs
@@ -135,8 +135,6 @@ pub(crate) struct Conn {
pub(crate) acp: Arc<Acp>,
pub(crate) rx: mpsc::UnboundedReceiver<Incoming>,
sessions: SessionCaps,
- /// The agent can reach remote (HTTP) MCP servers itself.
- mcp_http: bool,
/// Claude's adapter: takes `_meta.systemPrompt` and `_meta.claudeCode.options`.
pub(crate) claude: bool,
/// Sessions already created or loaded in this process.
@@ -256,7 +254,7 @@ impl Actor {
// 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.stop().await;
+ self.cancel_turn().await;
}
}
Cmd::Ask(ask) => {
@@ -292,8 +290,10 @@ impl Actor {
}
Cmd::Reconfigure(cfg) => {
let cfg = *cfg;
- let restart =
- cfg.backend != self.cfg.backend || cfg.command != self.cfg.command || cfg.cwd != self.cfg.cwd;
+ 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`).
@@ -308,7 +308,7 @@ impl Actor {
if self.session_id.is_some() {
self.forget_session();
self.notice(
- "The agent, command or folder changed — the agent starts with a fresh context.",
+ "The agent, model, command or folder changed — the agent starts with a fresh context.",
NoticeStyle::Divider,
);
}
@@ -330,6 +330,11 @@ impl Actor {
self.hub.set_entry(&entry_id, &e.data);
}
}
+ self.cancel_turn().await;
+ }
+
+ /// Stops the running turn only (queued ones stay).
+ async fn cancel_turn(&mut self) {
if self.turn.is_none() {
return;
}
@@ -557,9 +562,11 @@ impl Actor {
"sessionId": sid,
"prompt": [{"type": "text", "text": prompt}],
});
+ // 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(acp.request("session/prompt", params).await);
+ let _ = done_tx.send(answer.response().await);
});
Ok(())
}
@@ -647,23 +654,25 @@ impl Actor {
}
/// ACP connectors, team collaboration, and optional computer control.
- fn mcp_servers(&self, http_ok: bool) -> Value {
- let all = crate::market::connectors(&self.hub.store);
- let mut servers: Vec<Value> =
- all.iter().filter(|c| self.cfg.connectors.contains(&c.id)).filter_map(|c| c.acp(http_ok)).collect();
- match std::env::current_exe() {
- Ok(exe) => {
- let composio = crate::composio::enabled_for(&self.hub.store, &self.cfg.connectors);
- let builtin = [Some("team"), 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", self.hub.port.to_string()],
- "env": [],
- }));
- }
- }
- Err(error) => tracing::warn!(%error, "can't locate codync-host for built-in MCP servers"),
+ fn mcp_servers(&self) -> Value {
+ let Ok(exe) = std::env::current_exe() else {
+ tracing::warn!("can't locate codync-host for MCP servers");
+ return json!([]);
+ };
+ let port = self.hub.port;
+ let mut servers: Vec<Value> = 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::composio::enabled_for(&self.hub.store, &self.cfg.connectors);
+ let builtin = [Some("team"), 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": [],
+ }));
}
Value::Array(servers)
}
@@ -707,7 +716,7 @@ impl Actor {
return Err(last_err.unwrap_or_else(|| anyhow!("agent failed to start")));
}
}
- let servers = self.mcp_servers(self.conn.as_ref().is_some_and(|c| c.mcp_http));
+ 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
@@ -797,12 +806,12 @@ impl Actor {
let sid = res["sessionId"].as_str().ok_or_else(|| anyhow!("agent returned no sessionId"))?.to_owned();
conn.loaded.insert(sid.clone());
if let Some(model) = self.cfg.model.clone().filter(|m| !m.is_empty()) {
- let has_model = res["configOptions"].as_array().is_some_and(|o| o.iter().any(|o| o["id"] == "model"));
- let r = if has_model {
+ let config_id = crate::auth::model_config(&res).and_then(|c| c["id"].as_str());
+ let r = if let Some(config_id) = config_id {
conn.acp
.request(
"session/set_config_option",
- json!({"sessionId": sid, "configId": "model", "value": model}),
+ json!({"sessionId": sid, "configId": config_id, "value": model}),
)
.await
} else {
@@ -810,6 +819,7 @@ impl Actor {
};
if let Err(e) = r {
tracing::warn!(model, error = format!("{e:#}"), "couldn't set model");
+ bail!("Couldn't select model {model}: {e:#}");
}
}
self.set_session(slot, Some(&sid));
@@ -1266,9 +1276,8 @@ pub(crate) async fn start_agent(command: &str, cwd: &str, env: &[(String, String
load: init["agentCapabilities"]["loadSession"].as_bool().unwrap_or(false),
fork: init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object(),
};
- let mcp_http = init["agentCapabilities"]["mcpCapabilities"]["http"].as_bool().unwrap_or(false);
let claude = init["agentCapabilities"]["_meta"]["claudeCode"].is_object();
- Ok(Conn { acp, rx, sessions, mcp_http, claude, loaded: HashSet::new() })
+ Ok(Conn { acp, rx, sessions, claude, loaded: HashSet::new() })
}
async fn recv_incoming(conn: &mut Option<Conn>) -> Option<Incoming> {
diff --git a/host/src/group.rs b/host/src/group.rs
index cfe92afa..e35cfaeb 100644
--- a/host/src/group.rs
+++ b/host/src/group.rs
@@ -492,6 +492,26 @@ mod tests {
room.shutdown().await;
}
+ #[tokio::test]
+ async fn stop_ends_the_room_turn_before_the_next_speaker() {
+ let room = Room::new();
+ room.send("BLOCK everyone look", None).await;
+ let hub = room.hub.clone();
+ tokio::time::timeout(Duration::from_secs(10), async {
+ while hub.runtime("a").status != BotStatus::Working {
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ })
+ .await
+ .expect("a starts");
+ crate::api::dispatch(&room.hub, &Caller::Local, "stop", json!({"botId": room.group})).await.unwrap();
+ room.settle().await;
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ assert!(!room.dir.join("b/prompts.jsonl").exists(), "b never got a turn after Stop");
+ assert!(room.replies(&Lane::main(&room.group)).iter().all(|(_, t)| t != "reply: group"));
+ room.shutdown().await;
+ }
+
#[test]
fn pass_is_recognized_loosely() {
for t in ["(pass)", " (pass) ", "\"(pass)\"", "pass.", ""] {
diff --git a/host/src/tui/app.rs b/host/src/tui/app.rs
index 8894f63a..c60ff5a5 100644
--- a/host/src/tui/app.rs
+++ b/host/src/tui/app.rs
@@ -137,7 +137,12 @@ impl Bot {
/// Whether the running turn talks in this chat: its main lane (`None`) or that thread.
pub fn works_in(&self, thread: Option<&str>) -> bool {
- self.working_chat.as_deref().unwrap_or(&self.id) == self.id && self.working_thread.as_deref() == thread
+ self.away().is_none() && self.working_thread.as_deref() == thread
+ }
+
+ /// The other chat (a group) the running turn talks in, if it isn't this bot's own.
+ pub fn away(&self) -> Option<&str> {
+ self.working_chat.as_deref().filter(|c| *c != self.id)
}
pub fn mark(&self) -> Mark {
@@ -739,8 +744,13 @@ impl App {
id.and_then(|id| self.bots.get(id)).map_or_else(|| "A deleted bot".into(), |b| b.name.clone())
}
- pub fn latest_turn(&self, bot: &str) -> Option<i64> {
- self.entries.get(bot)?.values().map(|e| e.turn).max()
+ /// The turns of the lane on screen, oldest first: the trace steps through these.
+ /// Turn numbers count per bot, so a lane's own are not consecutive.
+ pub fn lane_turns(&self, bot: &str) -> Vec<i64> {
+ let mut v: Vec<i64> = self.lane(bot).iter().map(|e| e.turn).collect();
+ v.sort_unstable();
+ v.dedup();
+ v
}
/// Whether every older entry of this bot is loaded.
@@ -789,17 +799,22 @@ impl App {
/// Next bot (after the selected one, wrapping) whose mark matches.
fn jump(&mut self, want: Mark) {
- let ids: Vec<(String, Mark)> = self.roster().iter().map(|b| (b.id.clone(), b.mark())).collect();
+ // A bot busy in a group needs you there, and the group is marked too: skip the bot.
+ let ids: Vec<(String, bool)> = self
+ .roster()
+ .iter()
+ .map(|b| (b.id.clone(), b.mark() == want && (want != Mark::Need || b.away().is_none())))
+ .collect();
let start = self.selected.as_ref().and_then(|s| ids.iter().position(|(x, _)| x == s)).map_or(0, |i| i + 1);
- let found = (0..ids.len()).map(|k| &ids[(start + k) % ids.len()]).find(|(_, m)| *m == want).cloned();
+ let found = (0..ids.len()).map(|k| &ids[(start + k) % ids.len()]).find(|(_, hit)| *hit).cloned();
match found {
Some((id, _)) => {
self.select(&id);
self.chat_page = true;
self.focus = Focus::Chat;
// A card waiting in a thread shows there.
- let here = self.bots.get(&id).filter(|b| b.working_chat.as_deref().unwrap_or(&b.id) == b.id);
- if let Some(root) = here.and_then(|b| b.working_thread.clone()) {
+ let thread = self.bots.get(&id).and_then(|b| b.working_thread.clone()).filter(|_| want == Mark::Need);
+ if let Some(root) = thread {
self.open_thread(root);
}
}
@@ -936,7 +951,8 @@ impl App {
let old = self.bots.insert(new.id.clone(), new.clone());
let Some(old) = old else { return };
let watching = self.selected.as_deref() == Some(new.id.as_str()) && self.chat_visible() && self.term_focused;
- if !new.notify || watching {
+ // A member's turn in a group is the group's: it alone says done / needs you.
+ if !new.notify || watching || old.away().is_some() || new.away().is_some() {
return;
}
if new.status == Status::NeedsInput && old.status != Status::NeedsInput {
@@ -1039,16 +1055,24 @@ impl App {
}
After::Saved => {
let saved = self.overlays.iter().rposition(|o| matches!(o, Overlay::Form(_) | Overlay::Group(_)));
+ // A new bot or group opens ready to type; an edit goes back to where it was.
+ let created = saved.is_some_and(|i| match &self.overlays[i] {
+ Overlay::Form(f) => f.bot_id.is_none(),
+ Overlay::Group(g) => g.group_id.is_none(),
+ _ => false,
+ });
if let Some(i) = saved {
self.overlays.truncate(i);
}
if let Some(id) = v["bot"]["id"].as_str() {
let id = id.to_owned();
self.upsert_bot(&v["bot"]);
- self.select(&id);
- self.chat_page = true;
- self.focus = Focus::Chat;
- self.typing = true;
+ if created {
+ self.select(&id);
+ self.chat_page = true;
+ self.focus = Focus::Chat;
+ self.typing = true;
+ }
}
}
After::Connectors | After::Skills => {
@@ -1258,6 +1282,8 @@ impl App {
} else if self.thread.is_some() {
self.thread = None;
self.chat_scroll = 0;
+ self.trace_turn = None;
+ self.trace_scroll = 0;
} else if narrow && self.chat_page {
self.chat_page = false;
self.focus = Focus::Roster;
@@ -1303,11 +1329,13 @@ impl App {
}
KeyCode::Char('o') => {
let Some(id) = self.selected.clone() else { return };
- // The newest turn that did something.
+ // The newest turn in this lane that did something.
self.trace_turn = self
- .entries
- .get(&id)
- .and_then(|m| m.values().rev().find(|e| matches!(e.kind, Kind::Tool | Kind::Plan)).map(|e| e.turn));
+ .lane(&id)
+ .into_iter()
+ .filter(|e| matches!(e.kind, Kind::Tool | Kind::Plan))
+ .map(|e| e.turn)
+ .max();
self.trace_scroll = 0;
if self.trace == TraceMode::Off {
self.trace = if matches!(self.width, Width::Narrow | Width::Mid) {
@@ -1450,11 +1478,12 @@ impl App {
self.focus = p[j];
}
- fn step_turn(&mut self, d: i64) {
+ fn step_turn(&mut self, d: isize) {
let Some(id) = self.selected.clone() else { return };
- let Some(latest) = self.latest_turn(&id) else { return };
- let cur = self.trace_turn.unwrap_or(latest);
- let next = (cur + d).clamp(1, latest);
+ let turns = self.lane_turns(&id);
+ let Some(&latest) = turns.last() else { return };
+ let at = self.trace_turn.and_then(|t| turns.iter().position(|x| *x == t)).unwrap_or(turns.len() - 1);
+ let next = turns[at.saturating_add_signed(d).min(turns.len() - 1)];
self.trace_turn = if next == latest { None } else { Some(next) };
self.trace_scroll = 0;
if self.trace == TraceMode::Off {
@@ -1523,6 +1552,8 @@ impl App {
let Some(id) = self.selected.clone() else { return };
self.pick = None;
self.chat_scroll = 0;
+ self.trace_turn = None;
+ self.trace_scroll = 0;
self.chat_page = true;
self.focus = Focus::Chat;
if self.trace == TraceMode::Full {
@@ -2275,14 +2306,16 @@ mod tests {
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
let mut app = App::new(Client::new("http://127.0.0.1:1", None), tx, String::new());
for (seq, thread) in [(1, Value::Null), (2, json!("r")), (3, Value::Null)] {
- let v = json!({"botId": "g", "id": format!("e{seq}"), "seq": seq, "kind": "user", "threadId": thread});
+ let v = json!({"botId": "g", "id": format!("e{seq}"), "seq": seq, "turn": seq, "kind": "user", "threadId": thread});
let (bot, e) = Entry::parse(&v).expect("a full entry parses");
app.entries.entry(bot).or_default().insert(e.seq, e);
}
let ids = |app: &App| app.lane("g").iter().map(|e| e.id.clone()).collect::<Vec<_>>();
assert_eq!(ids(&app), ["e1", "e3"]);
+ assert_eq!(app.lane_turns("g"), [1, 3]);
app.thread = Some("r".into());
assert_eq!(ids(&app), ["e2"]);
+ assert_eq!(app.lane_turns("g"), [2]);
}
#[test]
diff --git a/host/src/tui/view.rs b/host/src/tui/view.rs
index e9c29ce1..c5ac1561 100644
--- a/host/src/tui/view.rs
+++ b/host/src/tui/view.rs
@@ -530,7 +530,7 @@ fn roster(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {
fill(buf, Rect::new(r.x, r.y, r.width, 1), t.panel);
}
put(buf, x0 + 1, r.y, wd.saturating_sub(10), if app.host.is_empty() { "codync" } else { &app.host }, t.bold);
- rput(buf, r.right() - 1, r.y, &format!("{} bots", bots.len()), t.dim);
+ rput(buf, r.right() - 1, r.y, &format!("{} chat{}", bots.len(), if bots.len() == 1 { "" } else { "s" }), t.dim);
if !narrow {
hline(buf, x0, r.y + 1, wd, t.line);
}
@@ -709,14 +709,16 @@ fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {
_ => (String::new(), t.dim),
};
let sx = rput(buf, r.right() - 1, r.y, &status, ss.add_modifier(Modifier::BOLD));
+ let room = sx.saturating_sub(x + 2);
if app.thread.is_some() {
- put(buf, x, r.y, sx.saturating_sub(x + 2), "esc back to the chat", t.dim);
+ put(buf, x, r.y, room, "esc back to the chat", t.dim);
} else if b.group {
let names: Vec<String> = b.members.iter().map(|m| app.author_name(Some(m))).collect();
- put(buf, x, r.y, sx.saturating_sub(x + 2), &format!("group · {}", names.join(", ")), t.secondary);
+ put(buf, x, r.y, room, &truncate(&format!("group · {}", names.join(", ")), usize::from(room)), t.secondary);
} else if !narrow {
- let meta = format!("{} · {} · {}", b.backend, tilde(&b.cwd, &app.home), if b.auto { "auto" } else { "ask" });
- put(buf, x, r.y, sx.saturating_sub(x + 2), &meta, t.secondary);
+ let mode = if b.auto { "auto" } else { "ask" };
+ let cwd = truncate(&tilde(&b.cwd, &app.home), usize::from(room).saturating_sub(w(&b.backend) + w(mode) + 6));
+ put(buf, x, r.y, room, &format!("{} · {cwd} · {mode}", b.backend), t.secondary);
}
let mut top = r.y + 1;
if !narrow {
@@ -752,29 +754,45 @@ fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {
let comp_rect = Rect::new(r.x, comp_top, r.width, ch + 2);
app.hits.clicks.push((comp_rect, Click::Composer));
let first = clines.len().saturating_sub(usize::from(ch)).min(cursor.1.saturating_sub(usize::from(ch) - 1));
+ // Where the first composer line's text ends, so the chip on its right never covers it.
+ let mut used = clines.get(first).map_or(0, |l| w(l));
if draft.text.is_empty() {
- let placeholder =
- if app.thread.is_some() { "Reply in thread…".to_owned() } else { format!("Message {}…", b.name) };
+ // The apps' wording.
+ let placeholder = if app.pick.is_some() {
+ "Reply in thread: j k pick a message · ↵ open · esc cancel".to_owned()
+ } else if app.thread.is_some() {
+ "Reply…".to_owned()
+ } else if b.group {
+ format!("Message {} · @ to ask one bot", b.name)
+ } else {
+ format!("Message {}…", b.name)
+ };
put(buf, r.x + 3, comp_top + 1, r.width.saturating_sub(4), &placeholder, t.dim);
+ used = w(&placeholder);
} else {
for (i, l) in clines.iter().skip(first).take(usize::from(ch)).enumerate() {
put(buf, r.x + 3, comp_top + 1 + u(i), r.width.saturating_sub(4), l, t.text);
}
}
+ // Only a turn in this lane holds a message back; in a group a new one ends the round instead.
+ let here = b.works_in(app.thread.as_deref());
let chip = if typing {
match b.status {
- Status::Working => "sends after this turn",
- Status::NeedsInput => "sends after the approval",
+ Status::Working if here && b.group => "goes in after this reply",
+ Status::Working if here => "sends after this turn",
+ Status::NeedsInput if here => "sends after the approval",
_ => "",
}
} else if app.pick.is_some() {
- "↵ opens its thread · esc cancels"
- } else if matches!(b.status, Status::Working) {
+ if draft.text.is_empty() { "" } else { "↵ opens its thread · esc cancels" }
+ } else if matches!(b.status, Status::Working | Status::NeedsInput) {
"s stops"
+ } else if app.thread.is_none() {
+ "i to type · r reply in thread"
} else {
"i to type"
};
- if draft.text.is_empty() || !typing {
+ if (draft.text.is_empty() || !typing) && used + w(chip) + 6 <= usize::from(r.width) {
rput(buf, r.right() - 1, comp_top + 1, chip, t.dim);
}
if typing {
@@ -964,16 +982,18 @@ fn build_chat(app: &App, b: &Bot, width: usize) -> Built {
t.dim,
)));
}
- } else if thread.is_none()
- && b.working_thread.is_some()
- && b.working_chat.as_deref().unwrap_or(&b.id) == b.id
- && matches!(b.status, Status::Working | Status::NeedsInput)
- {
+ } 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(" ◆ Needs you in a thread · ! opens it", t.amber)
+ Span::styled(format!(" ◆ Needs you in {place} · ! opens it"), t.amber)
} else {
- Span::styled(format!(" {} Working in a thread", spin(app)), t.secondary)
+ Span::styled(format!(" {} Working in {place}", spin(app)), t.secondary)
};
out.lines.push(Line::from(line));
}
@@ -1005,6 +1025,14 @@ fn intro(out: &mut Built, app: &App, b: &Bot, width: usize) {
)
};
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(" ")]));
}
@@ -1305,10 +1333,14 @@ fn trace(buf: &mut Buffer, r: Rect, app: &mut App) {
app.hits.trace = r;
let full = app.trace == TraceMode::Full;
let Some(b) = app.bot().cloned() else { return };
- let latest = app.latest_turn(&b.id).unwrap_or(0);
+ // The trace is the lane's: the main chat's turns, or the open thread's.
+ let turns = app.lane_turns(&b.id);
+ let latest = turns.last().copied().unwrap_or(0);
let turn = app.trace_turn.unwrap_or(latest);
- let live = turn == latest && b.status == Status::Working;
- let mut x = put(
+ let live = turn == latest && b.status == Status::Working && b.works_in(app.thread.as_deref());
+ let nth = turns.iter().position(|x| *x == turn).map_or(0, |i| i + 1);
+ let lane = if app.thread.is_some() { "thread" } else { "chat" };
+ let x = put(
buf,
r.x + 1,
r.y,
@@ -1316,16 +1348,16 @@ fn trace(buf: &mut Buffer, r: Rect, app: &mut App) {
"TRACE",
if app.focus == Focus::Trace { t.bold } else { t.secondary.add_modifier(Modifier::BOLD) },
);
- x = put(
- buf,
- x + 1,
- r.y,
- r.width.saturating_sub(20),
- &format!("· {} · turn {turn}{}", b.name, if live { " · live" } else { "" }),
- t.dim,
- );
- let _ = x;
- rput(buf, r.right() - 1, r.y, if full { "{ } turns · esc close" } else { "{ } turns · T full" }, t.dim);
+ let keys = if full { "{ } turns · esc close" } else { "{ } turns · T full" };
+ // The keys hint only when the title leaves it room.
+ let right = if r.width >= 64 { rput(buf, r.right() - 1, r.y, keys, t.dim) } else { r.right() };
+ let title = if turns.is_empty() {
+ format!("· {} · {lane}", b.name)
+ } else {
+ format!("· {} · {lane} · turn {nth} of {}{}", b.name, turns.len(), if live { " · live" } else { "" })
+ };
+ let room = right.saturating_sub(x + 2);
+ put(buf, x + 1, r.y, room, &truncate(&title, usize::from(room)), t.dim);
hline(buf, r.x, r.y + 1, r.width, t.line);
let body = Rect::new(r.x, r.y + 2, r.width, r.height.saturating_sub(2));
let lines = build_trace(app, &b, turn, usize::from(body.width.saturating_sub(1)), full);
@@ -1339,7 +1371,8 @@ fn trace(buf: &mut Buffer, r: Rect, app: &mut App) {
put_line(buf, body.x, body.y + u(i), body.width, l);
}
if lines.is_empty() {
- put(buf, body.x + 2, body.y, body.width.saturating_sub(2), "Nothing happened in this turn yet.", t.dim);
+ let empty = if turns.is_empty() { "Nothing yet." } else { "Nothing happened in this turn yet." };
+ put(buf, body.x + 2, body.y, body.width.saturating_sub(2), empty, t.dim);
}
}
@@ -1358,7 +1391,20 @@ fn build_trace(app: &App, b: &Bot, turn: i64, width: usize, full: bool) -> Vec<L
let label = |s: &str| Span::styled(format!("{s:<8} "), t.secondary);
let text_rest = |width: usize| width.saturating_sub(13);
let (diff_max, out_max) = if full { (400, 400) } else { (14, 6) };
- for e in map.values().filter(|e| e.turn == turn) {
+ let mut speaker: Option<&str> = None;
+ for e in map.values().filter(|e| e.turn == turn && e.thread_id == app.thread) {
+ // In a group, each member's steps under its name.
+ if b.group && e.kind != Kind::User {
+ let author = e.data["author"].as_str();
+ if author.is_some() && author != speaker {
+ speaker = author;
+ let (name, color) = author.and_then(|a| app.bots.get(a)).map_or_else(
+ || ("A deleted bot".to_owned(), "gray".to_owned()),
+ |a| (a.name.clone(), a.color.clone()),
+ );
+ out.push(Line::from(Span::styled(format!(" {name}"), name_style(&color))));
+ }
+ }
match e.kind {
Kind::User => out.push(Line::from(vec![
Span::styled(" › ", t.dim),
@@ -1672,10 +1718,15 @@ fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &Overlay) {
}
}
+/// A one-line text field. A search shows "/ " first, unless the caller drew its own prefix
+/// (the folder path, with an empty placeholder).
fn field_line(buf: &mut Buffer, r: Rect, y: u16, e: &Editor, placeholder: &str, active: bool) {
+ input_line(buf, r, y, e, placeholder, active, !placeholder.is_empty());
+}
+
+fn input_line(buf: &mut Buffer, r: Rect, y: u16, e: &Editor, placeholder: &str, active: bool, search: bool) {
let t = theme();
- // An empty placeholder means the caller drew its own prefix (the folder path).
- let x = if placeholder.is_empty() { r.x } else { put(buf, r.x, y, 2, "/ ", t.dim.patch(t.panel)) };
+ let x = if search { put(buf, r.x, y, 2, "/ ", t.dim.patch(t.panel)) } else { r.x };
if e.text.is_empty() {
if active {
set_cursor(Position::new(x, y));
@@ -1800,7 +1851,7 @@ fn goto(buf: &mut Buffer, area: Rect, app: &mut App, g: &super::app::Goto, items
);
}
-const HELP: [(&str, &str, &str); 44] = [
+const HELP: [(&str, &str, &str); 45] = [
("MOVE", "j k ↑ ↓", "next / previous bot"),
("MOVE", "[ ]", "previous / next bot"),
("MOVE", "1…9", "jump to bot 1–9"),
@@ -1819,8 +1870,8 @@ const HELP: [(&str, &str, &str); 44] = [
("CHAT", "s", "stop the bot"),
("CHAT", "o", "last turn's steps"),
("CHAT", "c", "copy the last reply"),
- ("CHAT", "r", "reply in thread: pick a message"),
- ("CHAT", "j k ↵", "picking: move / open its thread"),
+ ("CHAT", "r", "reply in a thread"),
+ ("CHAT", "j k ↵", "picking: move / open"),
("CHAT", "esc", "close the thread"),
("TYPE", "↵", "send"),
("TYPE", "⇧↵ alt↵ ^j", "new line"),
@@ -1829,12 +1880,13 @@ const HELP: [(&str, &str, &str); 44] = [
("TYPE", "^a ^e", "line start / end"),
("TYPE", "alt b / f", "word left / right"),
("TYPE", "^w ^u", "delete word / line"),
+ ("TYPE", "@name", "group: ask just that bot"),
("BOTS", "n", "new bot"),
("BOTS", "m", "new group chat"),
("BOTS", "e", "edit bot or group"),
("BOTS", "p", "pin / unpin"),
("BOTS", "S", "new session"),
- ("BOTS", "x", "delete bot"),
+ ("BOTS", "x", "delete bot or group"),
("VIEW", "t", "trace pane"),
("VIEW", "T", "trace full screen"),
("VIEW", "{ }", "previous / next turn"),
@@ -1843,13 +1895,14 @@ const HELP: [(&str, &str, &str); 44] = [
("VIEW", "P", "pair a phone"),
("VIEW", "esc", "close / go back"),
("VIEW", "q", "quit; bots keep going"),
- ("MOUSE", "click", "open bot or thread, press button"),
+ ("MOUSE", "click", "open, press a button"),
("MOUSE", "wheel", "scroll under pointer"),
];
fn help(buf: &mut Buffer, area: Rect, filter: &Editor) {
let t = theme();
- let r = centered(area, 80, 34);
+ // Two columns fit everything from 36 rows up; shorter windows get a third.
+ let r = centered(area, if area.height >= 36 { 80 } else { 120 }, 34);
let inner = frame_box(buf, r, t.text, t.panel, Some(("Keys", t.text)));
field_line(buf, inner, inner.y, filter, "filter actions and keys", true);
let q = filter.text.to_lowercase();
@@ -1857,16 +1910,19 @@ fn help(buf: &mut Buffer, area: Rect, filter: &Editor) {
.iter()
.filter(|(_, k, d)| q.is_empty() || d.to_lowercase().contains(&q) || k.to_lowercase().contains(&q))
.collect();
- let col_w = inner.width / 2;
+ // As many 38-wide columns as fit; what doesn't fit is counted in the footer.
+ let cols = (inner.width / 38).max(1);
+ let col_w = inner.width / cols;
let rows = usize::from(inner.height.saturating_sub(3));
- let (mut col, mut y, mut section) = (0u16, inner.y + 2, "");
+ let total = items.len();
+ let (mut col, mut y, mut section, mut shown) = (0u16, inner.y + 2, "", 0usize);
for (sec, k, d) in items {
let need = if *sec == section { 1 } else { 2 + u16::from(!section.is_empty()) };
if y + need > inner.y + 2 + u(rows) {
- if col == 1 {
+ if col + 1 == cols {
break;
}
- col = 1;
+ col += 1;
y = inner.y + 2;
section = "";
}
@@ -1882,8 +1938,11 @@ fn help(buf: &mut Buffer, area: Rect, filter: &Editor) {
put(buf, x, y, 11, k, t.bold.patch(t.panel));
put(buf, x + 12, y, col_w.saturating_sub(13), d, t.secondary.patch(t.panel));
y += 1;
+ shown += 1;
}
- put(buf, inner.x, inner.bottom() - 1, inner.width, "esc close", t.dim.patch(t.panel));
+ let foot =
+ if shown < total { format!("{} more: type to filter · esc close", total - shown) } else { "esc close".into() };
+ put(buf, inner.x, inner.bottom() - 1, inner.width, &foot, t.dim.patch(t.panel));
}
fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {
@@ -2047,22 +2106,24 @@ fn group_view(buf: &mut Buffer, area: Rect, app: &App, g: &GroupForm) {
put(buf, inner.x, inner.y, 8, "Name", label(g.field == GroupField::Name));
let default = app.group_default_name(&g.members);
let placeholder = if default.is_empty() { "Name" } else { default.as_str() };
- field_line(
+ input_line(
buf,
Rect::new(inner.x + 8, inner.y, inner.width.saturating_sub(8), 1),
inner.y,
&g.name,
placeholder,
g.field == GroupField::Name,
+ false,
);
put(buf, inner.x, inner.y + 2, 8, "About", label(g.field == GroupField::About));
- field_line(
+ input_line(
buf,
Rect::new(inner.x + 8, inner.y + 2, inner.width.saturating_sub(8), 1),
inner.y + 2,
&g.about,
- "optional: what this group is for",
+ "What this group works on (optional)",
g.field == GroupField::About,
+ false,
);
put(buf, inner.x, inner.y + 4, inner.width, &format!("Bots · {}", g.members.len()), label(on_bots));
let list_h = usize::from(inner.height.saturating_sub(9));
diff --git a/host/tests/fixtures/team_agent.py b/host/tests/fixtures/team_agent.py
index 22fd787b..f0ca5cf2 100644
--- a/host/tests/fixtures/team_agent.py
+++ b/host/tests/fixtures/team_agent.py
@@ -64,6 +64,11 @@ def prompt(request):
while "BLOCK" in text and not pathlib.Path("release").exists() and not cancel.wait(0.01):
pass
if text.startswith("[Group chat") or "\n[Group chat" in text:
+ while "BLOCK" in text and not pathlib.Path("release").exists() and not cancel.wait(0.01):
+ pass
+ if cancel.is_set():
+ send({"id": request["id"], "result": {"stopReason": "cancelled"}})
+ return
# A room turn: answer only when the user spoke last, otherwise pass.
room = text.split("New messages in the room (oldest first):\n", 1)[-1].split("\n\n", 1)[0]
last = room.strip().splitlines()[-1] if "New messages" in text else ""