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
Group chats and reply threads in the terminal and Linux apps; group replies keep their author while streaming
leepokai9d2aeaf8db98
diff --git a/CLAUDE.md b/CLAUDE.mdindex db136124..03ac1d35 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -19,7 +19,8 @@ Bot-based remote for coding agents: persistent named bots on your computer, mess- UI principle: buttons an icon can express are icon-only (with tooltip / accessibility label); text only where an icon would be ambiguous (approval choices).- No native/system UI at all: no `Menu`/`Picker`, `.switch` toggles, `Form`/`List` styling, `confirmationDialog`/`alert`, `ProgressView`, `.sheet`/`.popover`/`.fullScreenCover`, `.toolbar`/navigation bars, `TabView`, `ContentUnavailableView`. Use `kit/Sources/CodyncUI/Controls.swift` + `Chrome.swift` (`.codyncSheet`, `ModalHeader`, `ScreenHeader`, `TabBar`, `.codyncMenu`, `.codyncDialog`, `ToggleStyle.codync`). Every tap that shows/hides something animates (`Motion`). Anything with a background fill gets no border line.- `host/` — **codync-host** (Rust, macOS + Linux). Detects installed harnesses (`backends.rs`: login-shell PATH + known dirs) and the ACP registry (`registry.rs`, cached in `~/.codync/registry.json`, binaries under `~/.codync/agents`). Drives agents over **ACP** (JSON-RPC on stdio, hand-rolled in `acp.rs`, updates kept as `serde_json::Value` so new adapter variants never break parsing). One actor per bot (`bot.rs`) owns the agent process + session and maps `session/update` onto transcript entries.-- **Thread ≠ session**: a bot is one endless transcript (SQLite `entries`, ordered by `seq`); the ACP session underneath is resumed with `session/load` or replaced by *New session*.+- **Chat ≠ session**: a bot is one endless transcript (SQLite `entries`, ordered by `seq`); the ACP session underneath is resumed with `session/load` or replaced by *New session*.+- **Group chats and threads** are host features every client drives through the same methods (`send` with `threadId`, `thread`, `createBot {kind: group}`); clients never route, parse mentions or count replies themselves. A group is a roster row whose members answer in their own sessions (Grok Bot's room turns); a thread on a bot's message is a forked session: [docs/groups-and-threads.md](docs/groups-and-threads.md).- Bot collaboration: built-in `team` MCP (`team.rs`) lists visible bots and asks one for a reply through its actor queue. Requests are separate turns, cycle-checked and cancellable; native subagents stay with the harness. See [docs/bot-collaboration.md](docs/bot-collaboration.md).- **Context & memory** (Grok Bot's design): frozen instruction snapshot per session + compaction epoch (Claude gets it as a system prompt), profile edits as update blocks, per-bot memory files written by a keeper agent, busy-time messages folded into one turn, interrupted turns resumed: [docs/context-and-memory.md](docs/context-and-memory.md).- **Chat shows only**: user messages, the *final* agent message of each turn (`data.final`), permission cards, notices. Narration, thoughts, tool calls, plans are trace entries (Full conversation sheet).diff --git a/apps/linux/src/avatar.rs b/apps/linux/src/avatar.rsindex ea46ce9e..f06ad9a4 100644--- a/apps/linux/src/avatar.rs+++ b/apps/linux/src/avatar.rs@@ -2,9 +2,13 @@use gtk::cairo::Context;use gtk::prelude::*;+use serde_json::Value;+use std::collections::HashMap;use std::f64::consts::PI;-pub const SHAPES: &[&str] = &["blob", "pebble", "squircle", "tablet", "wedge", "hex", "cloud", "teardrop"];+pub const SHAPES: &[&str] = &[+ "blob", "pebble", "squircle", "tablet", "wedge", "hex", "cloud", "teardrop",+];pub const COLORS: &[(&str, u32)] = &[("black", 0x2B2B2B),("brown", 0x936439),@@ -20,11 +24,19 @@ pub const COLORS: &[(&str, u32)] = &[];pub fn rgb(hex: u32) -> (f64, f64, f64) {- (((hex >> 16) & 0xFF) as f64 / 255.0, ((hex >> 8) & 0xFF) as f64 / 255.0, (hex & 0xFF) as f64 / 255.0)+ (+ ((hex >> 16) & 0xFF) as f64 / 255.0,+ ((hex >> 8) & 0xFF) as f64 / 255.0,+ (hex & 0xFF) as f64 / 255.0,+ )}-fn color_of(name: &str) -> u32 {- COLORS.iter().find(|(n, _)| *n == name).map(|c| c.1).unwrap_or(0x1084FE)+pub fn color_of(name: &str) -> u32 {+ COLORS+ .iter()+ .find(|(n, _)| *n == name)+ .map(|c| c.1)+ .unwrap_or(0x1084FE)}fn rounded_rect(cr: &Context, x: f64, y: f64, w: f64, h: f64, r: f64) {@@ -59,7 +71,11 @@ fn silhouette(cr: &Context, shape: &str) {for i in 0..6 {let a = i as f64 * PI / 3.0 - PI / 2.0;let (x, y) = (50.0 + a.cos() * 49.0, 50.0 + a.sin() * 49.0);- if i == 0 { cr.move_to(x, y) } else { cr.line_to(x, y) }+ if i == 0 {+ cr.move_to(x, y)+ } else {+ cr.line_to(x, y)+ }}cr.close_path();}@@ -82,7 +98,11 @@ fn silhouette(cr: &Context, shape: &str) {let a = i as f64 / 64.0 * 2.0 * PI;let r = 46.0 + 3.5 * (a * 3.0 + 0.6).sin();let (x, y) = (50.0 + a.cos() * r, 50.0 + a.sin() * r);- if i == 0 { cr.move_to(x, y) } else { cr.line_to(x, y) }+ if i == 0 {+ cr.move_to(x, y)+ } else {+ cr.line_to(x, y)+ }}cr.close_path();}@@ -107,17 +127,31 @@ const CELLS: i32 = 13;const EYE_COLUMNS: [i32; 2] = [4, 8];const EYE_ROWS: [i32; 3] = [4, 5, 6];-pub fn draw(cr: &Context, size: f64, shape: &str, color: &str, ink: (f64, f64, f64), mood: Mood, t: f64) {+pub fn draw(+ cr: &Context,+ size: f64,+ shape: &str,+ color: &str,+ ink: (f64, f64, f64),+ mood: Mood,+ t: f64,+) {cr.save().ok();cr.scale(size / 100.0, size / 100.0);let (r, g, b) = rgb(color_of(color));let step = 100.0 / f64::from(CELLS);let animated = mood != Mood::Idle;// Glance: whole-cell steps left / center / right, like a small display.- let glance = if mood == Mood::Working { ((t * 2.0 * PI / 3.2).sin() * 1.4).round() as i32 } else { 0 };+ let glance = if mood == Mood::Working {+ ((t * 2.0 * PI / 3.2).sin() * 1.4).round() as i32+ } else {+ 0+ };let blinking = animated && (t / 4.7).fract() < 0.035;let eye_rows: &[i32] = if blinking { &EYE_ROWS[2..] } else { &EYE_ROWS };- let is_eye = |col: i32, row: i32| EYE_COLUMNS.iter().any(|c| c + glance == col) && eye_rows.contains(&row);+ let is_eye = |col: i32, row: i32| {+ EYE_COLUMNS.iter().any(|c| c + glance == col) && eye_rows.contains(&row)+ };silhouette(cr, shape);if size < 24.0 {@@ -127,7 +161,12 @@ pub fn draw(cr: &Context, size: f64, shape: &str, color: &str, ink: (f64, f64, fcr.set_operator(gtk::cairo::Operator::Clear);for c in EYE_COLUMNS {for &row in eye_rows {- cr.rectangle(f64::from(c + glance) * step, f64::from(row) * step, step, step);+ cr.rectangle(+ f64::from(c + glance) * step,+ f64::from(row) * step,+ step,+ step,+ );}}cr.fill().ok();@@ -168,20 +207,93 @@ pub fn draw(cr: &Context, size: f64, shape: &str, color: &str, ink: (f64, f64, fcr.restore().ok();}-pub fn widget(shape: &str, color: &str, size: i32, working: bool, status: &str) -> gtk::DrawingArea {- let area = gtk::DrawingArea::builder().content_width(size).content_height(size).valign(gtk::Align::Center).build();- let (shape, color, status) = (shape.to_owned(), color.to_owned(), status.to_owned());- let mood = if status == "needs" { Mood::Needs } else if working { Mood::Working } else { Mood::Idle };+pub fn widget(+ shape: &str,+ color: &str,+ size: i32,+ working: bool,+ status: &str,+) -> gtk::DrawingArea {+ many(+ vec![(shape.to_owned(), color.to_owned())],+ size,+ working,+ status,+ )+}++fn look(b: &Value) -> (String, String) {+ (+ b["avatarShape"].as_str().unwrap_or("blob").to_owned(),+ b["avatarColor"].as_str().unwrap_or("blue").to_owned(),+ )+}++/// A bot's character, or for a group its first two members overlapped.+pub fn of(+ bots: &HashMap<String, Value>,+ b: &Value,+ size: i32,+ working: bool,+ status: &str,+) -> gtk::DrawingArea {+ let parts = if b["kind"] == "group" {+ b["members"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|m| bots.get(m.as_str()?))+ .take(2)+ .map(look)+ .collect()+ } else {+ vec![look(b)]+ };+ many(parts, size, working, status)+}++fn many(parts: Vec<(String, String)>, size: i32, working: bool, status: &str) -> gtk::DrawingArea {+ let area = gtk::DrawingArea::builder()+ .content_width(size)+ .content_height(size)+ .valign(gtk::Align::Center)+ .build();+ let status = status.to_owned();+ let mood = if status == "needs" {+ Mood::Needs+ } else if working {+ Mood::Working+ } else {+ Mood::Idle+ };let start = std::time::Instant::now();area.set_draw_func(move |area, cr, w, _| {let s = w as f64;let fg = area.color();let ink = (fg.red() as f64, fg.green() as f64, fg.blue() as f64);- draw(cr, s, &shape, &color, ink, mood, start.elapsed().as_secs_f64());+ let t = start.elapsed().as_secs_f64();+ match parts.as_slice() {+ [] => draw(cr, s, "blob", "gray", ink, mood, t),+ [(shape, color)] => draw(cr, s, shape, color, ink, mood, t),+ _ => {+ let sub = s * 0.68;+ for (i, (shape, color)) in parts.iter().enumerate() {+ let o = if i == 0 { 0.0 } else { s - sub };+ cr.save().ok();+ cr.translate(o, o);+ draw(cr, sub, shape, color, ink, mood, t);+ cr.restore().ok();+ }+ }+ }if !status.is_empty() {let d = s * if status == "needs" { 0.36 } else { 0.28 };let (cx, cy) = (s - d / 2.0, s - d / 2.0);- let (r, g, b) = if status == "needs" { rgb(0xF0A030) } else { ink };+ let (r, g, b) = if status == "needs" {+ rgb(0xF0A030)+ } else {+ ink+ };cr.arc(cx, cy, d / 2.0, 0.0, 2.0 * PI);cr.set_source_rgb(r, g, b);cr.fill().ok();diff --git a/apps/linux/src/dialogs.rs b/apps/linux/src/dialogs.rsindex 71e5e3ba..f9115126 100644--- a/apps/linux/src/dialogs.rs+++ b/apps/linux/src/dialogs.rs@@ -1,4 +1,4 @@-//! Bot editor, full-conversation trace, settings/pairing and the bot menu.+//! Bot and group editors, full-conversation trace, settings/pairing and the bot menu.use crate::client;use crate::ui::{self, App};@@ -339,6 +339,8 @@ pub fn editor(ui: &App, bot: Option<Value>) {"rev","deleted","startedAt",+ "workingChat",+ "workingThread",] {body.as_object_mut().unwrap().remove(k);}@@ -372,6 +374,231 @@ pub fn editor(ui: &App, bot: Option<Value>) {dialog.present(Some(&ui.window));}+// MARK: group editor++const MAX_MEMBERS: usize = 6;++/// Create a group chat, or rename one and change who's in it (up to six bots).+pub fn group_editor(ui: &App, group: Option<Value>) {+ let is_new = group.is_none();+ let group_id = group+ .as_ref()+ .and_then(|g| g["id"].as_str())+ .map(str::to_owned);+ let members: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(+ group+ .as_ref()+ .and_then(|g| g["members"].as_array())+ .into_iter()+ .flatten()+ .filter_map(|m| m.as_str().map(str::to_owned))+ .collect(),+ ));+ let (dialog, view, header) = header_dialog(+ if is_new {+ "New group chat"+ } else {+ "Group chat"+ },+ 480,+ 620,+ );+ let save = gtk::Button::builder()+ .icon_name("object-select-symbolic")+ .tooltip_text(if is_new { "Create" } else { "Save" })+ .css_classes(["accent-fill", "circular"])+ .build();+ header.pack_end(&save);++ let page = adw::PreferencesPage::new();+ let profile = adw::PreferencesGroup::new();+ let name = adw::EntryRow::builder()+ .title("Name")+ .text(+ group+ .as_ref()+ .and_then(|g| g["name"].as_str())+ .unwrap_or(""),+ )+ .build();+ profile.add(&name);+ page.add(&profile);++ let bots_group = adw::PreferencesGroup::builder()+ .description("Everyone answers in turn unless you @mention someone. Each bot works in its own folder with its own tools.")+ .build();+ let st = ui.state.borrow();+ let mut candidates: Vec<&Value> = st+ .bots+ .values()+ .filter(|b| {+ b["kind"] != "group"+ && (b["hidden"] != true+ || b["id"]+ .as_str()+ .is_some_and(|id| members.borrow().iter().any(|m| m == id)))+ })+ .collect();+ candidates.sort_by_key(|b| b["name"].as_str().unwrap_or("").to_lowercase());+ let mut checks: Vec<(String, String, gtk::CheckButton)> = vec![];+ for b in candidates {+ let id = b["id"].as_str().unwrap_or_default().to_owned();+ let bname = b["name"].as_str().unwrap_or("").to_owned();+ let check = gtk::CheckButton::builder()+ .active(members.borrow().contains(&id))+ .valign(gtk::Align::Center)+ .build();+ let row = adw::ActionRow::builder()+ .title(gtk::glib::markup_escape_text(&bname))+ .subtitle(gtk::glib::markup_escape_text(&ui::folder(+ b["cwd"].as_str().unwrap_or(""),+ )))+ .activatable_widget(&check)+ .build();+ row.add_prefix(&avatar::of(&st.bots, b, 30, false, ""));+ row.add_suffix(&check);+ bots_group.add(&row);+ checks.push((id, bname, check));+ }+ drop(st);+ page.add(&bots_group);+ let checks = Rc::new(checks);+ // "Alice, Bob" when no name is typed; at most six; nothing to save without a bot.+ let sync = {+ let (members, checks, bots_group, name, save) = (+ members.clone(),+ checks.clone(),+ bots_group.clone(),+ name.clone(),+ save.clone(),+ );+ move || {+ let m = members.borrow();+ bots_group.set_title(&format!("Bots · {} of {MAX_MEMBERS}", m.len()));+ for (_, _, check) in checks.iter() {+ check.set_sensitive(check.is_active() || m.len() < MAX_MEMBERS);+ }+ let names: Vec<&str> = m+ .iter()+ .filter_map(|id| checks.iter().find(|c| c.0 == *id).map(|c| c.1.as_str()))+ .collect();+ name.set_title(+ if names.is_empty() {+ "Name".to_owned()+ } else {+ format!("Name · {}", names.join(", "))+ }+ .as_str(),+ );+ save.set_sensitive(!m.is_empty());+ }+ };+ for (id, _, check) in checks.iter() {+ let (members, sync, id) = (members.clone(), sync.clone(), id.clone());+ check.connect_toggled(move |c| {+ {+ let mut m = members.borrow_mut();+ m.retain(|x| *x != id);+ if c.is_active() {+ m.push(id.clone());+ }+ }+ sync();+ });+ }+ sync();++ if let Some(g) = group.as_ref() {+ let danger = adw::PreferencesGroup::new();+ let del = gtk::Button::builder()+ .label("Delete group chat")+ .css_classes(["destructive-action"])+ .halign(gtk::Align::Center)+ .build();+ let (ui2, dialog2, id, gname) = (+ ui.clone(),+ dialog.clone(),+ g["id"].as_str().unwrap_or_default().to_owned(),+ g["name"].as_str().unwrap_or("").to_owned(),+ );+ del.connect_clicked(move |_| {+ dialog2.close();+ confirm_delete(&ui2, &id, &gname, true);+ });+ danger.add(&del);+ page.add(&danger);+ }+ view.set_content(Some(&page));++ let (ui2, dialog2) = (ui.clone(), dialog.clone());+ save.connect_clicked(move |btn| {+ let m = members.borrow().clone();+ let typed = name.text().trim().to_owned();+ let final_name = if typed.is_empty() {+ m.iter()+ .filter_map(|id| checks.iter().find(|c| c.0 == *id).map(|c| c.1.clone()))+ .collect::<Vec<_>>()+ .join(", ")+ } else {+ typed+ };+ let (method, body) = match &group_id {+ Some(id) => (+ "updateBot",+ json!({"id": id, "name": final_name, "members": m}),+ ),+ None => (+ "createBot",+ json!({"id": "", "kind": "group", "name": final_name, "members": m}),+ ),+ };+ btn.set_sensitive(false);+ let (ui3, dialog3, btn2) = (ui2.clone(), dialog2.clone(), btn.clone());+ client::call(method, body, move |r| match r {+ Ok(v) => {+ let bot = v["bot"].clone();+ let id = bot["id"].as_str().unwrap_or_default().to_owned();+ {+ let mut st = ui3.state.borrow_mut();+ st.bots.insert(id.clone(), bot);+ if is_new {+ st.current = Some(id);+ st.open_thread = None;+ }+ }+ dialog3.close();+ ui3.split.set_show_content(true);+ ui::schedule(&ui3);+ }+ Err(e) => {+ btn2.set_sensitive(true);+ ui::toast(&ui3, &e);+ }+ });+ });+ dialog.present(Some(&ui.window));+}++fn confirm_delete(ui: &App, id: &str, name: &str, group: bool) {+ let alert = adw::AlertDialog::new(+ Some(&format!("Delete {name}?")),+ Some(if group {+ "The group chat is removed. Its bots stay."+ } else {+ "The conversation is removed. Files it changed stay as they are."+ }),+ );+ alert.add_responses(&[("cancel", "Cancel"), ("delete", "Delete")]);+ alert.set_response_appearance("delete", adw::ResponseAppearance::Destructive);+ let id = id.to_owned();+ alert.connect_response(None, move |_, r| {+ if r == "delete" {+ client::call("deleteBot", json!({"botId": id}), |_| {});+ }+ });+ alert.present(Some(&ui.window));+}+fn client_seed() -> usize {std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)@@ -543,6 +770,7 @@ pub fn bot_menu(ui: &App) -> gtk::Popover {};let Some(bot) = bot else { return pop };let id = bot["id"].as_str().unwrap_or_default().to_owned();+ let group = bot["kind"] == "group";let add = |label: &str, destructive: bool, f: Box<dyn Fn()>| {let b = gtk::Button::builder().label(label)@@ -560,11 +788,19 @@ pub fn bot_menu(ui: &App) -> gtk::Popover {};{let (ui2, bot2) = (ui.clone(), bot.clone());- add(- "Edit profile",- false,- Box::new(move || editor(&ui2, Some(bot2.clone()))),- );+ if group {+ add(+ "Edit group",+ false,+ Box::new(move || group_editor(&ui2, Some(bot2.clone()))),+ );+ } else {+ add(+ "Edit profile",+ false,+ Box::new(move || editor(&ui2, Some(bot2.clone()))),+ );+ }}{let (id2, pinned) = (id.clone(), bot["pinned"].as_bool().unwrap_or(false));@@ -576,7 +812,7 @@ pub fn bot_menu(ui: &App) -> gtk::Popover {}),);}- {+ if !group {let id2 = id.clone();add("New session",@@ -591,23 +827,13 @@ pub fn bot_menu(ui: &App) -> gtk::Popover {bot["name"].as_str().unwrap_or("").to_owned(),);add(- "Delete bot…",+ if group {+ "Delete group…"+ } else {+ "Delete bot…"+ },true,- Box::new(move || {- let alert = adw::AlertDialog::new(- Some(&format!("Delete {name}?")),- Some("The conversation is removed. Files it changed stay as they are."),- );- alert.add_responses(&[("cancel", "Cancel"), ("delete", "Delete")]);- alert.set_response_appearance("delete", adw::ResponseAppearance::Destructive);- let id3 = id2.clone();- alert.connect_response(None, move |_, r| {- if r == "delete" {- client::call("deleteBot", json!({"botId": id3}), |_| {});- }- });- alert.present(Some(&ui2.window));- }),+ Box::new(move || confirm_delete(&ui2, &id2, &name, group)),);}pop.set_child(Some(&col));@@ -623,7 +849,9 @@ fn remote_screen_group() -> adw::PreferencesGroup {.title("Remote screen").description("See and control this computer from your iPhone, and let bots use it. The first time, your desktop asks you to allow screen sharing.").build();- let row = adw::SwitchRow::builder().title("Allow remote screen").build();+ let row = adw::SwitchRow::builder()+ .title("Allow remote screen")+ .build();let status = adw::ActionRow::builder().title("Status").build();status.set_visible(false);group.add(&row);@@ -659,11 +887,15 @@ fn remote_screen_group() -> adw::PreferencesGroup {}row.connect_active_notify(move |row| {let show = show.clone();- client::call("setScreenEnabled", json!({"enabled": row.is_active()}), move |r| {- if let Ok(v) = r {- show(&v);- }- });+ client::call(+ "setScreenEnabled",+ json!({"enabled": row.is_active()}),+ move |r| {+ if let Ok(v) = r {+ show(&v);+ }+ },+ );});group}diff --git a/apps/linux/src/main.rs b/apps/linux/src/main.rsindex 7844a0a5..2def869d 100644--- a/apps/linux/src/main.rs+++ b/apps/linux/src/main.rs@@ -28,10 +28,16 @@ const CSS: &str = r#".composer textview, .composer text { background: transparent; }.notice-error { background: alpha(#e0443e, 0.12); border-radius: 12px; padding: 10px 12px; }.round { border-radius: 999px; min-width: 38px; min-height: 38px; padding: 0; }+.reply-btn { opacity: 0; transition: opacity 150ms ease-out; min-width: 28px; min-height: 28px; padding: 0; }+.reply-host:hover .reply-btn, .reply-btn:focus-visible { opacity: 1; }+.thread-chip { border-radius: 999px; padding: 3px 10px; background: alpha(currentColor, 0.06); }+.thread-chip:hover { background: alpha(currentColor, 0.1); }"#;fn main() -> gtk::glib::ExitCode {- let app = adw::Application::builder().application_id("com.pokai.Codync").build();+ let app = adw::Application::builder()+ .application_id("com.pokai.Codync")+ .build();app.connect_startup(|_| {let provider = gtk::CssProvider::new();provider.load_from_string(CSS);diff --git a/apps/linux/src/rows.rs b/apps/linux/src/rows.rsindex 779b0c41..dc425404 100644--- a/apps/linux/src/rows.rs+++ b/apps/linux/src/rows.rs@@ -1,7 +1,7 @@//! The rows a conversation is made of: bubbles, notices and approval cards.use crate::client;-use crate::ui::{App, State, folder, toast};+use crate::ui::{self, App, State, ago, folder, toast};use crate::{avatar, markup};use adw::prelude::*;use serde_json::{Value, json};@@ -241,3 +241,104 @@ pub fn permission_card(ui: &App, st: &State, e: &Value) -> gtk::Widget {}card.upcast()}++/// Who wrote a message in a group: their name in their color.+pub fn author_label(st: &State, id: Option<&str>) -> gtk::Widget {+ let bot = id.and_then(|id| st.bots.get(id));+ let name = bot+ .and_then(|b| b["name"].as_str())+ .unwrap_or("A deleted bot");+ let hex = avatar::color_of(+ bot.and_then(|b| b["avatarColor"].as_str())+ .unwrap_or("gray"),+ );+ gtk::Label::builder()+ .use_markup(true)+ .label(format!(+ "<span foreground=\"#{hex:06X}\">{}</span>",+ gtk::glib::markup_escape_text(name)+ ))+ .xalign(0.0)+ .css_classes(["small", "heading"])+ .margin_start(36)+ .margin_top(12)+ .build()+ .upcast()+}++/// A main-chat message with a "Reply in thread" button that shows on hover or focus.+pub fn with_reply(ui: &App, w: >k::Widget, end: bool, root: &str) -> gtk::Widget {+ let host = gtk::Box::builder()+ .spacing(4)+ .css_classes(["reply-host"])+ .build();+ if end {+ host.set_halign(gtk::Align::End);+ }+ let btn = gtk::Button::builder()+ .icon_name("mail-reply-sender-symbolic")+ .tooltip_text("Reply in thread")+ .css_classes(["flat", "circular", "reply-btn"])+ .valign(gtk::Align::Center)+ .build();+ let (ui2, root) = (ui.clone(), root.to_owned());+ btn.connect_clicked(move |_| ui::open_thread(&ui2, &root));+ if end {+ host.append(&btn);+ host.append(w);+ } else {+ host.append(w);+ host.append(&btn);+ }+ host.upcast()+}++/// Under a message with a thread (Slack's): who replied, how many, how recently.+pub fn thread_chip(ui: &App, st: &State, e: &Value, end: bool) -> Option<gtk::Widget> {+ let t = &e["data"]["thread"];+ let count = t["count"].as_i64().filter(|c| *c > 0)?;+ let inner = gtk::Box::builder().spacing(6).build();+ let faces = gtk::Box::builder().spacing(2).build();+ for b in t["authors"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|a| st.bots.get(a.as_str()?))+ .take(3)+ {+ faces.append(&avatar::of(&st.bots, b, 18, false, ""));+ }+ inner.append(&faces);+ inner.append(+ >k::Label::builder()+ .label(if count == 1 {+ "1 reply".to_owned()+ } else {+ format!("{count} replies")+ })+ .css_classes(["small", "heading"])+ .build(),+ );+ inner.append(+ >k::Label::builder()+ .label(ago(t["lastAt"].as_i64().unwrap_or(0)))+ .css_classes(["small", "muted"])+ .build(),+ );+ inner.append(>k::Image::from_icon_name("go-next-symbolic"));+ let btn = gtk::Button::builder()+ .child(&inner)+ .tooltip_text("View thread")+ .css_classes(["flat", "thread-chip"])+ .halign(if end {+ gtk::Align::End+ } else {+ gtk::Align::Start+ })+ .margin_start(if end { 0 } else { 36 })+ .margin_top(4)+ .build();+ let (ui2, root) = (ui.clone(), e["id"].as_str().unwrap_or_default().to_owned());+ btn.connect_clicked(move |_| ui::open_thread(&ui2, &root));+ Some(btn.upcast())+}diff --git a/apps/linux/src/ui.rs b/apps/linux/src/ui.rsindex 435f3de9..cedfed79 100644--- a/apps/linux/src/ui.rs+++ b/apps/linux/src/ui.rs@@ -1,7 +1,9 @@//! Main window: roster sidebar + conversation (Grok Bot's desktop layout).use crate::client::{self, Event};-use crate::rows::{agent_bubble, notice, permission_card, user_bubble};+use crate::rows::{+ agent_bubble, author_label, notice, permission_card, thread_chip, user_bubble, with_reply,+};use crate::{avatar, dialogs};use adw::prelude::*;use serde_json::{Value, json};@@ -16,9 +18,88 @@ pub struct State {pub usage: Value,pub hello: Value,pub current: Option<String>,+ /// Root entry of the thread open beside the current chat.+ pub open_thread: Option<String>,pub online: bool,}+/// A message box: send, or stop while the chat (or thread) is working. In a group,+/// typing `@` suggests its bots.+struct Composer {+ view: gtk::TextView,+ send_btn: gtk::Button,+ stop_btn: gtk::Button,+ mentions: gtk::Box,+ mentions_rev: gtk::Revealer,+ root: gtk::Box,+}++fn composer() -> Composer {+ let view = gtk::TextView::builder()+ .wrap_mode(gtk::WrapMode::WordChar)+ .accepts_tab(false)+ .hexpand(true)+ .top_margin(4)+ .bottom_margin(4)+ .build();+ let frame = gtk::ScrolledWindow::builder()+ .child(&view)+ .max_content_height(160)+ .propagate_natural_height(true)+ .hscrollbar_policy(gtk::PolicyType::Never)+ .css_classes(["composer"])+ .hexpand(true)+ .build();+ let send_btn = gtk::Button::builder()+ .icon_name("go-up-symbolic")+ .tooltip_text("Send")+ .css_classes(["round", "accent-fill"])+ .valign(gtk::Align::End)+ .build();+ let stop_btn = gtk::Button::builder()+ .icon_name("media-playback-stop-symbolic")+ .tooltip_text("Stop")+ .css_classes(["round"])+ .valign(gtk::Align::End)+ .build();+ let row = gtk::Box::builder()+ .spacing(8)+ .margin_start(12)+ .margin_end(12)+ .margin_top(8)+ .margin_bottom(12)+ .build();+ row.append(&frame);+ row.append(&stop_btn);+ row.append(&send_btn);+ let mentions = gtk::Box::builder()+ .spacing(6)+ .margin_start(12)+ .margin_end(12)+ .margin_top(8)+ .build();+ let mentions_rev = gtk::Revealer::builder()+ .transition_type(gtk::RevealerTransitionType::SlideUp)+ .child(+ >k::ScrolledWindow::builder()+ .vscrollbar_policy(gtk::PolicyType::Never)+ .child(&mentions)+ .build(),+ )+ .build();+ let root = gtk::Box::new(gtk::Orientation::Vertical, 0);+ root.append(&mentions_rev);+ root.append(&row);+ Composer {+ view,+ send_btn,+ stop_btn,+ mentions,+ mentions_rev,+ root,+ }+}+pub struct Ui {pub window: adw::ApplicationWindow,pub toasts: adw::ToastOverlay,@@ -28,21 +109,36 @@ pub struct Ui {banner: adw::Banner,title: adw::WindowTitle,head_avatar: gtk::Box,- thread: gtk::Box,+ chat_list: gtk::Box,scroller: gtk::ScrolledWindow,- composer: gtk::TextView,- send_btn: gtk::Button,- stop_btn: gtk::Button,+ compose: Composer,+ pane: gtk::Revealer,+ pane_title: adw::WindowTitle,+ pane_list: gtk::Box,+ pane_scroller: gtk::ScrolledWindow,+ reply: Composer,content_stack: gtk::Stack,chat_buttons: [gtk::Widget; 2],/// Bot shown in the last render; switching bots jumps to the newest message.shown_bot: RefCell<String>,+ /// Thread shown in the last render; opening one jumps to its newest reply.+ shown_thread: RefCell<String>,pub state: RefCell<State>,rendering: std::cell::Cell<bool>,}pub type App = Rc<Ui>;+impl Ui {+ fn composer(&self, in_thread: bool) -> &Composer {+ if in_thread {+ &self.reply+ } else {+ &self.compose+ }+ }+}+pub fn build(app: &adw::Application) {// Sidebarlet roster = gtk::ListBox::builder()@@ -72,6 +168,10 @@ pub fn build(app: &adw::Application) {.icon_name("document-edit-symbolic").tooltip_text("New bot").build();+ let group_btn = gtk::Button::builder()+ .icon_name("system-users-symbolic")+ .tooltip_text("New group chat")+ .build();let settings_btn = gtk::Button::builder().icon_name("emblem-system-symbolic").tooltip_text("Settings & pairing")@@ -79,6 +179,7 @@ pub fn build(app: &adw::Application) {let side_header = adw::HeaderBar::new();side_header.pack_start(&settings_btn);side_header.pack_end(&new_btn);+ side_header.pack_end(&group_btn);let side_view = adw::ToolbarView::new();side_view.add_top_bar(&side_header);side_view.set_content(Some(&sidebar_box));@@ -101,63 +202,66 @@ pub fn build(app: &adw::Application) {let content_header = adw::HeaderBar::builder().title_widget(&head).build();content_header.pack_end(&menu_btn);content_header.pack_end(&trace_btn);- let thread = gtk::Box::builder()- .orientation(gtk::Orientation::Vertical)- .spacing(4)- .margin_start(16)- .margin_end(16)- .margin_top(12)- .margin_bottom(12)- .build();+ let chat_list = entry_list();let clamp = adw::Clamp::builder().maximum_size(760)- .child(&thread)+ .child(&chat_list).build();let scroller = gtk::ScrolledWindow::builder().vexpand(true).child(&clamp).build();- let composer = gtk::TextView::builder()- .wrap_mode(gtk::WrapMode::WordChar)- .accepts_tab(false)- .hexpand(true)- .top_margin(4)- .bottom_margin(4)+ let compose = composer();+ let convo = gtk::Box::new(gtk::Orientation::Vertical, 0);+ convo.append(&scroller);+ convo.append(>k::Separator::new(gtk::Orientation::Horizontal));+ convo.append(&compose.root);+ convo.set_hexpand(true);++ // Thread pane beside the chat (Slack's).+ let pane_title = adw::WindowTitle::new("Thread", "");+ let close_thread = gtk::Button::builder()+ .icon_name("window-close-symbolic")+ .tooltip_text("Close thread")+ .css_classes(["flat", "circular"])+ .valign(gtk::Align::Center).build();- let composer_frame = gtk::ScrolledWindow::builder()- .child(&composer)- .max_content_height(160)- .propagate_natural_height(true)- .hscrollbar_policy(gtk::PolicyType::Never)- .css_classes(["composer"])- .hexpand(true)+ let pane_head = gtk::Box::builder()+ .spacing(8)+ .margin_start(12)+ .margin_end(8)+ .margin_top(6)+ .margin_bottom(6).build();- let send_btn = gtk::Button::builder()- .icon_name("go-up-symbolic")- .tooltip_text("Send")- .css_classes(["round", "accent-fill"])- .valign(gtk::Align::End)+ pane_title.set_hexpand(true);+ pane_head.append(&pane_title);+ pane_head.append(&close_thread);+ let pane_list = entry_list();+ let pane_scroller = gtk::ScrolledWindow::builder()+ .vexpand(true)+ .hscrollbar_policy(gtk::PolicyType::Never)+ .child(&pane_list).build();- let stop_btn = gtk::Button::builder()- .icon_name("media-playback-stop-symbolic")- .tooltip_text("Stop")- .css_classes(["round"])- .valign(gtk::Align::End)+ let reply = composer();+ let pane_box = gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .width_request(380).build();- let composer_row = gtk::Box::builder()- .spacing(8)- .margin_start(12)- .margin_end(12)- .margin_top(8)- .margin_bottom(12)+ pane_box.append(&pane_head);+ pane_box.append(>k::Separator::new(gtk::Orientation::Horizontal));+ pane_box.append(&pane_scroller);+ pane_box.append(>k::Separator::new(gtk::Orientation::Horizontal));+ pane_box.append(&reply.root);+ let pane_outer = gtk::Box::new(gtk::Orientation::Horizontal, 0);+ pane_outer.append(>k::Separator::new(gtk::Orientation::Vertical));+ pane_outer.append(&pane_box);+ let pane = gtk::Revealer::builder()+ .transition_type(gtk::RevealerTransitionType::SlideLeft)+ .child(&pane_outer).build();- composer_row.append(&composer_frame);- composer_row.append(&stop_btn);- composer_row.append(&send_btn);- let convo = gtk::Box::new(gtk::Orientation::Vertical, 0);- convo.append(&scroller);- convo.append(>k::Separator::new(gtk::Orientation::Horizontal));- convo.append(&composer_row);+ let chat_area = gtk::Box::new(gtk::Orientation::Horizontal, 0);+ chat_area.append(&convo);+ chat_area.append(&pane);let empty = adw::StatusPage::builder().title("Your coding agents, as teammates").description("Pick a bot, or create one for each kind of work and point it at a project.")@@ -165,7 +269,7 @@ pub fn build(app: &adw::Application) {.build();let content_stack = gtk::Stack::new();content_stack.add_named(&empty, Some("empty"));- content_stack.add_named(&convo, Some("chat"));+ content_stack.add_named(&chat_area, Some("chat"));let content_view = adw::ToolbarView::new();content_view.add_top_bar(&content_header);content_view.set_content(Some(&content_stack));@@ -202,14 +306,18 @@ pub fn build(app: &adw::Application) {banner,title,head_avatar,- thread,+ chat_list,scroller,- composer,- send_btn,- stop_btn,+ compose,+ pane,+ pane_title,+ pane_list,+ pane_scroller,+ reply,content_stack,chat_buttons: [trace_btn.clone().upcast(), menu_btn.clone().upcast()],shown_bot: RefCell::new(String::new()),+ shown_thread: RefCell::new(String::new()),state: RefCell::new(State::default()),rendering: std::cell::Cell::new(false),});@@ -218,7 +326,11 @@ pub fn build(app: &adw::Application) {{let ui2 = ui.clone();ui.roster.connect_row_activated(move |_, row| {- ui2.state.borrow_mut().current = Some(row.widget_name().to_string());+ {+ let mut st = ui2.state.borrow_mut();+ st.current = Some(row.widget_name().to_string());+ st.open_thread = None;+ }ui2.split.set_show_content(true);mark_read(&ui2);render(&ui2);@@ -228,6 +340,17 @@ pub fn build(app: &adw::Application) {let ui2 = ui.clone();new_btn.connect_clicked(move |_| dialogs::editor(&ui2, None));}+ {+ let ui2 = ui.clone();+ group_btn.connect_clicked(move |_| dialogs::group_editor(&ui2, None));+ }+ {+ let ui2 = ui.clone();+ close_thread.connect_clicked(move |_| {+ ui2.state.borrow_mut().open_thread = None;+ schedule(&ui2);+ });+ }{let ui2 = ui.clone();settings_btn.connect_clicked(move |_| dialogs::settings(&ui2));@@ -240,13 +363,41 @@ pub fn build(app: &adw::Application) {let ui2 = ui.clone();menu_btn.set_create_popup_func(move |btn| btn.set_popover(Some(&dialogs::bot_menu(&ui2))));}+ wire_composer(&ui, false);+ wire_composer(&ui, true);+ // Keep relative times fresh.+ {+ let ui2 = ui.clone();+ gtk::glib::timeout_add_seconds_local(30, move || {+ render_roster(&ui2);+ gtk::glib::ControlFlow::Continue+ });+ }++ ui.window.present();+ connect(&ui);+}++fn entry_list() -> gtk::Box {+ gtk::Box::builder()+ .orientation(gtk::Orientation::Vertical)+ .spacing(4)+ .margin_start(16)+ .margin_end(16)+ .margin_top(12)+ .margin_bottom(12)+ .build()+}++fn wire_composer(ui: &App, in_thread: bool) {+ let c = ui.composer(in_thread);{let ui2 = ui.clone();- ui.send_btn.connect_clicked(move |_| send(&ui2));+ c.send_btn.connect_clicked(move |_| send(&ui2, in_thread));}{let ui2 = ui.clone();- ui.stop_btn.connect_clicked(move |_| {+ c.stop_btn.connect_clicked(move |_| {if let Some(id) = ui2.state.borrow().current.clone() {client::call("stop", json!({"botId": id}), |_| {});}@@ -259,30 +410,19 @@ pub fn build(app: &adw::Application) {if (key == gtk::gdk::Key::Return || key == gtk::gdk::Key::KP_Enter)&& !mods.contains(gtk::gdk::ModifierType::SHIFT_MASK){- send(&ui2);+ send(&ui2, in_thread);return gtk::glib::Propagation::Stop;}gtk::glib::Propagation::Proceed});- ui.composer.add_controller(keys);+ c.view.add_controller(keys);}{let ui2 = ui.clone();- ui.composer+ c.view.buffer()- .connect_changed(move |_| update_composer(&ui2));+ .connect_changed(move |_| update_composer(&ui2, in_thread));}- // Keep relative times fresh.- {- let ui2 = ui.clone();- gtk::glib::timeout_add_seconds_local(30, move || {- render_roster(&ui2);- gtk::glib::ControlFlow::Continue- });- }-- ui.window.present();- connect(&ui);}fn connect(ui: &App) {@@ -330,12 +470,12 @@ fn handle(ui: &App, ev: Event) {"bot" => {let bot = &m["bot"];let id = bot["id"].as_str().unwrap_or_default().to_owned();- // Group chats and threads are on the iPhone and Mac apps only for now.- if bot["deleted"].as_bool().unwrap_or(false) || bot["kind"] == "group" {+ if bot["deleted"].as_bool().unwrap_or(false) {st.bots.remove(&id);st.entries.remove(&id);if st.current.as_deref() == Some(&id) {st.current = None;+ st.open_thread = None;}} else {if let Some(old) = st.bots.get(&id) {@@ -344,7 +484,7 @@ fn handle(ui: &App, ev: Event) {st.bots.insert(id, bot.clone());}}- "entry" if m["entry"]["threadId"].is_null() => upsert(&mut st, m["entry"].clone()),+ "entry" => upsert(&mut st, m["entry"].clone()),_ => {}},}@@ -357,6 +497,14 @@ fn notify(ui: &App, old: &Value, new: &Value) {if ui.window.is_active() || new["notify"] == false || new["hidden"] == true {return;}+ // A bot's turn in a group is announced by the group.+ if [old, new].iter().any(|b| {+ b["workingChat"]+ .as_str()+ .is_some_and(|c| Some(c) != b["id"].as_str())+ }) {+ return;+ }let name = new["name"].as_str().unwrap_or("Bot");let (title, body) = match (old["status"].as_str(), new["status"].as_str()) {(Some(o), Some("needsInput")) if o != "needsInput" => (@@ -418,13 +566,56 @@ pub fn render(ui: &App) {ui.banner.set_revealed(!ui.state.borrow().online);render_usage(ui);render_roster(ui);- render_thread(ui);+ render_chat(ui);+ render_pane(ui);}pub fn working(b: &Value) -> bool {matches!(b["status"].as_str(), Some("working" | "needsInput"))}+/// Working in this lane: the chat `chat` (its main chat, or the thread on `thread`).+pub fn working_in(b: &Value, chat: &str, thread: Option<&str>) -> bool {+ working(b)+ && b["workingChat"].as_str().or(b["id"].as_str()) == Some(chat)+ && b["workingThread"].as_str() == thread+}++fn is_group(b: &Value) -> bool {+ b["kind"] == "group"+}++fn members<'a>(st: &'a State, group: &Value) -> Vec<&'a Value> {+ group["members"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(|m| st.bots.get(m.as_str()?))+ .collect()+}++fn member_names(st: &State, group: &Value) -> String {+ members(st, group)+ .iter()+ .filter_map(|b| b["name"].as_str())+ .collect::<Vec<_>>()+ .join(" · ")+}++/// The `@partial` being typed at the end of a group message, if any.+fn mention_query(draft: &str) -> Option<&str> {+ let at = draft.rfind('@')?;+ if draft[..at]+ .chars()+ .next_back()+ .is_some_and(|c| !c.is_whitespace())+ {+ return None;+ }+ let q = &draft[at + 1..];+ (!q.contains('\n') && q.chars().count() <= 24).then_some(q)+}+pub fn backend_name(st: &State, id: &str) -> String {st.hello["backends"].as_array()@@ -525,13 +716,7 @@ fn render_roster(ui: &App) {.margin_top(6).margin_bottom(6).build();- row_box.append(&avatar::widget(- b["avatarShape"].as_str().unwrap_or("blob"),- b["avatarColor"].as_str().unwrap_or("blue"),- 40,- working(b),- status,- ));+ row_box.append(&avatar::of(&st.bots, b, 40, working(b), status));let text = gtk::Box::builder().orientation(gtk::Orientation::Vertical).hexpand(true)@@ -583,6 +768,9 @@ fn render_roster(ui: &App) {.as_str().map(str::to_owned).unwrap_or_else(|| {+ if is_group(b) {+ return member_names(&st, b);+ }format!("{} · {}",backend_name(&st, b["backend"].as_str().unwrap_or("")),@@ -628,7 +816,30 @@ fn is_chat(e: &Value) -> bool {}}-fn render_thread(ui: &App) {+fn clear(b: >k::Box) {+ while let Some(c) = b.first_child() {+ b.remove(&c);+ }+}++fn near_bottom(s: >k::ScrolledWindow) -> bool {+ let adj = s.vadjustment();+ adj.upper() - adj.value() - adj.page_size() < 120.0+}++fn scroll_to_end(s: >k::ScrolledWindow) {+ let adj = s.vadjustment();+ // Twice: labels finish wrapping (and the height settles) one frame later.+ gtk::glib::idle_add_local_once(move || {+ adj.set_value(adj.upper());+ let adj2 = adj.clone();+ gtk::glib::timeout_add_local_once(std::time::Duration::from_millis(60), move || {+ adj2.set_value(adj2.upper())+ });+ });+}++fn render_chat(ui: &App) {let st = ui.state.borrow();let Some(bot) = st.current.as_ref().and_then(|id| st.bots.get(id)) else {ui.content_stack.set_visible_child_name("empty");@@ -637,20 +848,17 @@ fn render_thread(ui: &App) {ui.title.set_subtitle("");return;};+ let id = bot["id"].as_str().unwrap_or_default();+ let group = is_group(bot);ui.content_stack.set_visible_child_name("chat");ui.chat_buttons.iter().for_each(|b| b.set_visible(true));- let switched = ui- .shown_bot- .replace(bot["id"].as_str().unwrap_or_default().to_owned())- != bot["id"].as_str().unwrap_or_default();- let near_bottom = switched || {- let adj = ui.scroller.vadjustment();- adj.upper() - adj.value() - adj.page_size() < 120.0- };+ let switched = *ui.shown_bot.replace(id.to_owned()) != *id;+ let stick = switched || near_bottom(&ui.scroller);ui.title.set_title(bot["name"].as_str().unwrap_or(""));let sub = match bot["status"].as_str() {Some("needsInput") => "Needs you".to_owned(),Some("working") => "Working".to_owned(),+ _ if group => member_names(&st, bot),_ => format!("{} · {}",backend_name(&st, bot["backend"].as_str().unwrap_or("")),@@ -658,43 +866,113 @@ fn render_thread(ui: &App) {),};ui.title.set_subtitle(&sub);- while let Some(c) = ui.head_avatar.first_child() {- ui.head_avatar.remove(&c);- }- ui.head_avatar.append(&avatar::widget(- bot["avatarShape"].as_str().unwrap_or("blob"),- bot["avatarColor"].as_str().unwrap_or("blue"),- 28,- working(bot),- "",- ));+ clear(&ui.head_avatar);+ ui.head_avatar+ .append(&avatar::of(&st.bots, bot, 28, working(bot), ""));- while let Some(c) = ui.thread.first_child() {- ui.thread.remove(&c);- }+ clear(&ui.chat_list);let entries: Vec<&Value> = st.entries- .get(bot["id"].as_str().unwrap_or_default())- .map(|l| l.iter().filter(|e| is_chat(e)).collect())+ .get(id)+ .map(|l| l.iter().filter(|e| e["threadId"].is_null()).collect()).unwrap_or_default();- if entries.is_empty() {+ if !entries.iter().any(|e| is_chat(e)) {let intro = adw::StatusPage::builder().title(bot["name"].as_str().unwrap_or(""))- .description(format!(+ .build();+ if group {+ intro.set_description(Some(&format!(+ "{}\n\nEveryone answers in turn unless you @mention someone.",+ member_names(&st, bot)+ )));+ } else {+ intro.set_description(Some(&format!("{} in {}\n\n{}\n\nTell it what you need.",backend_name(&st, bot["backend"].as_str().unwrap_or("")),bot["cwd"].as_str().unwrap_or(""),bot["description"].as_str().unwrap_or("")- ))- .build();- ui.thread.append(&intro);+ )));+ }+ ui.chat_list.append(&intro);+ }+ append_entries(ui, &st, &ui.chat_list, bot, &entries, true);+ if working_in(bot, id, None) {+ ui.chat_list.append(&working_row(&st, bot));}- let mut last_author = "";+ update_composer_for(ui, &st, bot, false);+ if stick {+ scroll_to_end(&ui.scroller);+ }+}++/// The thread open beside the chat: its root, the replies and a composer that replies there.+fn render_pane(ui: &App) {+ let st = ui.state.borrow();+ let (Some(bot), Some(root_id)) = (+ st.current.as_ref().and_then(|id| st.bots.get(id)),+ st.open_thread.as_deref(),+ ) else {+ ui.pane.set_reveal_child(false);+ ui.shown_thread.replace(String::new());+ return;+ };+ let id = bot["id"].as_str().unwrap_or_default();+ ui.pane.set_reveal_child(true);+ ui.pane_title+ .set_subtitle(bot["name"].as_str().unwrap_or(""));+ let switched = *ui.shown_thread.replace(root_id.to_owned()) != *root_id;+ let stick = switched || near_bottom(&ui.pane_scroller);+ clear(&ui.pane_list);+ let all = st.entries.get(id).map(Vec::as_slice).unwrap_or_default();+ if let Some(root) = all.iter().find(|e| e["id"] == root_id) {+ append_entries(ui, &st, &ui.pane_list, bot, &[root], false);+ }+ let replies: Vec<&Value> = all.iter().filter(|e| e["threadId"] == root_id).collect();+ let n = replies.iter().filter(|e| is_chat(e)).count();+ ui.pane_list.append(+ >k::Label::builder()+ .label(match n {+ 0 => "No replies yet".to_owned(),+ 1 => "1 reply".to_owned(),+ _ => format!("{n} replies"),+ })+ .xalign(0.0)+ .css_classes(["small", "muted"])+ .margin_top(12)+ .build(),+ );+ ui.pane_list+ .append(>k::Separator::new(gtk::Orientation::Horizontal));+ append_entries(ui, &st, &ui.pane_list, bot, &replies, false);+ if working_in(bot, id, Some(root_id)) {+ ui.pane_list.append(&working_row(&st, bot));+ }+ update_composer_for(ui, &st, bot, true);+ if stick {+ scroll_to_end(&ui.pane_scroller);+ }+ if switched {+ ui.reply.view.grab_focus();+ }+}++/// Chat-visible entries with time separators (gaps > 1 h) and author grouping.+/// `main`: the main chat, where messages can start threads and show their summary.+fn append_entries(+ ui: &App,+ st: &State,+ list: >k::Box,+ chat: &Value,+ entries: &[&Value],+ main: bool,+) {+ let group = is_group(chat);+ let mut last_author = String::new();let mut last_time = 0i64;- for e in entries {+ for e in entries.iter().filter(|e| is_chat(e)) {let at = e["createdAt"].as_i64().unwrap_or(0);if at - last_time > 3_600_000 {- ui.thread.append(+ list.append(>k::Label::builder().label(ago(at)).css_classes(["small", "muted"])@@ -702,135 +980,227 @@ fn render_thread(ui: &App) {.margin_bottom(6).build(),);- last_author = "";+ last_author.clear();}last_time = at;let kind = e["kind"].as_str().unwrap_or_default();- let start = kind != last_author;+ // In a group each bot is its own author.+ let author = match kind {+ "agent" => format!("agent:{}", e["data"]["author"].as_str().unwrap_or("")),+ k => k.to_owned(),+ };+ let start = author != last_author;last_author = if kind == "user" || kind == "agent" {- kind+ author} else {- ""+ String::new()+ };+ let entry_id = e["id"].as_str().unwrap_or_default();+ let author_id = e["data"]["author"].as_str();+ let reply = |w: gtk::Widget, end: bool| {+ // Local echoes have no id on the host yet.+ if main && !entry_id.starts_with("local-") {+ with_reply(ui, &w, end, entry_id)+ } else {+ w+ }};match kind {- "user" => ui.thread.append(&user_bubble(e, working(bot), start)),- "agent" => ui.thread.append(&agent_bubble(e, bot, start)),- "permission" => ui.thread.append(&permission_card(ui, &st, e)),- _ => ui.thread.append(¬ice(e)),+ "user" => list.append(&reply(user_bubble(e, working(chat), start), true)),+ "agent" => {+ let deleted = json!({"avatarColor": "gray"});+ let speaker = if group {+ if start {+ list.append(&author_label(st, author_id));+ }+ author_id.and_then(|a| st.bots.get(a)).unwrap_or(&deleted)+ } else {+ chat+ };+ list.append(&reply(agent_bubble(e, speaker, start), false));+ }+ "permission" => {+ if group {+ list.append(&author_label(st, author_id));+ }+ list.append(&permission_card(ui, st, e));+ }+ _ => list.append(¬ice(e)),+ }+ if main && let Some(chip) = thread_chip(ui, st, e, kind == "user") {+ list.append(&chip);}}- if working(bot) {- let row = gtk::Box::builder().spacing(8).margin_top(10).build();- row.append(&avatar::widget(- bot["avatarShape"].as_str().unwrap_or("blob"),- bot["avatarColor"].as_str().unwrap_or("blue"),- 28,- true,- "",- ));- let col = gtk::Box::new(gtk::Orientation::Vertical, 2);- col.append(- >k::Label::builder()- .label("•••")- .css_classes(["bubble", "bubble-agent", "muted"])- .halign(gtk::Align::Start)- .build(),- );- let act = bot["activity"]- .as_str()- .filter(|s| !s.is_empty())- .unwrap_or("Working…");- col.append(- >k::Label::builder()- .label(act)- .xalign(0.0)- .css_classes([- "small",- if bot["status"] == "needsInput" {- "needs-text"- } else {- "dim-label"- },- ])- .build(),- );- row.append(&col);- ui.thread.append(&row);- }- update_composer_for(ui, bot);- if near_bottom {- let adj = ui.scroller.vadjustment();- // Twice: labels finish wrapping (and the height settles) one frame later.- gtk::glib::idle_add_local_once(move || {- adj.set_value(adj.upper());- let adj2 = adj.clone();- gtk::glib::timeout_add_local_once(std::time::Duration::from_millis(60), move || {- adj2.set_value(adj2.upper())- });- });- }}-fn update_composer(ui: &App) {+fn working_row(st: &State, bot: &Value) -> gtk::Box {+ let row = gtk::Box::builder().spacing(8).margin_top(10).build();+ row.append(&avatar::of(&st.bots, bot, 28, true, ""));+ let col = gtk::Box::new(gtk::Orientation::Vertical, 2);+ col.append(+ >k::Label::builder()+ .label("•••")+ .css_classes(["bubble", "bubble-agent", "muted"])+ .halign(gtk::Align::Start)+ .build(),+ );+ let act = bot["activity"]+ .as_str()+ .filter(|s| !s.is_empty())+ .unwrap_or("Working…");+ col.append(+ >k::Label::builder()+ .label(act)+ .xalign(0.0)+ .css_classes([+ "small",+ if bot["status"] == "needsInput" {+ "needs-text"+ } else {+ "dim-label"+ },+ ])+ .build(),+ );+ row.append(&col);+ row+}++/// Starts (or opens) the thread on a main-chat message and pages in its replies.+pub fn open_thread(ui: &App, root: &str) {+ let Some(bot) = ui.state.borrow().current.clone() else {+ return;+ };+ ui.state.borrow_mut().open_thread = Some(root.to_owned());+ schedule(ui);+ let ui2 = ui.clone();+ client::call(+ "thread",+ json!({"botId": bot, "rootId": root}),+ move |r| match r {+ Ok(v) => {+ let mut st = ui2.state.borrow_mut();+ for e in v["entries"].as_array().into_iter().flatten() {+ upsert(&mut st, e.clone());+ }+ drop(st);+ schedule(&ui2);+ }+ Err(e) => toast(&ui2, &e),+ },+ );+}++fn update_composer(ui: &App, in_thread: bool) {let st = ui.state.borrow();if let Some(bot) = st.current.as_ref().and_then(|id| st.bots.get(id)) {- update_composer_for(ui, bot);+ update_composer_for(ui, &st, bot, in_thread);}}-fn update_composer_for(ui: &App, bot: &Value) {- let buf = ui.composer.buffer();- let has_text = !buf+fn update_composer_for(ui: &App, st: &State, chat: &Value, in_thread: bool) {+ let c = ui.composer(in_thread);+ let buf = c.view.buffer();+ let text = buf.text(&buf.start_iter(), &buf.end_iter(), false)- .trim()- .is_empty();- ui.stop_btn.set_visible(working(bot) && !has_text);- ui.send_btn.set_visible(!working(bot) || has_text);- ui.send_btn.set_sensitive(has_text);+ .to_string();+ let has_text = !text.trim().is_empty();+ let lane = if in_thread {+ st.open_thread.as_deref()+ } else {+ None+ };+ let busy = working_in(chat, chat["id"].as_str().unwrap_or_default(), lane);+ c.stop_btn.set_visible(busy && !has_text);+ c.send_btn.set_visible(!busy || has_text);+ c.send_btn.set_sensitive(has_text);++ // `@` suggests the group's bots.+ clear(&c.mentions);+ let mut any = false;+ if is_group(chat)+ && let Some(q) = mention_query(&text)+ {+ let q = q.to_lowercase();+ for m in members(st, chat) {+ let name = m["name"].as_str().unwrap_or_default().to_owned();+ if !name.to_lowercase().contains(&q) {+ continue;+ }+ let inner = gtk::Box::builder().spacing(6).build();+ inner.append(&avatar::of(&st.bots, m, 18, false, ""));+ inner.append(>k::Label::new(Some(&name)));+ let chip = gtk::Button::builder()+ .child(&inner)+ .tooltip_text(format!("Ask {name}"))+ .css_classes(["flat", "thread-chip"])+ .build();+ let (buf2, view, text2) = (buf.clone(), c.view.clone(), text.clone());+ chip.connect_clicked(move |_| {+ if let Some(at) = text2.rfind('@') {+ buf2.set_text(&format!("{}@{name} ", &text2[..at]));+ buf2.place_cursor(&buf2.end_iter());+ view.grab_focus();+ }+ });+ c.mentions.append(&chip);+ any = true;+ }+ }+ c.mentions_rev.set_reveal_child(any);}-fn send(ui: &App) {- let buf = ui.composer.buffer();+fn send(ui: &App, in_thread: bool) {+ let buf = ui.composer(in_thread).view.buffer();let text = buf.text(&buf.start_iter(), &buf.end_iter(), false).trim().to_owned();- let Some(bot) = ui.state.borrow().current.clone() else {+ let (bot, thread) = {+ let st = ui.state.borrow();+ let thread = if in_thread {+ st.open_thread.clone()+ } else {+ None+ };+ (st.current.clone(), thread)+ };+ let Some(bot) = bot else {return;};- if text.is_empty() {+ if text.is_empty() || (in_thread && thread.is_none()) {return;}buf.set_text("");let nonce = uuid::Uuid::new_v4().to_string();upsert(&mut ui.state.borrow_mut(),- json!({"id": format!("local-{nonce}"), "seq": i64::MAX, "botId": bot, "rev": 0, "kind": "user", "turn": 0,+ json!({"id": format!("local-{nonce}"), "seq": i64::MAX, "botId": bot, "threadId": thread, "rev": 0, "kind": "user", "turn": 0,"data": {"text": text, "status": "sending", "clientNonce": nonce}, "createdAt": now_ms(), "updatedAt": 0}),);schedule(ui);+ let mut body = json!({"botId": bot, "text": text, "clientNonce": nonce});+ if let Some(t) = thread {+ body["threadId"] = t.into();+ }let ui2 = ui.clone();- client::call(- "send",- json!({"botId": bot, "text": text, "clientNonce": nonce}),- move |r| {- let mut st = ui2.state.borrow_mut();- match r {- Ok(v) => upsert(&mut st, v["entry"].clone()),- Err(_) => {- if let Some(e) = st- .entries- .get_mut(&bot)- .and_then(|l| l.iter_mut().find(|e| e["id"] == format!("local-{nonce}")))- {- e["data"]["status"] = "failed".into();- }+ client::call("send", body, move |r| {+ let mut st = ui2.state.borrow_mut();+ match r {+ Ok(v) => upsert(&mut st, v["entry"].clone()),+ Err(_) => {+ if let Some(e) = st+ .entries+ .get_mut(&bot)+ .and_then(|l| l.iter_mut().find(|e| e["id"] == format!("local-{nonce}")))+ {+ e["data"]["status"] = "failed".into();}}- drop(st);- schedule(&ui2);- },- );+ }+ drop(st);+ schedule(&ui2);+ });}fn now_ms() -> i64 {@@ -852,3 +1222,17 @@ pub fn mark_read(ui: &App) {pub fn toast(ui: &App, text: &str) {ui.toasts.add_toast(adw::Toast::new(text));}++#[cfg(test)]+mod tests {+ use super::mention_query;++ #[test]+ fn mentions() {+ assert_eq!(mention_query("hi @al"), Some("al"));+ assert_eq!(mention_query("@"), Some(""));+ assert_eq!(mention_query("mail me@home"), None);+ assert_eq!(mention_query("no at"), None);+ assert_eq!(mention_query("@al\nnext"), None);+ }+}diff --git a/docs/groups-and-threads.md b/docs/groups-and-threads.mdnew file mode 100644index 00000000..9600ad11--- /dev/null+++ b/docs/groups-and-threads.md@@ -0,0 +1,68 @@+# Group chats and threads++Both features live in the host. Every client (iPhone, Mac, Linux, terminal) calls the same+methods and renders the same data: none of them routes messages, parses mentions or counts+replies itself.++## Words++- **Chat**: a bot's (or group's) one endless conversation. Entries with `threadId == null`.+- **Thread**: replies on one main-chat message (the *root*), Slack's "reply in thread".+ Entries with `threadId == <root entry id>`. Threads are flat: a reply can't start a thread.+- **Group**: a roster row (`kind: "group"`) holding several bots and the user. It has a+ transcript but no agent, folder or harness of its own.+- **Lane**: where a turn talks, `(chat, thread)`. `host/src/store.rs` `Lane`.++## Data (all over the existing sync: `bot` and `entry` events)++- Bot: `kind` (`agent` | `group`), `members` (group: bot ids, max 6), `workingChat` /+ `workingThread` (where the running turn talks). A group's `status` / `activity` are its busy+ member's (`"Alice: Writing a reply…"`); its `lastMessage` names who spoke (`"Alice: …"`).+- Entry: `threadId`; `data.author` (the bot that wrote it; every agent-made entry has one);+ on a root, `data.thread = {count, lastAt, authors}` (`authors`: bot ids and `"user"`, first+ reply first), kept up to date by the host.+- `sync` / `events` catch-up carries recent entries of chats *and* threads. Paging:+ `history` (main chat only), `thread` (a whole thread).++## Methods (`POST /api/<method>`, same on the E2E channel)++| Method | Body | Notes |+|---|---|---|+| `send` | `botId, text, clientNonce, threadId?` | `botId` is a bot or a group. `threadId` replies in that root's thread. Works in the relay mailbox too. |+| `thread` | `botId, rootId` | `{entries}`: the thread's replies, oldest first. |+| `createBot` | `{kind:"group", name, members}` | Returns the existing group when these exact bots already share one. |+| `updateBot` | `{id, name?, members?, pinned?, hidden?}` | A group can't become a bot or the reverse. |+| `deleteBot` | `botId` | A group's bots stay. A deleted bot leaves its groups. |+| `stop` | `botId` | For a group: ends its room turns (main and threads) and stops members working in it. |+| `respondPermission` | `entryId, optionId?` | Routed to `data.author`, so cards in a group reach the bot that asked. |+| `markRead` | `botId` | Unread counts include thread replies. |++## How a group answers (`host/src/group.rs`, Grok Bot's design)++- The user's message starts a *room turn* in its lane: up to 3 rounds, 10 replies in all.+- Who answers each round: the members @-mentioned since the user's last message (full+ name, name without spaces, or first word; `@all` / `@everyone`), or everyone if none is.+ Members speak one at a time; each round starts one member later.+- A member runs the turn in its **own main session** (its history is unified across chats),+ told who's in the room and what was said since it last spoke there, framed as+ `[Group chat: "<name>" - with …]`. Its final reply is the one message the room sees; replying+ `(pass)` says nothing. A round where nobody speaks ends the room turn.+- A new message in the same lane, or Stop, ends a running room turn before its next speaker.+- Tool calls, thoughts and permission cards of a member's group turn are written to the+ group (with `author`), not to the member's own chat. One "done" push per room turn.++## How a thread continues (`host/src/bot.rs`)++- In a bot's chat, a thread is its own ACP session. The first reply forks the chat's session+ (`session/fork`, e.g. Claude) so the thread starts from everything said so far; an agent+ that can't fork starts a fresh session given the root and the lines before it. Nothing said+ in the thread reaches the main chat's session.+- In a group, a thread is its own room: the room turn runs in the thread's lane and each+ member is shown the root and the thread's messages.++## Client checklist++Roster row for groups (member avatars), author label on group replies, the thread summary+under a root (opens the thread), "Reply in thread" on any main-chat message, a thread view+(root, replies, composer sending `threadId`), group create/edit (name, members), Stop in a+group calls `stop` with the group id.diff --git a/docs/structure.md b/docs/structure.mdindex 7c3214f1..0a473858 100644--- a/docs/structure.md+++ b/docs/structure.md@@ -15,5 +15,5 @@ Bot memory & teams ([context-and-memory](context-and-memory.md), [bot-collaborat- Files follow their language: Swift `UpperCamelCase.swift` named after the file's main type; Rust/TS `snake_case.rs` / `kebab-case.ts`.- One main type per file. Small private helpers of that type stay in it; a file of several small siblings takes the plural role (`ChatRows.swift`, `UsageViews.swift`, `Dialogs.swift`).- Type suffixes by role: full screen / sheet → `…View`; list item → `…Row`; card → `…Card`; chat bubble → `…Bubble`; window scene → `…Window`; `@Observable` state → `…Store` / `…Controller`; `ButtonStyle` → describes the effect (`PressScale`).-- One word per concept across Swift, Rust host and Linux: **bot** (the persona you message), **agent** (the harness it runs, `Backend` in code), **thread** (the endless chat; not conversation/session), **session** (the ACP session only), **trace** (full conversation sheet), **marketplace** for UI / **market** for its data, **computer** (a paired host, user-facing) vs **host** (code).+- One word per concept across Swift, Rust host and Linux: **bot** (the persona you message), **agent** (the harness it runs, `Backend` in code), **chat** (the endless conversation with a bot or group; not conversation/session), **thread** (replies on one chat message), **group** (a chat with several bots), **lane** (a chat or thread a turn talks in), **session** (the ACP session only), **trace** (full conversation sheet), **marketplace** for UI / **market** for its data, **computer** (a paired host, user-facing) vs **host** (code).- Linux mirrors the Swift feature names in its module names (`thread`, `editor`, `trace`, `settings`) when a file is split; don't invent new terms there.diff --git a/host/src/bot.rs b/host/src/bot.rsindex 49f9cbe2..cdb6ff44 100644--- a/host/src/bot.rs+++ b/host/src/bot.rs@@ -623,7 +623,8 @@ impl Actor {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.",+ 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));}@@ -639,7 +640,8 @@ impl Actor {.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.",+ 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"))}@@ -1024,7 +1026,7 @@ impl Actor {}}"plan" => {- let data = json!({"entries": u["entries"].clone()});+ let data = json!({"entries": u["entries"].clone(), "author": self.cfg.id});match &self.plan_entry {Some(id) => {self.hub.set_entry(id, &data);@@ -1153,8 +1155,8 @@ impl Actor {&& (force || flushed.elapsed() >= Duration::from_millis(300)){let data = match kind {- SegKind::Text => json!({"text": buf, "final": false}),- SegKind::Thought => json!({"text": buf}),+ 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();diff --git a/host/src/hub.rs b/host/src/hub.rsindex c6a83630..5831ee10 100644--- a/host/src/hub.rs+++ b/host/src/hub.rs@@ -330,6 +330,12 @@ impl Hub {}if before.status != after.status {push::live_activity_update(self, id, &after);+ // A group's Live Activity follows its busy member.+ for lane in [&before.lane, &after.lane].into_iter().flatten().filter(|l| l.chat != id) {+ if let Ok(Some(group)) = self.store.bot(&lane.chat) {+ push::live_activity_update(self, &lane.chat, &self.group_runtime(&group.config));+ }+ }}}diff --git a/host/src/tui/app.rs b/host/src/tui/app.rsindex 47a231b6..94569736 100644--- a/host/src/tui/app.rs+++ b/host/src/tui/app.rs@@ -24,6 +24,7 @@ pub enum After {Nothing,Hello,History(String),+ Thread,Dirs,Pairing,Backends,@@ -86,6 +87,12 @@ pub struct Bot {pub unread: i64,pub last_message: String,pub last_at: i64,+ /// A group chat: several bots and the user, no agent of its own.+ pub group: bool,+ pub members: Vec<String>,+ /// Where the running turn talks: a chat (`None` = its own) and a thread in it.+ pub working_chat: Option<String>,+ pub working_thread: Option<String>,}fn strs(v: &Value) -> Vec<String> {@@ -121,9 +128,18 @@ impl Bot {unread: v["unread"].as_i64().unwrap_or(0),last_message: s("lastMessage"),last_at: v["lastAt"].as_i64().unwrap_or(0),+ group: v["kind"] == "group",+ members: strs(&v["members"]),+ working_chat: v["workingChat"].as_str().map(str::to_owned),+ working_thread: v["workingThread"].as_str().map(str::to_owned),})}+ /// 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+ }+pub fn mark(&self) -> Mark {match self.status {Status::NeedsInput => Mark::Need,@@ -155,6 +171,8 @@ pub struct Entry {pub kind: Kind,pub data: Value,pub created_at: i64,+ /// The main-chat message whose thread this is in; `None` is the main chat.+ pub thread_id: Option<String>,}impl Entry {@@ -178,6 +196,7 @@ impl Entry {kind,data: v["data"].clone(),created_at: v["createdAt"].as_i64().unwrap_or(0),+ thread_id: v["threadId"].as_str().map(str::to_owned),},))}@@ -190,6 +209,11 @@ impl Entry {self.kind == Kind::Agent && self.data["final"].as_bool().unwrap_or(false)}+ /// What the chat shows as a message: the user's, and each turn's final reply.+ pub fn is_message(&self) -> bool {+ self.kind == Kind::User || self.is_final()+ }+pub fn pending(&self) -> bool {self.kind == Kind::Permission && self.data["status"] == "pending"}@@ -356,14 +380,16 @@ pub const FILTERS: [(&str, Option<Mark>); 5] = [#[derive(Clone, Copy, PartialEq, Eq, Debug)]pub enum Action {NewBot,+ NewGroup,RefreshAgents,Pair,Usage,Keys,}-pub const ACTIONS: [(&str, &str, Action); 5] = [+pub const ACTIONS: [(&str, &str, Action); 6] = [("New bot…", "n", Action::NewBot),+ ("New group chat…", "m", Action::NewGroup),("Refresh agents", "", Action::RefreshAgents),("Pair a phone…", "P", Action::Pair),("Usage", "U", Action::Usage),@@ -482,6 +508,23 @@ impl Form {}}+/// A group's bots: at most this many.+pub const MAX_MEMBERS: usize = 6;++/// Create a group chat, or rename one and change who's in it.+pub struct GroupForm {+ /// The group being edited; `None` creates one.+ pub group_id: Option<String>,+ pub name: Editor,+ /// Picked bot ids, in the order they were picked.+ pub members: Vec<String>,+ /// Typing the name (else moving in the bot list).+ pub on_name: bool,+ pub cursor: usize,+ pub error: Option<String>,+ pub saving: bool,+}+pub enum Overlay {Goto(Goto),Help(Editor),@@ -489,6 +532,7 @@ pub enum Overlay {Agents(AgentPicker),Folder(FolderPicker),Form(Box<Form>),+ Group(GroupForm),Usage,Pair(Option<String>),}@@ -502,9 +546,14 @@ pub struct Toast {#[derive(Clone)]pub enum Click {Bot(String),- Option { entry: String, option: String },+ Option {+ entry: String,+ option: String,+ },Filter(usize),Composer,+ /// The replies line under a message: opens its thread.+ Thread(String),}#[derive(Default)]@@ -551,6 +600,10 @@ pub struct App {/// Chat/trace viewport heights from the last draw, for page scrolling.pub chat_height: usize,pub chat_top: bool,+ /// The open thread's root entry in the selected chat; `None` shows the main chat.+ pub thread: Option<String>,+ /// A main-chat message picked to reply to in its thread (`r`, then j/k and ↵).+ pub pick: Option<String>,pub market: (Vec<Toggle>, Vec<Toggle>),reading: HashSet<String>,history_busy: HashSet<String>,@@ -591,6 +644,8 @@ impl App {width: Width::Wide,chat_height: 20,chat_top: false,+ thread: None,+ pick: None,market: (vec![], vec![]),reading: HashSet::new(),history_busy: HashSet::new(),@@ -630,9 +685,37 @@ impl App {c}+ /// A chat's entries in the lane on screen (main chat, or the open thread's replies), in display order.+ pub fn lane(&self, bot: &str) -> Vec<&Entry> {+ let thread = self.thread.as_deref();+ let mut v: Vec<&Entry> = self+ .entries+ .get(bot)+ .map(|m| m.values().filter(|e| e.thread_id.as_deref() == thread).collect())+ .unwrap_or_default();+ // A message sent mid-turn belongs after that turn's reply.+ v.sort_by_key(|e| (e.turn, e.seq));+ v+ }+pub fn pending(&self) -> Option<&Entry> {let id = self.selected.as_ref()?;- self.entries.get(id)?.values().rev().find(|e| e.pending())+ self.lane(id).into_iter().rev().find(|e| e.pending())+ }++ /// Where the composer's draft lives: per chat, and per thread in it.+ fn draft_key(&self) -> Option<String> {+ let id = self.selected.as_ref()?;+ Some(self.thread.as_ref().map_or_else(|| id.clone(), |root| format!("{id}#{root}")))+ }++ pub fn draft(&self) -> Editor {+ self.draft_key().and_then(|k| self.drafts.get(&k).cloned()).unwrap_or_default()+ }++ /// Name of an entry's author (a group reply's bot), as the apps show it.+ pub fn author_name(&self, id: Option<&str>) -> String {+ 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> {@@ -641,7 +724,12 @@ impl App {/// Whether every older entry of this bot is loaded.pub fn history_complete(&self, id: &str) -> bool {- self.history_done.contains(id) || self.entries.get(id).and_then(|m| m.keys().next()).is_none_or(|&s| s <= 1)+ self.history_done.contains(id) || self.oldest_main(id).is_none_or(|s| s <= 1)+ }++ /// Paging (`history`) covers the main chat only; thread replies don't count.+ fn oldest_main(&self, id: &str) -> Option<i64> {+ self.entries.get(id)?.values().find(|e| e.thread_id.is_none()).map(|e| e.seq)}pub fn chat_visible(&self) -> bool {@@ -655,6 +743,8 @@ impl App {fn select(&mut self, id: &str) {if self.selected.as_deref() != Some(id) {self.selected = Some(id.to_owned());+ self.thread = None;+ self.pick = None;self.chat_scroll = 0;self.trace_scroll = 0;self.trace_turn = None;@@ -686,6 +776,11 @@ impl App {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()) {+ self.open_thread(root);+ }}None => self.flash(match want {Mark::Need => "No bot needs you",@@ -735,7 +830,7 @@ impl App {self.reading.insert(id.clone());self.call("markRead", json!({"botId": id}), After::Nothing);}- if self.chat_top && self.chat_visible() {+ if self.chat_top && self.chat_visible() && self.thread.is_none() {self.load_history();}}@@ -745,7 +840,7 @@ impl App {if self.history_busy.contains(&id) || self.history_done.contains(&id) {return;}- let Some(oldest) = self.entries.get(&id).and_then(|m| m.keys().next().copied()) else { return };+ let Some(oldest) = self.oldest_main(&id) else { return };if oldest <= 1 {self.history_done.insert(id);return;@@ -786,7 +881,7 @@ impl App {Some("hello") if !v["usage"].is_null() => self.usage = v["usage"].clone(),Some("usage") => self.usage = v["usage"].clone(),Some("bot") => self.upsert_bot(&v["bot"]),- Some("entry") if v["entry"]["threadId"].is_null() => {+ Some("entry") => {if let Some((bot, e)) = Entry::parse(&v["entry"]) {self.entries.entry(bot).or_default().insert(e.seq, e);}@@ -797,12 +892,13 @@ impl App {fn upsert_bot(&mut self, v: &Value) {let Some(id) = v["id"].as_str() else { return };- // Group chats and threads are on the iPhone and Mac apps only for now.- if v["deleted"].as_bool().unwrap_or(false) || v["kind"] == "group" {+ if v["deleted"].as_bool().unwrap_or(false) {self.bots.remove(id);self.entries.remove(id);if self.selected.as_deref() == Some(id) {self.selected = None;+ self.thread = None;+ self.pick = None;self.chat_page = false;self.typing = false;}@@ -836,12 +932,17 @@ impl App {After::History(id) => {self.history_busy.remove(&id);}- After::Saved => {- if let Some(Overlay::Form(f)) = self.overlays.last_mut() {+ After::Saved => match self.overlays.last_mut() {+ Some(Overlay::Form(f)) => {f.saving = false;f.error = Some(e);}- }+ Some(Overlay::Group(g)) => {+ g.saving = false;+ g.error = Some(e);+ }+ _ => {}+ },After::Dirs => {if let Some(Overlay::Folder(p)) = self.overlays.last_mut() {p.error = Some(e);@@ -868,6 +969,13 @@ impl App {self.backends = v["backends"].as_array().cloned().unwrap_or_default();self.flash("Agents refreshed");}+ After::Thread => {+ for e in v["entries"].as_array().into_iter().flatten() {+ if let Some((bot, e)) = Entry::parse(e) {+ self.entries.entry(bot).or_default().entry(e.seq).or_insert(e);+ }+ }+ }After::History(id) => {self.history_busy.remove(&id);let list = v["entries"].as_array().cloned().unwrap_or_default();@@ -905,7 +1013,7 @@ impl App {}}After::Saved => {- let saved = self.overlays.iter().rposition(|o| matches!(o, Overlay::Form(_)));+ let saved = self.overlays.iter().rposition(|o| matches!(o, Overlay::Form(_) | Overlay::Group(_)));if let Some(i) = saved {self.overlays.truncate(i);}@@ -954,10 +1062,10 @@ impl App {let s = s.replace("\r\n", "\n").replace('\r', "\n");if let Some(ed) = self.top_editor() {ed.insert(&s);- } else if let Some(id) = self.selected.clone() {+ } else if let Some(key) = self.draft_key() {self.typing = true;self.focus = Focus::Chat;- self.drafts.entry(id).or_default().insert(&s);+ self.drafts.entry(key).or_default().insert(&s);}}@@ -967,6 +1075,7 @@ impl App {Overlay::Help(e) => Some(e),Overlay::Agents(a) => Some(&mut a.query),Overlay::Folder(p) => Some(&mut p.query),+ Overlay::Group(g) if g.on_name => Some(&mut g.name),Overlay::Form(f) => match f.current() {Field::Name => Some(&mut f.name),Field::Instructions => Some(&mut f.instructions),@@ -999,13 +1108,14 @@ impl App {}fn composer_key(&mut self, k: KeyEvent) {- let Some(id) = self.selected.clone() else {+ let (Some(id), Some(key)) = (self.selected.clone(), self.draft_key()) else {self.typing = false;return;};let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);let newline = k.modifiers.intersects(KeyModifiers::SHIFT | KeyModifiers::ALT);- let draft = self.drafts.entry(id.clone()).or_default();+ let thread = self.thread.clone();+ let draft = self.drafts.entry(key).or_default();match k.code {KeyCode::Esc => self.typing = false,KeyCode::Enter if newline => draft.insert("\n"),@@ -1018,7 +1128,11 @@ impl App {draft.clear();self.chat_scroll = 0;let nonce = uuid::Uuid::new_v4().to_string();- self.call("send", json!({"botId": id, "text": text, "clientNonce": nonce}), After::Nothing);+ let mut body = json!({"botId": id, "text": text, "clientNonce": nonce});+ if let Some(root) = thread {+ body["threadId"] = root.into();+ }+ self.call("send", body, After::Nothing);}KeyCode::Char('c') if ctrl => {if draft.text.is_empty() {@@ -1052,6 +1166,9 @@ impl App {let half = page(self.chat_height) / 2;let narrow = self.width == Width::Narrow;let roster_page = narrow && !self.chat_page;+ if self.pick.is_some() && self.pick_key(k) {+ return;+ }match k.code {KeyCode::Char('c') if ctrl => self.flash("q quits"),KeyCode::Char('d') if ctrl => self.scroll_focused(-half),@@ -1083,7 +1200,17 @@ impl App {self.answer_kind(c);}KeyCode::Char('n') => self.new_bot(),+ KeyCode::Char('m') => self.new_group(),KeyCode::Char('i') if !roster_page => self.start_typing(),+ KeyCode::Char('r') if !roster_page && self.selected.is_some() => {+ if self.thread.is_some() {+ self.start_typing();+ } else {+ self.chat_page = true;+ self.focus = Focus::Chat;+ self.step_pick(0);+ }+ }KeyCode::Enter => {if roster_page || self.focus == Focus::Roster {if self.selected.is_some() {@@ -1099,6 +1226,9 @@ impl App {if self.trace == TraceMode::Full {self.trace = TraceMode::Off;self.focus = Focus::Chat;+ } else if self.thread.is_some() {+ self.thread = None;+ self.chat_scroll = 0;} else if narrow && self.chat_page {self.chat_page = false;self.focus = Focus::Roster;@@ -1174,7 +1304,9 @@ impl App {}}KeyCode::Char('S') => {- if let Some(b) = self.bot() {+ if self.bot().is_some_and(|b| b.group) {+ self.flash("A group has no session of its own");+ } else if let Some(b) = self.bot() {let c = Confirm {title: format!("Start a new session for {}?", b.name),detail: "The agent forgets this conversation's context.".into(),@@ -1187,10 +1319,18 @@ impl App {}KeyCode::Char('x') => {if let Some(b) = self.bot() {+ let (detail, note) = if b.group {+ ("Its conversation goes away.".into(), "Its bots stay.".into())+ } else {+ (+ "Its conversation and settings go away.".into(),+ format!("Files in {} stay where they are.", tilde(&b.cwd, &self.home)),+ )+ };let c = Confirm {title: format!("Delete {}?", b.name),- detail: "Its conversation and settings go away.".into(),- note: format!("Files in {} stay where they are.", tilde(&b.cwd, &self.home)),+ detail,+ note,button: "Delete",act: ConfirmAct::Delete(b.id.clone()),};@@ -1319,11 +1459,53 @@ impl App {}}+ /// `r`: moves the pick through the main chat's messages (none picked: the newest).+ fn step_pick(&mut self, d: isize) {+ let Some(id) = self.selected.clone() else { return };+ let ids: Vec<String> = self.lane(&id).into_iter().filter(|e| e.is_message()).map(|e| e.id.clone()).collect();+ if ids.is_empty() {+ self.pick = None;+ self.flash("No message to reply to yet");+ return;+ }+ let at = self.pick.as_ref().and_then(|p| ids.iter().position(|x| x == p));+ let i = at.map_or(ids.len() - 1, |i| i.saturating_add_signed(d).min(ids.len() - 1));+ self.pick = Some(ids[i].clone());+ }++ /// Keys while a message is picked. Returns whether the key was used.+ fn pick_key(&mut self, k: KeyEvent) -> bool {+ match k.code {+ KeyCode::Char('j') | KeyCode::Down => self.step_pick(1),+ KeyCode::Char('k') | KeyCode::Up => self.step_pick(-1),+ KeyCode::Enter | KeyCode::Char('r') => {+ if let Some(root) = self.pick.take() {+ self.open_thread(root);+ self.start_typing();+ }+ }+ KeyCode::Esc => self.pick = None,+ _ => return false,+ }+ true+ }++ fn open_thread(&mut self, root: String) {+ let Some(id) = self.selected.clone() else { return };+ self.pick = None;+ self.chat_scroll = 0;+ self.chat_page = true;+ self.focus = Focus::Chat;+ if self.trace == TraceMode::Full {+ self.trace = TraceMode::Off;+ }+ self.call("thread", json!({"botId": id, "rootId": root}), After::Thread);+ self.thread = Some(root);+ }+fn copy_last(&mut self) {let Some(id) = self.selected.clone() else { return };- let Some(text) =- self.entries.get(&id).and_then(|m| m.values().rev().find(|e| e.is_final()).map(|e| e.text().to_owned()))- else {+ let Some(text) = self.lane(&id).into_iter().rev().find(|e| e.is_final()).map(|e| e.text().to_owned()) else {self.flash("No reply to copy");return;};@@ -1346,8 +1528,101 @@ impl App {self.overlays.push(Overlay::Agents(AgentPicker { query: Editor::default(), cursor: 0 }));}+ fn new_group(&mut self) {+ self.overlays.push(Overlay::Group(GroupForm {+ group_id: None,+ name: Editor::default(),+ members: vec![],+ on_name: false,+ cursor: 0,+ error: None,+ saving: false,+ }));+ }++ /// Bots a group can hold: the roster's agents, plus hidden ones already in it.+ pub fn group_candidates(&self, members: &[String]) -> Vec<&Bot> {+ let mut v: Vec<&Bot> = self.roster().into_iter().filter(|b| !b.group).collect();+ v.extend(self.bots.values().filter(|b| b.hidden && !b.group && members.contains(&b.id)));+ v+ }++ /// "Alice, Bob" when no name is typed.+ pub fn group_default_name(&self, members: &[String]) -> String {+ let names: Vec<&str> = members.iter().filter_map(|m| self.bots.get(m)).map(|b| b.name.as_str()).collect();+ names.join(", ")+ }++ fn group_key(&mut self, mut g: GroupForm, k: KeyEvent) -> Option<Overlay> {+ let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);+ let n = self.group_candidates(&g.members).len();+ match k.code {+ KeyCode::Esc => return None,+ KeyCode::Enter => self.save_group(&mut g),+ KeyCode::Char('s') if ctrl => self.save_group(&mut g),+ KeyCode::Tab | KeyCode::BackTab => g.on_name = !g.on_name,+ KeyCode::Down if g.on_name => g.on_name = false,+ KeyCode::Down => g.cursor = (g.cursor + 1).min(n.saturating_sub(1)),+ KeyCode::Up if g.cursor == 0 => g.on_name = true,+ KeyCode::Up if !g.on_name => g.cursor -= 1,+ KeyCode::Char(' ') if !g.on_name => {+ let id = self.group_candidates(&g.members).get(g.cursor).map(|b| b.id.clone());+ if let Some(id) = id {+ g.error = None;+ if let Some(i) = g.members.iter().position(|m| *m == id) {+ g.members.remove(i);+ } else if g.members.len() < MAX_MEMBERS {+ g.members.push(id);+ } else {+ g.error = Some(format!("A group holds up to {MAX_MEMBERS} bots."));+ }+ }+ }+ _ if g.on_name => {+ g.name.key(k);+ }+ _ => {}+ }+ Some(Overlay::Group(g))+ }++ fn save_group(&mut self, g: &mut GroupForm) {+ if g.saving {+ return;+ }+ if g.members.is_empty() {+ g.error = Some("Pick at least one bot.".into());+ return;+ }+ let typed = g.name.text.trim();+ let name = if typed.is_empty() { self.group_default_name(&g.members) } else { typed.to_owned() };+ let mut body = json!({"name": name, "members": g.members});+ g.saving = true;+ g.error = None;+ if let Some(id) = &g.group_id {+ body["id"] = id.clone().into();+ self.call("updateBot", body, After::Saved);+ } else {+ body["id"] = "".into();+ body["kind"] = "group".into();+ self.call("createBot", body, After::Saved);+ }+ }+fn edit_bot(&mut self) {let Some(b) = self.bot().cloned() else { return };+ if b.group {+ self.overlays.push(Overlay::Group(GroupForm {+ group_id: Some(b.id.clone()),+ name: Editor::with(&b.name),+ members: b.members.clone(),+ on_name: true,+ cursor: 0,+ error: None,+ saving: false,+ }));+ return;+ }let mut f = Form {bot_id: Some(b.id.clone()),name: Editor::with(&b.name),@@ -1409,6 +1684,7 @@ impl App {fn run_action(&mut self, a: Action) {match a {Action::NewBot => self.new_bot(),+ Action::NewGroup => self.new_group(),Action::RefreshAgents => self.call("refreshBackends", json!({}), After::Backends),Action::Pair => self.open_pair(),Action::Usage => self.overlays.push(Overlay::Usage),@@ -1445,6 +1721,7 @@ impl App {Overlay::Agents(a) => self.agents_key(a, k),Overlay::Folder(p) => self.folder_key(p, k),Overlay::Form(f) => self.form_key(f, k),+ Overlay::Group(g) => self.group_key(g, k),o @ (Overlay::Usage | Overlay::Pair(_)) => {if matches!(k.code, KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q' | 'U' | 'P')) {None@@ -1781,6 +2058,7 @@ impl App {}}Some(Click::Composer) => self.start_typing(),+ Some(Click::Thread(root)) => self.open_thread(root),None => {if self.overlays.is_empty() {if self.hits.trace.contains(at) {@@ -1937,12 +2215,32 @@ mod tests {{"optionId": "a", "name": "Allow", "kind": "allow_once"},]}),created_at: 0,+ thread_id: None,};assert!(e.pending());let kinds: Vec<String> = e.options().into_iter().map(|o| o.2).collect();assert_eq!(kinds, ["allow_once", "reject_once"]);}+ #[test]+ fn lanes_split_the_chat_from_its_threads() {+ let g = Bot::parse(&json!({"id": "g", "kind": "group", "members": ["a", "b"], "workingThread": "r"}))+ .expect("a bot with an id parses");+ assert!(g.group && g.members == ["a", "b"]);+ assert!(g.works_in(Some("r")) && !g.works_in(None));+ 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 (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"]);+ app.thread = Some("r".into());+ assert_eq!(ids(&app), ["e2"]);+ }+#[test]fn line_moves_keep_the_column() {let mut e = Editor::with("abc\nde");diff --git a/host/src/tui/view.rs b/host/src/tui/view.rsindex 04234675..d889fbdd 100644--- a/host/src/tui/view.rs+++ b/host/src/tui/view.rs@@ -15,8 +15,8 @@ use std::collections::{BTreeSet, HashMap};use std::sync::LazyLock;use super::app::{- ACTIONS, App, Bot, COLORS, Click, Editor, Entry, FIELDS, FILTERS, Field, Focus, Form, GotoItem, Kind, Mark,- Overlay, SHAPES, Status, TraceMode, Width, tilde,+ ACTIONS, App, Bot, COLORS, Click, Editor, Entry, FIELDS, FILTERS, Field, Focus, Form, GotoItem, GroupForm, Kind,+ MAX_MEMBERS, Mark, Overlay, SHAPES, Status, TraceMode, Width, tilde,};use super::md::{self, truncate, width as w};@@ -159,6 +159,10 @@ pub fn glyph(app: &App, m: Mark) -> (&'static str, Style) {fn avatar(b: &Bot) -> Span<'static> {let t = theme();+ if b.group {+ // A group: # and how many bots are in it.+ return Span::styled(format!("#{}", b.members.len().min(9)), t.bold.patch(t.btn));+ }if t.color {Span::styled("••", Style::default().fg(t.on_color).bg(bot_color(&b.color)).add_modifier(Modifier::BOLD))} else {@@ -589,7 +593,9 @@ fn roster(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {if !narrow {let hy = r.bottom() - 1;let mut x = put(buf, x0 + 1, hy, 2, "n", t.secondary.add_modifier(Modifier::BOLD)) + 1;- x = put(buf, x, hy, 10, "new bot", t.dim) + 3;+ x = put(buf, x, hy, 10, "new bot", t.dim) + 2;+ x = put(buf, x, hy, 2, "m", t.secondary.add_modifier(Modifier::BOLD)) + 1;+ x = put(buf, x, hy, 10, "group", t.dim) + 2;x = put(buf, x, hy, 3, "^k", t.secondary.add_modifier(Modifier::BOLD)) + 1;put(buf, x, hy, 8, "go to", t.dim);}@@ -652,6 +658,8 @@ struct Built {lines: Vec<Line<'static>>,/// (line index, x offset, width, click)buttons: Vec<(usize, u16, u16, Click)>,+ /// Each message's (entry id, first line, end line), for picking one to reply to.+ messages: Vec<(String, usize, usize)>,}fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {@@ -674,7 +682,8 @@ fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {x = put(buf, x, r.y, 2, "‹", t.bold) + 1;}put_line(buf, x, r.y, 2, &Line::from(avatar(&b)));- x = put(buf, x + 3, r.y, r.width / 3, &b.name, t.bold) + 2;+ let title = if app.thread.is_some() { format!("Thread · {}", b.name) } else { b.name.clone() };+ x = put(buf, x + 3, r.y, r.width / 3, &title, t.bold) + 2;let (status, ss) = match b.mark() {Mark::Need => ("◆ needs you".to_owned(), t.amber),Mark::Work => (format!("{} working {}", spin(app), elapsed(b.started_at)), t.secondary),@@ -682,7 +691,12 @@ 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));- if !narrow {+ if app.thread.is_some() {+ put(buf, x, r.y, sx.saturating_sub(x + 2), "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);+ } 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);}@@ -707,7 +721,7 @@ fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {}// Composer at the bottom.- let draft = app.drafts.get(&b.id).cloned().unwrap_or_default();+ let draft = app.draft();let inner = usize::from(r.width.saturating_sub(4)).max(1);let (clines, cursor) = composer_lines(&draft, inner);let ch = u(clines.len().clamp(1, 8));@@ -721,7 +735,9 @@ fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {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));if draft.text.is_empty() {- put(buf, r.x + 3, comp_top + 1, r.width.saturating_sub(4), &format!("Message {}…", b.name), t.dim);+ let placeholder =+ if app.thread.is_some() { "Reply in thread…".to_owned() } else { format!("Message {}…", b.name) };+ put(buf, r.x + 3, comp_top + 1, r.width.saturating_sub(4), &placeholder, t.dim);} 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);@@ -733,6 +749,8 @@ fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {Status::NeedsInput => "sends after the approval",_ => "",}+ } else if app.pick.is_some() {+ "↵ opens its thread · esc cancels"} else if matches!(b.status, Status::Working) {"s stops"} else {@@ -753,12 +771,27 @@ fn chat(buf: &mut Buffer, r: Rect, app: &mut App, narrow: bool) {let total = built.lines.len();let h = usize::from(body.height);let max = total.saturating_sub(h);+ // Keep the picked message on screen.+ let picked = app.pick.as_ref().and_then(|p| built.messages.iter().find(|m| &m.0 == p)).map(|m| (m.1, m.2));+ if let Some((from, to)) = picked {+ let start = total.saturating_sub(h + app.chat_scroll);+ if from < start {+ app.chat_scroll = total.saturating_sub(h + from);+ } else if to > start + h {+ app.chat_scroll = total.saturating_sub(to.max(h));+ }+ }app.chat_scroll = app.chat_scroll.min(max);app.chat_top = total > 0 && app.chat_scroll == max;let start = total.saturating_sub(h + app.chat_scroll);for (i, l) in built.lines.iter().skip(start).take(h).enumerate() {put_line(buf, body.x, body.y + u(i), body.width, l);}+ if let Some((from, to)) = picked {+ for li in from.max(start)..to.min(start + h) {+ put(buf, body.x, body.y + u(li - start), 1, "▌", t.amber);+ }+ }for (li, bx, bw, click) in built.buttons {if li >= start && li < start + h {let y = body.y + u(li - start);@@ -847,127 +880,60 @@ fn turn_info(entries: &[&Entry]) -> HashMap<i64, TurnInfo> {m}+fn gap(out: &mut Built) {+ if !out.lines.is_empty() {+ out.lines.push(Line::default());+ }+}++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 build_chat(app: &App, b: &Bot, width: usize) -> Built {let t = theme();- let mut out = Built { lines: vec![], buttons: vec![] };- let mut entries: Vec<&Entry> = app.entries.get(&b.id).map(|m| m.values().collect()).unwrap_or_default();- // A message sent mid-turn belongs after that turn's reply.- entries.sort_by_key(|e| (e.turn, e.seq));+ 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);- let name_style =- if t.color { Style::default().fg(bot_color(&b.color)).add_modifier(Modifier::BOLD) } else { t.bold };- let gap = |out: &mut Built| {- if !out.lines.is_empty() {- out.lines.push(Line::default());- }- };- if entries.is_empty() {- out.lines.push(Line::default());- 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)]));- out.lines.push(Line::from(vec![- Span::raw(" "),- Span::styled(format!("{} · {}", b.backend, tilde(&b.cwd, &app.home)), t.secondary),- ]));- out.lines.push(Line::default());- let hello =- format!("Say what you need. {} works in the background and pings you when it's done or needs you.", b.name);- out.lines.extend(md::wrap(&[Span::styled(hello, t.dim)], width, &[Span::raw(" ")], &[Span::raw(" ")]));+ if entries.is_empty() && thread.is_none() {+ intro(&mut out, app, b, width);return out;}- if !app.history_complete(&b.id) {+ 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)));}- for e in &entries {- match e.kind {- Kind::User => {- gap(&mut out);- 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 body = md::wrap(- &[Span::styled(e.text().to_owned(), t.text)],- width.saturating_sub(1),- &[Span::raw(" › ")],- &[Span::raw(" ")],- );- out.lines.extend(with_bg(body, width, t.band));- }- Kind::Agent if e.is_final() => {- gap(&mut out);- out.lines.push(Line::from(vec![- Span::styled(format!(" {}", b.name), name_style),- Span::styled(format!(" {}", clock(e.created_at)), t.dim),- ]));- out.lines.extend(md::render(e.text(), width, 1));- if let Some(ti) = info.get(&e.turn).filter(|ti| ti.steps > 0) {- 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,- )));- }- }- Kind::Permission => {- gap(&mut out);- if e.pending() {- permission_card(&mut out, e, b, width, &app.home);- } else {- decided_line(&mut out, e);- }- }- Kind::Notice => {- let text = e.text().to_owned();- match e.data["style"].as_str() {- Some("divider") => {- gap(&mut out);- 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") => {- gap(&mut out);- out.lines.extend(md::wrap(- &[Span::styled(text, t.red)],- width,- &[Span::styled(" × ", t.red)],- &[Span::raw(" ")],- ));- }- _ => {- gap(&mut out);- out.lines.extend(md::wrap(- &[Span::styled(text, t.dim)],- width,- &[Span::styled(" · ", t.dim)],- &[Span::raw(" ")],- ));- }- }- }- _ => {}+ 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)));+ }+ for e in &entries {+ 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);- let in_flight = info.get(&last_turn).is_none_or(|ti| !ti.has_final);- if b.status == Status::Working && in_flight {+ // 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 {gap(&mut out);- out.lines.push(Line::from(Span::styled(format!(" {}", b.name), name_style)));+ 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),@@ -980,10 +946,168 @@ 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)+ {+ gap(&mut out);+ let line = if b.status == Status::NeedsInput {+ Span::styled(" ◆ Needs you in a thread · ! opens it", t.amber)+ } else {+ Span::styled(format!(" {} Working in a thread", 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, tilde(&b.cwd, &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)]));+ 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 body = md::wrap(+ &[Span::styled(e.text().to_owned(), t.text)],+ width.saturating_sub(1),+ &[Span::raw(" › ")],+ &[Span::raw(" ")],+ );+ out.lines.extend(with_bg(body, width, t.band));+ out.messages.push((e.id.clone(), from, out.lines.len()));+ if main {+ thread_line(out, 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));+ out.messages.push((e.id.clone(), from, out.lines.len()));+ if let Some(ti) = info.get(&e.turn).filter(|ti| ti.steps > 0) {+ 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, e);+ }+ }+ Kind::Permission => {+ gap(out);+ if e.pending() {+ // A card in a group is its asking bot's.+ permission_card(out, e, author.unwrap_or(b), width, &app.home);+ } else {+ decided_line(out, e);+ }+ }+ Kind::Notice => {+ let text = e.text().to_owned();+ 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(" ")],+ )),+ }+ }+ _ => {}+ }+}++/// Under a message with a thread: how many replies, how recently (click opens it).+fn thread_line(out: &mut Built, e: &Entry) {+ let Some(text) = thread_summary(&e.data["thread"]) else { return };+ out.buttons.push((out.lines.len(), 3, u(w(&text)), Click::Thread(e.id.clone())));+ out.lines.push(Line::from(vec![Span::raw(" "), Span::styled(text, theme().secondary)]));+}++/// "↳ 3 replies · 12:31" 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 = when(v["lastAt"].as_i64().unwrap_or(0));+ Some(if at.is_empty() { format!("↳ {}", replies(n)) } else { format!("↳ {} · {at}", replies(n)) })+}+/// Keys printed on approval buttons: y / a / n for the usual kinds, digits otherwise.fn option_keys(opts: &[(String, String, String)]) -> Vec<String> {let mut used = vec![];@@ -1498,6 +1622,7 @@ fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &Overlay) {);}Overlay::Form(form) => form_view(buf, area, app, form),+ Overlay::Group(g) => group_view(buf, area, app, g),Overlay::Usage => usage(buf, area, app),Overlay::Pair(url) => pair(buf, area, url.as_deref()),}@@ -1575,8 +1700,9 @@ fn goto(buf: &mut Buffer, area: Rect, app: &mut App, g: &super::app::Goto, itemsput(buf, inner.x, y, 1, gl, gs.patch(base));put_line(buf, inner.x + 2, y, 2, &Line::from(avatar(b)));put(buf, inner.x + 5, y, 10, &b.name, t.bold.patch(base));- put(buf, inner.x + 16, y, 10, &b.backend, t.secondary.patch(base));- let cwd = truncate(&tilde(&b.cwd, &app.home), 18);+ put(buf, inner.x + 16, y, 10, if b.group { "group" } else { &b.backend }, t.secondary.patch(base));+ let cwd =+ if b.group { format!("{} bots", b.members.len()) } else { truncate(&tilde(&b.cwd, &app.home), 18) };put(buf, inner.x + 27, y, 19, &cwd, t.secondary.patch(base));let (pv, ps) = preview(b);let room = inner.width.saturating_sub(47);@@ -1612,14 +1738,13 @@ fn goto(buf: &mut Buffer, area: Rect, app: &mut App, g: &super::app::Goto, itemsif let Some(GotoItem::Bot(id)) = items.get(g.cursor)&& let Some(b) = app.bots.get(id){- put(- buf,- inner.x,- inner.bottom() - 2,- inner.width,- &format!("{} · {} · {}", b.name, b.backend, tilde(&b.cwd, &app.home)),- t.secondary.patch(t.panel),- );+ let meta = if b.group {+ let names: Vec<String> = b.members.iter().map(|m| app.author_name(Some(m))).collect();+ format!("{} · group · {}", b.name, names.join(", "))+ } else {+ format!("{} · {} · {}", b.name, b.backend, tilde(&b.cwd, &app.home))+ };+ put(buf, inner.x, inner.bottom() - 2, inner.width, &meta, t.secondary.patch(t.panel));}put(buf,@@ -1631,7 +1756,7 @@ fn goto(buf: &mut Buffer, area: Rect, app: &mut App, g: &super::app::Goto, items);}-const HELP: [(&str, &str, &str); 40] = [+const HELP: [(&str, &str, &str); 44] = [("MOVE", "j k ↑ ↓", "next / previous bot"),("MOVE", "[ ]", "previous / next bot"),("MOVE", "1…9", "jump to bot 1–9"),@@ -1650,6 +1775,9 @@ const HELP: [(&str, &str, &str); 40] = [("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", "esc", "close the thread"),("TYPE", "↵", "send"),("TYPE", "⇧↵ alt↵ ^j", "new line"),("TYPE", "esc", "back to NAV"),@@ -1658,7 +1786,8 @@ const HELP: [(&str, &str, &str); 40] = [("TYPE", "alt b / f", "word left / right"),("TYPE", "^w ^u", "delete word / line"),("BOTS", "n", "new bot"),- ("BOTS", "e", "edit bot"),+ ("BOTS", "m", "new group chat"),+ ("BOTS", "e", "edit bot or group"),("BOTS", "p", "pin / unpin"),("BOTS", "S", "new session"),("BOTS", "x", "delete bot"),@@ -1670,13 +1799,13 @@ const HELP: [(&str, &str, &str); 40] = [("VIEW", "P", "pair a phone"),("VIEW", "esc", "close / go back"),("VIEW", "q", "quit; bots keep going"),- ("MOUSE", "click", "open bot, press button"),+ ("MOUSE", "click", "open bot or thread, press button"),("MOUSE", "wheel", "scroll under pointer"),];fn help(buf: &mut Buffer, area: Rect, filter: &Editor) {let t = theme();- let r = centered(area, 80, 30);+ let r = centered(area, 80, 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();@@ -1863,6 +1992,82 @@ fn form_view(buf: &mut Buffer, area: Rect, app: &App, f: &Form) {rput(buf, inner.right(), by, hint, t.dim.patch(t.panel));}+fn group_view(buf: &mut Buffer, area: Rect, app: &App, g: &GroupForm) {+ let t = theme();+ let bots = app.group_candidates(&g.members);+ let r = centered(area, 74, u(bots.len() + 10).max(14));+ let title = if g.group_id.is_some() { "Group chat" } else { "New group chat" };+ let inner = frame_box(buf, r, t.text, t.panel, Some((title, t.text)));+ let label = |on: bool| if on { t.bold } else { t.secondary }.patch(t.panel);+ put(buf, inner.x, inner.y, 8, "Name", label(g.on_name));+ let default = app.group_default_name(&g.members);+ let placeholder = if default.is_empty() { "Name" } else { default.as_str() };+ field_line(+ buf,+ Rect::new(inner.x + 8, inner.y, inner.width.saturating_sub(8), 1),+ inner.y,+ &g.name,+ placeholder,+ g.on_name,+ );+ put(+ buf,+ inner.x,+ inner.y + 2,+ inner.width,+ &format!("Bots · {} of {MAX_MEMBERS}", g.members.len()),+ label(!g.on_name),+ );+ let list_h = usize::from(inner.height.saturating_sub(7));+ let off = g.cursor.saturating_sub(list_h.saturating_sub(1));+ if bots.is_empty() {+ put(buf, inner.x, inner.y + 3, inner.width, "No bots yet. n creates one.", t.dim.patch(t.panel));+ }+ for (y, (i, b)) in (inner.y + 3..).zip(bots.iter().enumerate().skip(off).take(list_h)) {+ let sel = !g.on_name && i == g.cursor;+ let base = if sel { t.sel } else { t.panel };+ if sel {+ restyle(buf, Rect::new(inner.x - 1, y, inner.width + 2, 1), t.sel);+ }+ let on = g.members.contains(&b.id);+ put(buf, inner.x, y, 2, if on { "☑" } else { "☐" }, if on { t.bold } else { t.dim }.patch(base));+ put_line(buf, inner.x + 2, y, 2, &Line::from(avatar(b)));+ put(buf, inner.x + 5, y, inner.width / 2, &b.name, if sel { t.bold } else { t.text }.patch(base));+ let folder =+ std::path::Path::new(&b.cwd).file_name().map(|f| f.to_string_lossy().into_owned()).unwrap_or_default();+ rput(buf, inner.right(), y, &truncate(&folder, usize::from(inner.width / 3)), t.dim.patch(base));+ }+ let by = inner.bottom() - 1;+ if let Some(e) = &g.error {+ put(buf, inner.x, by - 1, inner.width, e, t.red.patch(t.panel));+ } else {+ put(+ buf,+ inner.x,+ by - 1,+ inner.width,+ "Everyone answers in turn unless you @mention someone.",+ t.dim.patch(t.panel),+ );+ }+ let save = if g.saving {+ " … Saving "+ } else if g.group_id.is_some() {+ " ↵ Save "+ } else {+ " ↵ Create "+ };+ let x = put(buf, inner.x, by, 14, save, t.btn_primary) + 1;+ put(buf, x, by, 12, " esc Cancel ", t.text.patch(t.btn).add_modifier(Modifier::BOLD));+ rput(+ buf,+ inner.right(),+ by,+ if g.on_name { "tab bots" } else { "↑↓ move · space pick · tab name" },+ t.dim.patch(t.panel),+ );+}+fn usage(buf: &mut Buffer, area: Rect, app: &App) {let t = theme();let providers = app.usage["providers"].as_array().cloned().unwrap_or_default();@@ -2007,6 +2212,14 @@ mod tests {assert_eq!(c, (0, 2));}+ #[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"));+ }+#[test]fn option_keys_use_letters_then_digits() {let o = |k: &str| (String::new(), String::new(), k.to_owned());diff --git a/host/tests/fixtures/team_agent.py b/host/tests/fixtures/team_agent.pyindex b19c6b83..22fd787b 100644--- a/host/tests/fixtures/team_agent.py+++ b/host/tests/fixtures/team_agent.py@@ -5,6 +5,7 @@ import pathlibimport subprocessimport sysimport threading+import timeoutput_lock = threading.Lock()cancel = threading.Event()@@ -67,7 +68,10 @@ def prompt(request):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 ""reply = "reply: group" if last.startswith("User:") else "(pass)"- update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": reply}})+ # Two chunks, apart: the streamed entry is rewritten before it's final.+ update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": reply[:3]}})+ time.sleep(0.4)+ update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": reply[3:]}})send({"id": request["id"], "result": {"stopReason": "end_turn"}})returnif cancel.is_set():