Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.
TypeScript agent-teamagentic-aiai-agentsai-assistantclaude-codecodexcursorelectrongrokgrok-bot-alternativelinuxlocal-firstmacosmcpmulti-agentopenclaw-alternativeopencodewindows
Answer every message in a thread, and let a greeting reach everyone (#101)
Eduardo Machado318104afb98c
diff --git a/src/core/context.ts b/src/core/context.tsindex 0815fb8..a18cf95 100644--- a/src/core/context.ts+++ b/src/core/context.ts@@ -264,8 +264,9 @@ export const clock = (at: number): string => {// changes between turns (no "now", no closing line), so the next turn starts// with the same blocks and reads them from the cache. `task` (to continue after// an approval, a routine…) goes last, with the time, since it may come later.-// `images`: the names of the images attached to each message (by id).-type TranscriptOpts = { agent: Agent; conversation: Conversation; messages: Message[]; agents: Agent[]; me: string; task?: string; summary?: string; images?: Map<string, string[]> }+// `images`: the names of the images attached to each message (by id). `thread`: the message+// that started the thread this reply is in (then `messages` is that thread, root first).+type TranscriptOpts = { agent: Agent; conversation: Conversation; messages: Message[]; agents: Agent[]; me: string; task?: string; summary?: string; images?: Map<string, string[]>; thread?: Message }export function transcript(opts: TranscriptOpts): string[] {return transcriptBlocks(opts).blocks@@ -273,7 +274,7 @@ export function transcript(opts: TranscriptOpts): string[] {// The blocks, and which block each message became (where its images go).export function transcriptBlocks(opts: TranscriptOpts): { blocks: string[]; blockOf: Map<string, number> } {- const { agent, conversation, messages, agents, me, task, summary, images } = opts+ const { agent, conversation, messages, agents, me, task, summary, images, thread } = optsconst name = (m: Message): string | null => {if (m.author.kind === 'me') return meif (m.author.kind === 'system') return null@@ -295,9 +296,27 @@ export function transcriptBlocks(opts: TranscriptOpts): { blocks: string[]; blocconst shown = messages.filter((m) => m.author.kind !== 'system' && body(m))const where = conversation.kind === 'dm' ? L(`DM com ${me}`, `DM with ${me}`) : `#${conversation.name}`+ // Who started the thread this reply is in.+ const starter = thread?.author+ const starterName = starter?.kind === 'agent' ? agents.find((a) => a.id === starter.id)?.name : undefined+ const by =+ starter?.kind === 'me'+ ? L(`por ${me}`, `by ${me}`)+ : starter?.kind === 'agent'+ ? starter.id === agent.id+ ? L('por você', 'by you')+ : L(`por ${starterName ?? 'um agente'}`, `by ${starterName ?? 'an agent'}`)+ : starter?.kind === 'routine'+ ? L(`por uma rotina de ${me}`, `by a routine of ${me}'s`)+ : L('pelo app', 'by the app')const head = [summary?.trim() && `${L(`Resumo do que veio antes em ${where}`, `Summary of what came before in ${where}`)}:\n${summary.trim()}`,- `${summary?.trim() ? L('Mensagens desde o resumo', 'Messages since the summary') : L(`Conversa em ${where}`, `Conversation in ${where}`)}, ${L('das mais antigas pras mais novas', 'oldest to newest')}:`+ thread+ ? L(+ `Você está respondendo numa thread em ${where}, aberta ${by}. Abaixo, a mensagem que abriu a thread e as respostas dela, das mais antigas pras mais novas:`,+ `You're replying in a thread in ${where}, started ${by}. Below, the message that started the thread and its replies, oldest to newest:`+ )+ : `${summary?.trim() ? L('Mensagens desde o resumo', 'Messages since the summary') : L(`Conversa em ${where}`, `Conversation in ${where}`)}, ${L('das mais antigas pras mais novas', 'oldest to newest')}:`].filter((b): b is string => !!b)const blockOf = new Map(shown.map((m, i) => [m.id, head.length + i]))const blocks = [...head, ...shown.map((m) => `[${name(m)} · ${clock(m.at)}]\n${body(m)}`), ...(task ? [`${task}\n\n${L('Agora', 'Now')}: ${now()}.`] : [])]diff --git a/src/core/db.ts b/src/core/db.tsindex ebed88e..4f7e615 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -246,6 +246,10 @@ const MIGRATIONS = [`,`ALTER TABLE conversations ADD COLUMN wiki_capture INTEGER;+ `,+ `+ ALTER TABLE messages ADD COLUMN thread_id TEXT;+ CREATE INDEX messages_by_thread ON messages (conversation_id, thread_id, at);`]@@ -479,7 +483,8 @@ export class Db {text: str(r['text']),at: Number(r['at']),run: r['run'] ? (JSON.parse(str(r['run'])) as Run) : undefined,- routine: r['routine'] ? (JSON.parse(str(r['routine'])) as RoutineRun) : undefined+ routine: r['routine'] ? (JSON.parse(str(r['routine'])) as RoutineRun) : undefined,+ threadId: r['thread_id'] ? str(r['thread_id']) : undefined}}@@ -487,8 +492,11 @@ export class Db {return (this.db.prepare('SELECT * FROM messages ORDER BY at').all() as Row[]).map((r) => this.toMessage(r))}- recentMessages(conversationId: string, limit: number): Message[] {- const rows = this.db.prepare('SELECT * FROM messages WHERE conversation_id = ? ORDER BY at DESC LIMIT ?').all(conversationId, limit) as Row[]+ // `threadId`: only that thread's replies; null: only what's outside threads; left out: everything.+ recentMessages(conversationId: string, limit: number, threadId?: string | null): Message[] {+ const where = threadId === undefined ? '' : threadId === null ? ' AND thread_id IS NULL' : ' AND thread_id = ?'+ const args = typeof threadId === 'string' ? [conversationId, threadId, limit] : [conversationId, limit]+ const rows = this.db.prepare(`SELECT * FROM messages WHERE conversation_id = ?${where} ORDER BY at DESC LIMIT ?`).all(...args) as Row[]return rows.reverse().map((r) => this.toMessage(r))}@@ -511,7 +519,7 @@ export class Db {saveMessage(m: Message): void {this.db.prepare(- `INSERT INTO messages (id, conversation_id, author_kind, author_id, text, at, run, routine) VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ `INSERT INTO messages (id, conversation_id, author_kind, author_id, text, at, run, routine, thread_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)ON CONFLICT (id) DO UPDATE SET text = excluded.text, run = excluded.run`).run(@@ -522,7 +530,8 @@ export class Db {m.text,m.at,m.run ? JSON.stringify(m.run) : null,- m.routine ? JSON.stringify(m.routine) : null+ m.routine ? JSON.stringify(m.routine) : null,+ m.threadId ?? null)}diff --git a/src/core/index.ts b/src/core/index.tsindex c67982e..2144a78 100644--- a/src/core/index.ts+++ b/src/core/index.ts@@ -247,7 +247,7 @@ function toPhone(e: CoreEvent): void {// Desktop notification, and the same on the phone.// `fullText`: the whole reply, for the phone; `page`: a click opens that screen instead of a conversation.-const notifyAll = (title: string, shortText: string, conversationId?: string, fullText?: string, more: { kind?: 'approval'; page?: 'skills' } = {}): void => {+const notifyAll = (title: string, shortText: string, conversationId?: string, fullText?: string, more: { kind?: 'approval'; page?: 'skills'; threadId?: string } = {}): void => {toMain({ type: 'notify', title, body: shortText, conversationId, ...more, sound: settings().sounds !== false })void telegram?.notice(title, fullText ?? shortText)}@@ -258,7 +258,7 @@ type ToMain =| { type: 'open_path'; path: string }| { type: 'open_local'; path: string; how: 'open' | 'reveal' }| { type: 'wiki_dir'; path: string } // the wiki's folder, which the app may open- | { type: 'notify'; title: string; body: string; conversationId?: string; kind?: 'approval' | 'question' | 'done'; page?: 'skills'; sound?: boolean }+ | { type: 'notify'; title: string; body: string; conversationId?: string; threadId?: string; kind?: 'approval' | 'question' | 'done'; page?: 'skills'; sound?: boolean }| { type: 'login_item'; open: boolean }| { type: 'busy'; busy: boolean }| { type: 'lang'; lang: Lang }@@ -519,7 +519,8 @@ const runner = new Runner({wikiCurator: curator,models: () => availableModels(settings(), listed),// Approvals and questions reach the phone with their buttons, through toPhone; a finished reply stays on the Mac.- notify: (title, body, conversationId, kind) => (kind ? toMain({ type: 'notify', title, body, conversationId, kind, sound: settings().sounds !== false }) : notifyAll(title, body, conversationId)),+ notify: (title, body, conversationId, kind, threadId) =>+ kind ? toMain({ type: 'notify', title, body, conversationId, threadId, kind, sound: settings().sounds !== false }) : notifyAll(title, body, conversationId, undefined, { threadId }),jev: { key: () => secrets.get(JEV_SECRET) },github,onBusy: (busy) => toMain({ type: 'busy', busy }),@@ -538,7 +539,7 @@ telegram = new Telegram({secrets,decide: (id, decision, reason) => runner.decide(id, decision, reason),approval: (id) => db.approval(id),- answer: (conversationId, text) => void runner.send(conversationId, text),+ answer: (conversationId, text, threadId) => void runner.send(conversationId, text, [], threadId),changed: () => emit({ type: 'settings', settings: settings() })})@@ -705,8 +706,8 @@ const api: Api = {demoServer: existsSync(demoPath) ? { command: 'node', args: [demoPath] } : undefined}),- sendMessage: ({ conversationId, text, images }) => {- void runner.send(conversationId, text, images)+ sendMessage: ({ conversationId, text, images, threadId }) => {+ void runner.send(conversationId, text, images, threadId)},stopRun: ({ messageId }) => runner.stop(messageId),diff --git a/src/core/jev.ts b/src/core/jev.tsindex d7a851c..b6d164b 100644--- a/src/core/jev.ts+++ b/src/core/jev.ts@@ -11,6 +11,7 @@ export const JEV_MODEL = 'jev' // the routerModel value that picks itexport const JEV_SECRET = 'typesafe:key'const API = 'https://api.typesafe.ai/v1'const NOBODY = '__ninguem' // can't clash with a handle: handles never start with "_"+const EVERYONE = '__todos'const SECOND_AT = 0.3 // a second agent is called when the model gives it at least thisconst TIMEOUT_MS = 10_000@@ -42,6 +43,7 @@ export async function routeJev(opts: {agents: Agent[]me: stringconnectors?: Connector[]+ thread?: Messagefetch?: Fetch}): Promise<{ agents: Agent[]; reason: string; ms: number } | { error: string; ms: number }> {const started = Date.now()@@ -52,9 +54,13 @@ export async function routeJev(opts: {const state = prompt.endsWith(REPLY_JSON()) ? prompt.slice(0, -REPLY_JSON().length).trimEnd() : promptconst criteria: Record<string, string> = {}for (const a of agents) criteria[a.handle] = describeAgent(a, opts.connectors)+ criteria[EVERYONE] = L(+ 'Todos: a mensagem é pro grupo todo (um cumprimento, "pessoal", uma pergunta pra todos, uma apresentação).',+ 'Everyone: the message is for the whole group (a greeting, "everyone", a question for all, an introduction).'+ )criteria[NOBODY] = L(- 'Ninguém: a mensagem não pede nada a nenhum agente (cumprimento solto, agradecimento, recado, conversa já encerrada).',- "No one: the message asks nothing of any agent (a passing greeting, a thank-you, a note, a conversation that's already over)."+ 'Ninguém: a mensagem não pede nada a nenhum agente (agradecimento, recado, conversa já encerrada). Nunca um cumprimento.',+ "No one: the message asks nothing of any agent (a thank-you, a note, a conversation that's already over). Never a greeting.")let res: Response@@ -89,6 +95,7 @@ export async function routeJev(opts: {const probs = who.probabilities ?? {}const pct = (h: string): string => `${Math.round((probs[h] ?? 0) * 100)}%`if (who.choice === NOBODY) return { agents: [], reason: `Jev, ${pct(NOBODY)}`, ms: ms() }+ if (who.choice === EVERYONE) return { agents: [...agents], reason: `Jev, ${pct(EVERYONE)}`, ms: ms() }const first = agents.find((a) => a.handle === who.choice)if (!first) return { error: L('o TypeSafe escolheu alguém fora do canal', 'TypeSafe picked someone outside the channel'), ms: ms() }diff --git a/src/core/memory.ts b/src/core/memory.tsindex f43109c..2e8943e 100644--- a/src/core/memory.ts+++ b/src/core/memory.ts@@ -113,7 +113,8 @@ export function consolidationPrompt(opts: { summary?: string; messages: Message[summary?.trim() || L('(ainda não há)', '(none yet)'),'',L('Trecho que vai sair da janela:', 'Stretch about to leave the window:'),- ...messages.map((m, i) => `(${i + 1}) [${author(m)}] ${m.text.trim().slice(0, 4000)}`),+ // Thread replies are folded in too, marked, since the channel's window leaves them out.+ ...messages.map((m, i) => `(${i + 1}) [${author(m)}${m.threadId ? L(' · numa thread', ' · in a thread') : ''}] ${m.text.trim().slice(0, 4000)}`),'',L(`Memórias sobre ${me}:`, `Memories about ${me}:`),...(memories.length ? memories.map((m) => `- [${m.id}] ${m.text}`) : [none]),@@ -150,6 +151,24 @@ export function parseConsolidation(text: string): { summary: string; ops: Op[] }return { summary: summary.trim(), ops }}+// A reply in a thread: the message that started it, then the replies before this one.+// The root goes in however old it is; the replies are capped like the conversation's window.+// What an agent reads before replying: the conversation's recent messages, threads included+// (every answer goes in the thread of what it answers, so the threads are the conversation),+// and the whole thread it replies in, however old. `until`: what the summary already covers.+export function contextWindow(db: Pick<Db, 'message' | 'recentMessages'>, before: Message, limit: number, until = 0): Message[] {+ const recent = db+ .recentMessages(before.conversationId, limit + 40)+ .filter((m) => m.id !== before.id && m.at <= before.at && m.at > until)+ .slice(-limit)+ if (!before.threadId) return recent+ const seen = new Set(recent.map((m) => m.id))+ const thread = [db.message(before.threadId), ...db.recentMessages(before.conversationId, limit + 40, before.threadId)].filter(+ (m): m is Message => !!m && m.id !== before.id && m.at <= before.at && !seen.has(m.id)+ )+ return [...recent, ...thread].sort((a, b) => a.at - b.at)+}+// For matching a new memory against forgotten and existing ones.export const normalize = (t: string): string =>t@@ -190,14 +209,10 @@ export class Memories {return rankMemories(out, query, limit)}- // What a turn sees of the conversation: the summary and every message after it.+ // What a turn sees of the conversation: the summary and every message after it,+ // outside threads. A reply in a thread sees the summary and that thread instead.window(conv: Conversation, before: Message): { summary?: string; messages: Message[] } {- const until = conv.summaryUntil ?? 0- const messages = this.deps.db- .recentMessages(conv.id, MAX_AFTER + 40)- .filter((m) => m.id !== before.id && m.at <= before.at && m.at > until)- .slice(-MAX_AFTER)- return { summary: conv.summary, messages }+ return { summary: conv.summary, messages: contextWindow(this.deps.db, before, MAX_AFTER, conv.summaryUntil ?? 0) }}// ---------- short term: consolidation ----------diff --git a/src/core/router.ts b/src/core/router.tsindex 96a6245..22cb844 100644--- a/src/core/router.ts+++ b/src/core/router.ts@@ -13,19 +13,21 @@ export const routerSystem = (): string =>L(['Você decide quais agentes de um chat de trabalho devem responder à última mensagem humana.',- 'Responda SOMENTE com JSON, sem texto em volta, no formato {"handles": ["..."], "reason": "..."}:',+ 'Responda SOMENTE com JSON, sem texto em volta, no formato {"handles": ["..."], "todos": false, "reason": "..."}:',`- "handles": de 0 a ${MAX_ROUTED} handles, só da lista de agentes; prefira 1.`,+ '- "todos": true quando a mensagem é pro grupo todo (um cumprimento, "pessoal", uma pergunta pra todos, uma apresentação): aí todos os agentes respondem.','- "reason": um motivo de até 12 palavras, em português.','Se a mensagem depende de um sistema externo (ex.: Linear, GitHub), prefira quem tem acesso a ele; se ninguém tem, escolha pelo papel.',- 'Lista vazia quando ninguém precisa responder: cumprimento solto, agradecimento, recado, conversa já encerrada.'+ 'Um cumprimento nunca fica sem resposta. Lista vazia (e "todos" falso) só quando ninguém precisa responder: agradecimento, recado, conversa já encerrada.'].join('\n'),['You decide which agents in a work chat should answer the last human message.',- 'Reply ONLY with JSON, no text around it, in the format {"handles": ["..."], "reason": "..."}:',+ 'Reply ONLY with JSON, no text around it, in the format {"handles": ["..."], "everyone": false, "reason": "..."}:',`- "handles": 0 to ${MAX_ROUTED} handles, only from the list of agents; prefer 1.`,+ '- "everyone": true when the message is for the whole group (a greeting, "everyone", a question for all, an introduction): then every agent answers.','- "reason": a reason of up to 12 words, in English.','If the message depends on an external system (e.g. Linear, GitHub), prefer whoever has access to it; if no one does, choose by role.',- "An empty list when no one needs to answer: a passing greeting, a thank-you, a note, a conversation that's already over."+ "A greeting never goes unanswered. An empty list (and \"everyone\" false) only when no one needs to answer: a thank-you, a note, a conversation that's already over."].join('\n'))@@ -43,12 +45,13 @@ export function describeAgent(a: Agent, connectors: Connector[] = []): string {export const REPLY_JSON = (): string => L('Responda só com o JSON.', 'Reply with the JSON only.')-export function routerPrompt(opts: { messages: Message[]; agents: Agent[]; me: string; connectors?: Connector[] }): string {- const { messages, agents, me, connectors = [] } = opts+// `thread`: the message that started the thread the last message is in; `messages` are then its replies.+export function routerPrompt(opts: { messages: Message[]; agents: Agent[]; me: string; connectors?: Connector[]; thread?: Message }): string {+ const { messages, agents, me, connectors = [], thread } = optsconst roster = agents.map((a) => `- ${a.handle}: ${describeAgent(a, connectors)}`)- const lines = messages- .filter((m) => m.text.trim() && m.author.kind !== 'system')- .slice(-ROUTER_HISTORY)+ const said = (m: Message): boolean => !!m.text.trim() && m.author.kind !== 'system'+ const recent = messages.filter(said).slice(-ROUTER_HISTORY)+ const lines = [...(thread && said(thread) ? [thread] : []), ...recent].map((m) => {const author =m.author.kind === 'me'@@ -62,7 +65,9 @@ export function routerPrompt(opts: { messages: Message[]; agents: Agent[]; me: sL('Agentes no canal:', 'Agents in the channel:'),...roster,'',- L('Conversa (a última é a que precisa de resposta):', 'Conversation (the last one is the one that needs an answer):'),+ thread+ ? L('Thread (a primeira mensagem abriu a thread; a última é a que precisa de resposta):', 'Thread (the first message started it; the last one is the one that needs an answer):')+ : L('Conversa (a última é a que precisa de resposta):', 'Conversation (the last one is the one that needs an answer):'),...lines,'',REPLY_JSON()@@ -80,7 +85,10 @@ export function parseRoute(text: string, agents: Agent[]): { agents: Agent[]; rereturn null}if (!data || typeof data !== 'object') return null- const { handles, reason } = data as { handles?: unknown; reason?: unknown }+ const { handles, reason, todos, everyone } = data as { handles?: unknown; reason?: unknown; todos?: unknown; everyone?: unknown }+ const why = typeof reason === 'string' ? reason.trim() : ''+ // A message for the whole group: every agent in the channel answers.+ if (todos === true || everyone === true) return { agents: [...agents], reason: why }if (!Array.isArray(handles)) return nullconst picked: Agent[] = []for (const h of handles) {@@ -88,7 +96,7 @@ export function parseRoute(text: string, agents: Agent[]): { agents: Agent[]; reconst a = agents.find((x) => x.handle.toLowerCase() === h.replace(/^@/, '').toLowerCase())if (a && !picked.includes(a)) picked.push(a)}- return { agents: picked.slice(0, MAX_ROUTED), reason: typeof reason === 'string' ? reason.trim() : '' }+ return { agents: picked.slice(0, MAX_ROUTED), reason: why }}export async function route(opts: {@@ -98,6 +106,7 @@ export async function route(opts: {agents: Agent[]me: stringconnectors?: Connector[]+ thread?: Messagecwd: string}): Promise<{ agents: Agent[]; reason: string; usage?: Usage; ms: number } | { error: string; usage?: Usage; ms: number }> {const started = Date.now()diff --git a/src/core/runs.ts b/src/core/runs.tsindex 4846c89..86e5a0d 100644--- a/src/core/runs.ts+++ b/src/core/runs.ts@@ -7,7 +7,7 @@ import type { CoreEvent } from '../shared/rpc'import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'import { ACCESS_REQUEST, CACHE_READ_WEIGHT, describeSchedule, workIn, ENGINES, ERRORS_STOP, usable, modelInfo, REPEAT_STOP, REPEAT_WARN, RUN_BUDGET_PCT, RUN_STALL_MINUTES, IMAGE_MIMES, MAX_IMAGE_BYTES, MAX_IMAGES_PER_MESSAGE, type Account, type Agent, type Approval, type Artifact, type ImageUpload, type Connector, type ConnectorTool, type Conversation, type EngineId, type Message, type Quota, type Receipt, type Routine, type Run, type RunStatus, type Settings, type Step, wikiAccess } from '../shared/types'import { HISTORY_LIMIT, mentioned, systemPrompt, transcriptBlocks } from './context'-import { BUSCAR_MEMORIAS, LEMBRAR, type Memories } from './memory'+import { BUSCAR_MEMORIAS, contextWindow, LEMBRAR, type Memories } from './memory'import { WIKI_TOOL_NAMES, WIKI_TOOLS, wikiCall, type Wiki } from './wiki'import { BROWSER_TOOL_NAMES, browserStep, browserTools, NAVEGADOR, type Browser } from './browser'import { APP_TOOL_NAMES, APPS, appStep, appTools, type DesktopApps } from './apps'@@ -71,7 +71,7 @@ export interface RunnerDeps {browser?: Pick<Browser, 'call' | 'approved'> // without it, no agent has a browserapps?: Pick<DesktopApps, 'call' | 'approved'> // without it, no agent uses the person's appsroutines?: Pick<Routines, 'schedule' | 'cancel' | 'forAgent'> // without it, agents can't schedule- notify?: (title: string, body: string, conversationId?: string, kind?: 'approval' | 'question' | 'done') => void+ notify?: (title: string, body: string, conversationId?: string, kind?: 'approval' | 'question' | 'done', threadId?: string) => void // threadId: a click opens that thread toojev?: { key(): Promise<string | undefined>; fetch?: typeof fetch } // the TypeSafe router, when chosen in settingsonBusy?: (busy: boolean) => void // some reply is running (the Mac shouldn't sleep) or none isonQuota?: (q: Quota) => void // the subscription's windows, as the CLI reports them@@ -142,15 +142,25 @@ export class Runner {// Saves the human message and decides who answers it: mentioned agents// first, then whoever asked a pending question, then the DM agent or the- // only agent in the channel, and otherwise the router.- async send(conversationId: string, text: string, images: ImageUpload[] = []): Promise<void> {+ // only agent in the channel, and otherwise the router. The answers, and+ // everything else it sets off, go in its thread (`threadId`, or its own).+ async send(conversationId: string, text: string, images: ImageUpload[] = [], threadId?: string): Promise<void> {const { db, emit } = this.depsconst conv = db.conversation(conversationId)const body = text.trim()const pictures = this.deps.dataDir ? images.filter((i) => IMAGE_MIMES.includes(i.mime)).slice(0, MAX_IMAGES_PER_MESSAGE) : []if (!conv || (!body && pictures.length === 0)) return-- const mine: Message = { id: randomUUID(), conversationId, author: { kind: 'me' }, text: body, at: Date.now() }+ // Threads are one level deep: replying to a reply goes in its thread. A root that isn't+ // in this conversation (or is gone) doesn't make one: the message goes to the conversation.+ const root = threadId ? db.message(threadId) : undefined+ const thread = root?.conversationId === conv.id ? (root.threadId ?? root.id) : undefined+ // A question an agent left waiting is answered by my next message in its thread. What I+ // write outside threads stays outside: it only answers a question that is outside too.+ const asked = this.pendingQuestion(conv.id, thread)++ const mine: Message = { id: randomUUID(), conversationId, author: { kind: 'me' }, text: body, at: Date.now(), ...(thread ? { threadId: thread } : {}) }+ // Every answer goes in the thread of what it answers: a message of mine outside one opens it.+ const replyIn = thread ?? mine.idfor (const img of pictures) this.keepImage(mine, img)db.saveMessage(mine)emit({ type: 'message', message: mine })@@ -158,7 +168,6 @@ export class Runner {const members = this.members(conv)let responders = mentioned(body, members).slice(0, MAX_MENTIONS)- const asked = this.pendingQuestion(conv.id)if (asked) {this.update(asked, { run: { ...asked.run!, status: 'done' } })const asker = members.find((a) => asked.author.kind === 'agent' && a.id === asked.author.id)@@ -166,21 +175,21 @@ export class Runner {}if (members.length === 0) {- this.post(conv.id, L('Ninguém está neste canal ainda. Adicione agentes na página de cada um (Canais) e mande de novo.', "No one is in this channel yet. Add agents on each one's page (Channels) and send it again."))+ this.post(conv.id, replyIn, L('Ninguém está neste canal ainda. Adicione agentes na página de cada um (Canais) e mande de novo.', "No one is in this channel yet. Add agents on each one's page (Channels) and send it again."))return}if (this.paused) {- this.post(conv.id, L('Os agentes estão pausados: ninguém responde até você retomar (botão no topo da barra lateral).', 'The agents are paused: no one answers until you resume (button at the top of the sidebar).'))+ this.post(conv.id, replyIn, L('Os agentes estão pausados: ninguém responde até você retomar (botão no topo da barra lateral).', 'The agents are paused: no one answers until you resume (button at the top of the sidebar).'))return}if (responders.length === 0) {if (conv.kind === 'dm' || members.length === 1) responders = memberselse if (members.length > 1) {- void this.routeAndRun(conv, members)+ void this.routeAndRun(conv, members, replyIn)return}}- for (const agent of responders) this.enqueue(() => this.execute(agent, conv, { depth: 1 }))+ for (const agent of responders) this.enqueue(() => this.execute(agent, conv, { depth: 1, threadId: replyIn }))}// An image I attached, kept in the artifact store with my message (no agent made it).@@ -243,7 +252,7 @@ export class Runner {].filter(Boolean).join('\n\n')- this.enqueue(() => this.execute(agent, conv, { depth: msg.run!.depth ?? 1, task, work: msg.run!.work }))+ this.enqueue(() => this.execute(agent, conv, { depth: msg.run!.depth ?? 1, task, work: msg.run!.work, threadId: msg.threadId }))}// Posts a routine's request in its conversation and runs its agent on it.@@ -340,15 +349,16 @@ export class Runner {return conv.members.map((id) => this.deps.db.agent(id)).filter((a): a is Agent => !!a && !a.archived)}- private pendingQuestion(conversationId: string): Message | undefined {+ // The question waiting for me where I write: in a thread, that thread's; outside, one outside threads.+ private pendingQuestion(conversationId: string, threadId?: string): Message | undefined {return this.deps.db- .recentMessages(conversationId, 50)+ .recentMessages(conversationId, 50, threadId ?? null).reverse().find((m) => m.run?.status === 'waiting_input')}- private post(conversationId: string, text: string, run?: Run): Message {- const m: Message = { id: randomUUID(), conversationId, author: { kind: 'system' }, text, at: Date.now(), run }+ private post(conversationId: string, threadId: string | undefined, text: string, run?: Run): Message {+ const m: Message = { id: randomUUID(), conversationId, author: { kind: 'system' }, text, at: Date.now(), run, ...(threadId ? { threadId } : {}) }this.deps.db.saveMessage(m)this.deps.emit({ type: 'message', message: m })return m@@ -360,16 +370,18 @@ export class Runner {this.deps.emit({ type: 'message', message: { ...m } })}- private async routeAndRun(conv: Conversation, members: Agent[]): Promise<void> {+ // The router reads the conversation, threads included, and the thread it picks for.+ private async routeAndRun(conv: Conversation, members: Agent[], threadId?: string): Promise<void> {const { db, engines } = this.depsthis.routing++- const note = this.post(conv.id, L('Escolhendo quem responde…', 'Picking who answers…'), { status: 'working', steps: [] })+ const note = this.post(conv.id, threadId, L('Escolhendo quem responde…', 'Picking who answers…'), { status: 'working', steps: [] })const fail = (why: string): void =>this.update(note, { text: L(`Não consegui escolher quem responde (${why}). Mencione um agente com **@nome**.`, `I couldn't pick who answers (${why}). Mention an agent with **@name**.`), run: undefined })try {const settings = await this.deps.settings()const input = {- messages: db.recentMessages(conv.id, 20),+ messages: [...new Map([...db.recentMessages(conv.id, 20), ...(threadId ? db.recentMessages(conv.id, 60, threadId) : [])].map((m) => [m.id, m])).values()].sort((a, b) => a.at - b.at),+ thread: threadId ? db.message(threadId) : undefined,agents: members,me: settings.workspaceName,connectors: this.deps.connectors?.list()@@ -406,7 +418,7 @@ export class Runner {const why = reason ? ` · ${reason}` : ''if (agents.length === 0) return void this.update(note, { text: `${L('Ninguém precisa responder', 'No one needs to answer')}${why}`, run: undefined })this.update(note, { text: `${L('Chamei', 'Called')} ${agents.map((a) => `**${a.name}**`).join(L(' e ', ' and '))}${why}`, run: undefined })- for (const agent of agents) this.enqueue(() => this.execute(agent, conv, { depth: 1 }))+ for (const agent of agents) this.enqueue(() => this.execute(agent, conv, { depth: 1, threadId: note.threadId }))}private enqueue(job: () => Promise<unknown>): void {@@ -443,7 +455,8 @@ export class Runner {return { model, account }}- private async execute(agent: Agent, conv: Conversation, opts: { depth: number; existing?: Message; task?: string; work?: string; routine?: boolean }): Promise<Message> {+ // `threadId`: the reply goes in that thread (an existing reply keeps its own).+ private async execute(agent: Agent, conv: Conversation, opts: { depth: number; existing?: Message; task?: string; work?: string; routine?: boolean; threadId?: string }): Promise<Message> {const { db, emit, engines } = this.depsconst settings = await this.deps.settings()agent = db.agent(agent.id) ?? agent // limits or instructions may have changed while queued@@ -455,7 +468,7 @@ export class Runner {let engineId: EngineId = model?.engine ?? 'claude'let engineLabel = `${ENGINES[engineId].label} · ${model?.label ?? agent.modelId}`- const msg: Message = opts.existing ?? { id: randomUUID(), conversationId: conv.id, author: { kind: 'agent', id: agent.id }, text: '', at: Date.now() }+ const msg: Message = opts.existing ?? { id: randomUUID(), conversationId: conv.id, author: { kind: 'agent', id: agent.id }, text: '', at: Date.now(), ...(opts.threadId ? { threadId: opts.threadId } : {}) }const started = Date.now()let stepStarted = startedconst thinking = (): Step => ({ id: randomUUID(), label: L('Pensando', 'Thinking'), detail: engineLabel, status: 'running' })@@ -533,10 +546,7 @@ export class Runner {const memory = this.deps.memoryconst { summary, messages: history } = memory?.window(db.conversation(conv.id) ?? conv, msg) ?? {summary: undefined,- messages: db- .recentMessages(conv.id, HISTORY_LIMIT + 40)- .filter((m) => m.id !== msg.id && m.at <= msg.at)- .slice(-HISTORY_LIMIT)+ messages: contextWindow(db, msg, HISTORY_LIMIT)}// What this reply counts toward: given (a chain, a routine's issue), or an issue named in the message it answers.const asked = [...history].reverse().find((m) => m.author.kind === 'me' || m.author.kind === 'routine')@@ -843,7 +853,7 @@ export class Runner {}stepStarted = Date.now()save()- this.deps.notify?.(L(`${agent.name} pede aprovação`, `${agent.name} asks for approval`), `${out.approval.detail}: ${out.approval.why}`, conv.id, 'approval')+ this.deps.notify?.(L(`${agent.name} pede aprovação`, `${agent.name} asks for approval`), `${out.approval.detail}: ${out.approval.why}`, conv.id, 'approval', msg.threadId)return textResult(L(`Pedido de aprovação criado, com o print da tela. O clique ainda NÃO aconteceu. Encerre sua resposta agora dizendo em uma frase o que pediu. Quando ${settings.workspaceName} decidir, você recebe o resultado numa nova mensagem.`,@@ -900,7 +910,7 @@ export class Runner {msg.run = { ...msg.run!, approvalId: approval.id, steps: [...close('done', { label: L('Pediu aprovação', 'Asked for approval'), detail: out.approval.detail }), thinking()] }stepStarted = Date.now()save()- this.deps.notify?.(L(`${agent.name} pede aprovação`, `${agent.name} asks for approval`), `${out.approval.detail}: ${out.approval.why}`, conv.id, 'approval')+ this.deps.notify?.(L(`${agent.name} pede aprovação`, `${agent.name} asks for approval`), `${out.approval.detail}: ${out.approval.why}`, conv.id, 'approval', msg.threadId)return textResult(L(`Pedido de aprovação criado. A ação ainda NÃO aconteceu. Encerre sua resposta agora dizendo em uma frase o que pediu. Quando ${settings.workspaceName} decidir, você recebe o resultado numa nova mensagem.`,@@ -943,7 +953,7 @@ export class Runner {emit({ type: 'approval', approval })msg.run = { ...msg.run!, approvalId: approval.id }addSteps({ id: randomUUID(), label: L('Pediu pra abrir a PR', 'Asked to open the PR'), detail: `${branch} → ${prArgs.base}`, status: 'done' })- this.deps.notify?.(L(`${agent.name} quer abrir uma PR`, `${agent.name} wants to open a PR`), `${repo}: ${title}`, conv.id, 'approval')+ this.deps.notify?.(L(`${agent.name} quer abrir uma PR`, `${agent.name} wants to open a PR`), `${repo}: ${title}`, conv.id, 'approval', msg.threadId)return textResult(L(`Pedido de PR criado. A PR ainda NÃO existe. Encerre sua resposta agora dizendo em uma frase o que vai na PR. Quando ${settings.workspaceName} aprovar, você recebe o link numa nova mensagem.`,@@ -978,7 +988,7 @@ export class Runner {emit({ type: 'approval', approval })msg.run = { ...msg.run!, approvalId: approval.id }addSteps({ id: randomUUID(), label: L('Pediu acesso', 'Asked for access'), detail: `${c.name} · ${nivel === 'read' ? L('ler', 'read') : L('ler e escrever', 'read and write')}`, status: 'done' })- this.deps.notify?.(L(`${agent.name} pede acesso ao ${c.name}`, `${agent.name} asks for access to ${c.name}`), why || (nivel === 'read' ? L('Pra ler.', 'To read.') : L('Pra ler e escrever.', 'To read and write.')), conv.id, 'approval')+ this.deps.notify?.(L(`${agent.name} pede acesso ao ${c.name}`, `${agent.name} asks for access to ${c.name}`), why || (nivel === 'read' ? L('Pra ler.', 'To read.') : L('Pra ler e escrever.', 'To read and write.')), conv.id, 'approval', msg.threadId)return textResult(L(`Pedido de acesso enviado. Encerre sua resposta agora dizendo em uma frase o que pediu e por quê. Se ${settings.workspaceName} liberar, você continua numa nova mensagem.`,@@ -1019,7 +1029,7 @@ export class Runner {emit({ type: 'approval', approval })msg.run = { ...msg.run!, approvalId: approval.id }addSteps({ id: randomUUID(), label: L('Pediu aprovação', 'Asked for approval'), detail, status: 'done' })- this.deps.notify?.(L(`${agent.name} pede aprovação`, `${agent.name} asks for approval`), `${toolLabel(current.name)} · ${hit.connector.name}${approval.why ? `: ${approval.why}` : ''}`, conv.id, 'approval')+ this.deps.notify?.(L(`${agent.name} pede aprovação`, `${agent.name} asks for approval`), `${toolLabel(current.name)} · ${hit.connector.name}${approval.why ? `: ${approval.why}` : ''}`, conv.id, 'approval', msg.threadId)return textResult(L(`Pedido de aprovação criado. A ação ainda NÃO foi executada. Encerre sua resposta agora dizendo em uma frase o que pediu. Quando ${settings.workspaceName} decidir, você recebe o resultado numa nova mensagem.`,@@ -1098,7 +1108,8 @@ export class Runner {const attached = this.deps.dataDir ? db.artifacts().filter((a) => a.agentId === '' && a.kind === 'image' && a.conversationId === conv.id && ids.has(a.messageId)) : []const names = new Map<string, string[]>()for (const a of attached) names.set(a.messageId, [...(names.get(a.messageId) ?? []), a.name])- const { blocks, blockOf } = transcriptBlocks({ agent, conversation: conv, messages: history, agents: db.agents(), me: settings.workspaceName, task, summary, images: names })+ const thread = msg.threadId ? db.message(msg.threadId) : undefined+ const { blocks, blockOf } = transcriptBlocks({ agent, conversation: conv, messages: history, agents: db.agents(), me: settings.workspaceName, task, summary, images: names, thread })const images: TurnImage[] = attached.slice(-MAX_TURN_IMAGES).flatMap((a) => (blockOf.has(a.messageId) ? [{ block: blockOf.get(a.messageId)!, path: join(this.deps.dataDir!, 'artifacts', a.id, a.name), mime: mimeOf(a.name) }] : []))@@ -1206,6 +1217,7 @@ export class Runner {const pct = `${Math.floor((usedNow / agent.limit) * 100)}%`this.post(conv.id,+ msg.threadId,L(`**${agent.name}** já usou ${pct} do limite do mês (${tokenCount(usedNow)} de ${tokenCount(agent.limit)} tokens). Dá pra aumentar na página dele.`,`**${agent.name}** has used ${pct} of the month's limit (${tokenCount(usedNow)} of ${tokenCount(agent.limit)} tokens). It can be raised on their page.`@@ -1214,7 +1226,9 @@ export class Runner {this.deps.notify?.(L(`${agent.name} usou ${pct} do limite do mês`, `${agent.name} used ${pct} of the month's limit`),L(`${tokenCount(usedNow)} de ${tokenCount(agent.limit)} tokens. Dá pra aumentar na página dele.`, `${tokenCount(usedNow)} of ${tokenCount(agent.limit)} tokens. It can be raised on their page.`),- conv.id+ conv.id,+ undefined,+ msg.threadId)}@@ -1249,8 +1263,8 @@ export class Runner {run: { ...base, status: question ? 'waiting_input' : approval ? 'waiting_approval' : 'done', steps: closeThinking('done', L('Respondeu', 'Replied')) }})// The Mac tells you when it's your turn: a question, or the end of the work (once, when no other agent takes it on).- if (question) this.deps.notify?.(L(`${agent.name} te perguntou`, `${agent.name} asked you`), question, conv.id, 'question')- else if (!approval && !this.chain(agent, conv, msg, opts.depth) && !opts.routine) this.deps.notify?.(L(`${agent.name} terminou`, `${agent.name} is done`), outcome(msg) || L('Respondeu na conversa.', 'Replied in the conversation.'), conv.id, 'done')+ if (question) this.deps.notify?.(L(`${agent.name} te perguntou`, `${agent.name} asked you`), question, conv.id, 'question', msg.threadId)+ else if (!approval && !this.chain(agent, conv, msg, opts.depth) && !opts.routine) this.deps.notify?.(L(`${agent.name} terminou`, `${agent.name} is done`), outcome(msg) || L('Respondeu na conversa.', 'Replied in the conversation.'), conv.id, 'done', msg.threadId)} else {// What happened and what to do; the CLI's own words go folded under it.const failure = error === null ? { text: L('O motor terminou sem resposta.', 'The engine ended without a reply.') } : friendly(thrown ?? error, { engine: ENGINES[engineId].label, doing: L('responder', 'replying') })@@ -1258,7 +1272,7 @@ export class Runner {}// Stopped short on its own (a loop, the limit, a failure): you'd want to know. Not when you stopped it.const st = msg.run?.status- if (!opts.routine && (st === 'failed' || st === 'limit_reached')) this.deps.notify?.(L(`${agent.name} parou`, `${agent.name} stopped`), outcome(msg), conv.id, 'done')+ if (!opts.routine && (st === 'failed' || st === 'limit_reached')) this.deps.notify?.(L(`${agent.name} parou`, `${agent.name} stopped`), outcome(msg), conv.id, 'done', msg.threadId)const updated = db.agent(agent.id)if (updated) emit({ type: 'agent', agent: updated })@@ -1432,7 +1446,7 @@ export class Runner {}})}- if (agent && conv && !agent.archived) this.enqueue(() => this.execute(agent, conv, { depth: 1, task, work: msg?.run?.work }))+ if (agent && conv && !agent.archived) this.enqueue(() => this.execute(agent, conv, { depth: 1, task, work: msg?.run?.work, threadId: msg?.threadId }))}async expireApprovals(): Promise<void> {@@ -1463,6 +1477,7 @@ export class Runner {this.execute(agent, conv, {depth: 1,work: asked.run?.work,+ threadId: asked.threadId,task: L(`${workspaceName} devolveu o controle do seu navegador. Continue de onde parou.`, `${workspaceName} handed your browser back. Pick up where you left off.`)}))@@ -1476,10 +1491,10 @@ export class Runner {const next = mentioned(msg.text, this.members(conv).filter((a) => a.id !== agent.id)).slice(0, MAX_MENTIONS)if (next.length === 0) return falseif (depth >= MAX_DEPTH) {- this.post(conv.id, L(`Parei a conversa entre agentes aqui: foram ${MAX_DEPTH} respostas seguidas. Mande uma mensagem pra continuar.`, `I stopped the conversation between agents here: ${MAX_DEPTH} replies in a row. Send a message to go on.`))+ this.post(conv.id, msg.threadId, L(`Parei a conversa entre agentes aqui: foram ${MAX_DEPTH} respostas seguidas. Mande uma mensagem pra continuar.`, `I stopped the conversation between agents here: ${MAX_DEPTH} replies in a row. Send a message to go on.`))return false}- for (const a of next) this.enqueue(() => this.execute(a, conv, { depth: depth + 1, work: msg.run?.work }))+ for (const a of next) this.enqueue(() => this.execute(a, conv, { depth: depth + 1, work: msg.run?.work, threadId: msg.threadId }))return true}}diff --git a/src/core/telegram.ts b/src/core/telegram.tsindex d55b285..9d80497 100644--- a/src/core/telegram.ts+++ b/src/core/telegram.ts@@ -36,7 +36,7 @@ export interface TelegramDeps {secrets: Pick<Secrets, 'get' | 'set'>decide(approvalId: string, decision: 'approved' | 'refused', reason?: string): Promise<void>approval(id: string): Approval | undefined- answer(conversationId: string, text: string): void // a reply to a question, as if I wrote it in the app+ answer(conversationId: string, text: string, threadId?: string): void // a reply to a question, as if I wrote it in the app (in its thread)changed(): void // the bot or the pairing changed: settings show itfetch?: Fetch}@@ -48,7 +48,7 @@ export class Telegram {private error?: stringprivate loop?: AbortControllerprivate offset = 0- private questions = new Map<number, string>() // Telegram message id → conversation it asked from+ private questions = new Map<number, { conversationId: string; threadId?: string }>() // Telegram message id → where it was askedconstructor(private deps: TelegramDeps) {}@@ -184,9 +184,9 @@ export class Telegram {return}if (m.chat.id !== this.chat.id) return- const conv = m.reply_to_message && this.questions.get(m.reply_to_message.message_id)- if (conv) {- this.deps.answer(conv, m.text)+ const asked = m.reply_to_message && this.questions.get(m.reply_to_message.message_id)+ if (asked) {+ this.deps.answer(asked.conversationId, m.text, asked.threadId)await this.send(L('Mandei a sua resposta.', 'I sent your answer.'), { reply_to_message_id: m.message_id })} else {await this.send(L('Pra responder a um agente, responda à mensagem da pergunta (deslize pro lado). Aprovações têm botões.', "To answer an agent, reply to the question's message (swipe it sideways). Approvals have buttons."))@@ -239,7 +239,7 @@ export class Telegram {L(`${agentName} pergunta (${where}):\n\n${msg.run.question}\n\nResponda a esta mensagem.`, `${agentName} asks (${where}):\n\n${msg.run.question}\n\nReply to this message.`),{ reply_markup: { force_reply: true, input_field_placeholder: L('Sua resposta', 'Your answer') } })- if (id) this.questions.set(id, msg.conversationId)+ if (id) this.questions.set(id, { conversationId: msg.conversationId, ...(msg.threadId ? { threadId: msg.threadId } : {}) })}async notice(title: string, body: string): Promise<void> {diff --git a/src/core/wiki-curator.ts b/src/core/wiki-curator.tsindex a2ad086..710f587 100644--- a/src/core/wiki-curator.ts+++ b/src/core/wiki-curator.ts@@ -171,11 +171,14 @@ export class WikiCurator {wiki.setMark(conversationId, last.at)}- // A message kept on purpose: with the one it answers, if it's a reply.+ // A message kept on purpose: with the one it answers, if it's a reply (in a thread, my last message there).async keepMessage(messageId: string): Promise<WikiChange[]> {const m = this.deps.db.message(messageId)if (!m) throw new Error(L('Essa mensagem não existe mais.', 'That message no longer exists.'))- const before = this.deps.db.messagesAfter(m.conversationId, 0).filter((x) => x.at < m.at && x.author.kind === 'me').at(-1)+ const before = this.deps.db+ .messagesAfter(m.conversationId, 0)+ .filter((x) => x.at < m.at && x.author.kind === 'me' && (x.threadId === m.threadId || x.id === m.threadId))+ .at(-1)return this.curate({ messages: before && m.author.kind !== 'me' ? [before, m] : [m], kind: 'message', conversationId: m.conversationId, force: true })}diff --git a/src/main/index.ts b/src/main/index.tsindex 33874e6..6aa3b67 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -77,7 +77,7 @@ type CoreRequest =| { type: 'open_path'; path: string }| { type: 'open_local'; path: string; how: 'open' | 'reveal' }| { type: 'wiki_dir'; path: string }- | { type: 'notify'; title: string; body: string; conversationId?: string; kind?: 'approval' | 'question' | 'done'; page?: 'skills'; sound?: boolean }+ | { type: 'notify'; title: string; body: string; conversationId?: string; threadId?: string; kind?: 'approval' | 'question' | 'done'; page?: 'skills'; sound?: boolean }| { type: 'login_item'; open: boolean }| { type: 'busy'; busy: boolean }| { type: 'lang'; lang: Lang }@@ -225,7 +225,7 @@ function handleCore(child: UtilityProcess, msg: CoreRequest): void {if (sound) chirp(sound)if (!Notification.isSupported()) returnconst n = new Notification({ title: msg.title, body: msg.body, silent: true, ...noteIcon() })- n.on('click', () => showWindow(msg.conversationId, msg.page))+ n.on('click', () => showWindow(msg.conversationId, msg.page, msg.threadId))n.show()} else if (msg.type === 'busy') {if (msg.busy && awakeBlocker === null) awakeBlocker = powerSaveBlocker.start('prevent-app-suspension')@@ -322,17 +322,17 @@ ipcMain.on('core:connect', (event) => {})// Brings the window back (closing it keeps the app and its routines running),-// optionally opening a conversation.+// optionally opening a conversation (and a thread in it).// The app's own window; agents' browsers are windows too, hidden, and never count as it.let mainWindow: BrowserWindow | null = null-function showWindow(conversationId?: string, page?: 'skills'): void {+function showWindow(conversationId?: string, page?: 'skills', threadId?: string): void {const win = mainWindow && !mainWindow.isDestroyed() ? mainWindow : createWindow()if (win.isMinimized()) win.restore()win.show()win.focus()if (!conversationId && !page) return- const go = (): void => (page ? win.webContents.send('navigate-page', page) : win.webContents.send('navigate', conversationId))+ const go = (): void => (page ? win.webContents.send('navigate-page', page) : win.webContents.send('navigate', conversationId, threadId))if (win.webContents.isLoading()) win.webContents.once('did-finish-load', go)else go()}diff --git a/src/preload/index.ts b/src/preload/index.tsindex ea4ac6b..219b4a3 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -12,9 +12,9 @@ contextBridge.exposeInMainWorld('tucano', {pickFolder: (): Promise<string | null> => ipcRenderer.invoke('pick-folder') as Promise<string | null>,// A picked file's path, so the core reads a big .zip in parts instead of through the page.pathOf: (file: File): string => webUtils.getPathForFile(file),- // A click on a notification opens its conversation.- onNavigate: (cb: (conversationId: string) => void): void => {- ipcRenderer.on('navigate', (_e, id: unknown) => typeof id === 'string' && cb(id))+ // A click on a notification opens its conversation, and the thread it's about.+ onNavigate: (cb: (conversationId: string, threadId?: string) => void): void => {+ ipcRenderer.on('navigate', (_e, id: unknown, thread: unknown) => typeof id === 'string' && cb(id, typeof thread === 'string' ? thread : undefined))},// …or a screen (a skill proposal opens Skills).onNavigatePage: (cb: (page: 'skills') => void): void => {diff --git a/src/renderer/src/components/Conversation.tsx b/src/renderer/src/components/Conversation.tsxindex ef77052..9acff5c 100644--- a/src/renderer/src/components/Conversation.tsx+++ b/src/renderer/src/components/Conversation.tsx@@ -19,6 +19,9 @@ import {modelById,navigate,openDm,+ openPanel,+ openThread,+ seeThread,openTuca,removeRoutine,retryRun,@@ -36,6 +39,7 @@ import {type Approval,type Conversation,type ImageUpload,+ type Author,type Message,type Step,IMAGE_MIMES,@@ -45,7 +49,7 @@ import {transcribe,voiceStatus} from '../store'-import { AgentAvatar, Icon, MeAvatar, duration, time, tokens, usd, useJustEnded } from './ui'+import { AgentAvatar, Icon, MeAvatar, ago, duration, time, tokens, usd, useJustEnded } from './ui'import { canRecord, NoSound, record, type Recording } from '../voice'import { useVoice, VoicePopover } from './VoiceSetup'import { ArtifactCard, BrowserCard, ServiceCard, SidePanel } from './Panel'@@ -110,6 +114,7 @@ export function ConversationView({ id }: { id: string }): ReactNode {})const messages = useStore((s) => s.messages.filter((m) => m.conversationId === id))const focus = useStore((s) => (s.view?.kind === 'conversation' && s.view.id === id ? s.view.message : undefined))+ const thread = useStore((s) => (s.panel?.kind === 'thread' ? s.panel.id : undefined))const [showSummary, setShowSummary] = useState(false)const firstChannel = useStore((s) => s.conversations.find((c) => c.kind === 'channel'))@@ -165,19 +170,33 @@ export function ConversationView({ id }: { id: string }): ReactNode {</div></header>- {showSummary && <SummaryPanel conv={conv} messages={messages} onClose={() => setShowSummary(false)} />}+ {showSummary && <SummaryPanel conv={conv} messages={messages.filter((m) => !m.threadId)} onClose={() => setShowSummary(false)} />}- <MessageList messages={messages} conversationId={id} empty={conv.kind === 'channel' && members.length === 0} focus={focus} />+ <MessageList messages={messages} conversationId={id} empty={conv.kind === 'channel' && members.length === 0} focus={focus} threads /><Composer conversationId={id} members={members} placeholder={dmAgent ? L(`Mensagem pra ${dmAgent.name}`, `Message ${dmAgent.name}`) : L(`Mensagem em #${title}`, `Message #${title}`)} /></section>- <SidePanel />+ {thread ? <ThreadPanel rootId={thread} conv={conv} title={conv.kind === 'channel' ? `#${title}` : title} members={members} /> : <SidePanel />}</div>)}-export function MessageList({ messages, conversationId, empty, focus }: { messages: Message[]; conversationId: string; empty?: boolean; focus?: string }): ReactNode {+const NO_REPLIES: Message[] = []++// `threads`: the timeline shows only what's outside threads, and each message can start one.+export function MessageList({ messages: all, conversationId, empty, focus, threads, lead }: { messages: Message[]; conversationId: string; empty?: boolean; focus?: string; threads?: boolean; lead?: ReactNode }): ReactNode {const ref = useRef<HTMLDivElement>(null)const stick = useRef(true)+ const { messages, replies } = useMemo(() => {+ if (!threads) return { messages: all, replies: undefined }+ const replies = new Map<string, Message[]>()+ for (const m of all) {+ if (!m.threadId) continue+ const list = replies.get(m.threadId)+ if (list) list.push(m)+ else replies.set(m.threadId, [m])+ }+ return { messages: all.filter((m) => !m.threadId), replies }+ }, [all, threads])// In a DM, whose it is (for the empty state).const dmName = useStore((s) => {const c = s.conversations.find((x) => x.id === conversationId)@@ -187,7 +206,7 @@ export function MessageList({ messages, conversationId, empty, focus }: { messag// Opened on a message (a routine's run, say): scroll to it and flash it once.useEffect(() => {const i = focus ? messages.findIndex((m) => m.id === focus) : -1- const el = i >= 0 ? (ref.current?.children[i] as HTMLElement | undefined) : undefined+ const el = i >= 0 ? (ref.current?.children[i + (lead ? 1 : 0)] as HTMLElement | undefined) : undefinedif (!el) returnstick.current = falseel.scrollIntoView({ block: 'center' })@@ -198,7 +217,8 @@ export function MessageList({ messages, conversationId, empty, focus }: { messag}, [focus, conversationId])useEffect(() => {- stick.current = true+ if (!lead) stick.current = true+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [conversationId])useLayoutEffect(() => {@@ -206,7 +226,16 @@ export function MessageList({ messages, conversationId, empty, focus }: { messagif (el && stick.current) el.scrollTop = el.scrollHeight})- if (messages.length === 0 && empty) {+ // A thread opens on the message that started it: the replies follow below.+ useLayoutEffect(() => {+ const el = ref.current+ if (!lead || !el) return+ el.scrollTop = 0+ stick.current = el.scrollHeight - el.clientHeight < 60+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [])++ if (messages.length === 0 && empty && !lead) {return (<div className="messages messages--empty"><div className="empty">@@ -221,7 +250,7 @@ export function MessageList({ messages, conversationId, empty, focus }: { messag)}- if (messages.length === 0) {+ if (messages.length === 0 && !lead) {return (<div className="messages messages--empty"><div className="empty">@@ -242,6 +271,7 @@ export function MessageList({ messages, conversationId, empty, focus }: { messagstick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 60}}>+ {lead}{messages.map((m, i) => {const prev = messages[i - 1]const grouped =@@ -252,7 +282,7 @@ export function MessageList({ messages, conversationId, empty, focus }: { messag!m.run &&m.author.kind !== 'system' &&m.author.kind !== 'routine'- return <MessageRow key={m.id} message={m} grouped={grouped} />+ return <MessageRow key={m.id} message={m} grouped={grouped} replies={replies && (replies.get(m.id) ?? NO_REPLIES)} />})}</div>)@@ -261,8 +291,11 @@ export function MessageList({ messages, conversationId, empty, focus }: { messagconst AGENT_PLUGINS = [remarkGfm, remarkLocalPaths]const keepLocalLinks = (url: string): string => (url.startsWith(LOCAL_LINK) ? url : defaultUrlTransform(url))-function MessageRow({ message, grouped }: { message: Message; grouped: boolean }): ReactNode {+// `replies`: in a timeline with threads, the replies to this message (none yet: empty).+function MessageRow({ message, grouped, replies }: { message: Message; grouped: boolean; replies?: Message[] }): ReactNode {const me = useStore((s) => s.me)+ // In the timeline (not as the thread's own heading), lit while its thread is open on the side.+ const threadOpen = useStore((s) => !!replies && s.panel?.kind === 'thread' && s.panel.id === message.id)const agent = useStore((s) => (message.author.kind === 'agent' ? agentById(s, message.author.id) : undefined))const approval = useStore((s) => (message.run?.approvalId ? s.approvals.find((a) => a.id === message.run!.approvalId) : undefined))const attached = useStore((s) => (message.author.kind === 'me' ? s.artifacts.filter((a) => a.messageId === message.id && a.agentId === '') : []))@@ -281,17 +314,17 @@ function MessageRow({ message, grouped }: { message: Message; grouped: boolean }return (<div className={`system-line ${message.run?.status === 'working' ? 'is-pending' : ''}`}><Icon name="spark" size={13} />- <Markdown>{message.text}</Markdown>+ <SystemText text={message.text} /><span className="muted">{time(message.at)}</span></div>)}- if (message.author.kind === 'routine') return <RoutineMessage message={message} />+ if (message.author.kind === 'routine') return <RoutineMessage message={message} replies={replies} />const name = agent ? agent.name : me.namereturn (- <article className={`msg ${agent ? 'msg--agent' : 'msg--me'} ${grouped ? 'msg--grouped' : ''}`}>+ <article className={`msg ${agent ? 'msg--agent' : 'msg--me'} ${grouped ? 'msg--grouped' : ''} ${threadOpen ? 'is-thread-open' : ''}`}><div className="msg__gutter">{!grouped && (agent ? <AgentAvatar agent={agent} size={34} busy={message.run?.status === 'working'} /> : <MeAvatar initials={me.initials} size={34} />)}</div>@@ -374,15 +407,20 @@ function MessageRow({ message, grouped }: { message: Message; grouped: boolean }{L(`Aumentar o limite de ${agent.name}`, `Raise ${agent.name}’s limit`)}</button>)}- {message.run?.status === 'done' && message.text.trim() && !message.run.wikiChanges?.length && <KeepInWiki messageId={message.id} />}- {message.run?.receipt && <ReceiptLine receipt={message.run.receipt} />}+ {(message.run?.receipt || (message.run?.status === 'done' && message.text.trim() && !message.run.wikiChanges?.length)) && (+ <div className="msg__meta">+ {message.run?.receipt && <ReceiptLine receipt={message.run.receipt} />}+ {message.run?.status === 'done' && message.text.trim() && !message.run.wikiChanges?.length && <KeepInWiki messageId={message.id} />}+ </div>+ )}+ {replies && <ThreadLink message={message} replies={replies} />}</div></article>)}// What a routine asked, posted at its time; the agent's reply comes next.-function RoutineMessage({ message }: { message: Message }): ReactNode {+function RoutineMessage({ message, replies }: { message: Message; replies?: Message[] }): ReactNode {const exists = useStore((s) => s.routines.some((r) => message.author.kind === 'routine' && r.id === message.author.id))const info = message.routinereturn (@@ -413,11 +451,172 @@ function RoutineMessage({ message }: { message: Message }): ReactNode {<div className="md"><Markdown remarkPlugins={[remarkGfm]} components={{ pre: CodeBlock, a: (p) => <WikiLink href={p.href}>{p.children}</WikiLink> }}>{highlightMentions(message.text)}</Markdown></div>+ {replies && <ThreadLink message={message} replies={replies} />}</div></article>)}+// A system note says what happened first ("Chamei **Iris**"), then why, after " · ": the+// headline reads at a glance, the why stays quiet (and whole on hover).+function SystemText({ text }: { text: string }): ReactNode {+ const [head = '', ...why] = text.split(' · ')+ return (+ <>+ <Markdown>{head}</Markdown>+ {why.length > 0 && (+ <span className="system-line__why" title={why.join(' · ').replace(/\*\*/g, '')}>+ {why.join(' · ').replace(/\*\*/g, '')}+ </span>+ )}+ </>+ )+}++const repliesLabel = (n: number): string => L(`${n} resposta${n === 1 ? '' : 's'}`, `${n} repl${n === 1 ? 'y' : 'ies'}`)++// Who took part in a thread, as faces: agents with their eyes (reading while they work), me with my initials.+function Faces({ authors, busy }: { authors: Author[]; busy: Set<string> }): ReactNode {+ const agents = useStore((s) => s.agents)+ const me = useStore((s) => s.me)+ return (+ <span className="thread-link__faces" aria-hidden>+ {authors.slice(0, 3).map((a) => {+ if (a.kind === 'agent') {+ const agent = agents.find((x) => x.id === a.id)+ return agent ? <AgentAvatar key={a.id} agent={agent} size={18} busy={busy.has(a.id)} /> : null+ }+ return <MeAvatar key="me" initials={me.initials} size={18} />+ })}+ </span>+ )+}++// "Reply in thread" on hover and, under a message with replies, a small pill: who took part,+// how many replies and when the last came (or who's replying, or what waits on me). It opens+// the thread on the side. With no reply yet, the system's note says what happened.+function ThreadLink({ message, replies }: { message: Message; replies: Message[] }): ReactNode {+ const agents = useStore((s) => s.agents)+ const open = useStore((s) => s.panel?.kind === 'thread' && s.panel.id === message.id)+ const said = replies.filter((m) => m.author.kind !== 'system')+ const done = said.filter((m) => m.run?.status !== 'working')+ const nameOf = (m: Message): string => {+ const a = m.author+ return a.kind === 'agent' ? (agents.find((x) => x.id === a.id)?.name ?? L('agente', 'agent')) : a.kind === 'me' ? L('você', 'you') : L('rotina', 'routine')+ }+ const key = (a: Author): string => (a.kind === 'agent' ? a.id : a.kind)+ // The latest to speak first: their face leads.+ const authors = [...new Map([...said].reverse().map((m) => [key(m.author), m.author])).values()]+ const working = said.filter((m) => m.run?.status === 'working')+ const busy = [...new Set(working.map(nameOf))]+ // What's waiting on me in there, now that answers live in threads: a question or an approval.+ const asks = said.findLast((m) => m.run?.status === 'waiting_input' || m.run?.status === 'waiting_approval')+ const note = said.length === 0 ? replies.findLast((m) => m.author.kind === 'system') : undefined+ const last = done.at(-1)+ // New: what others said after I last had the thread open (while it's open, nothing is).+ const seen = useStore((s) => s.threadSeen[message.id] ?? 0)+ const fresh = open ? 0 : done.filter((m) => m.author.kind !== 'me' && m.at > seen).length+ const go = (): void => openThread(message.id)+ return (+ <>+ <button className="icon-btn icon-btn--sm msg__reply" title={L('Responder na thread', 'Reply in thread')} aria-label={L('Responder na thread', 'Reply in thread')} onClick={go}>+ <Icon name="thread" size={13} />+ </button>+ {note && (+ <button className={`thread-note ${note.run?.status === 'working' ? 'is-pending' : ''}`} onClick={go} title={note.text.replace(/\*\*/g, '')}>+ <Icon name="spark" size={12} />+ <span>{note.text.replace(/\*\*/g, '').split(' · ')[0]}</span>+ </button>+ )}+ {said.length > 0 && (+ <button className={`thread-link ${open ? 'is-open' : ''} ${asks ? 'is-asking' : ''}`} onClick={go} aria-label={L(`Abrir a thread: ${repliesLabel(done.length)}`, `Open the thread: ${repliesLabel(done.length)}`)}>+ {fresh > 0 && <span className="thread-link__dot" aria-label={L(`${fresh} nova${fresh === 1 ? '' : 's'}`, `${fresh} new`)} />}+ <Faces authors={authors} busy={new Set(working.flatMap((m) => (m.author.kind === 'agent' ? [m.author.id] : [])))} />+ {asks ? (+ <span className="thread-link__asks">+ {asks.run!.status === 'waiting_input' ? L(`${nameOf(asks)} te perguntou algo`, `${nameOf(asks)} asked you something`) : L(`${nameOf(asks)} pede aprovação`, `${nameOf(asks)} asks for approval`)}+ </span>+ ) : busy.length > 0 ? (+ <span className="shimmer">{L(`${busy.join(' e ')} ${busy.length === 1 ? 'está' : 'estão'} respondendo…`, `${busy.join(' and ')} ${busy.length === 1 ? 'is' : 'are'} replying…`)}</span>+ ) : (+ <strong key={done.length} className="thread-link__count">+ {repliesLabel(done.length)}+ {fresh > 0 && <span className="thread-link__fresh">{L(` · ${fresh} nova${fresh === 1 ? '' : 's'}`, ` · ${fresh} new`)}</span>}+ </strong>+ )}+ {!busy.length && !asks && last && (+ <span className="thread-link__when">+ <span className="thread-link__ago">{ago(last.at)}</span>+ <span className="thread-link__see">{L('Ver thread', 'View thread')}</span>+ </span>+ )}+ <Icon name="chevron" size={12} />+ </button>+ )}+ </>+ )+}++// A thread on the side: the message that started it, set apart, then its replies and a+// field that answers there.+function ThreadPanel({ rootId, conv, title, members }: { rootId: string; conv: Conversation; title: string; members: Agent[] }): ReactNode {+ const root = useStore((s) => s.messages.find((m) => m.id === rootId))+ const replies = useStore((s) => s.messages.filter((m) => m.threadId === rootId))+ const agents = useStore((s) => s.agents)+ const said = replies.filter((m) => m.author.kind !== 'system' && m.run?.status !== 'working').length+ const replying = [...new Set(replies.flatMap((m) => (m.run?.status === 'working' && m.author.kind === 'agent' ? [m.author.id] : [])))].map((id) => agents.find((a) => a.id === id)?.name ?? L('agente', 'agent'))+ // Open, the thread is seen as it goes; closed, up to when it closed.+ const latest = replies.at(-1)?.at+ useEffect(() => {+ seeThread(rootId)+ return () => seeThread(rootId)+ }, [rootId, latest])+ // Esc closes it, unless something on top (a menu, a window) takes the key first.+ useEffect(() => {+ const onKey = (e: KeyboardEvent): void => {+ if (e.key !== 'Escape' || e.defaultPrevented || document.querySelector('.modal, .menu, .mention-menu, .lightbox')) return+ openPanel(null)+ }+ window.addEventListener('keydown', onKey)+ return () => window.removeEventListener('keydown', onKey)+ }, [])+ const lead = root && (+ <div className="thread__lead">+ <MessageRow message={root} grouped={false} />+ <div className="thread__divider">+ {replying.length > 0 ? (+ <span key="replying" className="shimmer">+ {L(`${replying.join(' e ')} ${replying.length === 1 ? 'está' : 'estão'} respondendo…`, `${replying.join(' and ')} ${replying.length === 1 ? 'is' : 'are'} replying…`)}+ </span>+ ) : (+ <span key={said}>{said > 0 ? repliesLabel(said) : L('Ainda sem respostas', 'No replies yet')}</span>+ )}+ </div>+ </div>+ )+ return (+ <aside className="side-panel side-panel--thread">+ <header className="side-panel__head">+ <Icon name="thread" size={14} />+ <strong className="side-panel__title">{L('Thread', 'Thread')}</strong>+ <span className="side-panel__where">{L(`em ${title}`, `in ${title}`)}</span>+ <span className="grow" />+ <button className="icon-btn" title={L('Fechar', 'Close')} aria-label={L('Fechar a thread', 'Close the thread')} onClick={() => openPanel(null)}>+ <Icon name="x" size={14} />+ </button>+ </header>+ {root?.conversationId === conv.id ? (+ <>+ <MessageList key={rootId} messages={replies} conversationId={conv.id} lead={lead} />+ <Composer conversationId={conv.id} threadId={rootId} members={members} placeholder={L('Responder na thread…', 'Reply in thread…')} />+ </>+ ) : (+ <p className="empty">{L('Essa mensagem não está mais aqui.', 'That message is no longer here.')}</p>+ )}+ </aside>+ )+}+// Fenced code block in a chat message, with a copy button on the top right.function CodeBlock({ children }: { children?: ReactNode }): ReactNode {const ref = useRef<HTMLPreElement>(null)@@ -898,8 +1097,8 @@ async function prepareImage(file: File): Promise<Attached | string> {}}-// One draft per conversation, kept while the app runs: leaving a channel doesn't-// lose the message you were typing.+// One draft per conversation (and per thread), kept while the app runs: leaving a+// channel doesn't lose the message you were typing.const drafts = new Map<string, { text: string; images: Attached[] }>()type DictationState = 'idle' | 'starting' | 'recording' | 'transcribing'@@ -1134,11 +1333,13 @@ function RecordingClock({ since }: { since: number }): ReactNode {)}-export function Composer({ conversationId, members, placeholder }: { conversationId: string; members: Agent[]; placeholder: string }): ReactNode {+// `threadId`: it answers in the thread that message started, not in the conversation.+export function Composer({ conversationId, threadId, members, placeholder }: { conversationId: string; threadId?: string; members: Agent[]; placeholder: string }): ReactNode {+ const key = threadId ?? conversationId // the draft's// The field starts with the conversation's draft, not empty: StrictMode (in dev) unmounts// and mounts again at once, and saving an empty first render would wipe the draft.- const [text, setText] = useState(() => drafts.get(conversationId)?.text ?? '')- const [images, setImages] = useState<Attached[]>(() => drafts.get(conversationId)?.images ?? [])+ const [text, setText] = useState(() => drafts.get(key)?.text ?? '')+ const [images, setImages] = useState<Attached[]>(() => drafts.get(key)?.images ?? [])const [note, setNote] = useState('')const [dragging, setDragging] = useState(false)const picker = useRef<HTMLInputElement>(null)@@ -1148,9 +1349,11 @@ export function Composer({ conversationId, members, placeholder }: { conversatioconst platform = useStore((s) => s.platform)const allAgents = useStore((s) => s.agents.filter(isTeam))const isDm = useStore((s) => s.conversations.find((c) => c.id === conversationId)?.kind === 'dm')- const working = useStore((s) => s.messages.filter((m) => m.conversationId === conversationId && m.author.kind === 'agent' && m.run?.status === 'working'))+ // Replies at work and questions asked here: in this thread, or outside threads.+ const here = (m: Message): boolean => m.conversationId === conversationId && m.threadId === threadId+ const working = useStore((s) => s.messages.filter((m) => here(m) && m.author.kind === 'agent' && m.run?.status === 'working'))const asker = useStore((s) => {- const q = s.messages.findLast((m) => m.conversationId === conversationId && m.run?.status === 'waiting_input')+ const q = s.messages.findLast((m) => here(m) && m.run?.status === 'waiting_input')return q?.author.kind === 'agent' ? agentById(s, q.author.id)?.name : undefined})@@ -1159,17 +1362,17 @@ export function Composer({ conversationId, members, placeholder }: { conversatioconst live = useRef({ text, images })live.current = { text, images }useEffect(() => {- const draft = drafts.get(conversationId)+ const draft = drafts.get(key)setText(draft?.text ?? '')setImages(draft?.images ?? [])setNote('')ref.current?.focus()return () => {const { text, images } = live.current- if (text.trim() || images.length) drafts.set(conversationId, { text, images })- else drafts.delete(conversationId)+ if (text.trim() || images.length) drafts.set(key, { text, images })+ else drafts.delete(key)}- }, [conversationId])+ }, [key])const addFiles = async (files: File[]): Promise<void> => {if (!files.length) return@@ -1186,9 +1389,12 @@ export function Composer({ conversationId, members, placeholder }: { conversatio}// A file dropped anywhere in the window comes here (and never opens in place of the app).+ // With a thread open there are two fields: a drop on the thread goes to its own.+ const inThread = !!threadIduseEffect(() => {let depth = 0const files = (e: DragEvent): boolean => !!e.dataTransfer?.types.includes('Files')+ const mine = (e: DragEvent): boolean => !!(e.target instanceof Element && e.target.closest('.side-panel--thread')) === inThreadconst enter = (e: DragEvent): void => {if (!files(e)) returndepth++@@ -1205,7 +1411,7 @@ export function Composer({ conversationId, members, placeholder }: { conversatioe.preventDefault()depth = 0setDragging(false)- void addFiles([...(e.dataTransfer?.files ?? [])])+ if (mine(e)) void addFiles([...(e.dataTransfer?.files ?? [])])}window.addEventListener('dragenter', enter)window.addEventListener('dragover', over)@@ -1217,7 +1423,7 @@ export function Composer({ conversationId, members, placeholder }: { conversatiowindow.removeEventListener('dragleave', leave)window.removeEventListener('drop', drop)}- }, [])+ }, [inThread])useLayoutEffect(() => {const el = ref.current@@ -1264,16 +1470,17 @@ export function Composer({ conversationId, members, placeholder }: { conversatio})el?.focus()}- const [voice, voiceControls] = useDictation(insert, setNote, conversationId)+ const [voice, voiceControls] = useDictation(insert, setNote, key)const submit = (): void => {if (!text.trim() && images.length === 0) returnsendMessage(conversationId,text,- images.map(({ name, mime, data }) => ({ name, mime, data }))+ images.map(({ name, mime, data }) => ({ name, mime, data })),+ threadId)- drafts.delete(conversationId)+ drafts.delete(key)setText('')setImages([])setNote('')@@ -1282,7 +1489,7 @@ export function Composer({ conversationId, members, placeholder }: { conversatioreturn (<div className="composer-wrap">- {dragging && (+ {dragging && !inThread && (<div className="drop-overlay"><div className="drop-overlay__card"><Icon name="image" size={28} />@@ -1382,7 +1589,7 @@ export function Composer({ conversationId, members, placeholder }: { conversatio}}/><span className={`composer__hint ${note ? 'composer__hint--warn' : ''}`}>- {note || (members[0]?.kind === 'tuca' ? L('Nada é criado sem você', 'Nothing is created without you') : isDm ? L(`${members[0]?.name ?? 'O agente'} sempre responde aqui`, `${members[0]?.name ?? 'The agent'} always replies here`) : L('Quem estiver no canal responde · pra chamar alguém, use @', 'Whoever is in the channel replies · to call on someone, use @'))}+ {note || (members[0]?.kind === 'tuca' ? L('Nada é criado sem você', 'Nothing is created without you') : threadId ? L('Fica nesta thread · @ chama alguém', 'Stays in this thread · @ calls someone') : isDm ? L(`${members[0]?.name ?? 'O agente'} sempre responde aqui`, `${members[0]?.name ?? 'The agent'} always replies here`) : L('Quem estiver no canal responde · pra chamar alguém, use @', 'Whoever is in the channel replies · to call on someone, use @'))}</span>{working.length > 0 ? (<button className="btn btn--sm" onClick={() => working.forEach((m) => stopRun(m.id))}>diff --git a/src/renderer/src/components/Panel.tsx b/src/renderer/src/components/Panel.tsxindex 79577f8..552c9cd 100644--- a/src/renderer/src/components/Panel.tsx+++ b/src/renderer/src/components/Panel.tsx@@ -368,7 +368,7 @@ export function SidePanel(): ReactNode {const browser = useStore((s) => (s.panel?.kind === 'browser' ? browserOf(s, s.panel.agentId) : undefined))const browserName = useStore((s) => (s.panel?.kind === 'browser' ? agentById(s, s.panel.agentId)?.name : undefined))const [reload, setReload] = useState(0)- if (!panel) return null+ if (!panel || panel.kind === 'thread') return null // a thread is drawn by its conversationconst title = artifact?.title ?? service?.name ?? (panel.kind === 'browser' ? L(`Navegador de ${browserName ?? 'agente'}`, `${browserName ?? 'Agent'}'s browser`) : '')return (diff --git a/src/renderer/src/components/ui.tsx b/src/renderer/src/components/ui.tsxindex 35697ce..8207f49 100644--- a/src/renderer/src/components/ui.tsx+++ b/src/renderer/src/components/ui.tsx@@ -118,7 +118,8 @@ const PATHS: Record<string, ReactNode> = {),volume: <path d="M4 9v6h4l5 4V5L8 9H4ZM16.5 8.5a5 5 0 0 1 0 7M19 6a8.5 8.5 0 0 1 0 12" />,trash: <path d="M4 7h16M9 7V4h6v3M6 7l1 13h10l1-13M10 11v6M14 11v6" />,- archive: <path d="M3 4h18v4H3V4ZM5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M10 12h4" />+ archive: <path d="M3 4h18v4H3V4ZM5 8v11a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1V8M10 12h4" />,+ thread: <path d="M4 5h16v11H10l-4 4v-4H4V5ZM8 9h8M8 12h5" />}export type IconName = keyof typeof PATHSdiff --git a/src/renderer/src/rpc.ts b/src/renderer/src/rpc.tsindex 6365cd1..287c547 100644--- a/src/renderer/src/rpc.ts+++ b/src/renderer/src/rpc.ts@@ -8,7 +8,7 @@ declare global {connect: () => voidpickFolder: () => Promise<string | null>pathOf?: (file: File) => string // a dropped or picked file's path on this computer (desktop only)- onNavigate: (cb: (conversationId: string) => void) => void+ onNavigate: (cb: (conversationId: string, threadId?: string) => void) => voidonNavigatePage?: (cb: (page: 'skills') => void) => void // desktop onlyonCoreDown?: (cb: () => void) => void // desktop only: a browser reloads on its ownviewing: (conversationId: string | null) => voiddiff --git a/src/renderer/src/store.ts b/src/renderer/src/store.tsindex 858bb65..3edee81 100644--- a/src/renderer/src/store.ts+++ b/src/renderer/src/store.ts@@ -63,6 +63,7 @@ export type View =export interface State {ready: boolean+ threadSeen: Record<string, number> // thread root id → when I last had it open (what came after is new)navOpen: boolean // on a phone, the sidebar slid in over the viewview: View | nullme: { name: string; initials: string }@@ -100,7 +101,8 @@ export interface Toast {export type Dialog = { kind: 'members' | 'rename' | 'topic'; id: string } | { kind: 'archived' | 'new-channel' | 'search' } | { kind: 'oauth'; id: string; url: string }-export type Panel = { kind: 'artifact'; id: string } | { kind: 'service'; agentId: string; name: string } | { kind: 'browser'; agentId: string }+// `thread`: the replies to a message (its id), next to the conversation.+export type Panel = { kind: 'artifact'; id: string } | { kind: 'service'; agentId: string; name: string } | { kind: 'browser'; agentId: string } | { kind: 'thread'; id: string }const initials = (name: string): string =>name@@ -110,8 +112,19 @@ const initials = (name: string): string =>.map((w) => w[0]!.toUpperCase()).join('') || 'EU'+// When each thread was last seen, in this window's storage: only a convenience, so it may be empty.+const SEEN_KEY = 'tucano.threadSeen'+const loadSeen = (): Record<string, number> => {+ try {+ return JSON.parse(localStorage.getItem(SEEN_KEY) ?? '{}') as Record<string, number>+ } catch {+ return {}+ }+}+let state: State = {ready: false,+ threadSeen: loadSeen(),wikiRev: 0,voiceRev: 0,navOpen: false,@@ -284,7 +297,10 @@ function apply(e: CoreEvent): void {}export async function start(): Promise<void> {- window.tucano.onNavigate((id) => navigate({ kind: 'conversation', id }))+ window.tucano.onNavigate((id, thread) => {+ navigate({ kind: 'conversation', id })+ if (thread) openThread(thread)+ })window.tucano.onNavigatePage?.((page) => navigate({ kind: page }))window.tucano.onCoreDown?.(() => {disconnect()@@ -496,8 +512,9 @@ export const setChannelMembers = (id: string, agentIds: string[]): Promise<void>export const deleteConversation = (id: string): Promise<void> => call('deleteConversation', { id })export const markRead = (id: string): void => set((s) => ({ ...s, conversations: s.conversations.map((c) => (c.id === id ? { ...c, unread: 0 } : c)) }))-export const sendMessage = (conversationId: string, text: string, images: ImageUpload[] = []): void => {- if (text.trim() || images.length) void fire(L('Não consegui enviar a mensagem.', "I couldn't send the message."), 'sendMessage', { conversationId, text, ...(images.length ? { images } : {}) })+// `threadId`: a reply in the thread that message started.+export const sendMessage = (conversationId: string, text: string, images: ImageUpload[] = [], threadId?: string): void => {+ if (text.trim() || images.length) void fire(L('Não consegui enviar a mensagem.', "I couldn't send the message."), 'sendMessage', { conversationId, text, ...(images.length ? { images } : {}), ...(threadId ? { threadId } : {}) })}export const stopRun = (messageId: string): void => void fire(L('Não consegui parar a resposta.', "I couldn't stop the reply."), 'stopRun', { messageId })@@ -528,6 +545,16 @@ export function patchAgent(agentId: string, patch: Partial<Agent>): void {export const localPath = (messageId: string, path: string): Promise<LocalInfo | null> => call('localPath', { messageId, path })export const openLocal = (messageId: string, path: string, how: 'open' | 'reveal'): void => void call('openLocal', { messageId, path, how })export const openPanel = (panel: Panel | null): void => set((s) => ({ ...s, panel }))+export const openThread = (messageId: string): void => openPanel({ kind: 'thread', id: messageId })+// I've seen this thread up to now (it's open, or was just closed).+export const seeThread = (rootId: string): void =>+ set((s) => {+ const threadSeen = { ...s.threadSeen, [rootId]: Date.now() }+ try {+ localStorage.setItem(SEEN_KEY, JSON.stringify(threadSeen))+ } catch {}+ return { ...s, threadSeen }+ })export const openLightbox = (items: { url: string; title: string; video?: boolean }[], index: number): void => set((s) => ({ ...s, lightbox: { items, index } }))export const closeLightbox = (): void => set((s) => ({ ...s, lightbox: null }))export const moveLightbox = (by: number): void =>diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.cssindex 02038d4..e4fc33a 100644--- a/src/renderer/src/styles.css+++ b/src/renderer/src/styles.css@@ -975,6 +975,7 @@ h3 {max-width: none;}.msg {+ position: relative;display: grid;grid-template-columns: 34px 1fr;gap: 12px;@@ -2346,6 +2347,297 @@ h3 {.side-panel--browser {width: min(56%, 920px);}+/* a thread: the message that started it, set apart, then its replies */+.side-panel--thread {+ width: min(42%, 560px);+}+.side-panel__where {+ font-size: 12.5px;+ color: var(--text-3);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.side-panel--thread .messages {+ padding-top: 14px;+}+.side-panel--thread .msg {+ padding-inline: 16px;+}+.side-panel--thread .system-line {+ padding: 4px 16px 4px 62px;+}+.side-panel--thread .composer-wrap {+ padding-inline: 16px;+}+/* The root sits on the panel's paper, like the conversation it came from. */+.thread__lead {+ display: grid;+ gap: 4px;+}+.thread__lead > .msg {+ margin-inline: 10px;+ padding: 10px 12px;+ width: auto;+ border-radius: var(--radius-lg);+ background: var(--panel);+ box-shadow: var(--shadow-panel);+ animation: none;+}+.thread__lead > .msg .msg__reply {+ display: none;+}+/* Mine too reads as the thread's heading here: my face and name, no bubble. */+.thread__lead > .msg--me {+ grid-template-columns: 34px 1fr;+}+.thread__lead > .msg--me .msg__gutter {+ display: block;+}+.thread__lead > .msg--me .msg__head {+ display: flex;+}+.thread__lead > .msg--me .msg__body {+ justify-self: stretch;+ max-width: none;+ align-items: stretch;+}+.thread__lead > .msg--me .md {+ background: none;+ padding: 0;+ border-radius: 0;+}+.thread__divider {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 10px 26px 6px;+ font-size: 11.5px;+ font-weight: 500;+ color: var(--text-3);+ font-variant-numeric: tabular-nums;+}+.thread__divider::before,+.thread__divider::after {+ content: '';+ flex: 1;+ height: 1px;+ background: var(--border);+}+.thread__divider span {+ --pop-scale: 0.9;+ --pop-y: 0;+ animation: pop var(--dur-base) var(--ease-out) backwards;+}++/* A router's note: what it did, and why, quietly, on one line. */+.system-line__why {+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: var(--text-3);+}+.system-line__why::before {+ content: '· ';+}+.system-line > p {+ flex-shrink: 0;+}+.system-line > .muted {+ margin-left: auto;+ flex-shrink: 0;+}++/* A reply's receipt and "Guardar na wiki", on one quiet line that shows on hover. */+.msg__meta {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ column-gap: 14px;+ margin-top: 4px;+}+.msg__meta .receipt,+.msg__meta .wiki-keep {+ margin: 0;+}++/* The message whose thread is open on the side, lit, so the two sides read as one. */+.msg.is-thread-open::before {+ content: '';+ position: absolute;+ inset: 0 12px;+ z-index: -1;+ border-radius: var(--radius-lg);+ background: var(--accent-soft);+ opacity: 0.55;+ animation: fade var(--dur-enter) var(--ease-out) backwards;+}+.msg {+ isolation: isolate;+}++/* "Reply in thread" shows on hover: by my bubble, or at the corner of an agent's reply. */+.msg__reply {+ position: absolute;+ top: 4px;+ right: 4px;+ opacity: 0;+ transition: var(--transition-ui);+}+.msg--me .msg__body {+ position: relative;+}+.msg--me .msg__reply {+ top: 6px;+ right: calc(100% + 6px);+}+.msg:hover .msg__reply,+.msg__reply:focus-visible {+ opacity: 1;+}+@media (hover: none) {+ .msg__reply {+ opacity: 1;+ }+}+.thread-link {+ --rise: 3px;+ animation: rise var(--dur-enter) var(--ease-out) backwards;+ display: inline-flex;+ align-items: center;+ gap: 7px;+ margin-top: 6px;+ padding: 3px 9px 3px 3px;+ border: 1px solid var(--border);+ border-radius: 999px;+ background: var(--panel);+ box-shadow: 0 1px 2px rgba(60, 40, 20, 0.04);+ font-size: 12px;+ line-height: 18px;+ color: var(--text-2);+ white-space: nowrap;+ transition: var(--transition-ui);+}+.thread-link:hover,+.thread-link.is-open {+ border-color: var(--border-strong);+ color: var(--text);+}+.thread-link.is-open {+ background: var(--accent-soft);+ border-color: transparent;+}+.thread-link__faces {+ display: inline-flex;+}+.thread-link__faces > * {+ border-radius: 28%;+ box-shadow: 0 0 0 2px var(--panel);+}+.thread-link.is-open .thread-link__faces > * {+ box-shadow: none;+}+.thread-link__faces > * + * {+ margin-left: -5px;+}+.thread-link__count {+ color: var(--accent);+ font-weight: 600;+ /* Keyed by the count: each new reply pops it in. */+ --pop-scale: 0.85;+ --pop-y: 0;+ animation: pop var(--dur-enter) var(--ease-spring) backwards;+}+.thread-link__when {+ display: inline-grid;+ color: var(--text-3);+}+/* "há 2 min" gives way to "Ver thread" on hover, in the same spot. */+.thread-link__ago,+.thread-link__see {+ grid-area: 1 / 1;+ transition:+ opacity var(--dur-fast) var(--ease-out),+ transform var(--dur-fast) var(--ease-out);+}+.thread-link__see {+ opacity: 0;+ transform: translateY(3px);+ color: var(--text);+}+.thread-link:hover .thread-link__ago {+ opacity: 0;+ transform: translateY(-3px);+}+.thread-link:hover .thread-link__see {+ opacity: 1;+ transform: none;+}+.thread-link > .icon {+ margin-left: -3px;+ color: var(--text-3);+ transition: transform var(--dur-fast) var(--ease-out);+}+.thread-link:hover > .icon {+ transform: translateX(2px);+ color: var(--text-2);+}+/* New since I last had it open: a dot, and how many. */+.thread-link__dot {+ width: 7px;+ height: 7px;+ margin: 0 -2px 0 3px;+ border-radius: 50%;+ background: var(--accent);+ --pop-scale: 0.4;+ --pop-y: 0;+ animation: pop var(--dur-enter) var(--ease-spring) backwards;+}+.thread-link__fresh {+ font-weight: 500;+}+/* Something waits on me in there: said in the warning's color, with a quiet pulse. */+.thread-link.is-asking {+ border-color: transparent;+ background: var(--warn-soft);+}+.thread-link__asks {+ color: var(--warn);+ font-weight: 600;+}+.thread-link__asks::before {+ content: '';+ display: inline-block;+ width: 6px;+ height: 6px;+ margin-right: 6px;+ border-radius: 50%;+ background: currentColor;+ vertical-align: 1px;+ animation: fade-pulse var(--dur-loop) var(--ease-in-out) infinite;+}+/* With no reply yet, what the system did, small and quiet. */+.thread-note {+ --rise: 3px;+ animation: rise var(--dur-enter) var(--ease-out) backwards;+ display: inline-flex;+ align-items: center;+ gap: 6px;+ margin-top: 5px;+ padding: 2px 6px;+ border-radius: 6px;+ font-size: 12px;+ color: var(--text-3);+ transition: var(--transition-ui);+}+.thread-note:hover {+ background: var(--hover);+ color: var(--text-2);+}+.thread-note.is-pending span {+ animation: fade-pulse var(--dur-loop) var(--ease-in-out) infinite;+}.live-badge {display: inline-flex;align-items: center;diff --git a/src/shared/rpc.ts b/src/shared/rpc.tsindex 17490d5..b5d4a6e 100644--- a/src/shared/rpc.ts+++ b/src/shared/rpc.ts@@ -23,7 +23,7 @@ export interface Snapshot {export interface Api {snapshot(): SnapshotartifactText(p: { id: string }): string | null // a text file an agent showed (Markdown, CSV, code), for the side panel- sendMessage(p: { conversationId: string; text: string; images?: ImageUpload[] }): void+ sendMessage(p: { conversationId: string; text: string; images?: ImageUpload[]; threadId?: string }): void // threadId: a reply in the thread that message startedstopRun(p: { messageId: string }): voidretryRun(p: { messageId: string }): voidcontinueRun(p: { messageId: string }): void // a reply paused at its budget goes ondiff --git a/src/shared/types.ts b/src/shared/types.tsindex 5999d9a..69fae03 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -200,6 +200,7 @@ export interface Message {at: numberrun?: Runroutine?: RoutineRun // set on the message a routine posts (author kind 'routine')+ threadId?: string // a reply in a thread: the id of the message that started it (threads are one level deep)}// Dictation with whisper-cli. Unset paths are looked for in the usual places.diff --git a/test/jev.test.ts b/test/jev.test.tsindex 2347803..34eae32 100644--- a/test/jev.test.ts+++ b/test/jev.test.ts@@ -40,7 +40,7 @@ describe('Jev router', () => {const body = api.body()expect(body.model).toBe('jev-latest')expect(body.questions.who.type).toBe('choice')- expect(Object.keys(body.questions.who.criteria)).toEqual(['lia', 'nina', '__ninguem'])+ expect(Object.keys(body.questions.who.criteria)).toEqual(['lia', 'nina', '__todos', '__ninguem'])expect(body.state).toContain('[Edu] o build quebrou')})@@ -49,6 +49,10 @@ describe('Jev router', () => {expect(await routeJev({ key: 'k', messages, agents: [lia, nina], me: 'Edu', fetch: typesafe({ lia: 0.2, nina: 0.1, __ninguem: 0.7 }).f })).toMatchObject({ agents: [], reason: 'Jev, 70%' })})+ it('calls every agent when the message is for the whole group, like a greeting', async () => {+ expect(await routeJev({ key: 'k', messages, agents: [lia, nina, theo], me: 'Edu', fetch: typesafe({ lia: 0.1, nina: 0.1, theo: 0.05, __todos: 0.75 }).f })).toMatchObject({ agents: [lia, nina, theo], reason: 'Jev, 75%' })+ })+it('says what went wrong instead of guessing', async () => {expect(await routeJev({ key: 'k', messages, agents: [lia], me: 'Edu', fetch: typesafe(401).f })).toMatchObject({ error: 'a chave do TypeSafe não vale mais' })expect(await routeJev({ key: 'k', messages, agents: [lia], me: 'Edu', fetch: typesafe({ ghost: 0.9 }).f })).toMatchObject({ error: 'o TypeSafe escolheu alguém fora do canal' })diff --git a/test/router.test.ts b/test/router.test.tsindex 43c28bd..04ae8dc 100644--- a/test/router.test.ts+++ b/test/router.test.ts@@ -32,6 +32,12 @@ describe('parseRoute', () => {expect(parseRoute('{"handles":[],"reason":"cumprimento"}', team)).toEqual({ agents: [], reason: 'cumprimento' })})+ it('calls every agent when the message is for the whole group, like a greeting, past the cap of two', () => {+ const three = [...team, agent('a3', 'theo', 'Dados')]+ expect(parseRoute('{"handles":[],"todos":true,"reason":"cumprimento pro grupo"}', three)).toEqual({ agents: three, reason: 'cumprimento pro grupo' })+ expect(parseRoute('{"handles":["lia"],"everyone":true,"reason":"greeting"}', three)?.agents).toEqual(three)+ })+it('drops unknown handles and duplicates, and caps at two', () => {const three = [...team, agent('a3', 'theo', 'Dados')]expect(parseRoute('{"handles":["ghost","lia","lia","nina","theo"],"reason":""}', three)?.agents).toEqual([lia, nina])diff --git a/test/runner.test.ts b/test/runner.test.tsindex aaab12e..5b3463d 100644--- a/test/runner.test.ts+++ b/test/runner.test.ts@@ -284,8 +284,8 @@ describe('ask_user through the gateway', () => {expect(asked?.run?.steps.map((s) => s.label)).toEqual(['Pensou', 'Perguntou a você', 'Respondeu'])expect(claude.turns[0]?.mcpUrl).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/mcp\/[a-f0-9]{48}$/)- // No mention and two agents in the channel, but Lia asked: she answers, not the router.- await r.send('c1', 'até sexta')+ // No mention and two agents in the channel, but Lia asked in this thread: she answers, not the router.+ await r.send('c1', 'até sexta', [], asked!.threadId)await r.idle()expect(db.message(asked!.id)?.run?.status).toBe('done')const replies = agentMessages()diff --git a/test/telegram.test.ts b/test/telegram.test.tsindex ef26f30..e478832 100644--- a/test/telegram.test.ts+++ b/test/telegram.test.ts@@ -42,7 +42,7 @@ describe('Telegram', () => {let store: Map<string, string>let tg: Telegramlet decided: [string, string, string | undefined][]- let answered: [string, string][]+ let answered: [string, string, string?][]let approvals: Map<string, Approval>beforeEach(async () => {@@ -58,7 +58,7 @@ describe('Telegram', () => {approvals.set(id, { ...approvals.get(id)!, state: d })},approval: (id) => approvals.get(id),- answer: (conv, text) => answered.push([conv, text]),+ answer: (conv, text, thread) => answered.push(thread ? [conv, text, thread] : [conv, text]),changed: () => {},fetch: api.f})@@ -129,6 +129,15 @@ describe('Telegram', () => {expect(answered).toEqual([['c1', 'Sexta que vem']])})+ it("a reply to a question asked in a thread goes back to that thread", async () => {+ await pair()+ const question: Message = { id: 'm2', conversationId: 'c1', threadId: 'root', author: { kind: 'agent', id: 'a1' }, text: '', at: 0, run: { status: 'waiting_input', steps: [], question: 'Qual o prazo?' } }+ await tg.questionAsked(question, 'PM', '#simula-oab')+ api.push({ message: { message_id: 7, chat: me, text: 'Amanhã', reply_to_message: { message_id: api.sent.at(-1)!.id } } })+ await settle()+ expect(answered).toEqual([['c1', 'Amanhã', 'root']])+ })+it("a long notice arrives whole, in as many messages as it takes, split between lines", async () => {await pair()const lines = Array.from({ length: 120 }, (_, i) => `- Item ${i + 1}: ${'texto '.repeat(8).trim()}`)diff --git a/test/threads.test.ts b/test/threads.test.tsnew file mode 100644index 0000000..fbf8eb8--- /dev/null+++ b/test/threads.test.ts@@ -0,0 +1,300 @@+import { mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { DatabaseSync } from 'node:sqlite'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import type { Agent, Author, EngineId, Message, Settings } from '../src/shared/types'+import { Db } from '../src/core/db'+import { fakeEngine } from '../src/core/engines/fake'+import type { Engine, Turn } from '../src/core/engines/types'+import { Gateway } from '../src/core/gateway'+import { consolidationPrompt, MAX_AFTER, Memories, memorySystem } from '../src/core/memory'+import { routerSystem } from '../src/core/router'+import { Runner } from '../src/core/runs'++const ready = { installed: true, loggedIn: true }+const agent = (id: string, handle: string, extra: Partial<Agent> = {}): Agent => ({+ id, name: handle[0]!.toUpperCase() + handle.slice(1), handle, role: '', color: 'sky', instructions: '', modelId: 'sonnet', effort: 'low',+ limit: 1_000_000, used: 0, grants: {}, memory: 'auto', computer: false, archived: false, ...extra+})++let db: Db+let settings: Settings+let gateway: Gateway+let turns: Turn[]+let notes: { conversationId?: string; kind?: string; threadId?: string }[]+let memory: Memories++function runner(opts: { reply?: (t: Turn) => string; memory?: boolean } = {}): Runner {+ const base = fakeEngine('claude', { delayMs: 1, reply: opts.reply })+ const claude: Engine = { id: 'claude', run: (t) => (turns.push(t), base.run(t)) }+ const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex', { delayMs: 1 }), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }+ const workDir = mkdtempSync(join(tmpdir(), 'ad-work-'))+ memory = new Memories({ db, engines, settings: async () => settings, emit: () => {}, workDir })+ return new Runner({+ db,+ engines,+ settings: async () => settings,+ emit: () => {},+ workDir,+ gateway,+ ...(opts.memory ? { memory } : {}),+ notify: (_t, _b, conversationId, kind, threadId) => void notes.push({ conversationId, kind, threadId })+ })+}++let clock = 1_000_000+function put(conversationId: string, author: Author, text: string, threadId?: string): Message {+ const m: Message = { id: `m${clock}`, conversationId, author, text, at: clock++, ...(threadId ? { threadId } : {}) }+ db.saveMessage(m)+ return m+}++const agentTurns = (): Turn[] => turns.filter((t) => t.system !== routerSystem() && t.system !== memorySystem())+const replies = (): Message[] => db.messages().filter((m) => m.author.kind === 'agent')+const mine = (): Message[] => db.messages().filter((m) => m.author.kind === 'me')++beforeEach(async () => {+ db = new Db(join(mkdtempSync(join(tmpdir(), 'ad-db-')), 'test.db'))+ turns = []+ notes = []+ settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }+ db.saveAgent(agent('a1', 'lia', { role: 'Engenharia' }))+ db.saveAgent(agent('a2', 'theo', { role: 'Dados' }))+ db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'] })+ db.createConversation({ id: 'c1', kind: 'channel', name: 'lancamento', members: ['a1', 'a2'] })+ gateway = new Gateway()+ await gateway.start()+})++afterEach(async () => {+ await gateway.stop()+})++describe('sending into a thread', () => {+ it('my message and the reply it sets off carry the thread; a reply to a reply goes in the same thread', async () => {+ const root = put('d1', { kind: 'me' }, 'Vamos lançar sexta?')+ const r = runner()+ await r.send('d1', 'e o texto do post?', [], root.id)+ await r.idle()+ expect(mine().at(-1)?.threadId).toBe(root.id)+ expect(replies().map((m) => m.threadId)).toEqual([root.id])+ expect(notes.at(-1)).toEqual({ conversationId: 'd1', kind: 'done', threadId: root.id })++ // Answering the agent's reply (itself in the thread) stays in the thread: one level only.+ await r.send('d1', 'manda outra versão', [], replies()[0]!.id)+ await r.idle()+ expect(mine().at(-1)?.threadId).toBe(root.id)+ expect(replies().every((m) => m.threadId === root.id)).toBe(true)+ })++ it('a message outside threads opens one, and the answer goes in it', async () => {+ const r = runner()+ await r.send('d1', 'quais as notícias de IA?')+ await r.idle()+ expect(mine().at(-1)?.threadId).toBeUndefined()+ expect(replies().map((m) => m.threadId)).toEqual([mine().at(-1)!.id])+ })++ it('a root from another conversation does not make a thread: the message opens its own', async () => {+ const elsewhere = put('c1', { kind: 'me' }, 'outro canal')+ const r = runner()+ await r.send('d1', 'oi', [], elsewhere.id)+ await r.idle()+ expect(mine().at(-1)?.threadId).toBeUndefined()+ expect(replies()[0]?.threadId).toBe(mine().at(-1)!.id)+ })+})++describe("what the agent sees", () => {+ it('in a thread: the summary, the recent conversation and the whole thread, however old', async () => {+ const root = put('c1', { kind: 'me' }, 'RAIZ: o plano de lançamento')+ put('c1', { kind: 'agent', id: 'a1' }, 'RESPOSTA ANTIGA na thread', root.id)+ db.setSummary('c1', 'RESUMO DO CANAL', root.at + 5) // the summary already covers the thread's start+ clock += 10+ put('c1', { kind: 'me' }, 'OUTRO ASSUNTO depois')+ const r = runner({ memory: true })+ await r.send('c1', '@lia e a data?', [], root.id)+ await r.idle()++ const prompt = agentTurns()[0]!.prompt+ expect(prompt).toContain('RESUMO DO CANAL')+ expect(prompt).toContain('Você está respondendo numa thread em #lancamento, aberta por Edu.')+ expect(prompt).toContain('RAIZ: o plano de lançamento')+ expect(prompt).toContain('RESPOSTA ANTIGA na thread')+ expect(prompt).toContain('OUTRO ASSUNTO depois')+ expect(prompt).toContain('@lia e a data?')+ expect(prompt.indexOf('RAIZ')).toBeLessThan(prompt.indexOf('RESPOSTA ANTIGA'))+ })++ it("a new message: the agent reads what was said in the earlier threads, so it doesn't start from zero", async () => {+ const root = put('d1', { kind: 'me' }, 'as 3 notícias de IA?')+ put('d1', { kind: 'agent', id: 'a1' }, 'NOTÍCIAS: IPO, buyouts, busca', root.id)+ for (const withMemory of [false, true]) {+ turns = []+ const r = runner({ memory: withMemory })+ await r.send('d1', 'e sobre a Apple?')+ await r.idle()+ const prompt = agentTurns()[0]!.prompt+ expect(prompt).toContain('NOTÍCIAS: IPO, buyouts, busca')+ }+ })+})++describe('who answers in a thread', () => {+ it('in a DM, the DM agent, with no mention', async () => {+ const root = put('d1', { kind: 'me' }, 'pergunta solta')+ const r = runner()+ await r.send('d1', 'e aí?', [], root.id)+ await r.idle()+ expect(replies().map((m) => [(m.author as { id: string }).id, m.threadId])).toEqual([['a1', root.id]])+ })++ it('in a channel, the router reads the conversation and the thread, and its note and the reply stay in it', async () => {+ put('c1', { kind: 'me' }, 'CANAL: bom dia pra todos')+ const root = put('c1', { kind: 'me' }, 'RAIZ: precisamos da métrica de retenção')+ const r = runner()+ await r.send('c1', 'qual a média da semana?', [], root.id)+ await r.idle()++ const routed = turns.find((t) => t.system === routerSystem())!.prompt+ expect(routed).toContain('Thread (a primeira mensagem abriu a thread')+ expect(routed).toContain('RAIZ: precisamos da métrica')+ expect(routed).toContain('qual a média da semana?')+ expect(replies().map((m) => [(m.author as { id: string }).id, m.threadId])).toEqual([['a2', root.id]])+ expect(db.messages().find((m) => m.author.kind === 'system')).toMatchObject({ threadId: root.id, text: expect.stringContaining('Chamei **Theo**') as string })+ })+})++describe('questions in threads', () => {+ it("a question waits in its thread: my next message there answers it; another thread or outside threads doesn't", async () => {+ const root = put('c1', { kind: 'me' }, 'RAIZ')+ const other = put('c1', { kind: 'me' }, 'OUTRA RAIZ')+ const r = runner()+ await r.send('c1', '@lia me pergunte o que faltar', [], root.id)+ await r.idle()+ const asked = replies()[0]!+ expect(asked).toMatchObject({ threadId: root.id, run: { status: 'waiting_input' } })+ expect(notes.at(-1)).toMatchObject({ kind: 'question', threadId: root.id })++ // A reply in another thread doesn't answer it.+ await r.send('c1', '@theo e aqui?', [], other.id)+ await r.idle()+ expect(db.message(asked.id)?.run?.status).toBe('waiting_input')++ // Nor does a new subject written outside threads: it stays outside, in a thread of its own.+ await r.send('c1', '@theo assunto novo: revisa o PR 50')+ await r.idle()+ const outside = mine().at(-1)!+ expect(outside.threadId).toBeUndefined()+ expect(db.message(asked.id)?.run?.status).toBe('waiting_input')+ expect(replies().at(-1)).toMatchObject({ threadId: outside.id, author: { id: 'a2' } })++ // My next message in its thread does, back to Lia.+ await r.send('c1', 'até sexta', [], root.id)+ await r.idle()+ expect(mine().at(-1)?.threadId).toBe(root.id)+ expect(db.message(asked.id)?.run?.status).toBe('done')+ expect(replies().at(-1)).toMatchObject({ threadId: root.id, author: { id: 'a1' } })+ })++ it('a question outside threads (from before them) is still answered outside', async () => {+ const r = runner()+ const asked = put('c1', { kind: 'agent', id: 'a1' }, 'Qual o prazo?')+ db.saveMessage({ ...asked, run: { status: 'waiting_input', depth: 1, steps: [] } })+ await r.send('c1', 'até sexta')+ await r.idle()+ expect(db.message(asked.id)?.run?.status).toBe('done')+ expect(replies().at(-1)).toMatchObject({ author: { id: 'a1' } })+ })+})++describe('what a thread message sets off stays in the thread', () => {+ it('chained mentions between agents, and the note that stops them', async () => {+ const root = put('c1', { kind: 'me' }, 'RAIZ')+ const r = runner({ reply: (t) => (t.system.startsWith('Você é Lia') ? '@theo, sua vez' : '@lia, sua vez') })+ await r.send('c1', '@lia começa', [], root.id)+ await r.idle()+ expect(replies().map((m) => [m.run?.depth, m.threadId])).toEqual([+ [1, root.id],+ [2, root.id],+ [3, root.id]+ ])+ expect(db.messages().at(-1)).toMatchObject({ author: { kind: 'system' }, threadId: root.id, text: expect.stringContaining('Parei a conversa entre agentes') as string })+ })++ it('the notes for an empty channel and for paused agents', async () => {+ db.createConversation({ id: 'c2', kind: 'channel', name: 'vazio', members: [] })+ const empty = put('c2', { kind: 'me' }, 'RAIZ')+ const r = runner()+ await r.send('c2', 'alguém?', [], empty.id)+ expect(db.messages().at(-1)).toMatchObject({ author: { kind: 'system' }, threadId: empty.id, text: expect.stringContaining('Ninguém está neste canal') as string })++ const root = put('d1', { kind: 'me' }, 'RAIZ')+ r.setPaused(true)+ await r.send('d1', 'oi', [], root.id)+ expect(db.messages().at(-1)).toMatchObject({ author: { kind: 'system' }, threadId: root.id, text: expect.stringContaining('pausados') as string })+ })++ it('trying again, continuing a paused reply and a handed-back browser', async () => {+ const root = put('d1', { kind: 'me' }, 'RAIZ')+ const run = (status: 'failed' | 'paused' | 'waiting_input'): Message['run'] => ({ status, depth: 1, steps: [] })+ const failed = put('d1', { kind: 'agent', id: 'a1' }, '', root.id)+ db.saveMessage({ ...failed, run: run('failed') })+ const paused = put('d1', { kind: 'agent', id: 'a1' }, 'metade', root.id)+ db.saveMessage({ ...paused, run: run('paused') })+ const r = runner()++ r.retry(failed.id)+ await r.idle()+ expect(db.message(failed.id)).toMatchObject({ threadId: root.id, run: { status: 'done' } })++ await r.continue(paused.id)+ await r.idle()+ expect(replies().at(-1)).toMatchObject({ threadId: root.id, run: { status: 'done' } })++ const asked = put('d1', { kind: 'agent', id: 'a1' }, 'entra pra mim?', root.id)+ db.saveMessage({ ...asked, run: run('waiting_input') })+ await r.handedBack('a1')+ await r.idle()+ expect(replies().at(-1)).toMatchObject({ threadId: root.id, run: { status: 'done' } })+ expect(replies()).toHaveLength(5) // retried in place, the paused one and its continuation, the question and the reply after it+ })+})++describe('the database', () => {+ it('an existing database gains thread_id, and messages round-trip it', () => {+ const file = join(mkdtempSync(join(tmpdir(), 'ad-db-')), 'old.db')+ // A database from before threads: the schema one migration back, with a message in it.+ new Db(file).close()+ const raw = new DatabaseSync(file)+ const { user_version } = raw.prepare('PRAGMA user_version').get() as { user_version: number }+ raw.exec(`DROP INDEX messages_by_thread; ALTER TABLE messages DROP COLUMN thread_id; PRAGMA user_version = ${user_version - 1};`)+ raw.exec("INSERT INTO conversations (id, kind, name, created_at) VALUES ('c1', 'channel', 'geral', 1)")+ raw.exec("INSERT INTO messages (id, conversation_id, author_kind, text, at) VALUES ('old', 'c1', 'me', 'antes das threads', 1)")+ raw.close()++ const reopened = new Db(file)+ expect(reopened.message('old')).toMatchObject({ text: 'antes das threads', threadId: undefined })+ reopened.saveMessage({ id: 'r1', conversationId: 'c1', author: { kind: 'me' }, text: 'na thread', at: 2, threadId: 'old' })+ expect(reopened.message('r1')?.threadId).toBe('old')+ expect(reopened.recentMessages('c1', 10, 'old').map((m) => m.id)).toEqual(['r1'])+ expect(reopened.recentMessages('c1', 10, null).map((m) => m.id)).toEqual(['old'])+ expect(reopened.recentMessages('c1', 10).map((m) => m.id)).toEqual(['old', 'r1'])+ reopened.close()+ })+})++describe('memory keeps what was said in threads', () => {+ it('consolidation folds thread replies into the summary, marked', async () => {+ const root = put('c1', { kind: 'me' }, 'RAIZ da thread')+ put('c1', { kind: 'me' }, 'ZEBRA é o cupom', root.id)+ for (let i = 1; i < MAX_AFTER + 10; i++) put('c1', i % 2 ? { kind: 'agent', id: 'a1' } : { kind: 'me' }, `mensagem ${i}`)+ runner({ memory: true })+ await memory.consolidate('c1')+ expect(db.conversation('c1')!.summary).toContain('ZEBRA')+ const prompt = turns.find((t) => t.system === memorySystem())!.prompt+ expect(prompt).toContain('[Edu · numa thread] ZEBRA é o cupom')+ expect(consolidationPrompt({ messages: [{ ...root, threadId: undefined }], me: 'Edu', agents: [], memories: [], forgotten: [] })).toContain('[Edu] RAIZ')+ })+})