Skip to content

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.

Reply once at a time per agent and thread, folding hand-offs into one follow-up (#151)

Alan Jones Rios2f3c0c53af7f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 975a390..7f58156 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
> - **A página do servidor abre por HTTP num endereço privado,** como o Tailscale ou a rede de casa. Ela ficava em branco.
> - **Os agentes do Claude respondem mais rápido e gastam menos do plano em conversas longas.** Cada agente continua a mesma sessão do Claude Code na conversa e manda só o que é novo; entre uma resposta e outra o processo fica aberto por 5 minutos. O primeiro trecho da resposta chega quase 1 segundo antes, e uma conversa longa não é mandada inteira de novo a cada resposta.
> - **A resposta começa enquanto você digita.** O Tucano já abre o Claude Code de quem vai responder: o router escolhe quem responde num canal em 1,5 s em vez de 2,8 s, e numa DM parada há mais de 5 minutos a resposta começa meio segundo antes.
+> - **Um agente responde uma vez de cada vez na mesma conversa.** Quando outro agente passa a vez pra quem já está respondendo ali, não abre uma segunda resposta ao lado: fica anotado, e quando a resposta acaba vem uma só, que lê tudo o que chegou no meio. Em outras conversas e threads ele segue em paralelo.
> - **Um agente só acorda outro quando precisa.** Quando um agente menciona outro na resposta, o router lê e chama só quem tem algo a fazer: um agradecimento ou um “combinado” não acordam ninguém. Na dúvida, chama.
> - **O app abre fora do instalador mesmo com uma versão estranha.** O atualizador, que nem é usado ali, conferia a versão ao abrir e derrubava o app.
> - **Workspaces.** Empresa e emprego, por exemplo, em workspaces separados: cada um com seus agentes, conversas, conectores e credenciais, memórias e rotinas, e um não vê o outro. Você troca pelo nome no topo da barra lateral, que mostra as não lidas e aprovações dos outros; as rotinas de todos continuam rodando. Ao criar, você marca o que levar do workspace atual (configurações gerais, contexto, wiki, agentes, canais, skills, conectores e credenciais, rotinas; a wiki é a mesma, não uma cópia); duplicar leva tudo isso, nunca as conversas nem as memórias.
@@ -31,6 +32,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
### Fixed
+- **An agent replies once at a time in the same conversation or thread.** When another agent handed the turn to one already replying there, a second reply of it started next to the first, each working from the conversation as it was when it began. The hand-off is now noted instead, and the caller's step says so ("already replying here, will see this next"); when the current reply ends well, one follow-up reply reads everything that came in meanwhile, in the same Claude Code session. A reply that stopped, failed, hit a limit or waits on you gets no follow-up, since you act there anyway. The same agent elsewhere still runs in parallel, and the hand-off router is told who is already replying, and that waiting for someone's update isn't a request. Thanks [@eialanjones](https://github.com/eialanjones)! ([#151](https://github.com/eduwxyz/tucano/pull/151))
- **A connector tool that fails says why.** The reply's step showed a bare ✗ next to the tool's name, and for some failures the agent got an empty result too. The step now shows the reason under its label (a few lines, all of it on a click), and the agent gets it: a reason only in the structured content or an embedded resource, an MCP error's code and data, a timeout in seconds, a result that doesn't match the tool's schema, or a session that couldn't reconnect. An approved call and a routine's poll say it the same way. Thanks [@rjgdias](https://github.com/rjgdias)! ([#133](https://github.com/eduwxyz/tucano/pull/133))
- **Long conversations stay light while an agent replies.** Each streamed word redrew and re-parsed every message in the list, keeping the window busy on long conversations. Now only the message that changed is drawn again.
- **An agent's browser loads pages on a Linux server that is a desktop PC.** Chrome waited for the desktop's locked keyring before its first page and never got it, so every page hung. On a server it now uses its own cookie store; a desktop keeps the keyring.
diff --git a/src/core/engines/fake.ts b/src/core/engines/fake.ts
index c49302f..7594a99 100644
--- a/src/core/engines/fake.ts
+++ b/src/core/engines/fake.ts
@@ -176,7 +176,7 @@ function fakeHandoff(prompt: string): { handles: string[]; reason: string } {
const [head = '', rest = ''] = prompt.split('<reply>\n')
const reply = rest.slice(0, rest.lastIndexOf('\n</reply>'))
const body = reply.replace(/^(?:@[\w-]+|[\s,.!:;-])+/, '')
- if (!body.includes('?') && /^(valeu|obrigad|combinado|ok\b|beleza|👍|thanks|got it)/i.test(body)) return { handles: [], reason: 'agradecimento, ninguém precisa responder' }
+ if (!body.includes('?') && /^(valeu|obrigad|combinado|ok\b|beleza|👍|thanks|got it|fico esperando|aguardo)/i.test(body)) return { handles: [], reason: 'agradecimento, ninguém precisa responder' }
return { handles: [...head.matchAll(/^- ([a-z0-9_-]+): /gim)].map((m) => m[1]!), reason: 'pedido' }
}
diff --git a/src/core/followups.ts b/src/core/followups.ts
new file mode 100644
index 0000000..dedca1a
--- /dev/null
+++ b/src/core/followups.ts
@@ -0,0 +1,66 @@
+// One reply at a time per agent and thread. Two replies of the same agent in the same conversation would
+// each run on a context the other is about to change, so a hand-off that reaches an agent already replying
+// there is noted instead, and the agent answers it once, after the reply it's in. Other conversations and
+// other threads stay parallel: the key is agent + conversation + thread.
+
+// Also the key of an agent's kept session: same agent, same conversation, same thread.
+export const replyKey = (agentId: string, convId: string, threadId?: string): string => `${agentId}:${convId}:${threadId ?? ''}`
+
+export type Followup = { depth: number; work?: string }
+
+type Slot = { running: number; reserved: number; pending?: Followup }
+
+export class Followups {
+ private slots = new Map<string, Slot>()
+
+ private slot(key: string): Slot {
+ let s = this.slots.get(key)
+ if (!s) this.slots.set(key, (s = { running: 0, reserved: 0 }))
+ return s
+ }
+
+ private tidy(key: string): void {
+ const s = this.slots.get(key)
+ if (s && !s.running && !s.reserved && !s.pending) this.slots.delete(key)
+ }
+
+ // A reply starts; `reserved` when it was queued with reserve() and now takes that place.
+ start(key: string, reserved = false): void {
+ const s = this.slot(key)
+ s.running++
+ if (reserved && s.reserved > 0) s.reserved--
+ }
+
+ end(key: string): void {
+ const s = this.slots.get(key)
+ if (!s) return
+ s.running = Math.max(0, s.running - 1)
+ this.tidy(key)
+ }
+
+ // A reply is queued but hasn't started: the place is taken so a second hand-off doesn't queue another.
+ reserve(key: string): void {
+ this.slot(key).reserved++
+ }
+
+ busy(key: string): boolean {
+ const s = this.slots.get(key)
+ return !!s && (s.running > 0 || s.reserved > 0)
+ }
+
+ // Several hand-offs while it replies become one follow-up: the deepest chain, the latest work.
+ add(key: string, f: Followup): void {
+ const s = this.slot(key)
+ s.pending = { depth: Math.max(s.pending?.depth ?? 0, f.depth), work: f.work ?? s.pending?.work }
+ }
+
+ // Only once the agent is free: whoever finishes last in a crowded key is the one that gets it.
+ take(key: string): Followup | undefined {
+ const s = this.slots.get(key)
+ if (!s || s.running > 0 || s.reserved > 0) return undefined
+ const f = s.pending
+ s.pending = undefined
+ this.tidy(key)
+ return f
+ }
+}
diff --git a/src/core/router.ts b/src/core/router.ts
index d351c20..15d43ab 100644
--- a/src/core/router.ts
+++ b/src/core/router.ts
@@ -96,7 +96,7 @@ export const handoffSystem = (): string =>
'- "handles": só handles da lista de agentes mencionados.',
'- "reason": um motivo de até 12 palavras, em português.',
'Passe a vez para: um pedido, uma pergunta, uma tarefa, uma revisão, uma decisão que alguém está esperando.',
- 'Não passe a vez para: agradecimento, confirmação ("combinado", "valeu", "ok", 👍), menção que só dá crédito ou informa, recado sem pedido.',
+ 'Não passe a vez para: agradecimento, confirmação ("combinado", "valeu", "ok", 👍), menção que só dá crédito ou informa, recado sem pedido, ficar esperando o aviso ou o resultado de alguém ("Fico esperando o aviso do Léo").',
'Na dúvida, passe a vez.'
].join('\n'),
[
@@ -105,18 +105,26 @@ export const handoffSystem = (): string =>
'- "handles": only handles from the list of mentioned agents.',
'- "reason": a reason of up to 12 words, in English.',
'Hand the turn over for: a request, a question, a task, a review, a decision someone is waiting on.',
- 'Do not hand it over for: thanks, an acknowledgement ("agreed", "thanks", "ok", 👍), a mention that only credits or informs, a note with no ask.',
+ "Do not hand it over for: thanks, an acknowledgement (\"agreed\", \"thanks\", \"ok\", 👍), a mention that only credits or informs, a note with no ask, waiting for someone's update or result (\"I'll wait for Léo's heads-up\").",
'When in doubt, hand the turn over.'
].join('\n')
)
// The reply sits between <reply> tags so it can't be confused with the roster or the history.
-export function handoffPrompt(opts: { reply: string; author: Agent; candidates: Agent[]; messages: Message[]; members: Agent[]; me: string; connectors?: Connector[] }): string {
- const { reply, author, candidates, messages, members, me, connectors = [] } = opts
+export function handoffPrompt(opts: { reply: string; author: Agent; candidates: Agent[]; messages: Message[]; members: Agent[]; me: string; connectors?: Connector[]; busy?: Agent[] }): string {
+ const { reply, author, candidates, messages, members, me, connectors = [], busy = [] } = opts
const name = speaker(members, me)
return [
L('Agentes mencionados:', 'Mentioned agents:'),
...candidates.map((a) => `- ${a.handle}: ${describeAgent(a, connectors)}`),
+ ...(busy.length
+ ? [
+ L(
+ `Já estão respondendo aqui: ${busy.map((a) => a.name).join(', ')}. Só passe a vez para eles se a resposta trouxer algo novo pra eles (decisão, pedido, correção).`,
+ `Already replying here: ${busy.map((a) => a.name).join(', ')}. Only hand them the turn if the reply brings them something new (a decision, a request, a correction).`
+ )
+ ]
+ : []),
'',
L('Conversa recente:', 'Recent conversation:'),
...messages.filter(said).slice(-ROUTER_HISTORY).map((m) => `[${name(m)}] ${m.text.trim().slice(0, 600)}`),
@@ -197,6 +205,7 @@ export async function screenHandoff(opts: {
members: Agent[]
me: string
connectors?: Connector[]
+ busy?: Agent[]
cwd: 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.ts
index c06fd78..6002bae 100644
--- a/src/core/runs.ts
+++ b/src/core/runs.ts
@@ -21,6 +21,7 @@ import type { Engine, TurnImage } from './engines/types'
import { accountDir } from './engines/detect'
import { outOfQuota } from './engines/cli'
import { textResult, type Gateway, type Session, type ToolDef } from './gateway'
+import { Followups, replyKey, type Followup } from './followups'
import { sessionConfig, Sessions, type SessionPlan, type Shown } from './sessions'
import { JEV_MODEL, routeJev } from './jev'
import { ROUTER_HISTORY, route, routerTurn, screenHandoff } from './router'
@@ -138,6 +139,7 @@ export interface RoutineEvent {
}
// msg is the live reply: a decision taken mid-run must land on it, or the run's last save overwrites it.
+type ReplyOpts = { depth: number; existing?: Message; task?: string; work?: string; routine?: boolean; threadId?: string }
type Control = { ctl: AbortController; msg: Message; reason?: 'stopped' | 'limit' | 'budget' | 'loop' | 'errors' | 'stall' | 'computer' }
export class Runner {
@@ -148,6 +150,7 @@ export class Runner {
private paused = false // "Pausar tudo": nobody starts working until it's off
private idleWaiters: (() => void)[] = []
private sessions: Sessions
+ private followups = new Followups()
constructor(private deps: RunnerDeps) {
this.sessions = new Sessions({
@@ -191,6 +194,7 @@ export class Runner {
stopAll(): void {
this.paused = true
this.queue.length = 0
+ this.followups = new Followups() // the places the dropped queue held, and what was noted for later
for (const c of this.controllers.values()) {
c.reason = 'stopped'
c.ctl.abort()
@@ -230,7 +234,7 @@ export class Runner {
// A message outside threads in a conversation that answers in them opens a new thread: nothing is kept there yet.
if (!agent || (conv.threads && !threadId)) return
const engine = modelInfo(agent.modelId)?.engine ?? 'claude'
- const id = this.sessions.idOf(`${agent.id}:${conv.id}:${threadId ?? ''}`)
+ const id = this.sessions.idOf(replyKey(agent.id, conv.id, threadId))
if (id && ready(engine)) engines[engine].rewarm?.(id)
return
}
@@ -567,8 +571,31 @@ export class Runner {
return { model, account }
}
+ // Every reply counts while it runs, wherever it came from. A hand-off that reached this agent meanwhile
+ // is answered once, right after, when the reply ended well: otherwise the person acts on it anyway.
+ // `reserved`: this reply was queued by handOff, which already holds its place.
+ private async execute(agent: Agent, conv: Conversation, opts: ReplyOpts & { reserved?: boolean }): Promise<Message> {
+ const threadId = opts.existing ? opts.existing.threadId : opts.threadId
+ const key = replyKey(agent.id, conv.id, threadId)
+ const { reserved, ...rest } = opts
+ this.followups.start(key, reserved)
+ let msg: Message
+ let f: Followup | undefined
+ try {
+ msg = await this.reply(agent, conv, rest)
+ } finally {
+ this.followups.end(key)
+ f = this.followups.take(key) // taken even when the reply threw: a stale follow-up must not wait for the next one
+ }
+ if (f && msg.run?.status === 'done' && !this.paused) {
+ this.followups.reserve(key)
+ this.enqueue(() => this.execute(agent, conv, { depth: f.depth, work: f.work, threadId, reserved: true }))
+ }
+ return msg
+ }
+
// `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> {
+ private async reply(agent: Agent, conv: Conversation, opts: ReplyOpts): Promise<Message> {
const { db, emit, engines } = this.deps
const settings = await this.deps.settings()
agent = db.agent(agent.id) ?? agent // limits or instructions may have changed while queued
@@ -1329,7 +1356,7 @@ export class Runner {
// A kept session: the reply goes on from this agent's last one here (this conversation, or this
// thread) with only what's new since. Not while another agent is still writing a message this
// reply would see half of: that one goes the usual way, and the session takes it all next time.
- const sessionKey = `${agent.id}:${conv.id}:${msg.threadId ?? ''}`
+ const sessionKey = replyKey(agent.id, conv.id, msg.threadId)
const config = sessionConfig({ engine: engineId, model: modelName, effort: agent.effort, account: account?.id ?? '', web: agent.web !== false, system, tools: toolDefs, gateway: !!this.deps.gateway })
const shown: Shown[] = [...blockOf].map(([id, i]) => ({ id, block: blocks[i]! }))
const writing = history.some((m) => m.author.kind === 'agent' && m.run?.status === 'working')
@@ -1745,6 +1772,8 @@ export class Runner {
const list = (agents: Agent[]): string => agents.map((a) => a.name).join(and)
this.routing++
try {
+ const keyOf = (a: Agent): string => replyKey(a.id, conv.id, msg.threadId)
+ const isBusy = (a: Agent): boolean => this.followups.busy(keyOf(a))
let called = next
let step = { label: L('Chamou', 'Called'), detail: list(next), ms: 0 }
const failed = (why: string): void => {
@@ -1761,7 +1790,7 @@ export class Runner {
const cwd = join(this.deps.workDir, '_router')
mkdirSync(cwd, { recursive: true })
const { messages } = contextWindow(db, msg, ROUTER_HISTORY)
- const r = await screenHandoff({ engine: engines[model.engine], model: model.id, reply: msg.text, author: agent, candidates: next, messages, members: this.members(conv), me: settings.workspaceName, connectors: this.deps.connectors?.list(), cwd })
+ const r = await screenHandoff({ engine: engines[model.engine], model: model.id, reply: msg.text, author: agent, candidates: next, busy: next.filter(isBusy), messages, members: this.members(conv), me: settings.workspaceName, connectors: this.deps.connectors?.list(), cwd })
if (r.usage) db.addReceipt({ ...r.usage, model: model.id, ms: r.ms, messageId: msg.id, agentId: 'router', engine: model.engine, at: Date.now() })
step.ms = r.ms
if ('error' in r) failed(r.error)
@@ -1776,7 +1805,10 @@ export class Runner {
}
// Paused while the router was thinking: call no one.
if (this.paused) called = []
- else {
+ // Nothing awaits from here to the enqueues, so who is busy now is who is busy when they're called.
+ const busy = called.filter(isBusy)
+ if (!this.paused) {
+ if (busy.length) step.detail = `${step.detail ? `${step.detail} · ` : ''}${busy.length === called.length ? '' : `${list(busy)}: `}${busy.length > 1 ? L('já estão respondendo aqui, veem isto na próxima resposta', 'already replying here, will see this next') : L('já está respondendo aqui, vê isto na próxima resposta', 'already replying here, will see this next')}`
// Seconds have passed: other code may have saved this reply meanwhile (the wiki, a draft), so add to what's stored.
const saved = db.message(msg.id) ?? msg
if (saved.run) this.update(saved, { run: { ...saved.run, steps: [...saved.run.steps, { id: randomUUID(), ...step, status: 'done' }] } })
@@ -1786,7 +1818,14 @@ export class Runner {
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 finished()
}
- for (const a of called) this.enqueue(() => this.execute(a, conv, { depth: depth + 1, work: msg.run?.work, threadId: msg.threadId }))
+ // A noted follow-up counts as someone taking the turn: the agent will answer it, so no "done" yet.
+ for (const a of called) {
+ if (busy.includes(a)) this.followups.add(keyOf(a), { depth: depth + 1, work: msg.run?.work })
+ else {
+ this.followups.reserve(keyOf(a))
+ this.enqueue(() => this.execute(a, conv, { depth: depth + 1, work: msg.run?.work, threadId: msg.threadId, reserved: true }))
+ }
+ }
} finally {
this.routing--
this.checkIdle()
diff --git a/test/followups.test.ts b/test/followups.test.ts
new file mode 100644
index 0000000..832c219
--- /dev/null
+++ b/test/followups.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from 'vitest'
+import { Followups, replyKey } from '../src/core/followups'
+
+describe('Followups', () => {
+ it('keys by agent, conversation and thread', () => {
+ expect(replyKey('a', 'c', 't')).toBe('a:c:t')
+ expect(replyKey('a', 'c')).toBe('a:c:')
+ })
+
+ it('is busy while a reply runs or is reserved', () => {
+ const f = new Followups()
+ expect(f.busy('k')).toBe(false)
+ f.reserve('k')
+ expect(f.busy('k')).toBe(true)
+ f.start('k', true) // the reservation becomes the running reply
+ expect(f.busy('k')).toBe(true)
+ f.end('k')
+ expect(f.busy('k')).toBe(false)
+ f.start('k')
+ f.start('k')
+ f.end('k')
+ expect(f.busy('k')).toBe(true)
+ f.end('k')
+ expect(f.busy('k')).toBe(false)
+ })
+
+ it('keeps the deepest depth and the latest work of what was noted', () => {
+ const f = new Followups()
+ f.start('k')
+ f.add('k', { depth: 3, work: 'A-1' })
+ f.add('k', { depth: 2, work: 'A-2' })
+ f.add('k', { depth: 2 })
+ f.end('k')
+ expect(f.take('k')).toEqual({ depth: 3, work: 'A-2' })
+ })
+
+ it('hands the follow-up over only once the agent is free, and only once', () => {
+ const f = new Followups()
+ f.start('k')
+ f.start('k')
+ f.add('k', { depth: 2 })
+ f.end('k')
+ expect(f.take('k')).toBeUndefined()
+ f.end('k')
+ f.reserve('k')
+ expect(f.take('k')).toBeUndefined()
+ f.start('k', true)
+ f.end('k')
+ expect(f.take('k')).toEqual({ depth: 2, work: undefined })
+ expect(f.take('k')).toBeUndefined()
+ })
+
+ it('forgets a key once nothing is left on it', () => {
+ const f = new Followups()
+ f.start('k')
+ f.add('k', { depth: 2 })
+ f.end('k')
+ f.take('k')
+ expect((f as unknown as { slots: Map<string, unknown> }).slots.size).toBe(0)
+ })
+})
diff --git a/test/router.test.ts b/test/router.test.ts
index 916a02e..e803054 100644
--- a/test/router.test.ts
+++ b/test/router.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { handoffPrompt, parseRoute, routerPrompt } from '../src/core/router'
+import { handoffPrompt, handoffSystem, parseRoute, routerPrompt } from '../src/core/router'
import type { Agent, Connector, Message } from '../src/shared/types'
const agent = (id: string, handle: string, role: string, instructions = ''): Agent => ({
@@ -93,6 +93,17 @@ describe('handoffPrompt', () => {
expect(p).toContain('[Edu] revisa o build')
expect(p).not.toContain('Chamei')
})
+
+ it('says who is already replying, only when someone is', () => {
+ expect(p).not.toContain('Já estão respondendo')
+ const busy = handoffPrompt({ reply: 'Valeu, @nina!', author: lia, candidates: [nina], busy: [nina], messages, members: team, me: 'Edu' })
+ expect(busy).toContain('Já estão respondendo aqui: Nina.')
+ expect(busy).toContain('algo novo')
+ })
+
+ it('does not count waiting for someone as a request', () => {
+ expect(handoffSystem()).toContain('Fico esperando o aviso do Léo')
+ })
})
describe('parseRoute with hand-off candidates', () => {
diff --git a/test/runner.test.ts b/test/runner.test.ts
index 922338b..1096f8d 100644
--- a/test/runner.test.ts
+++ b/test/runner.test.ts
@@ -279,6 +279,71 @@ describe('Runner', () => {
})
})
+describe('one reply at a time per agent and thread', () => {
+ const sleep = (ms: number, signal: AbortSignal): Promise<void> => new Promise((res) => { const t = setTimeout(res, ms); signal.addEventListener('abort', () => (clearTimeout(t), res()), { once: true }) })
+ // Lia and Bia ask Theo for something; Theo takes `ms` and records how many of his turns overlap.
+ const slowTheo = (ms: number): { engine: Engine; active: () => number; max: () => number } => {
+ let active = 0
+ let max = 0
+ const base = fakeEngine('claude', { delayMs: 1, reply: (t) => (t.system.startsWith('Você é lia') ? '@theo, revisa o PR?' : t.system.startsWith('Você é bia') ? '@theo, e o deploy?' : 'feito') })
+ const engine: Engine = {
+ id: 'claude',
+ run: (t) =>
+ t.system.startsWith('Você é theo')
+ ? (async function* () {
+ max = Math.max(max, ++active)
+ try {
+ await sleep(ms, t.signal)
+ yield* base.run(t)
+ } finally {
+ active--
+ }
+ })()
+ : base.run(t)
+ }
+ return { engine, active: () => active, max: () => max }
+ }
+ const by = (id: string): Message[] => agentMessages().filter((m) => (m.author as { id: string }).id === id)
+
+ beforeEach(() => {
+ db.saveAgent(agent('a2', 'theo')) // on Claude, like the others
+ db.saveAgent(agent('a3', 'bia'))
+ db.createConversation({ id: 'c3', kind: 'channel', name: 'time', members: ['a1', 'a2', 'a3'] })
+ db.createConversation({ id: 'c4', kind: 'channel', name: 'outro', members: ['a1', 'a2'] })
+ })
+
+ it('answers hand-offs that arrive while the agent replies once more, after, never at the same time', async () => {
+ const t = slowTheo(800)
+ const r = runner(t.engine)
+ await r.send('c3', '@lia @bia começam')
+ await r.idle()
+ expect(by('a2').map((m) => [m.run?.status, m.run?.depth])).toEqual([['done', 2], ['done', 2]])
+ expect(t.max()).toBe(1)
+ // Whoever reached Theo while he was replying says so on their reply.
+ const notes = [...by('a1'), ...by('a3')].flatMap((m) => m.run!.steps.map((x) => x.detail ?? ''))
+ expect(notes.some((x) => x.includes('já está respondendo'))).toBe(true)
+ })
+
+ it('keeps conversations parallel: the same agent replies in two at once', async () => {
+ const t = slowTheo(300)
+ const r = runner(t.engine)
+ await Promise.all([r.send('c1', '@lia começa'), r.send('c4', '@lia começa')])
+ await r.idle()
+ expect(by('a2')).toHaveLength(2)
+ expect(t.max()).toBe(2)
+ })
+
+ it('drops the follow-up when the reply it waited for was stopped', async () => {
+ const t = slowTheo(2000)
+ const r = runner(t.engine)
+ await r.send('c3', '@lia @bia começam')
+ for (let i = 0; i < 100 && !(by('a2')[0]?.run?.status === 'working' && by('a1')[0]?.run?.steps.some((x) => x.label === 'Chamou') && by('a3')[0]?.run?.steps.some((x) => x.label === 'Chamou')); i++) await new Promise((res) => setTimeout(res, 10))
+ r.stop(by('a2')[0]!.id)
+ await r.idle()
+ expect(by('a2').map((m) => m.run?.status)).toEqual(['stopped'])
+ })
+})
+
describe('Db', () => {
it('marks runs left working as interrupted on startup', () => {
db.saveMessage({ id: 'm1', conversationId: 'd1', author: { kind: 'agent', id: 'a1' }, text: 'meio', at: 1, run: { status: 'working', steps: [{ id: 's', label: 'Pensando', status: 'running' }] } })