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.

Show replies in the order they ended (#173)

Diasec8c2655d6cb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5303cf8..a08c7ca 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ What changed in each version of Tucano. The format follows [Keep a Changelog](ht
### Fixed
- **An agent's Chrome gets more time to open.** The first open on a slow computer could pass the 15 s it had, and the agent got an error instead of the page. It now gets 30 s.
+- **Replies show in the order they ended.** With several agents answering at once, a reply that took longer stayed above one that was already done. Now it takes its place when it ends, with that time on it, and whoever is still working stays at the end of the conversation. Agents still read each other in the order they started, so what each one saw doesn't change.
## [0.2.14] - 2026-11-06
diff --git a/src/core/runs.ts b/src/core/runs.ts
index 9fa11b6..4bd62d7 100644
--- a/src/core/runs.ts
+++ b/src/core/runs.ts
@@ -647,7 +647,7 @@ export class Runner {
if (used >= agent.limit) {
save({
text: L('Parei: usei todo o meu limite de tokens deste mês. Dá pra aumentar na minha página.', "I stopped: I've used all my tokens for this month. It can be raised on my page."),
- run: { status: 'limit_reached', depth: opts.depth, steps: [], ...again }
+ run: { status: 'limit_reached', endedAt: Date.now(), depth: opts.depth, steps: [], ...again }
})
return msg
}
@@ -658,6 +658,7 @@ export class Runner {
save({
run: {
status: 'failed',
+ endedAt: Date.now(),
depth: opts.depth,
steps: [],
...again,
@@ -674,6 +675,7 @@ export class Runner {
save({
run: {
status: 'failed',
+ endedAt: Date.now(),
depth: opts.depth,
steps: [],
...again,
@@ -1527,7 +1529,8 @@ export class Runner {
this.controllers.delete(msg.id)
}
- const ms = Date.now() - started
+ const endedAt = Date.now()
+ const ms = endedAt - started
const receipt: Receipt | undefined = result
? { model: modelId, ms, ...result.usage }
: progress.tokens > 0
@@ -1554,7 +1557,7 @@ export class Runner {
)
}
- const base = { depth: opts.depth, work, receipt, question, approvalId: approval?.id, memoryIds: memoryIds.length ? memoryIds : undefined, artifactIds: artifactIds.length ? artifactIds : undefined, services: services.length ? services : undefined, routineIds: routineIds.length ? routineIds : undefined, browser: msg.run?.browser, agentDraft: msg.run?.agentDraft, proposal: msg.run?.proposal }
+ const base = { endedAt, depth: opts.depth, work, receipt, question, approvalId: approval?.id, memoryIds: memoryIds.length ? memoryIds : undefined, artifactIds: artifactIds.length ? artifactIds : undefined, services: services.length ? services : undefined, routineIds: routineIds.length ? routineIds : undefined, browser: msg.run?.browser, agentDraft: msg.run?.agentDraft, proposal: msg.run?.proposal }
if (control.reason === 'stopped') {
save({ run: { ...base, ...again, status: 'stopped', steps: closeThinking('error', L('Parado', 'Stopped')) } })
} else if (control.reason === 'loop' || control.reason === 'errors' || control.reason === 'stall' || control.reason === 'sleeping') {
diff --git a/src/renderer/src/components/Conversation.tsx b/src/renderer/src/components/Conversation.tsx
index 58ee698..8cb5c08 100644
--- a/src/renderer/src/components/Conversation.tsx
+++ b/src/renderer/src/components/Conversation.tsx
@@ -4,6 +4,7 @@ import Markdown, { type ExtraProps } from 'react-markdown'
import { safeUrl } from '../links'
import { remarkLocalPaths } from '../../../shared/path-text'
import { remarkMentions, splitMentions } from '../../../shared/mention-text'
+import { asSaid, saidAt } from '../../../shared/types'
import { localLinkFor } from './LocalLink'
import remarkGfm from 'remark-gfm'
import { KeepInWiki, WikiChip, WikiLink, wikiLinks } from './Wiki'
@@ -198,15 +199,16 @@ export function MessageList({ messages: all, conversationId, empty, focus, threa
const stick = useRef(true)
const [farFromBottom, setFarFromBottom] = useState(false)
const { messages, replies } = useMemo(() => {
- if (!threads) return { messages: all, replies: undefined }
+ const said = asSaid(all)
+ if (!threads) return { messages: said, replies: undefined }
const replies = new Map<string, Message[]>()
- for (const m of all) {
+ for (const m of said) {
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 }
+ return { messages: said.filter((m) => !m.threadId), replies }
}, [all, threads])
// In a DM, whose it is (for the empty state).
const dmName = useStore((s) => {
@@ -373,7 +375,7 @@ const MessageRow = memo(function MessageRow({ message, grouped, replies }: { mes
{L('no seu computador', 'on your computer')}
</span>
)}
- <span className="msg__time">{time(message.at)}</span>
+ <span className="msg__time">{time(saidAt(message))}</span>
</div>
)}
{message.run && <RunSteps message={message} />}
@@ -546,7 +548,7 @@ function ThreadLink({ message, replies }: { message: Message; replies: Message[]
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 fresh = open ? 0 : done.filter((m) => m.author.kind !== 'me' && saidAt(m) > seen).length
const go = (): void => openThread(message.id)
return (
<>
@@ -577,7 +579,7 @@ function ThreadLink({ message, replies }: { message: Message; replies: Message[]
)}
{!busy.length && !asks && last && (
<span className="thread-link__when">
- <span className="thread-link__ago">{ago(last.at)}</span>
+ <span className="thread-link__ago">{ago(saidAt(last))}</span>
<span className="thread-link__see">{L('Ver thread', 'View thread')}</span>
</span>
)}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 4272185..799d6c7 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -159,6 +159,7 @@ export type RunStatus = 'working' | 'waiting_input' | 'waiting_approval' | 'done
export interface Run {
status: RunStatus
steps: Step[]
+ endedAt?: number // when this reply ended, however it ended: where the conversation shows it (saidAt)
receipt?: Receipt
approvalId?: string
error?: string // what happened and what to do, for people (src/shared/errors.ts)
@@ -222,6 +223,16 @@ export interface Message {
threadSummary?: ThreadSummary // on the message that started a thread: what the thread has covered
}
+// When a message was said: a reply when it ended, anything else when it was written. `at` stays when it
+// started, since that's what decides what it had read: agents read each other in that order.
+export const saidAt = (m: Message): number => m.run?.endedAt ?? m.at
+
+// A conversation as people read it: in the order things were said, and whoever is still working at the end.
+export function asSaid(messages: Message[]): Message[] {
+ const working = (m: Message): boolean => m.run?.status === 'working'
+ return [...messages.filter((m) => !working(m)).sort((a, b) => saidAt(a) - saidAt(b)), ...messages.filter(working).sort((a, b) => a.at - b.at)]
+}
+
// A thread's own summary, kept on its first message. `until`: the `at` of the last message it covers.
export interface ThreadSummary {
text: string
diff --git a/test/reply-order.test.ts b/test/reply-order.test.ts
new file mode 100644
index 0000000..e9e6a2c
--- /dev/null
+++ b/test/reply-order.test.ts
@@ -0,0 +1,145 @@
+import { mkdtempSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { asSaid, saidAt, type Agent, type EngineId, type Message, type RunStatus, type Settings } from '../src/shared/types'
+import { Db } from '../src/core/db'
+import { fakeEngine } from '../src/core/engines/fake'
+import type { Engine, EngineEvent, Turn } from '../src/core/engines/types'
+import { Runner } from '../src/core/runs'
+
+describe('asSaid', () => {
+ const said = (id: string, at: number, status?: RunStatus, endedAt?: number): Message => ({
+ id,
+ conversationId: 'c',
+ author: status ? { kind: 'agent', id: 'a' } : { kind: 'me' },
+ text: id,
+ at,
+ ...(status ? { run: { status, steps: [], ...(endedAt ? { endedAt } : {}) } } : {})
+ })
+ const ids = (messages: Message[]): string[] => asSaid(messages).map((m) => m.id)
+
+ it('puts a reply where it ended, not where it started', () => {
+ expect(ids([said('pedido', 1), said('lenta', 2, 'done', 9), said('rápida', 3, 'done', 4), said('depois', 5)])).toEqual(['pedido', 'rápida', 'depois', 'lenta'])
+ })
+
+ it('leaves whoever is still working at the end, in the order they started', () => {
+ expect(ids([said('pedido', 1), said('b', 3, 'working'), said('a', 2, 'working'), said('pronta', 4, 'done', 5), said('depois', 6)])).toEqual(['pedido', 'pronta', 'depois', 'a', 'b'])
+ })
+
+ it('counts a reply as said however it ended, or that it asks something', () => {
+ for (const status of ['done', 'failed', 'stopped', 'limit_reached', 'paused', 'waiting_input', 'waiting_approval'] as const) expect(ids([said('r', 1, status, 5), said('m', 3)])).toEqual(['m', 'r'])
+ })
+
+ it('leaves replies with no end where they started: older ones, and those cut when the app closed', () => {
+ expect(ids([said('antiga', 1, 'done'), said('m', 2), said('cortada', 3, 'interrupted'), said('n', 4)])).toEqual(['antiga', 'm', 'cortada', 'n'])
+ expect(saidAt(said('antiga', 1, 'done'))).toBe(1)
+ })
+
+ it('leaves the list it was given as it was', () => {
+ const list = [said('lenta', 1, 'done', 9), said('m', 2)]
+ asSaid(list)
+ expect(list.map((m) => m.id)).toEqual(['lenta', 'm'])
+ })
+})
+
+describe('replies that overlap', () => {
+ const ready = { installed: true, loggedIn: true }
+ const agent = (id: string, handle: string, extra: Partial<Agent> = {}): Agent => ({ id, name: handle, 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 turns: Turn[]
+ let broken: boolean
+
+ // Lia takes much longer than Theo, so she starts first and ends last. Her turns can fail on demand.
+ function runner(): Runner {
+ turns = []
+ broken = false
+ const fast = fakeEngine('claude', { delayMs: 1, sessions: true })
+ const slow = fakeEngine('claude', { delayMs: 40, sessions: true })
+ const isLia = (t: Turn): boolean => t.system.startsWith('Você é lia')
+ const claude: Engine = {
+ ...fast,
+ async *run(t: Turn): AsyncIterable<EngineEvent> {
+ if (isLia(t)) turns.push(t)
+ if (isLia(t) && broken) {
+ yield { type: 'error', message: 'quebrou' }
+ return
+ }
+ yield* (isLia(t) ? slow : fast).run(t)
+ }
+ }
+ const engines: Record<EngineId, Engine> = { claude, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor'), grok: fakeEngine('grok') }
+ const settings: Settings = { workspaceName: 'Edu', context: '', engines: { claude: ready, codex: ready, opencode: ready, pi: ready, gemini: ready, cursor: ready, grok: ready }, routerModel: 'haiku', memoryModel: 'haiku', memoryLearning: 'approve', defaultLimit: 1000, approvalTtlHours: 24, theme: 'system', language: 'pt' }
+ return new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ro-work-')) })
+ }
+
+ const whose = (m: Message): string => (m.author.kind === 'agent' ? m.author.id : m.author.kind)
+ const of = (id: string): Message => db.messages().find((m) => whose(m) === id)!
+
+ // Lia is asked first and is at work when Theo is asked: two messages, since agents called in one may take turns.
+ const overlap = async (r: Runner): Promise<void> => {
+ await r.send('c', '@lia bom dia')
+ await vi.waitFor(() => expect(turns).toHaveLength(1))
+ await r.send('c', '@theo bom dia')
+ await r.idle()
+ }
+
+ beforeEach(() => {
+ db = new Db(join(mkdtempSync(join(tmpdir(), 'ro-db-')), 'test.db'))
+ db.saveAgent(agent('lia', 'lia'))
+ db.saveAgent(agent('theo', 'theo'))
+ db.createConversation({ id: 'c', kind: 'channel', name: 'geral', members: ['lia', 'theo'] })
+ })
+
+ it('shows the one that ended last below the other, with the time it ended', async () => {
+ await overlap(runner())
+
+ expect(of('lia').at).toBeLessThan(of('theo').at) // she started first…
+ expect(of('lia').run!.endedAt!).toBeGreaterThan(of('theo').run!.endedAt!) // …and ended last
+ expect(asSaid(db.messages()).map(whose)).toEqual(['me', 'me', 'theo', 'lia'])
+ expect(saidAt(of('lia'))).toBe(of('lia').run!.endedAt)
+ })
+
+ it('goes on with the session it had: what the other said while it worked is simply new to it', async () => {
+ const r = runner()
+ await overlap(r)
+ await r.send('c', '@lia e agora?')
+ await r.idle()
+
+ const [first, second] = turns
+ expect(second!.session).toEqual({ id: first!.session!.id, resume: true, keep: true })
+ expect(second!.blocks).toHaveLength(3)
+ expect(second!.blocks![0]).toMatch(/theo bom dia$/)
+ expect(second!.blocks![1]).toMatch(/^\[theo · agente/)
+ expect(second!.blocks![2]).toMatch(/e agora\?$/)
+ expect(db.messages().map(whose)).toEqual(['me', 'lia', 'me', 'theo', 'me', 'lia']) // agents read in the order they started
+ })
+
+ it('marks the end of a reply that failed, and a new end when it is tried again', async () => {
+ const r = runner()
+ broken = true
+ await r.send('c', '@lia bom dia')
+ await r.idle()
+ const failed = of('lia')
+ expect(failed.run).toMatchObject({ status: 'failed', endedAt: expect.any(Number) })
+
+ await r.send('c', '@theo oi')
+ await r.idle()
+ expect(asSaid(db.messages()).map(whose)).toEqual(['me', 'lia', 'me', 'theo'])
+
+ broken = false
+ r.retry(failed.id)
+ await r.idle()
+ expect(of('lia').run!.status).toBe('done')
+ expect(asSaid(db.messages()).map(whose)).toEqual(['me', 'me', 'theo', 'lia'])
+ })
+
+ it('marks the end of a reply that never got to run', async () => {
+ db.saveAgent(agent('lia', 'lia', { limit: 0 }))
+ const r = runner()
+ await r.send('c', '@lia bom dia')
+ await r.idle()
+ expect(of('lia').run).toMatchObject({ status: 'limit_reached', endedAt: expect.any(Number) })
+ })
+})