Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat: show bot exchanges as conversations
Sean Fergusonc1a10aac73fb
diff --git a/apps/desktop/src/renderer/client/host-client.ts b/apps/desktop/src/renderer/client/host-client.tsindex 012212bf..5974bbd2 100644--- a/apps/desktop/src/renderer/client/host-client.ts+++ b/apps/desktop/src/renderer/client/host-client.ts@@ -147,6 +147,10 @@ export class HostClient {return (await this.call<{ entries: Entry[] }>('thread', { botId, rootId })).entries}+ async botConversation(botId: string, peerId: string) {+ return (await this.call<{ entries: Entry[] }>('botConversation', { botId, peerId })).entries+ }+async send(botId: string, text: string, clientNonce: string, threadId: string | null, attachments: string[] | null) {return (await this.call<{ entry: Entry }>('send', { botId, text, clientNonce, threadId, attachments })).entry}diff --git a/apps/desktop/src/renderer/components/Overlay.tsx b/apps/desktop/src/renderer/components/Overlay.tsxindex 1549d190..aba55c11 100644--- a/apps/desktop/src/renderer/components/Overlay.tsx+++ b/apps/desktop/src/renderer/components/Overlay.tsx@@ -302,7 +302,7 @@ export function useContextMenu() {}/** A modal's title row: title, optional trailing actions, and a close button. */-export function ModalHeader({ title, trailing }: { title: string; trailing?: ReactNode }) {+export function ModalHeader({ title, trailing }: { title: ReactNode; trailing?: ReactNode }) {const dismiss = useDismiss()return (<div className="modal-header">diff --git a/apps/desktop/src/renderer/components/icon-fallbacks.ts b/apps/desktop/src/renderer/components/icon-fallbacks.tsindex 18cbeb08..b70b9b52 100644--- a/apps/desktop/src/renderer/components/icon-fallbacks.ts+++ b/apps/desktop/src/renderer/components/icon-fallbacks.ts@@ -10,6 +10,7 @@ const map: Record<string, IconNode> = {'arrow.down.circle': L.CircleArrowDown,'arrow.down.right.and.arrow.up.left': L.Minimize2,'arrow.left': L.ArrowLeft,+ 'arrow.left.arrow.right': L.ArrowLeftRight,'arrow.right': L.ArrowRight,'arrow.right.doc.on.clipboard': L.ClipboardCopy,'arrow.up.doc.on.clipboard': L.ClipboardPaste,diff --git a/apps/desktop/src/renderer/components/symbols.json b/apps/desktop/src/renderer/components/symbols.jsonindex 2d7bbf65..d8609484 100644--- a/apps/desktop/src/renderer/components/symbols.json+++ b/apps/desktop/src/renderer/components/symbols.json@@ -7,6 +7,7 @@"arrow.down.doc.on.clipboard","arrow.down.right.and.arrow.up.left","arrow.left",+"arrow.left.arrow.right","arrow.right","arrow.right.doc.on.clipboard","arrow.right.to.line",diff --git a/apps/desktop/src/renderer/store/bot-mirror.ts b/apps/desktop/src/renderer/store/bot-mirror.tsindex 45235af8..35929389 100644--- a/apps/desktop/src/renderer/store/bot-mirror.ts+++ b/apps/desktop/src/renderer/store/bot-mirror.ts@@ -12,6 +12,7 @@ import {import type { HostClient, HostRoute, HostTransport } from '../client/host-client'import { Observable } from '../lib/observable'import { ComposerDrafts } from '@shared/composer-drafts'+import { canLoadHistory } from '@shared/mirror-window'export type Connection =| { kind: 'unpaired' }@@ -124,6 +125,10 @@ export class BotMirror extends Observable {return this.entries.get(botId) ?? []}+ canLoadOlder(botId: string) {+ return canLoadHistory(this.allEntries(botId), this.historyComplete.has(botId))+ }+replies(botId: string, root: string) {return (this.entries.get(botId) ?? []).filter((e) => e.threadId === root)}diff --git a/apps/desktop/src/renderer/store/bot-store.ts b/apps/desktop/src/renderer/store/bot-store.tsindex 75aeb414..d78b549c 100644--- a/apps/desktop/src/renderer/store/bot-store.ts+++ b/apps/desktop/src/renderer/store/bot-store.ts@@ -267,6 +267,15 @@ export class BotStore extends BotSync {} catch {}}+ /** The history between a bot and one peer. Never upserted: old notices would break `loadOlder`'s paging. */+ async botConversation(botId: string, peerId: string): Promise<Entry[]> {+ try {+ return await (await this.ready()).botConversation(botId, peerId)+ } catch {+ return []+ }+ }+async save(draft: BotDraft) {const client = await this.ready()const res = draft.iddiff --git a/apps/desktop/src/renderer/store/bot-sync.ts b/apps/desktop/src/renderer/store/bot-sync.tsindex b2106076..93856974 100644--- a/apps/desktop/src/renderer/store/bot-sync.ts+++ b/apps/desktop/src/renderer/store/bot-sync.ts@@ -1,4 +1,5 @@import { isChat, type AccessRequest, type CloudStatus, type Entry } from '@shared/models'+import { isOutsideLoadedWindow, snapshotFloors } from '@shared/mirror-window'import { HostClient, HostError, type HostEvent } from '../client/host-client'import { BotMirror, type Connection } from './bot-mirror'@@ -20,6 +21,9 @@ export class BotSync extends BotMirror {private closeEvents: (() => void) | null = nullprivate eventsLoop = 0private rewound = false+ /** The `since` the current events connection asked for, and the per-bot floors snapshotted at its `hello`. */+ private requestedSince = 0+ private floors = new Map<string, number>()private readingViews = new Map<string, { botId: string; thread: string | null }>()// MARK: lifecycle@@ -115,8 +119,10 @@ export class BotSync extends BotMirror {}if (!alive()) returnawait new Promise<void>((resolve, reject) => {+ this.requestedSince = this.rev+ this.floors = new Map()this.closeEvents = client.events(- this.rev,+ this.requestedSince,this.clientKind,(event) => {if (!alive()) return@@ -177,6 +183,7 @@ export class BotSync extends BotMirror {this.usage = event.usagethis.screen = event.screenif (event.rev < this.rev) this.rev = 0+ this.floors = snapshotFloors(this.entries, this.rev === 0 ? 0 : this.requestedSince)breakcase 'bot':this.bots.set(event.bot.id, event.bot)@@ -188,12 +195,14 @@ export class BotSync extends BotMirror {this.composerDrafts.removeBot(event.id)this.bots.delete(event.id)this.entries.delete(event.id)+ this.floors.delete(event.id)this.bump(event.rev)if (this.selection === event.id) this.selection = nullthis.onRosterChanged?.()breakcase 'entry':- this.upsert(event.entry)+ // Old entries re-stamped by the host (new rev) belong to history paging, not the live window.+ if (!this.isBelowFloor(event.entry)) this.upsert(event.entry)this.bump(event.entry.rev)this.acknowledgeVisible(event.entry.botId, event.entry)break@@ -242,10 +251,16 @@ export class BotSync extends BotMirror {this.rev = 0this.hostId = nullthis.historyComplete = new Set()+ this.floors = new Map()this.screen = nullthis.saveCache()}+ private isBelowFloor(e: Entry) {+ const held = this.allEntries(e.botId).some((x) => x.id === e.id)+ return isOutsideLoadedWindow(this.floors.get(e.botId), held, e)+ }+private bump(r: number) {this.rev = Math.max(this.rev, r)}diff --git a/apps/desktop/src/renderer/views/thread/BotConversation.tsx b/apps/desktop/src/renderer/views/thread/BotConversation.tsxnew file mode 100644index 00000000..4fa9b525--- /dev/null+++ b/apps/desktop/src/renderer/views/thread/BotConversation.tsx@@ -0,0 +1,114 @@+import { useEffect, useRef, useState } from 'react'+import { BotAvatar } from '../../components/Avatar'+import { Icon } from '../../components/Icon'+import { ModalHeader } from '../../components/Overlay'+import { font } from '../../lib/fonts'+import { useStore } from '../../store/context'+import type { Entry } from '@shared/models'+import { botConversation, buildBotConversation, groupSummary, verbOf, type BotConversationRow, type BotExchange } from './bot-exchange'+import { AuthorLabel, Bubble, TimeSeparator } from './ChatRows'+import { MarkdownText } from './Markdown'+import './bot-conversation.css'++/** The compact chat row for bot-to-bot messages with one peer: who, never what. Opens the conversation. */+export function BotMessageRow({ exchanges, open }: { exchanges: BotExchange[]; open: (peerId: string) => void }) {+ const store = useStore()+ const { peerId, count, failed } = groupSummary(exchanges)+ const peer = store.bots.get(peerId)+ const name = store.authorName(peerId)+ const lead = count > 1 ? `${count} messages with` : verbOf(exchanges[0]!)+ return (+ <button+ className="press bot-message-row"+ onClick={() => open(peerId)}+ title="Open conversation"+ aria-label={`${lead} ${name}${failed ? ', failed' : ''}`}+ style={{ ...font('footnote'), color: failed ? 'var(--danger)' : 'var(--secondary)' }}+ >+ {failed ? <Icon name="exclamationmark.triangle.fill" size={10} color="var(--danger)" /> : null}+ <span>{lead}</span>+ {peer ? <BotAvatar bot={peer} size={18} animated={false} /> : null}+ <span style={{ ...font('footnote', 'semibold'), color: failed ? 'var(--danger)' : 'var(--text)' }}>{name}</span>+ <Icon name="chevron.right" size={10} color="var(--tertiary)" />+ </button>+ )+}++/** The pair a conversation is between, for its header: the chat's own bot, then its peer. */+function BotPair({ botId, peerId }: { botId: string; peerId: string }) {+ const store = useStore()+ const label = (id: string) => (+ <span style={{ display: 'flex', alignItems: 'center', gap: 6, minWidth: 0 }}>+ {store.bots.get(id) ? <BotAvatar bot={store.bots.get(id)!} size={20} animated={false} /> : null}+ <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{store.authorName(id)}</span>+ </span>+ )+ return (+ <span style={{ display: 'flex', alignItems: 'center', gap: 8 }} aria-label={`${store.authorName(botId)} and ${store.authorName(peerId)}`}>+ {label(botId)}+ <Icon name="arrow.left.arrow.right" size={11} color="var(--tertiary)" />+ {label(peerId)}+ </span>+ )+}++/** Read-only history between a bot and one peer: the live chat merged with what the host returns. */+export function BotConversationView({ botId, peerId }: { botId: string; peerId: string }) {+ const store = useStore()+ const [fetched, setFetched] = useState<Entry[]>([])+ const scroller = useRef<HTMLDivElement>(null)+ const rows = buildBotConversation(botConversation(fetched, store.chat(botId), peerId))++ useEffect(() => {+ let current = true+ void store.botConversation(botId, peerId).then((entries) => {+ if (current) setFetched(entries)+ })+ return () => {+ current = false+ }+ }, [store, botId, peerId])++ useEffect(() => {+ const el = scroller.current+ if (el) el.scrollTop = el.scrollHeight+ }, [rows.length, rows[rows.length - 1]?.id])++ return (+ <div className="bot-conversation">+ <ModalHeader title={<BotPair botId={botId} peerId={peerId} />} />+ <div className="bot-conversation-scroll" ref={scroller}>+ <div className="bot-conversation-rows">+ {rows.length === 0 ? <div style={{ ...font('footnote'), color: 'var(--tertiary)', textAlign: 'center', paddingTop: 24 }}>No messages yet.</div> : null}+ {rows.map((row) => <ConversationRow key={row.id} row={row} />)}+ </div>+ </div>+ </div>+ )+}++function ConversationRow({ row }: { row: BotConversationRow }) {+ const store = useStore()+ switch (row.kind) {+ case 'separator':+ return <TimeSeparator date={row.at} />+ case 'message':+ return (+ <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 4, paddingTop: row.showsAuthor ? 12 : 4 }}>+ {row.showsAuthor ? <AuthorLabel botId={row.author} /> : null}+ <div className="message agent">+ <div className="message-body">+ <Bubble className="bubble agent selectable" items={() => [{ title: 'Copy', icon: 'square.on.square', action: () => window.codync.app.copy(row.text) }]}>+ <MarkdownText text={row.text} />+ </Bubble>+ </div>+ </div>+ </div>+ )+ case 'status': {+ const failed = row.outcome.kind === 'failed'+ const text = row.outcome.kind === 'failed' ? row.outcome.detail || "Didn't complete." : `Waiting for ${store.authorName(row.awaiting)}…`+ return <div className="selectable" style={{ ...font('footnote'), color: failed ? 'var(--danger)' : 'var(--secondary)', padding: '6px 12px' }}>{text}</div>+ }+ }+}diff --git a/apps/desktop/src/renderer/views/thread/ChatRows.tsx b/apps/desktop/src/renderer/views/thread/ChatRows.tsxindex d03bd146..b0d1e3f1 100644--- a/apps/desktop/src/renderer/views/thread/ChatRows.tsx+++ b/apps/desktop/src/renderer/views/thread/ChatRows.tsx@@ -114,7 +114,7 @@ export function ThreadChip({ summary, open }: { summary: ThreadSummary; open: ()}/** A message's text with a right-click menu (with quick reactions on top). */-function Bubble({ className, items, reactions, children }: { className: string; items: () => MenuItem[]; reactions: ReactionPick; children: React.ReactNode }) {+export function Bubble({ className, items, reactions, children }: { className: string; items: () => MenuItem[]; reactions?: ReactionPick; children: React.ReactNode }) {const menu = useContextMenu()return (<>@@ -126,6 +126,11 @@ function Bubble({ className, items, reactions, children }: { className: string;)}+/** The centered time label between runs of messages. */+export function TimeSeparator({ date }: { date: number }) {+ return <div style={{ ...font('footnote'), color: 'var(--tertiary)', textAlign: 'center', padding: '18px 0 6px' }}>{relativeTime.separator(date)}</div>+}+const fullDate = new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' })export function UserBubble({ entry, botWorking, reply }: { entry: Entry; botWorking: boolean; reply?: () => void }) {diff --git a/apps/desktop/src/renderer/views/thread/ThreadView.tsx b/apps/desktop/src/renderer/views/thread/ThreadView.tsxindex 429fe10b..4cc1a462 100644--- a/apps/desktop/src/renderer/views/thread/ThreadView.tsx+++ b/apps/desktop/src/renderer/views/thread/ThreadView.tsx@@ -7,8 +7,9 @@ import { Sheet } from '../../components/Overlay'import { font } from '../../lib/fonts'import { useStore } from '../../store/context'import { UpdateNeededCard } from '../UpdateNeededCard'-import { buildChat, relativeTime, rowIn, useArrivals, type ChatItem } from './chat-items'-import { ChatRow, WorkingIndicator } from './ChatRows'+import { buildChat, rowIn, useArrivals, type ChatItem } from './chat-items'+import { BotConversationView, BotMessageRow } from './BotConversation'+import { ChatRow, TimeSeparator, WorkingIndicator } from './ChatRows'import { Composer } from './Composer'import { ChatSidePanel } from './ChatSidePanel'import { DetailsPanel } from './DetailsPanel'@@ -35,6 +36,7 @@ export function ThreadView({ botId }: { botId: string }) {const bot = store.bots.get(botId) ?? nullconst [showTrace, setShowTrace] = useState(false)const [openThread, setOpenThread] = useState<string | null>(null)+ const [botChat, setBotChat] = useState<string | null>(null)const [editingGroup, setEditingGroup] = useState(false)const [templateDraft, setTemplateDraft] = useState<BotDraft | null>(null)const [showSettings, setShowSettings] = useState(false)@@ -140,7 +142,7 @@ export function ThreadView({ botId }: { botId: string }) {{store.shownConnection.kind !== 'online' || store.mismatch ? <ConnectionSubtitle /> : null}</button></div>- <Transcript botId={botId} openTrace={openTrace} openThread={openThreadOn} openRoutine={presentRoutine} />+ <Transcript botId={botId} openTrace={openTrace} openThread={openThreadOn} openRoutine={presentRoutine} openBotChat={setBotChat} /><div className="composer-dock" ref={dock}><div className="composer-fade" />{store.mismatch ? (@@ -171,6 +173,9 @@ export function ThreadView({ botId }: { botId: string }) {<Sheet open={openThread !== null && !wide} onClose={closeThread} width={440} height={600}>{openThread ? <RepliesView botId={botId} rootId={openThread} close={closeThread} /> : null}</Sheet>+ <Sheet open={botChat !== null} onClose={() => setBotChat(null)} width={620} height={560}>+ {botChat ? <BotConversationView botId={botId} peerId={botChat} /> : null}+ </Sheet><Sheet open={showTrace} onClose={() => setShowTrace(false)} width={620} height={560}><TraceView botId={botId} /></Sheet>@@ -219,19 +224,19 @@ function ConnectionSubtitle() {/** The messages: every loaded message, brought to the newest as it changes while the reader is at the bottom. */const PAGE = 40-function Transcript({ botId, openTrace, openThread, openRoutine }: { botId: string; openTrace: () => void; openThread: (e: { id: string }) => void; openRoutine: (id: string | null) => void }) {+function Transcript({ botId, openTrace, openThread, openRoutine, openBotChat }: { botId: string; openTrace: () => void; openThread: (e: { id: string }) => void; openRoutine: (id: string | null) => void; openBotChat: (peerId: string) => void }) {const store = useStore()const bot = store.bots.get(botId) ?? nullconst thread = store.chat(botId)const live = !!bot && isWorkingIn(bot, botId, null) && !store.isOffline- const all = buildChat(thread)+ const all = buildChat(thread, true)// The newest 40 items first; older pages come in near the top.const [firstShown, setFirstShown] = useState<string | null>(null)const [loadingEarlier, setLoadingEarlier] = useState(false)const found = firstShown ? all.findIndex((i) => i.id === firstShown) : -1const start = found >= 0 ? found : Math.max(0, all.length - PAGE)const items = all.slice(start)- const more = start > 0 || (!store.historyComplete.has(botId) && thread.length >= 50)+ const more = start > 0 || store.canLoadOlder(botId)// Following the newest message, or reading history: scrolling up releases the bottom,// arriving back at the end (or Jump to latest) restores it. Content growth alone never changes it.const [following, setFollowing] = useState(true)@@ -262,7 +267,7 @@ function Transcript({ botId, openTrace, openThread, openRoutine }: { botId: striif (at === 0) {const anchor = list[0]?.idawait store.loadOlder(botId)- list = buildChat(store.chat(botId))+ list = buildChat(store.chat(botId), true)at = anchor ? Math.max(0, list.findIndex((i) => i.id === anchor)) : 0}if (at > 0) setFirstShown(list[Math.max(0, at - PAGE)]!.id)@@ -320,7 +325,7 @@ function Transcript({ botId, openTrace, openThread, openRoutine }: { botId: stri{items.length === 0 && bot ? <div style={{ paddingTop: 40 }}>{isGroup(bot) ? <GroupIntroCard group={bot} /> : <IntroCard bot={bot} />}</div> : null}{items.map((item) => (<div key={item.id} className={arrivals.has(item.id) ? rowIn(item) : undefined}>- <Row item={item} chat={bot} openTrace={openTrace} openThread={openThread} openRoutine={openRoutine} />+ <Row item={item} chat={bot} openTrace={openTrace} openThread={openThread} openRoutine={openRoutine} openBotChat={openBotChat} /></div>))}{bot && live ? (@@ -348,10 +353,11 @@ function Transcript({ botId, openTrace, openThread, openRoutine }: { botId: stri)}-function Row({ item, chat, openTrace, openThread, openRoutine }: { item: ChatItem; chat: Bot | null; openTrace: () => void; openThread: (e: { id: string }) => void; openRoutine: (id: string | null) => void }) {+function Row({ item, chat, openTrace, openThread, openRoutine, openBotChat }: { item: ChatItem; chat: Bot | null; openTrace: () => void; openThread: (e: { id: string }) => void; openRoutine: (id: string | null) => void; openBotChat: (peerId: string) => void }) {if (item.kind === 'separator') {- return <div style={{ ...font('footnote'), color: 'var(--tertiary)', textAlign: 'center', padding: '18px 0 6px' }}>{relativeTime.separator(item.date)}</div>+ return <TimeSeparator date={item.date} />}+ if (item.kind === 'exchanges') return <BotMessageRow exchanges={item.exchanges} open={openBotChat} />const e = item.entryif (e.kind === 'notice' && e.data.routineId) {return (diff --git a/apps/desktop/src/renderer/views/thread/bot-conversation.css b/apps/desktop/src/renderer/views/thread/bot-conversation.cssnew file mode 100644index 00000000..592fcdd6--- /dev/null+++ b/apps/desktop/src/renderer/views/thread/bot-conversation.css@@ -0,0 +1,24 @@+.bot-message-row {+ display: flex;+ align-items: center;+ gap: 6px;+ margin: 0 auto;+ padding: 10px 0;+}+.bot-conversation {+ display: flex;+ flex-direction: column;+ height: 100%;+ min-height: 0;+ background: var(--background);+}+.bot-conversation-scroll {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ /* So `.message.agent` sizes against the sheet, not the window. */+ container-type: inline-size;+}+.bot-conversation-rows {+ padding: 0 16px 8px;+}diff --git a/apps/desktop/src/renderer/views/thread/bot-exchange.test.ts b/apps/desktop/src/renderer/views/thread/bot-exchange.test.tsnew file mode 100644index 00000000..30026739--- /dev/null+++ b/apps/desktop/src/renderer/views/thread/bot-exchange.test.ts@@ -0,0 +1,165 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { botConversation, botExchange, buildBotConversation, groupExchanges, groupSummary, isOutgoing, peerOf, verbOf } from './bot-exchange.ts'+import type { Entry, EntryData } from '../../../shared/models.ts'++interface Extra {+ intent?: string+ sourceBotId?: string+ targetBotId?: string+ request?: string+ outcome?: string+ reply?: string+ heading?: string+}++const notice = (id: string, chat: string, seq: number, status: string, extra: Extra = {}, createdAt = 1000, rev = 1): Entry => {+ const sourceBotId = extra.sourceBotId ?? 'egan'+ const targetBotId = extra.targetBotId ?? 'owen'+ const intent = extra.intent ?? 'message'+ const outgoing = chat === sourceBotId+ const verb = intent === 'ask' ? (outgoing ? 'Asked ' : 'Request from ') : outgoing ? 'Messaged ' : 'Message from '+ const heading = extra.heading ?? `${verb}${outgoing ? 'Owen' : 'Egan'}: ${extra.request ?? 'Inspect this.'}`+ const data: EntryData = {+ text: extra.outcome === undefined ? heading : `${heading}\n${extra.outcome}`,+ heading, status, delegationId: 'd', sourceBotId, targetBotId,+ botMessage: { sourceBotId, targetBotId, text: extra.request ?? 'Inspect this.', reply: extra.reply,+ detail: status === 'failed' || status === 'cancelled' ? extra.outcome : undefined },+ }+ return { id, seq, botId: chat, rev, kind: 'notice', turn: 0, createdAt, updatedAt: createdAt, data }+}+const parsed = (e: Entry) => botExchange(e)!++test('decodes the wire JSON and reads direction and verb from either chat', () => {+ const wire = JSON.parse('{"id":"n","seq":1,"botId":"egan","rev":3,"kind":"notice","turn":0,"createdAt":5,"updatedAt":5,"data":{"text":"Messaged Owen: Hi\\nQueued. Outcome will appear in Owen\'s chat.","heading":"Messaged Owen: Hi","style":"info","status":"queued","delegationId":"d","sourceBotId":"egan","targetBotId":"owen","botMessage":{"sourceBotId":"egan","targetBotId":"owen","text":"Hi"}}}') as Entry+ const out = botExchange(wire)!+ assert.equal(isOutgoing(out), true)+ assert.equal(peerOf(out), 'owen')+ assert.equal(verbOf(out), 'Messaged')+ assert.equal(out.message.text, 'Hi')+ const incoming = botExchange({ ...wire, botId: 'owen', data: { ...wire.data, heading: 'Message from Egan: Hi' } })!+ assert.equal(isOutgoing(incoming), false)+ assert.equal(peerOf(incoming), 'egan')+ assert.equal(verbOf(incoming), 'Message from')+ assert.equal(incoming.message.text, 'Hi')+})++test('structured request is independent of the displayed verb and chat direction', () => {+ for (const intent of ['ask', 'message']) {+ assert.equal(parsed(notice('a', 'egan', 1, 'queued', { intent, request: 'Do it.' })).message.text, 'Do it.')+ assert.equal(parsed(notice('a', 'owen', 1, 'queued', { intent, request: 'Do it.' })).message.text, 'Do it.')+ }+ assert.equal(parsed(notice('a', 'egan', 1, 'queued', { intent: 'ask' })).message.text, 'Inspect this.')+})++test('a name with spaces and a request containing ": " and newlines', () => {+ const heading = 'Asked Owen The Third: Check a: b\nand c: d'+ const x = parsed(notice('a', 'egan', 1, 'queued', { intent: 'ask', heading, request: 'Check a: b\nand c: d' }))+ assert.equal(x.message.text, 'Check a: b\nand c: d')+})++test('completed ask extracts a multi-line reply; message completion has none', () => {+ const ask = parsed(notice('a', 'egan', 1, 'completed', { intent: 'ask', reply: 'Line one.\nLine two: ok.' }))+ assert.equal(ask.message.reply, 'Line one.\nLine two: ok.')+ assert.deepEqual(ask.outcome, { kind: 'done' })+ const msg = parsed(notice('b', 'egan', 2, 'completed', { intent: 'message', outcome: 'Completed.' }))+ assert.equal(msg.message.reply, undefined)+ assert.deepEqual(msg.outcome, { kind: 'done' })+})++test('failed and cancelled carry the outcome as detail', () => {+ const failed = parsed(notice('a', 'egan', 1, 'failed', { outcome: 'Owen stopped.' }))+ assert.deepEqual(failed.outcome, { kind: 'failed', detail: 'Owen stopped.' })+ const cancelled = parsed(notice('b', 'egan', 2, 'cancelled', { intent: 'ask' }))+ assert.deepEqual(cancelled.outcome, { kind: 'failed', detail: '' })+})++test('queued and sent are pending', () => {+ for (const status of ['queued', 'sent']) assert.deepEqual(parsed(notice('a', 'egan', 1, status, { outcome: 'Queued.' })).outcome, { kind: 'pending' })+})++test('structured request does not depend on the rendered notice heading', () => {+ assert.equal(parsed(notice('a', 'egan', 1, 'queued', { heading: 'Something else: odd' })).message.text, 'Inspect this.')+ assert.equal(parsed(notice('a', 'egan', 1, 'queued', { heading: 'Asked Owen: x', intent: 'message' })).message.text, 'Inspect this.')+})++test('existing notices without structured data remain ordinary notices', () => {+ const plain: Entry = { ...notice('a', 'egan', 1, 'sent'), data: { text: 'Hello' } }+ assert.equal(botExchange(plain), null)+ const oldNotice = notice('a', 'egan', 1, 'sent')+ delete oldNotice.data.botMessage+ assert.equal(botExchange(oldNotice), null)+ assert.equal(botExchange({ ...notice('a', 'egan', 1, 'completed'), kind: 'agent' }), null)+})++test('outcome follows the status', () => {+ const of = (status: string, outcome?: string) => botExchange(notice('a', 'egan', 1, status, { outcome }))!.outcome+ assert.deepEqual(of('completed'), { kind: 'done' })+ assert.deepEqual(of('failed', 'Stopped.'), { kind: 'failed', detail: 'Stopped.' })+ assert.deepEqual(of('cancelled'), { kind: 'failed', detail: '' })+ assert.deepEqual(of('queued'), { kind: 'pending' })+ assert.deepEqual(of('sent'), { kind: 'pending' })+})++test('the merge keeps the higher rev, filters the peer and sorts by seq', () => {+ const fetched = [notice('a', 'egan', 2, 'queued', {}, 1000, 1), notice('b', 'egan', 1, 'completed', {}, 900, 1), notice('c', 'egan', 3, 'queued', { targetBotId: 'miles' })]+ const live = [notice('a', 'egan', 2, 'completed', {}, 1000, 2)]+ const merged = botConversation(fetched, live, 'owen')+ assert.deepEqual(merged.map((x) => x.id), ['b', 'a'])+ assert.deepEqual(merged[1]!.outcome, { kind: 'done' })+ const stale = botConversation([notice('a', 'egan', 2, 'completed', {}, 1000, 5)], [notice('a', 'egan', 2, 'queued', {}, 1000, 2)], 'owen')+ assert.deepEqual(stale[0]!.outcome, { kind: 'done' })+})++test('rows: separators, author grouping, reply and status captions', () => {+ const hour = 3_600_000+ const xs = botConversation([+ notice('a', 'egan', 1, 'completed', { intent: 'ask', reply: 'Looks good.' }, 1000),+ notice('b', 'egan', 2, 'completed', {}, 2000),+ notice('c', 'egan', 3, 'queued', {}, 2000 + hour + 1),+ notice('d', 'egan', 4, 'failed', { outcome: 'Stopped.' }, 2000 + hour + 2),+ ], [], 'owen')+ const rows = buildBotConversation(xs)+ assert.deepEqual(rows.map((r) => r.id), [+ 'sep-a', 'a-request', 'a-reply', 'b-request', 'sep-c', 'c-request', 'c-status', 'd-request', 'd-status',+ ])+ const shows = (id: string) => (rows.find((r) => r.id === id) as { showsAuthor: boolean }).showsAuthor+ assert.equal(shows('a-request'), true)+ assert.equal(shows('a-reply'), true)+ assert.equal(shows('b-request'), true)+ assert.equal(shows('c-request'), true)+ assert.equal(shows('d-request'), true)+ assert.deepEqual(rows.find((r) => r.id === 'd-status'), { kind: 'status', id: 'd-status', outcome: { kind: 'failed', detail: 'Stopped.' }, awaiting: 'owen' })+})++test('consecutive requests from one author drop the repeated label', () => {+ const rows = buildBotConversation(botConversation([notice('a', 'egan', 1, 'completed'), notice('b', 'egan', 2, 'completed')], [], 'owen'))+ assert.deepEqual(rows.filter((r) => r.kind === 'message').map((r) => (r as { showsAuthor: boolean }).showsAuthor), [true, false])+})++const user = (id: string, seq: number): Entry => ({ ...notice(id, 'egan', seq, 'x'), kind: 'user', data: { text: 'hi' } })+const trace = (id: string, seq: number): Entry => ({ ...notice(id, 'egan', seq, 'x'), kind: 'thought', data: { text: '…' } })+const counts = (es: Entry[]) => groupExchanges(es).map((s) => [s.entry.id, s.exchanges?.length ?? 0])++test('same-peer runs group at their first entry, in either direction', () => {+ const incoming = notice('b', 'egan', 2, 'completed', { sourceBotId: 'owen', targetBotId: 'egan' })+ assert.deepEqual(counts([notice('a', 'egan', 1, 'completed'), incoming, notice('c', 'egan', 3, 'completed')]), [['a', 3]])+})++test('a different peer or a visible entry splits the run', () => {+ const other = notice('b', 'egan', 2, 'completed', { targetBotId: 'miles' })+ assert.deepEqual(counts([notice('a', 'egan', 1, 'completed'), other, notice('c', 'egan', 3, 'completed')]), [['a', 1], ['b', 1], ['c', 1]])+ assert.deepEqual(counts([notice('a', 'egan', 1, 'completed'), user('u', 2), notice('c', 'egan', 3, 'completed')]), [['a', 1], ['u', 0], ['c', 1]])+})++test('trace entries and plain notices: trace is skipped, a plain notice splits', () => {+ assert.deepEqual(counts([notice('a', 'egan', 1, 'completed'), trace('t', 2), notice('c', 'egan', 3, 'completed')]), [['a', 2]])+ const plain: Entry = { ...notice('p', 'egan', 2, 'sent'), data: { text: 'Hello' } }+ assert.deepEqual(counts([notice('a', 'egan', 1, 'completed'), plain, notice('c', 'egan', 3, 'completed')]), [['a', 1], ['p', 0], ['c', 1]])+})++test('the summary counts and flags a failure anywhere in the group', () => {+ const slot = groupExchanges([notice('a', 'egan', 1, 'completed'), notice('b', 'egan', 2, 'failed'), notice('c', 'egan', 3, 'completed')])[0]!+ assert.deepEqual(groupSummary(slot.exchanges!), { peerId: 'owen', count: 3, failed: true })+ assert.equal(groupSummary(groupExchanges([notice('a', 'egan', 1, 'completed')])[0]!.exchanges!).failed, false)+})diff --git a/apps/desktop/src/renderer/views/thread/bot-exchange.ts b/apps/desktop/src/renderer/views/thread/bot-exchange.tsnew file mode 100644index 00000000..b1f5cf2a--- /dev/null+++ b/apps/desktop/src/renderer/views/thread/bot-exchange.ts@@ -0,0 +1,122 @@+import { isChat, type Entry, type BotMessage } from '../../../shared/models.ts'++/** How a bot-to-bot message ended: still going, delivered, or it didn't complete. */+export type BotOutcome = { kind: 'pending' } | { kind: 'done' } | { kind: 'failed'; detail: string }++/** One bot-to-bot message as seen from `chat`'s own transcript. */+export interface BotExchange {+ id: string+ seq: number+ rev: number+ createdAt: number+ /** The bot whose chat this notice is in. */+ chat: string+ message: BotMessage+ outcome: BotOutcome+}++const SEPARATOR_GAP = 3_600_000++function outcomeOf(status: string | undefined, detail: string | undefined): BotOutcome {+ switch (status) {+ case 'completed':+ return { kind: 'done' }+ case 'failed':+ case 'cancelled':+ return { kind: 'failed', detail: detail ?? '' }+ default:+ return { kind: 'pending' }+ }+}++/** The structured exchange a notice carries, or null for any other entry. */+export function botExchange(e: Entry): BotExchange | null {+ const { botMessage: message, status } = e.data+ if (e.kind !== 'notice' || !message) return null+ if (typeof message.sourceBotId !== 'string' || typeof message.targetBotId !== 'string' || typeof message.text !== 'string') return null+ return { id: e.id, seq: e.seq, rev: e.rev, createdAt: e.createdAt, chat: e.botId, message, outcome: outcomeOf(status, message.detail) }+}++export const isOutgoing = (x: BotExchange) => x.chat === x.message.sourceBotId+export const peerOf = (x: BotExchange) => (isOutgoing(x) ? x.message.targetBotId : x.message.sourceBotId)+export const verbOf = (x: BotExchange) => (isOutgoing(x) ? 'Messaged' : 'Message from')++/** A chat-visible entry; a run of same-peer bot exchanges is one slot at its first entry. */+export interface ChatSlot {+ entry: Entry+ /** The run's exchanges (oldest first), or null for any other entry. */+ exchanges: BotExchange[] | null+}++/**+ * The chat-visible entries of a main transcript, with consecutive exchanges with the same peer+ * (either direction) merged. Anything else visible ends the run; trace entries don't.+ */+export function groupExchanges(entries: Entry[]): ChatSlot[] {+ const out: ChatSlot[] = []+ let run: ChatSlot | null = null+ for (const entry of entries) {+ if (!isChat(entry)) continue+ const x = botExchange(entry)+ if (!x) {+ out.push({ entry, exchanges: null })+ run = null+ } else if (run?.exchanges && peerOf(run.exchanges[0]!) === peerOf(x)) {+ run.exchanges.push(x)+ } else {+ run = { entry, exchanges: [x] }+ out.push(run)+ }+ }+ return out+}++/** What a group row shows: the peer, how many messages, and whether any failed. */+export function groupSummary(xs: BotExchange[]) {+ return { peerId: peerOf(xs[0]!), count: xs.length, failed: xs.some((x) => x.outcome.kind === 'failed') }+}++/**+ * The history between `chat` and `peer`: fetched entries plus the live chat, by id (the higher+ * rev wins), oldest first.+ */+export function botConversation(fetched: Entry[], live: Entry[], peer: string): BotExchange[] {+ const byId = new Map<string, BotExchange>()+ for (const e of [...fetched, ...live]) {+ const x = botExchange(e)+ if (!x) continue+ const known = byId.get(x.id)+ if (!known || x.rev >= known.rev) byId.set(x.id, x)+ }+ return [...byId.values()].filter((x) => peerOf(x) === peer).sort((a, b) => a.seq - b.seq)+}++export type BotConversationRow =+ | { kind: 'separator'; id: string; at: number }+ | { kind: 'message'; id: string; author: string; text: string; showsAuthor: boolean }+ | { kind: 'status'; id: string; outcome: BotOutcome; awaiting: string }++/** The sheet's rows: time separators, request and reply messages, and a caption while pending or failed. */+export function buildBotConversation(xs: BotExchange[]): BotConversationRow[] {+ const rows: BotConversationRow[] = []+ let previousAt: number | null = null+ let author: string | null = null+ const message = (id: string, by: string, text: string) => {+ rows.push({ kind: 'message', id, author: by, text, showsAuthor: by !== author })+ author = by+ }+ for (const x of xs) {+ if (previousAt === null || x.createdAt - previousAt > SEPARATOR_GAP) {+ rows.push({ kind: 'separator', id: `sep-${x.id}`, at: x.createdAt })+ author = null+ }+ previousAt = x.createdAt+ message(`${x.id}-request`, x.message.sourceBotId, x.message.text)+ if (x.message.reply) message(`${x.id}-reply`, x.message.targetBotId, x.message.reply)+ if (x.outcome.kind !== 'done') {+ rows.push({ kind: 'status', id: `${x.id}-status`, outcome: x.outcome, awaiting: x.message.targetBotId })+ author = null+ }+ }+ return rows+}diff --git a/apps/desktop/src/renderer/views/thread/chat-items.ts b/apps/desktop/src/renderer/views/thread/chat-items.tsindex 44aaa537..e0afecf9 100644--- a/apps/desktop/src/renderer/views/thread/chat-items.ts+++ b/apps/desktop/src/renderer/views/thread/chat-items.ts@@ -1,25 +1,34 @@import { useRef } from 'react'import { isChat, type Entry } from '@shared/models'+import { groupExchanges, type BotExchange, type ChatSlot } from './bot-exchange'export type ChatItem =| { id: string; kind: 'separator'; date: number }| { id: string; kind: 'entry'; entry: Entry; groupStart: boolean }+ | { id: string; kind: 'exchanges'; entry: Entry; exchanges: BotExchange[] }/*** Chat-visible entries plus time separators (gaps > 1 h) and author grouping. A bot's messages- * arrive whole (Grok Bot's `send_message`); what it writes along the way is trace.+ * arrive whole (Grok Bot's `send_message`); what it writes along the way is trace. `grouped`+ * (the main transcript, not threads) folds runs of bot exchanges with one peer into one item.*/-export function buildChat(entries: Entry[]): ChatItem[] {+export function buildChat(entries: Entry[], grouped = false): ChatItem[] {const out: ChatItem[] = []let lastDate: number | null = nulllet lastAuthor: string | null = null- for (const e of entries) {- if (!isChat(e)) continue+ const slots: ChatSlot[] = grouped ? groupExchanges(entries) : entries.filter(isChat).map((entry) => ({ entry, exchanges: null }))+ for (const { entry: e, exchanges } of slots) {const id = e.kind === 'user' && e.data.clientNonce ? `user-${e.data.clientNonce}` : e.idif (lastDate === null || e.createdAt - lastDate > 3_600_000) {out.push({ id: `sep-${id}`, kind: 'separator', date: e.createdAt })lastAuthor = null}+ if (exchanges) {+ out.push({ id, kind: 'exchanges', entry: e, exchanges })+ lastAuthor = null+ lastDate = e.createdAt+ continue+ }// In a group each bot is its own author.const author = e.kind === 'user' ? 'user' : e.kind === 'agent' ? `agent:${e.data.author ?? ''}` : e.kindout.push({ id, kind: 'entry', entry: e, groupStart: author !== lastAuthor })diff --git a/apps/desktop/src/shared/mirror-window.test.ts b/apps/desktop/src/shared/mirror-window.test.tsnew file mode 100644index 00000000..b122d88b--- /dev/null+++ b/apps/desktop/src/shared/mirror-window.test.ts@@ -0,0 +1,69 @@+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { canLoadHistory, isOutsideLoadedWindow, mainChatFloor, snapshotFloors } from './mirror-window.ts'+import type { Entry } from './models.ts'++const entry = (id: string, seq: number, extra: Partial<Entry> = {}): Entry => ({ id, seq, botId: 'b', rev: 1, kind: 'notice', turn: 0, createdAt: 0, updatedAt: 0, data: {}, ...extra })++test('earlier main-chat history stays available after a catch-up dominated by replies', () => {+ const catchUp = Array.from({ length: 200 }, (_, i) => entry(`e${i}`, i + 100, { threadId: i < 6 ? null : 'root' }))+ assert.equal(canLoadHistory(catchUp, false), true)+ assert.equal(canLoadHistory(catchUp.filter((e) => e.threadId), false), true)+ assert.equal(canLoadHistory([entry('one', 100)], false), true)+ assert.equal(canLoadHistory(catchUp, true), false)+})++test('empty chats and unsent optimistic messages do not offer server history', () => {+ assert.equal(canLoadHistory([], false), false)+ assert.equal(canLoadHistory([entry('local-draft', Number.MAX_SAFE_INTEGER)], false), false)+ assert.equal(canLoadHistory([entry('local-draft', 0)], false), false)+})++test('a rewritten old entry below the floor is dropped, even with turn 0', () => {+ assert.equal(isOutsideLoadedWindow(100, false, entry('old', 40)), true)+})++test('an update to a held entry applies', () => {+ assert.equal(isOutsideLoadedWindow(100, true, entry('a', 40, { rev: 5 })), false)+})++test('a new entry at or above the floor applies', () => {+ assert.equal(isOutsideLoadedWindow(100, false, entry('mid', 102)), false)+ assert.equal(isOutsideLoadedWindow(100, false, entry('edge', 100)), false)+})++test('thread entries never fall outside', () => {+ assert.equal(isOutsideLoadedWindow(100, false, entry('r', 40, { threadId: 'root' })), false)+})++test('no floor accepts everything, including lower seqs after higher ones (rev-ordered catch-up)', () => {+ const floors = snapshotFloors(new Map(), 0)+ assert.equal(floors.get('b'), undefined)+ assert.equal(isOutsideLoadedWindow(floors.get('b'), false, entry('high', 90)), false)+ assert.equal(isOutsideLoadedWindow(floors.get('b'), false, entry('low', 10)), false)+})++test('since 0 snapshots nothing even when the mirror is loaded', () => {+ assert.equal(snapshotFloors(new Map([['b', [entry('a', 100)]]]), 0).size, 0)+})++test('floor ignores optimistic, threaded and unsequenced entries', () => {+ const list = [entry('local-n', 0), entry('local-m', 3), entry('t', 5, { threadId: 'x' }), entry('a', 100), entry('c', 120)]+ assert.equal(mainChatFloor(list, 7), 100)+ assert.equal(snapshotFloors(new Map([['b', list]]), 7).get('b'), 100)+ assert.equal(mainChatFloor([entry('local-n', 0)], 7), undefined)+})++test('a floor taken at hello is not moved by later inserts (RPC upsert before catch-up)', () => {+ const floors = snapshotFloors(new Map([['b', [entry('a', 100)]]]), 7)+ // A sent message's response lands at a high seq; catch-up entries between still apply.+ assert.equal(isOutsideLoadedWindow(floors.get('b'), false, entry('sent', 130)), false)+ assert.equal(isOutsideLoadedWindow(floors.get('b'), false, entry('caught', 110)), false)+ assert.equal(isOutsideLoadedWindow(floors.get('b'), false, entry('old', 20)), true)+})++test("a send's RPC response newer than since doesn't set the floor", () => {+ const floors = snapshotFloors(new Map([['b', [entry('sent', 1010, { rev: 9 })]]]), 7)+ assert.equal(floors.get('b'), undefined)+ assert.equal(isOutsideLoadedWindow(floors.get('b'), false, entry('routine', 1000, { rev: 8 })), false)+})diff --git a/apps/desktop/src/shared/mirror-window.ts b/apps/desktop/src/shared/mirror-window.tsnew file mode 100644index 00000000..79ef26ab--- /dev/null+++ b/apps/desktop/src/shared/mirror-window.ts@@ -0,0 +1,42 @@+import type { Entry } from './models.ts'++/** A catch-up can be filled by thread replies, leaving fewer main-chat entries than a page. */+export function canLoadHistory(entries: Entry[], complete: boolean): boolean {+ return !complete && entries.some((e) => e.seq > 0 && e.seq !== Number.MAX_SAFE_INTEGER)+}++/**+ * Lowest `seq` among a bot's main-chat entries the mirror had at `since` (optimistic `local-*` ones+ * are left out), or undefined. Newer entries (a send's RPC response landing before this hello) come+ * again in this catch-up and say nothing about the window.+ */+export function mainChatFloor(entries: Entry[], since: number): number | undefined {+ let floor: number | undefined+ for (const e of entries) {+ if (e.threadId || e.seq <= 0 || e.id.startsWith('local-') || e.rev > since) continue+ floor = floor === undefined ? e.seq : Math.min(floor, e.seq)+ }+ return floor+}++/** The per-bot floors for a connection that resumes from `since`: none when it starts from scratch. */+export function snapshotFloors(entries: Map<string, Entry[]>, since: number): Map<string, number> {+ const floors = new Map<string, number>()+ if (since <= 0) return floors+ for (const [botId, list] of entries) {+ const floor = mainChatFloor(list, since)+ if (floor !== undefined) floors.set(botId, floor)+ }+ return floors+}++/**+ * Whether an entry event is a main-chat entry the mirror does not hold that sits below the bot's+ * floor. `seq` follows insert order, so everything created after a connection's `since` is above+ * the floor; an unknown entry below it is an old one the host re-stamped (a rewrite, a reaction)+ * and arrives with history paging. Inserting it would make `loadOlder` skip the gap.+ */+export function isOutsideLoadedWindow(floor: number | undefined, held: boolean, e: Entry): boolean {+ if (floor === undefined || held || e.threadId) return false+ return e.seq < floor+}diff --git a/apps/desktop/src/shared/models.ts b/apps/desktop/src/shared/models.tsindex 63f1c31e..8a6a704a 100644--- a/apps/desktop/src/shared/models.ts+++ b/apps/desktop/src/shared/models.ts@@ -129,7 +129,21 @@ export interface ConnectionRequest {[key: string]: unknown}+export interface BotMessage {+ sourceBotId: string+ targetBotId: string+ text: string+ reply?: string+ detail?: string+}+export interface EntryData {+ /** Structured conversation data added to the existing team-tool notice. */+ botMessage?: BotMessage+ heading?: string+ delegationId?: string+ sourceBotId?: string+ targetBotId?: stringconnectionRequest?: ConnectionRequestroutineId?: stringrunId?: stringdiff --git a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swiftindex 9eecb55f..6d132389 100644--- a/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Client/HostClient.swift@@ -155,6 +155,13 @@ public extension HostClient {return res.entries}+ /// The newest 200 bot-to-bot notices between a bot's chat and a peer, oldest first.+ func botConversation(botId: String, peerId: String) async throws -> [Entry] {+ struct Res: Decodable { var entries: [Entry] }+ let res: Res = try await call("botConversation", ["botId": botId, "peerId": peerId])+ 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 }diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/BotExchange.swift b/apps/ios/Kit/Sources/CodyncKit/Models/BotExchange.swiftnew file mode 100644index 00000000..9cb6eb6d--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Models/BotExchange.swift@@ -0,0 +1,101 @@+import Foundation++/// One bot-to-bot exchange as seen from the chat of one of the two bots.+public struct BotExchange: Identifiable, Equatable, Sendable {+ public enum Outcome: Equatable, Sendable {+ case pending, done, failed(String)++ public var isFailed: Bool {+ if case .failed = self { true } else { false }+ }+ }++ public let id: String+ /// The bot whose chat holds the notice.+ public let chatId: String+ public let seq: Int64+ public let rev: Int64+ public let createdAt: Int64+ public let source: String+ public let target: String+ public let text: String+ public let reply: String?+ public let outcome: Outcome++ /// A notice with structured message data is a bot exchange; existing notices stay plain.+ public init?(_ entry: Entry) {+ guard entry.kind == "notice", let message = entry.data.botMessage else { return nil }+ id = entry.id+ chatId = entry.botId+ seq = entry.seq+ rev = entry.rev+ createdAt = entry.createdAt+ source = message.sourceBotId+ target = message.targetBotId+ text = message.text+ reply = message.reply+ switch entry.data.status {+ case "completed": outcome = .done+ case "failed", "cancelled": outcome = .failed(message.detail ?? "")+ default: outcome = .pending+ }+ }++ public var isOutgoing: Bool { chatId == source }+ public var peerId: String { isOutgoing ? target : source }+ public var verb: String { isOutgoing ? "Messaged" : "Message from" }+ public var date: Date { Date(milliseconds: createdAt) }++ /// The exchanges with `peer` in a chat, oldest first: what the host returned plus the live+ /// chat, keyed by entry id (the higher `rev` wins).+ public static func conversation(fetched: [Entry], live: [Entry], peer: String) -> [BotExchange] {+ var byId: [String: Entry] = [:]+ for e in fetched + live where e.kind == "notice" {+ if let known = byId[e.id], known.rev > e.rev { continue }+ byId[e.id] = e+ }+ return byId.values.compactMap(BotExchange.init).filter { $0.peerId == peer }.sorted { $0.seq < $1.seq }+ }+}++/// A line of the read-only conversation sheet.+public enum BotConversationRow: Identifiable, Equatable, Sendable {+ case separator(id: String, at: Date)+ case message(id: String, author: String, text: String, showsAuthor: Bool)+ /// `awaiting` is the bot being waited for while the outcome is pending.+ case status(id: String, outcome: BotExchange.Outcome, awaiting: String)++ public var id: String {+ switch self {+ case .separator(let id, _), .message(let id, _, _, _), .status(let id, _, _): id+ }+ }++ /// A gap of more than an hour starts a new time block.+ static let gap: Int64 = 3_600_000++ /// Rows for exchanges oldest first. A separator or status row resets the previous author.+ public static func build(_ exchanges: [BotExchange]) -> [BotConversationRow] {+ var rows: [BotConversationRow] = []+ var previousAuthor: String?+ var previousAt: Int64?+ for x in exchanges {+ if previousAt.map({ x.createdAt - $0 > gap }) ?? true {+ rows.append(.separator(id: "sep-\(x.id)", at: x.date))+ previousAuthor = nil+ }+ previousAt = x.createdAt+ rows.append(.message(id: "\(x.id)-request", author: x.source, text: x.text, showsAuthor: previousAuthor != x.source))+ previousAuthor = x.source+ if let reply = x.reply, !reply.isEmpty {+ rows.append(.message(id: "\(x.id)-reply", author: x.target, text: reply, showsAuthor: previousAuthor != x.target))+ previousAuthor = x.target+ }+ if x.outcome != .done {+ rows.append(.status(id: "\(x.id)-status", outcome: x.outcome, awaiting: x.target))+ previousAuthor = nil+ }+ }+ return rows+ }+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/BotExchangeGroup.swift b/apps/ios/Kit/Sources/CodyncKit/Models/BotExchangeGroup.swiftnew file mode 100644index 00000000..001b1fbd--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Models/BotExchangeGroup.swift@@ -0,0 +1,66 @@+import Foundation++/// A run of consecutive bot exchanges with the same peer in a chat's main transcript. Shown as+/// one row: "Messaged Dex" for one exchange, "3 messages with Dex" for more.+public struct BotExchangeGroup: Identifiable, Equatable, Sendable {+ /// The exchanges, oldest first; never empty.+ public let exchanges: [BotExchange]++ /// The first exchange's entry id.+ public var id: String { exchanges[0].id }+ public var first: BotExchange { exchanges[0] }+ public var peerId: String { first.peerId }+ public var count: Int { exchanges.count }+ public var date: Date { first.date }+ /// Any exchange failed.+ public var failed: Bool { exchanges.contains { $0.outcome.isFailed } }++ /// What the row says before the peer's name.+ public var title: String { count == 1 ? first.verb : "\(count) messages with" }++ public func accessibilityLabel(peerName: String) -> String {+ "\(title) \(peerName)\(failed ? ", failed" : "")"+ }++ /// A chat-visible entry of the main transcript, or a group of exchanges.+ public enum Item: Identifiable, Equatable, Sendable {+ case entry(Entry)+ case exchanges(BotExchangeGroup)++ public var id: String {+ switch self {+ case .entry(let e): e.id+ case .exchanges(let g): g.id+ }+ }++ public var date: Date {+ switch self {+ case .entry(let e): e.date+ case .exchanges(let g): g.date+ }+ }+ }++ /// The chat-visible entries with consecutive same-peer exchanges merged. Entries that aren't+ /// shown in the chat (trace) don't end a run; anything shown does.+ public static func collapse(_ entries: [Entry]) -> [Item] {+ var out: [Item] = []+ var run: [BotExchange] = []+ func flush() {+ if !run.isEmpty { out.append(.exchanges(BotExchangeGroup(exchanges: run))) }+ run = []+ }+ for entry in entries where entry.isChat {+ guard let x = BotExchange(entry) else {+ flush()+ out.append(.entry(entry))+ continue+ }+ if let last = run.last, last.peerId != x.peerId { flush() }+ run.append(x)+ }+ flush()+ return out+ }+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/BotMessage.swift b/apps/ios/Kit/Sources/CodyncKit/Models/BotMessage.swiftnew file mode 100644index 00000000..acfa46e3--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncKit/Models/BotMessage.swift@@ -0,0 +1,16 @@+/// Structured conversation data added to a team-tool notice; its existing display fields remain unchanged.+public struct BotMessage: Codable, Hashable, Sendable {+ public var sourceBotId: String+ public var targetBotId: String+ public var text: String+ public var reply: String?+ public var detail: String?++ public init(sourceBotId: String, targetBotId: String, text: String, reply: String? = nil, detail: String? = nil) {+ self.sourceBotId = sourceBotId+ self.targetBotId = targetBotId+ self.text = text+ self.reply = reply+ self.detail = detail+ }+}diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swiftindex 7ecbd075..ee7d408e 100644--- a/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Models.swift@@ -125,6 +125,12 @@ public struct EntryData: Codable, Hashable, Sendable {public var entries: [PlanItem]?/// notice: info | error | dividerpublic var style: String?+ /// Structured conversation data added to the existing team-tool notice.+ public var botMessage: BotMessage?+ public var heading: String?+ public var delegationId: String?+ public var sourceBotId: String?+ public var targetBotId: 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.diff --git a/apps/ios/Kit/Sources/CodyncUI/Chrome.swift b/apps/ios/Kit/Sources/CodyncUI/Chrome.swiftindex e7467150..f4cc8eb5 100644--- a/apps/ios/Kit/Sources/CodyncUI/Chrome.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Chrome.swift@@ -74,19 +74,20 @@ public struct IconButtonStyle: ButtonStyle {// MARK: - Headers/// A modal's title row: title, optional trailing actions, and a close button.-public struct ModalHeader<Trailing: View>: View {- let title: String+public struct ModalHeader<Title: View, Trailing: View>: View {+ let title: Titlelet trailing: Trailing@Environment(\.dismissModal) private var dismiss- public init(_ title: String, @ViewBuilder trailing: () -> Trailing) {- self.title = title+ /// A header whose title is a view (a bot pair, say), set in the header's font.+ public init(@ViewBuilder title: () -> Title, @ViewBuilder trailing: () -> Trailing) {+ self.title = title()self.trailing = trailing()}public var body: some View {HStack(spacing: 8) {- Text(title)+ title.font(.body.weight(.semibold)).foregroundStyle(Palette.text).lineLimit(1)@@ -101,10 +102,20 @@ public struct ModalHeader<Trailing: View>: View {}}-public extension ModalHeader where Trailing == EmptyView {+public extension ModalHeader where Title == Text {+ init(_ title: String, @ViewBuilder trailing: () -> Trailing) {+ self.init(title: { Text(title) }, trailing: trailing)+ }+}++public extension ModalHeader where Title == Text, Trailing == EmptyView {init(_ title: String) { self.init(title) { EmptyView() } }}+public extension ModalHeader where Trailing == EmptyView {+ init(@ViewBuilder title: () -> Title) { self.init(title: title) { EmptyView() } }+}+/// A full screen's top bar (replaces the navigation bar): leading, centered title, trailing.public struct ScreenHeader<Leading: View, Title: View, Trailing: View>: View {let leading: Leadingdiff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swiftindex d1d1ad5d..2429e02b 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Actions.swift@@ -201,6 +201,17 @@ extension BotStore {for e in replies { upsert(e) }}+ /// The bot-to-bot notices between a chat and a peer. Never `upsert`ed: old notices in the+ /// mirror would break `loadOlder`, which pages from the oldest loaded `seq`.+ public func botConversation(_ botId: String, peer: String) async -> [Entry] {+ do {+ return try await ready().botConversation(botId: botId, peerId: peer)+ } catch {+ log.error("botConversation failed: \(error.localizedDescription, privacy: .public)")+ return []+ }+ }+public func save(_ draft: BotDraft) async throws -> Bot {let client = try await ready()let bot = draft.id == nil ? try await client.createBot(draft) : try await client.updateBot(draft)diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swiftindex b241fbe7..ddbd5c60 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore+Sync.swift@@ -19,7 +19,9 @@ extension BotStore {try await Task.sleep(for: Self.mismatchRecheck)continue}- for try await event in client.events(since: rev, client: clientKind) {+ requestedSince = rev+ windowFloors = [:]+ for try await event in client.events(since: requestedSince, client: clientKind) {guard !Task.isCancelled, !retired else { return }setConnection(.online)backoff = 1@@ -84,7 +86,9 @@ extension BotStore {hostId = idsetUsage(newUsage)screen = newScreen- if hostRev < rev { rev = 0 }+ let hostRewound = hostRev < rev+ if hostRewound { rev = 0 }+ windowFloors = requestedSince > 0 && !hostRewound ? loadedFloors() : [:]catchUpRev = hostRevbump(rev)case let .bot(bot):@@ -103,10 +107,15 @@ extension BotStore {removeComposerDrafts(for: id)bots[id] = nilentries[id] = nil+ windowFloors[id] = nilbump(r)if selection == id { selection = nil }onRosterChanged?()case let .entry(e):+ if Self.isOutsideLoadedWindow(e, floor: windowFloors[e.botId], held: entries[e.botId]?.contains { $0.id == e.id } == true) {+ bump(e.rev)+ break+ }let known = entries[e.botId]?.first(where: { $0.id == e.id })upsert(e)bump(e.rev)@@ -160,6 +169,7 @@ extension BotStore {rev = 0hostId = nilhistoryComplete = []+ windowFloors = [:]screen = nilsaveCache()}@@ -176,6 +186,25 @@ extension BotStore {if !caughtUp && rev >= catchUpRev { caughtUp = true }}+ /// Per bot, the lowest synced main-chat `seq` in the mirror (optimistic entries don't count).+ /// Only entries the mirror had at `requestedSince`: newer ones (a send's RPC response landing+ /// before this hello) come again in this catch-up and say nothing about the window.+ private func loadedFloors() -> [String: Int64] {+ entries.compactMapValues { list in+ list.filter { $0.threadId == nil && $0.seq > 0 && $0.seq != .max && $0.rev <= requestedSince }.map(\.seq).min()+ }+ }++ /// An entry event the mirror doesn't hold, in the main chat, below the floor the mirror had+ /// when this connection started: it existed before the window and arrives only because its+ /// rev was bumped (a rewrite, a reaction). Inserting it would hide the gap from `loadOlder`,+ /// which pages from the oldest loaded `seq`; history paging brings it. `seq` follows insert+ /// order, so anything created since the mirror was last synced sits above the floor.+ static func isOutsideLoadedWindow(_ e: Entry, floor: Int64?, held: Bool) -> Bool {+ guard e.threadId == nil, !held, let floor else { return false }+ return e.seq < floor+ }+func upsert(_ e: Entry) {var list = entries[e.botId] ?? []if let i = list.firstIndex(where: { $0.id == e.id }) {diff --git a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swiftindex f9139633..ea12177b 100644--- a/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Store/BotStore.swift@@ -38,6 +38,12 @@ public final class BotStore {/// The first catch-up has arrived: everything up to the host's rev when this app connected.public internal(set) var caughtUp = falsevar catchUpRev = Int64.max+ /// The `since` this connection's events stream was opened with; the `hello` that opens its+ /// catch-up reads it (after a mirror reset `rev` no longer says what was requested).+ var requestedSince: Int64 = 0+ /// Per bot, the lowest synced main-chat `seq` held when this connection's catch-up began+ /// (empty when it began from rev 0). See `isOutsideLoadedWindow`.+ var windowFloors: [String: Int64] = [:]static let dropGrace: Duration = .seconds(5)static let initialConnectionGrace: Duration = .seconds(1)var heldDrop: Connection?@@ -204,6 +210,11 @@ public final class BotStore {/// Everything in a chat, threads included (the full conversation).public func allEntries(_ botId: String) -> [Entry] { entries[botId] ?? [] }+ /// A catch-up full of thread replies can leave only a few main-chat entries, or none.+ public func canLoadOlder(_ botId: String) -> Bool {+ !historyComplete.contains(botId) && allEntries(botId).contains { $0.seq > 0 && $0.seq != Int64.max }+ }+/// The replies in the thread on `root`, oldest first.public func replies(_ botId: String, root: String) -> [Entry] { (entries[botId] ?? []).filter { $0.threadId == root } }diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/BotConversation.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/BotConversation.swiftnew file mode 100644index 00000000..88738490--- /dev/null+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/BotConversation.swift@@ -0,0 +1,140 @@+import CodyncKit+import SwiftUI++/// The peer whose conversation with the chat's bot the sheet shows.+struct BotChatTarget: Identifiable, Equatable {+ let id: String+}++/// The compact line a bot-to-bot message leaves in the chat; tapping it opens the conversation.+struct BotMessageRow: View {+ let group: BotExchangeGroup+ let open: () -> Void+ @Environment(BotStore.self) private var model++ var body: some View {+ let peer = model.bots[group.peerId]+ let name = model.authorName(group.peerId)+ let failed = group.failed+ Button(action: open) {+ HStack(spacing: 6) {+ if failed {+ Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(Palette.danger)+ }+ Text(group.title).foregroundStyle(failed ? Palette.danger : Palette.secondary)+ if let peer { CharacterAvatar(bot: peer, size: 18, animated: false) }+ Text(name).fontWeight(.semibold).foregroundStyle(failed ? Palette.danger : Palette.text)+ Image(systemName: "chevron.right").font(.caption2).foregroundStyle(Palette.tertiary)+ }+ .font(.footnote)+ .padding(.vertical, 10)+ .frame(maxWidth: .infinity)+ .contentShape(Rectangle())+ }+ .buttonStyle(PressScale())+ .padding(.top, 2)+ .accessibilityLabel(group.accessibilityLabel(peerName: name))+ .accessibilityHint("Opens the conversation")+ }+}++/// "[avatar] A ⇄ [avatar] B": the two bots of a conversation.+/// The pair a conversation is between, as its sheet's title: the chat's own bot, then its peer.+struct BotPairTitle: View {+ let botId: String+ let peerId: String+ @Environment(BotStore.self) private var model++ var body: some View {+ HStack(spacing: 8) {+ side(botId)+ Image(systemName: "arrow.left.arrow.right").font(.footnote).foregroundStyle(Palette.tertiary)+ side(peerId)+ }+ .accessibilityElement(children: .ignore)+ .accessibilityLabel("\(model.authorName(botId)) and \(model.authorName(peerId))")+ }++ private func side(_ id: String) -> some View {+ HStack(spacing: 6) {+ if let bot = model.bots[id] { CharacterAvatar(bot: bot, size: 22, animated: false) }+ Text(model.authorName(id))+ }+ }+}++/// Read-only history between a bot and one peer, newest at the bottom.+struct BotConversationView: View {+ let botId: String+ let peerId: String+ @Environment(BotStore.self) private var model+ @State private var fetched: [Entry]?++ private var rows: [BotConversationRow] {+ BotConversationRow.build(BotExchange.conversation(fetched: fetched ?? [], live: model.chat(botId), peer: peerId))+ }++ var body: some View {+ let rows = rows+ VStack(spacing: 0) {+ ModalHeader { BotPairTitle(botId: botId, peerId: peerId) }+ ScrollView {+ LazyVStack(alignment: .leading, spacing: 4) {+ if rows.isEmpty, fetched != nil {+ Text("No messages yet.").font(.footnote).foregroundStyle(Palette.tertiary)+ .frame(maxWidth: .infinity).padding(.top, 24)+ }+ ForEach(rows) { rowView($0) }+ }+ .padding(.horizontal, 16)+ .padding(.bottom, 12)+ }+ .defaultScrollAnchor(.bottom)+ }+ .background(Palette.background)+ .task(id: peerId) { fetched = await model.botConversation(botId, peer: peerId) }+ }++ @ViewBuilder private func rowView(_ row: BotConversationRow) -> some View {+ switch row {+ case .separator(_, let date):+ TimeSeparator(date: date)+ case .message(_, let author, let text, let showsAuthor):+ VStack(alignment: .leading, spacing: 4) {+ if showsAuthor { AuthorLabel(botId: author).padding(.top, 8) }+ ConversationBubble(text: text)+ }+ case .status(_, let outcome, let awaiting):+ caption(outcome, awaiting: awaiting)+ }+ }++ @ViewBuilder private func caption(_ outcome: BotExchange.Outcome, awaiting: String) -> some View {+ switch outcome {+ case .pending:+ Text("Waiting for \(model.authorName(awaiting))…").font(.footnote).foregroundStyle(Palette.secondary)+ .padding(.leading, 12)+ case .failed(let detail):+ Text(detail.isEmpty ? "Didn't complete." : detail).font(.footnote).foregroundStyle(Palette.danger)+ .textSelection(.enabled).padding(.leading, 12)+ case .done:+ EmptyView()+ }+ }+}++/// A message of the conversation: the agent bubble.+private struct ConversationBubble: View {+ let text: String++ var body: some View {+ MarkdownText(text)+ .equatable()+ .padding(.horizontal, 16)+ .padding(.vertical, 10)+ .background(Palette.bubbleAgent, in: RoundedRectangle(cornerRadius: 22, style: .continuous))+ .contextActions { [MenuItem("Copy", icon: "square.on.square") { Pasteboard.copy(text) }] }+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.trailing, 40)+ }+}diff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swiftindex 57ca4aea..79c4e8f5 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ChatRows.swift@@ -62,6 +62,20 @@ struct ChatRow: View {}}+/// A chat's time separator: Today 3:27 AM.+struct TimeSeparator: View {+ let date: Date++ var body: some View {+ Text(RelativeTime.separator(date))+ .font(.footnote)+ .foregroundStyle(Palette.tertiary)+ .frame(maxWidth: .infinity)+ .padding(.top, 18)+ .padding(.bottom, 6)+ }+}+/// Who wrote a message in a group: their avatar and name in their color.struct AuthorLabel: View {let botId: String?@@ -219,6 +233,7 @@ struct AgentBubble: View {}}+struct NoticeRow: View {let entry: Entrydiff --git a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swiftindex 607dceab..a95bad01 100644--- a/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift+++ b/apps/ios/Kit/Sources/CodyncUI/Thread/ThreadView.swift@@ -13,6 +13,7 @@ public struct ThreadView: View {@Environment(\.dismiss) var dismiss@State var showTrace = false@State var openThread: ThreadTarget?+ @State var botChat: BotChatTarget?@State var editingGroup = false@State var editing: EditorRequest?@State var templateRequest: EditorRequest?@@ -76,6 +77,7 @@ public struct ThreadView: View {.codyncSheet(isPresented: $showTrace) {TraceView(botId: botId)}+ .codyncSheet(item: $botChat) { BotConversationView(botId: botId, peerId: $0.id) }.codyncSheet(item: $templateRequest) { request inBotTemplateView(draft: request.draft)}@@ -104,12 +106,9 @@ public struct ThreadView: View {@ViewBuilder func row(_ item: ChatItem) -> some View {switch item.kind {case .separator(let date):- Text(RelativeTime.separator(date))- .font(.footnote)- .foregroundStyle(Palette.tertiary)- .frame(maxWidth: .infinity)- .padding(.top, 18)- .padding(.bottom, 6)+ TimeSeparator(date: date)+ case .exchanges(let group):+ BotMessageRow(group: group) { botChat = BotChatTarget(id: group.peerId) }case .entry(let e, let groupStart):if e.kind == "notice", let id = e.data.routineId {Button {@@ -228,6 +227,8 @@ struct ChatItem: Identifiable {enum Kind {case separator(Date)case entry(Entry, groupStart: Bool)+ /// Main chat only: consecutive bot-to-bot exchanges with one peer.+ case exchanges(BotExchangeGroup)}let id: String@@ -235,24 +236,31 @@ struct ChatItem: Identifiable {/// Chat-visible entries plus time separators (gaps > 1 h) and author grouping. A bot's/// messages arrive whole (Grok Bot's `send_message`); what it writes along the way is trace.- static func build(_ entries: [Entry]) -> [ChatItem] {+ static func build(_ entries: [Entry], groupingExchanges: Bool = false) -> [ChatItem] {var out: [ChatItem] = []var lastDate: Date?var lastAuthor: String?- for e in entries where e.isChat {- let date = e.date+ let slots = groupingExchanges ? BotExchangeGroup.collapse(entries) : entries.filter(\.isChat).map(BotExchangeGroup.Item.entry)+ for slot in slots {+ let date = slot.date// Bot-originated messages carry an empty nonce. Their entry IDs// distinguish them; only real nonces identify optimistic echoes.- let id = if e.kind == "user", let nonce = e.data.clientNonce, !nonce.isEmpty { "user-\(nonce)" } else { e.id }+ let id = if case .entry(let e) = slot, e.kind == "user", let nonce = e.data.clientNonce, !nonce.isEmpty { "user-\(nonce)" } else { slot.id }if lastDate.map({ date.timeIntervalSince($0) > 3600 }) ?? true {out.append(ChatItem(id: "sep-\(id)", kind: .separator(date)))lastAuthor = nil}- // 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: id, kind: .entry(e, groupStart: author != lastAuthor)))- lastAuthor = (author == "user" || e.kind == "agent") ? author : nillastDate = date+ switch slot {+ case .exchanges(let group):+ out.append(ChatItem(id: id, kind: .exchanges(group)))+ lastAuthor = nil+ case .entry(let e):+ // 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: id, kind: .entry(e, groupStart: author != lastAuthor)))+ lastAuthor = (author == "user" || e.kind == "agent") ? author : nil+ }}return out}@@ -340,7 +348,7 @@ extension ThreadView {/// revealed steadily as it's written.var transcript: some View {let thread = model.chat(botId)- let items = ChatItem.build(thread)+ let items = ChatItem.build(thread, groupingExchanges: true)var rows: [ConversationRow] = []if moreOnComputer {rows.append(ConversationRow("earlier") {@@ -367,7 +375,7 @@ extension ThreadView {}private var moreOnComputer: Bool {- !model.historyComplete.contains(botId) && model.chat(botId).count >= 50+ model.canLoadOlder(botId)}/// The reader scrolled up to the top: fetch earlier messages from the computer.diff --git a/apps/ios/Kit/Tests/CodyncKitTests/BotExchangeTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/BotExchangeTests.swiftnew file mode 100644index 00000000..596262aa--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncKitTests/BotExchangeTests.swift@@ -0,0 +1,199 @@+import Foundation+import Testing+@testable import CodyncKit++private func notice(_ id: String, chat: String = "egan", seq: Int64 = 1, rev: Int64 = 1, at: Int64 = 1_000,+ source: String = "egan", target: String = "owen", status: String = "queued",+ request: String = "Check this", reply: String? = nil, detail: String? = nil,+ intent: String = "message") -> Entry {+ let outgoing = chat == source+ let verb = switch intent {+ case "ask": outgoing ? "Asked Owen" : "Request from Egan"+ default: outgoing ? "Messaged Owen" : "Message from Egan"+ }+ let heading = "\(verb): \(request)"+ var outcome = detail ?? ""+ if let reply { outcome = "Reply from Owen:\n\(reply)" }+ var data = EntryData(text: "\(heading)\n\(outcome)", status: status)+ data.heading = heading+ data.delegationId = id+ data.sourceBotId = source+ data.targetBotId = target+ data.botMessage = BotMessage(sourceBotId: source, targetBotId: target, text: request, reply: reply, detail: detail)+ return Entry(id: id, seq: seq, botId: chat, rev: rev, kind: "notice", turn: 1, data: data, createdAt: at, updatedAt: at)+}++@Test func noticeDecodesTheHostContract() throws {+ let json = #"""+ {"id":"n1","seq":3,"botId":"egan","rev":9,"kind":"notice","turn":1,"createdAt":5,"updatedAt":6,+ "data":{"text":"Asked Owen: Review\nReply from Owen:\nLGTM","heading":"Asked Owen: Review","style":"info",+ "status":"completed","delegationId":"d1","sourceBotId":"egan","targetBotId":"owen","botMessage":{"sourceBotId":"egan","targetBotId":"owen","text":"Review","reply":"LGTM"}}}+ """#+ let entry = try JSONDecoder().decode(Entry.self, from: Data(json.utf8))+ let x = try #require(BotExchange(entry))+ #expect(x.text == "Review" && x.reply == "LGTM" && x.outcome == .done)+}++@Test func structuredRequestIsIndependentOfDisplayedVerb() throws {+ for (intent, chat) in [("ask", "egan"), ("ask", "owen"), ("message", "egan"), ("message", "owen")] {+ let x = try #require(BotExchange(notice("a", chat: chat, request: "Do it", intent: intent)))+ #expect(x.text == "Do it")+ }+}++@Test func requestKeepsColonsAndNewlinesAndNamesMaySpace() throws {+ var e = notice("a", request: "Plan: step 1\nstep 2: go", intent: "ask")+ e.data.heading = "Asked Owen the Bot: Plan: step 1\nstep 2: go"+ e.data.text = "\(e.data.heading!)\n"+ #expect(BotExchange(e)?.text == "Plan: step 1\nstep 2: go")+ let multi = try #require(BotExchange(notice("b", request: "Plan: a\nb: c", intent: "ask")))+ #expect(multi.text == "Plan: a\nb: c")+}++@Test func completedAskExtractsAMultiLineReply() throws {+ let x = try #require(BotExchange(notice("a", status: "completed", reply: "Line 1\nLine 2: ok", intent: "ask")))+ #expect(x.reply == "Line 1\nLine 2: ok" && x.outcome == .done)+}++@Test func completedMessageHasNoReply() throws {+ var e = notice("a", status: "completed", intent: "message")+ e.data.text = "\(e.data.heading!)\nCompleted."+ let x = try #require(BotExchange(e))+ #expect(x.reply == nil && x.outcome == .done)+}++@Test func failedAndCancelledCarryTheDetail() {+ #expect(BotExchange(notice("a", status: "failed", detail: "boom"))?.outcome == .failed("boom"))+ #expect(BotExchange(notice("a", status: "cancelled", detail: "Cancelled by user."))?.outcome == .failed("Cancelled by user."))+}++@Test func queuedAndSentArePending() {+ #expect(BotExchange(notice("a", status: "queued"))?.outcome == .pending)+ #expect(BotExchange(notice("a", status: "sent"))?.outcome == .pending)+}++@Test func structuredRequestDoesNotDependOnNoticeHeading() throws {+ var e = notice("a")+ e.data.heading = "Something else: odd"+ e.data.text = "Something else: odd\n"+ #expect(try #require(BotExchange(e)).text == "Check this")+}++@Test func existingNoticeWithoutStructuredDataStaysPlain() {+ var e = notice("a")+ e.data.botMessage = nil+ #expect(BotExchange(e) == nil)+}++@Test func directionAndVerbFollowTheChat() throws {+ let sender = try #require(BotExchange(notice("a", chat: "egan")))+ #expect(sender.isOutgoing && sender.verb == "Messaged" && sender.peerId == "owen")+ let recipient = try #require(BotExchange(notice("a", chat: "owen")))+ #expect(!recipient.isOutgoing && recipient.verb == "Message from" && recipient.peerId == "egan")+}++@Test func outcomeFollowsTheStatus() throws {+ #expect(BotExchange(notice("a", status: "sent"))?.outcome == .pending)+ #expect(BotExchange(notice("a", status: "completed"))?.outcome == .done)+ #expect(BotExchange(notice("a", status: "cancelled"))?.outcome == .failed(""))+}++@Test func onlyNoticesWithStructuredDataAreExchanges() {+ var plain = notice("a")+ plain.data.botMessage = nil+ #expect(BotExchange(plain) == nil)+ var agent = notice("b")+ agent.kind = "agent"+ #expect(BotExchange(agent) == nil)+}++@Test func mergeKeepsTheHigherRevAndFiltersThePeer() {+ let fetched = [notice("a", seq: 1, rev: 1), notice("b", seq: 2, rev: 5, status: "completed"),+ notice("c", seq: 3, target: "dex")]+ let live = [notice("b", seq: 2, rev: 3, status: "queued"), notice("d", seq: 4, rev: 2)]+ let merged = BotExchange.conversation(fetched: fetched, live: live, peer: "owen")+ #expect(merged.map(\.id) == ["a", "b", "d"])+ #expect(merged[1].outcome == .done)+}++@Test func rowsGroupAuthorsAndSeparateTimeBlocks() {+ let xs = [+ notice("a", seq: 1, at: 1_000, status: "completed", reply: "Done", intent: "ask"),+ notice("b", seq: 2, at: 2_000, status: "completed"),+ notice("c", seq: 3, at: 2_000 + 3_600_001, status: "queued"),+ ].compactMap(BotExchange.init)+ let rows = BotConversationRow.build(xs)+ #expect(rows.map(\.id) == ["sep-a", "a-request", "a-reply", "b-request", "sep-c", "c-request", "c-status"])+ #expect(rows[1] == .message(id: "a-request", author: "egan", text: "Check this", showsAuthor: true))+ #expect(rows[2] == .message(id: "a-reply", author: "owen", text: "Done", showsAuthor: true))+ #expect(rows[3] == .message(id: "b-request", author: "egan", text: "Check this", showsAuthor: true))+ #expect(rows[5] == .message(id: "c-request", author: "egan", text: "Check this", showsAuthor: true))+ #expect(rows[6] == .status(id: "c-status", outcome: .pending, awaiting: "owen"))+}++@Test func consecutiveRequestsFromOneBotShareAnAuthor() {+ let xs = [notice("a", seq: 1, status: "completed"), notice("b", seq: 2, at: 1_500, status: "completed")].compactMap(BotExchange.init)+ let rows = BotConversationRow.build(xs)+ #expect(rows[2] == .message(id: "b-request", author: "egan", text: "Check this", showsAuthor: false))+}++@Test func failedExchangeAddsACaptionAndResetsTheAuthor() {+ let xs = [notice("a", seq: 1, status: "failed", detail: "Recipient stopped."),+ notice("b", seq: 2, at: 1_500, status: "completed")].compactMap(BotExchange.init)+ let rows = BotConversationRow.build(xs)+ #expect(rows[2] == .status(id: "a-status", outcome: .failed("Recipient stopped."), awaiting: "owen"))+ #expect(rows[3] == .message(id: "b-request", author: "egan", text: "Check this", showsAuthor: true))+}++private func items(_ entries: [Entry]) -> [BotExchangeGroup.Item] { BotExchangeGroup.collapse(entries) }++private func plain(_ id: String, kind: String = "user", seq: Int64) -> Entry {+ Entry(id: id, seq: seq, botId: "egan", rev: 1, kind: kind, turn: 1, data: EntryData(text: "hi"), createdAt: 1_000, updatedAt: 1_000)+}++@Test func sameRunWithOnePeerFormsOneGroupAtItsFirstExchange() {+ let out = items([notice("a", seq: 1), notice("b", seq: 2, status: "completed"), notice("c", seq: 3)])+ #expect(out.count == 1)+ guard case .exchanges(let g) = out[0] else { Issue.record("not a group"); return }+ #expect(g.id == "a" && g.count == 3 && g.peerId == "owen" && g.title == "3 messages with")+ #expect(g.accessibilityLabel(peerName: "Owen") == "3 messages with Owen")+}++@Test func aSingleExchangeKeepsTheVerb() {+ guard case .exchanges(let g) = items([notice("a")])[0] else { Issue.record("not a group"); return }+ #expect(g.count == 1 && g.title == "Messaged")+}++@Test func aDifferentPeerSplitsTheRun() {+ let out = items([notice("a", seq: 1), notice("b", seq: 2, target: "dex"), notice("c", seq: 3, target: "dex")])+ #expect(out.map(\.id) == ["a", "b"])+}++@Test func aVisibleEntryBetweenExchangesSplitsTheRun() {+ let out = items([notice("a", seq: 1), plain("u", seq: 2), notice("b", seq: 3)])+ #expect(out.map(\.id) == ["a", "u", "b"])+ var routine = notice("r", seq: 2)+ routine.data.botMessage = nil+ #expect(items([notice("a", seq: 1), routine, notice("b", seq: 3)]).count == 3)+}++@Test func traceEntriesDoNotSplitTheRun() {+ let out = items([notice("a", seq: 1), plain("t", kind: "tool", seq: 2), plain("n", kind: "agent", seq: 3), notice("b", seq: 4)])+ #expect(out.map(\.id) == ["a"])+ guard case .exchanges(let g) = out[0] else { Issue.record("not a group"); return }+ #expect(g.count == 2)+}++@Test func directionsMixInOneGroup() {+ let out = items([notice("a", seq: 1, source: "egan", target: "owen"), notice("b", seq: 2, source: "owen", target: "egan")])+ guard case .exchanges(let g) = out[0] else { Issue.record("not a group"); return }+ #expect(out.count == 1 && g.count == 2 && g.peerId == "owen")+}++@Test func anyFailureMarksTheGroup() {+ let ok = items([notice("a", seq: 1, status: "completed"), notice("b", seq: 2, status: "completed")])+ let bad = items([notice("a", seq: 1, status: "completed"), notice("b", seq: 2, status: "failed")])+ guard case .exchanges(let good) = ok[0], case .exchanges(let failed) = bad[0] else { Issue.record("not groups"); return }+ #expect(!good.failed && failed.failed)+ #expect(failed.accessibilityLabel(peerName: "Owen") == "2 messages with Owen, failed")+}diff --git a/apps/ios/Kit/Tests/CodyncUITests/HistoryPagingTests.swift b/apps/ios/Kit/Tests/CodyncUITests/HistoryPagingTests.swiftnew file mode 100644index 00000000..8d45b084--- /dev/null+++ b/apps/ios/Kit/Tests/CodyncUITests/HistoryPagingTests.swift@@ -0,0 +1,37 @@+import Foundation+import Testing+@testable import CodyncKit+@testable import CodyncUI++@MainActor @Test func threadHeavyCatchUpKeepsEarlierMainChatAvailable() {+ let suite = "HistoryPagingTests.\(UUID().uuidString)"+ let storage = SharedStore.Context(accountID: UUID().uuidString, suite: suite)+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let computer = Computer(id: "history", name: "Test", signKey: "")+ let store = BotStore(computer: computer, clientKind: "ios", storage: storage) { throw HostError.unreachable }+ defer { store.retire() }+ store.entries["b"] = (0..<200).map { index in+ Entry(id: "e\(index)", seq: Int64(index + 100), botId: "b", threadId: index < 6 ? nil : "root",+ rev: 1, kind: "notice", turn: 0, data: EntryData(), createdAt: 1, updatedAt: 1)+ }+ #expect(store.chat("b").count == 6)+ #expect(store.canLoadOlder("b"))+ store.entries["b"]?.removeAll { $0.threadId == nil }+ #expect(store.chat("b").isEmpty)+ #expect(store.canLoadOlder("b"))+ store.historyComplete.insert("b")+ #expect(!store.canLoadOlder("b"))+}++@MainActor @Test func emptyChatsAndUnsentMessagesDoNotOfferServerHistory() {+ let suite = "HistoryPagingTests.\(UUID().uuidString)"+ let storage = SharedStore.Context(accountID: UUID().uuidString, suite: suite)+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let computer = Computer(id: "history", name: "Test", signKey: "")+ let store = BotStore(computer: computer, clientKind: "ios", storage: storage) { throw HostError.unreachable }+ defer { store.retire() }+ #expect(!store.canLoadOlder("b"))+ store.entries["b"] = [Entry(id: "local-draft", seq: Int64.max, botId: "b", rev: 1, kind: "user", turn: 0,+ data: EntryData(), createdAt: 1, updatedAt: 1)]+ #expect(!store.canLoadOlder("b"))+}diff --git a/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift b/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swiftindex d5c49bad..87917e9c 100644--- a/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift+++ b/apps/ios/Kit/Tests/CodyncUITests/StoreTests.swift@@ -741,3 +741,94 @@ private func helloJSON(version: String, minApp: String? = nil, backends: Stringlet anotherAccount = SharedStore.Context(accountID: "another-user", suite: suite)#expect(anotherAccount.composerDrafts.isEmpty)}++@MainActor @Test func existingCachesKeepTheirMessagesAndLocalSends() throws {+ let (storage, suite) = context()+ defer { storage.erase(); UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let computer = randomComputer("Fixture")+ let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "0"+ let url = URL.cachesDirectory.appending(path: "codync-mirror-\(Bundle.main.bundleIdentifier ?? "app")-\(storage.id)-\(computer.id).json")+ let cached = #"""+ {"stamp":"\#(build)/3.0.0","hostId":"h1","rev":77,"bots":[],"entries":[+ {"id":"notice","seq":1,"botId":"dex","rev":77,"kind":"notice","turn":1,"createdAt":1,"updatedAt":1,+ "data":{"text":"Message from Miles","status":"completed"}},+ {"id":"local-pending","seq":2,"botId":"dex","rev":0,"kind":"user","turn":1,"createdAt":2,"updatedAt":2,+ "data":{"text":"My unsent message","status":"failed"}}+ ]}+ """#+ try Data(cached.utf8).write(to: url)+ let store = BotStore(computer: computer, clientKind: "ios", storage: storage) { FakeRemote(.ready(.direct)) }+ defer { store.retire() }+ // Adding conversation metadata does not invalidate the existing base cache.+ #expect(store.allEntries("dex").map(\.id) == ["notice", "local-pending"])+ #expect(store.allEntries("dex").last?.data.text == "My unsent message")+ store.saveCache()+ let bytes = try Data(contentsOf: url)+ let cache = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any])+ #expect(cache["rev"] as? Int == 77)+}++private func entryEvent(_ id: String, seq: Int, rev: Int, turn: Int = 5, text: String = "hi") -> String {+ #"{"type":"entry","entry":{"id":"\#(id)","seq":\#(seq),"botId":"b1","rev":\#(rev),"kind":"agent","turn":\#(turn),"data":{"text":"\#(text)","final":true},"createdAt":1,"updatedAt":1}}"#+}++private func windowEntry(_ id: String, seq: Int64, rev: Int64 = 1, threadId: String? = nil) -> Entry {+ var data = EntryData(text: id)+ data.final = true+ return Entry(id: id, seq: seq, botId: "b1", threadId: threadId, rev: rev, kind: "agent", turn: 0, data: data, createdAt: 1, updatedAt: 1)+}++@MainActor @Test func windowRuleDropsOnlyUnknownMainChatEntriesBelowTheFloor() {+ let below = windowEntry("a", seq: 5)+ #expect(BotStore.isOutsideLoadedWindow(below, floor: 100, held: false))+ #expect(!BotStore.isOutsideLoadedWindow(below, floor: 100, held: true))+ #expect(!BotStore.isOutsideLoadedWindow(windowEntry("a", seq: 100), floor: 100, held: false))+ #expect(!BotStore.isOutsideLoadedWindow(windowEntry("a", seq: 150), floor: 100, held: false))+ #expect(!BotStore.isOutsideLoadedWindow(below, floor: nil, held: false))+ #expect(!BotStore.isOutsideLoadedWindow(windowEntry("a", seq: 5, threadId: "t"), floor: 100, held: false))+}++/// A connection that resumes from a rev > 0 leaves a rewritten old entry to history paging.+@MainActor @Test func resumedConnectionDropsRewrittenEntriesBelowTheMirrorsFloor() async throws {+ let (storage, suite) = context()+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let fake = FakeRemote(.ready(.direct))+ let store = BotStore(computer: randomComputer("Mac"), clientKind: "ios", storage: storage) { fake }+ defer { store.retire() }+ store.upsert(windowEntry("e100", seq: 100))+ store.upsert(windowEntry("local-1", seq: 0)) // optimistic: not a floor+ store.rev = 10+ store.setActive(true)+ #expect(await until { await fake.subscribed })+ await fake.emit(#"{"type":"hello","hostId":"h1","rev":20}"#)+ await fake.emit(botEvent("b1", name: "Bot", rev: 11))+ // Rewritten old entry: dropped, though its rev is consumed.+ await fake.emit(entryEvent("old", seq: 5, rev: 12, turn: 0))+ // New entry above the floor and an update to a held one apply.+ await fake.emit(entryEvent("e101", seq: 101, rev: 13))+ await fake.emit(entryEvent("e100", seq: 100, rev: 14, text: "edited"))+ #expect(await until { store.chat("b1").first { $0.id == "e100" }?.data.text == "edited" && store.chat("b1").contains { $0.id == "e101" } })+ #expect(!store.chat("b1").contains { $0.id == "old" })+ #expect(store.rev == 14)+ // History results still insert older entries.+ store.upsert(windowEntry("old", seq: 5))+ #expect(store.chat("b1").contains { $0.id == "old" })+}++/// From rev 0 the catch-up is rev-ordered, not seq-ordered, and a sent message's RPC response may+/// land first: nothing is below a floor.+@MainActor @Test func freshCatchUpAcceptsEntriesInRevOrder() async throws {+ let (storage, suite) = context()+ defer { UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) }+ let fake = FakeRemote(.ready(.direct))+ let store = BotStore(computer: randomComputer("Mac"), clientKind: "ios", storage: storage) { fake }+ defer { store.retire() }+ store.upsert(windowEntry("sent", seq: 100)) // RPC response before the catch-up+ store.setActive(true)+ #expect(await until { await fake.subscribed })+ await fake.emit(#"{"type":"hello","hostId":"h1","rev":20}"#)+ await fake.emit(botEvent("b1", name: "Bot", rev: 1))+ await fake.emit(entryEvent("e50", seq: 50, rev: 2, turn: 0))+ await fake.emit(entryEvent("e5", seq: 5, rev: 3, turn: 0))+ #expect(await until { store.chat("b1").map(\.id) == ["e5", "e50", "sent"] })+}diff --git a/docs/architecture/desktop-app.md b/docs/architecture/desktop-app.mdindex fb7fe072..d3427a5e 100644--- a/docs/architecture/desktop-app.md+++ b/docs/architecture/desktop-app.md@@ -4,6 +4,11 @@ Codync's computer-side app is one Electron app in `apps/desktop/` for macOS, Linreplaced the SwiftUI Mac app (`apps/macos/`) and the GTK 4 Linux app (`apps/linux/`) in 2.7.0.The iPhone app stays native SwiftUI; its package moved from `kit/` into `apps/ios/Kit/`.+Conversation history stays available even when the recent snapshot contains mostly thread+replies. The desktop, iPhone and terminal clients page the main conversation independently+of the number of main-chat entries in that snapshot; reaching the end of a history response+determines when there are no earlier messages.+## Why- **The chat was too slow.** Long transcripts with Markdown, variable-height rows anddiff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.mdindex bd07ca97..15a168c6 100644--- a/docs/design/ui-conventions.md+++ b/docs/design/ui-conventions.md@@ -114,6 +114,22 @@ carries its behavior; the October 2026 parity changes brought the TUI up to it.and pressing Enter opens that request. Credentials, connector installation/sign-inand hosted apps use the secure setup APIs. Ctrl+X cancels the request; Escape closesthe editor without cancelling. Secrets are masked and never sent as chat text.+- A bot-to-bot exchange is a compact centered row ("Messaged [avatar] Owen" / "Message from+ [avatar] Egan"; same verbs for asks; the TUI draws one ` · ` line), never a bubble. Only a+ failure is marked: danger color, a warning mark (triangle icon; Android and TUI use a+ glyph), "failed" in the accessibility label. The row+ opens a read-only "A ⇄ B" sheet. In the main chat consecutive exchanges with the same peer+ (either direction; trace entries don't break the run, any other visible entry does) are one+ row, "{N} messages with [avatar] Owen", failed if any failed, keyed by the first exchange+ (TUI: one pick, `c` on it says it is read-only). The sheet matches "Full conversation" (same size;+ `ModalHeader` with the pair, own bot first, as its left title and the close X on the right):+ the pair's whole history as author-labelled grey bubbles (avatar and name above each run),+ time separators after gaps over an hour, "Waiting for {name}…" or the failure detail under+ a pending or failed exchange, no composer. TUI:+ `v`/`r` picks a message, j/k moves to the row, ↵ (or a click) opens it, j/k ↑↓ and+ ^u/^d scroll, esc closes; `r`, `f` and `1…6` on the row say it is read-only. The+ watch shows the row only, not tappable. The data contract is+ [bot collaboration](../features/bot-collaboration.md#notice-data).- TUI bot settings include **Use computer**, matching the iPhone and desktop apps. Theremote-screen viewer and voice-call UI are not in the TUI.diff --git a/docs/features/bot-collaboration.md b/docs/features/bot-collaboration.mdindex 738eac4e..b9bee273 100644--- a/docs/features/bot-collaboration.md+++ b/docs/features/bot-collaboration.md@@ -6,7 +6,42 @@ Create two or more bots normally, giving each a clear name, description, projectEvery bot receives the built-in `team` MCP server. `list_bots` returns the other visible bots' IDs, descriptions, agents, folders and status. `ask_bot(botId, message)` sends a self-contained request and waits for the recipient's final text reply. The requesting bot incorporates that answer into its response to you. `message_bot(botId, message)` queues a request and returns immediately; the recipient reports to you in its own chat. The same tools work across ACP backends that support MCP servers.-The host records the request and its outcome in both chats using existing notice entries, so the current iOS, desktop and terminal clients can display them. Tool details also remain in the trace. There is no additional team setup screen.+The host records each exchange as one notice in both chats. Every client shows it as a compact row (centered in the apps, one ` · ` line in the terminal UI), "Messaged [avatar] Owen" in the sender's chat and "Message from [avatar] Egan" in the recipient's, with no request text. In the main chat (never threads) a run of consecutive exchanges with the same peer, in either direction, is one row, "3 messages with [avatar] Owen"; anything else the chat shows (a message, another notice, a card, an exchange with another peer) ends the run, trace entries do not, and the run is marked failed if any exchange failed. Only a failure is marked (danger color and a warning mark). Tapping the row opens a read-only "Egan ⇄ Owen" conversation sheet with the pair's whole history: author-labelled grey bubbles for each request and reply, time separators, "Waiting for Owen…" or the failure detail under a pending or failed exchange. It is laid out like the Full conversation sheet, with the pair as its title and an X to close. Tool details also remain in the trace. There is no additional team setup screen.++## Notice data++New bot-to-bot notices retain all fields written by the team tools in the base:+`text`, `heading`, `style`, `status`, `delegationId`, `sourceBotId` and `targetBotId`.+They add one optional structured field:++```json+{+ "botMessage": {+ "sourceBotId": "egan",+ "targetBotId": "owen",+ "text": "Review this change",+ "reply": "Looks good",+ "detail": "Failure or cancellation detail, when applicable"+ }+}+```++`text` is the original request. Completed asks add `reply` (at most 4,000 bytes);+failures and cancellations add `detail`. The existing notice `status` determines+whether the exchange is pending, completed, failed or cancelled. The base notice+heading and rendered text remain unchanged for clients that display plain notices.+Clients read the structured data directly; they do not parse display strings.++Existing notices remain ordinary notices. There is no startup rewrite, data+migration or transcript-cache reset. The existing restart cleanup still marks+unfinished requests failed and adds the failure detail to their structured data,+when present. It never replays work.++`botConversation {botId, peerId}` returns `{entries}`: the newest 200 main-chat+notices containing structured messages with that peer, oldest first. It requires+the Control scope. Clients merge these with the live chat (the higher `rev` wins)+and keep the result in the sheet; it is never added to the chat mirror, so main+history paging is unaffected.## Ask execution@@ -24,7 +59,7 @@ The host records the request and its outcome in both chats using existing notice- Pending request notices are persisted with IDs and statuses. After host restart they become interrupted errors; delegated turns are not automatically replayed. Check partial work before retrying. Ordinary user turns retain their existing session-resume behavior.- Completion push notifications come from the requesting bot; delegated replies do not send a second “done” push. Recipient permission requests still use the usual “needs you” notifications.-`ask_bot` uses synchronous request/reply over MCP; neither tool adds a task scheduler or isolated worktrees. Give bots explicit file ownership when they share a working directory. Rebuild and restart the host to load the new built-in MCP server; phone clients need no protocol upgrade.+`ask_bot` uses synchronous request/reply over MCP; neither tool adds a task scheduler or isolated worktrees. Give bots explicit file ownership when they share a working directory. Rebuild and restart the host to load the new built-in MCP server.## Independent messages@@ -40,7 +75,9 @@ an error without queuing more work. A new user turn starts a fresh allowance.## Code and verification-- `host/src/chat/team.rs`: discovery, request lifetime and persisted notices.+- `host/src/chat/team.rs`: discovery, request lifetime and persisted notices and structured conversation data.+- `host/src/store/entries.rs` (`bot_conversation`, `expire_pending`) and `host/src/api/bots.rs` (`botConversation`): the pair history and restart cleanup.+- `host/src/tui/app/exchange.rs`, `manage/bot_chat.rs`, `view/bot_chat.rs`: the terminal client's row logic, keys and conversation sheet.- `host/src/chat/team/requests.rs`: admission, wait graph, capacity and chain hop limit.- `host/src/agent/bot/` (`queue.rs`, `turn.rs`): queue boundaries, recipient execution, completion and targeted cancellation.- `host/src/mcp.rs`: the authenticated local MCP → HTTP bridge.diff --git a/docs/features/chat-messages.md b/docs/features/chat-messages.mdindex f39f445a..f3b0c7c2 100644--- a/docs/features/chat-messages.md+++ b/docs/features/chat-messages.md@@ -15,6 +15,10 @@ How a bot's work turns into what the user reads, copied from Grok Bot.turn's last text, as before (`chat/group.rs`, `chat/team.rs`, `routines`).- The rules reach the agent twice: the MCP server's instructions, and the frozen instructionsnapshot (`chat/context.rs`).+- A bot-to-bot exchange (`ask_bot`, `message_bot`) is one compact notice row, "Messaged Owen" /+ "Message from Egan". Its text lives only in the bot conversation sheet it opens; follow-ups+ are normal bubbles. Consecutive exchanges with the same peer in the main chat (either+ direction, trace entries ignored) collapse into one "3 messages with Owen" row ([bot collaboration](bot-collaboration.md#notice-data)).- Clients never stream text into a bubble: the chat shows user messages, `final` agent entries,permission cards and notices (`isChat`). Nothing pops in and out while a turn runs.diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rsindex 3735ebc3..66f81cce 100644--- a/host/src/agent/bot/turn.rs+++ b/host/src/agent/bot/turn.rs@@ -6,7 +6,7 @@ use crate::chat::context::{self, Snapshot};use crate::chat::memory;use crate::hub::BotStatus;use crate::remote::push::{self, AlertKind};-use crate::store::{Lane, now_ms};+use crate::store::{EntryKind, Lane, now_ms};use anyhow::{Context, Result, anyhow};use serde_json::json;use std::time::Duration;@@ -36,8 +36,9 @@ impl Actor {|e| e.turn,);for id in entry_ids {- if let Some(mut e) = self.hub.store.entry(id) {- e.data["status"] = json!(crate::chat::team::RequestStatus::Sent);+ // Bot-message notices belong to `chat::team`; writing them here would race its final status.+ if let Some(mut e) = self.hub.store.entry(id).filter(|e| e.kind == EntryKind::User.as_str()) {+ e.data["status"] = "sent".into();self.hub.set_entry(id, &e.data);}}diff --git a/host/src/api/bots.rs b/host/src/api/bots.rsindex 169ab3ff..edf4e78f 100644--- a/host/src/api/bots.rs+++ b/host/src/api/bots.rs@@ -55,6 +55,10 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Contr}// 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)?}),+ // Notices between a bot and one peer (the newest 200), for the read-only bot conversation sheet.+ "botConversation" => {+ json!({"entries": hub.store.bot_conversation(str_arg(&b, "botId")?, str_arg(&b, "peerId")?, 200)?})+ }"createBot" => {let mut b = b;b["id"] = "".into();diff --git a/host/src/chat/team.rs b/host/src/chat/team.rsindex fd550f4d..9939c170 100644--- a/host/src/chat/team.rs+++ b/host/src/chat/team.rs@@ -144,15 +144,23 @@ struct Pending {}impl Pending {- fn finish(&mut self, status: RequestStatus, detail: &str) {- finish_notices(&self.hub, &self.entries, status, detail);+ fn finish(&mut self, status: RequestStatus, detail: &str, reply: Option<&str>) {+ finish_notices(&self.hub, &self.entries, status, detail, reply);self.finished = true;}}-fn finish_notices(hub: &Hub, entries: &[String], status: RequestStatus, detail: &str) {+fn finish_notices(hub: &Hub, entries: &[String], status: RequestStatus, detail: &str, reply: Option<&str>) {for id in entries {if let Some(mut e) = hub.store.entry(id) {+ if let Some(message) = e.data.get_mut("botMessage").and_then(Value::as_object_mut) {+ if let Some(reply) = reply {+ message.insert("reply".into(), reply.into());+ }+ if matches!(status, RequestStatus::Failed | RequestStatus::Cancelled) {+ message.insert("detail".into(), detail.into());+ }+ }e.data["status"] = json!(status);let heading = e.data["heading"].as_str().unwrap_or("Bot request");e.data["text"] = format!("{heading}\n{detail}").into();@@ -177,7 +185,7 @@ struct MessageLifetime {impl MessageLifetime {fn finish(&mut self, status: RequestStatus, detail: &str) {- finish_notices(&self.hub, &self.entries, status, detail);+ finish_notices(&self.hub, &self.entries, status, detail, None);self.finished = true;}}@@ -199,7 +207,7 @@ impl Drop for MessageLifetime {impl Drop for Pending {fn drop(&mut self) {if !self.finished {- self.finish(RequestStatus::Cancelled, "Request cancelled. Partial work may have happened.");+ self.finish(RequestStatus::Cancelled, "Request cancelled. Partial work may have happened.", None);}self.hub.team.0.locked().pending.remove(&self.id);// Targeted cancellation never clears unrelated user messages or turns.@@ -279,6 +287,7 @@ fn message_bot(hub: &Arc<Hub>, source: &BotConfig, to: &str, message: &str) -> R"text": format!("{heading}\nQueued. Outcome will appear in {}'s chat.", target.name),"heading": heading, "style": "info", "status": RequestStatus::Queued, "delegationId": id,"sourceBotId": source.id, "targetBotId": target.id,+ "botMessage": {"sourceBotId": source.id, "targetBotId": target.id, "text": message},}),).ok_or_else(|| anyhow!("couldn't save bot message"))?;@@ -321,6 +330,7 @@ async fn ask(hub: &Arc<Hub>, source: &BotConfig, to: &str, message: &str, timeou"text": format!("{heading}\nWaiting for a reply…"), "heading": heading,"style": "info", "status": RequestStatus::Queued, "delegationId": id,"sourceBotId": source.id, "targetBotId": target.id,+ "botMessage": {"sourceBotId": source.id, "targetBotId": target.id, "text": message},}),).ok_or_else(|| anyhow!("couldn't save bot request"))?;@@ -340,14 +350,12 @@ async fn ask(hub: &Arc<Hub>, source: &BotConfig, to: &str, message: &str, timeou};match result {Ok(text) => {- pending.finish(- RequestStatus::Completed,- &format!("Reply from {}:\n{}", target.name, crate::agent::acp::truncate(&text, 4000)),- );+ let reply = crate::agent::acp::truncate(&text, 4000);+ pending.finish(RequestStatus::Completed, &format!("Reply from {}:\n{reply}", target.name), Some(&reply));Ok(json!({"requestId": id, "botId": target.id, "name": target.name, "reply": text}))}Err(error) => {- pending.finish(RequestStatus::Failed, &format!("{error:#}"));+ pending.finish(RequestStatus::Failed, &format!("{error:#}"), None);Err(error)}}diff --git a/host/src/chat/team/tests.rs b/host/src/chat/team/tests.rsindex 5ad57448..a150de6f 100644--- a/host/src/chat/team/tests.rs+++ b/host/src/chat/team/tests.rs@@ -150,6 +150,29 @@ async fn delegation_roundtrip_keeps_queued_user_messages_separate() {assert_eq!(f.prompts()[1], "thanks");assert_eq!(f.hub.store.entry(sent["entry"]["id"].as_str().unwrap()).unwrap().data["status"], "sent");assert_eq!(f.hub.store.entry(&request_entry.id).unwrap().data["status"], "completed");+ for entry in f.notices(&result) {+ assert_eq!(entry.data["botMessage"]["text"], "BLOCK review these changes");+ assert_eq!(entry.data["botMessage"]["reply"], "reply: BLOCK review these changes");+ // Existing clients still receive the base notice display fields.+ let heading = entry.data["heading"].as_str().unwrap();+ assert_eq!(entry.data["text"], format!("{heading}\nReply from b:\nreply: BLOCK review these changes"));+ }+ let conversation = |peer: &str| {+ let hub = f.hub.clone();+ let peer = peer.to_owned();+ async move {+ crate::api::dispatch(+ &hub,+ &crate::api::devices::Caller::Local,+ "botConversation",+ json!({"botId": "a", "peerId": peer}),+ )+ .await+ .unwrap()+ }+ };+ assert_eq!(conversation("b").await["entries"].as_array().unwrap().len(), 1);+ assert_eq!(conversation("c").await["entries"].as_array().unwrap().len(), 0);assert!(f.hub.team.0.locked().pending.is_empty());let servers: Value = serde_json::from_slice(&std::fs::read(f.dir.join("b/servers.json")).unwrap()).unwrap();assert!(servers.as_array().unwrap().iter().any(|s| s["name"] == "team"));@@ -296,6 +319,9 @@ async fn message_returns_before_approval_and_survives_sender_stop() {assert_eq!(entry.data["sourceBotId"], "a");assert_eq!(entry.data["targetBotId"], "b");assert_eq!(entry.data["status"], "sent");+ assert_eq!(entry.data["botMessage"]["sourceBotId"], "a");+ assert_eq!(entry.data["botMessage"]["targetBotId"], "b");+ assert!(entry.data["botMessage"]["text"].is_string());}assert!(notices.iter().any(|e| e.data["heading"].as_str().unwrap().starts_with("Messaged b:")));assert!(notices.iter().any(|e| e.data["heading"].as_str().unwrap().starts_with("Message from a:")));@@ -575,6 +601,7 @@ fn restart_marks_requests_interrupted_without_replaying_them() {1,&json!({"delegationId": "d", "status": "sent", "heading": "Request from a",+ "botMessage": {"sourceBotId": "a", "targetBotId": "b", "text": "Work"},}),).unwrap();@@ -594,4 +621,6 @@ fn restart_marks_requests_interrupted_without_replaying_them() {assert!(interrupted.data["text"].as_str().unwrap().contains("Interrupted by host restart"));assert_eq!(store.entry(&complete.id).unwrap().data["status"], "completed");assert!(interrupted.rev > pending.rev);+ assert_eq!(interrupted.data["botMessage"]["text"], "Work");+ assert!(interrupted.data["botMessage"]["detail"].as_str().unwrap().contains("Interrupted by host restart"));}diff --git a/host/src/store/entries.rs b/host/src/store/entries.rsindex 9b94aa54..cbd8b42b 100644--- a/host/src/store/entries.rs+++ b/host/src/store/entries.rs@@ -163,6 +163,21 @@ impl Store {Ok(rows)}+ /// The newest `limit` bot-to-bot notices in `bot_id`'s main chat that involve `peer_id`, oldest first.+ pub fn bot_conversation(&self, bot_id: &str, peer_id: &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 IS NULL AND kind = 'notice'+ AND json_type(data, '$.botMessage') = 'object'+ AND ?2 IN (json_extract(data, '$.botMessage.sourceBotId'), json_extract(data, '$.botMessage.targetBotId'))+ ORDER BY seq DESC LIMIT ?3"+ ))?;+ let mut rows: Vec<Entry> =+ st.query_map(params![bot_id, peer_id, 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();@@ -237,6 +252,13 @@ impl Store {"{heading}\nInterrupted by host restart. Partial work may have happened; check before retrying.").into();+ if let Some(message) = e.data.get_mut("botMessage").and_then(Value::as_object_mut) {+ message.insert(+ "detail".into(),+ "Interrupted by host restart. Partial work may have happened; check before retrying."+ .into(),+ );+ }e.data["style"] = "error".into();"failed"} else if e.kind == EntryKind::User.as_str() {@@ -291,4 +313,38 @@ mod tests {assert_eq!(s.entry(&q.id).unwrap().data["status"], "failed");assert_eq!(s.expire_pending().unwrap(), 0, "idempotent");}++ #[test]+ fn bot_conversation_lists_one_peers_notices_oldest_first() {+ let s = temp_store();+ let notice = |bot: &str, source: &str, target: &str, text: &str| {+ let data = json!({"text": text, "sourceBotId": source, "targetBotId": target,+ "botMessage": {"sourceBotId": source, "targetBotId": target, "text": text}});+ s.insert_entry(&Lane::main(bot), EntryKind::Notice, 1, &data).unwrap();+ };+ notice("a", "a", "b", "first");+ notice("a", "a", "c", "other peer");+ notice("a", "b", "a", "second");+ notice("b", "a", "b", "other chat");+ s.insert_entry(&Lane::main("a"), EntryKind::Notice, 1, &json!({"text": "plain"})).unwrap();+ let old = s+ .insert_entry(+ &Lane::main("a"),+ EntryKind::Notice,+ 1,+ &json!({"text": "Messaged b: old", "heading": "Messaged b: old", "delegationId": "old",+ "sourceBotId": "a", "targetBotId": "b", "status": "completed"}),+ )+ .unwrap();+ let old_data = old.data.clone();+ let texts: Vec<_> = s+ .bot_conversation("a", "b", 10)+ .unwrap()+ .into_iter()+ .map(|e| e.data["text"].as_str().unwrap().to_owned())+ .collect();+ assert_eq!(texts, ["first", "second"]);+ assert_eq!(s.entry(&old.id).unwrap().data, old_data, "existing notice is untouched");+ assert_eq!(s.bot_conversation("a", "b", 1).unwrap().len(), 1, "limit keeps the newest");+ }}diff --git a/host/src/tui/app/events.rs b/host/src/tui/app/events.rsindex cfba8297..7c7add57 100644--- a/host/src/tui/app/events.rs+++ b/host/src/tui/app/events.rs@@ -1,9 +1,18 @@//! Host messages: the event stream and command replies.+use std::collections::HashMap;+use serde_json::{Value, json};use super::{After, App, Bot, Dir, Entry, Focus, Msg, Overlay, Status, merge_toggles};+/// A main-chat entry the mirror doesn't hold, below the floor its bot's loaded chat had when this+/// connection began: `seq` grows with insertion, so it predates the window and only arrived because+/// its rev was bumped (a rewrite, a reaction). History paging brings it.+fn outside_window(floor: Option<i64>, held: bool, e: &Entry) -> bool {+ e.thread_id.is_none() && !held && floor.is_some_and(|f| e.seq < f)+}+impl App {pub fn on_msg(&mut self, m: Msg) {match m {@@ -23,11 +32,16 @@ impl App {self.bots.clear();self.entries.clear();self.history_done.clear();+ self.floors.clear();// Catch-up carries only recent thread replies: fetch the open thread whole again.if let (Some(id), Some(root)) = (&self.selected, &self.thread) {self.call("thread", json!({"botId": id, "rootId": root}), After::Thread);}}+ Msg::Connected { since } => {+ self.stream_since = since;+ self.floors.clear();+ }Msg::Event(v) => self.on_event(&v),Msg::Reply(after, r) => self.on_reply(after, r),Msg::Term(id, v) => self.on_term(&id, &v),@@ -36,11 +50,18 @@ impl App {fn on_event(&mut self, v: &Value) {match v["type"].as_str() {- Some("hello") if !v["usage"].is_null() => self.usage = v["usage"].clone(),+ Some("hello") => {+ self.snapshot_floors();+ if !v["usage"].is_null() {+ self.usage = v["usage"].clone();+ }+ }Some("usage") => self.usage = v["usage"].clone(),Some("bot") => self.upsert_bot(&v["bot"]),Some("entry") => {- if let Some((bot, e)) = Entry::parse(&v["entry"]) {+ if let Some((bot, e)) = Entry::parse(&v["entry"])+ && !self.outside_window(&bot, &e)+ {self.entries.entry(bot).or_default().insert(e.seq, e);}}@@ -48,11 +69,32 @@ impl App {}}+ /// A catch-up from `since > 0` starts: remember where each bot's loaded main chat begins.+ fn snapshot_floors(&mut self) {+ self.floors = if self.stream_since > 0 {+ self.entries+ .iter()+ .filter_map(|(bot, loaded)| {+ let oldest = loaded.values().filter(|e| e.thread_id.is_none() && e.seq > 0).map(|e| e.seq).min();+ Some((bot.clone(), oldest?))+ })+ .collect()+ } else {+ HashMap::new()+ };+ }++ fn outside_window(&self, bot: &str, e: &Entry) -> bool {+ let held = self.entries.get(bot).is_some_and(|m| m.contains_key(&e.seq));+ outside_window(self.floors.get(bot).copied(), held, e)+ }+fn upsert_bot(&mut self, v: &Value) {let Some(id) = v["id"].as_str() else { return };if v["deleted"].as_bool().unwrap_or(false) {self.bots.remove(id);self.entries.remove(id);+ self.floors.remove(id);let prefix = format!("{id}#");self.drafts.retain(|key, _| key != id && !key.starts_with(&prefix));self.files.retain(|key, _| key != id && !key.starts_with(&prefix));@@ -280,6 +322,84 @@ mod tests {use super::super::{Editor, FIELDS, Field, PendingSend, test_app};use super::*;+ fn entry_event(seq: i64, thread: &Value) -> Value {+ json!({"type": "entry", "entry": {"botId": "a", "id": format!("e{seq}"), "seq": seq, "turn": seq,+ "kind": "user", "threadId": thread}})+ }++ fn seqs(app: &App) -> Vec<i64> {+ app.entries.get("a").map(|m| m.keys().copied().collect()).unwrap_or_default()+ }++ #[tokio::test]+ async fn catch_up_with_only_replies_can_fetch_main_chat_history() {+ fn entry_event(seq: i64, thread: &Value) -> Value {+ json!({"type": "entry", "entry": {"botId": "a", "id": format!("e{seq}"), "seq": seq, "turn": seq,+ "kind": "user", "threadId": thread}})+ }+ let mut app = test_app();+ app.selected = Some("a".into());+ app.on_event(&entry_event(100, &json!("root")));+ assert!(!app.history_complete("a"));+ app.load_history();+ assert!(app.history_busy.contains("a"));+ app.on_reply(After::History("a".into()), Ok(json!({"entries": [entry_event(90, &Value::Null)["entry"]]})));+ assert_eq!(app.lane("a").iter().map(|e| e.seq).collect::<Vec<_>>(), [90]);+ app.on_reply(After::History("a".into()), Ok(json!({"entries": []})));+ assert!(app.history_complete("a"));+ }++ fn connect(app: &mut App, since: i64) {+ app.on_msg(Msg::Connected { since });+ app.on_event(&json!({"type": "hello"}));+ }++ #[test]+ fn rewritten_entry_below_the_floor_waits_for_paging() {+ let mut app = test_app();+ for seq in [5, 6] {+ app.on_event(&entry_event(seq, &Value::Null));+ }+ connect(&mut app, 40);+ app.on_event(&entry_event(2, &Value::Null));+ assert_eq!(seqs(&app), [5, 6], "below the floor: dropped");+ app.on_event(&entry_event(2, &json!("root")));+ assert_eq!(seqs(&app), [2, 5, 6], "thread replies are not paged");+ let mut update = entry_event(5, &Value::Null);+ update["entry"]["reactions"] = json!(["x"]);+ app.on_event(&update);+ app.on_event(&entry_event(7, &Value::Null));+ assert_eq!(seqs(&app), [2, 5, 6, 7], "held updates and newer entries apply");+ app.on_reply(After::History("a".into()), Ok(json!({"entries": [entry_event(3, &Value::Null)["entry"]]})));+ assert_eq!(seqs(&app), [2, 3, 5, 6, 7], "history inserts older entries");+ }++ #[test]+ fn a_full_catch_up_accepts_entries_in_rev_order() {+ let mut app = test_app();+ app.on_event(&entry_event(9, &Value::Null)); // a sent message's reply, before catch-up+ connect(&mut app, 0);+ for seq in [4, 2, 7] {+ app.on_event(&entry_event(seq, &Value::Null));+ }+ assert_eq!(seqs(&app), [2, 4, 7, 9]);+ connect(&mut app, 40);+ app.on_event(&entry_event(1, &Value::Null));+ assert_eq!(seqs(&app), [2, 4, 7, 9], "a later resume floors at the loaded window");+ connect(&mut app, 0);+ app.on_event(&entry_event(1, &Value::Null));+ assert_eq!(seqs(&app), [1, 2, 4, 7, 9], "each connection replaces the floors");+ }++ #[test]+ fn floor_rule_is_pure() {+ let (_, e) = Entry::parse(&entry_event(3, &Value::Null)["entry"]).expect("parses");+ assert!(outside_window(Some(5), false, &e));+ assert!(!outside_window(Some(5), true, &e));+ assert!(!outside_window(Some(3), false, &e));+ assert!(!outside_window(None, false, &e));+ }+#[test]fn send_failure_keeps_text_files_and_nonce_for_retry() {let mut app = test_app();diff --git a/host/src/tui/app/exchange.rs b/host/src/tui/app/exchange.rsnew file mode 100644index 00000000..175fe1b6--- /dev/null+++ b/host/src/tui/app/exchange.rs@@ -0,0 +1,356 @@+//! Bot-to-bot exchanges: the notices `chat::team` writes, and the conversation a pair of bots had.+//! Pure functions over entries, so the chat row and the conversation sheet share one reading.++use std::collections::BTreeMap;++use super::{Entry, Kind};++/// Gap between exchanges that starts a new time separator.+const SEPARATOR_GAP_MS: i64 = 3_600_000;++#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Outcome {+ Pending,+ Done,+ /// The detail the host recorded; empty when it gave none.+ Failed(String),+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Exchange {+ pub id: String,+ pub seq: i64,+ /// The bot whose chat holds this notice.+ pub chat: String,+ pub source: String,+ pub target: String,+ pub text: String,+ pub reply: Option<String>,+ pub created_at: i64,+ pub outcome: Outcome,+}++impl Exchange {+ /// The structured exchange a notice in `chat` carries, if it carries one.+ pub fn of(chat: &str, e: &Entry) -> Option<Self> {+ if !e.is_bot_message() {+ return None;+ }+ let message = &e.data["botMessage"];+ let (source, target, text) =+ (message["sourceBotId"].as_str()?, message["targetBotId"].as_str()?, message["text"].as_str()?);+ let reply = message["reply"].as_str();+ let outcome = match e.data["status"].as_str() {+ Some("completed") => Outcome::Done,+ Some("failed" | "cancelled") => Outcome::Failed(message["detail"].as_str().unwrap_or_default().to_owned()),+ _ => Outcome::Pending,+ };+ Some(Self {+ id: e.id.clone(),+ seq: e.seq,+ chat: chat.to_owned(),+ source: source.to_owned(),+ target: target.to_owned(),+ text: text.to_owned(),+ reply: reply.map(str::to_owned),+ created_at: e.created_at,+ outcome,+ })+ }++ /// The chat's bot sent it.+ pub fn outgoing(&self) -> bool {+ self.source == self.chat+ }++ /// The other bot.+ pub fn peer(&self) -> &str {+ if self.outgoing() { &self.target } else { &self.source }+ }++ pub fn verb(&self) -> &'static str {+ if self.outgoing() { "Messaged" } else { "Message from" }+ }+}++/// One chat row: an entry, or a run of two or more exchanges with the same peer.+#[derive(Debug)]+pub enum Item<'a> {+ Entry(&'a Entry),+ Group(Group<'a>),+}++#[derive(Debug)]+pub struct Group<'a> {+ /// The run's first exchange: its id keys the row and opens the conversation.+ pub first: &'a Entry,+ pub peer: String,+ pub count: usize,+ /// Any exchange in the run failed.+ pub failed: bool,+}++/// Whether the chat draws this entry (the rest is trace).+fn is_visible(e: &Entry) -> bool {+ matches!(e.kind, Kind::User | Kind::Permission | Kind::Notice) || e.is_final()+}++/// The main chat's rows: consecutive exchanges with one peer (either direction) become one group.+/// Anything else the chat shows ends the run; trace entries neither break nor appear in it.+/// A run of one stays a plain entry, and threads (`main` false) are never grouped.+pub fn group<'a>(chat: &str, entries: &[&'a Entry], main: bool) -> Vec<Item<'a>> {+ fn flush<'a>(out: &mut Vec<Item<'a>>, run: &mut Vec<(&'a Entry, Exchange)>) {+ match run.as_slice() {+ [] => {}+ [(e, _)] => out.push(Item::Entry(e)),+ [(first, x), ..] => out.push(Item::Group(Group {+ first,+ peer: x.peer().to_owned(),+ count: run.len(),+ failed: run.iter().any(|(_, x)| matches!(x.outcome, Outcome::Failed(_))),+ })),+ }+ run.clear();+ }+ let mut out = vec![];+ let mut run: Vec<(&Entry, Exchange)> = vec![];+ for &e in entries {+ if !main {+ out.push(Item::Entry(e));+ } else if let Some(x) = Exchange::of(chat, e) {+ if run.last().is_some_and(|(_, r)| r.peer() != x.peer()) {+ flush(&mut out, &mut run);+ }+ run.push((e, x));+ } else if is_visible(e) {+ flush(&mut out, &mut run);+ out.push(Item::Entry(e));+ }+ }+ flush(&mut out, &mut run);+ out+}++/// `peer`'s exchanges with `chat`, oldest first: the fetched history plus the live chat, the live copy winning.+pub fn conversation(chat: &str, fetched: &[Entry], live: Option<&BTreeMap<i64, Entry>>, peer: &str) -> Vec<Exchange> {+ let mut by_id: BTreeMap<String, Exchange> = BTreeMap::new();+ for e in fetched.iter().chain(live.into_iter().flat_map(BTreeMap::values)) {+ if let Some(x) = Exchange::of(chat, e) {+ by_id.insert(x.id.clone(), x);+ }+ }+ let mut all: Vec<Exchange> = by_id.into_values().filter(|x| x.peer() == peer).collect();+ all.sort_by_key(|x| x.seq);+ all+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub enum ConversationRow {+ Separator(i64),+ Message {+ author: String,+ text: String,+ shows_author: bool,+ },+ /// A pending or failed exchange; `awaiting` is the bot being waited for.+ Status {+ outcome: Outcome,+ awaiting: String,+ },+}++/// The sheet's rows. A separator or status row ends the previous author's run.+pub fn rows(exchanges: &[Exchange]) -> Vec<ConversationRow> {+ let mut out = vec![];+ let mut prev_at: Option<i64> = None;+ let mut prev_author: Option<&str> = None;+ for x in exchanges {+ if prev_at.is_none_or(|at| x.created_at - at > SEPARATOR_GAP_MS) {+ out.push(ConversationRow::Separator(x.created_at));+ prev_author = None;+ }+ prev_at = Some(x.created_at);+ let mut say = |author: &'_ str, text: &str, prev: &mut Option<&str>| {+ out.push(ConversationRow::Message {+ author: author.to_owned(),+ text: text.to_owned(),+ shows_author: *prev != Some(author),+ });+ };+ say(&x.source, &x.text, &mut prev_author);+ prev_author = Some(&x.source);+ if let Some(reply) = &x.reply {+ say(&x.target, reply, &mut prev_author);+ prev_author = Some(&x.target);+ }+ if x.outcome != Outcome::Done {+ out.push(ConversationRow::Status { outcome: x.outcome.clone(), awaiting: x.target.clone() });+ prev_author = None;+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::super::Kind;+ use super::*;+ use serde_json::json;++ fn notice(id: &str, seq: i64, at: i64, message: &serde_json::Value, status: &str) -> Entry {+ let data = json!({"text": "A rendered notice", "botMessage": message, "status": status});+ Entry { id: id.into(), seq, turn: 1, kind: Kind::Notice, created_at: at, thread_id: None, data }+ }++ fn msg(source: &str, target: &str, text: &str) -> serde_json::Value {+ json!({"sourceBotId": source, "targetBotId": target, "text": text})+ }++ #[test]+ fn direction_and_peer_follow_the_chat() {+ let e = notice("n", 1, 0, &msg("a", "b", "hi"), "queued");+ let out = Exchange::of("a", &e).unwrap();+ assert!(out.outgoing());+ assert_eq!((out.peer(), out.verb(), out.text.as_str()), ("b", "Messaged", "hi"));+ let inc = Exchange::of("b", &e).unwrap();+ assert_eq!((inc.peer(), inc.verb()), ("a", "Message from"));+ assert_eq!(inc.text, "hi", "the same structured request appears in either chat");+ let mut plain = e.clone();+ plain.data = json!({"text": "Messaged Owen"});+ assert!(Exchange::of("a", &plain).is_none());+ let mut old_notice = e.clone();+ old_notice.data =+ json!({"text": "Asked b: hi", "heading": "Asked b: hi", "sourceBotId": "a", "targetBotId": "b"});+ assert!(Exchange::of("a", &old_notice).is_none());+ let mut other = e;+ other.kind = Kind::Agent;+ assert!(Exchange::of("a", &other).is_none());+ }++ fn shape(items: &[Item]) -> Vec<String> {+ items+ .iter()+ .map(|i| match i {+ Item::Entry(e) => e.id.clone(),+ Item::Group(g) => format!("{}x{}{}@{}", g.count, g.peer, if g.failed { "!" } else { "" }, g.first.id),+ })+ .collect()+ }++ fn grouped(chat: &str, entries: &[Entry], main: bool) -> Vec<String> {+ let refs: Vec<&Entry> = entries.iter().collect();+ shape(&group(chat, &refs, main))+ }++ #[test]+ fn same_peer_runs_group_in_either_direction() {+ let xs = [+ notice("1", 1, 0, &msg("a", "b", "x"), "completed"),+ notice("2", 2, 0, &msg("b", "a", "y"), "completed"),+ notice("3", 3, 0, &msg("a", "b", "z"), "failed"),+ ];+ assert_eq!(grouped("a", &xs, true), ["3xb!@1"]);+ assert_eq!(grouped("a", &xs[..2], true), ["2xb@1"]);+ assert_eq!(grouped("a", &xs[..1], true), ["1"]);+ assert_eq!(grouped("a", &xs, false), ["1", "2", "3"], "threads never group");+ }++ #[test]+ fn other_peers_and_visible_entries_split_but_trace_does_not() {+ let mut user = notice("u", 3, 0, &msg("a", "b", ""), "queued");+ user.kind = Kind::User;+ user.data = json!({"text": "hi"});+ let mut tool = user.clone();+ tool.id = "t".into();+ tool.kind = Kind::Tool;+ let mut thought = tool.clone();+ thought.id = "th".into();+ thought.kind = Kind::Agent;+ let ex = |id: &str, seq, peer: &str| notice(id, seq, 0, &msg("a", peer, "x"), "completed");+ let xs = [ex("1", 1, "b"), ex("2", 2, "b"), tool.clone(), thought, ex("3", 5, "b")];+ assert_eq!(grouped("a", &xs, true), ["3xb@1"], "trace entries do not split");+ let xs = [ex("1", 1, "b"), ex("2", 2, "b"), user.clone(), ex("3", 4, "b"), ex("4", 5, "b")];+ assert_eq!(grouped("a", &xs, true), ["2xb@1", "u", "2xb@3"]);+ let xs = [ex("1", 1, "b"), ex("2", 2, "b"), ex("3", 3, "c"), ex("4", 4, "b")];+ assert_eq!(grouped("a", &xs, true), ["2xb@1", "3", "4"]);+ let mut other = ex("n", 3, "b");+ other.data = json!({"text": "Routine ran"});+ let xs = [ex("1", 1, "b"), other, ex("2", 3, "b")];+ assert_eq!(grouped("a", &xs, true), ["1", "n", "2"]);+ }++ #[test]+ fn reply_comes_from_structured_data_without_parsing_display_text() {+ let mut m = msg("a", "b", "hi");+ m["reply"] = "line one\nline two".into();+ let reply = |m: &serde_json::Value| Exchange::of("a", ¬ice("n", 1, 0, m, "completed")).unwrap().reply;+ assert_eq!(reply(&m).as_deref(), Some("line one\nline two"));+ m.as_object_mut().unwrap().remove("reply");+ m["detail"] = "Reply from b:\nThis is display text, not a reply".into();+ assert_eq!(reply(&m), None);+ }++ #[test]+ fn status_maps_to_an_outcome() {+ let mut m = msg("a", "b", "hi");+ m["detail"] = "Recipient stopped.".into();+ let outcome = |status: &str| Exchange::of("a", ¬ice("n", 1, 0, &m, status)).unwrap().outcome;+ assert_eq!(outcome("queued"), Outcome::Pending);+ assert_eq!(outcome("sent"), Outcome::Pending);+ assert_eq!(outcome("completed"), Outcome::Done);+ assert_eq!(outcome("failed"), Outcome::Failed("Recipient stopped.".into()));+ assert_eq!(outcome("cancelled"), Outcome::Failed("Recipient stopped.".into()));+ }++ #[test]+ fn merge_prefers_live_copy_and_filters_the_peer() {+ let fetched = [+ notice("old", 1, 0, &msg("a", "b", "first"), "queued"),+ notice("c", 2, 0, &msg("a", "c", "elsewhere"), "queued"),+ ];+ let live: BTreeMap<i64, Entry> = [+ (1, notice("old", 1, 0, &msg("a", "b", "first"), "completed")),+ (3, notice("new", 3, 0, &msg("b", "a", "second"), "queued")),+ ]+ .into();+ let xs = conversation("a", &fetched, Some(&live), "b");+ assert_eq!(xs.iter().map(|x| x.id.as_str()).collect::<Vec<_>>(), ["old", "new"]);+ assert_eq!(xs[0].outcome, Outcome::Done);+ assert_eq!(conversation("a", &fetched, None, "b").len(), 1);+ }++ #[test]+ fn rows_group_authors_and_separate_by_hour() {+ let mut ask = msg("a", "b", "question");+ ask["reply"] = "answer".into();+ let hour = SEPARATOR_GAP_MS;+ let xs = [+ Exchange::of("a", ¬ice("1", 1, 0, &ask, "completed")).unwrap(),+ Exchange::of("a", ¬ice("2", 2, 1000, &msg("a", "b", "again"), "queued")).unwrap(),+ Exchange::of("a", ¬ice("3", 3, 1000 + hour + 1, &msg("a", "b", "later"), "failed")).unwrap(),+ ];+ let message = |author: &str, text: &str, shows_author| ConversationRow::Message {+ author: author.into(),+ text: text.into(),+ shows_author,+ };+ assert_eq!(+ rows(&xs),+ [+ ConversationRow::Separator(0),+ message("a", "question", true),+ message("b", "answer", true),+ message("a", "again", true),+ ConversationRow::Status { outcome: Outcome::Pending, awaiting: "b".into() },+ ConversationRow::Separator(1000 + hour + 1),+ message("a", "later", true),+ ConversationRow::Status { outcome: Outcome::Failed(String::new()), awaiting: "b".into() },+ ]+ );+ let same_author = [+ Exchange::of("a", ¬ice("1", 1, 0, &msg("a", "b", "x"), "completed")).unwrap(),+ Exchange::of("a", ¬ice("2", 2, 1, &msg("a", "b", "y"), "completed")).unwrap(),+ ];+ assert!(matches!(&rows(&same_author)[2], ConversationRow::Message { shows_author: false, .. }));+ }+}diff --git a/host/src/tui/app/input.rs b/host/src/tui/app/input.rsindex e7981786..54b7df5d 100644--- a/host/src/tui/app/input.rs+++ b/host/src/tui/app/input.rs@@ -405,6 +405,7 @@ impl App {}Some(Click::Composer) => self.start_typing(),Some(Click::Thread(root)) => self.open_thread(root),+ Some(Click::BotChat(entry)) => self.open_bot_chat(&entry),None => {if self.overlays.is_empty() {if self.hits.trace.contains(at) {diff --git a/host/src/tui/app/mod.rs b/host/src/tui/app/mod.rsindex c050318a..bc436edd 100644--- a/host/src/tui/app/mod.rs+++ b/host/src/tui/app/mod.rs@@ -3,6 +3,7 @@mod analytics;mod editor;mod events;+mod exchange;mod forms;mod input;mod model;@@ -11,6 +12,7 @@ mod overlay_keys;mod ui;pub use editor::Editor;+pub use exchange::{ConversationRow, Exchange, Item, Outcome, conversation, group, rows};pub use model::{After, Bot, Entry, Kind, Mark, Msg, Status};pub use ui::{ACTIONS, Action, AgentPicker, COLORS, Click, Confirm, ConfirmAct, Dir, FIELDS, FILTERS, Field, Focus, FolderPicker,@@ -91,6 +93,11 @@ pub struct App {/// Permission cards whose answer is on its way, with the chosen option.pub answering: HashMap<String, String>,history_done: HashSet<String>,+ /// The `since` the current events connection requested.+ stream_since: i64,+ /// Per bot, the lowest seq of its loaded main chat when this connection's catch-up began+ /// (empty when it asked for everything): unknown entries below it are rewrites of old ones.+ floors: HashMap<String, i64>,pub hint: Option<(String, Instant)>,/// Whether this computer shares usage analytics (`None`: nobody decided yet).pub analytics: Option<bool>,@@ -144,6 +151,8 @@ impl App {history_busy: HashSet::new(),answering: HashMap::new(),history_done: HashSet::new(),+ stream_since: 0,+ floors: HashMap::new(),hint: None,analytics: None,opened: false,@@ -229,7 +238,9 @@ impl App {/// Whether every older entry of this bot is loaded.pub fn history_complete(&self, id: &str) -> bool {- self.history_done.contains(id) || self.oldest_main(id).is_none_or(|s| s <= 1)+ self.history_done.contains(id)+ || self.entries.get(id).is_none_or(BTreeMap::is_empty)+ || self.oldest_main(id).is_some_and(|s| s <= 1)}/// Paging (`history`) covers the main chat only; thread replies don't count.@@ -354,7 +365,7 @@ impl App {if self.history_busy.contains(&id) || self.history_done.contains(&id) {return;}- let Some(oldest) = self.oldest_main(&id) else { return };+ let oldest = self.oldest_main(&id).unwrap_or(i64::MAX);if oldest <= 1 {self.history_done.insert(id);return;diff --git a/host/src/tui/app/model.rs b/host/src/tui/app/model.rsindex bf4fe530..e366bdee 100644--- a/host/src/tui/app/model.rs+++ b/host/src/tui/app/model.rs@@ -7,6 +7,10 @@ use super::tilde;pub enum Msg {Online(bool),+ /// A new events connection asked for everything after `since`; its `hello` starts the catch-up.+ Connected {+ since: i64,+ },Event(Value),Reply(After, Result<Value, String>),/// The stream is starting over from rev 0: drop what we have.@@ -197,7 +201,7 @@ pub struct Entry {}impl Entry {- pub(super) fn parse(v: &Value) -> Option<(String, Self)> {+ pub(in crate::tui) fn parse(v: &Value) -> Option<(String, Self)> {let kind = match v["kind"].as_str()? {"user" => Kind::User,"agent" => Kind::Agent,@@ -253,6 +257,13 @@ impl Entry {self.kind == Kind::User || self.is_final() || self.data["connectionRequest"].is_object()}+ /// A notice for a bot-to-bot message or request (`chat::team`).+ pub fn is_bot_message(&self) -> bool {+ self.kind == Kind::Notice+ && self.data["botMessage"].is_object()+ && ["sourceBotId", "targetBotId", "text"].iter().all(|k| self.data["botMessage"][k].is_string())+ }+pub fn pending(&self) -> bool {self.kind == Kind::Permission && self.data["status"] == "pending"}diff --git a/host/src/tui/app/navigate.rs b/host/src/tui/app/navigate.rsindex 312cfbbf..f3bb8a58 100644--- a/host/src/tui/app/navigate.rs+++ b/host/src/tui/app/navigate.rs@@ -3,7 +3,7 @@use crossterm::event::{KeyCode, KeyEvent};use serde_json::{Value, json};-use super::{After, App, Focus, Msg, TraceMode, Width, copy};+use super::{After, App, Focus, Item, Msg, TraceMode, Width, copy, group};impl App {/// `codync-host install` with this same binary, for when nothing is listening yet.@@ -129,15 +129,26 @@ impl App {/// `r`: moves the pick through the main chat's messages (none picked: the newest).pub(super) fn step_pick(&mut self, d: isize) {let Some(id) = self.selected.clone() else { return };- let ids: Vec<String> = self.lane(&id).into_iter().filter(|e| e.is_message()).map(|e| e.id.clone()).collect();- if ids.is_empty() {+ // A run of exchanges with one peer is one pick: its first entry.+ let lane = self.lane(&id);+ let picks: Vec<(String, bool)> = group(&id, &lane, self.thread.is_none())+ .into_iter()+ .filter_map(|item| match item {+ Item::Entry(e) if e.is_message() || e.is_bot_message() => Some((e.id.clone(), e.is_message())),+ Item::Group(g) => Some((g.first.id.clone(), false)),+ Item::Entry(_) => None,+ })+ .collect();+ if picks.is_empty() {self.pick = None;self.flash("No message to reply to yet");return;}- let at = self.pick.as_ref().and_then(|p| ids.iter().position(|x| x == p));- let i = at.map_or(ids.len() - 1, |i| i.saturating_add_signed(d).min(ids.len() - 1));- self.pick = Some(ids[i].clone());+ let at = self.pick.as_ref().and_then(|p| picks.iter().position(|(x, _)| x == p));+ // A fresh pick lands on the newest message, so `r` still replies to it; j/k reach bot rows.+ let newest = picks.iter().rposition(|&(_, message)| message).unwrap_or(picks.len() - 1);+ let i = at.map_or(newest, |i| i.saturating_add_signed(d).min(picks.len() - 1));+ self.pick = Some(picks[i].0.clone());}/// Keys while a message is picked. Returns whether the key was used.@@ -148,6 +159,28 @@ impl App {KeyCode::Char('j') | KeyCode::Down => self.step_pick(1),KeyCode::Char('k') | KeyCode::Up => self.step_pick(-1),KeyCode::Char('C') => self.open_connection(),+ KeyCode::Enter if picked.as_ref().is_some_and(super::Entry::is_bot_message) => {+ if let Some(e) = picked {+ self.open_bot_chat(&e.id);+ }+ }+ KeyCode::Char('c') if picked.as_ref().is_some_and(super::Entry::is_bot_message) => {+ if let Some(e) = picked {+ let lane = self.lane(&id);+ let grouped = group(&id, &lane, self.thread.is_none())+ .iter()+ .any(|i| matches!(i, Item::Group(g) if g.first.id == e.id));+ if grouped {+ self.flash("Bot conversations are read-only");+ } else {+ copy(&super::Exchange::of(&id, &e).map(|x| x.text).unwrap_or_default());+ self.flash("Copied");+ }+ }+ }+ KeyCode::Char('r' | 'f' | '1'..='6') if picked.as_ref().is_some_and(super::Entry::is_bot_message) => {+ self.flash("Bot conversations are read-only");+ }KeyCode::Enter if picked.as_ref().is_some_and(|e| e.data["connectionRequest"]["status"] == "pending") => {self.open_connection();}diff --git a/host/src/tui/app/overlay_keys.rs b/host/src/tui/app/overlay_keys.rsindex 35440ac0..9f228e16 100644--- a/host/src/tui/app/overlay_keys.rs+++ b/host/src/tui/app/overlay_keys.rs@@ -102,6 +102,7 @@ impl App {Overlay::Form(f) => self.form_key(f, k),Overlay::Group(g) => self.group_key(g, k),Overlay::Memory(m) => self.memory_key(m, k),+ Overlay::BotChat(c) => Self::bot_chat_key(c, k),Overlay::Routines(l) => self.routines_key(l, k),Overlay::Routine(f) => self.routine_key(f, k),Overlay::Market(m) => self.market_key(m, k),diff --git a/host/src/tui/app/ui.rs b/host/src/tui/app/ui.rsindex 6f5a1bee..3e5da1ce 100644--- a/host/src/tui/app/ui.rs+++ b/host/src/tui/app/ui.rs@@ -3,7 +3,7 @@use ratatui::layout::Rect;use std::time::Instant;-use super::super::manage::{AgentSetup, Fields, Market, MemorySheet, RoutineForm, RoutineList};+use super::super::manage::{AgentSetup, BotChatSheet, Fields, Market, MemorySheet, RoutineForm, RoutineList};use super::{Editor, Mark};#[derive(Clone, Copy, PartialEq, Eq, Debug)]@@ -238,6 +238,8 @@ pub enum Overlay {Usage,Pair(Option<String>),Memory(MemorySheet),+ /// A read-only conversation between two bots.+ BotChat(BotChatSheet),Routines(RoutineList),Routine(Box<RoutineForm>),Market(Box<Market>),@@ -264,6 +266,8 @@ pub enum Click {Composer,/// The replies line under a message: opens its thread.Thread(String),+ /// A bot-message row (entry id): opens the conversation.+ BotChat(String),}#[derive(Default)]diff --git a/host/src/tui/manage/bot_chat.rs b/host/src/tui/manage/bot_chat.rsnew file mode 100644index 00000000..682d6b39--- /dev/null+++ b/host/src/tui/manage/bot_chat.rs@@ -0,0 +1,49 @@+//! A bot-to-bot conversation sheet: read-only, opened from a bot-message row.++use std::cell::Cell;++use crossterm::event::{KeyCode, KeyEvent};+use serde_json::json;++use super::super::app::{App, Exchange, Overlay};+use super::{BotChatSheet, Reply, ctrl};++impl App {+ /// Opens the conversation a bot-message row in the selected chat stands for.+ pub(in crate::tui) fn open_bot_chat(&mut self, entry: &str) {+ let Some(chat) = self.selected.clone() else { return };+ let Some(x) = self.lane(&chat).into_iter().find(|e| e.id == entry).and_then(|e| Exchange::of(&chat, e)) else {+ return;+ };+ let peer = x.peer().to_owned();+ self.sheet(+ "botConversation",+ json!({"botId": chat, "peerId": peer}),+ Reply::BotChat { bot: chat.clone(), peer: peer.clone() },+ );+ self.overlays.push(Overlay::BotChat(BotChatSheet {+ bot: chat,+ peer,+ fetched: None,+ scroll: 0,+ max_scroll: Cell::default(),+ page: Cell::default(),+ }));+ }++ pub(in crate::tui) fn bot_chat_key(mut c: BotChatSheet, k: KeyEvent) -> Option<Overlay> {+ let max = c.max_scroll.get();+ let half = (c.page.get() / 2).max(1);+ match k.code {+ KeyCode::Esc | KeyCode::Char('q') | KeyCode::Enter => return None,+ KeyCode::Up | KeyCode::Char('k') => c.scroll = (c.scroll + 1).min(max),+ KeyCode::Down | KeyCode::Char('j') => c.scroll = c.scroll.saturating_sub(1),+ KeyCode::PageUp => c.scroll = (c.scroll + half).min(max),+ KeyCode::PageDown => c.scroll = c.scroll.saturating_sub(half),+ KeyCode::Char('u') if ctrl(k) => c.scroll = (c.scroll + half).min(max),+ KeyCode::Char('d') if ctrl(k) => c.scroll = c.scroll.saturating_sub(half),+ _ => {}+ }+ Some(Overlay::BotChat(c))+ }+}diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rsindex 77051901..480a612b 100644--- a/host/src/tui/manage/mod.rs+++ b/host/src/tui/manage/mod.rs@@ -6,6 +6,7 @@#![allow(clippy::many_single_char_names)]mod agent;+mod bot_chat;mod fields;mod market;mod memory;@@ -17,7 +18,9 @@ pub use routines::local_zone;use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};use serde_json::{Value, json};-use super::app::{After, App, Editor};+use std::cell::Cell;++use super::app::{After, App, Editor, Entry};/// Quick reactions, as the other apps offer them.pub const REACTIONS: [&str; 6] = ["👍", "❤️", "😂", "🎉", "👀", "✅"];@@ -30,6 +33,11 @@ pub enum Reply {RoutineSaved,/// A routine's webhook URL and key: copied as a ready-to-run curl.Webhook,+ /// A bot conversation's fetched history.+ BotChat {+ bot: String,+ peer: String,+ },Registry {more: bool,},@@ -56,6 +64,19 @@ pub struct MemorySheet {pub cursor: usize,}+/// A read-only conversation between `bot` and `peer`, scrolled from the bottom.+pub struct BotChatSheet {+ pub bot: String,+ pub peer: String,+ /// The host's history; `None` while it loads.+ pub fetched: Option<Vec<Entry>>,+ /// Lines up from the bottom.+ pub scroll: usize,+ /// Set by the last draw, for clamping the scroll and paging.+ pub max_scroll: Cell<usize>,+ pub page: Cell<usize>,+}+pub struct RoutineList {pub bot: String,pub items: Option<Vec<Value>>,diff --git a/host/src/tui/manage/replies.rs b/host/src/tui/manage/replies.rsindex 95e6c541..8c245873 100644--- a/host/src/tui/manage/replies.rs+++ b/host/src/tui/manage/replies.rs@@ -2,7 +2,7 @@use serde_json::{Value, json};-use super::super::app::{After, App, Overlay, Toggle};+use super::super::app::{After, App, Entry, Overlay, Toggle};use super::{Fact, Reply, Shell, open_browser, s};impl App {@@ -31,6 +31,18 @@ impl App {}}}+ Reply::BotChat { bot, peer } => {+ let entries: Vec<Entry> =+ v["entries"].as_array().into_iter().flatten().filter_map(Entry::parse).map(|(_, e)| e).collect();+ for o in &mut self.overlays {+ if let Overlay::BotChat(c) = o+ && c.bot == bot+ && c.peer == peer+ {+ c.fetched = Some(entries.clone());+ }+ }+ }Reply::Routines(bot) => {if v["routines"].is_array() {for o in &mut self.overlays {@@ -196,6 +208,17 @@ impl App {m.error = Some(e);}}+ Reply::BotChat { bot, peer } => {+ for o in &mut self.overlays {+ if let Overlay::BotChat(c) = o+ && c.bot == *bot+ && c.peer == *peer+ {+ c.fetched.get_or_insert_with(Vec::new);+ }+ }+ self.flash(&e);+ }Reply::Memory(_) | Reply::Routines(_) => {for o in &mut self.overlays {match o {diff --git a/host/src/tui/net.rs b/host/src/tui/net.rsindex b075827e..11c59858 100644--- a/host/src/tui/net.rs+++ b/host/src/tui/net.rs@@ -208,12 +208,13 @@ impl Client {let c = self.clone();tokio::spawn(async move {loop {- let url = format!("{}/events?since={}&client=tui", c.base, c.rev.load(Ordering::Relaxed));+ let since = c.rev.load(Ordering::Relaxed);+ let url = format!("{}/events?since={since}&client=tui", c.base);if let Some(token) = c.token()&& let Ok(res) = crate::http().get(url).bearer_auth(token).send().await&& res.status().is_success(){- if tx.send(Msg::Online(true)).is_err() {+ if tx.send(Msg::Online(true)).is_err() || tx.send(Msg::Connected { since }).is_err() {return;}let mut body = res.bytes_stream();diff --git a/host/src/tui/view/bot_chat.rs b/host/src/tui/view/bot_chat.rsnew file mode 100644index 00000000..521f2f36--- /dev/null+++ b/host/src/tui/view/bot_chat.rs@@ -0,0 +1,100 @@+//! The read-only conversation sheet between two bots.++use ratatui::buffer::Buffer;+use ratatui::layout::Rect;+use ratatui::text::{Line, Span};++use super::super::app::{App, ConversationRow, Outcome, conversation, rows};+use super::super::manage::BotChatSheet;+use super::super::md::{self, width as w};+use super::buffer::{centered, frame_box, hline, put, put_line, u};+use super::chat::with_bg;+use super::style::{person, theme};+use super::time::when;+use super::transcript::name_style;++fn name_and_color(app: &App, id: &str) -> (String, String) {+ app.bots+ .get(id)+ .map_or_else(|| ("A deleted bot".to_owned(), "gray".to_owned()), |b| (b.name.clone(), b.color.clone()))+}++pub(super) fn bot_chat(buf: &mut Buffer, area: Rect, app: &App, c: &BotChatSheet) {+ let t = theme();+ let r = centered(area, 84, area.height.saturating_sub(4));+ let inner = frame_box(buf, r, t.text, t.panel, None);+ if inner.height < 5 {+ return;+ }+ let mut pill = vec![Span::raw(" ")];+ for (i, id) in [&c.bot, &c.peer].into_iter().enumerate() {+ let (name, color) = name_and_color(app, id);+ if i == 1 {+ pill.push(Span::styled(" ⇄ ", t.dim));+ }+ pill.extend([person(app, id), Span::raw(" "), Span::styled(name, name_style(&color))]);+ }+ put_line(buf, inner.x, inner.y, inner.width, &Line::from(pill));+ hline(buf, inner.x, inner.y + 1, inner.width, t.dim.patch(t.panel));+ put(buf, inner.x, inner.bottom() - 1, inner.width, " ↑↓ scroll · esc close", t.dim.patch(t.panel));++ let body = Rect::new(inner.x, inner.y + 2, inner.width, inner.height - 3);+ let lines = body_lines(app, c, usize::from(body.width));+ let h = usize::from(body.height);+ let max = lines.len().saturating_sub(h);+ c.max_scroll.set(max);+ c.page.set(h);+ let start = lines.len().saturating_sub(h + c.scroll.min(max));+ for (i, l) in lines.iter().skip(start).take(h).enumerate() {+ put_line(buf, body.x, body.y + u(i), body.width, l);+ }+}++fn body_lines(app: &App, c: &BotChatSheet, width: usize) -> Vec<Line<'static>> {+ let t = theme();+ let Some(fetched) = &c.fetched else {+ return vec![Line::from(Span::styled(" Loading…", t.dim))];+ };+ let live = app.entries.get(&c.bot);+ let exchanges = conversation(&c.bot, fetched, live, &c.peer);+ if exchanges.is_empty() {+ return vec![Line::from(Span::styled(" No messages yet.", t.dim))];+ }+ let mut out: Vec<Line<'static>> = vec![];+ for row in rows(&exchanges) {+ match row {+ ConversationRow::Separator(at) => {+ if !out.is_empty() {+ out.push(Line::default());+ }+ let label = format!(" {} ", when(at));+ let side = width.saturating_sub(w(&label) + 4);+ out.push(Line::from(Span::styled(format!(" ───{label}{}", "─".repeat(side)), t.dim)));+ }+ ConversationRow::Message { author, text, shows_author } => {+ if shows_author {+ out.push(Line::default());+ let (name, color) = name_and_color(app, &author);+ out.push(Line::from(vec![+ Span::raw(" "),+ person(app, &author),+ Span::raw(" "),+ Span::styled(name, name_style(&color)),+ ]));+ }+ out.extend(with_bg(md::render(&text, width, 1), width, t.band));+ }+ ConversationRow::Status { outcome, awaiting } => {+ out.push(Line::default());+ if let Outcome::Failed(detail) = outcome {+ let detail = if detail.is_empty() { "Didn't complete.".to_owned() } else { detail };+ out.extend(md::wrap(&[Span::styled(detail, t.red)], width, &[Span::raw(" ")], &[Span::raw(" ")]));+ } else {+ let (name, _) = name_and_color(app, &awaiting);+ out.push(Line::from(Span::styled(format!(" Waiting for {name}…"), t.dim)));+ }+ }+ }+ }+ out+}diff --git a/host/src/tui/view/help.rs b/host/src/tui/view/help.rsindex 7a3add71..70e01c10 100644--- a/host/src/tui/view/help.rs+++ b/host/src/tui/view/help.rs@@ -9,7 +9,7 @@ use super::buffer::{centered, frame_box, put, u};use super::overlay::field_line;use super::style::theme;-const HELP: [(&str, &str, &str); 53] = [+const HELP: [(&str, &str, &str); 54] = [("MOVE", "j k ↑ ↓", "next / previous bot"),("MOVE", "[ ]", "previous / next bot"),("MOVE", "1…9", "jump to bot 1–9"),@@ -34,6 +34,7 @@ const HELP: [(&str, &str, &str); 53] = [("CHAT", "j k ↵", "picking: move / open"),("CHAT", "1…6", "picking: react"),("CHAT", "f", "picking: save its files"),+ ("CHAT", "↵", "picking a bot message: open its conversation"),("CHAT", "esc", "close the thread"),("TYPE", "↵", "send"),("TYPE", "⇧↵ alt↵ ^j", "new line"),diff --git a/host/src/tui/view/mod.rs b/host/src/tui/view/mod.rsindex d909aec0..cc9bc14e 100644--- a/host/src/tui/view/mod.rs+++ b/host/src/tui/view/mod.rs@@ -6,6 +6,7 @@// Drawing code reads best with x / y / w / t (theme) / r (rect).#![allow(clippy::many_single_char_names, clippy::similar_names)]+mod bot_chat;mod buffer;mod chat;mod consent;diff --git a/host/src/tui/view/overlay.rs b/host/src/tui/view/overlay.rsindex 0bd53b22..5d3c16fe 100644--- a/host/src/tui/view/overlay.rs+++ b/host/src/tui/view/overlay.rs@@ -190,6 +190,7 @@ pub(super) fn overlay(buf: &mut Buffer, area: Rect, app: &mut App, top: &OverlayOverlay::Usage => usage(buf, area, app),Overlay::Pair(url) => pair(buf, area, url.as_deref()),Overlay::Memory(m) => super::super::sheets::memory(buf, area, app, m),+ Overlay::BotChat(c) => super::bot_chat::bot_chat(buf, area, app, c),Overlay::Routines(l) => super::super::sheets::routines(buf, area, app, l),Overlay::Routine(f) => super::super::sheets::routine(buf, area, f),Overlay::Market(m) => super::super::sheets::market(buf, area, app, m),diff --git a/host/src/tui/view/transcript.rs b/host/src/tui/view/transcript.rsindex 9e7322ce..e1c1742d 100644--- a/host/src/tui/view/transcript.rs+++ b/host/src/tui/view/transcript.rs@@ -4,7 +4,7 @@ use ratatui::style::{Modifier, Style};use ratatui::text::{Line, Span};use std::collections::{BTreeSet, HashMap};-use super::super::app::{App, Bot, Click, Entry, Kind, Status};+use super::super::app::{App, Bot, Click, Entry, Exchange, Item, Kind, Outcome, Status, group};use super::super::md::{self, truncate, width as w};use super::buffer::u;use super::chat::with_bg;@@ -92,8 +92,15 @@ pub(super) fn build_chat(app: &App, b: &Bot, width: usize) -> Built {out.lines.push(Line::from(Span::styled(format!(" ───{label}{}", "─".repeat(side)), t.dim)));}// A bot's messages arrive whole (Grok Bot's `send_message`); what it writes along the way is trace.- for e in &entries {- entry_lines(&mut out, app, b, e, &info, thread.is_none(), width);+ for item in group(&b.id, &entries, thread.is_none()) {+ match item {+ Item::Entry(e) => entry_lines(&mut out, app, b, e, &info, thread.is_none(), width),+ Item::Group(g) => {+ let from = out.lines.len();+ let lead = format!("{} messages with ", g.count);+ bot_message_line(&mut out, app, g.first, &g.peer, &lead, g.failed, from);+ }+ }}// A turn in flight: who's on it and what they're doing.let last_turn = entries.iter().map(|e| e.turn).max().unwrap_or(0);@@ -259,6 +266,12 @@ fn entry_lines(}Kind::Notice => {let from = out.lines.len();+ if let Some(x) = Exchange::of(&b.id, e) {+ let lead = format!("{} ", x.verb());+ let failed = matches!(x.outcome, Outcome::Failed(_));+ bot_message_line(out, app, e, x.peer(), &lead, failed, from);+ return;+ }let text = if let Some(status) = e.data["connectionRequest"]["status"].as_str() {format!("{} · {} · {}",@@ -297,6 +310,30 @@ fn entry_lines(}}+/// A bot-to-bot exchange, or a run of them, as one compact line ("· Messaged ▌O▐ Owen",+/// "· 3 messages with ▌O▐ Owen"); click opens the conversation with `peer`.+/// Only a failure is marked: its text lives in the conversation sheet.+fn bot_message_line(out: &mut Built, app: &App, e: &Entry, peer: &str, lead: &str, failed: bool, from: usize) {+ let t = theme();+ gap(out);+ let (name, color) = app.bots.get(peer).map_or(("A deleted bot", "gray"), |p| (p.name.as_str(), p.color.as_str()));+ let mark = if failed { Span::styled(" × ", t.red) } else { Span::styled(" · ", t.dim) };+ let mut line = vec![+ Span::styled(lead.to_owned(), t.secondary),+ person(app, peer),+ Span::raw(" "),+ Span::styled(name.to_owned(), name_style(color)),+ ];+ if failed {+ line.push(Span::styled(" · failed", t.red));+ }+ let width = u(line.iter().map(|s| w(&s.content)).sum());+ out.buttons.push((out.lines.len(), 3, width, Click::BotChat(e.id.clone())));+ line.insert(0, mark);+ out.lines.push(Line::from(line));+ out.messages.push((e.id.clone(), from, out.lines.len()));+}+/// A message's reactions, under it.fn reactions(out: &mut Built, e: &Entry) {let r: Vec<&str> = e.data["reactions"].as_array().into_iter().flatten().filter_map(|r| r.as_str()).collect();@@ -352,6 +389,92 @@ fn thread_summary(v: &serde_json::Value) -> Option<String> {mod tests {use super::*;+ fn app_with_bots() -> App {+ let (tx, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(super::super::super::net::Client::new("http://127.0.0.1:1", None), tx, String::new());+ for (id, name) in [("a", "Egan"), ("b", "Owen")] {+ app.on_msg(super::super::super::app::Msg::Event(+ serde_json::json!({"type":"bot","bot":{"id":id,"name":name}}),+ ));+ }+ app+ }++ fn exchange_entry(status: &str) -> Entry {+ Entry {+ id: "n".into(),+ seq: 1,+ turn: 1,+ kind: Kind::Notice,+ created_at: 0,+ thread_id: None,+ data: serde_json::json!({+ "text": "Messaged b: Please review the secret plan\nCompleted.", "style": "info", "status": status,+ "heading": "Messaged b: Please review the secret plan",+ "botMessage": {"sourceBotId": "a", "targetBotId": "b", "text": "Please review the secret plan"},+ "sourceBotId": "a", "targetBotId": "b", "delegationId": "r",+ }),+ }+ }++ #[test]+ fn bot_message_is_one_line_with_a_click_and_marks_only_failure() {+ let app = app_with_bots();+ let bot = &app.bots["a"];+ let render = |e: &Entry| {+ let mut out = Built { lines: vec![], buttons: vec![], messages: vec![] };+ entry_lines(&mut out, &app, bot, e, &HashMap::new(), true, 80);+ out+ };+ let ok = render(&exchange_entry("completed"));+ let text = ok.lines.iter().map(ToString::to_string).collect::<Vec<_>>().join("\n");+ assert!(text.contains("Messaged") && text.contains("Owen"));+ assert!(!text.contains("secret plan") && !text.contains("failed"));+ assert!(matches!(ok.buttons.as_slice(), [(_, 3, _, Click::BotChat(id))] if id == "n"));+ assert_eq!(ok.messages.len(), 1);+ let mut failed = exchange_entry("failed");+ failed.data["text"] = "Messaged b: Please review the secret plan\nRecipient stopped.".into();+ let bad = render(&failed);+ let line = bad.lines.last().unwrap();+ assert!(line.to_string().ends_with("Owen · failed"));+ assert_eq!(line.spans[0].style, theme().red);+ }++ #[test]+ fn a_run_of_exchanges_is_one_counted_line() {+ let app = app_with_bots();+ let bot = &app.bots["a"];+ let mut entries = vec![];+ for (i, status) in ["completed", "failed", "completed"].into_iter().enumerate() {+ let mut e = exchange_entry(status);+ e.id = format!("n{i}");+ e.seq = i64::try_from(i).unwrap_or(0) + 1;+ entries.push(e);+ }+ let refs: Vec<&Entry> = entries.iter().collect();+ let build = |refs: &[&Entry]| {+ let mut out = Built { lines: vec![], buttons: vec![], messages: vec![] };+ for item in group(&bot.id, refs, true) {+ match item {+ Item::Entry(e) => entry_lines(&mut out, &app, bot, e, &HashMap::new(), true, 80),+ Item::Group(g) => {+ let lead = format!("{} messages with ", g.count);+ bot_message_line(&mut out, &app, g.first, &g.peer, &lead, g.failed, 0);+ }+ }+ }+ out+ };+ let out = build(&refs);+ assert_eq!(out.lines.len(), 1);+ let line = &out.lines[0];+ assert!(line.to_string().contains("3 messages with") && line.to_string().ends_with("Owen · failed"), "{line}");+ assert_eq!(line.spans[0].style, theme().red);+ assert!(matches!(out.buttons.as_slice(), [(_, 3, _, Click::BotChat(id))] if id == "n0"));+ assert_eq!(out.messages.len(), 1);+ assert!(build(&refs[..1]).lines[0].to_string().contains("Messaged"));+ }+#[test]fn thread_summary_counts_replies() {assert_eq!(thread_summary(&serde_json::json!({"count": 0})), None);diff --git a/host/tests/team_e2e.rs b/host/tests/team_e2e.rsindex d8b4cb44..8cd6b4b5 100644--- a/host/tests/team_e2e.rs+++ b/host/tests/team_e2e.rs@@ -113,6 +113,9 @@ async fn agent_uses_team_mcp_and_returns_the_reviewers_answer() {assert_eq!(requests.len(), 2);assert!(requests.iter().all(|e| e["data"]["status"] == "completed"));assert_eq!(requests[0]["data"]["delegationId"], requests[1]["data"]["delegationId"]);+ assert!(requests.iter().all(|e| e["data"]["botMessage"]["reply"] == "reply: PERMISSION review the changes"));+ let conversation = host.call("botConversation", json!({"botId": lead, "peerId": reviewer})).await;+ assert_eq!(conversation["entries"].as_array().unwrap().len(), 1);assert!(sync["bots"].as_array().unwrap().iter().all(|b| b["status"] == "idle"));}