Skip to content

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

Group chats with several bots, reply threads on any message, and Google sign-in on the iPhone welcome screen

leepokai8f1987435cc1
diff --git a/apps/ios/App/CodyncApp.swift b/apps/ios/App/CodyncApp.swift
index 8e6524b9..5acab2db 100644
--- a/apps/ios/App/CodyncApp.swift
+++ b/apps/ios/App/CodyncApp.swift
@@ -21,7 +21,7 @@ struct CodyncApp: App {
.environment(app.account)
.tint(Palette.accent)
.codyncSheet(isPresented: Binding(
- get: { onboardingCompleted && app.account.showSwitcher },
+ get: { (onboardingCompleted || app.account.isSignedIn) && app.account.showSwitcher },
set: { app.account.showSwitcher = $0 }
)) {
// Holds the pushes inside the sheet (Computers & settings, Widgets); no bar shows.
diff --git a/apps/ios/Views/BotListView.swift b/apps/ios/Views/BotListView.swift
index b1abb24a..e6da9198 100644
--- a/apps/ios/Views/BotListView.swift
+++ b/apps/ios/Views/BotListView.swift
@@ -7,6 +7,8 @@ struct BotListView: View {
@Environment(AppStore.self) private var app
@Environment(AccountStore.self) private var accounts
@State private var editing: EditTarget?
+ @State private var editingGroup: GroupTarget?
+ @State private var newMenu = false
@State private var pickingComputer = false
@State private var confirmDelete: RosterItem?
@@ -50,8 +52,14 @@ struct BotListView: View {
EmptyView()
} trailing: {
IconButton("Computers", systemImage: "desktopcomputer") { app.showComputers = true }
- IconButton("New bot", systemImage: "plus", action: newBot)
+ IconButton("New", systemImage: "plus") { newMenu = true }
.disabled(onlineStores.isEmpty)
+ .codyncMenu(isPresented: $newMenu) {
+ [
+ MenuItem("New bot", icon: "plus", action: newBot),
+ MenuItem("New group chat", icon: "person.2", action: newGroup),
+ ]
+ }
}
}
.hidesSystemNavigationBar()
@@ -71,6 +79,17 @@ struct BotListView: View {
}
}
}
+ .codyncSheet(item: $editingGroup) { target in
+ if let store = accounts.store(for: target.computerId) {
+ GroupEditorView(group: target.group)
+ .environment(store)
+ .onChange(of: store.selection) { _, botId in
+ guard let botId else { return }
+ store.selection = nil
+ accounts.selection = BotReference(accountId: accounts.accountId, computerId: target.computerId, botId: botId)
+ }
+ }
+ }
.codyncSheet(isPresented: $pickingComputer) {
ComputerPicker(stores: onlineStores) { store in
// Let the picker slide away before the editor slides up.
@@ -82,9 +101,9 @@ struct BotListView: View {
}
.codyncDialog("Delete \(confirmDelete?.bot.name ?? "bot")?",
isPresented: Binding(get: { confirmDelete != nil }, set: { if !$0 { confirmDelete = nil } }),
- message: "Files it changed on your computer stay as they are.") {
+ message: confirmDelete?.bot.isGroup == true ? "Its bots and their own chats stay." : "Files it changed on your computer stay as they are.") {
let item = confirmDelete
- return [DialogAction("Delete bot and its conversation", destructive: true) {
+ return [DialogAction(item?.bot.isGroup == true ? "Delete group chat" : "Delete bot and its conversation", destructive: true) {
if let item { accounts.store(for: item.ref.computerId)?.delete(item.bot) }
}]
}
@@ -107,7 +126,9 @@ struct BotListView: View {
.contextActions {
[
MenuItem(bot.pinned ? "Unpin" : "Pin", icon: bot.pinned ? "pin.slash" : "pin") { store.setPinned(bot, !bot.pinned) },
- MenuItem("Edit profile", icon: "pencil") { editing = EditTarget(computerId: item.ref.computerId, draft: BotDraft(bot)) },
+ bot.isGroup
+ ? MenuItem("Edit group", icon: "person.2") { editingGroup = GroupTarget(computerId: item.ref.computerId, group: bot) }
+ : MenuItem("Edit profile", icon: "pencil") { editing = EditTarget(computerId: item.ref.computerId, draft: BotDraft(bot)) },
MenuItem("Mark as read", icon: "checkmark.message") { store.markRead(bot.id) },
MenuItem("Hide from list", icon: "eye.slash") { store.setHidden(bot, true) },
MenuItem("Delete", icon: "trash", destructive: true, divider: true) { confirmDelete = item },
@@ -115,6 +136,16 @@ struct BotListView: View {
}
}
+ /// A group chat gathers bots of one computer (the first one online; more computers are future work).
+ private func newGroup() {
+ guard let store = onlineStores.first else { return }
+ Task {
+ // Let the menu fold away before the editor slides up.
+ try? await Task.sleep(for: .milliseconds(200))
+ editingGroup = GroupTarget(computerId: store.computer.id, group: nil)
+ }
+ }
+
/// A new bot lives on one computer: pick it first when there's a choice.
private func newBot() {
let stores = onlineStores
@@ -126,6 +157,12 @@ struct BotListView: View {
}
}
+private struct GroupTarget: Identifiable {
+ let id = UUID()
+ let computerId: ComputerID
+ let group: Bot?
+}
+
private struct EditTarget: Identifiable {
let id = UUID()
let computerId: ComputerID
diff --git a/apps/ios/Views/RootView.swift b/apps/ios/Views/RootView.swift
index 61b47e8d..a1e18521 100644
--- a/apps/ios/Views/RootView.swift
+++ b/apps/ios/Views/RootView.swift
@@ -6,6 +6,7 @@ import WidgetKit
struct RootView: View {
@Environment(AppStore.self) private var app
@Environment(AccountStore.self) private var accounts
+ @Environment(AccountSession.self) private var account
@AppStorage("onboardingCompleted") private var onboardingCompleted = false
@Environment(\.accessibilityReduceMotion) private var reduceMotion
/// First launch only: past the welcome, on to setup.
@@ -19,12 +20,12 @@ struct RootView: View {
var body: some View {
Group {
if accounts.computers.isEmpty && accounts.cloudComputers.isEmpty {
- if !onboardingCompleted && !welcomed {
+ if !onboardingCompleted && !welcomed && !account.isSignedIn {
WelcomeView { withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { welcomed = true } }
.transition(.move(edge: .leading).combined(with: .opacity))
} else {
PairingView {
- if onboardingCompleted {
+ if onboardingCompleted || account.isSignedIn {
AccountSwitcherButton()
} else {
BackButton { withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { welcomed = false } }
diff --git a/apps/ios/Views/WelcomeView.swift b/apps/ios/Views/WelcomeView.swift
index 7c08b140..5acf0512 100644
--- a/apps/ios/Views/WelcomeView.swift
+++ b/apps/ios/Views/WelcomeView.swift
@@ -5,6 +5,7 @@ import SwiftUI
/// First launch, before any setup: who the bots are, a glimpse of talking to one, one way forward.
struct WelcomeView: View {
let start: () -> Void
+ @Environment(AccountSession.self) private var account
@Environment(\.accessibilityReduceMotion) private var reduceMotion
/// 0 = nothing yet … 4 = everything shown. Each beat enters in turn.
@State private var beat = 0
@@ -34,10 +35,31 @@ struct WelcomeView: View {
Spacer(minLength: 32)
- Button(action: start) {
- Text("Get started").font(.headline).frame(maxWidth: .infinity, minHeight: 50)
+ VStack(spacing: 10) {
+ Button(action: start) {
+ Text("Get started").font(.headline).frame(maxWidth: .infinity, minHeight: 50)
+ }
+ .buttonStyle(.primary)
+ // Signed in, the computers on the account show up without scanning a code.
+ if account.isConfigured {
+ Button { Task { await account.signIn() } } label: {
+ ZStack {
+ Label("Continue with Google", systemImage: "person.crop.circle")
+ .opacity(account.isBusy ? 0 : 1)
+ if account.isBusy { Spinner(size: 18) }
+ }
+ .font(.headline)
+ .frame(maxWidth: .infinity, minHeight: 50)
+ }
+ .buttonStyle(.secondary)
+ .disabled(account.isBusy)
+ .animation(Motion.fade, value: account.isBusy)
+ }
+ if let message = account.errorMessage {
+ Text(message).font(.footnote).foregroundStyle(Palette.danger)
+ .transition(.opacity)
+ }
}
- .buttonStyle(.primary)
.rise(beat >= 4)
}
.padding(.horizontal, 24)
diff --git a/apps/linux/src/ui.rs b/apps/linux/src/ui.rs
index 282367f7..435f3de9 100644
--- a/apps/linux/src/ui.rs
+++ b/apps/linux/src/ui.rs
@@ -330,7 +330,8 @@ fn handle(ui: &App, ev: Event) {
"bot" => {
let bot = &m["bot"];
let id = bot["id"].as_str().unwrap_or_default().to_owned();
- if bot["deleted"].as_bool().unwrap_or(false) {
+ // 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" {
st.bots.remove(&id);
st.entries.remove(&id);
if st.current.as_deref() == Some(&id) {
@@ -343,7 +344,7 @@ fn handle(ui: &App, ev: Event) {
st.bots.insert(id, bot.clone());
}
}
- "entry" => upsert(&mut st, m["entry"].clone()),
+ "entry" if m["entry"]["threadId"].is_null() => upsert(&mut st, m["entry"].clone()),
_ => {}
},
}
diff --git a/apps/macos/App/CodyncMacApp.swift b/apps/macos/App/CodyncMacApp.swift
index 85f43768..c0ab2069 100644
--- a/apps/macos/App/CodyncMacApp.swift
+++ b/apps/macos/App/CodyncMacApp.swift
@@ -205,7 +205,8 @@ struct MenuView: View {
} else {
ScrollView {
VStack(spacing: 0) {
- ForEach(host.roster) { item in
+ // The menu shows what the bots are doing; group chats open in the window.
+ ForEach(host.roster.filter { !$0.bot.isGroup }) { item in
BotLine(bot: item.bot, computer: host.accounts.computers.count > 1 ? item.computer : nil) { host.stop(item) }
.contentShape(Rectangle())
.onTapGesture {
diff --git a/host/src/api.rs b/host/src/api.rs
index 91cd5dea..d322cbbb 100644
--- a/host/src/api.rs
+++ b/host/src/api.rs
@@ -6,7 +6,7 @@ use crate::LockExt;
use crate::bot::Cmd;
use crate::devices::{Caller, Forbidden};
use crate::hub::Hub;
-use crate::store::{BotConfig, DeviceSource, EntryKind};
+use crate::store::{BotConfig, DeviceSource, EntryKind, Lane};
use crate::{backends, crypto, market, usage};
use anyhow::{Context, Result, anyhow, bail};
use axum::body::Bytes;
@@ -226,6 +226,8 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -
let limit = b["limit"].as_i64().unwrap_or(100).clamp(1, 500);
json!({"entries": hub.store.history(bot, before, limit)?})
}
+ // A thread's replies (its newest 500); the root is in the main chat.
+ "thread" => json!({"entries": hub.store.thread(str_arg(&b, "botId")?, str_arg(&b, "rootId")?, 500)?}),
"createBot" => {
let mut b = b;
b["id"] = "".into();
@@ -253,19 +255,41 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -
{
return Ok(json!({"entry": e}));
}
- hub.store.bot(bot)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("unknown bot"))?;
+ let row = hub.store.bot(bot)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("unknown bot"))?;
+ // `threadId`: reply in the thread on that message of the main chat (threads are flat).
+ let thread = match b["threadId"].as_str().filter(|t| !t.is_empty()) {
+ Some(root) => {
+ let r = hub.store.entry(root).ok_or_else(|| anyhow!("unknown message"))?;
+ if r.bot_id != bot || r.thread_id.is_some() {
+ bail!("threads start from a message in the main chat");
+ }
+ Some(root.to_owned())
+ }
+ None => None,
+ };
+ let lane = Lane { chat: bot.to_owned(), thread };
let turn = hub.store.max_turn(bot) + 1;
+ // A group has no agent of its own to queue behind: its message is simply sent.
+ let status = if row.config.is_group() { "sent" } else { "queued" };
let e = hub
- .add_entry(bot, EntryKind::User, turn, &json!({"text": text, "clientNonce": nonce, "status": "queued"}))
+ .add_entry(&lane, EntryKind::User, turn, &json!({"text": text, "clientNonce": nonce, "status": status}))
.ok_or_else(|| anyhow!("couldn't save the message"))?;
- hub.send_cmd(bot, Cmd::Send { entry_id: e.id.clone(), text: text.to_owned() })?;
+ if row.config.is_group() {
+ crate::group::start(hub, &row.config, lane);
+ } else {
+ hub.send_cmd(bot, Cmd::Send { lane, entry_id: e.id.clone(), text: text.to_owned() })?;
+ }
if let Err(error) = hub.mark_read(bot) {
tracing::warn!(%error, bot, "couldn't mark bot read after send");
}
json!({"entry": e})
}
"stop" => {
- hub.send_cmd(str_arg(&b, "botId")?, Cmd::Stop)?;
+ let bot = str_arg(&b, "botId")?;
+ match hub.store.bot(bot)? {
+ Some(row) if row.config.is_group() => hub.groups.stop(hub, bot),
+ _ => hub.send_cmd(bot, Cmd::Stop)?,
+ }
json!({})
}
"newSession" => {
@@ -292,7 +316,9 @@ pub async fn dispatch(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value) -
let entry_id = str_arg(&b, "entryId")?;
let e = hub.store.entry(entry_id).ok_or_else(|| anyhow!("unknown card"))?;
let option_id = b["optionId"].as_str().map(str::to_owned);
- hub.send_cmd(&e.bot_id, Cmd::Permission { entry_id: entry_id.to_owned(), option_id })?;
+ // A card in a group belongs to the bot that asked.
+ let bot = e.data["author"].as_str().unwrap_or(&e.bot_id);
+ hub.send_cmd(bot, Cmd::Permission { entry_id: entry_id.to_owned(), option_id })?;
json!({})
}
"registerDevice" => {
diff --git a/host/src/bot.rs b/host/src/bot.rs
index 8b52da32..49f9cbe2 100644
--- a/host/src/bot.rs
+++ b/host/src/bot.rs
@@ -10,13 +10,18 @@
//! snapshot per session and compaction epoch (`context`), finished exchanges feed
//! its memory keeper (`memory`), messages sent while it works are folded into
//! its next turn, and a turn cut off by a host restart is resumed.
+//!
+//! Lanes: besides its own chat, a bot talks in threads (each a session of its own,
+//! forked from the main one when the agent can fork) and in group chats (turns in
+//! its main session, written to the group's transcript; see `group`).
use crate::acp::{self, Acp, Incoming};
use crate::context::{self, Identity, Snapshot};
+use crate::group::GroupTurn;
use crate::hub::{BotStatus, Hub};
use crate::memory;
use crate::push::{self, AlertKind};
-use crate::store::{BotConfig, EntryKind, Permission, now_ms};
+use crate::store::{BotConfig, Entry, EntryKind, Lane, Permission, lane_key, now_ms};
use anyhow::{Result, anyhow, bail};
use serde::Serialize;
use serde_json::{Value, json};
@@ -35,19 +40,36 @@ pub enum NoticeStyle {
}
pub enum Cmd {
- Send { entry_id: String, text: String },
+ /// The user wrote in the bot's chat or one of its threads.
+ Send {
+ lane: Lane,
+ entry_id: String,
+ text: String,
+ },
Ask(crate::team::Ask),
- CancelAsk { id: String },
+ CancelAsk {
+ id: String,
+ },
+ /// Its turn in a group's room turn.
+ Group(GroupTurn),
+ /// The group's room turns stopped: drop its queued turns, stop a running one.
+ CancelGroup {
+ chat: String,
+ },
Stop,
- Permission { entry_id: String, option_id: Option<String> },
+ Permission {
+ entry_id: String,
+ option_id: Option<String>,
+ },
NewSession,
Reconfigure(Box<BotConfig>),
Shutdown,
}
enum Queued {
- User { entry_id: String, text: String },
+ User { lane: Lane, entry_id: String, text: String },
Ask(crate::team::Ask),
+ Group(GroupTurn),
}
pub struct BotHandle {
@@ -61,17 +83,24 @@ pub fn spawn(hub: Arc<Hub>, cfg: BotConfig) -> BotHandle {
let session_id = hub.store.bot(&cfg.id).ok().flatten().and_then(|b| b.session_id);
// A turn the previous host process never finished (crash, update, restart), unless
// it's stale: an hour-old task is more likely unwanted than awaited (gawkbot's rule).
- let interrupted = hub
- .store
- .kv_get(&inflight_key(&cfg.id))
- .and_then(|v| v.parse::<i64>().ok())
- .is_some_and(|started| now_ms() - started < STALE_RESUME_MS);
+ let interrupted = hub.store.kv_get(&inflight_key(&cfg.id)).and_then(|v| {
+ let (started, thread) = v.split_once('\t').unwrap_or((&v, ""));
+ let started: i64 = started.parse().ok()?;
+ (now_ms() - started < STALE_RESUME_MS)
+ .then(|| Lane { chat: cfg.id.clone(), thread: (!thread.is_empty()).then(|| thread.to_owned()) })
+ });
let keeper = memory::spawn_keeper(hub.clone(), cfg.id.clone());
+ let lane = Lane::main(&cfg.id);
let actor = Actor {
hub,
cfg,
conn: None,
session_id,
+ thread_sessions: HashMap::new(),
+ lane,
+ turn_session: None,
+ thread_intro: None,
+ active_group: None,
session_fresh: false,
applied_system: None,
keeper,
@@ -93,10 +122,19 @@ pub fn spawn(hub: Arc<Hub>, cfg: BotConfig) -> BotHandle {
BotHandle { tx, task }
}
+/// What the agent can do with sessions besides creating them.
+#[derive(Clone, Copy)]
+struct SessionCaps {
+ /// `session/load`: resume a session after a restart.
+ load: bool,
+ /// `session/fork`: a thread starts as a copy of the main session.
+ fork: bool,
+}
+
pub(crate) struct Conn {
pub(crate) acp: Arc<Acp>,
pub(crate) rx: mpsc::UnboundedReceiver<Incoming>,
- can_load: bool,
+ sessions: SessionCaps,
/// The agent can reach remote (HTTP) MCP servers itself.
mcp_http: bool,
/// Claude's adapter: takes `_meta.systemPrompt` and `_meta.claudeCode.options`.
@@ -120,7 +158,17 @@ struct Actor {
hub: Arc<Hub>,
cfg: BotConfig,
conn: Option<Conn>,
+ /// The main session: the bot's own chat and its group turns.
session_id: Option<String>,
+ /// Thread root -> the thread's session (loaded from kv on first use).
+ thread_sessions: HashMap<String, String>,
+ /// Where the current (or last) turn talks; entries go there.
+ lane: Lane,
+ /// The session the current turn prompts.
+ turn_session: Option<String>,
+ /// Told on the first message of a new thread session: what the thread is about.
+ thread_intro: Option<String>,
+ active_group: Option<GroupTurn>,
/// True until the first prompt of a new ACP session has been sent.
session_fresh: bool,
/// (session, instructions) last handed to Claude as its system prompt by this process.
@@ -150,12 +198,13 @@ struct Actor {
type Done = Result<Value>;
impl Actor {
- /// `interrupted`: the previous host process stopped mid-turn; resume it first.
- async fn run(mut self, mut rx: mpsc::UnboundedReceiver<Cmd>, interrupted: bool) {
+ /// `interrupted`: the previous host process stopped a turn in this lane (the bot's
+ /// chat or one of its threads); resume it first.
+ async fn run(mut self, mut rx: mpsc::UnboundedReceiver<Cmd>, interrupted: Option<Lane>) {
let (done_tx, mut done_rx) = mpsc::unbounded_channel::<Done>();
let mut flush_tick = tokio::time::interval(Duration::from_millis(300));
- if interrupted {
- self.resume_interrupted(&done_tx).await;
+ if let Some(lane) = interrupted {
+ self.resume_interrupted(lane, &done_tx).await;
}
loop {
tokio::select! {
@@ -177,6 +226,7 @@ impl Actor {
}
self.hub.team.cancel_from(&self.cfg.id);
self.complete_ask(Err(anyhow!("recipient shut down")));
+ self.complete_group(Err(anyhow!("bot shut down")));
if let Some(c) = self.conn.take() {
c.acp.kill().await;
}
@@ -190,12 +240,25 @@ impl Actor {
async fn on_cmd(&mut self, cmd: Cmd, done_tx: &mpsc::UnboundedSender<Done>) -> bool {
match cmd {
- Cmd::Send { entry_id, text } => {
- self.queue.push_back(Queued::User { entry_id, text });
+ Cmd::Send { lane, entry_id, text } => {
+ self.queue.push_back(Queued::User { lane, entry_id, text });
+ if self.turn.is_none() {
+ self.next_in_queue(done_tx).await;
+ }
+ }
+ Cmd::Group(turn) => {
+ self.queue.push_back(Queued::Group(turn));
if self.turn.is_none() {
self.next_in_queue(done_tx).await;
}
}
+ Cmd::CancelGroup { chat } => {
+ // Dropping a queued turn's reply tells the room it won't come.
+ self.queue.retain(|q| !matches!(q, Queued::Group(g) if g.lane.chat == chat));
+ if self.active_group.as_ref().is_some_and(|g| g.lane.chat == chat) {
+ self.stop().await;
+ }
+ }
Cmd::Ask(ask) => {
self.queue.push_back(Queued::Ask(ask));
if self.turn.is_none() {
@@ -239,6 +302,9 @@ impl Actor {
if let Some(c) = self.conn.take() {
c.acp.kill().await;
}
+ for root in self.thread_roots() {
+ self.set_session(Some(&root), None);
+ }
if self.session_id.is_some() {
self.forget_session();
self.notice(
@@ -272,40 +338,65 @@ impl Actor {
for id in ids {
self.answer_permission(&id, None).await;
}
- if let (Some(c), Some(sid)) = (&self.conn, &self.session_id) {
+ if let (Some(c), Some(sid)) = (&self.conn, &self.turn_session) {
let _ = c.acp.notify("session/cancel", json!({"sessionId": sid})).await;
}
}
async fn next_in_queue(&mut self, done_tx: &mpsc::UnboundedSender<Done>) {
+ let main = Lane::main(&self.cfg.id);
while self.turn.is_none() && !self.queue.is_empty() {
- if matches!(self.queue.front(), Some(Queued::Ask(_))) {
- let Some(Queued::Ask(ask)) = self.queue.pop_front() else { unreachable!("front is an ask") };
- if ask.reply.is_closed() {
+ match self.queue.front() {
+ Some(Queued::Ask(_)) => {
+ let Some(Queued::Ask(ask)) = self.queue.pop_front() else { unreachable!("front is an ask") };
+ if ask.reply.is_closed() {
+ continue;
+ }
+ let ids = [ask.entry_id.clone()];
+ let prompt = ask.prompt.clone();
+ self.active_ask = Some(ask);
+ let result = self.start_turn(main.clone(), &ids, &prompt, false, done_tx).await;
+ // Another bot's words are not facts learned from the user.
+ self.turn_text = None;
+ if let Err(e) = result {
+ self.start_failed(&e);
+ }
continue;
}
- let ids = [ask.entry_id.clone()];
- let prompt = ask.prompt.clone();
- self.active_ask = Some(ask);
- let result = self.start_turn(&ids, &prompt, false, done_tx).await;
- // Another bot's words are not facts learned from the user.
- self.turn_text = None;
- if let Err(e) = result {
- self.start_failed(&e);
+ Some(Queued::Group(_)) => {
+ let Some(Queued::Group(turn)) = self.queue.pop_front() else {
+ unreachable!("front is a group turn")
+ };
+ if turn.reply.is_closed() {
+ continue;
+ }
+ let (lane, prompt) = (turn.lane.clone(), turn.prompt.clone());
+ self.active_group = Some(turn);
+ let result = self.start_turn(lane, &[], &prompt, false, done_tx).await;
+ // The room is not the user's private chat: nothing here feeds memory.
+ self.turn_text = None;
+ if let Err(e) = result {
+ self.start_failed(&e);
+ }
+ continue;
}
- continue;
+ _ => {}
}
// Messages sent while the agent worked go out together as its next turn
- // without crossing a bot request: each ask gets its own reply.
+ // without crossing a bot request or another lane: each gets its own reply.
+ let Some(Queued::User { lane, .. }) = self.queue.front() else { continue };
+ let lane = lane.clone();
let mut batch = Vec::new();
- while matches!(self.queue.front(), Some(Queued::User { .. })) {
- if let Some(Queued::User { entry_id, text }) = self.queue.pop_front() {
+ while let Some(Queued::User { lane: l, .. }) = self.queue.front()
+ && *l == lane
+ {
+ if let Some(Queued::User { entry_id, text, .. }) = self.queue.pop_front() {
batch.push((entry_id, text));
}
}
let ids: Vec<String> = batch.iter().map(|(id, _)| id.clone()).collect();
let text = batch.iter().map(|(_, t)| t.as_str()).collect::<Vec<_>>().join("\n\n");
- if let Err(e) = self.start_turn(&ids, &text, false, done_tx).await {
+ if let Err(e) = self.start_turn(lane, &ids, &text, false, done_tx).await {
self.start_failed(&e);
}
}
@@ -313,6 +404,7 @@ impl Actor {
fn start_failed(&mut self, e: &anyhow::Error) {
self.complete_ask(Err(anyhow!("couldn't start recipient: {e:#}")));
+ self.complete_group(Err(anyhow!("couldn't start: {e:#}")));
let mut msg = format!("Couldn't start the agent: {e}");
if e.to_string().to_lowercase().contains("auth")
&& let Some(h) = crate::backends::harness(&self.cfg.backend)
@@ -326,6 +418,7 @@ impl Actor {
r.status = BotStatus::Error;
r.activity = "Couldn't start".into();
r.started_at = None;
+ r.lane = None;
});
self.hub.team.cancel_from(&self.cfg.id);
}
@@ -336,21 +429,32 @@ impl Actor {
}
}
+ fn complete_group(&mut self, result: Result<Option<String>>) {
+ if let Some(turn) = self.active_group.take() {
+ let _ = turn.reply.send(result);
+ }
+ }
+
/// Grok Bot's upgrade resume: the previous host process stopped mid-turn, so
/// the agent is told, in the same session, to finish without redoing steps.
- async fn resume_interrupted(&mut self, done_tx: &mpsc::UnboundedSender<Done>) {
+ async fn resume_interrupted(&mut self, lane: Lane, done_tx: &mpsc::UnboundedSender<Done>) {
self.set_inflight(false);
- if self.session_id.is_none() {
+ if self.session_for(lane.thread.as_deref()).is_none() {
return;
}
- if let Err(e) = self.start_turn(&[], RESUME_PROMPT, true, done_tx).await {
+ if let Err(e) = self.start_turn(lane, &[], RESUME_PROMPT, true, done_tx).await {
self.start_failed(&e);
}
}
- /// Marks a turn as running across host restarts (see [`Self::resume_interrupted`]).
+ /// Marks a turn in the bot's own chat or a thread as running across host restarts
+ /// (see [`Self::resume_interrupted`]); the thread root rides along.
fn set_inflight(&self, on: bool) {
- let value = if on { now_ms().to_string() } else { String::new() };
+ let value = match (&self.lane.thread, on) {
+ (_, false) => String::new(),
+ (Some(root), true) => format!("{}\t{root}", now_ms()),
+ (None, true) => now_ms().to_string(),
+ };
if let Err(error) = self.hub.store.kv_set(&inflight_key(&self.cfg.id), &value) {
tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't record the running turn");
}
@@ -362,9 +466,10 @@ impl Actor {
tokio::task::spawn_blocking(move || context::resolve(&hub.store, &cfg, &session)).await?
}
- /// Starts a turn for the given user entries (none for a hidden turn).
+ /// Starts a turn in `lane` for the given user entries (none for a hidden turn).
async fn start_turn(
&mut self,
+ lane: Lane,
entry_ids: &[String],
text: &str,
hidden: bool,
@@ -373,13 +478,14 @@ impl Actor {
let turn = entry_ids
.last()
.and_then(|id| self.hub.store.entry(id))
- .map_or_else(|| self.hub.store.max_turn(&self.cfg.id), |e| e.turn);
+ .map_or_else(|| self.hub.store.max_turn(&lane.chat) + i64::from(self.active_group.is_some()), |e| e.turn);
for id in entry_ids {
if let Some(mut e) = self.hub.store.entry(id) {
e.data["status"] = "sent".into();
self.hub.set_entry(id, &e.data);
}
}
+ self.lane = lane.clone();
self.turn = Some(turn);
self.turn_text = (!hidden).then(|| text.to_owned());
self.announce = None;
@@ -390,16 +496,18 @@ impl Actor {
self.tools.clear();
self.plan_entry = None;
self.last_text = None;
- // A delegated turn has no live waiter after a host restart. Its persisted
+ // A delegated or group turn has no live waiter after a host restart. Its persisted
// notices are marked interrupted instead of silently repeating work.
- self.set_inflight(self.active_ask.is_none());
+ self.set_inflight(self.active_ask.is_none() && self.active_group.is_none());
self.hub.set_runtime(&self.id(), |r| {
r.status = BotStatus::Working;
r.activity = if hidden { "Picking up where it left off…" } else { "Starting…" }.into();
r.started_at = Some(now_ms());
+ r.lane = Some(lane.clone());
});
- self.ensure_session().await?;
+ let slot = self.slot(&lane);
+ self.ensure_session(slot.as_deref()).await?;
if hidden && self.session_fresh {
// The interrupted session couldn't be resumed, so there is nothing to continue.
self.turn = None;
@@ -409,6 +517,7 @@ impl Actor {
r.status = BotStatus::Idle;
r.activity = String::new();
r.started_at = None;
+ r.lane = None;
});
return Ok(());
}
@@ -425,9 +534,12 @@ impl Actor {
}
}
let claude = self.conn.as_ref().is_some_and(|c| c.claude);
- let sid = self.session_id.clone().ok_or_else(|| anyhow!("no session"))?;
+ let sid = self.turn_session.clone().ok_or_else(|| anyhow!("no session"))?;
let snapshot = self.snapshot(&sid).await?;
let mut prompt = text.to_owned();
+ if let Some(intro) = self.thread_intro.take() {
+ prompt = format!("{intro}\n\n{prompt}");
+ }
if self.session_fresh {
self.session_fresh = false;
// Claude already has the instructions as its system prompt.
@@ -452,6 +564,86 @@ impl Actor {
Ok(())
}
+ /// Which session a lane's turns use: a thread of the bot's own chat has its own
+ /// (by root); its chat and every group lane use the main one.
+ fn slot(&self, lane: &Lane) -> Option<String> {
+ (lane.chat == self.cfg.id).then(|| lane.thread.clone()).flatten()
+ }
+
+ fn session_for(&mut self, slot: Option<&str>) -> Option<String> {
+ let Some(root) = slot else { return self.session_id.clone() };
+ if let Some(sid) = self.thread_sessions.get(root) {
+ return Some(sid.clone());
+ }
+ let sid = self.hub.store.kv_get(&lane_key("session", &self.cfg.id, &Lane::in_thread(&self.cfg.id, root)));
+ let sid = sid.filter(|s| !s.is_empty())?;
+ self.thread_sessions.insert(root.to_owned(), sid.clone());
+ Some(sid)
+ }
+
+ fn set_session(&mut self, slot: Option<&str>, sid: Option<&str>) {
+ let Some(root) = slot else {
+ self.session_id = sid.map(str::to_owned);
+ if let Err(error) = self.hub.store.set_session(&self.cfg.id, sid) {
+ tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't store the session");
+ }
+ return;
+ };
+ match sid {
+ Some(s) => self.thread_sessions.insert(root.to_owned(), s.to_owned()),
+ None => self.thread_sessions.remove(root),
+ };
+ let key = lane_key("session", &self.cfg.id, &Lane::in_thread(&self.cfg.id, root));
+ if let Err(error) = self.hub.store.kv_set(&key, sid.unwrap_or_default()) {
+ tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't store the thread session");
+ }
+ }
+
+ /// Roots of the threads that have a session (stored or loaded).
+ fn thread_roots(&self) -> Vec<String> {
+ let prefix = lane_key("session", &self.cfg.id, &Lane::main(&self.cfg.id)) + "/";
+ let mut roots: Vec<String> = self.thread_sessions.keys().cloned().collect();
+ roots.extend(
+ self.hub.store.kv_prefix(&prefix).into_iter().filter_map(|k| k.strip_prefix(&prefix).map(str::to_owned)),
+ );
+ roots.sort();
+ roots.dedup();
+ roots
+ }
+
+ /// What a new thread session is told first: where the thread branches off.
+ fn thread_intro(&self, root: &str, forked: bool) -> String {
+ let quote = |e: &Entry| {
+ let who = if e.kind == EntryKind::User.as_str() { "the user" } else { "you" };
+ format!("{who}: \"{}\"", acp::truncate(e.data["text"].as_str().unwrap_or_default(), 1500))
+ };
+ let Some(root_entry) = self.hub.store.entry(root) else {
+ return "[Thread] The user opened a thread off your main chat. It is a separate branch of the conversation.".into();
+ };
+ if forked {
+ return format!(
+ "[Thread] The user opened a thread on this message from your main chat — {}. This thread is its own \
+ branch: it starts from everything said so far, and nothing said here reaches the main chat.",
+ quote(&root_entry)
+ );
+ }
+ // A fresh session: bring the lines leading up to the message along.
+ let before = self.hub.store.history(&self.cfg.id, root_entry.seq, 12).unwrap_or_default();
+ let lines: Vec<String> = before
+ .iter()
+ .chain(std::iter::once(&root_entry))
+ .filter(|e| {
+ e.kind == EntryKind::User.as_str() || (e.kind == EntryKind::Agent.as_str() && e.data["final"] == true)
+ })
+ .map(quote)
+ .collect();
+ format!(
+ "[Thread] The user opened a thread on the last of these messages from your main chat (oldest first):\n{}\n\
+ This thread is its own branch of the conversation; nothing said here reaches the main chat.",
+ lines.join("\n")
+ )
+ }
+
/// ACP connectors, team collaboration, and optional computer control.
fn mcp_servers(&self, http_ok: bool) -> Value {
let all = crate::market::connectors(&self.hub.store);
@@ -474,7 +666,9 @@ impl Actor {
Value::Array(servers)
}
- async fn ensure_session(&mut self) -> Result<()> {
+ /// Makes sure the agent runs and `slot`'s session (main, or a thread's) is live;
+ /// sets `turn_session`. A thread without one forks the main session when it can.
+ async fn ensure_session(&mut self, slot: Option<&str>) -> Result<()> {
if self.tools_changed && self.turn.is_none() {
self.tools_changed = false;
if let Some(c) = self.conn.take() {
@@ -513,28 +707,52 @@ impl Actor {
}
let servers = self.mcp_servers(self.conn.as_ref().is_some_and(|c| c.mcp_http));
let claude = self.conn.as_ref().is_some_and(|c| c.claude);
+ let mut forked = false;
+ if let Some(root) = slot
+ && self.session_for(slot).is_none()
+ && let Some(main) = self.session_id.clone()
+ && self.conn.as_ref().is_some_and(|c| c.sessions.fork)
+ {
+ self.hub.set_runtime(&self.cfg.id, |r| r.activity = "Opening the thread…".into());
+ let conn = self.conn.as_ref().ok_or_else(|| anyhow!("agent not running"))?;
+ let res = conn
+ .acp
+ .request("session/fork", json!({"sessionId": main, "cwd": self.cfg.cwd, "mcpServers": servers}))
+ .await;
+ if let Some(sid) = res.ok().and_then(|r| r["sessionId"].as_str().map(str::to_owned)) {
+ self.set_session(slot, Some(&sid));
+ forked = true;
+ } else {
+ tracing::warn!(bot = %self.cfg.id, "session/fork failed; the thread starts fresh");
+ }
+ if forked {
+ self.thread_intro = Some(self.thread_intro(root, true));
+ }
+ }
// Claude gets the frozen instructions as its system prompt. When a compaction
// re-rendered them, loading the session again swaps the prompt in (the adapter
// rebuilds its query and resumes the same conversation).
- let snapshot = match (&self.session_id, claude) {
+ let current = self.session_for(slot);
+ let snapshot = match (&current, claude) {
(Some(sid), true) => Some(self.snapshot(sid).await?),
_ => None,
};
let Some(conn) = self.conn.as_mut() else { bail!("agent not running") };
- if let Some(sid) = self.session_id.clone() {
+ if let Some(sid) = current {
let prompt_current = snapshot
.as_ref()
.is_none_or(|s| self.applied_system.as_ref().is_some_and(|(a, t)| *a == sid && *t == s.system));
if conn.loaded.contains(&sid) && prompt_current {
+ self.turn_session = Some(sid);
return Ok(());
}
- if !conn.can_load {
+ if !conn.sessions.load {
self.notice(
"This agent can't resume sessions after a restart — starting a fresh one.",
NoticeStyle::Divider,
);
- self.session_id = None;
- return Box::pin(self.ensure_session()).await;
+ self.set_session(slot, None);
+ return Box::pin(self.ensure_session(slot)).await;
}
self.hub.set_runtime(&self.cfg.id, |r| r.activity = "Resuming session…".into());
let mut params = json!({"sessionId": sid, "cwd": self.cfg.cwd, "mcpServers": servers});
@@ -552,12 +770,14 @@ impl Actor {
Ok(_) => {
conn.loaded.insert(sid.clone());
if let Some(s) = snapshot {
- self.applied_system = Some((sid, s.system));
+ self.applied_system = Some((sid.clone(), s.system));
}
+ self.turn_session = Some(sid);
return Ok(());
}
Err(e) => {
tracing::warn!(error = format!("{e:#}"), "session/load failed; starting fresh");
+ self.thread_intro = None;
self.notice("Couldn't resume the previous session — starting a fresh one.", NoticeStyle::Divider);
}
}
@@ -590,9 +810,12 @@ impl Actor {
tracing::warn!(model, error = format!("{e:#}"), "couldn't set model");
}
}
- self.session_id = Some(sid.clone());
+ self.set_session(slot, Some(&sid));
self.session_fresh = true;
- self.hub.store.set_session(&self.cfg.id, Some(&sid))?;
+ self.turn_session = Some(sid.clone());
+ if let Some(root) = slot {
+ self.thread_intro = Some(self.thread_intro(root, false));
+ }
context::adopt(&self.hub.store, &self.cfg, &sid, system.clone())?;
if claude {
self.applied_system = Some((sid, system));
@@ -625,12 +848,17 @@ impl Actor {
}
}
let mut final_text = None;
+ let grouped = self.active_group.is_some();
if let Some(id) = self.last_text.take().filter(|_| !stopped)
&& let Some(mut e) = self.hub.store.entry(&id)
{
- e.data["final"] = true.into();
- final_text = e.data["text"].as_str().map(str::to_owned);
- self.hub.set_entry(&id, &e.data);
+ let text = e.data["text"].as_str().map(str::to_owned);
+ // A pass in a room stays in the trace; the room doesn't see it.
+ if !(grouped && text.as_deref().is_none_or(crate::group::is_pass)) {
+ e.data["final"] = true.into();
+ self.hub.set_entry(&id, &e.data);
+ final_text = text;
+ }
}
let stop_reason = match &done {
Ok(v) => v["stopReason"].as_str().unwrap_or("end_turn").to_owned(),
@@ -661,6 +889,7 @@ impl Actor {
.ok_or_else(|| anyhow!("recipient finished without a text reply"))
};
self.complete_ask(reply);
+ self.complete_group(if stopped || failed { Err(anyhow!("stopped")) } else { Ok(final_text.clone()) });
self.turn = None;
self.set_inflight(false);
// The message reached the agent: the profile update it carried is now known to it.
@@ -678,9 +907,11 @@ impl Actor {
r.status = if failed { BotStatus::Error } else { BotStatus::Idle };
r.activity = String::new();
r.started_at = None;
+ r.lane = None;
});
self.hub.team.cancel_from(&self.cfg.id);
- if !self.stop_requested && !delegated {
+ // A room turn's news comes from the group once the room is done (see `group`).
+ if !self.stop_requested && !delegated && !grouped {
let body =
final_text.unwrap_or_else(|| if failed { "The agent failed.".into() } else { "Finished.".into() });
push::notify(&self.hub, &self.cfg, &self.cfg.name, &body, AlertKind::Done);
@@ -703,7 +934,7 @@ impl Actor {
}
Some(Incoming::Notification { method, params }) => {
if method == "session/update"
- && params["sessionId"].as_str() == self.session_id.as_deref()
+ && params["sessionId"].as_str() == self.turn_session.as_deref()
&& self.turn.is_some()
{
self.on_update(&params["update"]);
@@ -748,7 +979,7 @@ impl Actor {
});
merge_tool_content(&mut data, &u["content"]);
let title = data["title"].as_str().unwrap_or("Tool").to_owned();
- if let Some(e) = self.hub.add_entry(&self.cfg.id, EntryKind::Tool, turn, &data) {
+ if let Some(e) = self.add(EntryKind::Tool, turn, data) {
self.tools.insert(tool_id, e.id);
}
self.set_activity(&title);
@@ -776,7 +1007,7 @@ impl Actor {
// The agent summarized its context: the next turn gets freshly rendered
// instructions and memory (see `context`).
"compaction_update" if u["status"] == "completed" => {
- let Some(sid) = &self.session_id else { return };
+ let Some(sid) = &self.turn_session else { return };
let id = u["compactionId"].as_str().unwrap_or_default();
match context::bump_epoch(&self.hub.store, &self.cfg.id, sid, id) {
Ok(true) => self.notice("Earlier context was summarized to make room.", NoticeStyle::Info),
@@ -799,7 +1030,7 @@ impl Actor {
self.hub.set_entry(id, &data);
}
None => {
- if let Some(e) = self.hub.add_entry(&self.cfg.id, EntryKind::Plan, turn, &data) {
+ if let Some(e) = self.add(EntryKind::Plan, turn, data) {
self.plan_entry = Some(e.id);
}
}
@@ -853,14 +1084,16 @@ impl Actor {
});
let turn = self.turn.unwrap_or(0);
self.close_seg();
- if let Some(e) = self.hub.add_entry(&self.cfg.id, EntryKind::Permission, turn, &data) {
+ if let Some(e) = self.add(EntryKind::Permission, turn, data) {
self.perms.insert(e.id, rpc_id);
}
self.hub.set_runtime(&self.cfg.id, |r| {
r.status = BotStatus::NeedsInput;
r.activity = format!("Needs approval: {title}");
});
- push::notify(&self.hub, &self.cfg, &format!("{} needs you", self.cfg.name), &title, AlertKind::NeedsInput);
+ // Tapping it opens where the card is: the group, for a room turn.
+ let target = self.hub.store.bot(&self.lane.chat).ok().flatten().map_or_else(|| self.cfg.clone(), |r| r.config);
+ push::notify(&self.hub, &target, &format!("{} needs you", self.cfg.name), &title, AlertKind::NeedsInput);
}
async fn answer_permission(&mut self, entry_id: &str, option_id: Option<String>) {
@@ -898,7 +1131,7 @@ impl Actor {
SegKind::Text => (EntryKind::Agent, json!({"text": text, "final": false})),
SegKind::Thought => (EntryKind::Thought, json!({"text": text})),
};
- if let Some(e) = self.hub.add_entry(&self.cfg.id, k, self.turn.unwrap_or(0), &data) {
+ if let Some(e) = self.add(k, self.turn.unwrap_or(0), data) {
if kind == SegKind::Text {
self.last_text = Some(e.id.clone());
}
@@ -945,17 +1178,26 @@ impl Actor {
}
}
- /// Drops the ACP session so the next turn starts a fresh one.
+ /// Drops the main ACP session so the next turn starts a fresh one.
fn forget_session(&mut self) {
- self.session_id = None;
- if let Err(error) = self.hub.store.set_session(&self.cfg.id, None) {
- tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't clear the stored session");
- }
+ self.set_session(None, None);
+ }
+
+ /// Adds an entry to the current lane, signed by this bot (a group shows who said it).
+ fn add(&self, kind: EntryKind, turn: i64, mut data: Value) -> Option<Entry> {
+ data["author"] = self.cfg.id.clone().into();
+ self.hub.add_entry(&self.lane, kind, turn, &data)
}
+ /// A notice in the running turn's lane (or the bot's own chat between turns).
fn notice(&self, text: &str, style: NoticeStyle) {
- let turn = self.turn.unwrap_or_else(|| self.hub.store.max_turn(&self.cfg.id));
- self.hub.add_entry(&self.cfg.id, EntryKind::Notice, turn, &json!({"text": text, "style": style}));
+ let Some(turn) = self.turn else {
+ let main = Lane::main(&self.cfg.id);
+ let turn = self.hub.store.max_turn(&self.cfg.id);
+ self.hub.add_entry(&main, EntryKind::Notice, turn, &json!({"text": text, "style": style}));
+ return;
+ };
+ self.add(EntryKind::Notice, turn, json!({"text": text, "style": style}));
}
}
@@ -1018,10 +1260,13 @@ pub(crate) async fn start_agent(command: &str, cwd: &str, env: &[(String, String
return Err(anyhow!("the agent didn't answer the ACP handshake within {}s", budget.as_secs()));
}
};
- let can_load = init["agentCapabilities"]["loadSession"].as_bool().unwrap_or(false);
+ let sessions = SessionCaps {
+ load: init["agentCapabilities"]["loadSession"].as_bool().unwrap_or(false),
+ fork: init["agentCapabilities"]["sessionCapabilities"]["fork"].is_object(),
+ };
let mcp_http = init["agentCapabilities"]["mcpCapabilities"]["http"].as_bool().unwrap_or(false);
let claude = init["agentCapabilities"]["_meta"]["claudeCode"].is_object();
- Ok(Conn { acp, rx, can_load, mcp_http, claude, loaded: HashSet::new() })
+ Ok(Conn { acp, rx, sessions, mcp_http, claude, loaded: HashSet::new() })
}
async fn recv_incoming(conn: &mut Option<Conn>) -> Option<Incoming> {
diff --git a/host/src/context.rs b/host/src/context.rs
index 67da6ea9..1b38c8f7 100644
--- a/host/src/context.rs
+++ b/host/src/context.rs
@@ -44,18 +44,20 @@ pub struct Snapshot {
pub announced: Identity,
}
-fn key(bot_id: &str) -> String {
- format!("context.{bot_id}")
+// A bot talks in several lanes (its chat, threads, groups), each its own session: snapshots
+// and epochs are kept per session.
+fn key(bot_id: &str, session: &str) -> String {
+ format!("context.{bot_id}.{session}")
}
-fn epoch_key(bot_id: &str) -> String {
- format!("context.epoch.{bot_id}")
+fn epoch_key(bot_id: &str, session: &str) -> String {
+ format!("context.epoch.{bot_id}.{session}")
}
/// `(epoch, last compaction id)` stored as `session \t epoch \t id`.
fn epoch_state(store: &Store, bot_id: &str, session: &str) -> (u32, String) {
store
- .kv_get(&epoch_key(bot_id))
+ .kv_get(&epoch_key(bot_id, session))
.and_then(|v| {
let mut parts = v.splitn(3, '\t');
(parts.next()? == session).then(|| {
@@ -77,23 +79,23 @@ pub fn bump_epoch(store: &Store, bot_id: &str, session: &str, compaction_id: &st
if !compaction_id.is_empty() && compaction_id == last {
return Ok(false);
}
- store.kv_set(&epoch_key(bot_id), &format!("{session}\t{}\t{compaction_id}", n + 1))?;
+ store.kv_set(&epoch_key(bot_id, session), &format!("{session}\t{}\t{compaction_id}", n + 1))?;
Ok(true)
}
-fn load(store: &Store, bot_id: &str) -> Option<Snapshot> {
- store.kv_get(&key(bot_id)).and_then(|v| serde_json::from_str(&v).ok())
+fn load(store: &Store, bot_id: &str, session: &str) -> Option<Snapshot> {
+ store.kv_get(&key(bot_id, session)).and_then(|v| serde_json::from_str(&v).ok())
}
fn save(store: &Store, bot_id: &str, s: &Snapshot) -> Result<()> {
- store.kv_set(&key(bot_id), &serde_json::to_string(s)?)
+ store.kv_set(&key(bot_id, &s.session), &serde_json::to_string(s)?)
}
/// The snapshot for `session` at its current epoch, rendering a fresh one when
/// the stored one belongs to another session or an earlier epoch. Reads memory files.
pub fn resolve(store: &Store, cfg: &BotConfig, session: &str) -> Result<Snapshot> {
let epoch = epoch(store, &cfg.id, session);
- if let Some(s) = load(store, &cfg.id).filter(|s| s.session == session && s.epoch == epoch) {
+ if let Some(s) = load(store, &cfg.id, session).filter(|s| s.epoch == epoch) {
return Ok(s);
}
adopt(store, cfg, session, render(store, cfg))
@@ -129,6 +131,10 @@ pub fn render(store: &Store, cfg: &BotConfig) -> String {
.to_owned(),
);
lines.push(crate::team::INSTRUCTIONS.to_owned());
+ lines.push(
+ "Your history is shared across your chats: a message that starts with [Group chat: ...] is your turn in a group chat, where the user and the other bots see only your final reply. Everything else here is your private chat with the user: don't @-mention anyone in it, and don't assume a group sees it."
+ .to_owned(),
+ );
if let Some(skills) = crate::market::skills_brief(store, &cfg.skills) {
lines.push(skills);
}
@@ -169,7 +175,7 @@ pub fn profile_update(store: &Store, snapshot: &Snapshot, cfg: &BotConfig) -> Op
/// After the turn that carried an update reached the agent: remember it heard
/// `identity`, unless the snapshot moved on meanwhile (a compaction re-rendered it).
pub fn mark_announced(store: &Store, bot_id: &str, turn_snapshot: &Snapshot, identity: Identity) -> Result<()> {
- let Some(mut current) = load(store, bot_id) else { return Ok(()) };
+ let Some(mut current) = load(store, bot_id, &turn_snapshot.session) else { return Ok(()) };
if current.session != turn_snapshot.session
|| current.epoch != turn_snapshot.epoch
|| current.system != turn_snapshot.system
diff --git a/host/src/group.rs b/host/src/group.rs
new file mode 100644
index 00000000..b23a3904
--- /dev/null
+++ b/host/src/group.rs
@@ -0,0 +1,501 @@
+//! Group chats (Grok Bot's design): several bots and the user in one conversation.
+//!
+//! A group is a roster row (`BotKind::Group`) with a member list and its own
+//! transcript, but no agent. When the user writes, the group runs a *room turn*:
+//! up to [`MAX_ROUNDS`] rounds in which the members answer one at a time, each in
+//! its **own** session (a member's history is unified across its chats), told
+//! what was said since it last spoke. Everyone answers unless the new messages
+//! @-mention someone; a member with nothing to add says `(pass)`, and a round
+//! where nobody speaks ends the turn. A newer message in the same lane (or Stop)
+//! moves the lane's epoch, which ends a running room turn before its next speaker.
+//!
+//! Threads work the same way inside a group: the room turn runs in the thread's
+//! lane and only sees the thread.
+
+use crate::LockExt;
+use crate::bot::Cmd;
+use crate::hub::Hub;
+use crate::push::{self, AlertKind};
+use crate::store::{BotConfig, BotKind, Entry, EntryKind, Lane, Store};
+use anyhow::{Result, anyhow, bail};
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+use tokio::sync::oneshot;
+
+pub const MAX_MEMBERS: usize = 6;
+const MAX_ROUNDS: usize = 3;
+/// Replies per room turn, across all rounds.
+const MAX_REPLIES: usize = 10;
+/// Room lines a member is shown per turn.
+const HISTORY_LINES: i64 = 24;
+/// A bot's line in another member's prompt is clipped (the user's never is).
+const LINE_CHARS: usize = 2000;
+const PASS: &str = "(pass)";
+
+/// One member's turn in a room, queued on its actor like any other turn.
+pub struct GroupTurn {
+ pub lane: Lane,
+ pub prompt: String,
+ /// The reply the room sees, or `None` for a pass.
+ pub reply: oneshot::Sender<Result<Option<String>>>,
+}
+
+/// Room turn epochs per lane (`Lane::key`).
+#[derive(Default)]
+pub struct Rooms(Mutex<HashMap<String, u64>>);
+
+impl Rooms {
+ fn next(&self, lane: &Lane) -> u64 {
+ let mut map = self.0.locked();
+ let epoch = map.entry(lane.key()).or_default();
+ *epoch += 1;
+ *epoch
+ }
+
+ fn current(&self, lane: &Lane, epoch: u64) -> bool {
+ self.0.locked().get(&lane.key()).copied() == Some(epoch)
+ }
+
+ /// Stop: ends every room turn in `group` (main chat and threads) and the member turns in it.
+ pub fn stop(&self, hub: &Hub, group: &str) {
+ let thread_prefix = format!("{group}/");
+ let mut stopped = false;
+ for (key, epoch) in self.0.locked().iter_mut() {
+ if key == group || key.starts_with(&thread_prefix) {
+ *epoch += 1;
+ stopped = true;
+ }
+ }
+ if !stopped {
+ return;
+ }
+ let Ok(Some(row)) = hub.store.bot(group) else { return };
+ for member in &row.config.members {
+ let _ = hub.send_cmd(member, Cmd::CancelGroup { chat: group.to_owned() });
+ }
+ }
+}
+
+/// Existing, distinct agent bots (not groups, not the group itself), at most [`MAX_MEMBERS`].
+pub fn valid_members(store: &Store, group_id: &str, ids: &[String]) -> Result<Vec<String>> {
+ let mut out: Vec<String> = vec![];
+ for id in ids.iter().map(|i| i.trim()) {
+ if id.is_empty() || id == group_id || out.iter().any(|o| o == id) {
+ continue;
+ }
+ match store.bot(id)? {
+ Some(row) if !row.deleted && row.config.kind == BotKind::Agent => out.push(id.to_owned()),
+ Some(row) if row.config.is_group() => bail!("a group can't be a member of another group"),
+ _ => {}
+ }
+ }
+ if out.is_empty() {
+ bail!("a group needs at least one bot");
+ }
+ if out.len() > MAX_MEMBERS {
+ bail!("groups can have up to {MAX_MEMBERS} bots");
+ }
+ Ok(out)
+}
+
+/// A group whose members are exactly `members`.
+pub fn with_members(store: &Store, members: &[String]) -> Result<Option<String>> {
+ let mut wanted = members.to_vec();
+ wanted.sort();
+ Ok(store.bots()?.into_iter().find_map(|row| {
+ let mut have = row.config.members.clone();
+ have.sort();
+ (!row.deleted && row.config.is_group() && have == wanted).then_some(row.config.id)
+ }))
+}
+
+/// The user wrote in a group lane: start a room turn there (ending one still running).
+pub fn start(hub: &Arc<Hub>, group: &BotConfig, lane: Lane) {
+ let epoch = hub.groups.next(&lane);
+ let (hub, group_id) = (hub.clone(), group.id.clone());
+ tokio::spawn(async move {
+ if let Err(error) = run(&hub, &group_id, &lane, epoch).await {
+ tracing::warn!(group = group_id, error = format!("{error:#}"), "room turn failed");
+ }
+ });
+}
+
+async fn run(hub: &Arc<Hub>, group_id: &str, lane: &Lane, epoch: u64) -> Result<()> {
+ let mut replies = 0;
+ let mut last_reply: Option<(String, String)> = None;
+ for round in 0..MAX_ROUNDS {
+ let group = hub.store.bot(group_id)?.filter(|r| !r.deleted).ok_or_else(|| anyhow!("group deleted"))?.config;
+ let members = members(hub, &group);
+ let since_user = since_last_user_message(hub, lane)?;
+ let mut speakers = responders(&members, &since_user);
+ // Each round starts one member later, so the same bot doesn't always speak first.
+ if !speakers.is_empty() {
+ let offset = round % speakers.len();
+ speakers.rotate_left(offset);
+ }
+ let mut spoke = 0;
+ for member in &speakers {
+ if !hub.groups.current(lane, epoch) || replies >= MAX_REPLIES {
+ return Ok(());
+ }
+ let prompt = member_prompt(hub, &group, &members, member, lane)?;
+ let (reply, answer) = oneshot::channel();
+ if hub.send_cmd(&member.id, Cmd::Group(GroupTurn { lane: lane.clone(), prompt, reply })).is_err() {
+ continue;
+ }
+ // A failed, cancelled or overdue member turn counts as a pass; its error shows in the room.
+ if let Ok(Ok(Ok(Some(text)))) = tokio::time::timeout(crate::team::ASK_TIMEOUT, answer).await {
+ spoke += 1;
+ replies += 1;
+ last_reply = Some((member.name.clone(), text));
+ }
+ }
+ if spoke == 0 {
+ break;
+ }
+ }
+ if let Some((name, text)) = last_reply
+ && let Some(group) = hub.store.bot(group_id)?.map(|r| r.config)
+ {
+ push::notify(hub, &group, &format!("{name} in {}", group.name), &text, AlertKind::Done);
+ }
+ Ok(())
+}
+
+fn members(hub: &Hub, group: &BotConfig) -> Vec<BotConfig> {
+ group
+ .members
+ .iter()
+ .filter_map(|id| hub.store.bot(id).ok().flatten())
+ .filter(|r| !r.deleted)
+ .map(|r| r.config)
+ .collect()
+}
+
+/// The lane's messages since the user last wrote there, that message included.
+fn since_last_user_message(hub: &Hub, lane: &Lane) -> Result<Vec<Entry>> {
+ let recent = hub.store.messages_after(lane, 0, HISTORY_LINES)?;
+ let start = recent.iter().rposition(|e| e.kind == EntryKind::User.as_str()).unwrap_or(0);
+ Ok(recent[start..].to_vec())
+}
+
+/// Who answers: the members @-mentioned since the user's last message, or everyone
+/// when nobody (or `@all` / `@everyone`) is.
+fn responders<'a>(members: &'a [BotConfig], messages: &[Entry]) -> Vec<&'a BotConfig> {
+ let texts: Vec<&str> = messages.iter().filter_map(|e| e.data["text"].as_str()).collect();
+ let everyone = texts.iter().any(|t| mentions(t, "all") || mentions(t, "everyone"));
+ let named: Vec<&BotConfig> =
+ members.iter().filter(|m| texts.iter().any(|t| handles(&m.name).iter().any(|h| mentions(t, h)))).collect();
+ if everyone || named.is_empty() { members.iter().collect() } else { named }
+}
+
+/// Ways to @-mention a bot: its full name, without spaces, or its first word (lowercased).
+fn handles(name: &str) -> Vec<String> {
+ let lower = name.trim().to_lowercase();
+ let mut out = vec![lower.clone(), lower.split_whitespace().collect::<String>()];
+ if let Some(first) = lower.split_whitespace().next() {
+ out.push(first.to_owned());
+ }
+ out.retain(|h| !h.is_empty());
+ out.dedup();
+ out
+}
+
+/// `@handle` in `text`, not followed by more of a Latin word (`@al` isn't `@alice`).
+/// CJK names are often followed straight by the message, so only ASCII letters end a match early.
+fn mentions(text: &str, handle: &str) -> bool {
+ let lower = text.to_lowercase();
+ let needle = format!("@{handle}");
+ lower
+ .match_indices(&needle)
+ .any(|(i, _)| lower[i + needle.len()..].chars().next().is_none_or(|c| !(c.is_ascii_alphanumeric() || c == '_')))
+}
+
+fn member_prompt(hub: &Hub, group: &BotConfig, members: &[BotConfig], me: &BotConfig, lane: &Lane) -> Result<String> {
+ let peers: Vec<&BotConfig> = members.iter().filter(|m| m.id != me.id).collect();
+ let peer_names = if peers.is_empty() {
+ "just the user".to_owned()
+ } else {
+ peers.iter().map(|p| p.name.as_str()).collect::<Vec<_>>().join(", ")
+ };
+ let mut out = vec![format!(
+ "You are {}, one participant in a group chat (\"{}\") with the user and {peer_names}.",
+ me.name, group.name
+ )];
+ if !peers.is_empty() {
+ out.push("Other participants in the room:".into());
+ for p in &peers {
+ let about =
+ if p.description.trim().is_empty() { String::new() } else { format!(" ({})", p.description.trim()) };
+ out.push(format!("- {}{about}", p.name));
+ }
+ }
+ out.push(format!(
+ "You have your full toolkit here. Do the work first, then answer: your final reply of this turn is \
+ the one message the room sees. Keep it short and conversational. @-mention another participant only \
+ when you need them to act. If you have nothing new worth adding, reply exactly \"{PASS}\". Never \
+ reveal private one-on-one context."
+ ));
+ out.push(String::new());
+
+ let seen = hub.store.last_spoke(lane, &me.id);
+ let mut lines: Vec<String> = vec![];
+ let mut header = format!("[Group chat: \"{}\" - with {peer_names}]", group.name);
+ if let Some(root) = lane.thread.as_deref().and_then(|r| hub.store.entry(r)) {
+ header = format!("[Group chat: \"{}\", in a thread - with {peer_names}]", group.name);
+ if seen == 0 {
+ lines.push(format!("(thread started on) {}", line(hub, &root, me)));
+ }
+ }
+ for e in hub.store.messages_after(lane, seen, HISTORY_LINES)? {
+ lines.push(line(hub, &e, me));
+ }
+ out.push(header);
+ if lines.is_empty() {
+ out.push("No new messages in the room since your last turn.".into());
+ } else {
+ out.push("New messages in the room (oldest first):".into());
+ out.extend(lines);
+ }
+ out.push(String::new());
+ out.push(format!(
+ "It's your turn, {}. Reply to the room if you have something worth adding, or reply exactly \"{PASS}\" if you don't.",
+ me.name
+ ));
+ Ok(out.join("\n"))
+}
+
+fn line(hub: &Hub, e: &Entry, me: &BotConfig) -> String {
+ let text = e.data["text"].as_str().unwrap_or_default();
+ if e.kind == EntryKind::User.as_str() {
+ return format!("User: {text}");
+ }
+ let author = e.data["author"].as_str().unwrap_or_default();
+ let text = crate::acp::truncate(text, LINE_CHARS);
+ if author == me.id { format!("{} (you): {text}", me.name) } else { format!("{}: {text}", hub.bot_name(author)) }
+}
+
+/// A member's final text is a pass (the room doesn't see it).
+pub fn is_pass(text: &str) -> bool {
+ let t = text.trim().trim_matches(|c: char| c == '"' || c == '.' || c == '*').to_lowercase();
+ t.is_empty() || t == PASS || t == "pass"
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn bot(id: &str, name: &str) -> BotConfig {
+ serde_json::from_value(json!({"id": id, "name": name, "backend": "claude", "cwd": "/tmp"})).expect("valid bot")
+ }
+
+ fn said(text: &str) -> Entry {
+ Entry {
+ id: "e".into(),
+ seq: 1,
+ bot_id: "g".into(),
+ thread_id: None,
+ rev: 1,
+ kind: "user".into(),
+ turn: 1,
+ data: json!({"text": text}),
+ created_at: 0,
+ updated_at: 0,
+ }
+ }
+
+ #[test]
+ fn mentions_pick_responders_and_no_mention_means_everyone() {
+ let members = [bot("a", "Alice Chen"), bot("b", "Bob"), bot("c", "尼采課")];
+ let ids = |m: &[BotConfig], text: &str| -> Vec<String> {
+ responders(m, &[said(text)]).into_iter().map(|b| b.id.clone()).collect()
+ };
+ assert_eq!(ids(&members, "hi all"), ["a", "b", "c"]);
+ assert_eq!(ids(&members, "@bob can you look"), ["b"]);
+ assert_eq!(ids(&members, "@alicechen and @Alice"), ["a"]);
+ assert_eq!(ids(&members, "@尼采課幫我整理"), ["c"], "CJK names can run into the message");
+ assert_eq!(ids(&members, "@bobby?"), ["a", "b", "c"], "a longer word isn't a mention");
+ assert_eq!(ids(&members, "@all go"), ["a", "b", "c"]);
+ }
+
+ use crate::devices::Caller;
+ use crate::hub::BotStatus;
+ use std::path::PathBuf;
+ use std::time::Duration;
+
+ /// A host with agent bots `a` and `b` (the scripted fixture agent) and a group of both.
+ struct Room {
+ hub: Arc<Hub>,
+ dir: PathBuf,
+ group: String,
+ }
+
+ impl Room {
+ fn new() -> Self {
+ let dir = std::env::temp_dir().join(format!("codync-group-{}", uuid::Uuid::new_v4()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let store = Store::open(&dir.join("test.db")).unwrap();
+ let agent = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/team_agent.py");
+ for id in ["a", "b"] {
+ let cwd = dir.join(id);
+ std::fs::create_dir_all(&cwd).unwrap();
+ let cfg: BotConfig = serde_json::from_value(json!({
+ "id": id, "name": id, "backend": "fixture", "cwd": cwd,
+ "command": format!("python3 -u '{}'", agent.display()), "notify": false,
+ }))
+ .unwrap();
+ store.save_bot(&cfg).unwrap();
+ }
+ let hub = Hub::new(
+ store,
+ "test-host".into(),
+ crate::identity::Identity::load_or_create(&dir).unwrap(),
+ "test-token".into(),
+ 19222,
+ );
+ hub.start().unwrap();
+ let group = hub
+ .create_bot(
+ serde_json::from_value(
+ json!({"id": "", "kind": "group", "name": "Crew", "members": ["a", "b", "a"]}),
+ )
+ .unwrap(),
+ )
+ .unwrap();
+ let group = group["id"].as_str().unwrap().to_owned();
+ Self { hub, dir, group }
+ }
+
+ async fn send(&self, text: &str, thread: Option<&str>) -> Entry {
+ let sent = crate::api::dispatch(
+ &self.hub,
+ &Caller::Local,
+ "send",
+ json!({"botId": self.group, "text": text, "threadId": thread}),
+ )
+ .await
+ .unwrap();
+ serde_json::from_value::<serde_json::Value>(sent["entry"].clone())
+ .ok()
+ .and_then(|e| self.hub.store.entry(e["id"].as_str()?))
+ .unwrap()
+ }
+
+ fn replies(&self, lane: &Lane) -> Vec<(String, String)> {
+ self.hub
+ .store
+ .messages_after(lane, 0, 100)
+ .unwrap()
+ .into_iter()
+ .filter(|e| e.kind == "agent")
+ .map(|e| (e.data["author"].as_str().unwrap().to_owned(), e.data["text"].as_str().unwrap().to_owned()))
+ .collect()
+ }
+
+ async fn settle(&self) {
+ tokio::time::timeout(Duration::from_secs(10), async {
+ loop {
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ let idle = ["a", "b"].iter().all(|b| self.hub.runtime(b).status == BotStatus::Idle);
+ if idle && self.hub.bots_json(0).unwrap().iter().all(|b| b["status"] == "idle") {
+ break;
+ }
+ }
+ })
+ .await
+ .expect("room settles");
+ }
+
+ async fn shutdown(self) {
+ self.hub.shutdown().await;
+ std::fs::remove_dir_all(self.dir).unwrap();
+ }
+ }
+
+ #[tokio::test]
+ async fn room_turns_follow_mentions_and_end_when_everyone_passes() {
+ let room = Room::new();
+ let row = room.hub.store.bot(&room.group).unwrap().unwrap();
+ assert_eq!(row.config.members, ["a", "b"], "members are deduplicated");
+ let again = room
+ .hub
+ .create_bot(
+ serde_json::from_value(json!({"id": "", "kind": "group", "name": "Dup", "members": ["b", "a"]}))
+ .unwrap(),
+ )
+ .unwrap();
+ assert_eq!(again["id"], room.group, "the same bots reopen their group");
+
+ let main = Lane::main(&room.group);
+ room.send("hello everyone", None).await;
+ room.settle().await;
+ // `a` answers the user; `b` then sees a bot spoke last and passes; round two is all passes.
+ assert_eq!(room.replies(&main), [("a".to_owned(), "reply: group".to_owned())]);
+
+ room.send("@b your turn", None).await;
+ room.settle().await;
+ assert_eq!(room.replies(&main).last().unwrap().0, "b", "only the mentioned bot answers");
+ assert_eq!(room.replies(&main).len(), 2);
+ let listed = room.hub.bot_value_for_test(&room.group);
+ assert_eq!(listed["lastMessage"], "b: reply: group");
+ // The members' own chats stay private: the room's entries live in the group.
+ assert!(room.hub.store.messages_after(&Lane::main("a"), 0, 100).unwrap().is_empty());
+ room.shutdown().await;
+ }
+
+ #[tokio::test]
+ async fn threads_stay_out_of_the_main_chat_and_summarize_on_their_root() {
+ let room = Room::new();
+ let first = room.send("@a start here", None).await;
+ room.settle().await;
+ room.send("@a in the thread", Some(&first.id)).await;
+ room.settle().await;
+ let thread = Lane::in_thread(&room.group, &first.id);
+ assert_eq!(room.replies(&thread).len(), 1);
+ assert_eq!(room.replies(&Lane::main(&room.group)).len(), 1, "the thread's reply isn't in the main chat");
+ let summary = room.hub.store.entry(&first.id).unwrap().data["thread"].clone();
+ assert_eq!(summary["count"], 2);
+ assert_eq!(summary["authors"], json!(["user", "a"]));
+
+ // A thread in a bot's own chat gets a session of its own, told where it branched off.
+ let dm = crate::api::dispatch(&room.hub, &Caller::Local, "send", json!({"botId": "b", "text": "main"}))
+ .await
+ .unwrap();
+ room.settle().await;
+ let dm_root = dm["entry"]["id"].as_str().unwrap().to_owned();
+ crate::api::dispatch(
+ &room.hub,
+ &Caller::Local,
+ "send",
+ json!({"botId": "b", "text": "aside", "threadId": dm_root}),
+ )
+ .await
+ .unwrap();
+ room.settle().await;
+ let prompts = std::fs::read_to_string(room.dir.join("b/prompts.jsonl")).unwrap();
+ assert!(prompts.lines().last().unwrap().contains("[Thread]"), "{prompts}");
+ let replies = room.hub.store.thread("b", &dm_root, 10).unwrap();
+ assert_eq!(replies.iter().filter(|e| e.data["final"] == true).count(), 1);
+ assert!(
+ crate::api::dispatch(
+ &room.hub,
+ &Caller::Local,
+ "send",
+ json!({"botId": "b", "text": "x", "threadId": replies[0].id})
+ )
+ .await
+ .is_err(),
+ "threads are flat"
+ );
+ room.shutdown().await;
+ }
+
+ #[test]
+ fn pass_is_recognized_loosely() {
+ for t in ["(pass)", " (pass) ", "\"(pass)\"", "pass.", ""] {
+ assert!(is_pass(t), "{t:?}");
+ }
+ assert!(!is_pass("I'll pass this to Bob"));
+ }
+}
diff --git a/host/src/hub.rs b/host/src/hub.rs
index 769dbd2a..c6a83630 100644
--- a/host/src/hub.rs
+++ b/host/src/hub.rs
@@ -5,7 +5,7 @@ use crate::bot::{self, BotHandle, Cmd};
use crate::devices::Pairing;
use crate::identity::Identity;
use crate::screen::Screen;
-use crate::store::{BotConfig, BotRow, Entry, EntryKind, Store};
+use crate::store::{BotConfig, BotRow, Entry, EntryKind, Lane, Store};
use crate::usage::Usage;
use crate::{push, service};
use anyhow::{Result, anyhow, bail};
@@ -33,10 +33,13 @@ pub struct Runtime {
pub status: BotStatus,
pub activity: String,
pub started_at: Option<i64>,
+ /// Where the running turn talks: its own chat, a thread, or a group.
+ pub lane: Option<Lane>,
}
pub struct Hub {
pub team: crate::team::Requests,
+ pub groups: crate::group::Rooms,
pub store: Store,
pub host_id: String,
pub identity: Identity,
@@ -72,6 +75,7 @@ impl Hub {
let screen = Arc::new(Screen::new(Screen::load_enabled(&store), events.clone()));
Arc::new(Self {
team: crate::team::Requests::default(),
+ groups: crate::group::Rooms::default(),
store,
host_id,
identity,
@@ -98,7 +102,7 @@ impl Hub {
// Approval cards and queued sends from a previous run can't be honored anymore.
self.store.expire_pending()?;
for row in self.store.bots()? {
- if !row.deleted {
+ if !row.deleted && !row.config.is_group() {
self.spawn_bot(row.config);
}
}
@@ -137,20 +141,53 @@ impl Hub {
// MARK: bots
pub fn bot_json(&self, row: &BotRow) -> Value {
- let mut v = serde_json::to_value(&row.config).expect("BotConfig is plain data and always serializes");
- let rt = self.runtime.locked().get(&row.config.id).cloned().unwrap_or_default();
- let last = self.store.last_message(&row.config.id);
+ let cfg = &row.config;
+ let mut v = serde_json::to_value(cfg).expect("BotConfig is plain data and always serializes");
+ let rt = if cfg.is_group() {
+ self.group_runtime(cfg)
+ } else {
+ self.runtime.locked().get(&cfg.id).cloned().unwrap_or_default()
+ };
+ let last = self.store.last_message(&cfg.id);
v["rev"] = row.rev.into();
v["deleted"] = row.deleted.into();
v["status"] = json!(rt.status);
v["activity"] = rt.activity.into();
v["startedAt"] = rt.started_at.into();
- v["unread"] = self.store.unread(&row.config.id, row.read_rev).into();
- v["lastMessage"] = last.as_ref().map(|l| crate::acp::truncate(&l.0, 280)).into();
- v["lastAt"] = last.map_or(row.config.created_at, |l| l.1).into();
+ v["workingChat"] = rt.lane.as_ref().map(|l| l.chat.clone()).into();
+ v["workingThread"] = rt.lane.and_then(|l| l.thread).into();
+ v["unread"] = self.store.unread(&cfg.id, row.read_rev).into();
+ let preview = last.as_ref().map(|l| match &l.author {
+ // A group names who spoke.
+ Some(author) if cfg.is_group() => format!("{}: {}", self.bot_name(author), l.text),
+ Some(_) => l.text.clone(),
+ None => format!("You: {}", l.text),
+ });
+ v["lastMessage"] = preview.map(|p| crate::acp::truncate(&p, 280)).into();
+ v["lastAt"] = last.map_or(cfg.created_at, |l| l.at).into();
v
}
+ pub fn bot_name(&self, id: &str) -> String {
+ self.store.bot(id).ok().flatten().map_or_else(|| "A deleted bot".into(), |b| b.config.name)
+ }
+
+ /// A group is busy while one of its members works in it: that member's status and activity.
+ fn group_runtime(&self, group: &BotConfig) -> Runtime {
+ let busy = {
+ let runtime = self.runtime.locked();
+ group.members.iter().find_map(|m| {
+ let r = runtime.get(m)?;
+ (r.status != BotStatus::Idle && r.lane.as_ref().is_some_and(|l| l.chat == group.id))
+ .then(|| (m.clone(), r.clone()))
+ })
+ };
+ let Some((member, mut r)) = busy else { return Runtime::default() };
+ let name = self.bot_name(&member);
+ r.activity = if r.activity.is_empty() { name } else { format!("{name}: {}", r.activity) };
+ r
+ }
+
pub fn bots_json(&self, since: i64) -> Result<Vec<Value>> {
Ok(self
.store
@@ -164,12 +201,21 @@ impl Hub {
pub fn create_bot(self: &Arc<Self>, mut cfg: BotConfig) -> Result<Value> {
cfg.id = uuid::Uuid::new_v4().to_string();
cfg.created_at = crate::store::now_ms();
+ if cfg.is_group() {
+ cfg.members = crate::group::valid_members(&self.store, &cfg.id, &cfg.members)?;
+ // The same bots again: open the group they already share (Grok Bot's rule).
+ if let Some(existing) = crate::group::with_members(&self.store, &cfg.members)? {
+ return Ok(self.bot_value(&existing).unwrap_or(Value::Null));
+ }
+ }
validate(&cfg)?;
{
let _g = self.emit_lock.locked();
self.store.save_bot(&cfg)?;
}
- self.spawn_bot(cfg.clone());
+ if !cfg.is_group() {
+ self.spawn_bot(cfg.clone());
+ }
self.emit_bot(&cfg.id);
Ok(self.bot_value(&cfg.id).unwrap_or(Value::Null))
}
@@ -183,25 +229,49 @@ impl Hub {
merged[k] = v.clone();
}
}
- let cfg: BotConfig = serde_json::from_value(merged)?;
+ let mut cfg: BotConfig = serde_json::from_value(merged)?;
+ if cfg.kind != row.config.kind {
+ bail!("a bot can't become a group, or a group a bot");
+ }
+ if cfg.is_group() {
+ cfg.members = crate::group::valid_members(&self.store, &cfg.id, &cfg.members)?;
+ }
validate(&cfg)?;
{
let _g = self.emit_lock.locked();
self.store.save_bot(&cfg)?;
}
- self.send_cmd(&id, Cmd::Reconfigure(Box::new(cfg)))?;
+ if !cfg.is_group() {
+ self.send_cmd(&id, Cmd::Reconfigure(Box::new(cfg)))?;
+ }
self.emit_bot(&id);
Ok(self.bot_value(&id).unwrap_or(Value::Null))
}
pub fn delete_bot(&self, id: &str) -> Result<()> {
self.team.cancel_bot(id);
+ self.groups.stop(self, id);
let _ = self.send_cmd(id, Cmd::Shutdown);
self.bots.locked().remove(id);
self.runtime.locked().remove(id);
- let _g = self.emit_lock.locked();
- let rev = self.store.delete_bot(id)?;
- let _ = self.events.send(json!({"type": "bot", "rev": rev, "bot": {"id": id, "deleted": true, "rev": rev}}));
+ {
+ let _g = self.emit_lock.locked();
+ let rev = self.store.delete_bot(id)?;
+ let _ =
+ self.events.send(json!({"type": "bot", "rev": rev, "bot": {"id": id, "deleted": true, "rev": rev}}));
+ }
+ // A deleted bot leaves its groups; what it said there stays.
+ for row in self.store.bots()? {
+ let mut group = row.config;
+ if !row.deleted && group.is_group() && group.members.iter().any(|m| m == id) {
+ group.members.retain(|m| m != id);
+ {
+ let _g = self.emit_lock.locked();
+ self.store.save_bot(&group)?;
+ }
+ self.emit_bot(&group.id);
+ }
+ }
Ok(())
}
@@ -214,6 +284,11 @@ impl Hub {
Ok(())
}
+ #[cfg(test)]
+ pub fn bot_value_for_test(&self, id: &str) -> Value {
+ self.bot_value(id).unwrap_or(Value::Null)
+ }
+
fn bot_value(&self, id: &str) -> Option<Value> {
self.store.bot(id).ok().flatten().map(|r| self.bot_json(&r))
}
@@ -243,8 +318,14 @@ impl Hub {
f(rt);
(before, rt.clone())
};
- if before.status != after.status || before.activity != after.activity {
+ if before.status != after.status || before.activity != after.activity || before.lane != after.lane {
self.emit_bot(id);
+ // A group shows what its busy member is doing.
+ for lane in [&before.lane, &after.lane].into_iter().flatten() {
+ if lane.chat != id {
+ self.emit_bot(&lane.chat);
+ }
+ }
self.update_keep_awake();
}
if before.status != after.status {
@@ -265,39 +346,71 @@ impl Hub {
/// Persists and broadcasts a new transcript entry. A failed write is logged here
/// (once) and yields `None`: the conversation goes on without that line.
- pub fn add_entry(&self, bot_id: &str, kind: EntryKind, turn: i64, data: &Value) -> Option<Entry> {
- let _g = self.emit_lock.locked();
- match self.store.insert_entry(bot_id, kind, turn, data) {
- Ok(e) => {
- let _ = self.events.send(json!({"type": "entry", "rev": e.rev, "entry": e}));
- Some(e)
- }
- Err(error) => {
- tracing::error!(
- error = format!("{error:#}"),
- bot = bot_id,
- kind = kind.as_str(),
- "couldn't save transcript entry"
- );
- None
+ pub fn add_entry(&self, lane: &Lane, kind: EntryKind, turn: i64, data: &Value) -> Option<Entry> {
+ let added = {
+ let _g = self.emit_lock.locked();
+ match self.store.insert_entry(lane, kind, turn, data) {
+ Ok(e) => {
+ let _ = self.events.send(json!({"type": "entry", "rev": e.rev, "entry": e}));
+ Some(e)
+ }
+ Err(error) => {
+ tracing::error!(
+ error = format!("{error:#}"),
+ chat = lane.chat,
+ kind = kind.as_str(),
+ "couldn't save transcript entry"
+ );
+ None
+ }
}
+ };
+ if let Some(e) = &added {
+ self.update_thread_summary(e);
}
+ added
}
/// Updates and broadcasts an entry; failures are logged here, like [`Self::add_entry`].
pub fn set_entry(&self, id: &str, data: &Value) -> Option<Entry> {
- let _g = self.emit_lock.locked();
- match self.store.update_entry(id, data) {
- Ok(e) => {
- if let Some(e) = &e {
- let _ = self.events.send(json!({"type": "entry", "rev": e.rev, "entry": e}));
+ let updated = {
+ let _g = self.emit_lock.locked();
+ match self.store.update_entry(id, data) {
+ Ok(e) => {
+ if let Some(e) = &e {
+ let _ = self.events.send(json!({"type": "entry", "rev": e.rev, "entry": e}));
+ }
+ e
+ }
+ Err(error) => {
+ tracing::error!(error = format!("{error:#}"), entry = id, "couldn't update transcript entry");
+ None
}
- e
}
- Err(error) => {
- tracing::error!(error = format!("{error:#}"), entry = id, "couldn't update transcript entry");
- None
+ };
+ if let Some(e) = &updated {
+ self.update_thread_summary(e);
+ }
+ updated
+ }
+
+ /// A message in a thread refreshes the summary on its root (`data.thread`: reply count,
+ /// newest reply, who replied), which the main chat shows under it.
+ fn update_thread_summary(&self, e: &Entry) {
+ let Some(root) = &e.thread_id else { return };
+ let visible =
+ e.kind == EntryKind::User.as_str() || (e.kind == EntryKind::Agent.as_str() && e.data["final"] == true);
+ if !visible {
+ return;
+ }
+ let Some(mut root_entry) = self.store.entry(root) else { return };
+ match self.store.thread_summary(&e.bot_id, root) {
+ Ok(summary) if root_entry.data["thread"] != summary => {
+ root_entry.data["thread"] = summary;
+ self.set_entry(root, &root_entry.data);
}
+ Ok(_) => {}
+ Err(error) => tracing::warn!(error = format!("{error:#}"), root, "couldn't summarize thread"),
}
}
@@ -332,6 +445,9 @@ fn validate(cfg: &BotConfig) -> Result<()> {
if cfg.name.trim().is_empty() {
bail!("name is required");
}
+ if cfg.is_group() {
+ return Ok(());
+ }
if !std::path::Path::new(&cfg.cwd).is_dir() {
bail!("workspace folder does not exist: {}", cfg.cwd);
}
diff --git a/host/src/main.rs b/host/src/main.rs
index 205b4429..f07fcd67 100644
--- a/host/src/main.rs
+++ b/host/src/main.rs
@@ -11,6 +11,7 @@ mod composio;
mod context;
mod crypto;
mod devices;
+mod group;
mod hub;
mod identity;
mod market;
diff --git a/host/src/store.rs b/host/src/store.rs
index dec08936..3e00dd49 100644
--- a/host/src/store.rs
+++ b/host/src/store.rs
@@ -50,10 +50,25 @@ impl EntryKind {
}
}
+/// A roster row is an agent bot or a group chat of bots (wire values `agent` / `group`).
+#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq)]
+#[serde(rename_all = "lowercase")]
+pub enum BotKind {
+ #[default]
+ Agent,
+ /// Several bots and the user in one conversation; it has no agent of its own (see `group`).
+ Group,
+}
+
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct BotConfig {
pub id: String,
+ #[serde(default)]
+ pub kind: BotKind,
+ /// A group's bots, in the order they were added.
+ #[serde(default)]
+ pub members: Vec<String>,
pub name: String,
#[serde(default)]
pub description: String,
@@ -62,9 +77,13 @@ pub struct BotConfig {
/// Grok-Bot-style character shape: blob | pebble | squircle | tablet | wedge | hex | cloud | teardrop.
#[serde(default = "default_shape")]
pub avatar_shape: String,
+ /// Empty for a group.
+ #[serde(default)]
pub backend: String,
#[serde(default)]
pub command: Option<String>,
+ /// Empty for a group.
+ #[serde(default)]
pub cwd: String,
#[serde(default)]
pub permission: Permission,
@@ -89,6 +108,12 @@ pub struct BotConfig {
pub created_at: i64,
}
+impl BotConfig {
+ pub fn is_group(&self) -> bool {
+ self.kind == BotKind::Group
+ }
+}
+
fn default_color() -> String {
"blue".into()
}
@@ -96,12 +121,45 @@ fn default_shape() -> String {
"blob".into()
}
+/// kv key for per-bot state in one lane (`what`: `session`, `seen`).
+pub fn lane_key(what: &str, bot_id: &str, lane: &Lane) -> String {
+ format!("lane.{what}.{bot_id}@{}", lane.key())
+}
+
+/// Where an entry lives: a bot's or group's chat (`bot_id`), and optionally a thread in it,
+/// named by its root entry. Every lane a bot talks in has its own ACP session.
+#[derive(Clone, Debug, PartialEq, Eq, Hash)]
+pub struct Lane {
+ pub chat: String,
+ pub thread: Option<String>,
+}
+
+impl Lane {
+ pub fn main(chat: &str) -> Self {
+ Self { chat: chat.to_owned(), thread: None }
+ }
+
+ pub fn in_thread(chat: &str, root: &str) -> Self {
+ Self { chat: chat.to_owned(), thread: Some(root.to_owned()) }
+ }
+
+ /// Stable text form for kv keys: `chat` or `chat/root`.
+ pub fn key(&self) -> String {
+ match &self.thread {
+ Some(t) => format!("{}/{t}", self.chat),
+ None => self.chat.clone(),
+ }
+ }
+}
+
#[derive(Serialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Entry {
pub id: String,
pub seq: i64,
pub bot_id: String,
+ /// The thread's root entry; `None` in the main chat.
+ pub thread_id: Option<String>,
pub rev: i64,
pub kind: String,
pub turn: i64,
@@ -110,6 +168,13 @@ pub struct Entry {
pub updated_at: i64,
}
+pub struct LastMessage {
+ pub text: String,
+ pub at: i64,
+ /// The bot that wrote it; `None` when the user did.
+ pub author: Option<String>,
+}
+
pub struct BotRow {
pub config: BotConfig,
pub rev: i64,
@@ -157,6 +222,7 @@ fn row_entry(r: &rusqlite::Row) -> rusqlite::Result<Entry> {
data: serde_json::from_str(&data).unwrap_or(Value::Null),
created_at: r.get(7)?,
updated_at: r.get(8)?,
+ thread_id: r.get(9)?,
})
}
@@ -176,16 +242,33 @@ fn parse_bot((id, cfg, rev, deleted, session_id, read_rev): RawBot) -> Option<Bo
}
/// Current schema version (kv `schema`).
-const SCHEMA: i64 = 3;
+const SCHEMA: i64 = 4;
/// 3: authorized devices (keys, not push tickets) with their push and Live Activity
/// tickets. The old ticket-only `devices` table is dropped; phones re-register on connect.
+/// 4: threads (`entries.thread_id`); instruction snapshots are kept per session, so the
+/// per-bot ones go.
fn migrate(c: &Connection) -> Result<()> {
let version: i64 =
c.query_row("SELECT CAST(v AS INTEGER) FROM kv WHERE k = 'schema'", [], |r| r.get(0)).optional()?.unwrap_or(0);
if version >= SCHEMA {
return Ok(());
}
+ if version < 3 {
+ migrate_3(c)?;
+ }
+ c.execute_batch(
+ "BEGIN;
+ ALTER TABLE entries ADD COLUMN thread_id TEXT;
+ CREATE INDEX IF NOT EXISTS entries_thread ON entries(bot_id, thread_id, seq);
+ DELETE FROM kv WHERE k GLOB 'context.*';
+ INSERT INTO kv(k, v) VALUES('schema', '4') ON CONFLICT(k) DO UPDATE SET v = '4';
+ COMMIT;",
+ )?;
+ Ok(())
+}
+
+fn migrate_3(c: &Connection) -> Result<()> {
c.execute_batch(
"BEGIN;
DROP TABLE IF EXISTS devices;
@@ -265,7 +348,7 @@ fn row_device(r: &rusqlite::Row) -> rusqlite::Result<Device> {
})
}
-const ENTRY_COLS: &str = "seq, id, bot_id, rev, kind, turn, data, created_at, updated_at";
+const ENTRY_COLS: &str = "seq, id, bot_id, rev, kind, turn, data, created_at, updated_at, thread_id";
const BOT_COLS: &str = "id, config, rev, deleted, session_id, read_rev";
impl Store {
@@ -300,6 +383,15 @@ impl Store {
Ok(())
}
+ /// Keys starting with `prefix`.
+ pub fn kv_prefix(&self, prefix: &str) -> Vec<String> {
+ let c = self.db.locked();
+ let rows = c
+ .prepare("SELECT k FROM kv WHERE substr(k, 1, length(?1)) = ?1")
+ .and_then(|mut st| st.query_map([prefix], |r| r.get(0))?.collect::<rusqlite::Result<Vec<String>>>());
+ logged("kv prefix", rows).unwrap_or_default()
+ }
+
pub fn current_rev(&self) -> i64 {
self.kv_get("rev").and_then(|v| v.parse().ok()).unwrap_or(0)
}
@@ -342,6 +434,13 @@ impl Store {
let rev = next_rev(&c)?;
c.execute("UPDATE bots SET rev = ?2, deleted = 1, session_id = NULL WHERE id = ?1", params![id, rev])?;
c.execute("DELETE FROM entries WHERE bot_id = ?1", [id])?;
+ // Lane state (see `lane_key`) it owned, or that bots kept in it.
+ c.execute("DELETE FROM kv WHERE k GLOB ?1 OR k GLOB ?2", [format!("lane.*.{id}@*"), format!("lane.*@{id}*")])?;
+ // ponytail: snapshots of replaced sessions stay until the bot goes; prune by session if kv grows.
+ c.execute(
+ "DELETE FROM kv WHERE k GLOB ?1 OR k GLOB ?2",
+ [format!("context.{id}.*"), format!("context.epoch.{id}.*")],
+ )?;
Ok(rev)
}
@@ -371,11 +470,12 @@ impl Store {
logged("unread", n).unwrap_or(0)
}
- /// Newest chat-visible line for the roster preview.
- pub fn last_message(&self, id: &str) -> Option<(String, i64)> {
+ /// Newest chat-visible line in the main chat for the roster preview, with its author
+ /// (`None` for the user; a group reply names the bot that wrote it).
+ pub fn last_message(&self, id: &str) -> Option<LastMessage> {
let c = self.db.locked();
let row = c.query_row(
- "SELECT kind, data, updated_at FROM entries WHERE bot_id = ?1 AND
+ "SELECT kind, data, updated_at FROM entries WHERE bot_id = ?1 AND thread_id IS NULL AND
(kind = 'user' OR (kind = 'agent' AND json_extract(data, '$.final') = 1))
ORDER BY seq DESC LIMIT 1",
[id],
@@ -383,12 +483,11 @@ impl Store {
let kind: String = r.get(0)?;
let data: String = r.get(1)?;
let at: i64 = r.get(2)?;
- let text = serde_json::from_str::<Value>(&data)
- .ok()
- .and_then(|v| v["text"].as_str().map(str::to_owned))
- .unwrap_or_default();
- let text = if kind == EntryKind::User.as_str() { format!("You: {text}") } else { text };
- Ok((text, at))
+ let data = serde_json::from_str::<Value>(&data).unwrap_or_default();
+ let text = data["text"].as_str().unwrap_or_default().to_owned();
+ let author =
+ (kind != EntryKind::User.as_str()).then(|| data["author"].as_str().unwrap_or(id).to_owned());
+ Ok(LastMessage { text, at, author })
},
);
logged("last message", row.optional()).flatten()
@@ -396,20 +495,21 @@ impl Store {
// MARK: entries
- pub fn insert_entry(&self, bot_id: &str, kind: EntryKind, turn: i64, data: &Value) -> Result<Entry> {
+ pub fn insert_entry(&self, lane: &Lane, kind: EntryKind, turn: i64, data: &Value) -> Result<Entry> {
let c = self.db.locked();
let rev = next_rev(&c)?;
let now = now_ms();
let id = uuid::Uuid::new_v4().to_string();
c.execute(
- "INSERT INTO entries(id, bot_id, rev, kind, turn, data, created_at, updated_at)
- VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?7)",
- params![id, bot_id, rev, kind.as_str(), turn, data.to_string(), now],
+ "INSERT INTO entries(id, bot_id, thread_id, rev, kind, turn, data, created_at, updated_at)
+ VALUES(?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?8)",
+ params![id, lane.chat, lane.thread, rev, kind.as_str(), turn, data.to_string(), now],
)?;
Ok(Entry {
id,
seq: c.last_insert_rowid(),
- bot_id: bot_id.into(),
+ bot_id: lane.chat.clone(),
+ thread_id: lane.thread.clone(),
rev,
kind: kind.as_str().to_owned(),
turn,
@@ -469,10 +569,12 @@ impl Store {
Ok(st.query_map(params![since, cap], row_entry)?.collect::<rusqlite::Result<_>>()?)
}
+ /// Older main-chat entries (threads load whole with [`Self::thread`]).
pub fn history(&self, bot_id: &str, before_seq: i64, limit: i64) -> Result<Vec<Entry>> {
let c = self.db.locked();
let mut st = c.prepare(&format!(
- "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND seq < ?2 ORDER BY seq DESC LIMIT ?3"
+ "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND thread_id IS NULL AND seq < ?2
+ ORDER BY seq DESC LIMIT ?3"
))?;
let mut rows: Vec<Entry> =
st.query_map(params![bot_id, before_seq, limit], row_entry)?.collect::<rusqlite::Result<_>>()?;
@@ -480,6 +582,68 @@ impl Store {
Ok(rows)
}
+ /// A thread's newest `limit` entries, oldest first.
+ pub fn thread(&self, bot_id: &str, root: &str, limit: i64) -> Result<Vec<Entry>> {
+ let c = self.db.locked();
+ let mut st = c.prepare(&format!(
+ "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND thread_id = ?2 ORDER BY seq DESC LIMIT ?3"
+ ))?;
+ let mut rows: Vec<Entry> =
+ st.query_map(params![bot_id, root, limit], row_entry)?.collect::<rusqlite::Result<_>>()?;
+ rows.reverse();
+ Ok(rows)
+ }
+
+ /// Chat-visible messages (the user's, final replies) in `lane` after `after_seq`, oldest first.
+ pub fn messages_after(&self, lane: &Lane, after_seq: i64, limit: i64) -> Result<Vec<Entry>> {
+ let c = self.db.locked();
+ let mut st = c.prepare(&format!(
+ "SELECT {ENTRY_COLS} FROM entries WHERE bot_id = ?1 AND thread_id IS ?2 AND seq > ?3 AND
+ (kind = 'user' OR (kind = 'agent' AND json_extract(data, '$.final') = 1))
+ ORDER BY seq DESC LIMIT ?4"
+ ))?;
+ let mut rows: Vec<Entry> = st
+ .query_map(params![lane.chat, lane.thread, after_seq, limit], row_entry)?
+ .collect::<rusqlite::Result<_>>()?;
+ rows.reverse();
+ Ok(rows)
+ }
+
+ /// The `seq` of `bot`'s last reply in `lane` (0 if it hasn't spoken there).
+ pub fn last_spoke(&self, lane: &Lane, bot: &str) -> i64 {
+ let c = self.db.locked();
+ let n = c.query_row(
+ "SELECT COALESCE(MAX(seq), 0) FROM entries WHERE bot_id = ?1 AND thread_id IS ?2 AND kind = 'agent'
+ AND json_extract(data, '$.final') = 1 AND json_extract(data, '$.author') = ?3",
+ params![lane.chat, lane.thread, bot],
+ |r| r.get(0),
+ );
+ logged("last spoke", n).unwrap_or(0)
+ }
+
+ /// A thread's reply count, newest reply time and the bots that replied (first reply first).
+ pub fn thread_summary(&self, chat: &str, root: &str) -> Result<Value> {
+ let c = self.db.locked();
+ let mut st = c.prepare(
+ "SELECT kind, json_extract(data, '$.author'), created_at FROM entries WHERE bot_id = ?1 AND thread_id = ?2
+ AND (kind = 'user' OR (kind = 'agent' AND json_extract(data, '$.final') = 1)) ORDER BY seq",
+ )?;
+ let rows = st.query_map(params![chat, root], |r| {
+ Ok((r.get::<_, String>(0)?, r.get::<_, Option<String>>(1)?, r.get::<_, i64>(2)?))
+ })?;
+ let (mut count, mut last_at, mut authors) = (0, 0, Vec::<String>::new());
+ for row in rows {
+ let (kind, author, at) = row?;
+ count += 1;
+ last_at = at;
+ let author = if kind == EntryKind::User.as_str() { "user".to_owned() } else { author.unwrap_or_default() };
+ if !author.is_empty() && !authors.contains(&author) {
+ authors.push(author);
+ }
+ }
+ Ok(serde_json::json!({"count": count, "lastAt": last_at, "authors": authors}))
+ }
+
/// Permission cards left `pending` (and sends left `queued`) by a crash or restart
/// can never be honored; returns how many were closed out.
pub fn expire_pending(&self) -> Result<usize> {
@@ -649,6 +813,8 @@ mod tests {
let s = temp_store();
let cfg = BotConfig {
id: "b1".into(),
+ kind: BotKind::Agent,
+ members: vec![],
name: "Rev".into(),
description: String::new(),
avatar_color: "blue".into(),
@@ -667,15 +833,17 @@ mod tests {
created_at: 0,
};
s.save_bot(&cfg).unwrap();
- let u = s.insert_entry("b1", EntryKind::User, 1, &serde_json::json!({"text": "hi"})).unwrap();
- let a = s.insert_entry("b1", EntryKind::Agent, 1, &serde_json::json!({"text": "yo", "final": false})).unwrap();
+ let u = s.insert_entry(&Lane::main("b1"), EntryKind::User, 1, &serde_json::json!({"text": "hi"})).unwrap();
+ let a = s
+ .insert_entry(&Lane::main("b1"), EntryKind::Agent, 1, &serde_json::json!({"text": "yo", "final": false}))
+ .unwrap();
assert!(a.rev > u.rev);
assert_eq!(s.unread("b1", 0), 0, "narration is not unread");
let a2 = s.update_entry(&a.id, &serde_json::json!({"text": "yo!", "final": true})).unwrap().unwrap();
assert_eq!(s.unread("b1", 0), 1);
assert_eq!(s.entries_since(a2.rev - 1, 500).unwrap().len(), 1);
assert_eq!(s.entries_since(0, 1).unwrap().len(), 1, "fresh sync is capped per bot");
- assert_eq!(s.last_message("b1").unwrap().0, "yo!");
+ assert_eq!(s.last_message("b1").unwrap().text, "yo!");
let r = s.mark_read("b1").unwrap();
assert_eq!(s.unread("b1", r), 0);
assert_eq!(s.history("b1", a.seq, 10).unwrap().len(), 1);
@@ -686,9 +854,10 @@ mod tests {
#[test]
fn restart_expires_pending_cards_and_queued_sends() {
let s = temp_store();
- s.insert_entry("b1", EntryKind::Permission, 1, &serde_json::json!({"status": "pending"})).unwrap();
- let q = s.insert_entry("b1", EntryKind::User, 2, &serde_json::json!({"status": "queued"})).unwrap();
- s.insert_entry("b1", EntryKind::User, 1, &serde_json::json!({"status": "sent"})).unwrap();
+ s.insert_entry(&Lane::main("b1"), EntryKind::Permission, 1, &serde_json::json!({"status": "pending"})).unwrap();
+ let q =
+ s.insert_entry(&Lane::main("b1"), EntryKind::User, 2, &serde_json::json!({"status": "queued"})).unwrap();
+ s.insert_entry(&Lane::main("b1"), EntryKind::User, 1, &serde_json::json!({"status": "sent"})).unwrap();
assert_eq!(s.expire_pending().unwrap(), 2);
assert_eq!(s.entry(&q.id).unwrap().data["status"], "failed");
assert_eq!(s.expire_pending().unwrap(), 0, "idempotent");
@@ -727,7 +896,7 @@ mod tests {
}
#[test]
- fn schema_3_replaces_the_old_ticket_table() {
+ fn migrations_replace_the_old_ticket_table_and_add_threads() {
let dir = std::env::temp_dir().join(format!("codync-test-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
let db = dir.join("t.db");
@@ -742,7 +911,8 @@ mod tests {
}
let s = Store::open(&db).unwrap();
assert!(s.devices().unwrap().is_empty());
- assert_eq!(s.kv_get("schema").as_deref(), Some("3"));
+ assert_eq!(s.kv_get("schema").as_deref(), Some("4"));
+ assert!(s.thread("b", "root", 10).unwrap().is_empty(), "entries have a thread column");
drop(s);
let s = Store::open(&db).unwrap();
assert!(s.devices().unwrap().is_empty(), "reopening keeps the new table");
diff --git a/host/src/team.rs b/host/src/team.rs
index b9554808..19b8a0db 100644
--- a/host/src/team.rs
+++ b/host/src/team.rs
@@ -173,7 +173,7 @@ impl Drop for Pending {
fn visible_bot(hub: &Hub, id: &str) -> Result<BotConfig> {
hub.store
.bot(id)?
- .filter(|r| !r.deleted && !r.config.hidden)
+ .filter(|r| !r.deleted && !r.config.hidden && !r.config.is_group())
.map(|r| r.config)
.ok_or_else(|| anyhow!("unknown or hidden bot"))
}
@@ -186,7 +186,7 @@ pub async fn call(hub: &Arc<Hub>, from: &str, name: &str, args: &Value) -> Resul
.store
.bots()?
.into_iter()
- .filter(|b| !b.deleted && !b.config.hidden && b.config.id != from)
+ .filter(|b| !b.deleted && !b.config.hidden && !b.config.is_group() && b.config.id != from)
.map(|b| {
json!({
"id": b.config.id, "name": b.config.name, "description": b.config.description,
@@ -227,7 +227,7 @@ async fn ask(hub: &Arc<Hub>, source: &BotConfig, to: &str, message: &str, timeou
] {
let entry = hub
.add_entry(
- bot,
+ &crate::store::Lane::main(bot),
EntryKind::Notice,
hub.store.max_turn(bot) + i64::from(bot != &source.id),
&json!({
@@ -526,7 +526,7 @@ mod tests {
let store = Store::open(std::path::Path::new(":memory:")).unwrap();
let pending = store
.insert_entry(
- "b",
+ &crate::store::Lane::main("b"),
EntryKind::Notice,
1,
&json!({
@@ -536,7 +536,7 @@ mod tests {
.unwrap();
let complete = store
.insert_entry(
- "a",
+ &crate::store::Lane::main("a"),
EntryKind::Notice,
1,
&json!({
diff --git a/host/src/tui/app.rs b/host/src/tui/app.rs
index dc7cce42..47a231b6 100644
--- a/host/src/tui/app.rs
+++ b/host/src/tui/app.rs
@@ -786,7 +786,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") => {
+ Some("entry") if v["entry"]["threadId"].is_null() => {
if let Some((bot, e)) = Entry::parse(&v["entry"]) {
self.entries.entry(bot).or_default().insert(e.seq, e);
}
@@ -797,7 +797,8 @@ impl App {
fn upsert_bot(&mut self, v: &Value) {
let Some(id) = v["id"].as_str() else { return };
- if v["deleted"].as_bool().unwrap_or(false) {
+ // 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" {
self.bots.remove(id);
self.entries.remove(id);
if self.selected.as_deref() == Some(id) {
diff --git a/host/tests/fixtures/team_agent.py b/host/tests/fixtures/team_agent.py
index 9df791e8..b19c6b83 100644
--- a/host/tests/fixtures/team_agent.py
+++ b/host/tests/fixtures/team_agent.py
@@ -62,6 +62,14 @@ def prompt(request):
pass
while "BLOCK" in text and not pathlib.Path("release").exists() and not cancel.wait(0.01):
pass
+ if text.startswith("[Group chat") or "\n[Group chat" in text:
+ # A room turn: answer only when the user spoke last, otherwise pass.
+ room = text.split("New messages in the room (oldest first):\n", 1)[-1].split("\n\n", 1)[0]
+ last = room.strip().splitlines()[-1] if "New messages" in text else ""
+ reply = "reply: group" if last.startswith("User:") else "(pass)"
+ update({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": reply}})
+ send({"id": request["id"], "result": {"stopReason": "end_turn"}})
+ return
if cancel.is_set():
send({"id": request["id"], "result": {"stopReason": "cancelled"}})
elif "FAIL" in text:
diff --git a/kit/Sources/CodyncKit/Client/ChannelTransport.swift b/kit/Sources/CodyncKit/Client/ChannelTransport.swift
index 4fd02ee1..c2c95c21 100644
--- a/kit/Sources/CodyncKit/Client/ChannelTransport.swift
+++ b/kit/Sources/CodyncKit/Client/ChannelTransport.swift
@@ -855,16 +855,16 @@ public actor ChannelTransport: RemoteTransport {
return link
}
- public func enqueue(botId: String, text: String, clientNonce: String) async throws {
+ public func enqueue(botId: String, text: String, clientNonce: String, threadId: String? = nil) async throws {
guard pairingCode == nil, let bk = computer.boxKey.flatMap(Data.init(base64URL:)), bk.count == 32 else {
throw HostError.computerOffline(lastSeen: lastSeen)
}
if case let .ready(route) = state, route == .direct { throw MailboxError.hostOnline }
let link = try relaySocket()
guard puts[clientNonce] == nil else { throw MailboxError.rejected("busy") }
- struct Send: Encodable { var botId: String; var text: String; var clientNonce: String }
+ struct Send: Encodable { var botId: String; var text: String; var clientNonce: String; var threadId: String? }
struct Inner: Encodable { var m = "send"; var b: Send; var ts: Int64 }
- let inner = try JSONEncoder().encode(Inner(b: Send(botId: botId, text: text, clientNonce: clientNonce),
+ let inner = try JSONEncoder().encode(Inner(b: Send(botId: botId, text: text, clientNonce: clientNonce, threadId: threadId),
ts: Int64(Date.now.timeIntervalSince1970 * 1000)))
// A fresh ephemeral key on every seal, retries included (§6.4 MUST).
let sealed = try RelayCrypto.sealMailbox(inner, hostBoxKey: bk, computerId: computer.id, deviceKey: identity.deviceKey,
diff --git a/kit/Sources/CodyncKit/Client/HostClient.swift b/kit/Sources/CodyncKit/Client/HostClient.swift
index 306cb512..a979b4f9 100644
--- a/kit/Sources/CodyncKit/Client/HostClient.swift
+++ b/kit/Sources/CodyncKit/Client/HostClient.swift
@@ -139,6 +139,26 @@ public extension HostClient {
return res.entries
}
+ /// A thread's replies (the root is in the main chat).
+ func thread(botId: String, rootId: String) async throws -> [Entry] {
+ struct Res: Decodable { var entries: [Entry] }
+ let res: Res = try await call("thread", ["botId": botId, "rootId": rootId])
+ return res.entries
+ }
+
+ /// Creates a group chat (or returns the one these bots already share).
+ func createGroup(_ draft: GroupDraft) async throws -> Bot {
+ struct Res: Decodable { var bot: Bot }
+ let res: Res = try await call("createBot", draft)
+ return res.bot
+ }
+
+ func updateGroup(_ draft: GroupDraft) async throws -> Bot {
+ struct Res: Decodable { var bot: Bot }
+ let res: Res = try await call("updateBot", draft)
+ return res.bot
+ }
+
func createBot(_ draft: BotDraft) async throws -> Bot {
struct Res: Decodable { var bot: Bot }
let res: Res = try await call("createBot", draft)
@@ -159,9 +179,11 @@ public extension HostClient {
let _: Empty = try await call("markRead", ["botId": id])
}
- func send(botId: String, text: String, clientNonce: String) async throws -> Entry {
+ /// `threadId`: reply in the thread on that main-chat message.
+ func send(botId: String, text: String, clientNonce: String, threadId: String? = nil) async throws -> Entry {
+ struct Body: Encodable { var botId: String; var text: String; var clientNonce: String; var threadId: String? }
struct Res: Decodable { var entry: Entry }
- let res: Res = try await call("send", ["botId": botId, "text": text, "clientNonce": clientNonce])
+ let res: Res = try await call("send", Body(botId: botId, text: text, clientNonce: clientNonce, threadId: threadId))
return res.entry
}
diff --git a/kit/Sources/CodyncKit/Client/HostTransport.swift b/kit/Sources/CodyncKit/Client/HostTransport.swift
index 8f5f033f..98153d13 100644
--- a/kit/Sources/CodyncKit/Client/HostTransport.swift
+++ b/kit/Sources/CodyncKit/Client/HostTransport.swift
@@ -34,7 +34,7 @@ public protocol HostTransport: Sendable {
/// in the relay mailbox while it is offline. `ChannelTransport` is the real one.
public protocol RemoteTransport: HostTransport {
func computerUpdates() -> AsyncStream<Computer>
- func enqueue(botId: String, text: String, clientNonce: String) async throws
+ func enqueue(botId: String, text: String, clientNonce: String, threadId: String?) async throws
func cancelQueued(clientNonce: String) async -> MailboxCancel
func listQueued() async -> [QueuedItem]
func mailboxEvents() -> AsyncStream<MailboxEvent>
diff --git a/kit/Sources/CodyncKit/Design/CharacterAvatar.swift b/kit/Sources/CodyncKit/Design/CharacterAvatar.swift
index 2538c1b1..45a0dfb1 100644
--- a/kit/Sources/CodyncKit/Design/CharacterAvatar.swift
+++ b/kit/Sources/CodyncKit/Design/CharacterAvatar.swift
@@ -175,18 +175,56 @@ public struct CharacterShape: Shape {
}
}
+/// A group chat's face: its first two bots, one tucked behind the other.
+public struct GroupAvatar: View {
+ let members: [Bot]
+ let size: CGFloat
+ let animated: Bool
+
+ public init(members: [Bot], size: CGFloat = 40, animated: Bool = true) {
+ self.members = members
+ self.size = size
+ self.animated = animated
+ }
+
+ public var body: some View {
+ let small = size * 0.66
+ ZStack {
+ if members.isEmpty {
+ Image(systemName: "person.2")
+ .font(.system(size: size * 0.4))
+ .foregroundStyle(.secondary)
+ } else if members.count == 1 {
+ CharacterAvatar(bot: members[0], size: size, animated: animated)
+ } else {
+ CharacterAvatar(bot: members[1], size: small, animated: animated)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topTrailing)
+ CharacterAvatar(bot: members[0], size: small, animated: animated)
+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .bottomLeading)
+ }
+ }
+ .frame(width: size, height: size)
+ .accessibilityHidden(true)
+ }
+}
+
/// Avatar with the roster status dot: lime = unread, orange = needs you.
+/// A group shows its `members`.
public struct AvatarWithStatus: View {
let bot: Bot
+ let members: [Bot]
let size: CGFloat
- public init(bot: Bot, size: CGFloat = 44) {
+ public init(bot: Bot, members: [Bot] = [], size: CGFloat = 44) {
self.bot = bot
+ self.members = members
self.size = size
}
public var body: some View {
- CharacterAvatar(bot: bot, size: size)
+ Group {
+ if bot.isGroup { GroupAvatar(members: members, size: size) } else { CharacterAvatar(bot: bot, size: size) }
+ }
.overlay(alignment: .bottomTrailing) {
if bot.needsInput {
Image(systemName: "exclamationmark")
diff --git a/kit/Sources/CodyncKit/Models/Models.swift b/kit/Sources/CodyncKit/Models/Models.swift
index 047d4446..d4bf9387 100644
--- a/kit/Sources/CodyncKit/Models/Models.swift
+++ b/kit/Sources/CodyncKit/Models/Models.swift
@@ -5,6 +5,10 @@ import Foundation
public struct Bot: Codable, Identifiable, Hashable, Sendable {
public var id: String
+ /// `agent`, or `group`: several bots and the user in one chat (it has no agent, folder or harness).
+ public var kind: String
+ /// A group's bots.
+ public var members: [String]
public var name: String
public var description: String
public var avatarColor: String
@@ -31,11 +35,19 @@ public struct Bot: Codable, Identifiable, Hashable, Sendable {
public var status: String
public var activity: String
public var startedAt: Int64?
+ /// Where the running turn talks: the chat (a bot's own, or a group) and thread root.
+ public var workingChat: String?
+ public var workingThread: String?
public var unread: Int
public var lastMessage: String?
public var lastAt: Int64
+ public var isGroup: Bool { kind == "group" }
public var isWorking: Bool { status == "working" || status == "needsInput" }
+ /// Working right now in this chat's main conversation (`thread == nil`) or in that thread.
+ public func isWorking(in chat: String, thread: String?) -> Bool {
+ isWorking && (workingChat ?? id) == chat && workingThread == thread
+ }
public var needsInput: Bool { status == "needsInput" }
public var folderName: String { (cwd as NSString).lastPathComponent }
}
@@ -50,7 +62,10 @@ struct BotStub: Decodable {
public struct Entry: Codable, Identifiable, Hashable, Sendable {
public var id: String
public var seq: Int64
+ /// The chat it's in: a bot's, or a group's.
public var botId: String
+ /// The root message of the thread it's in; nil in the main chat.
+ public var threadId: String?
public var rev: Int64
/// user | agent | thought | tool | plan | permission | notice
public var kind: String
@@ -59,10 +74,11 @@ public struct Entry: Codable, Identifiable, Hashable, Sendable {
public var createdAt: Int64
public var updatedAt: Int64
- public init(id: String, seq: Int64, botId: String, rev: Int64, kind: String, turn: Int64, data: EntryData, createdAt: Int64, updatedAt: Int64) {
+ public init(id: String, seq: Int64, botId: String, threadId: String? = nil, rev: Int64, kind: String, turn: Int64, data: EntryData, createdAt: Int64, updatedAt: Int64) {
self.id = id
self.seq = seq
self.botId = botId
+ self.threadId = threadId
self.rev = rev
self.kind = kind
self.turn = turn
@@ -102,6 +118,10 @@ public struct EntryData: Codable, Hashable, Sendable {
public var entries: [PlanItem]?
/// notice: info | error | divider
public var style: String?
+ /// The bot that wrote it (a group shows who spoke).
+ public var author: String?
+ /// On a main-chat message that has a thread: its replies.
+ public var thread: ThreadSummary?
public init(text: String? = nil, status: String? = nil, clientNonce: String? = nil) {
self.text = text
@@ -110,6 +130,13 @@ public struct EntryData: Codable, Hashable, Sendable {
}
}
+public struct ThreadSummary: Codable, Hashable, Sendable {
+ public var count: Int
+ public var lastAt: Int64
+ /// Who replied, first reply first: bot ids, and `user`.
+ public var authors: [String]
+}
+
public struct FileDiff: Codable, Hashable, Sendable {
public var path: String
public var added: Int
@@ -351,6 +378,27 @@ public struct DirItem: Codable, Hashable, Sendable, Identifiable {
public var id: String { path }
}
+/// Create / update payload for a group chat.
+public struct GroupDraft: Codable, Hashable, Sendable {
+ public var id: String?
+ public var kind = "group"
+ public var name: String
+ public var members: [String]
+ public var pinned: Bool?
+
+ public init(name: String, members: [String]) {
+ self.name = name
+ self.members = members
+ }
+
+ public init(_ group: Bot) {
+ id = group.id
+ name = group.name
+ members = group.members
+ pinned = group.pinned
+ }
+}
+
/// Create / update payload for a bot.
public struct BotDraft: Codable, Hashable, Sendable {
public var id: String?
@@ -411,6 +459,8 @@ extension Bot {
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
id = try c.decode(String.self, forKey: .id)
+ kind = try c.decodeIfPresent(String.self, forKey: .kind) ?? "agent"
+ members = try c.decodeIfPresent([String].self, forKey: .members) ?? []
name = try c.decodeIfPresent(String.self, forKey: .name) ?? "Bot"
description = try c.decodeIfPresent(String.self, forKey: .description) ?? ""
avatarColor = try c.decodeIfPresent(String.self, forKey: .avatarColor) ?? "blue"
@@ -431,6 +481,8 @@ extension Bot {
status = try c.decodeIfPresent(String.self, forKey: .status) ?? "idle"
activity = try c.decodeIfPresent(String.self, forKey: .activity) ?? ""
startedAt = try c.decodeIfPresent(Int64.self, forKey: .startedAt)
+ workingChat = try c.decodeIfPresent(String.self, forKey: .workingChat)
+ workingThread = try c.decodeIfPresent(String.self, forKey: .workingThread)
unread = try c.decodeIfPresent(Int.self, forKey: .unread) ?? 0
lastMessage = try c.decodeIfPresent(String.self, forKey: .lastMessage)
lastAt = try c.decodeIfPresent(Int64.self, forKey: .lastAt) ?? createdAt
diff --git a/kit/Sources/CodyncUI/Bots/BotEditorView.swift b/kit/Sources/CodyncUI/Bots/BotEditorView.swift
index 76400721..5ec26dcb 100644
--- a/kit/Sources/CodyncUI/Bots/BotEditorView.swift
+++ b/kit/Sources/CodyncUI/Bots/BotEditorView.swift
@@ -254,7 +254,7 @@ struct BotSettingsForm: View {
}
}
-private struct Field<Content: View>: View {
+struct Field<Content: View>: View {
let label: String
@ViewBuilder let content: Content
diff --git a/kit/Sources/CodyncUI/Bots/BotRow.swift b/kit/Sources/CodyncUI/Bots/BotRow.swift
index eb06d81c..c3deea67 100644
--- a/kit/Sources/CodyncUI/Bots/BotRow.swift
+++ b/kit/Sources/CodyncUI/Bots/BotRow.swift
@@ -24,7 +24,7 @@ public struct BotRow: View {
public var body: some View {
HStack(spacing: compact ? 0 : InterfaceMetrics.value(mac: 8, mobile: 12)) {
- AvatarWithStatus(bot: bot, size: avatar)
+ AvatarWithStatus(bot: bot, members: model.members(of: bot), size: avatar)
VStack(alignment: .leading, spacing: lineSpacing) {
HStack(alignment: .firstTextBaseline) {
if bot.pinned {
diff --git a/kit/Sources/CodyncUI/Bots/Dialogs.swift b/kit/Sources/CodyncUI/Bots/Dialogs.swift
index 06f3930b..7c60126b 100644
--- a/kit/Sources/CodyncUI/Bots/Dialogs.swift
+++ b/kit/Sources/CodyncUI/Bots/Dialogs.swift
@@ -25,7 +25,7 @@ private struct DeleteBotConfirmation: ViewModifier {
content.codyncDialog(
"Delete \(bot?.name ?? "bot")?",
isPresented: Binding(get: { bot != nil }, set: { if !$0 { bot = nil } }),
- message: "Files it changed on your computer stay as they are."
+ message: bot?.isGroup == true ? "Its bots and their own chats stay." : "Files it changed on your computer stay as they are."
) {
// Captured now: the dialog clears `bot` before running the action.
let target = bot
diff --git a/kit/Sources/CodyncUI/Bots/GroupEditorView.swift b/kit/Sources/CodyncUI/Bots/GroupEditorView.swift
new file mode 100644
index 00000000..8562fc14
--- /dev/null
+++ b/kit/Sources/CodyncUI/Bots/GroupEditorView.swift
@@ -0,0 +1,125 @@
+import CodyncKit
+import SwiftUI
+
+/// Create a group chat, or rename one and change who's in it (up to six bots).
+public struct GroupEditorView: View {
+ @Environment(BotStore.self) private var model
+ @Environment(\.dismissModal) private var dismiss
+ /// The group being edited; nil creates one.
+ let groupId: String?
+ @State private var name: String
+ @State private var members: [String]
+ @State private var saving = false
+ @State private var error: String?
+ @State private var confirmDelete: Bot?
+
+ static let maxMembers = 6
+
+ public init(group: Bot? = nil, members: [String] = []) {
+ groupId = group?.id
+ _name = State(initialValue: group?.name ?? "")
+ _members = State(initialValue: group?.members ?? members)
+ }
+
+ private var candidates: [Bot] { model.roster.filter { !$0.isGroup } + model.hiddenBots.filter { members.contains($0.id) } }
+ private var isNew: Bool { groupId == nil }
+ private var canSave: Bool { !members.isEmpty && !saving }
+
+ public var body: some View {
+ VStack(spacing: 0) {
+ ModalHeader(isNew ? "New group chat" : "Group chat") {
+ if saving {
+ Spinner()
+ } else {
+ IconButton(isNew ? "Create" : "Save", systemImage: "checkmark") { save() }
+ .disabled(!canSave)
+ }
+ }
+ ScrollView {
+ VStack(alignment: .leading, spacing: InterfaceMetrics.value(mac: 12, mobile: 18)) {
+ GroupAvatar(members: members.compactMap { model.bots[$0] }, size: 72)
+ .frame(maxWidth: .infinity)
+ .animation(Motion.layout, value: members)
+ Field("Name") {
+ TextField(defaultName, text: $name).fieldBox()
+ }
+ Field("Bots · \(members.count) of \(Self.maxMembers)") {
+ VStack(spacing: 2) {
+ ForEach(candidates) { bot in memberRow(bot) }
+ }
+ Text("Everyone answers in turn unless you @mention someone. Each bot works in its own folder with its own tools.")
+ .font(.caption)
+ .foregroundStyle(Palette.tertiary)
+ }
+ if let error {
+ Text(error).font(.footnote).foregroundStyle(Palette.danger).transition(.opacity)
+ }
+ if let group = groupId.flatMap({ model.bots[$0] }) {
+ Button("Delete group chat", role: .destructive) { confirmDelete = group }
+ .buttonStyle(.secondary)
+ .padding(.top, 8)
+ }
+ }
+ .padding(InterfaceMetrics.value(mac: 16, mobile: 20))
+ }
+ }
+ .background(Palette.background)
+ .deleteBotConfirmation($confirmDelete) { dismiss() }
+ }
+
+ /// "Alice, Bob" when no name is typed.
+ private var defaultName: String {
+ let names = members.compactMap { model.bots[$0]?.name }
+ return names.isEmpty ? "Name" : names.joined(separator: ", ")
+ }
+
+ private func memberRow(_ bot: Bot) -> some View {
+ let on = members.contains(bot.id)
+ return Button {
+ withAnimation(Motion.layout) {
+ if on { members.removeAll { $0 == bot.id } } else if members.count < Self.maxMembers { members.append(bot.id) }
+ }
+ } label: {
+ HStack(spacing: 12) {
+ CharacterAvatar(bot: bot, size: InterfaceMetrics.value(mac: 26, mobile: 34), animated: false)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(bot.name).foregroundStyle(Palette.text).lineLimit(1)
+ Text(bot.folderName).font(.caption).foregroundStyle(Palette.tertiary).lineLimit(1)
+ }
+ Spacer()
+ Image(systemName: on ? "checkmark.circle.fill" : "circle")
+ .font(.system(size: 20))
+ .foregroundStyle(on ? Palette.accent : Palette.tertiary)
+ .contentTransition(.symbolEffect(.replace))
+ }
+ .padding(.horizontal, 12)
+ .padding(.vertical, 8)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(PressScale())
+ .disabled(!on && members.count >= Self.maxMembers)
+ .accessibilityAddTraits(on ? .isSelected : [])
+ }
+
+ private func save() {
+ saving = true
+ error = nil
+ let typed = name.trimmingCharacters(in: .whitespacesAndNewlines)
+ let finalName = typed.isEmpty ? defaultName : typed
+ Task {
+ do {
+ if let groupId {
+ var draft = GroupDraft(name: finalName, members: members)
+ draft.id = groupId
+ try await model.updateGroup(draft)
+ } else {
+ _ = try await model.createGroup(name: finalName, members: members)
+ }
+ dismiss()
+ } catch {
+ withAnimation(Motion.fade) { self.error = error.localizedDescription }
+ }
+ saving = false
+ }
+ }
+}
diff --git a/kit/Sources/CodyncUI/Bots/NewChatView.swift b/kit/Sources/CodyncUI/Bots/NewChatView.swift
index 9b2055c6..2cd1e588 100644
--- a/kit/Sources/CodyncUI/Bots/NewChatView.swift
+++ b/kit/Sources/CodyncUI/Bots/NewChatView.swift
@@ -10,6 +10,7 @@ public struct NewChatView: View {
@State private var query = ""
@State private var draft = ""
@State private var creating = false
+ @State private var creatingGroup = false
@FocusState private var toFocused: Bool
public init(close: @escaping () -> Void) { self.close = close }
@@ -45,9 +46,21 @@ public struct NewChatView: View {
} label: {
Text(query.isEmpty ? "Create new Bot" : "Create “\(query)”")
}
+ PickRow(shortcut: 2, action: { creatingGroup = true }) {
+ Image(systemName: "person.2")
+ .font(.system(size: 12, weight: .medium))
+ .frame(width: 26, height: 26)
+ .background(Palette.bubbleAgent, in: Circle())
+ } label: {
+ Text("Create group chat")
+ }
ForEach(Array(matches.enumerated()), id: \.element.id) { i, bot in
- PickRow(shortcut: i + 2 <= 9 ? i + 2 : nil, action: { pick(bot) }) {
- CharacterAvatar(bot: bot, size: 26, animated: false)
+ PickRow(shortcut: i + 3 <= 9 ? i + 3 : nil, action: { pick(bot) }) {
+ if bot.isGroup {
+ GroupAvatar(members: model.members(of: bot), size: 26, animated: false)
+ } else {
+ CharacterAvatar(bot: bot, size: 26, animated: false)
+ }
} label: {
Text(bot.name)
}
@@ -83,6 +96,11 @@ public struct NewChatView: View {
await Task.yield()
toFocused = true
}
+ .codyncSheet(isPresented: $creatingGroup) {
+ GroupEditorView()
+ .frame(width: 420, height: 560)
+ .onDisappear { if model.selection != nil { finishGroup() } }
+ }
}
private func pick(_ bot: Bot) {
@@ -92,6 +110,14 @@ public struct NewChatView: View {
close()
}
+ /// The new group is selected: carry over what was typed and close.
+ private func finishGroup() {
+ guard let id = model.selection else { return }
+ let text = draft.trimmingCharacters(in: .whitespacesAndNewlines)
+ if !text.isEmpty { model.send(text, to: id) }
+ close()
+ }
+
private func create() {
guard !creating else { return }
creating = true
diff --git a/kit/Sources/CodyncUI/Call/CallView.swift b/kit/Sources/CodyncUI/Call/CallView.swift
index c4550e40..3ac25e61 100644
--- a/kit/Sources/CodyncUI/Call/CallView.swift
+++ b/kit/Sources/CodyncUI/Call/CallView.swift
@@ -14,7 +14,7 @@ struct CallView: View {
private var bot: Bot? { model.bots[botId] }
/// The newest final reply; each new one is read aloud.
- private var lastReply: Entry? { model.thread(botId).last { $0.kind == "agent" && $0.data.final == true } }
+ private var lastReply: Entry? { model.chat(botId).last { $0.kind == "agent" && $0.data.final == true } }
var body: some View {
VStack(spacing: 0) {
diff --git a/kit/Sources/CodyncUI/Chrome.swift b/kit/Sources/CodyncUI/Chrome.swift
index 0f71d8a1..3e5dc505 100644
--- a/kit/Sources/CodyncUI/Chrome.swift
+++ b/kit/Sources/CodyncUI/Chrome.swift
@@ -4,6 +4,17 @@ import SwiftUI
import UIKit
#endif
+private struct ScreenHeaderIconGlassKey: EnvironmentKey {
+ static let defaultValue = false
+}
+
+private extension EnvironmentValues {
+ var screenHeaderIconGlass: Bool {
+ get { self[ScreenHeaderIconGlassKey.self] }
+ set { self[ScreenHeaderIconGlassKey.self] = newValue }
+ }
+}
+
// Codync's own screen chrome: modals, headers, icon buttons and the iPhone tab bar.
// Never use `.sheet`, `.popover`, `.toolbar`/`ToolbarItem`, navigation bars or
// `TabView`: present with `.codyncSheet`, title with `ModalHeader` / `ScreenHeader`.
@@ -52,16 +63,24 @@ public struct IconButtonStyle: ButtonStyle {
let size: CGFloat
@State private var hovering = false
@Environment(\.isEnabled) private var isEnabled
+ @Environment(\.screenHeaderIconGlass) private var screenHeaderIconGlass
var body: some View {
configuration.label
.font(.system(size: size / 2, weight: .medium))
.foregroundStyle(selected ? Palette.onAccent : hovering ? Palette.text : Palette.secondary)
.frame(width: size, height: size)
- .background(
- selected ? Palette.accentFill : Palette.text.opacity(configuration.isPressed ? 0.14 : hovering ? 0.08 : 0),
- in: RoundedRectangle(cornerRadius: size * 0.28, style: .continuous)
- )
+ .background {
+ let shape = RoundedRectangle(cornerRadius: size * 0.34, style: .continuous)
+ #if os(iOS)
+ if screenHeaderIconGlass {
+ shape.fill(.clear).glass(in: shape)
+ }
+ #endif
+ shape.fill(
+ selected ? Palette.accentFill : Palette.text.opacity(configuration.isPressed ? 0.14 : hovering ? 0.08 : 0)
+ )
+ }
.opacity(isEnabled ? 1 : 0.35)
.scaleEffect(configuration.isPressed ? Motion.pressScale : 1)
.animation(Motion.press, value: configuration.isPressed)
@@ -127,6 +146,7 @@ public struct ScreenHeader<Leading: View, Title: View, Trailing: View>: View {
Spacer(minLength: 8)
trailing
}
+ .environment(\.screenHeaderIconGlass, true)
}
.padding(.horizontal, InterfaceMetrics.value(mac: 12, mobile: 12))
.frame(height: InterfaceMetrics.value(mac: 44, mobile: 52))
diff --git a/kit/Sources/CodyncUI/Store/BotStore.swift b/kit/Sources/CodyncUI/Store/BotStore.swift
index 8f810e44..2236b3a5 100644
--- a/kit/Sources/CodyncUI/Store/BotStore.swift
+++ b/kit/Sources/CodyncUI/Store/BotStore.swift
@@ -148,7 +148,20 @@ public final class BotStore {
public var hiddenBots: [Bot] { bots.values.filter(\.hidden).sorted { $0.name < $1.name } }
- public func thread(_ botId: String) -> [Entry] { entries[botId] ?? [] }
+ /// A bot's or group's main chat (thread replies are left out).
+ public func chat(_ botId: String) -> [Entry] { (entries[botId] ?? []).filter { $0.threadId == nil } }
+
+ /// Everything in a chat, threads included (the full conversation).
+ public func allEntries(_ botId: String) -> [Entry] { entries[botId] ?? [] }
+
+ /// The replies in the thread on `root`, oldest first.
+ public func replies(_ botId: String, root: String) -> [Entry] { (entries[botId] ?? []).filter { $0.threadId == root } }
+
+ /// A group's bots that still exist.
+ public func members(of group: Bot) -> [Bot] { group.members.compactMap { bots[$0] } }
+
+ /// Display name of an entry's author in a group chat.
+ public func authorName(_ id: String?) -> String { id.flatMap { bots[$0]?.name } ?? "A deleted bot" }
func updateComputer(_ change: (inout Computer) -> Void) {
var c = computer
@@ -454,31 +467,32 @@ public final class BotStore {
return client
}
- public func send(_ text: String, to botId: String) {
- send(text, to: botId, nonce: UUID().uuidString)
+ /// `thread`: reply in the thread on that main-chat message.
+ public func send(_ text: String, to botId: String, thread: String? = nil) {
+ send(text, to: botId, thread: thread, nonce: UUID().uuidString)
}
- private func send(_ text: String, to botId: String, nonce: String) {
+ private func send(_ text: String, to botId: String, thread: String?, nonce: String) {
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, !retired else { return }
let local = Entry(
- id: "local-\(nonce)", seq: Int64.max, botId: botId, rev: 0, kind: "user",
+ id: "local-\(nonce)", seq: Int64.max, botId: botId, threadId: thread, rev: 0, kind: "user",
turn: 0, data: EntryData(text: trimmed, status: "sending", clientNonce: nonce),
createdAt: Int64(Date.now.timeIntervalSince1970 * 1000), updatedAt: 0
)
upsert(local)
storage.lastComputerId = computer.id
if canQueue, let remote = transport as? any RemoteTransport {
- enqueue(remote, text: trimmed, botId: botId, nonce: nonce)
+ enqueue(remote, text: trimmed, botId: botId, thread: thread, nonce: nonce)
return
}
- deliver(trimmed, botId: botId, nonce: nonce)
+ deliver(trimmed, botId: botId, thread: thread, nonce: nonce)
}
- private func deliver(_ text: String, botId: String, nonce: String) {
+ private func deliver(_ text: String, botId: String, thread: String?, nonce: String) {
Task {
do {
- let e = try await require().send(botId: botId, text: text, clientNonce: nonce)
+ let e = try await require().send(botId: botId, text: text, clientNonce: nonce, threadId: thread)
upsert(e)
if let bot = bots[botId] { onSent?(bot) }
} catch {
@@ -488,18 +502,18 @@ public final class BotStore {
}
/// The computer is offline: the message waits, sealed for it, in the relay mailbox.
- private func enqueue(_ remote: any RemoteTransport, text: String, botId: String, nonce: String) {
+ private func enqueue(_ remote: any RemoteTransport, text: String, botId: String, thread: String?, nonce: String) {
markLocal(nonce: nonce, botId: botId, status: "waiting")
saveCache()
Task {
do {
- try await remote.enqueue(botId: botId, text: text, clientNonce: nonce)
+ try await remote.enqueue(botId: botId, text: text, clientNonce: nonce, threadId: thread)
if let bot = bots[botId] { onSent?(bot) }
} catch MailboxError.hostOnline {
// It came back meanwhile: send it the normal way once the link is up.
markLocal(nonce: nonce, botId: botId, status: "sending")
try? await Task.sleep(for: .seconds(2))
- deliver(text, botId: botId, nonce: nonce)
+ deliver(text, botId: botId, thread: thread, nonce: nonce)
} catch {
lastError = error.localizedDescription
markLocal(nonce: nonce, botId: botId, status: "failed")
@@ -558,7 +572,7 @@ public final class BotStore {
entries[entry.botId]?.removeAll { $0.id == entry.id }
// The same clientNonce: if the computer got it after all, it won't run twice (the host
// skips a nonce it has). Every seal still takes a fresh ephemeral key (§6.4).
- send(text, to: entry.botId, nonce: entry.data.clientNonce ?? UUID().uuidString)
+ send(text, to: entry.botId, thread: entry.threadId, nonce: entry.data.clientNonce ?? UUID().uuidString)
}
public func discard(_ entry: Entry) {
@@ -616,6 +630,25 @@ public final class BotStore {
perform { try await $0.deleteBot(bot.id) }
}
+ /// Creates a group chat (or opens the one these bots already share) and selects it.
+ public func createGroup(name: String, members: [String]) async throws -> Bot {
+ let group = try await require().createGroup(GroupDraft(name: name, members: members))
+ bots[group.id] = group
+ selection = group.id
+ return group
+ }
+
+ public func updateGroup(_ draft: GroupDraft) async throws {
+ let group = try await require().updateGroup(draft)
+ bots[group.id] = group
+ }
+
+ /// Pages in a thread's replies (the stream only carries recent entries).
+ public func loadThread(_ botId: String, root: String) async {
+ guard let client, let replies = try? await client.thread(botId: botId, rootId: root) else { return }
+ for e in replies { upsert(e) }
+ }
+
public func save(_ draft: BotDraft) async throws -> Bot {
let client = try require()
let bot = draft.id == nil ? try await client.createBot(draft) : try await client.updateBot(draft)
@@ -688,7 +721,7 @@ public final class BotStore {
public func loadOlder(_ botId: String) async {
guard let client, !historyComplete.contains(botId) else { return }
- let first = thread(botId).first { $0.seq > 0 && $0.seq != Int64.max }?.seq ?? Int64.max
+ let first = chat(botId).first { $0.seq > 0 && $0.seq != Int64.max }?.seq ?? Int64.max
guard let older = try? await client.history(botId: botId, beforeSeq: first, limit: 100) else { return }
if older.count < 100 { historyComplete.insert(botId) }
for e in older { upsert(e) }
diff --git a/kit/Sources/CodyncUI/Thread/ChatRows.swift b/kit/Sources/CodyncUI/Thread/ChatRows.swift
index 98987f9b..43c3497d 100644
--- a/kit/Sources/CodyncUI/Thread/ChatRows.swift
+++ b/kit/Sources/CodyncUI/Thread/ChatRows.swift
@@ -3,9 +3,106 @@ import SwiftUI
/// The rows a conversation is made of.
+/// One chat-visible entry in a chat or a thread, with what can be done to it.
+struct ChatRow: View {
+ let entry: Entry
+ let groupStart: Bool
+ /// The bot or group the chat belongs to.
+ let chat: Bot?
+ let openTrace: () -> Void
+ /// Main chat only: start (or open) the thread on this message.
+ var openThread: ((Entry) -> Void)?
+ @Environment(BotStore.self) private var model
+
+ var body: some View {
+ let reply = openThread.map { open in { open(entry) } }
+ switch entry.kind {
+ case "user":
+ VStack(alignment: .trailing, spacing: 4) {
+ UserBubble(entry: entry, botWorking: chat?.isWorking == true, reply: reply)
+ threadChip
+ }
+ .padding(.top, groupStart ? 12 : 4)
+ case "agent":
+ VStack(alignment: .leading, spacing: 4) {
+ if chat?.isGroup == true, groupStart { AuthorLabel(botId: entry.data.author) }
+ AgentBubble(entry: entry, openTrace: openTrace, reply: reply)
+ threadChip.padding(.leading, chat?.isGroup == true ? 34 : 0)
+ }
+ .padding(.top, groupStart ? 12 : 4)
+ case "permission":
+ VStack(alignment: .leading, spacing: 4) {
+ if chat?.isGroup == true { AuthorLabel(botId: entry.data.author) }
+ PermissionCard(entry: entry, hostName: model.hostName) { option in
+ model.respond(entry, option: option)
+ }
+ }
+ .padding(.top, 12)
+ default:
+ NoticeRow(entry: entry).padding(.top, 10)
+ }
+ }
+
+ @ViewBuilder private var threadChip: some View {
+ if let summary = entry.data.thread, summary.count > 0, let openThread {
+ ThreadChip(summary: summary) { openThread(entry) }
+ }
+ }
+}
+
+/// Who wrote a message in a group: their avatar and name in their color.
+struct AuthorLabel: View {
+ let botId: String?
+ @Environment(BotStore.self) private var model
+
+ var body: some View {
+ let bot = botId.flatMap { model.bots[$0] }
+ HStack(spacing: 8) {
+ if let bot { CharacterAvatar(bot: bot, size: 26, animated: false) }
+ Text(model.authorName(botId))
+ .font(.subheadline.weight(.medium))
+ .foregroundStyle(bot.map { AvatarPalette.color($0.avatarColor) } ?? Palette.secondary)
+ }
+ }
+}
+
+/// Under a message with a thread (Slack's): who replied, how many, how recently.
+struct ThreadChip: View {
+ let summary: ThreadSummary
+ let open: () -> Void
+ @Environment(BotStore.self) private var model
+
+ var body: some View {
+ Button(action: open) {
+ HStack(spacing: 6) {
+ HStack(spacing: -6) {
+ ForEach(summary.authors.compactMap { model.bots[$0] }.prefix(3)) { bot in
+ CharacterAvatar(bot: bot, size: 18, animated: false)
+ }
+ }
+ Text(summary.count == 1 ? "1 reply" : "\(summary.count) replies")
+ .font(.footnote.weight(.semibold))
+ .foregroundStyle(Palette.accent)
+ Text(RelativeTime.day(Date(milliseconds: summary.lastAt)))
+ .font(.footnote)
+ .foregroundStyle(Palette.tertiary)
+ Image(systemName: "chevron.right").font(.caption2).foregroundStyle(Palette.tertiary)
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 5)
+ .background(Palette.surface, in: Capsule())
+ .contentShape(Capsule())
+ }
+ .buttonStyle(PressScale())
+ .accessibilityLabel("View thread, \(summary.count) \(summary.count == 1 ? "reply" : "replies")")
+ .help("View thread")
+ }
+}
+
struct UserBubble: View {
let entry: Entry
let botWorking: Bool
+ var reply: (() -> Void)?
@Environment(BotStore.self) private var model
var body: some View {
@@ -18,7 +115,9 @@ struct UserBubble: View {
.padding(.vertical, InterfaceMetrics.value(mac: 8, mobile: 10))
.background(Palette.bubbleUser, in: RoundedRectangle(cornerRadius: 22, style: .continuous))
.contextActions {
- [MenuItem("Copy", icon: "doc.on.doc") { Pasteboard.copy(entry.data.text) }]
+ var items = [MenuItem("Copy", icon: "doc.on.doc") { Pasteboard.copy(entry.data.text) }]
+ if let reply { items.append(MenuItem("Reply in thread", icon: "bubble.left.and.bubble.right", action: reply)) }
+ return items
}
status
}
@@ -67,6 +166,7 @@ struct UserBubble: View {
struct AgentBubble: View {
let entry: Entry
let openTrace: () -> Void
+ var reply: (() -> Void)?
var body: some View {
VStack(alignment: .leading, spacing: 4) {
@@ -75,10 +175,12 @@ struct AgentBubble: View {
.padding(.vertical, InterfaceMetrics.value(mac: 8, mobile: 10))
.background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 22, style: .continuous))
.contextActions {
- [
+ var items = [
MenuItem("Copy", icon: "doc.on.doc") { Pasteboard.copy(entry.data.text) },
MenuItem("Show what it did", icon: "list.bullet.rectangle", action: openTrace),
]
+ if let reply { items.insert(MenuItem("Reply in thread", icon: "bubble.left.and.bubble.right", action: reply), at: 1) }
+ return items
}
#if os(macOS)
Text(entry.date, style: .time)
diff --git a/kit/Sources/CodyncUI/Thread/Composer.swift b/kit/Sources/CodyncUI/Thread/Composer.swift
new file mode 100644
index 00000000..29e9e592
--- /dev/null
+++ b/kit/Sources/CodyncUI/Thread/Composer.swift
@@ -0,0 +1,131 @@
+import CodyncKit
+import SwiftUI
+
+/// The message box under a chat or a thread: send, or stop while the bot (or the
+/// group) is working there. In a group, typing `@` suggests its bots.
+struct Composer: View {
+ let botId: String
+ /// Replies go to the thread on this message.
+ var thread: String?
+ @Environment(BotStore.self) private var model
+ @State private var draft = ""
+ @FocusState private var focused: Bool
+
+ private var bot: Bot? { model.bots[botId] }
+ private var working: Bool { bot?.isWorking(in: botId, thread: thread) == true }
+
+ private var canSend: Bool {
+ // Offline computers still take messages when the relay can hold them for it.
+ !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && (model.connection == .online || model.canQueue)
+ }
+
+ private var placeholder: String {
+ let name = bot?.name ?? ""
+ if thread != nil { return "Reply…" }
+ if bot?.isGroup == true { return "Message \(name) · @ to ask one bot" }
+ return working ? "Queue a message for \(name)" : "Message \(name)"
+ }
+
+ /// The `@partial` being typed at the end, if any.
+ private var mentionQuery: String? {
+ guard bot?.isGroup == true, let at = draft.lastIndex(of: "@") else { return nil }
+ let query = draft[draft.index(after: at)...]
+ if at > draft.startIndex, !draft[draft.index(before: at)].isWhitespace { return nil }
+ return query.contains(where: \.isNewline) || query.count > 24 ? nil : String(query)
+ }
+
+ private var suggestions: [Bot] {
+ guard let query = mentionQuery, let bot else { return [] }
+ return model.members(of: bot).filter {
+ query.isEmpty || $0.name.localizedCaseInsensitiveContains(query)
+ }
+ }
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: 6) {
+ if !suggestions.isEmpty {
+ ScrollView(.horizontal, showsIndicators: false) {
+ HStack(spacing: 6) {
+ ForEach(suggestions) { member in
+ Button { mention(member) } label: {
+ HStack(spacing: 6) {
+ CharacterAvatar(bot: member, size: 18, animated: false)
+ Text(member.name).font(.subheadline).foregroundStyle(Palette.text)
+ }
+ .padding(.horizontal, 10)
+ .padding(.vertical, 6)
+ .background(Palette.surface, in: Capsule())
+ }
+ .buttonStyle(PressScale())
+ }
+ }
+ .padding(.horizontal, 16)
+ }
+ .transition(.move(edge: .bottom).combined(with: .opacity))
+ }
+ field
+ }
+ .animation(Motion.layout, value: suggestions.map(\.id))
+ }
+
+ private var field: some View {
+ HStack(alignment: .bottom, spacing: 8) {
+ TextField(placeholder, text: $draft, axis: .vertical)
+ .lineLimit(1...8)
+ .font(InterfaceMetrics.body)
+ .textFieldStyle(.plain)
+ .focused($focused)
+ .padding(.vertical, InterfaceMetrics.value(mac: 7, mobile: 10))
+ .sendOnReturn(submit)
+ if working && draft.isEmpty {
+ Button {
+ model.stop(botId)
+ } label: {
+ Image(systemName: "stop.fill")
+ .font(.system(size: 12, weight: .bold))
+ .frame(width: InterfaceMetrics.value(mac: 28, mobile: 34), height: InterfaceMetrics.value(mac: 28, mobile: 34))
+ .background(Palette.accentFill, in: Circle())
+ .foregroundStyle(Palette.onAccent)
+ }
+ .buttonStyle(.plain)
+ .accessibilityLabel("Stop")
+ .help("Stop")
+ } else {
+ Button(action: submit) {
+ Image(systemName: "arrow.up")
+ .font(.system(size: 14, weight: .bold))
+ .frame(width: InterfaceMetrics.value(mac: 28, mobile: 34), height: InterfaceMetrics.value(mac: 28, mobile: 34))
+ .background(canSend ? Palette.accentFill : Palette.accentDim, in: Circle())
+ .foregroundStyle(canSend ? Palette.onAccent : Palette.tertiary)
+ }
+ .buttonStyle(.plain)
+ .disabled(!canSend)
+ .accessibilityLabel("Send")
+ .help("Send")
+ }
+ }
+ .padding(.leading, InterfaceMetrics.value(mac: 14, mobile: 18))
+ .padding(.trailing, 6)
+ .padding(.vertical, InterfaceMetrics.value(mac: 4, mobile: 6))
+ .composerSurface(in: RoundedRectangle(cornerRadius: 24, style: .continuous))
+ .padding(.horizontal, 16)
+ .padding(.top, 6)
+ .padding(.bottom, 16)
+ #if os(macOS)
+ .frame(maxWidth: 820)
+ .frame(maxWidth: .infinity)
+ #endif
+ }
+
+ private func mention(_ member: Bot) {
+ guard let at = draft.lastIndex(of: "@") else { return }
+ draft = String(draft[..<at]) + "@\(member.name) "
+ focused = true
+ }
+
+ private func submit() {
+ guard canSend else { return }
+ model.send(draft, to: botId, thread: thread)
+ draft = ""
+ }
+}
diff --git a/kit/Sources/CodyncUI/Thread/RepliesView.swift b/kit/Sources/CodyncUI/Thread/RepliesView.swift
new file mode 100644
index 00000000..9970c395
--- /dev/null
+++ b/kit/Sources/CodyncUI/Thread/RepliesView.swift
@@ -0,0 +1,79 @@
+import CodyncKit
+import SwiftUI
+
+/// A thread (Slack's "reply in thread"): the message it started on, its replies,
+/// and a box to continue there. In a bot's own chat the thread is a separate branch
+/// of the conversation (its own session, forked from the chat); in a group the room
+/// answers inside the thread.
+struct RepliesView: View {
+ let botId: String
+ let rootId: String
+ let close: () -> Void
+ @Environment(BotStore.self) private var model
+ @State private var showTrace = false
+
+ private var chat: Bot? { model.bots[botId] }
+ private var root: Entry? { model.allEntries(botId).first { $0.id == rootId } }
+
+ var body: some View {
+ let replies = model.replies(botId, root: rootId)
+ VStack(spacing: 0) {
+ HStack(spacing: 8) {
+ VStack(alignment: .leading, spacing: 0) {
+ Text("Thread").font(InterfaceMetrics.body.weight(.semibold)).foregroundStyle(Palette.text)
+ Text(chat?.name ?? "").font(.caption).foregroundStyle(Palette.tertiary).lineLimit(1)
+ }
+ Spacer(minLength: 8)
+ IconButton("Close thread", systemImage: "xmark", action: close)
+ .keyboardShortcut(.cancelAction)
+ }
+ .padding(.leading, InterfaceMetrics.value(mac: 16, mobile: 20))
+ .padding(.trailing, InterfaceMetrics.value(mac: 10, mobile: 12))
+ .frame(height: InterfaceMetrics.value(mac: 48, mobile: 56))
+ Rectangle().fill(Palette.border).frame(height: 0.5)
+
+ ScrollView {
+ LazyVStack(alignment: .leading, spacing: 0) {
+ if let root {
+ ChatRow(entry: root, groupStart: true, chat: chat) { showTrace = true }
+ HStack(spacing: 10) {
+ Text(replies.isEmpty ? "No replies yet" : replies.count == 1 ? "1 reply" : "\(replies.count) replies")
+ .font(.caption)
+ .foregroundStyle(Palette.tertiary)
+ .fixedSize()
+ Rectangle().fill(Palette.border).frame(height: 1)
+ }
+ .padding(.vertical, 12)
+ }
+ ForEach(ChatItem.build(replies)) { item in
+ if case let .entry(e, groupStart) = item.kind {
+ ChatRow(entry: e, groupStart: groupStart, chat: chat) { showTrace = true }
+ }
+ }
+ if let chat, chat.isWorking(in: botId, thread: rootId), !model.isOffline {
+ WorkingIndicator(bot: chat) { showTrace = true }.padding(.top, 6)
+ }
+ Color.clear.frame(height: 8)
+ }
+ .padding(.horizontal, 16)
+ .padding(.top, 8)
+ }
+ .defaultScrollAnchor(.bottom)
+ .scrollDismissesKeyboard(.interactively)
+ .safeAreaInset(edge: .bottom) { Composer(botId: botId, thread: rootId) }
+ }
+ .background(Palette.background)
+ .task(id: rootId) { await model.loadThread(botId, root: rootId) }
+ .codyncSheet(isPresented: $showTrace) {
+ TraceView(botId: botId)
+ #if os(macOS)
+ .frame(width: 620, height: 560)
+ #endif
+ }
+ }
+}
+
+/// Which thread is open.
+struct ThreadTarget: Identifiable, Equatable {
+ let id: String
+}
diff --git a/kit/Sources/CodyncUI/Thread/ThreadView.swift b/kit/Sources/CodyncUI/Thread/ThreadView.swift
index aa5a04b3..abbfe452 100644
--- a/kit/Sources/CodyncUI/Thread/ThreadView.swift
+++ b/kit/Sources/CodyncUI/Thread/ThreadView.swift
@@ -1,16 +1,18 @@
import CodyncKit
import SwiftUI
-/// One endless conversation with a bot. Only deliberate messages show here;
-/// tool calls and thinking live in the "Full conversation" sheet.
+/// One endless conversation with a bot or a group chat. Only deliberate messages show
+/// here; tool calls and thinking live in the "Full conversation" sheet. Any message can
+/// start a thread, which opens beside the chat (Mac) or over it (iPhone).
public struct ThreadView: View {
let botId: String
public init(botId: String) { self.botId = botId }
@Environment(BotStore.self) private var model
@Environment(\.dismiss) private var dismiss
- @State private var draft = ""
@State private var showTrace = false
+ @State private var openThread: ThreadTarget?
+ @State private var editingGroup = false
@State private var editing: EditorRequest?
@State private var templateRequest: EditorRequest?
@State private var confirmNewSession = false
@@ -21,7 +23,6 @@ public struct ThreadView: View {
@State private var availableWidth: CGFloat = 800
@State private var compactDetails = false
@State private var calling = false
- @FocusState private var composerFocused: Bool
@Environment(\.accessibilityReduceMotion) private var reduceMotion
private var bot: Bot? { model.bots[botId] }
@@ -31,7 +32,15 @@ public struct ThreadView: View {
GeometryReader { geometry in
HStack(spacing: 0) {
conversation.frame(maxWidth: .infinity)
- if showSettings && geometry.size.width >= 680 {
+ if let openThread, geometry.size.width >= 680 {
+ HStack(spacing: 0) {
+ Rectangle().fill(Palette.border).frame(width: 1)
+ RepliesView(botId: botId, rootId: openThread.id) { closeThread() }
+ .frame(width: min(420, geometry.size.width * 0.45))
+ }
+ .id(openThread.id)
+ .transition(.move(edge: .trailing).combined(with: .opacity))
+ } else if showSettings && geometry.size.width >= 680 {
HStack(spacing: 0) {
Rectangle().fill(Palette.border).frame(width: 1)
detailsPanel.frame(width: 292)
@@ -47,16 +56,29 @@ public struct ThreadView: View {
}
}
.ignoresSafeArea(.container, edges: .top)
+ .animation(Motion.reduced(Motion.layout, reduceMotion), value: openThread)
.codyncSheet(isPresented: $compactDetails) {
detailsPanel.frame(width: 340, height: 600)
}
+ .codyncSheet(isPresented: Binding(get: { openThread != nil && availableWidth < 680 }, set: { if !$0 { openThread = nil } })) {
+ if let openThread {
+ RepliesView(botId: botId, rootId: openThread.id) { closeThread() }.frame(width: 440, height: 600)
+ }
+ }
#else
conversation
+ .codyncSheet(item: $openThread) { target in
+ RepliesView(botId: botId, rootId: target.id) { closeThread() }
+ }
#endif
}
+ private func closeThread() {
+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { openThread = nil }
+ }
+
@ViewBuilder private var conversation: some View {
- let thread = model.thread(botId)
+ let thread = model.chat(botId)
let items = ChatItem.build(thread)
ScrollViewReader { proxy in
ScrollView {
@@ -70,14 +92,14 @@ public struct ThreadView: View {
.padding(.vertical, 12)
}
if items.isEmpty, let bot {
- IntroCard(bot: bot).padding(.top, 40)
+ if bot.isGroup { GroupIntroCard(group: bot).padding(.top, 40) } else { IntroCard(bot: bot).padding(.top, 40) }
}
ForEach(items) { item in
row(item)
.id(item.id)
}
// Offline, "working" is only what the computer last said; don't show it as live.
- if let bot, bot.isWorking, !model.isOffline {
+ if let bot, bot.isWorking(in: botId, thread: nil), !model.isOffline {
WorkingIndicator(bot: bot) { showTrace = true }
.padding(.top, 6)
.id("working")
@@ -107,7 +129,7 @@ public struct ThreadView: View {
#if os(iOS)
ConnectionBanner().padding(.horizontal, 14)
#endif
- composer
+ Composer(botId: botId)
}
}
#if os(iOS)
@@ -125,7 +147,9 @@ public struct ThreadView: View {
.symbolEffect(.pulse, options: .repeating)
.transition(.opacity)
}
- IconButton("Call", systemImage: "phone") { calling = true }
+ if bot?.isGroup != true {
+ IconButton("Call", systemImage: "phone") { calling = true }
+ }
menu
}
.animation(Motion.reduced(Motion.fade, reduceMotion), value: model.screen?.agentBot == botId)
@@ -141,7 +165,7 @@ public struct ThreadView: View {
HStack {
header
Spacer(minLength: 8)
- if let bot {
+ if let bot, !bot.isGroup {
IconButton("Create template", systemImage: "square.and.arrow.up") {
templateRequest = EditorRequest(BotDraft(bot))
}
@@ -160,7 +184,7 @@ public struct ThreadView: View {
.background(Palette.background)
}
.onAppear {
- if bot?.name == "New Bot", model.thread(botId).isEmpty { editingDetails = true }
+ if bot?.name == "New Bot", model.chat(botId).isEmpty { editingDetails = true }
}
#endif
.onAppear { model.markRead(botId) }
@@ -176,6 +200,12 @@ public struct ThreadView: View {
.codyncSheet(item: $editing) { request in
BotEditorView(draft: request.draft)
}
+ .codyncSheet(isPresented: $editingGroup) {
+ GroupEditorView(group: bot)
+ #if os(macOS)
+ .frame(width: 420, height: 560)
+ #endif
+ }
.codyncDialog("Start a new session?", isPresented: $confirmNewSession,
message: "The conversation stays here, but the agent starts with a fresh context.") {
[DialogAction("New session") { model.newSession(botId) }]
@@ -195,20 +225,10 @@ public struct ThreadView: View {
.padding(.top, 18)
.padding(.bottom, 6)
case .entry(let e, let groupStart):
- switch e.kind {
- case "user":
- UserBubble(entry: e, botWorking: bot?.isWorking == true)
- .padding(.top, groupStart ? 12 : 4)
- case "agent":
- AgentBubble(entry: e) { showTrace = true }
- .padding(.top, groupStart ? 12 : 4)
- case "permission":
- PermissionCard(entry: e, hostName: model.hostName) { option in
- model.respond(e, option: option)
- }
- .padding(.top, 12)
- default:
- NoticeRow(entry: e).padding(.top, 10)
+ ChatRow(entry: e, groupStart: groupStart, chat: bot) {
+ showTrace = true
+ } openThread: { root in
+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { openThread = ThreadTarget(id: root.id) }
}
}
}
@@ -220,11 +240,13 @@ public struct ThreadView: View {
#if os(macOS)
toggleDetails()
#else
- if let bot { editing = EditorRequest(BotDraft(bot)) }
+ if bot?.isGroup == true { editingGroup = true } else if let bot { editing = EditorRequest(BotDraft(bot)) }
#endif
} label: {
HStack(spacing: 7) {
- if let bot { CharacterAvatar(bot: bot, size: 22) }
+ if let bot {
+ if bot.isGroup { GroupAvatar(members: model.members(of: bot), size: 22) } else { CharacterAvatar(bot: bot, size: 22) }
+ }
Text(bot?.name ?? "")
.font(.system(size: 13, weight: .semibold))
.foregroundStyle(Palette.text)
@@ -252,7 +274,7 @@ public struct ThreadView: View {
/// Its own view so it stays live inside the compact modal (which captures its content).
private var detailsPanel: some View {
- DetailsPanel(botId: botId, editing: $editingDetails, showTrace: $showTrace) {
+ DetailsPanel(botId: botId, editing: $editingDetails, editGroup: { editingGroup = true }) {
withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { showSettings = false }
compactDetails = false
}
@@ -262,6 +284,12 @@ public struct ThreadView: View {
private var menu: some View {
DropdownMenu {
var items = [MenuItem("Full conversation", icon: "list.bullet.rectangle") { showTrace = true }]
+ if let bot, bot.isGroup {
+ items.append(MenuItem("Edit group", icon: "person.2") { editingGroup = true })
+ items.append(MenuItem(bot.pinned ? "Unpin" : "Pin", icon: "pin") { model.setPinned(bot, !bot.pinned) })
+ items.append(MenuItem("Delete group", icon: "trash", destructive: true, divider: true) { confirmDelete = bot })
+ return items
+ }
if let bot {
items.append(MenuItem("Edit profile", icon: "pencil") {
#if os(macOS)
@@ -289,67 +317,6 @@ public struct ThreadView: View {
.accessibilityLabel("More")
.help("More")
}
-
- private var canSend: Bool {
- // Offline computers still take messages when the relay can hold them for it.
- !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && (model.connection == .online || model.canQueue)
- }
-
- private func submit() {
- guard canSend else { return }
- model.send(draft, to: botId)
- draft = ""
- }
-
- private var composer: some View {
- let working = bot?.isWorking == true
- return HStack(alignment: .bottom, spacing: 8) {
- TextField(working ? "Queue a message for \(bot?.name ?? "it")" : "Message \(bot?.name ?? "")", text: $draft, axis: .vertical)
- .lineLimit(1...8)
- .font(InterfaceMetrics.body)
- .textFieldStyle(.plain)
- .focused($composerFocused)
- .padding(.vertical, InterfaceMetrics.value(mac: 7, mobile: 10))
- .sendOnReturn(submit)
- if working && draft.isEmpty {
- Button {
- model.stop(botId)
- } label: {
- Image(systemName: "stop.fill")
- .font(.system(size: 12, weight: .bold))
- .frame(width: InterfaceMetrics.value(mac: 28, mobile: 34), height: InterfaceMetrics.value(mac: 28, mobile: 34))
- .background(Palette.accentFill, in: Circle())
- .foregroundStyle(Palette.onAccent)
- }
- .buttonStyle(.plain)
- .accessibilityLabel("Stop")
- .help("Stop")
- } else {
- Button(action: submit) {
- Image(systemName: "arrow.up")
- .font(.system(size: 14, weight: .bold))
- .frame(width: InterfaceMetrics.value(mac: 28, mobile: 34), height: InterfaceMetrics.value(mac: 28, mobile: 34))
- .background(canSend ? Palette.accentFill : Palette.accentDim, in: Circle())
- .foregroundStyle(canSend ? Palette.onAccent : Palette.tertiary)
- }
- .buttonStyle(.plain)
- .disabled(!canSend)
- .accessibilityLabel("Send")
- .help("Send")
- }
- }
- .padding(.leading, InterfaceMetrics.value(mac: 14, mobile: 18))
- .padding(.trailing, 6)
- .padding(.vertical, InterfaceMetrics.value(mac: 4, mobile: 6))
- .composerSurface(in: RoundedRectangle(cornerRadius: 24, style: .continuous))
- .padding(.horizontal, 16)
- .padding(.top, 6)
- .padding(.bottom, 16)
- #if os(macOS)
- .frame(maxWidth: 820)
- .frame(maxWidth: .infinity)
- #endif
- }
}
// MARK: - Chat model
@@ -374,15 +341,74 @@ struct ChatItem: Identifiable {
out.append(ChatItem(id: "sep-\(e.id)", kind: .separator(date)))
lastAuthor = nil
}
- let author = e.kind == "user" ? "user" : e.kind == "agent" ? "agent" : e.kind
+ // In a group each bot is its own author.
+ let author = e.kind == "user" ? "user" : e.kind == "agent" ? "agent:\(e.data.author ?? "")" : e.kind
out.append(ChatItem(id: e.id, kind: .entry(e, groupStart: author != lastAuthor)))
- lastAuthor = (author == "user" || author == "agent") ? author : nil
+ lastAuthor = (author == "user" || e.kind == "agent") ? author : nil
lastDate = date
}
return out
}
}
+/// The start of an empty group chat: who's in it and how the room works.
+private struct GroupIntroCard: View {
+ let group: Bot
+ @Environment(BotStore.self) private var model
+
+ var body: some View {
+ VStack(spacing: 12) {
+ GroupAvatar(members: model.members(of: group), size: 72)
+ Text(group.name).font(.title2.weight(.semibold)).foregroundStyle(Palette.text)
+ Text(model.members(of: group).map(\.name).joined(separator: " · "))
+ .font(.subheadline)
+ .foregroundStyle(Palette.secondary)
+ .multilineTextAlignment(.center)
+ Text("Everyone answers in turn. @mention a bot to ask just that one. Each bot works in its own folder.")
+ .font(.footnote)
+ .foregroundStyle(Palette.tertiary)
+ .multilineTextAlignment(.center)
+ .padding(.top, 4)
+ }
+ .frame(maxWidth: .infinity)
+ .padding(.horizontal, 24)
+ }
+}
+
+#if os(macOS)
+/// A group's bots in the Mac inspector; clicking one opens its own chat.
+private struct GroupMembersList: View {
+ let group: Bot
+ @Environment(BotStore.self) private var model
+
+ var body: some View {
+ ScrollView {
+ VStack(alignment: .leading, spacing: 2) {
+ Text("\(group.members.count) bots").font(.system(size: 13, weight: .semibold)).padding(.bottom, 6)
+ ForEach(model.members(of: group)) { bot in
+ Button { model.selection = bot.id } label: {
+ HStack(spacing: 10) {
+ CharacterAvatar(bot: bot, size: 26)
+ VStack(alignment: .leading, spacing: 1) {
+ Text(bot.name).font(.system(size: 13)).foregroundStyle(Palette.text)
+ Text(bot.isWorking ? (bot.activity.isEmpty ? "Working…" : bot.activity) : bot.folderName)
+ .font(.system(size: 11)).foregroundStyle(Palette.tertiary).lineLimit(1)
+ }
+ Spacer()
+ }
+ .padding(.vertical, 6)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(PressScale())
+ .help("Open \(bot.name)'s own chat")
+ }
+ }
+ .padding(.horizontal, 16)
+ }
+ }
+}
+#endif
+
private struct IntroCard: View {
let bot: Bot
@Environment(BotStore.self) private var model
@@ -417,7 +443,7 @@ private struct IntroCard: View {
private struct DetailsPanel: View {
let botId: String
@Binding var editing: Bool
- @Binding var showTrace: Bool
+ let editGroup: () -> Void
let close: () -> Void
@Environment(BotStore.self) private var model
@Environment(\.accessibilityReduceMotion) private var reduceMotion
@@ -431,6 +457,9 @@ private struct DetailsPanel: View {
IconButton("Back to details", systemImage: "chevron.left") { setEditing(false) }
Text("Settings").font(.system(size: 13, weight: .semibold)).foregroundStyle(Palette.text)
Spacer()
+ } else if bot?.isGroup == true {
+ Spacer()
+ IconButton("Edit group", systemImage: "gearshape", action: editGroup)
} else {
Spacer()
IconButton("Bot settings", systemImage: "gearshape") { setEditing(true) }
@@ -441,7 +470,9 @@ private struct DetailsPanel: View {
.padding(.horizontal, 12)
.frame(height: 44)
ZStack {
- if editing {
+ if let bot, bot.isGroup {
+ GroupMembersList(group: bot)
+ } else if editing {
BotSettingsPanel(botId: botId)
.transition(.move(edge: .trailing).combined(with: .opacity))
} else {
@@ -492,20 +523,6 @@ private struct DetailsPanel: View {
}
.font(.system(size: 13))
}
- Button {
- showTrace = true
- } label: {
- HStack {
- Label("Full conversation", systemImage: "list.bullet.rectangle")
- Spacer()
- Image(systemName: "chevron.right").font(.caption2)
- }
- .font(.system(size: 13))
- .padding(12)
- .background(Palette.surface, in: RoundedRectangle(cornerRadius: 8))
- .contentShape(Rectangle())
- }
- .buttonStyle(PressScale())
}
.padding(.horizontal, 16)
.padding(.bottom, 16)
diff --git a/kit/Sources/CodyncUI/Thread/TraceView.swift b/kit/Sources/CodyncUI/Thread/TraceView.swift
index 62e0712a..331c47f4 100644
--- a/kit/Sources/CodyncUI/Thread/TraceView.swift
+++ b/kit/Sources/CodyncUI/Thread/TraceView.swift
@@ -10,7 +10,7 @@ public struct TraceView: View {
@Environment(BotStore.self) private var model
public var body: some View {
- let turns = Dictionary(grouping: model.thread(botId), by: \.turn)
+ let turns = Dictionary(grouping: model.allEntries(botId), by: \.turn)
.sorted { $0.key < $1.key }
VStack(spacing: 0) {
ModalHeader("Full conversation")
diff --git a/kit/Tests/CodyncUITests/StoreTests.swift b/kit/Tests/CodyncUITests/StoreTests.swift
index 863491d0..f081417a 100644
--- a/kit/Tests/CodyncUITests/StoreTests.swift
+++ b/kit/Tests/CodyncUITests/StoreTests.swift
@@ -66,7 +66,7 @@ actor FakeRemote: RemoteTransport {
nonisolated func computerUpdates() -> AsyncStream<Computer> { AsyncStream { _ in } }
- func enqueue(botId: String, text: String, clientNonce: String) async throws { enqueued.append(clientNonce) }
+ func enqueue(botId: String, text: String, clientNonce: String, threadId: String?) async throws { enqueued.append(clientNonce) }
func cancelQueued(clientNonce: String) async -> MailboxCancel { cancelResult }
func listQueued() async -> [QueuedItem] { enqueued.map { QueuedItem(nonce: $0, exp: nil, state: "queued") } }
@@ -125,28 +125,28 @@ private func botEvent(_ id: String, name: String, rev: Int) -> String {
store.send("hi", to: "b1")
#expect(await until { await fake.enqueued.count == 1 })
- let waiting = try #require(store.thread("b1").first)
+ let waiting = try #require(store.chat("b1").first)
#expect(waiting.data.status == "waiting")
#expect(await fake.sent.isEmpty)
// Cancelled before the computer saw it: gone.
store.cancelQueued(waiting)
- #expect(await until { store.thread("b1").isEmpty })
+ #expect(await until { store.chat("b1").isEmpty })
// Already handed over: it stays, marked delivered.
store.send("second", to: "b1")
#expect(await until { await fake.enqueued.count == 2 })
await fake.setCancelResult(.delivering)
- let second = try #require(store.thread("b1").first)
+ let second = try #require(store.chat("b1").first)
store.cancelQueued(second)
- #expect(await until { store.thread("b1").first?.data.status == "delivering" })
+ #expect(await until { store.chat("b1").first?.data.status == "delivering" })
// Expired in the mailbox: failed, can be resent.
store.send("third", to: "b2")
#expect(await until { await fake.enqueued.count == 3 })
- let third = try #require(store.thread("b2").first?.data.clientNonce)
+ let third = try #require(store.chat("b2").first?.data.clientNonce)
await fake.emit(.expired(nonce: third))
- #expect(await until { store.thread("b2").first?.data.status == "failed" })
+ #expect(await until { store.chat("b2").first?.data.status == "failed" })
// Back online: sends go straight to the computer, and its copy replaces the local one.
await fake.set(.ready(.relay))
@@ -154,7 +154,7 @@ private func botEvent(_ id: String, name: String, rev: Int) -> String {
await fake.emit(botEvent("b1", name: "Rex", rev: 1))
#expect(await until { store.connection == .online })
store.send("live", to: "b3")
- #expect(await until { store.thread("b3").first?.id == "e1" })
+ #expect(await until { store.chat("b3").first?.id == "e1" })
#expect(await fake.sent == ["live"])
store.retire()
}