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 in the conversation again, and let each conversation choose threads (#126)
Eduardo Machado1be8610c91d3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e9a9d5e..5fa36b3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,10 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht## [Unreleased]+### Changed++- **Answers come in the conversation again, and threads are a choice of each conversation.** Since 0.2.10 every message opened a thread with its answers. Now a channel or a DM answers in the conversation, like a chat, unless its settings say **In threads, one per message**: then each message opens a thread with its answers, as before. The settings open from the conversation's name at its top or from its menu in the sidebar, and hold a channel's name and topic too; a new channel asks where its agents answer. A thread you open by hand, with a message's reply button, works either way, and the threads you already have stay as they are. An answer in the conversation reads the conversation and the message that opened each thread; what was said inside a thread it looks up when it needs it, as it does from another thread.+### Fixed- **A thread opens at its latest message,** like in Slack, instead of at the message that started it: a long thread no longer has to be scrolled all the way down to see where it is. Scrolling up still stays put when a reply comes in.diff --git a/src/core/context.ts b/src/core/context.tsindex 31340c6..735cb6d 100644--- a/src/core/context.ts+++ b/src/core/context.ts@@ -339,17 +339,21 @@ export function transcriptBlocks(opts: TranscriptOpts): { blocks: string[]; bloc? L(`por uma rotina de ${me}`, `by a routine of ${me}'s`): L('pelo app', 'by the app')// A thread is a conversation of its own: the others reach it only when looked up.+ const lookUp = L(+ `Se ${me} falar de outra conversa, ou de algo combinado antes que não está aqui nem nas memórias, procure com buscar_threads e leia com ler_thread.`,+ `If ${me} mentions another conversation, or something agreed before that isn't here or in the memories, look it up with buscar_threads and read it with ler_thread.`+ )const apart = searchable- ? L(- ` Ela é uma conversa à parte: você não vê as outras threads de ${where}. Se ${me} falar de outra conversa, ou de algo combinado antes que não está aqui nem nas memórias, procure com buscar_threads e leia com ler_thread.`,- ` It's a conversation of its own: you don't see the other threads of ${where}. If ${me} mentions another conversation, or something agreed before that isn't here or in the memories, look it up with buscar_threads and read it with ler_thread.`- )+ ? thread+ ? ` ${L(`Ela é uma conversa à parte: você não vê as outras threads de ${where}.`, `It's a conversation of its own: you don't see the other threads of ${where}.`)} ${lookUp}`+ : ` ${L('As threads ficam à parte: daqui você só vê a mensagem que abriu cada uma.', 'Threads are kept apart: from here you only see the message that started each one.')} ${lookUp}`: ''const head = [summary?.trim() &&(thread? `${L('Resumo do começo desta thread (as mensagens mais antigas dela não vão inteiras)', "Summary of this thread's beginning (its oldest messages don't go in full)")}:\n${summary.trim()}`: `${L(`Resumo do que veio antes em ${where}`, `Summary of what came before in ${where}`)}:\n${summary.trim()}`),+ !thread && apart.trim(),thread? L(`Você está respondendo numa thread em ${where}, aberta ${by}.${apart} Abaixo, a mensagem que abriu a thread e as respostas dela, das mais antigas pras mais novas:`,diff --git a/src/core/db.ts b/src/core/db.tsindex 5334482..46de774 100644--- a/src/core/db.ts+++ b/src/core/db.ts@@ -253,6 +253,9 @@ const MIGRATIONS = [`,`ALTER TABLE messages ADD COLUMN thread_summary TEXT;+ `,+ `+ ALTER TABLE conversations ADD COLUMN threads INTEGER;`]@@ -409,7 +412,8 @@ export class Db {summary: r['summary'] ? str(r['summary']) : undefined,summaryUntil: r['summary_until'] ? Number(r['summary_until']) : undefined,summaryAt: r['summary_at'] ? Number(r['summary_at']) : undefined,- ...(r['wiki_capture'] === 0 ? { wikiCapture: false } : {})+ ...(r['wiki_capture'] === 0 ? { wikiCapture: false } : {}),+ ...(r['threads'] === 1 ? { threads: true } : {})}))}@@ -425,7 +429,7 @@ export class Db {createConversation(c: Omit<Conversation, 'unread'>): void {this.tx(() => {- this.db.prepare('INSERT INTO conversations (id, kind, name, topic, created_at) VALUES (?, ?, ?, ?, ?)').run(c.id, c.kind, c.name, c.topic ?? null, Date.now())+ this.db.prepare('INSERT INTO conversations (id, kind, name, topic, threads, created_at) VALUES (?, ?, ?, ?, ?, ?)').run(c.id, c.kind, c.name, c.topic ?? null, c.threads ? 1 : null, Date.now())for (const m of c.members) this.db.prepare('INSERT INTO members (conversation_id, agent_id) VALUES (?, ?)').run(c.id, m)})}@@ -439,6 +443,11 @@ export class Db {this.db.prepare('UPDATE conversations SET wiki_capture = ? WHERE id = ?').run(on ? null : 0, id)}+ // On: answers go in threads. Off, in the conversation, is the default (stored as null).+ setThreads(id: string, on: boolean): void {+ this.db.prepare('UPDATE conversations SET threads = ? WHERE id = ?').run(on ? 1 : null, id)+ }+setTopic(id: string, topic: string | undefined): void {this.db.prepare('UPDATE conversations SET topic = ? WHERE id = ?').run(topic ?? null, id)}diff --git a/src/core/index.ts b/src/core/index.tsindex 949a5a2..e30aeb7 100644--- a/src/core/index.ts+++ b/src/core/index.ts@@ -798,12 +798,12 @@ const api: Api = {emit({ type: 'conversation_removed', id })},- createChannel: ({ name }) => {+ createChannel: ({ name, threads }) => {const clean = channelName(name)if (!clean) throw new Error(L('Dê um nome ao canal.', 'Give the channel a name.'))if (db.conversations().some((c) => c.kind === 'channel' && c.name === clean)) throw new Error(L(`Já existe o canal #${clean}.`, `There's already a #${clean} channel.`))const id = randomUUID()- db.createConversation({ id, kind: 'channel', name: clean, members: [] })+ db.createConversation({ id, kind: 'channel', name: clean, members: [], ...(threads ? { threads } : {}) })emitConversations([id])return id},@@ -1083,6 +1083,11 @@ const api: Api = {const c = db.conversation(conversationId)if (c) emit({ type: 'conversation', conversation: c })},+ setThreads: ({ conversationId, on }) => {+ db.setThreads(conversationId, on)+ const c = db.conversation(conversationId)+ if (c) emit({ type: 'conversation', conversation: c })+ },setWikiDir: async ({ dir }) => {const next = dir?.trim() || wikiHomeif (!existsSync(next)) throw new Error(L('Essa pasta não existe.', "That folder doesn't exist."))diff --git a/src/core/memory.ts b/src/core/memory.tsindex c0bcc80..b66b9d3 100644--- a/src/core/memory.ts+++ b/src/core/memory.ts@@ -194,16 +194,18 @@ function digests(db: Pick<Db, 'message'>, recent: Message[], except?: string): T// What a reply reads of the conversation. In a thread, only that thread: the message that// opened it and its newest `limit` replies, with the thread's summary when older ones are// left out. The other threads aren't in it (an agent looks them up with buscar_threads);-// `threads` digests them for the router. Outside threads (a routine, a conversation from-// before them): the recent messages after `until`, what the conversation's summary covers.+// `threads` digests them for the router. Outside threads (a conversation that answers in it,+// a routine): its recent messages after `until`, what the conversation's summary covers, and of+// a thread only the message that opened it; what was said inside is looked up the same way.export function contextWindow(db: Pick<Db, 'message' | 'recentMessages'>,before: Message,limit: number,until = 0): { messages: Message[]; threads: ThreadDigest[]; summary?: string } {- const recent = db.recentMessages(before.conversationId, limit + 40).filter((m) => m.id !== before.id && m.at <= before.at && m.at > until)- if (!before.threadId) return { messages: recent.slice(-limit), threads: [] }+ const here = (m: Message): boolean => m.id !== before.id && m.at <= before.at && m.at > until+ if (!before.threadId) return { messages: db.recentMessages(before.conversationId, limit + 40, null).filter(here).slice(-limit), threads: [] }+ const recent = db.recentMessages(before.conversationId, limit + 40).filter(here)const root = db.message(before.threadId)const replies = db.recentMessages(before.conversationId, limit + 2, before.threadId).filter((m) => m.id !== before.id && m.at <= before.at)const omitted = replies.length > limitdiff --git a/src/core/runs.ts b/src/core/runs.tsindex 2e60b74..b6a3538 100644--- a/src/core/runs.ts+++ b/src/core/runs.ts@@ -154,7 +154,8 @@ 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. The answers, and- // everything else it sets off, go in its thread (`threadId`, or its own).+ // everything else it sets off, go in its thread (`threadId`, or its own when+ // the conversation answers in threads) or else in the conversation.async send(conversationId: string, text: string, images: ImageUpload[] = [], threadId?: string): Promise<void> {const { db, emit } = this.depsconst conv = db.conversation(conversationId)@@ -170,8 +171,9 @@ export class Runner {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.id+ // An answer goes in the thread of what it answers. A message of mine outside one opens it+ // only where the conversation answers in threads; elsewhere the answers follow in the conversation.+ const replyIn = thread ?? (conv.threads ? mine.id : undefined)for (const img of pictures) this.keepImage(mine, img)db.saveMessage(mine)emit({ type: 'message', message: mine })@@ -565,8 +567,9 @@ export class Runner {// Past the prompt's budget, the older memories are searched instead: the tool shows up only then.const promptMemories = memory?.forPrompt(agent)const canSearch = !!this.deps.gateway && !!promptMemories?.searchable- // A thread sees only itself: the other threads, of the conversations this agent is in, are looked up.- const canSeekThreads = !!this.deps.gateway && !!msg.threadId+ // A thread sees only itself, and the conversation only what's outside threads: the other+ // threads, of the conversations this agent is in, are looked up.+ const canSeekThreads = !!this.deps.gateway && (!!msg.threadId || db.threadRoots(conv.id).size > 0)const myConversations = (): Conversation[] => db.conversations().filter((c) => c.members.includes(agent.id))// The Tuca proposes agents; nobody else does.const builds = !!this.deps.gateway && agent.kind === 'tuca'diff --git a/src/renderer/src/components/Conversation.tsx b/src/renderer/src/components/Conversation.tsxindex 91ab8e3..474fdd8 100644--- a/src/renderer/src/components/Conversation.tsx+++ b/src/renderer/src/components/Conversation.tsx@@ -142,8 +142,10 @@ export function ConversationView({ id }: { id: string }): ReactNode {<section className="conversation"><header className="topbar"><div className="topbar__title">- {dmAgent ? <AgentAvatar agent={dmAgent} size={22} /> : <Icon name="hash" />}- <h1>{title}</h1>+ <button className="topbar__name" title={conv.kind === 'channel' ? L('Configurações do canal', 'Channel settings') : L('Configurações da conversa', 'Conversation settings')} onClick={() => openDialog({ kind: 'settings', id })}>+ {dmAgent ? <AgentAvatar agent={dmAgent} size={22} /> : <Icon name="hash" />}+ <h1>{title}</h1>+ </button>{dmAgent?.role && (<span className="tag topbar__role" title={dmAgent.role}>{dmAgent.role}diff --git a/src/renderer/src/components/Dialogs.tsx b/src/renderer/src/components/Dialogs.tsxindex d6928fc..f925f95 100644--- a/src/renderer/src/components/Dialogs.tsx+++ b/src/renderer/src/components/Dialogs.tsx@@ -1,9 +1,9 @@-// Small windows over the app (a channel's members, name and topic) and the+// Small windows over the app (a channel's members and settings) and the// right-click menu. Which window is open lives in the store, so the sidebar's// menu and the channel's header open the same ones.import { L } from '../../../shared/lang'-import { useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from 'react'-import { agentById, archiveAgent, isTeam, openTuca, createChannel, finishConnectorAuth, getState, navigate, openDialog, openDm, renameChannel, setChannelMembers, setTopic, shortcut, useStore, type State, type View } from '../store'+import { useEffect, useRef, useState, useSyncExternalStore, type KeyboardEvent as KeyEvent, type ReactNode } from 'react'+import { agentById, archiveAgent, isTeam, openTuca, createChannel, finishConnectorAuth, getState, navigate, openDialog, openDm, renameChannel, setChannelMembers, setThreads, setTopic, shortcut, useStore, type Conversation, type State, type View } from '../store'import { AgentAvatar, Icon, type IconName } from './ui'const message = (e: unknown): string => (e instanceof Error ? e.message.replace(/^Error invoking.*?: /, '') : String(e))@@ -76,13 +76,91 @@ function DialogBody(): ReactNode {if (dialog?.kind === 'search') return <Search onClose={close} />if (dialog?.kind === 'archived') return <Archived onClose={close} />if (dialog?.kind === 'oauth') return <OAuthDialog id={dialog.id} url={dialog.url} onClose={close} />- if (dialog?.kind === 'new-channel')- return <TextDialog title={L('Novo canal', 'New channel')} label={L('Nome', 'Name')} value="" hint={L('Minúsculas e hífens: “Squad Pagamentos” vira squad-pagamentos. Depois você escolhe os agentes.', 'Lowercase and hyphens: “Payments Squad” becomes payments-squad. You pick the agents next.')} prefix="#" onSave={(v) => createChannel(v)} onClose={() => getState().dialog?.kind === 'new-channel' && close()} />+ if (dialog?.kind === 'new-channel') return <SettingsDialog onClose={() => getState().dialog?.kind === 'new-channel' && close()} />if (!dialog || !conv) return nullif (dialog.kind === 'members') return <MembersDialog id={conv.id} name={conv.name} members={conv.members} onClose={close} />- if (dialog.kind === 'rename')- return <TextDialog title={L(`Renomear #${conv.name}`, `Rename #${conv.name}`)} label={L('Nome', 'Name')} value={conv.name} hint={L('Minúsculas e hífens: “Lançamento do App” vira lancamento-do-app.', 'Lowercase and hyphens: “App Launch” becomes app-launch.')} prefix="#" onSave={(v) => renameChannel(conv.id, v)} onClose={close} />- return <TextDialog title={L(`Tema de #${conv.name}`, `Topic of #${conv.name}`)} label={L('Tema', 'Topic')} value={conv.topic ?? ''} hint={L('Uma linha no topo do canal dizendo pra que ele serve. Vazio, some.', 'One line at the top of the channel saying what it is for. Empty, it goes away.')} onSave={(v) => setTopic(conv.id, v)} onClose={close} allowEmpty />+ return <SettingsDialog conv={conv} onClose={close} />+}++// A channel's name, topic and where its agents answer; a DM's, only where. Without `conv`, a new channel.+function SettingsDialog({ conv, onClose }: { conv?: Conversation; onClose: () => void }): ReactNode {+ const dmName = useStore((s) => (conv?.kind === 'dm' && conv.members[0] ? agentById(s, conv.members[0])?.name : undefined))+ const channel = conv?.kind !== 'dm'+ const [name, setName] = useState(conv?.name ?? '')+ const [topic, setTopicText] = useState(conv?.topic ?? '')+ const [threads, setThreadsOn] = useState(!!conv?.threads)+ const [error, setError] = useState<string | null>(null)+ // Saving with no name: the field shakes and goes red, instead of nothing happening.+ const [invalid, setInvalid] = useState(false)+ const [shaking, setShaking] = useState(false)+ const save = (): void => {+ if (channel && !name.trim()) return void (setInvalid(true), setShaking(true))+ const done = !conv+ ? createChannel(name, threads)+ : Promise.all([+ channel && name.trim() !== conv.name ? renameChannel(conv.id, name) : undefined,+ channel && topic.trim() !== (conv.topic ?? '') ? setTopic(conv.id, topic) : undefined,+ threads !== !!conv.threads ? setThreads(conv.id, threads) : undefined+ ])+ done.then(onClose, (e: unknown) => setError(message(e)))+ }+ const enter = (e: KeyEvent): void => void (e.key === 'Enter' && save())+ const choices = [+ { on: false, label: L('Na conversa, como um chat', 'In the conversation, like a chat'), about: L('As respostas vêm logo abaixo da mensagem.', 'Answers come right below the message.') },+ { on: true, label: L('Em threads, uma por mensagem', 'In threads, one per message'), about: L('Cada mensagem abre uma thread na lateral, com as respostas dela.', 'Each message opens a thread on the side, with its answers.') }+ ]+ const title = !conv ? L('Novo canal', 'New channel') : channel ? L(`Configurações de #${conv.name}`, `#${conv.name} settings`) : L(`Conversa com ${dmName ?? 'o agente'}`, `Conversation with ${dmName ?? 'the agent'}`)+ return (+ <Modal title={title} onClose={onClose}>+ {channel && (+ <label className="field">+ <span className="field__label">{L('Nome', 'Name')}</span>+ <span className={`row row--center modal__input ${invalid ? 'is-invalid' : ''} ${shaking ? 'is-shaking' : ''}`} onAnimationEnd={() => setShaking(false)}>+ <span className="muted">#</span>+ <input autoFocus className="grow" value={name} onChange={(e) => (setName(e.target.value), setInvalid(false))} onKeyDown={enter} />+ </span>+ <span className="hint">+ {conv+ ? L('Minúsculas e hífens: “Lançamento do App” vira lancamento-do-app.', 'Lowercase and hyphens: “App Launch” becomes app-launch.')+ : L('Minúsculas e hífens: “Squad Pagamentos” vira squad-pagamentos. Depois você escolhe os agentes.', 'Lowercase and hyphens: “Payments Squad” becomes payments-squad. You pick the agents next.')}+ </span>+ </label>+ )}+ {channel && conv && (+ <label className="field">+ <span className="field__label">{L('Tema', 'Topic')}</span>+ <span className="row row--center modal__input">+ <input className="grow" value={topic} onChange={(e) => setTopicText(e.target.value)} onKeyDown={enter} />+ </span>+ <span className="hint">{L('Uma linha no topo do canal dizendo pra que ele serve. Vazio, some.', 'One line at the top of the channel saying what it is for. Empty, it goes away.')}</span>+ </label>+ )}+ <div className="field">+ <span className="field__label" id="answers-where">+ {L('Onde os agentes respondem', 'Where the agents answer')}+ </span>+ <div className="choices" role="radiogroup" aria-labelledby="answers-where">+ {choices.map((c) => (+ <button key={String(c.on)} type="button" role="radio" aria-checked={threads === c.on} className={`choice ${threads === c.on ? 'is-on' : ''}`} onClick={() => setThreadsOn(c.on)}>+ <b>{c.label}</b>+ <small>{c.about}</small>+ </button>+ ))}+ </div>+ <span className="hint">{L('Dá pra abrir uma thread numa mensagem quando quiser, nos dois jeitos.', 'You can open a thread on a message whenever you want, either way.')}</span>+ </div>+ {error && <p className="field__error">{error}</p>}+ <footer className="modal__foot">+ <span className="grow" />+ <button className="btn btn--ghost btn--sm" onClick={onClose}>+ {L('Cancelar', 'Cancel')}+ </button>+ <button className="btn btn--primary btn--sm" disabled={channel && !name.trim()} onClick={save}>+ {conv ? L('Salvar', 'Save') : L('Criar canal', 'Create channel')}+ </button>+ </footer>+ </Modal>+ )}// Open windows, newest last: Esc and Tab belong to the one on top only.@@ -182,44 +260,6 @@ function MembersDialog({ id, name, members, onClose }: { id: string; name: strin)}-function TextDialog(p: { title: string; label: string; value: string; hint: string; prefix?: string; allowEmpty?: boolean; onSave: (v: string) => Promise<void>; onClose: () => void }): ReactNode {- const [value, setValue] = useState(p.value)- const [error, setError] = useState<string | null>(null)- // Enter on an empty name: the field shakes and goes red, instead of nothing happening.- const [invalid, setInvalid] = useState(false)- const [shaking, setShaking] = useState(false)- const save = (): void => {- if (!p.allowEmpty && !value.trim()) {- setInvalid(true)- setShaking(true)- return- }- p.onSave(value).then(p.onClose, (e: unknown) => setError(message(e)))- }- return (- <Modal title={p.title} onClose={p.onClose}>- <label className="field">- <span className="field__label">{p.label}</span>- <span className={`row row--center modal__input ${invalid ? 'is-invalid' : ''} ${shaking ? 'is-shaking' : ''}`} onAnimationEnd={() => setShaking(false)}>- {p.prefix && <span className="muted">{p.prefix}</span>}- <input autoFocus className="grow" value={value} onChange={(e) => (setValue(e.target.value), setInvalid(false))} onKeyDown={(e) => e.key === 'Enter' && save()} />- </span>- <span className="hint">{p.hint}</span>- </label>- {error && <p className="field__error">{error}</p>}- <footer className="modal__foot">- <span className="grow" />- <button className="btn btn--ghost btn--sm" onClick={p.onClose}>- {L('Cancelar', 'Cancel')}- </button>- <button className="btn btn--primary btn--sm" disabled={!p.allowEmpty && !value.trim()} onClick={save}>- {L('Salvar', 'Save')}- </button>- </footer>- </Modal>- )-}-// Signing a connector in on a server: the authorization page opens here, and its// last stop (the server's loopback, which this browser can't reach) is pasted back.function OAuthDialog({ id, url, onClose }: { id: string; url: string; onClose: () => void }): ReactNode {diff --git a/src/renderer/src/components/Sidebar.tsx b/src/renderer/src/components/Sidebar.tsxindex 4a70c93..f3f3334 100644--- a/src/renderer/src/components/Sidebar.tsx+++ b/src/renderer/src/components/Sidebar.tsx@@ -160,8 +160,7 @@ export function Sidebar(): ReactNode {})const channelMenu = (c: (typeof channels)[number]): MenuItem[] => [{ label: L('Adicionar ou remover agentes…', 'Add or remove agents…'), icon: 'users', onClick: () => openDialog({ kind: 'members', id: c.id }) },- { label: L('Renomear…', 'Rename…'), icon: 'edit', onClick: () => openDialog({ kind: 'rename', id: c.id }) },- { label: L('Mudar o tema…', 'Change the topic…'), icon: 'hash', onClick: () => openDialog({ kind: 'topic', id: c.id }) },+ { label: L('Configurações do canal…', 'Channel settings…'), icon: 'gear', onClick: () => openDialog({ kind: 'settings', id: c.id }) },...(c.unread ? [{ label: L('Marcar como lido', 'Mark as read'), icon: 'check' as const, onClick: () => markRead(c.id) }] : []),wikiItem(c.id, c.wikiCapture !== false),'separator',@@ -189,6 +188,7 @@ export function Sidebar(): ReactNode {const dmMenu = (id: string, agentId: string, agentName: string): MenuItem[] => [{ label: L(`Ver ${agentName}`, `See ${agentName}`), icon: 'eye', onClick: () => navigate({ kind: 'agent', id: agentId }) },{ label: L('Marcar como lido', 'Mark as read'), icon: 'check', onClick: () => markRead(id) },+ { label: L('Configurações da conversa…', 'Conversation settings…'), icon: 'gear', onClick: () => openDialog({ kind: 'settings', id }) },wikiItem(id, s.conversations.find((x) => x.id === id)?.wikiCapture !== false),'separator',{diff --git a/src/renderer/src/store.ts b/src/renderer/src/store.tsindex d9c49c5..b1b0ebf 100644--- a/src/renderer/src/store.ts+++ b/src/renderer/src/store.ts@@ -99,7 +99,7 @@ export interface Toast {leaving?: boolean // fading out}-export type Dialog = { kind: 'members' | 'rename' | 'topic'; id: string } | { kind: 'archived' | 'new-channel' | 'search' } | { kind: 'oauth'; id: string; url: string }+export type Dialog = { kind: 'members' | 'settings'; id: string } | { kind: 'archived' | 'new-channel' | 'search' } | { kind: 'oauth'; id: string; url: 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 }@@ -464,8 +464,8 @@ export function newAgentDraft(): Agent {export const newChannel = (name: string): Promise<string> => call('createChannel', { name })// A new channel opens with the window to pick who's in it.-export async function createChannel(name: string): Promise<void> {- const id = await call('createChannel', { name })+export async function createChannel(name: string, threads?: boolean): Promise<void> {+ const id = await call('createChannel', { name, ...(threads ? { threads } : {}) })navigate({ kind: 'conversation', id })set((s) => ({ ...s, dialog: { kind: 'members', id } }))}@@ -508,6 +508,8 @@ export const importHarnessMcp = (key: string): Promise<string> => call('importHaexport const renameChannel = (id: string, name: string): Promise<void> => call('renameChannel', { id, name })export const archiveAgent = (id: string, archived: boolean): Promise<void> => call('archiveAgent', { id, archived })export const setTopic = (id: string, topic: string): Promise<void> => call('setTopic', { id, topic })+// Where a conversation's answers go: each in the thread of what it answers, or in the conversation.+export const setThreads = (conversationId: string, on: boolean): Promise<void> => call('setThreads', { conversationId, on })export const setChannelMembers = (id: string, agentIds: string[]): Promise<void> => call('setChannelMembers', { id, agentIds })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)) }))diff --git a/src/renderer/src/styles.css b/src/renderer/src/styles.cssindex 4a21a55..7b24c1f 100644--- a/src/renderer/src/styles.css+++ b/src/renderer/src/styles.css@@ -739,6 +739,24 @@ h3 {align-items: center;gap: 8px;}+/* The conversation's name opens its settings. */+.topbar__name {+ display: flex;+ align-items: center;+ gap: 8px;+ min-width: 0;+ margin: -3px -6px;+ padding: 3px 6px;+ border: 0;+ border-radius: 6px;+ background: none;+ color: inherit;+ font: inherit;+ cursor: pointer;+}+.topbar__name:hover {+ background: var(--hover);+}.topbar__topic {color: var(--text-3);font-size: 13px;@@ -7866,11 +7884,11 @@ button.wk-pill.is-on { box-shadow: 0 0 0 1.5px var(--k); background: color-mix(i.voice-pop__close { position: absolute; top: 8px; right: 8px; }.voice-pop__hide { justify-self: start; font-size: 12px; color: var(--text-3); }.voice-setup { display: grid; gap: 10px; justify-items: start; }-.voice-setup__choices { display: grid; gap: 6px; width: 100%; }-.voice-choice { display: grid; gap: 2px; width: 100%; padding: 9px 12px; border-radius: 10px; border: 1px solid var(--border); background: var(--panel); font: inherit; font-size: 13px; color: var(--text); text-align: left; cursor: pointer; }-.voice-choice small { color: var(--text-2); font-size: 12px; }-.voice-choice:hover { border-color: var(--border-strong); }-.voice-choice.is-on { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); background: var(--accent-soft); }+.voice-setup__choices, .choices { display: grid; gap: 6px; width: 100%; }+.voice-choice, .choice { display: grid; gap: 2px; width: 100%; padding: 9px 12px; border-radius: 10px; border: 1px solid var(--border); background: var(--panel); font: inherit; font-size: 13px; color: var(--text); text-align: left; cursor: pointer; }+.voice-choice small, .choice small { color: var(--text-2); font-size: 12px; }+.voice-choice:hover, .choice:hover { border-color: var(--border-strong); }+.voice-choice.is-on, .choice.is-on { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); background: var(--accent-soft); }.voice-setup__bar { width: 100%; height: 6px; border-radius: 3px; background: var(--hover); overflow: hidden; }.voice-setup__bar i { display: block; height: 100%; border-radius: 3px; background: var(--accent); transition: width 0.25s; }.voice-setup__row { display: flex; align-items: center; justify-content: space-between; gap: 10px; width: 100%; }diff --git a/src/shared/rpc.ts b/src/shared/rpc.tsindex 95952de..9d6effd 100644--- a/src/shared/rpc.ts+++ b/src/shared/rpc.ts@@ -28,7 +28,7 @@ export interface Api {retryRun(p: { messageId: string }): voidcontinueRun(p: { messageId: string }): void // a reply paused at its budget goes onsaveAgent(p: { agent: Agent; channelIds: string[] }): void- createChannel(p: { name: string }): string+ createChannel(p: { name: string; threads?: boolean }): stringrenameChannel(p: { id: string; name: string }): void // throws a message when the name is takenarchiveAgent(p: { id: string; archived: boolean }): void // out of the sidebar, its replies stopped and routines off; back with archived: falsesetTopic(p: { id: string; topic: string }): void@@ -141,6 +141,7 @@ export interface Api {wikiDismissFinding(p: { id: string }): void // and refuses its fixwikiImport(p: { dir: string }): WikiImport // an Obsidian vault copied in, as it issetWikiCapture(p: { conversationId: string; on: boolean }): void+ setThreads(p: { conversationId: string; on: boolean }): voidsetWikiDir(p: { dir: string | null }): Promise<string> // null: back to the app's own folder; returns where it is now}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 3893571..e1355be 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -118,6 +118,7 @@ export interface Conversation {summaryAt?: numberunread?: numberwikiCapture?: boolean // false: the wiki's curator leaves this conversation out+ threads?: boolean // true: each message's answers go in its thread; unset: in the conversation, like a chat}// "Lançamento do App" → "lancamento-do-app": lowercase, no accents, hyphens.diff --git a/test/governance.test.ts b/test/governance.test.tsindex 953d8b9..e2cd1aa 100644--- a/test/governance.test.ts+++ b/test/governance.test.ts@@ -134,7 +134,7 @@ describe('grants', () => {const r = runner((_, tools) => ({ tool: tools.find((t) => t.endsWith('__create_task')) ?? 'tarefas__create_task', args: { title: 'invasora' } }))await r.send('d1', 'oi')await r.idle()- expect(seen.tools[0]).toEqual(['ask_user', 'pedir_acesso', 'buscar_threads', 'ler_thread', 'tarefas__list_tasks']) // it can ask for more, not take it+ expect(seen.tools[0]).toEqual(['ask_user', 'pedir_acesso', 'tarefas__list_tasks']) // it can ask for more, not take itexpect(seen.results[0]).toMatchObject({ isError: true })expect(textOf(seen.results[0])).toContain('não permitida')expect(tasks().some((t) => t.title === 'invasora')).toBe(false)diff --git a/test/memory.test.ts b/test/memory.test.tsindex 9cac6c8..ec4d4b4 100644--- a/test/memory.test.ts+++ b/test/memory.test.ts@@ -98,6 +98,7 @@ describe('summary (short term)', () => {expect(outside.messages.at(-1)?.text).toBe(`mensagem ${MAX_AFTER + 9}`)// A thread is a conversation of its own: neither the summary nor those messages.+ db.setThreads('c1', true)await runner.send('c1', '@lia qual é o cupom?')await settle()const prompt = agentTurns('lia')[0]!.promptdiff --git a/test/threads.test.ts b/test/threads.test.tsindex b35941b..ead1807 100644--- a/test/threads.test.ts+++ b/test/threads.test.ts@@ -68,8 +68,9 @@ beforeEach(async () => {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'] })+ // Both answer in threads; a conversation that answers in it is made where it's tested.+ db.createConversation({ id: 'd1', kind: 'dm', name: 'a1', members: ['a1'], threads: true })+ db.createConversation({ id: 'c1', kind: 'channel', name: 'lancamento', members: ['a1', 'a2'], threads: true })gateway = new Gateway()await gateway.start()})@@ -113,6 +114,68 @@ describe('sending into a thread', () => {})})+describe('a conversation that answers in it', () => {+ beforeEach(() => {+ db.createConversation({ id: 'p1', kind: 'channel', name: 'papo', members: ['a1', 'a2'] }) // threads off, the default+ })++ it("my message, the router's note and the answers stay in the conversation, like a chat", async () => {+ const r = runner()+ await r.send('p1', 'qual a média de retenção da semana?')+ await r.idle()+ const here = db.messages().filter((m) => m.conversationId === 'p1')+ expect(here.map((m) => m.author.kind)).toEqual(['me', 'system', 'agent'])+ expect(here.every((m) => m.threadId === undefined)).toBe(true)+ expect(notes.at(-1)).toEqual({ conversationId: 'p1', kind: 'done', threadId: undefined })+ })++ it('a thread opened by hand still takes its answers; switched to threads, every message opens one', async () => {+ const root = put('p1', { kind: 'me' }, 'um assunto à parte')+ const r = runner()+ await r.send('p1', '@lia e esse?', [], root.id)+ await r.idle()+ expect(mine().at(-1)?.threadId).toBe(root.id)+ expect(replies().at(-1)?.threadId).toBe(root.id)++ db.setThreads('p1', true)+ await r.send('p1', '@lia e agora?')+ await r.idle()+ expect(mine().at(-1)?.threadId).toBeUndefined()+ expect(replies().at(-1)?.threadId).toBe(mine().at(-1)!.id)+ })++ it('an answer there reads the conversation and the message that opened each thread, not what was said inside: that is looked up', async () => {+ put('p1', { kind: 'me' }, 'CANAL: bom dia')+ const root = put('p1', { kind: 'me' }, 'RAIZ: o plano do post')+ put('p1', { kind: 'agent', id: 'a2' }, 'DENTRO DA THREAD: o plano inteiro', root.id)+ const found: string[] = []+ const r = runner({+ onTurn: async (t) => {+ if (t.mcpUrl) found.push(JSON.stringify(await callTool(t.mcpUrl, 'buscar_threads', { busca: 'plano' })))+ }+ })+ await r.send('p1', '@lia e o plano?')+ await r.idle()++ const prompt = agentTurns()[0]!.prompt+ expect(prompt).toContain('CANAL: bom dia')+ expect(prompt).toContain('RAIZ: o plano do post')+ expect(prompt).not.toContain('DENTRO DA THREAD')+ expect(prompt).toContain('As threads ficam à parte')+ expect(found[0]).toContain('DENTRO DA THREAD: o plano inteiro')+ expect(replies().at(-1)?.threadId).toBeUndefined()+ })++ it('with no thread in it, an answer there is given no thread tools nor the note about them', async () => {+ put('p1', { kind: 'me' }, 'CANAL: bom dia')+ const r = runner()+ await r.send('p1', '@lia tudo certo?')+ await r.idle()+ expect(agentTurns()[0]!.prompt).toContain('CANAL: bom dia')+ expect(agentTurns()[0]!.prompt).not.toContain('buscar_threads')+ })+})+describe("what the agent sees", () => {it("in a thread: only that thread, however old; not the channel's summary nor the other threads", async () => {const root = put('c1', { kind: 'me' }, 'RAIZ: o plano de lançamento')@@ -343,13 +406,13 @@ describe('what a thread message sets off stays in the thread', () => {})describe('the database', () => {- it('an existing database gains thread_id and thread_summary, and messages round-trip them', () => {+ it('an existing database gains thread_id, thread_summary and threads, and round-trips them', () => {const file = join(mkdtempSync(join(tmpdir(), 'ad-db-')), 'old.db')- // A database from before threads: the schema two migrations back, with a message in it.+ // A database from before threads: the schema three migrations 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(`ALTER TABLE messages DROP COLUMN thread_summary; DROP INDEX messages_by_thread; ALTER TABLE messages DROP COLUMN thread_id; PRAGMA user_version = ${user_version - 2};`)+ raw.exec(`ALTER TABLE conversations DROP COLUMN threads; ALTER TABLE messages DROP COLUMN thread_summary; DROP INDEX messages_by_thread; ALTER TABLE messages DROP COLUMN thread_id; PRAGMA user_version = ${user_version - 3};`)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()@@ -365,6 +428,12 @@ describe('the database', () => {reopened.saveMessage({ ...reopened.message('old')!, text: 'antes das threads (editada)' }) // saving a message keeps its summaryreopened.setThreadSummary('old', 'editado à mão') // a hand edit keeps what it coversexpect(reopened.message('old')?.threadSummary).toMatchObject({ text: 'editado à mão', until: 2 })+ // A conversation answers in it until it's switched to threads, and back.+ expect(reopened.conversation('c1')?.threads).toBeUndefined()+ reopened.setThreads('c1', true)+ expect(reopened.conversation('c1')?.threads).toBe(true)+ reopened.setThreads('c1', false)+ expect(reopened.conversation('c1')?.threads).toBeUndefined()reopened.close()})})