The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Batch X: Swarm chat threads (#2132), leaderboard follow-ups (#2128), switcher Buddy row (#2135) (#2136)
0xken15a01d2a3316e7
diff --git a/backend/integration/superTabIndexes.test.ts b/backend/integration/superTabIndexes.test.tsindex 462860b6a..635d98693 100644--- a/backend/integration/superTabIndexes.test.ts+++ b/backend/integration/superTabIndexes.test.ts@@ -6,7 +6,7 @@ import { tmpdir } from 'node:os'import { afterAll, beforeAll, describe, expect, it } from 'vitest'import { MongoMemoryReplSet } from 'mongodb-memory-server-core'import { PrismaClient } from '@prisma/client'-import { inConversationOrder, pageDeliveries, pageReactions } from '../src/superTabs/pageReads.js'+import { inConversationOrder, pageDeliveries, pageReactions, pageThreads } from '../src/superTabs/pageReads.js'import { costRows } from '../src/superTabs/costs/read.js'import { recentDecisions } from '../src/superTabs/routeDecisions.js'import { settleStuckDeliveries } from '../src/superTabs/deliverySettle.js'@@ -99,6 +99,28 @@ describe('message page reads', () => {expect(profile).toEqual({ plans: ['IXSCAN { tabId: 1, messageId: 1 }'], docsExamined: 1001, returned: 1001 })})+ it('reads a page\'s threads through the tabId+conversationId+thread index, examining only their messages', async () => {+ // 300 top-level messages in one conversation, every tenth with three replies, beside another conversation's.+ const rows = []+ for (const conversationId of ['t0', 't1']) {+ for (let m = 0; m < 300; m++) {+ const root = `${conversationId}-m${pad(m)}`+ rows.push({ id: root, thread: root, sequence: m * 4 })+ if (m % 10 === 0) for (let r = 1; r <= 3; r++) rows.push({ id: `${root}-r${r}`, thread: root, sequence: m * 4 + r })+ }+ }+ await db.superTabMessage.createMany({ data: rows.map(row => ({ ...row, tabId: 'T', conversationId: row.id.slice(0, 2), text: 'x',+ author: { kind: 'person', id: 'owner', name: 'owner', membershipGeneration: 'gen' }, recipientIds: [], mentions: [],+ createdAt: new Date(T0 + row.sequence * 1000) })) })+ const roots = Array.from({ length: 100 }, (_, i) => `t0-m${pad(100 + i)}`)+ const [threads, profile] = await profiled('SuperTabMessage', () => pageThreads(db, 'T', 't0', roots))+ expect(threads).toHaveLength(130)+ expect(threads.filter(row => row.id !== row.thread).map(row => row.id).slice(0, 3)).toEqual(['t0-m100-r1', 't0-m100-r2', 't0-m100-r3'])+ expect(threads[0]).toEqual({ thread: 't0-m100', id: 't0-m100', author: expect.objectContaining({ id: 'owner' }), mentions: [],+ sequence: 400, createdAt: new Date(T0 + 400_000), agentOnly: false })+ expect(profile).toEqual({ plans: ['IXSCAN { tabId: 1, conversationId: 1, thread: 1, sequence: 1 }'], docsExamined: 130, returned: 130 })+ })+it('reads a page of reactions through the tabId+messageId index, examining only the reactions it returns', async () => {const [rows, profile] = await profiled('SuperTabReaction', () => pageReactions(db, 'A', PAGE))expect(rows).toHaveLength(200)diff --git a/backend/integration/superTabProfile.test.ts b/backend/integration/superTabProfile.test.tsindex 37c3c90bc..65d43aa2d 100644--- a/backend/integration/superTabProfile.test.ts+++ b/backend/integration/superTabProfile.test.ts@@ -340,7 +340,7 @@ describe('reactions', () => {const tab = await swarm()const messageId = await post(tab)const poll = async () => (await read(tab, peer, 'conversations/lead/messages?after=1000000')).body.data as { messages: unknown[]; reactionSeq: number }- expect(await poll()).toEqual({ messages: [], next: null, reactionSeq: 0 })+ expect(await poll()).toEqual({ messages: [], next: null, reactionSeq: 0, threads: [] })await react(tab, messageId, true)expect((await poll()).reactionSeq).toBe(1)})diff --git a/backend/integration/superTabs.test.ts b/backend/integration/superTabs.test.tsindex 424151dfc..46a2e1dcc 100644--- a/backend/integration/superTabs.test.ts+++ b/backend/integration/superTabs.test.ts@@ -1164,6 +1164,68 @@ describe('Super Tabs on a real Mongo replica set', () => {expect(await store.delivery(host, tab, lead, delivery.id, { type: 'hold', claimId: 'claim', reason: 'team_waiting_idle' })).toEqual({ held: false })})+ it('files replies under their thread root, summarises each thread for its page, and reads one thread', async () => {+ const { tab, lead } = await fixture()+ await invite(tab)+ const reply = (text: string, replyTo: string, extra: Record<string, unknown> = {}) =>+ ({ type: 'message.send', conversationId: 'lead', text, replyTo, recipientIds: [], ...extra }) as Command+ const root = String((await run(tab, message('Should we do thread replies?'))).result.messageId)+ const first = String((await run(tab, reply('Yes, threads.', root, { mentions: [owner.sub] }), host, lead)).result.messageId)+ // A reply only in its thread leaves the chat's newest main-stream message where it was; an also-sent one moves it.+ const lead1 = async () => (await store.read(owner, tab)).state.conversations.find(c => c.id === 'lead')!+ const afterFirst = await lead1()+ expect(afterFirst.lastMainSequence).toBe(afterFirst.lastMessageSequence - 1)+ const second = String((await run(tab, reply('Agreed.', first, { alsoSend: true }), peer)).result.messageId)+ const after = String((await run(tab, message('Next topic.'))).result.messageId)+ const afterAll = await lead1()+ expect(afterAll.lastMainSequence).toBe(afterAll.lastMessageSequence)++ // Agents read one feed: every reply, each with its thread root.+ const feed = (await store.messages(host, tab, 'lead', {}, lead)).messages+ expect(feed.map(m => [m.id, m.thread, m.alsoInChat ?? null])).toEqual(+ [[root, root, null], [first, root, null], [second, root, true], [after, after, null]])+ expect(feed.find(m => m.id === second)!.replyTo).toBe(first)+ const page = await store.messages(owner, tab, 'lead', {})+ const last = feed.find(m => m.id === second)!+ expect(page.threads).toEqual([{ id: root, replies: 2, lastSequence: last.sequence, lastAt: last.createdAt,+ authors: [expect.objectContaining({ kind: 'person', id: peer.sub }), expect.objectContaining({ kind: 'agent', id: lead })],+ people: [owner.sub, peer.sub] }])+ // A poll that reads only a new reply still learns its root's summary.+ const poll = await store.messages(owner, tab, 'lead', { after: feed.find(m => m.id === first)!.sequence })+ expect(poll.threads.map(t => [t.id, t.replies])).toEqual([[root, 2]])++ const thread = await store.messages(owner, tab, 'lead', { thread: root })+ expect(thread.messages.map(m => m.id)).toEqual([root, first, second])+ expect(thread.threads.map(t => t.id)).toEqual([root])++ // A person who leaves is no longer named, though their reply stays.+ await run(tab, { type: 'member.remove', userId: peer.sub })+ const left = (await store.messages(owner, tab, 'lead', { thread: root })).threads[0]!+ expect(left.people).toEqual([owner.sub])+ expect(left.authors.map(a => a.id)).toEqual([lead])+ expect(left.replies).toBe(2)+ })++ it('keeps a reply to a message written before threads inline, and refuses a thread of a conversation the reader cannot see', async () => {+ const { tab } = await fixture()+ await invite(tab)+ const old = randomUUID().replaceAll('-', '').slice(0, 24)+ await db.superTabMessage.create({ data: { id: old, tabId: tab, conversationId: 'lead', sequence: 0,+ author: { kind: 'person', id: owner.sub, name: owner.email, membershipGeneration: 'g' }, text: 'Before threads.', recipientIds: [], mentions: [] } })+ const answer = String((await run(tab, { type: 'message.send', conversationId: 'lead', text: 'Answered inline.', replyTo: old, recipientIds: [],+ alsoSend: true }, peer)).result.messageId)+ const rows = (await store.messages(owner, tab, 'lead', {})).messages+ expect(rows.find(m => m.id === answer)).toMatchObject({ replyTo: old, thread: answer, alsoInChat: null })+ expect(rows.find(m => m.id === old)!.thread).toBeNull()++ const project = (await run(tab, { type: 'project.create', name: 'Private project', visibility: 'private', brief: '' })).result+ const hidden = String(project.conversationId)+ const secret = String((await run(tab, { ...message('Private root'), conversationId: hidden } as Command)).result.messageId)+ await expect(store.messages(peer, tab, hidden, { thread: secret })).rejects.toMatchObject({ code: 'NOT_FOUND' })+ // A root named under another conversation reads nothing of it.+ expect((await store.messages(peer, tab, 'lead', { thread: secret })).messages).toEqual([])+ })+it('delivers a Lead\'s agent-only notice to the Lead once and shows it to no person in the project chat', async () => {const { tab, lead } = await fixture()await invite(tab)diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prismaindex c38e268bb..6dae9bdc8 100644--- a/backend/prisma/schema.prisma+++ b/backend/prisma/schema.prisma@@ -1084,10 +1084,17 @@ model SuperTabMessage {recipientIds String[]/// People a Lead tagged (superTabs/mentions.ts); absent on older rows.mentions String[]+ /// The thread's root (superTabs/threads.ts): a top-level message's own id, a reply's root. Absent on rows written before+ /// threads, whose replies stay inline quotes.+ thread String?+ /// A thread reply also shown in the conversation's main stream.+ alsoInChat Boolean?createdAt DateTime @default(now())/// Pages read by (sequence, id): older rows of one command share a sequence.@@index([tabId, conversationId, sequence, id])+ /// One thread's page, and a page's thread summaries (superTabs/pageReads.ts pageThreads).+ @@index([tabId, conversationId, thread, sequence])}/// A Lead's tag of a person, waiting until they reply in that conversation or mark it done (superTabs/mentions.ts).diff --git a/backend/src/routes/superTabs.ts b/backend/src/routes/superTabs.tsindex 566ec8d83..82a3c6de1 100644--- a/backend/src/routes/superTabs.ts+++ b/backend/src/routes/superTabs.ts@@ -64,7 +64,9 @@ const nativeParams = tabParams.extend({ contextId: id })const messageParams = tabParams.extend({ conversationId: id })// Pages by (sequence, id) (design 4.6): `afterId`/`beforeId` go with `after`/`before`, from the previous page's `next`.const messageQuery = agentQuery.extend({ after: z.coerce.number().int().nonnegative().safe().optional(),- before: z.coerce.number().int().nonnegative().safe().optional(), messageId: id.optional(), afterId: id.optional(), beforeId: id.optional() })+ before: z.coerce.number().int().nonnegative().safe().optional(), messageId: id.optional(), afterId: id.optional(), beforeId: id.optional(),+ // One thread's root and replies, paged like the conversation.+ thread: id.optional() }).refine(q => [q.after, q.before, q.messageId].filter(value => value !== undefined).length <= 1, 'Choose one message cursor or exact message.').refine(q => (q.afterId === undefined || q.after !== undefined) && (q.beforeId === undefined || q.before !== undefined), 'Send afterId with after, beforeId with before.')const decisionParams = tabParams.extend({ decisionId: id })diff --git a/backend/src/superTabs/commands.test.ts b/backend/src/superTabs/commands.test.tsindex 166f5bc87..22716beab 100644--- a/backend/src/superTabs/commands.test.ts+++ b/backend/src/superTabs/commands.test.ts@@ -237,6 +237,27 @@ describe('Super Tab collaboration policy', () => {{ reply: { id: posted.id, conversationId: 'elsewhere', author: posted.author, createdAt: 0 } })).toThrow('Reply to a message in this conversation')})+ it('files a reply under its thread root, never a nested thread, and keeps a reply to a pre-thread message inline', () => {+ const f = fixture()+ const lead = f.add('lead', 'owner', 'lead', true)+ const root = f.run({ type: 'message.send', conversationId: 'lead', text: 'Should we do threads?', replyTo: null, recipientIds: [] }).messages[0]!+ expect(root.thread).toBeUndefined()+ const first = f.run({ type: 'message.send', conversationId: 'lead', text: 'Yes.', replyTo: root.id, recipientIds: [] },+ { kind: 'agent', agentId: lead, machineOwnerId: 'host-owner' }, { reply: { id: root.id, conversationId: 'lead', author: root.author, createdAt: 0, thread: root.id } }).messages[0]!+ expect(first).toMatchObject({ replyTo: root.id, thread: root.id })+ expect(first.alsoInChat).toBeUndefined()+ // A reply to a reply joins the root's thread.+ const second = f.run({ type: 'message.send', conversationId: 'lead', text: 'Agreed.', replyTo: first.id, recipientIds: [], alsoSend: true },+ owner, { reply: { id: first.id, conversationId: 'lead', author: first.author, createdAt: 0, thread: root.id } }).messages[0]!+ expect(second).toMatchObject({ replyTo: first.id, thread: root.id, alsoInChat: true })+ // A message written before threads has none: a reply to it stays an inline quote.+ const inline = f.run({ type: 'message.send', conversationId: 'lead', text: 'Old question answered.', replyTo: 'old-message', recipientIds: [], alsoSend: true },+ owner, { reply: { id: 'old-message', conversationId: 'lead', author: root.author, createdAt: 0, thread: null } }).messages[0]!+ expect(inline.replyTo).toBe('old-message')+ expect(inline.thread).toBeUndefined()+ expect(inline.alsoInChat).toBeUndefined()+ })+it('delivers an assigned worker\'s own post to its Lead, and nobody else\'s', () => {const f = fixture()const lead = f.add('lead', 'owner', 'lead', true)diff --git a/backend/src/superTabs/commands.ts b/backend/src/superTabs/commands.tsindex b58502da7..70d90890a 100644--- a/backend/src/superTabs/commands.ts+++ b/backend/src/superTabs/commands.ts@@ -166,7 +166,7 @@ export const commandSchema = z.discriminatedUnion('type', [z.object({ type: z.literal('agent.avatar'), agentId: id, avatar: avatarChoice }).strict(),// Text may be empty when the message carries files; applyCommand checks that one of them is there.z.object({ type: z.literal('message.send'), conversationId: id, text: z.string().trim().max(32_000), replyTo: id.nullable(), recipientIds: z.array(id).max(16),- attachmentIds: z.array(id).max(MAX_ATTACHMENTS).optional(), mentions: z.array(id).max(MAX_MENTIONS).optional(), agentOnly: z.literal(true).optional() }).strict(),+ alsoSend: z.literal(true).optional(), attachmentIds: z.array(id).max(MAX_ATTACHMENTS).optional(), mentions: z.array(id).max(MAX_MENTIONS).optional(), agentOnly: z.literal(true).optional() }).strict(),z.object({ type: z.literal('mention.done'), mentionId: id }).strict(),z.object({ type: z.literal('message.react'), conversationId: id, messageId: id, emoji: reactionSchema, on: z.boolean() }).strict(),z.object({ type: z.literal('decision.ask'), conversationId: id, personId: id, questions: z.array(decisionQuestion).min(1).max(MAX_QUESTIONS) }).strict(),@@ -271,12 +271,13 @@ export interface CommandContext {/** A Harness Team account's machine: the Mac it lives on, from its account row (machines.ts ContributedMachine). */hostMachineId?: string }/** Loaded from this tab and conversation by the store. */- reply?: { id: string; conversationId: string; author: Author; createdAt: number }+ /** `thread` is the replied message's thread root, null for a message written before threads (it keeps inline replies). */+ reply?: { id: string; conversationId: string; author: Author; createdAt: number; thread?: string | null }/** For a person's `message.send`: the tags waiting on them in that conversation, read by the store (leaderboard/record.ts). */openTags?: Array<{ messageId: string; createdAt: number }>- /** The message a Buddy's proposal names as its owner's request, loaded from this tab by the store. *//** The proposal a new group names as its origin (conversation.create proposalMessageId), loaded from this tab by the store. */proposal?: { id: string; conversationId: string; author: Author; source: Record<string, unknown> | null }+ /** The message a Buddy's proposal names as its owner's request, loaded from this tab by the store. */proposalAsk?: { id: string; conversationId: string; author: Author; source: boolean; createdAt: number/** The owner's newest message in that chat, which may always be named. */newestOwnerMessageId?: string }@@ -1765,6 +1766,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Comma}// The transcript still accepts a human message while the lead is unavailable. The UI can say why no delivery was created.message(group.id, command.text, recipients, command.replyTo, command.agentOnly ? AGENT_ONLY : undefined, attachments, mentions)+ // A reply joins its message's thread, always at the root, so threads never nest.+ const thread = command.replyTo ? context.reply?.thread : null+ if (thread) Object.assign(effects.messages.at(-1)!, { thread, ...(command.alsoSend ? { alsoInChat: true } : {}) })recordPost(state, group, actor, { replyTo: command.replyTo, text: command.text, reply: context.reply, openTags: context.openTags }, context.now)if (actor.kind === 'agent') renewOwnTask(group, actor.agentId, context.now)leadActed(group.id, 'post')@@ -2057,8 +2061,9 @@ export function applyCommand(original: SuperTabState, actor: Actor, input: Commaif (check.independent && actor.kind === 'agent' && actor.agentId === group.assignment.agentId) fail('INDEPENDENT_REVIEW', 'Another agent or a person must perform this check.')check.evidence = command.evidencecheck.passedBy = command.passed ? actorKey(actor) : null- recordReview(group, check, command.passed)+ // Before the review's first verdict is kept: a check's verdict counts once per attempt.if (actor.kind === 'agent') recordVerdict(state, group, check, agent(state, actor.agentId), context.now)+ recordReview(group, check, command.passed)if (actor.kind === 'agent') renewOwnTask(group, actor.agentId, context.now)break}diff --git a/backend/src/superTabs/leaderboard/record.test.ts b/backend/src/superTabs/leaderboard/record.test.tsindex 1d0c9714b..ed4fad5be 100644--- a/backend/src/superTabs/leaderboard/record.test.ts+++ b/backend/src/superTabs/leaderboard/record.test.ts@@ -607,33 +607,56 @@ describe('the model behind each assignment, and its first review (roadmap, Dec:const reviewer = f.add('reviewer', id)f.state.agents.find(a => a.id === reviewer)!.configuration = { ...config, engine: 'codex', model: 'gpt-5.5', effort: 'medium' }verdict(f, id, assignmentId, false, true, f.asAgent(reviewer))+ // The same check passed again on the same attempt is the same review (full review of #2097).verdict(f, id, assignmentId, true, true, f.asAgent(reviewer))// A person's verdict, and one on a check that is not a review, are no model's review.verdict(f, id, assignmentId, true)verdict(f, id, assignmentId, true, false, f.asAgent(reviewer))expect(f.group(id).ledger!.reviews).toEqual([- { week: weekStart(7_000), engine: 'codex', model: 'gpt-5.5', effort: 'medium', count: 2 },+ { week: weekStart(7_000), engine: 'codex', model: 'gpt-5.5', effort: 'medium', count: 1 },])+ // A new attempt is reviewed anew.+ f.run({ type: 'work.cancel', conversationId: id, assignmentId, reason: 'Again.' })+ const second = f.assign(id)+ verdict(f, id, second.assignmentId, true, true, f.asAgent(reviewer))+ expect(f.group(id).ledger!.reviews![0]!.count).toBe(2)})- it('counts every verdict exactly, however many a group gets in a week (review of #2097)', () => {+ it('gives no model credit for verdicts on an attempt recorded before attempts were (review of #2128)', () => {const f = fixture()const id = f.create(owner, { checks: independent })const { assignmentId } = f.assign(id)const reviewer = f.add('reviewer', id)- for (let i = 0; i < 45; i++) verdict(f, id, assignmentId, i % 2 === 0, true, f.asAgent(reviewer))+ // As an assignment from before attempts were recorded: no run, so no way to tell a repeat.+ delete f.group(id).ledger!.runs+ for (let i = 0; i < 3; i++) verdict(f, id, assignmentId, true, true, f.asAgent(reviewer))+ expect(f.group(id).ledger!.reviews).toBeUndefined()+ })++ it('counts every verdict exactly, however many a group gets in a week (review of #2097)', () => {+ const f = fixture()+ const id = f.create(owner, { checks: independent })+ const worker = f.add('worker', id), reviewer = f.add('reviewer', id)+ // 45 attempts, each reviewed once: more than the 20 attempts a group keeps.+ for (let i = 0; i < 45; i++) {+ const { assignmentId } = f.assign(id, worker)+ verdict(f, id, assignmentId, i % 2 === 0, true, f.asAgent(reviewer))+ f.run({ type: 'work.cancel', conversationId: id, assignmentId, reason: 'Again.' })+ }expect(f.group(id).ledger!.reviews).toEqual([{ week: weekStart(1_000), engine: 'claude', model: 'opus', effort: 'high', count: 45 }])})it('keeps review counts for the weeks the board reads, and drops older ones', () => {const f = fixture()const id = f.create(owner, { checks: independent })- const { assignmentId } = f.assign(id)- const reviewer = f.add('reviewer', id)+ const worker = f.add('worker', id), reviewer = f.add('reviewer', id)const start = weekStart(Date.UTC(2026, 9, 26))+ // A new attempt reviewed each week.for (let back = 6; back >= 0; back--) {f.at(start - back * WEEK_MS + DAY_MS)+ const { assignmentId } = f.assign(id, worker)verdict(f, id, assignmentId, true, true, f.asAgent(reviewer))+ f.run({ type: 'work.cancel', conversationId: id, assignmentId, reason: 'Again.' })}expect(f.group(id).ledger!.reviews!.map(r => (start - r.week) / WEEK_MS)).toEqual([4, 3, 2, 1, 0])})@@ -652,6 +675,23 @@ describe('the model behind each assignment, and its first review (roadmap, Dec:expect(f.group(id).ledger!.runs!.map(r => r.assignmentId)).not.toContain(first)})+ it('takes the asked time for a request recorded before the first assignment was kept, once its first attempt may have rolled off', () => {+ const f = fixture()+ f.at(1_000)+ const id = f.create(owner, { checks: independent })+ const worker = f.add('worker', id)+ for (let i = 0; i < 21; i++) {+ f.at(10_000 + i)+ const { assignmentId } = f.assign(id, worker)+ f.run({ type: 'work.cancel', conversationId: id, assignmentId, reason: 'Again.' })+ }+ // As a group recorded before the time was kept: 20 attempts kept, the first rolled off.+ delete f.group(id).ledger!.firstAssignedAt+ f.at(20_000)+ f.assign(id, worker)+ expect(f.group(id).ledger!.firstAssignedAt).toBe(1_000)+ })+it('takes the first assignment time from the kept attempts for a request recorded before it was kept (review of #2097)', () => {const f = fixture()const id = f.create(owner, { checks: independent })diff --git a/backend/src/superTabs/leaderboard/record.ts b/backend/src/superTabs/leaderboard/record.tsindex 563f9442b..1a119f448 100644--- a/backend/src/superTabs/leaderboard/record.ts+++ b/backend/src/superTabs/leaderboard/record.ts@@ -196,16 +196,29 @@ export function waitsNow(group: Conversation): boolean {export function recordRun(state: SuperTabState, group: Conversation, assignment: Assignment, worker: Agent, now: number): void {const run: Run = { assignmentId: assignment.id, ...ranOn(state, worker, assignment.configuration), at: now }const ledger = group.ledger ??= {}- // A request recorded before this time was kept still has its first attempt in [runs] until 20 more roll it off; only a- // request with no attempt yet starts now (review of #2097).- ledger.firstAssignedAt ??= ledger.runs?.[0]?.at ?? now+ ledger.firstAssignedAt ??= firstAssignedAt(ledger) ?? nowledger.runs = [...ledger.runs ?? [], run].slice(-MAX_RUNS)}+/** When a request's first attempt was assigned: kept since that was recorded. A request recorded before has its first+ * attempt in [runs] while fewer than MAX_RUNS are kept; once that many are, the first may have rolled off, so it takes+ * the time the request was asked (full review of #2097). Undefined for a request never assigned. */+export function firstAssignedAt(ledger: GroupLedger): number | undefined {+ if (ledger.firstAssignedAt != null) return ledger.firstAssignedAt+ const runs = ledger.runs ?? []+ if (!runs.length) return undefined+ return runs.length < MAX_RUNS ? runs[0]!.at : ledger.askedAt ?? runs[0]!.at+}+/** An agent's verdict on an independent check is one finished review by the model it runs on. */export function recordVerdict(state: SuperTabState, group: Conversation, check: Check, reviewer: Agent, now: number): void {if (!check.independent) returnconst ledger = group.ledger ??= {}+ // A check given again on the same attempt is the same review (full review of #2097): only its first verdict counts.+ // An attempt recorded before attempts were has no run to tell a repeat by, so it earns no model credit (review of+ // #2128).+ const run = ledger.runs?.find(r => r.assignmentId === group.assignment?.id)+ if (!run || run.firstVerdicts?.[check.id] !== undefined) returnconst on = ranOn(state, reviewer, reviewer.configuration), week = weekStart(now)// Only the weeks the board reads: one row per week and model, however many verdicts.const kept = (ledger.reviews ?? []).filter(r => week - r.week < LEDGER_WEEKS * WEEK_MS)diff --git a/backend/src/superTabs/leaderboard/stats.test.ts b/backend/src/superTabs/leaderboard/stats.test.tsindex 054ed0a68..50504d398 100644--- a/backend/src/superTabs/leaderboard/stats.test.ts+++ b/backend/src/superTabs/leaderboard/stats.test.ts@@ -334,6 +334,12 @@ describe('Models: temporary workers by engine, model and effort, never by agentexpect(model(view, 'opus').shipped).toMatchObject({ count: 1, medianAttemptMs: 0, medianRequestMs: 0 })})+ it('times a request recorded before its first assignment was kept from its asked time once 20 attempts are kept', () => {+ const runs = Array.from({ length: 20 }, (_, i) => run(`a${i}`, WEEK + (i + 1) * HOUR))+ const view = board(swarm(), [landed(WEEK + 30 * HOUR, runs, { askedAt: WEEK })])+ expect(model(view, 'opus').shipped.medianRequestMs).toBe(30 * HOUR)+ })+it('times the whole request from its first assignment, kept after its first attempt rolled off (review of #2097)', () => {const view = board(swarm(), [landed(WEEK + 5 * HOUR, [run('a21', WEEK + 4 * HOUR)], { firstAssignedAt: WEEK })])expect(model(view, 'opus').shipped).toMatchObject({ medianAttemptMs: HOUR, medianRequestMs: 5 * HOUR })@@ -408,6 +414,39 @@ describe('Agents: the permanent agents, the PM and Buddies, by name like peopleexpect(of(view, 'river')).toMatchObject({ points: 6, shipped: 2 })})+ it('keeps a removed Buddy and a replaced PM on the board for the weeks they earned in (full review of #2097)', () => {+ const state = agents(swarm())+ state.agents = state.agents.filter(a => a.id !== 'sparky')+ state.agents.push({ ...state.agents.find(a => a.id === 'river')!, id: 'old-pm', displayName: 'Atlas' })+ const ledger = (extra: object) => ({ askedAt: WEEK, shippedAt: WEEK + HOUR, ...extra })+ const view = board(state, [+ shipped('dee', WEEK, WEEK + HOUR, { ledger: ledger({ shippedLeadId: 'old-pm' }) }),+ shipped('dee', WEEK, WEEK + HOUR, { ledger: ledger({ shippedLeadId: 'gone-pm' }) }),+ shipped('dee', WEEK, WEEK + HOUR, { ledger: ledger({ shippedLeadId: null, proposal: { buddyId: 'sparky', messageId: 'm1' } }) }),+ ])+ expect(view.agents.map(a => [a.agentId, a.displayName, a.kind, a.points])).toEqual([+ ['old-pm', 'Atlas', 'pm', 3], ['gone-pm', 'Former PM', 'pm', 3], ['sparky', 'Former Buddy', 'buddy', 3], ['river', 'River', 'pm', 0]])+ // Last week they earned nothing, and only the current agents are listed.+ expect(board(state, [], LAST).agents.map(a => a.agentId)).toEqual(['river'])+ })++ it('never shows who a former agent is now when it was re-added in another project (privacy, review of #2128)', () => {+ const state = agents(swarm())+ // The same terminals, removed here and added again in a private project, under new names and owners.+ const river = state.agents.find(a => a.id === 'river')!+ state.agents.push({ ...river, id: 'old-pm', projectId: 'secret', displayName: 'Hidden', machineId: 'mac-secret' },+ { ...river, id: 'old-buddy', projectId: 'secret', displayName: 'Whisper', machineId: 'mac-secret', buddyOf: { personId: 'tony', generation: 'g' } })+ const ledger = (extra: object) => ({ askedAt: WEEK, shippedAt: WEEK + HOUR, ...extra })+ const view = board(state, [+ shipped('dee', WEEK, WEEK + HOUR, { ledger: ledger({ shippedLeadId: 'old-pm' }) }),+ shipped('dee', WEEK, WEEK + HOUR, { ledger: ledger({ shippedLeadId: null, proposal: { buddyId: 'old-buddy', messageId: 'm1' } }) }),+ ])+ const former = view.agents.filter(a => a.agentId.startsWith('old-')).map(a => [a.agentId, a.displayName, a.kind, a.personId, a.machineId])+ expect(former).toEqual([['old-pm', 'Former PM', 'pm', null, ''], ['old-buddy', 'Former Buddy', 'buddy', null, '']])+ // Nowhere in the board: the private registration's names and machine (its Buddy's owner is checked above).+ expect(JSON.stringify(view)).not.toMatch(/Hidden|Whisper|mac-secret/)+ })+it('gives a Buddy 3 points per group opened from its proposal that shipped this week', () => {const fromProposal = { askedAt: WEEK, shippedAt: WEEK + HOUR, proposal: { buddyId: 'sparky', messageId: 'm1' } }const view = board(agents(swarm()), [shipped('dee', WEEK, WEEK + HOUR, { ledger: fromProposal }), shipped('dee', WEEK, WEEK + HOUR)])diff --git a/backend/src/superTabs/leaderboard/stats.ts b/backend/src/superTabs/leaderboard/stats.tsindex 39264fcb8..d7c6326f3 100644--- a/backend/src/superTabs/leaderboard/stats.ts+++ b/backend/src/superTabs/leaderboard/stats.ts@@ -8,7 +8,7 @@ import type { ContributedMachine } from '../machines.js'import { isLeads, type Conversation, type SuperTabState } from '../model.js'import { isBuddy } from '../buddies.js'import { agentProjectId, canReadProject, projectOf } from '../projects.js'-import { waitedOn, waitsNow, type RanOn, type Unblock } from './record.js'+import { firstAssignedAt, waitedOn, waitsNow, type RanOn, type Unblock } from './record.js'import { DAY_MS, WEEK_MS } from './week.js'import type { AgentScore, Leaderboard, Medal, ModelScore, ModelShare, PersonDetails, PersonScore, WeekGoal } from './contract.js'@@ -103,21 +103,34 @@ export function leaderboard({ state, groups, machines: visibleMachines, projectI}}-/** The project's PM and Buddies with the requests each shipped this week: the PM by the groups it led, a Buddy by the groups- * opened from its proposals. Builders and Reviewers are counted by model instead (modelScores). */+/** The project's PM and Buddies with the requests each shipped this week: a PM by the groups it led when they shipped, a+ * Buddy by the groups opened from its proposals. One credited this week stays listed after it was removed or replaced,+ * as "Former PM" or "Former Buddy" once the Swarm no longer has it (full review of #2097). Builders and Reviewers are+ * counted by model instead (modelScores). */function agentScores(state: SuperTabState, projectId: string, shippedThisWeek: Conversation[]): AgentScore[] {const pmId = state.conversations.find(c => c.id === projectOf(state, projectId).leadConversationId)?.leadId- const scored = state.agents- .filter(a => a.id === pmId || (isBuddy(a) && agentProjectId(state, a) === projectId))- .map(a => {- const buddy = isBuddy(a)- // The lead recorded when it shipped; a request shipped before that was recorded, its lead now.- const ledBy = (g: Conversation) => g.ledger?.shippedLeadId !== undefined ? g.ledger.shippedLeadId : g.leadId- const shipped = shippedThisWeek.filter(g => buddy ? g.ledger?.proposal?.buddyId === a.id : ledBy(g) === a.id).length- return { agentId: a.id, displayName: a.displayName ?? a.name, kind: buddy ? 'buddy' as const : 'pm' as const,- personId: a.buddyOf?.personId ?? null, machineId: a.machineId, points: shipped * SHIPPED_POINTS, shipped }- })- .sort((a, b) => b.points - a.points || (a.kind === b.kind ? a.displayName.localeCompare(b.displayName) : a.kind === 'pm' ? -1 : 1))+ const shipped = new Map<string, { kind: 'pm' | 'buddy'; count: number }>()+ for (const a of state.agents) {+ if (a.id === pmId || (isBuddy(a) && agentProjectId(state, a) === projectId)) shipped.set(a.id, { kind: isBuddy(a) ? 'buddy' : 'pm', count: 0 })+ }+ const credit = (agentId: string, kind: 'pm' | 'buddy') => {+ const entry = shipped.get(agentId) ?? { kind, count: 0 }+ entry.count+++ shipped.set(agentId, entry)+ }+ for (const g of shippedThisWeek) {+ // The lead recorded when it shipped; a request shipped before that was recorded, its lead now.+ const ledBy = g.ledger?.shippedLeadId !== undefined ? g.ledger.shippedLeadId : g.leadId+ if (ledBy) credit(ledBy, 'pm')+ if (g.ledger?.proposal) credit(g.ledger.proposal.buddyId, 'buddy')+ }+ const scored = [...shipped].map(([agentId, { kind, count }]) => {+ // Who it is now only while it is this project's: an agent id stays the same when its terminal is added again+ // elsewhere, and a private project's names and owners are not this board's to show (review of #2128).+ const a = state.agents.find(agent => agent.id === agentId && agentProjectId(state, agent) === projectId)+ return { agentId, displayName: a ? a.displayName ?? a.name : kind === 'pm' ? 'Former PM' : 'Former Buddy', kind,+ personId: a?.buddyOf?.personId ?? null, machineId: a?.machineId ?? '', points: count * SHIPPED_POINTS, shipped: count }+ }).sort((a, b) => b.points - a.points || (a.kind === b.kind ? a.displayName.localeCompare(b.displayName) : a.kind === 'pm' ? -1 : 1))return scored.map(entry => ({ ...entry, rank: 1 + scored.filter(other => other.points > entry.points).length }))}@@ -142,7 +155,7 @@ function modelScores(requests: Conversation[], shippedThisWeek: Conversation[],entry.shipped.count++// Merged before its attempt started: shipped at once, never in negative time (Lead, 2026-10-29).entry.attemptMs.push(Math.max(0, shippedAt - last.at))- const first = ledger.firstAssignedAt ?? runs[0]?.at+ const first = firstAssignedAt(ledger)if (first != null) entry.requestMs.push(Math.max(0, shippedAt - first))}for (const group of requests) {diff --git a/backend/src/superTabs/model.ts b/backend/src/superTabs/model.tsindex 6167d10fe..ffdcbd8dd 100644--- a/backend/src/superTabs/model.ts+++ b/backend/src/superTabs/model.ts@@ -202,6 +202,9 @@ export interface Conversation {checks: Check[]assignment: Assignment | nulllastMessageSequence: number+ /** The sequence of its newest message in the main stream: a reply only in its thread leaves it (threads.ts). Absent until+ * this conversation's first message after threads; readers fall back to lastMessageSequence. */+ lastMainSequence?: number/** Linked GitHub pull requests, including links older than the latest message page. Absent in older snapshots. */pullRequestUrls?: string[]/** The last sequence given to a message here. Each conversation numbers its own messages (store by parts). */@@ -348,6 +351,10 @@ export interface MessageDraft {attachments?: import('./attachments.js').Attachment[]/** People a Lead tagged (mentions.ts). */mentions?: string[]+ /** The root of the thread this reply is in; absent on a top-level message, which is its own thread (writeMessages). */+ thread?: string+ /** A thread reply also shown in the conversation's main stream. */+ alsoInChat?: true}/** A notice for one agent alone (a skill update): delivered to it like any message, never shown to people or other agents. */export const AGENT_ONLY = { kind: 'agent-only' }diff --git a/backend/src/superTabs/native.ts b/backend/src/superTabs/native.tsindex a8a60f75c..3f15cb911 100644--- a/backend/src/superTabs/native.ts+++ b/backend/src/superTabs/native.ts@@ -234,7 +234,7 @@ export class SuperTabNativeStore {await tx.superTabMessage.create({ data: { id: eventId, tabId, conversationId: group.id, sequence,author: json(observedBy), source: json({ kind: 'native', phase: event.kind, turnId: event.turnId,operator: binding.operator, truncated: event.truncated, interrupted: event.interrupted, ...(recovery ? { recovery: recovery.source } : {}) }),- text, replyTo: event.kind === 'answer' ? promptId : null, recipientIds: recipients } })+ text, replyTo: event.kind === 'answer' ? promptId : null, recipientIds: recipients, thread: eventId } })for (const recipient of recipients) {const lead = agent(state, recipient)await tx.superTabDelivery.create({ data: { id: stableId(eventId, recipient), tabId, conversationId: group.id,diff --git a/backend/src/superTabs/pageReads.ts b/backend/src/superTabs/pageReads.tsindex deb376b7c..321288ddf 100644--- a/backend/src/superTabs/pageReads.ts+++ b/backend/src/superTabs/pageReads.ts@@ -1,6 +1,7 @@import type { Prisma, SuperTabDelivery } from '@prisma/client'import { ms } from './parts/light.js'import type { ReactionRow } from './reactions.js'+import { agentOnly, type Author } from './model.js'type Transaction = Prisma.TransactionClient@@ -55,3 +56,16 @@ export async function inConversationOrder<T extends Pick<SuperTabDelivery, 'conv}return ordered}++export interface ThreadReply { thread: string; id: string; author: Author; mentions: string[]; sequence: number; createdAt: Date; agentOnly: boolean }++/** Every message of the threads rooted at `roots` in one conversation, roots included, oldest first: what the page's thread+ * summaries are counted from. Matched as the page reads are, so the tabId+conversationId+thread index bounds it. */+export async function pageThreads(tx: Transaction, tabId: string, conversationId: string, roots: string[]): Promise<ThreadReply[]> {+ // Sorted here: a $sort in the pipeline makes the planner walk the conversation's sequence index instead.+ const rows = await tx.superTabMessage.aggregateRaw({ pipeline: [{ $match: { tabId, conversationId, thread: { $in: roots } } },+ { $project: { thread: 1, author: 1, mentions: 1, sequence: 1, createdAt: 1, source: 1 } }] }) as unknown as Array<Record<string, unknown>>+ return rows.map(row => ({ thread: row.thread as string, id: row._id as string, author: row.author as Author,+ mentions: (row.mentions ?? []) as string[], sequence: row.sequence as number, createdAt: new Date(ms(row.createdAt)),+ agentOnly: agentOnly(row.source) })).sort((a, b) => a.sequence - b.sequence || (a.id < b.id ? -1 : 1))+}diff --git a/backend/src/superTabs/parts/commit.ts b/backend/src/superTabs/parts/commit.tsindex 0bf3c39cd..4d1a5af0c 100644--- a/backend/src/superTabs/parts/commit.ts+++ b/backend/src/superTabs/parts/commit.ts@@ -96,6 +96,7 @@ export function numberMessages(state: SuperTabState, messages: MessageDraft[], nsequences.set(message.id, sequence)if (agentOnly(message.source)) continuegroup.lastMessageSequence = sequence+ if (!message.thread || message.alsoInChat) group.lastMainSequence = sequencegroup.lastActivityAt = new Date(now).toISOString()delete group.dormant}diff --git a/backend/src/superTabs/parts/light.test.ts b/backend/src/superTabs/parts/light.test.tsindex cb45640bf..0649c5ea7 100644--- a/backend/src/superTabs/parts/light.test.ts+++ b/backend/src/superTabs/parts/light.test.ts@@ -11,7 +11,7 @@ const assignment: Required<Assignment> = {}const conversation: Required<Conversation> = {id: 'g', kind: 'leads', projectId: 'p', number: 1, title: 't', leadId: null, agentIds: [], archived: false, brief: '',- task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', checks: [], assignment, lastMessageSequence: 0, pullRequestUrls: [],+ task: { goal: '', changes: '', constraints: '', owns: [] }, reviewOf: 'r', checks: [], assignment, lastMessageSequence: 0, lastMainSequence: 0, pullRequestUrls: [],messageSeq: 0, reportSeq: 0, dormant: false, lastActivityAt: '', audience: { people: [] }, lostAttempt: { id: 'w', agentId: 'a' }, reactionSeq: 0,requesterId: 'p', ledger: {}, proposals: [], liveness: { state: 'quiet', why: 'silent', since: 1 }, leadAction: { kind: 'post', at: 1 },}diff --git a/backend/src/superTabs/parts/light.ts b/backend/src/superTabs/parts/light.tsindex c241f5134..441aa8105 100644--- a/backend/src/superTabs/parts/light.ts+++ b/backend/src/superTabs/parts/light.ts@@ -27,7 +27,7 @@ export const GROUP_FIELDS = {always: ['id', 'kind', 'projectId', 'leadId', 'agentIds', 'archived', 'audience', 'dormant', 'assignment.id', 'assignment.agentId', 'assignment.status','assignment.lost'],whenRunning: ['title', 'task.owns', 'assignment.execution', 'assignment.result'],- unread: ['number', 'brief', 'reviewOf', 'checks', 'lastMessageSequence', 'pullRequestUrls', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'liveness', 'leadAction',+ unread: ['number', 'brief', 'reviewOf', 'checks', 'lastMessageSequence', 'lastMainSequence', 'pullRequestUrls', 'messageSeq', 'reportSeq', 'lastActivityAt', 'lostAttempt', 'requesterId', 'ledger', 'reactionSeq', 'proposals', 'liveness', 'leadAction','assignment.configuration', 'assignment.recordingProgress', 'assignment.leaseUntil', 'assignment.progressAt', 'assignment.askedOf'],} as constconst LIGHT_GROUP = {diff --git a/backend/src/superTabs/store.ts b/backend/src/superTabs/store.tsindex a45313f12..237e5bb6a 100644--- a/backend/src/superTabs/store.ts+++ b/backend/src/superTabs/store.ts@@ -11,7 +11,8 @@ import { applyCommand, authorizeCommandAccess, operationSchema, PAIR_CHAIN_LIMITimport { redactCredentials } from './credentials.js'import type { AvatarUpload } from './profile.js'import { reactionCounts, type ReactionTarget } from './reactions.js'-import { inConversationOrder, pageDeliveries, pageReactions } from './pageReads.js'+import { inConversationOrder, pageDeliveries, pageReactions, pageThreads } from './pageReads.js'+import { threadSummaries } from './threads.js'import { attachmentMime, attachmentName, AttachmentTooLarge, AVATAR_PURPOSE, AVATAR_TYPES, checkedType, MAX_ATTACHMENT_BYTES, MAX_AVATAR_BYTES, objectKeyFor, peekType, publicUrl, trimPrefix,type Attachment, type Attachments, type AttachmentStore, type AvatarStore } from './attachments.js'import { randomBytes } from 'node:crypto'@@ -1020,7 +1021,8 @@ export class SuperTabStore {}if (command.type === 'message.send' && command.replyTo) {const reply = await tx.superTabMessage.findFirst({ where: { id: command.replyTo, tabId, conversationId: command.conversationId } })- if (reply) context.reply = { id: reply.id, conversationId: reply.conversationId, author: reply.author as unknown as Author, createdAt: reply.createdAt.getTime() }+ if (reply) context.reply = { id: reply.id, conversationId: reply.conversationId, author: reply.author as unknown as Author, createdAt: reply.createdAt.getTime(),+ thread: reply.thread }}if (command.type === 'message.send' && actor.kind === 'person') context.openTags = await openTags(tx, tabId, command.conversationId, actor.userId, context.now)if ((command.type === 'rule.set' || command.type === 'rule.remove' || command.type === 'project.skills' || command.type === 'tab.tidy') && command.askedIn) {@@ -1767,7 +1769,9 @@ export class SuperTabStore {if (!kept.has(message.id)) rows.push({ id: message.id, tabId, conversationId: message.conversationId,sequence: sequences.get(message.id)!, author: json(message.author), ...(message.source ? { source: json(message.source) } : {}),...(message.attachments ? { attachments: json(message.attachments) } : {}),- text: message.text, replyTo: message.replyTo, recipientIds: message.recipients, mentions: message.mentions ?? [] })+ text: message.text, replyTo: message.replyTo, recipientIds: message.recipients, mentions: message.mentions ?? [],+ // A top-level message is its own thread's root; only a row written before threads has none (its replies stay inline).+ thread: message.thread ?? message.id, ...(message.alsoInChat ? { alsoInChat: true } : {}) })for (const recipient of message.recipients) {const target = agent(state, recipient)const group = conversation(state, message.conversationId)@@ -1799,7 +1803,7 @@ export class SuperTabStore {* sequence, so a page edge inside such a run must not skip any (design section 4.6). `after` alone reads strictly after* a sequence, which is enough to poll for new messages. */async messages(user: AuthUser, tabId: string, conversationId: string,- cursor: { after?: number; afterId?: string; before?: number; beforeId?: string; messageId?: string }, asAgentId?: string) {+ cursor: { after?: number; afterId?: string; before?: number; beforeId?: string; messageId?: string; thread?: string }, asAgentId?: string) {const tx = this.dbconst { state } = await this.readLoad(user, tabId, { groupIds: [conversationId] })const actor = await this.actor(tx, user, state, asAgentId)@@ -1809,6 +1813,8 @@ export class SuperTabStore {: { OR: [{ sequence: { [direction]: sequence } }, { sequence, id: { [direction]: id } }] }const where = { tabId, conversationId,...(cursor.messageId ? { id: cursor.messageId } : {}),+ // One thread: its root (its own thread) and its replies.+ ...(cursor.thread ? { thread: cursor.thread } : {}),...(forward ? past(cursor.after!, cursor.afterId, 'gt') : cursor.before !== undefined ? past(cursor.before, cursor.beforeId, 'lt') : {}) }// An agent-only notice is listed for its own recipient alone. Hidden rows never shorten a page: Desktop reads on from the// last row it shows, so the page reads past them until it has 101 rows this reader may see, or reaches the end.@@ -1827,8 +1833,11 @@ export class SuperTabStore {if (!forward) page.reverse()const reactions = page.length ? reactionCounts(state, await pageReactions(tx, tabId, page.map(m => m.id))) : new Map()const deliveries = page.length ? await pageDeliveries(tx, tabId, page.map(m => m.id)) : []+ // The threads the page's rows are in, so a poll that brings only a reply still moves its root's reply line.+ const roots = [...new Set(page.flatMap(m => m.thread ? [m.thread] : []))]+ const threads = roots.length ? threadSummaries(state, group, await pageThreads(tx, tabId, conversationId, roots)) : []return { messages: page.map(m => ({ ...m, mentions: m.mentions ?? [], reactions: reactions.get(m.id) ?? [],- deliveries: deliveries.filter(d => d.messageId === m.id) })), next,+ deliveries: deliveries.filter(d => d.messageId === m.id) })), next, threads,// A poll for new messages learns here that a reaction changed on a message it already shows (reactions.ts).reactionSeq: group.reactionSeq ?? 0 }}diff --git a/backend/src/superTabs/threads.ts b/backend/src/superTabs/threads.tsnew file mode 100644index 000000000..a05efee7f--- /dev/null+++ b/backend/src/superTabs/threads.ts@@ -0,0 +1,35 @@+import type { Author, Conversation, SuperTabState } from './model.js'+import type { ThreadReply } from './pageReads.js'+import { canReadGroup } from './projects.js'++/** What a page says about one thread: the line under its root, and who it marks unread for. */+export interface ThreadSummary {+ id: string+ replies: number+ lastSequence: number+ lastAt: Date+ /** The newest distinct reply authors, up to three. */+ authors: Author[]+ /** People who wrote in the thread or were tagged in it, in order of first appearance. */+ people: string[]+}++/** Summaries of the threads in `rows` (pageThreads), roots with no reply left out. Only people who can read the conversation+ * now are named, as an author or among `people`: someone who left keeps their replies but is no longer listed. */+export function threadSummaries(state: SuperTabState, group: Conversation, rows: ThreadReply[]): ThreadSummary[] {+ const reads = new Map<string, boolean>()+ const readable = (author: Pick<Author, 'kind' | 'id'>) => author.kind !== 'person' || (reads.get(author.id)+ ?? reads.set(author.id, canReadGroup(state, { kind: 'person', userId: author.id, email: '' }, group)).get(author.id)!)+ const threads = new Map<string, ThreadReply[]>()+ for (const row of rows) if (!row.agentOnly) threads.set(row.thread, [...threads.get(row.thread) ?? [], row])+ return [...threads].flatMap(([id, thread]) => {+ const replies = thread.filter(row => row.id !== id)+ const last = replies.at(-1)+ if (!last) return []+ const people = [...new Set(thread.flatMap(row => [...row.author.kind === 'person' ? [row.author.id] : [], ...row.mentions]))]+ .filter(person => readable({ kind: 'person', id: person }))+ const authors = [...new Map(replies.toReversed().map(row => [`${row.author.kind}:${row.author.id}`, row.author])).values()]+ .filter(readable).slice(0, 3)+ return [{ id, replies: replies.length, lastSequence: last.sequence, lastAt: last.createdAt, authors, people }]+ })+}diff --git a/cli/src/lib/swarmSkills.spec.ts b/cli/src/lib/swarmSkills.spec.tsindex b67da1c0b..8ea8d7812 100644--- a/cli/src/lib/swarmSkills.spec.ts+++ b/cli/src/lib/swarmSkills.spec.ts@@ -65,6 +65,9 @@ describe('built-in Swarm skills', () => {const lost = '- When you are told a task is lost, hand it on at once: route it and assign it to another agent, avoiding what failed (another machine if its machine died, another account or engine if it hit a usage limit). The new brief tells the successor to continue from the lost attempt\'s pushed branch and last result, not to start over.\n'// The night-shift lines (v2 B, 2026-10-27): a task lost to a usage limit resumes by itself unless an account or engine// with allowance can take it now, and the morning digest. The Lead's alone, in both modes, right after the lost-work line.+ // The thread line (Dee's threads, 2026-10-29): the Lead answers inside the thread of the message it answers. The Lead's+ // alone, in both modes, right after its write-like-a-colleague line.+ const thread = '- Answer a message inside its thread: post with --reply-to that message, and your reply joins its thread. Many people talk to you at once; answers in the main chat bury each other. Post at the top level only to start a new topic.\n'const limit = '- A task lost to a usage limit resumes by itself in the same session when the limit resets (its wake-up says when). Hand it on at once only to another account or engine with allowance now, with its pushed branch and last progress note.\n'const digest = '- Morning digest: when a person asks for one, set the project\'s digest to their local time and time zone ("project.digest" with time "08:00" and timeZone "Asia/Ho_Chi_Minh"). When it wakes you, check that each pull request under Shipped is merged, then post one message to the people in the project chat.\n'const checkpoint = '- Push your work branch at least every 30 minutes, and set your work status to working with a one-line note of what is done and what is next, so another agent can continue if you stop.\n'@@ -185,9 +188,10 @@ describe('built-in Swarm skills', () => {expect(text.split(missingStop)).toHaveLength(role === 'dev' ? 2 : 1)expect(text.split(reviewCheck)).toHaveLength(role === 'review' ? 2 : 1)expect(text.split(moveMissing)).toHaveLength(role === 'lead' ? 2 : 1)+ expect(text.split(thread)).toHaveLength(role === 'lead' ? 2 : 1)expect(sha(approved(text, 'orchestration', role).replace(twoHours, '').replace(terminal, '').replace(overlap, '').replace(local, '').replace(failedStart, '').replace(mention, '').replace(lost, '').replace(checkpoint, '').replace(limit, '').replace(digest, '').replace(decision, '').replace(ask, '').replace(requests, '').replace(shared, '').replace(report, '')- .replace(missingStop, '').replace(reviewCheck, '').replace(moveMissing, ''))).toBe(sha256)+ .replace(missingStop, '').replace(reviewCheck, '').replace(moveMissing, '').replace(thread, ''))).toBe(sha256)}})it('adds the 2-hour line to section 7 right after the stall rule', () => {@@ -237,7 +241,7 @@ describe('built-in Swarm skills', () => {const orchestration = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session' }).file, 'utf8')expect(orchestration).toContain(`\n\n${requests}## Red flags`)const plain = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session', mode: 'default' }).file, 'utf8')- expect(plain.endsWith(`Call the roles Product Manager, Engineer and Reviewer.\n${requestsLast}`)).toBe(true)+ expect(plain.endsWith(`Call the roles Product Manager, Engineer and Reviewer.\n${thread}${requestsLast}`)).toBe(true)})it('gives each Builder and Reviewer skill its shared-machine rules in a section of their own: before the red flags, or last', () => {const lastBefore = { dev: '- Write to people in their language, without commands or internal ids. Call the roles Product Manager, Engineer and Reviewer.\n',@@ -261,6 +265,12 @@ describe('built-in Swarm skills', () => {const plain = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session', mode: 'default' }).file, 'utf8')expect(plain).toContain(`assign it to another agent with what the first one left (branch, last revision, last report).\n${lost}${limit}${digest}- When the Swarm tells you a task stalled`)})+ it('adds the thread line right after each Lead skill\'s write-like-a-colleague line', () => {+ for (const mode of ['orchestration', 'default'] as const) {+ const lines = readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session', mode }).file, 'utf8').split('\n')+ expect(lines[lines.indexOf(thread.trimEnd()) - 1]).toMatch(/^- Write like a colleague: /)+ }+ })it('adds the usage-limit and digest lines right after each Lead skill\'s lost-work line', () => {for (const mode of ['orchestration', 'default'] as const) {expect(readFileSync(prepareSwarmSkill(fixture(), { role: 'lead', key: 'session', mode }).file, 'utf8')).toContain(`${lost}${limit}${digest}`)@@ -328,9 +338,10 @@ describe('built-in Swarm skills', () => {expect(text.split(missingStop)).toHaveLength(role === 'dev' ? 2 : 1)expect(text.split(reviewCheck)).toHaveLength(role === 'review' ? 2 : 1)expect(text.split(moveMissing)).toHaveLength(role === 'lead' ? 2 : 1)+ expect(text.split(thread)).toHaveLength(role === 'lead' ? 2 : 1)expect(sha(approved(text, 'default', role).replace(terminal, '').replace(overlap, '').replace(localDefault, '').replace(failedStart, '').replace(mention, '').replace(lost, '').replace(checkpoint, '').replace(limit, '').replace(digest, '').replace(decision, '').replace(ask, '').replace(requestsLast, '').replace(sharedLast, '').replace(report, '')- .replace(missingStop, '').replace(reviewCheck, '').replace(moveMissing, ''))).toBe(sha256)+ .replace(missingStop, '').replace(reviewCheck, '').replace(moveMissing, '').replace(thread, ''))).toBe(sha256)expect(prepared.instructions).toBe(`Use the swarm-${role} skill for this session: the team process; otherwise work your usual way. Before working, read ${JSON.stringify(prepared.file)} with your file or shell tool.`)})diff --git a/cli/src/lib/swarmSkills.ts b/cli/src/lib/swarmSkills.tsindex 3d1d07f21..a3616e0e9 100644--- a/cli/src/lib/swarmSkills.ts+++ b/cli/src/lib/swarmSkills.ts@@ -155,6 +155,7 @@ For large work, post the group plan and get the owner's ok before assigning; onc- Summarize long threads once; record important decisions once.- When your own session grows long, post a checkpoint in the project chat: the approved description, groups and their state, open rulings, and next steps. It must be enough for a fresh Lead session to continue.- Write like a colleague: short, in their language, without commands or internal IDs. Lead with what matters: give the most important points and offer the rest. Use their words, not Swarm's process terms; ask your question rather than explain the process.+- Answer a message inside its thread: post with --reply-to that message, and your reply joins its thread. Many people talk to you at once; answers in the main chat bury each other. Post at the top level only to start a new topic.- When talking to people, call the roles Product Manager, Engineer and Reviewer.## Requests and Done@@ -442,6 +443,7 @@ When the project owner asks in chat to switch this project's skills (Default or- Answer questions, blockers and completions at once.- Every post carries a result, a decision asked for with your recommendation, a question, or a fault; never an acknowledgement alone.- Write like a colleague: short, in their language, no commands or internal ids. Call the roles Product Manager, Engineer and Reviewer.+- Answer a message inside its thread: post with --reply-to that message, and your reply joins its thread. Many people talk to you at once; answers in the main chat bury each other. Post at the top level only to start a new topic.## Requests and Done- When you open a group for a person's request, asked in the project chat or proposed by their Buddy on their behalf, name them as its requester: requesterId on conversation.create, or conversation.requester for a group already open. It records only that they asked, never what they wrote.diff --git a/cli/src/superTabs/service.spec.ts b/cli/src/superTabs/service.spec.tsindex eeaf3cc26..77190f95b 100644--- a/cli/src/superTabs/service.spec.ts+++ b/cli/src/superTabs/service.spec.ts@@ -641,6 +641,22 @@ describe('which messages still need an answer', () => {// A person's email is passed as the backend sent it.expect((value.messages[0]!.author as { name: string }).name).toBe('[email protected]')})+ it('names the thread root on each thread reply only, so an agent reading one feed sees which thread a reply is in', async () => {+ const t = setup()+ const feed = [+ { id: 'r1', sequence: 1, author: person, recipientIds: [], replyTo: null, thread: 'r1' },+ { id: 'r2', sequence: 2, author: person, recipientIds: [t.agentId], replyTo: 'r1', thread: 'r1' },+ { id: 'r3', sequence: 3, author: person, recipientIds: [], replyTo: 'old', thread: 'r3' },+ { id: 'r4', sequence: 4, author: person, recipientIds: [], replyTo: null, thread: null },+ ]+ vi.mocked(t.core.account.backend).mockImplementation(async (_method, path) => ({ status: 200, body: { success: true,+ data: path.includes('/messages') ? { messages: feed, next: null, threads: [{ id: 'r1', replies: 1 }] } : swarmData(t.agent, path) } }))+ const value = (await t.ask({ action: 'messages', tabId: 'tab', agentId: t.agentId, conversationId: 'lead' }, owner) as+ { value: { messages: Record<string, unknown>[]; threads: unknown[] } }).value+ expect(value.messages.map(m => m.thread)).toEqual([undefined, 'r1', undefined, undefined])+ expect(value.messages.map(m => 'thread' in m)).toEqual([false, true, false, false])+ expect(value.threads).toEqual([{ id: 'r1', replies: 1 }])+ })it('reads the later messages of one exact message to tell whether it was answered', async () => {const t = setup()vi.mocked(t.core.account.backend).mockImplementation(async (_method, path) => {diff --git a/cli/src/superTabs/service.ts b/cli/src/superTabs/service.tsindex 83ca01561..0124ac951 100644--- a/cli/src/superTabs/service.ts+++ b/cli/src/superTabs/service.ts@@ -49,7 +49,7 @@ const HELP = {leads: 'The Leads conversation (leadsConversationId in a Lead\'s status) is one conversation for the whole Swarm, outside every project. Only Leads and people post there, and only Leads among agents receive it. Before assigning, look at otherProjectsWork; if your task touches the same code, say so there and agree an order first, then tell your own project. The Swarm posts there by itself when two projects\' active tasks own the same code.',// Help without --tab cannot tell who asks, so it does not list a Lead's own options; this tells a Lead where they are.leadOptions: 'Leads: run help with --tab ID for options only a Lead has.',- messages: 'messages GROUP: read recent messages in a conversation.',+ messages: 'messages GROUP: read recent messages in a conversation, thread replies included: each names its thread, the root message it answers there. A post with --reply-to lands in that message\'s thread.',message: 'message GROUP MESSAGE_ID: read one exact message, including an earlier question or result referenced by a reply.',decisions: 'decisions [--answered]: the decisions you asked of people, still open, or with --answered those answered (each with its choice and note). A Lead also sees those asked in its project. When your work needs a person to decide, ask through work.status needs_human with ask: the question as its result, 2 to 5 options, the one you recommend and what the answer unblocks. Keep working on your recommendation, marked provisional, until a notice in that conversation says it was answered; then read the answer here with --answered. The notice carries none of the answer. A decision is not a private channel: to tell one person something directly, a Lead sends person.tell; it lands in their Buddy chat, which the Lead cannot read. Project members watching the Lead\'s terminal see what it sends: put nothing there you would not say in the project chat.',costs: 'costs [--days N]: what the attempts routed in the last N days (7 unless set, at most 90) cost and how they went, per engine, model, effort and kind of job: attempts, first-review pass rate, shipped, median minutes to ship, tokens, API-equivalent cost and actual per-token spend in US dollars, and cost per shipped change, with the prices and their sources. Only attempts routed since cost records began, in the groups you may read.',@@ -179,9 +179,12 @@ function markAnswered(page: unknown, later: unknown[], agentId: string): unknownconst body = object(page)if (!Array.isArray(body.messages)) return pageconst mine = new Set([...body.messages, ...later].map(object).filter(m => object(m.author).id === agentId && typeof m.replyTo === 'string').map(m => m.replyTo))- return { ...body, messages: body.messages.map(object).map(m => {+ return { ...body, messages: body.messages.map(object).map(row => {+ // `thread` is named on a thread reply only: a top-level message is its own thread's root, and an older row has none.+ const { thread, ...m } = row+ const reply = typeof thread === 'string' && thread !== m.id ? { ...m, thread } : mconst asked = Array.isArray(m.recipientIds) && m.recipientIds.includes(agentId) && object(m.author).id !== agentId- return asked ? { ...m, answered: mine.has(m.id) } : m+ return asked ? { ...reply, answered: mine.has(m.id) } : reply}) }}@@ -531,7 +534,7 @@ export function superTabService(core: CoreApi, options: SuperTabServiceOptions =// this agent. If that read fails the message is still returned, just without a verdict.const sent = object(list(object(page).messages)[0])const asked = Array.isArray(sent.recipientIds) && sent.recipientIds.includes(agentId) && object(sent.author).id !== agentId- if (!asked || !Number.isInteger(Number(sent.sequence))) return { ok: true, value: page }+ if (!asked || !Number.isInteger(Number(sent.sequence))) return { ok: true, value: markAnswered(page, [], agentId) }try {const later = object(await backend(core, 'GET', `${path}/conversations/${payload.conversationId}/messages?${identity}&after=${sent.sequence}`)).messagesreturn { ok: true, value: markAnswered(page, list(later), agentId) }diff --git a/desktop/lib/super_tabs/controller.dart b/desktop/lib/super_tabs/controller.dartindex f0e04faa3..46036e167 100644--- a/desktop/lib/super_tabs/controller.dart+++ b/desktop/lib/super_tabs/controller.dart@@ -73,10 +73,19 @@ class SuperTabOutgoing {required this.state,this.operationId,this.replyTo,+ this.thread,+ this.alsoSend = false,this.error,});final String conversationId, text;+ /// The thread root a reply goes to, null for a top-level or inline reply.+ final String? thread;++ /// A thread reply also sent to the main stream.+ final bool alsoSend;+ bool get inMainStream => thread == null || alsoSend;+/// The send's receipt id, while it is not confirmed.final String? operationId;final String? replyTo;@@ -153,6 +162,11 @@ class SuperTabController extends ChangeNotifier {}}}+ if (initial['threadSeen'] case final Map seen) {+ for (final MapEntry(:key, :value) in seen.entries) {+ if (key is String && value is num) _threadSeen[key] = value.toInt();+ }+ }final refused = initial['refused'];if (refused is Map) {for (final MapEntry(:key, :value) in refused.entries) {@@ -343,6 +357,22 @@ class SuperTabController extends ChangeNotifier {final _terminals = <String, String>{};final _mentions = <String, Map<String, String>>{};final _readAt = <String, int>{};++ /// Per conversation, each thread's summary as the newest page said it.+ final _threads = <String, Map<String, SuperTabThread>>{};++ /// Per thread root, the newest reply the reader has seen.+ final _threadSeen = <String, int>{};++ /// Each thread's rows as its own read brought them.+ final _threadRows = <String, List<SuperTabMessage>>{};++ /// Where each thread's earlier replies continue, while there are more.+ final _threadBefore = <String, Map<String, dynamic>>{};+ final _threadDrafts = <String, String>{};++ /// The thread open beside the chat.+ ({String conversationId, String root})? openedThread;final _attachments = <String, HarnessAttachments>{};// Files already uploaded for the message being sent, so a retry sends their// ids rather than uploading them again.@@ -730,6 +760,226 @@ class SuperTabController extends ChangeNotifier {_quoteRetries.add(retry);}+ /// [root]'s thread summary in conversation [id], once a page named it.+ SuperTabThread? thread(String id, String root) => _threads[id]?[root];++ /// Whether [thread] has a reply the reader has not seen, from someone else,+ /// in a thread they wrote in or were tagged in.+ bool threadUnread(SuperTabThread thread) {+ final last = thread.authors.firstOrNull;+ return thread.people.contains(accountId) &&+ thread.lastSequence > (_threadSeen[thread.id] ?? 0) &&+ !(last?['kind'] == 'person' && last?['id'] == accountId);+ }++ void _keepThreads(String id, Object? rows) {+ if (rows is! List) return;+ final held = _threads[id] ??= {};+ for (final row in rows) {+ final thread = SuperTabThread.fromJson(superTabMap(row));+ if ((held[thread.id]?.lastSequence ?? -1) > thread.lastSequence) continue;+ held[thread.id] = thread;+ // A thread first seen here is read as far as the conversation is:+ // replies the reader passed before threads were counted stay read.+ _threadSeen.putIfAbsent(+ thread.id,+ () => min(_readAt[id] ?? 0, thread.lastSequence),+ );+ if (openedThread?.root == thread.id) _seeThread(thread.id);+ }+ }++ void _seeThread(String root) {+ final open = openedThread;+ final last = max(+ (open == null ? null : _threads[open.conversationId]?[root])+ ?.lastSequence ??+ 0,+ threadMessages(root).lastOrNull?.sequence ?? 0,+ );+ if ((_threadSeen[root] ?? 0) >= last) return;+ // Moved to the end: the newest marks are the ones a save keeps.+ _threadSeen.remove(root);+ _threadSeen[root] = last;+ _saveSoon();+ }++ /// The root and replies of [root]'s thread in the selected conversation,+ /// oldest first: what its own read brought, and replies polled since.+ List<SuperTabMessage> threadMessages(String root) {+ final id = openedThread?.conversationId ?? selectedId;+ final rows = {+ for (final m in _threadRows[root] ?? const <SuperTabMessage>[]) m.id: m,+ for (final m in _messages[id] ?? const <SuperTabMessage>[])+ if (m.thread == root) m.id: m,+ };+ return rows.values.toList()..sort(superTabMessageOrder);+ }++ /// The thread [messageId] is in, from the rows held of [id].+ String? _threadOf(String id, String? messageId) {+ if (messageId == null) return null;+ for (final m in [+ ..._messages[id] ?? const <SuperTabMessage>[],+ for (final rows in _threadRows.values) ...rows,+ ]) {+ if (m.id == messageId) return m.thread;+ }+ return null;+ }++ /// Forgets what was read of threads in conversations [keep] refuses (all,+ /// without it), as the transcript is forgotten when access goes.+ void _forgetThreads([bool Function(String conversationId)? keep]) {+ bool gone(String id) => keep == null || !keep(id);+ _threads.removeWhere((id, _) => gone(id));+ final roots = {+ for (final MapEntry(key: root, value: rows) in _threadRows.entries)+ if (rows.any((m) => gone(m.conversationId))) root,+ };+ _threadRows.removeWhere((root, _) => roots.contains(root));+ _threadBefore.removeWhere((root, _) => roots.contains(root));+ if (openedThread case final open? when gone(open.conversationId)) {+ openedThread = null;+ }+ }++ /// Whether [root]'s thread has replies before those read.+ bool hasEarlierReplies(String root) => _threadBefore.containsKey(root);+ bool readingEarlierReplies = false;++ /// Opens [root]'s thread of the selected conversation beside the chat.+ void openThread(String root) {+ if (accessRevoked) return;+ openedThread = (conversationId: selectedId, root: root);+ _seeThread(root);+ _changed();+ unawaited(loadThread());+ }++ void closeThread() {+ if (openedThread == null) return;+ openedThread = null;+ _changed();+ }++ String threadDraft(String root) => _threadDrafts[root] ?? '';+ void setThreadDraft(String root, String text) => _threadDrafts[root] = text;++ /// How many pages a thread reads when it opens; past them "Show earlier+ /// replies" reads on, a page at a time.+ static const threadPagesOnOpen = 5;++ /// Reads the open thread: from its newest reply back through+ /// [threadPagesOnOpen] pages, or with [earlier] the page before those read,+ /// and its root when no page brought it.+ Future<void> loadThread({bool earlier = false}) async {+ final open = openedThread;+ if (open == null || _disposed || accessRevoked) return;+ if (earlier && (!hasEarlierReplies(open.root) || readingEarlierReplies)) {+ return;+ }+ final path = _messagesPath(open.conversationId);+ final thread = Uri.encodeQueryComponent(open.root);+ // Still open, still readable: an answer that comes back after access went+ // or the thread closed is not kept.+ bool current() =>+ !_disposed &&+ !accessRevoked &&+ openedThread == open &&+ snapshot?.conversation(open.conversationId) != null;+ List<SuperTabMessage> rowsOf(Map<String, dynamic> page) => [+ for (final row in page['messages'] as List)+ if (SuperTabMessage.fromJson(superTabMap(row)) case final m+ when m.conversationId == open.conversationId &&+ m.thread == open.root)+ m,+ ];+ readingEarlierReplies = earlier;+ try {+ final rows = {+ if (earlier)+ for (final m in _threadRows[open.root] ?? const <SuperTabMessage>[])+ m.id: m,+ };+ Map<String, dynamic>? from = earlier ? _threadBefore[open.root] : null;+ Object? threads;+ for (var page = 0; page < (earlier ? 1 : threadPagesOnOpen); page++) {+ final answer = await request(+ 'GET',+ from == null+ ? '$path?thread=$thread'+ : '$path?thread=$thread&before=${from['sequence']}&beforeId=${Uri.encodeQueryComponent(from['id'] as String)}',+ );+ if (!current()) return;+ threads ??= answer['threads'];+ for (final m in rowsOf(answer)) {+ rows[m.id] = m;+ }+ from = answer['next'] is Map ? superTabMap(answer['next']) : null;+ if (from == null) break;+ }+ // A long thread's pages read so far start after its root.+ if (!rows.containsKey(open.root) &&+ !(_messages[open.conversationId] ?? const []).any(+ (m) => m.id == open.root,+ )) {+ final root = await request(+ 'GET',+ '$path?messageId=${Uri.encodeQueryComponent(open.root)}',+ );+ if (!current()) return;+ for (final m in rowsOf(root)) {+ if (m.id == open.root) rows[m.id] = m;+ }+ }+ _threadRows[open.root] = rows.values.toList();+ if (from == null) {+ _threadBefore.remove(open.root);+ } else {+ _threadBefore[open.root] = from;+ }+ _keepThreads(open.conversationId, threads);+ _seeThread(open.root);+ _changed();+ } catch (failure) {+ if (!current()) return;+ _readFailure(failure, revokeTab: false);+ _changed();+ } finally {+ if (earlier) readingEarlierReplies = false;+ }+ }++ /// Sends the open thread's draft to its root; [alsoSend] shows it in the+ /// main stream too.+ Future<Map<String, dynamic>?> sendThreadReply({bool alsoSend = false}) async {+ final open = openedThread;+ final text = threadDraft(open?.root ?? '').trim();+ if (open == null ||+ text.isEmpty ||+ selected == null ||+ selected!.archived ||+ !canWrite ||+ saving ||+ _pending != null) {+ return null;+ }+ final sending = command({+ 'type': 'message.send',+ 'conversationId': open.conversationId,+ 'text': text,+ 'replyTo': open.root,+ 'recipientIds': const <String>[],+ if (alsoSend) 'alsoSend': true,+ });+ if (_pending != null) {+ _threadDrafts.remove(open.root);+ _changed();+ }+ return await sending;+ }+List<SuperTabMessage> messages(String id) => List.unmodifiable((_messages[id] ?? const <SuperTabMessage>[]).where(_listed),);@@ -826,8 +1076,20 @@ class SuperTabController extends ChangeNotifier {.firstOrNull?.sequence ??0;++ /// A reply only in its thread leaves the chat as it was: it lights its+ /// thread's reply line instead ([threadUnread]).bool unread(SuperTabConversation group) =>- max(group.lastMessageSequence, _loadedMessageSequence(group.id)) >+ max(+ group.lastMainSequence ?? group.lastMessageSequence,+ _messages[group.id]?.reversed+ .where(+ (m) => m.source['kind'] != 'update-request' && m.inMainStream,+ )+ .firstOrNull+ ?.sequence ??+ 0,+ ) >(_readAt[group.id] ?? 0);void start() {@@ -1013,6 +1275,7 @@ class SuperTabController extends ChangeNotifier {_messages.clear();_quoted.clear();_quoting.clear();+ _forgetThreads();_rows.clear();_before.clear();}@@ -1046,6 +1309,7 @@ class SuperTabController extends ChangeNotifier {_forgetNewer();_quoted.clear();_quoting.clear();+ _forgetThreads();_sent.clear();_refused.clear();_poll?.cancel();@@ -1071,6 +1335,11 @@ class SuperTabController extends ChangeNotifier {entry.key: Map<String, String>.of(entry.value),},'readAt': Map<String, int>.of(_readAt),+ // ponytail: the newest 500 threads' marks; an older one forgotten shows+ // read again through the conversation's read mark ([_keepThreads]).+ 'threadSeen': Map<String, int>.fromEntries(+ _threadSeen.entries.skip(max(0, _threadSeen.length - 500)),+ ),if (_pending != null) 'pending': _pending,if (_refused.isNotEmpty)'refused': {@@ -1142,6 +1411,8 @@ class SuperTabController extends ChangeNotifier {conversationId: id,text: command['text'] as String? ?? '',replyTo: command['replyTo'] as String?,+ thread: _threadOf(id, command['replyTo'] as String?),+ alsoSend: command['alsoSend'] == true,state: state,operationId: operationId,error: error,@@ -1361,7 +1632,7 @@ class SuperTabController extends ChangeNotifier {if (!unread(group)) return 0;final readAt = _readAt[group.id] ?? 0;final count = messages(group.id)- .where((m) => m.sequence > readAt && !_ownMessage(m))+ .where((m) => m.sequence > readAt && !_ownMessage(m) && m.inMainStream).length;return _heldSinceRead(group) ? count : max(count, 1);}@@ -1578,6 +1849,7 @@ class SuperTabController extends ChangeNotifier {if (group.closed) closedOpenProjects.add(group.projectId);}_moveView(to: id);+ openedThread = null;_viewVersion++;operationNotice = null;_saveSoon();@@ -1688,6 +1960,7 @@ class SuperTabController extends ChangeNotifier {_messages.removeWhere((id, _) => !allowed.contains(id));_quoted.removeWhere((id, _) => !allowed.contains(id));_quoting.removeWhere((id, _) => !allowed.contains(id));+ _forgetThreads(allowed.contains);_rows.removeWhere((id, _) => !allowed.contains(id));_drafts.removeWhere((id, _) => removed.contains(id));_attachments.removeWhere((id, files) {@@ -2068,6 +2341,7 @@ class SuperTabController extends ChangeNotifier {_forgetNewer();_quoted.clear();_quoting.clear();+ _forgetThreads();_poll?.cancel();}}@@ -2199,6 +2473,7 @@ class SuperTabController extends ChangeNotifier {(_showingSaved || latest || (skipped && !keepPlace)) && !older;if (replacing) _rows.remove(id);_keepRows(id, answer['messages'] as List);+ _keepThreads(id, answer['threads']);final combined = {if (!replacing)for (final m in _messages[id] ?? <SuperTabMessage>[]) m.id: m,diff --git a/desktop/lib/super_tabs/leaderboard/worker_rows.dart b/desktop/lib/super_tabs/leaderboard/worker_rows.dartindex 9460fa31b..cebbaccc2 100644--- a/desktop/lib/super_tabs/leaderboard/worker_rows.dart+++ b/desktop/lib/super_tabs/leaderboard/worker_rows.dart@@ -224,7 +224,8 @@ class LeaderboardModelRow extends StatelessWidget {points: score.points,columns: columns,weekName: weekName,- crowned: score.rank == 1 && score.points > 0,+ // Crowns are for people and agents, not models (full review of #2097).+ crowned: false,identity: EngineMark(engine: score.engine),name: name,tag: score.grid ? 'grid' : null,diff --git a/desktop/lib/super_tabs/message_row.dart b/desktop/lib/super_tabs/message_row.dartindex f4d3dfc15..923f36b12 100644--- a/desktop/lib/super_tabs/message_row.dart+++ b/desktop/lib/super_tabs/message_row.dart@@ -11,6 +11,7 @@ import '../widgets/engine_identity.dart';import '../widgets/finger_target.dart';import 'attachment_chips.dart';import 'identity.dart';+import 'machine_status.dart' show superTabAgo;import 'message_link.dart';import 'message_link_preview.dart';import 'message_more_menu.dart';@@ -44,6 +45,9 @@ class SuperTabMessageRow extends StatefulWidget {this.reactorName,this.onReact,this.proposalOwner,+ this.thread,+ this.threadUnread = false,+ this.onOpenThread,this.link,this.linkTarget,this.onOpenLink,@@ -51,6 +55,14 @@ class SuperTabMessageRow extends StatefulWidget {final SuperTabMessage message;+ /// The thread [message] is the root of, once it has a reply.+ final SuperTabThread? thread;+ final bool threadUnread;++ /// Opens [message]'s thread: from its reply line, or from an also-sent+ /// reply's mark.+ final VoidCallback? onOpenThread;+/// The person a Buddy's proposal speaks for, by name, from the server's tag/// on it ([SuperTabMessage.proposalOwnerId]); null for any other message.final String? proposalOwner;@@ -353,7 +365,28 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {),const SizedBox(height: 4),],- if (message.replyTo != null)+ if (message.threadReply &&+ widget.onOpenThread != null)+ Padding(+ padding: const EdgeInsets.only(+ bottom: grid.AppDesktop.menuInset,+ ),+ child: SuperTabLink(+ key: ValueKey(+ 'super-thread-also-${message.id}',+ ),+ label: 'Replied in thread, open thread',+ onTap: widget.onOpenThread!,+ child: Text(+ 'Replied in thread',+ style: DesktopChrome.metadata(),+ ),+ ),+ ),+ // A thread reply sits under its root, so it+ // quotes nothing; an older reply keeps its quote.+ if (message.replyTo != null &&+ !message.threadReply)Padding(padding: const EdgeInsets.only(bottom: 8),child: SuperTabReplyPreview(@@ -438,6 +471,18 @@ class _SuperTabMessageRowState extends State<SuperTabMessageRow> {nameOf: widget.reactorName ?? (_, id) => id,onReact: widget.onReact,),+ if ((widget.thread, widget.onOpenThread) case (+ final thread?,+ final open?,+ ))+ SuperTabThreadLine(+ key: ValueKey(+ 'super-thread-line-${message.id}',+ ),+ thread: thread,+ unread: widget.threadUnread,+ onOpen: open,+ ),...widget.receipts,],),@@ -582,3 +627,117 @@ class SuperTabMessageHighlight extends StatelessWidget {);}}++/// A quiet link in a message: a hand cursor, reached by Tab and pressed with+/// Enter or Space, and a button with [label] to assistive technology. Focus+/// draws the shared rim, reserved at rest so it never moves the words.+class SuperTabLink extends StatefulWidget {+ const SuperTabLink({+ super.key,+ required this.onTap,+ required this.label,+ required this.child,+ });++ final VoidCallback onTap;+ final String label;+ final Widget child;++ @override+ State<SuperTabLink> createState() => _SuperTabLinkState();+}++class _SuperTabLinkState extends State<SuperTabLink> {+ var _focused = false;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final radius = BorderRadius.circular(DesktopChrome.controlRadius);+ return Semantics(+ button: true,+ label: widget.label,+ child: InkWell(+ onTap: widget.onTap,+ onFocusChange: (focused) => setState(() => _focused = focused),+ mouseCursor: SystemMouseCursors.click,+ borderRadius: radius,+ hoverColor: Colors.transparent,+ focusColor: Colors.transparent,+ highlightColor: Colors.transparent,+ splashFactory: NoSplash.splashFactory,+ child: DecoratedBox(+ decoration: BoxDecoration(+ borderRadius: radius,+ border: Border.all(+ color: _focused ? DesktopChrome.focusRing : Colors.transparent,+ width: grid.AppDesktop.focusWidth,+ ),+ ),+ child: ExcludeSemantics(child: widget.child),+ ),+ ),+ );+ }+}++/// The line under a thread's root: who replied, how many replies, and when+/// the last came. Bold while the thread has a reply the reader has not seen.+class SuperTabThreadLine extends StatelessWidget {+ const SuperTabThreadLine({+ super.key,+ required this.thread,+ required this.unread,+ required this.onOpen,+ });++ final SuperTabThread thread;+ final bool unread;+ final VoidCallback onOpen;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final count = thread.replies == 1 ? '1 reply' : '${thread.replies} replies';+ final last = thread.lastAt;+ return Padding(+ padding: const EdgeInsets.only(top: grid.AppDesktop.menuInset),+ child: SuperTabLink(+ label: unread ? '$count, unread' : count,+ onTap: onOpen,+ child: Row(+ mainAxisSize: MainAxisSize.min,+ children: [+ for (final author in thread.authors) ...[+ SuperTabAvatar(+ identity: '${author['kind']}:${author['id']}',+ name: author['kind'] == 'agent'+ ? (author['displayName'] ?? author['name'] ?? 'Agent')+ as String+ : superTabPersonName(author['name'] as String? ?? ''),+ size: grid.AppDesktop.iconSize,+ pattern: author['kind'] == 'agent',+ ),+ const SizedBox(width: grid.AppDesktop.menuInset),+ ],+ Text(+ count,+ key: ValueKey('super-thread-count-${thread.id}'),+ style: DesktopChrome.control(color: DesktopChrome.accent)+ .copyWith(+ fontWeight: unread ? FontWeight.w700 : FontWeight.w500,+ ),+ ),+ if (last != null) ...[+ const SizedBox(width: grid.AppDesktop.controlGap),+ Text(+ 'Last reply ${superTabAgo(DateTime.now().difference(last))}',+ style: DesktopChrome.metadata(),+ ),+ ],+ ],+ ),+ ),+ );+ }+}diff --git a/desktop/lib/super_tabs/model.dart b/desktop/lib/super_tabs/model.dartindex f22c4ceee..86e1bf3f5 100644--- a/desktop/lib/super_tabs/model.dart+++ b/desktop/lib/super_tabs/model.dart@@ -160,6 +160,7 @@ class SuperTabConversation {? SuperTabTask.fromJson(superTabMap(row['task'])): null,lastMessageSequence = (row['lastMessageSequence'] as num?)?.toInt() ?? 0,+ lastMainSequence = (row['lastMainSequence'] as num?)?.toInt(),assignment = row['assignment'] == null? null: Map.unmodifiable(superTabMap(row['assignment'])),@@ -200,6 +201,11 @@ class SuperTabConversation {/// Persisted links may be absent on older backends; loaded messages still supply links.final List<String> pullRequestUrls;final int lastMessageSequence;++ /// Its newest message in the main stream: a reply only in its thread+ /// leaves it. Null from a backend before threads, or before this+ /// conversation's first message since.+ final int? lastMainSequence;final Map<String, dynamic>? assignment;/// Whether its task waits on purpose or is stuck, as the server last found@@ -763,12 +769,40 @@ class SuperTabDelivery {};}+/// What a page says about one thread (backend threads.ts): the line under its+/// root, and who it marks unread for.+class SuperTabThread {+ SuperTabThread.fromJson(Map<String, dynamic> row)+ : id = _text(row, 'id'),+ replies = (row['replies'] as num).toInt(),+ lastSequence = (row['lastSequence'] as num).toInt(),+ lastAt = DateTime.tryParse(row['lastAt'] as String? ?? ''),+ authors = List.unmodifiable(+ (row['authors'] as List? ?? const []).map(superTabMap),+ ),+ people = List.unmodifiable(+ (row['people'] as List? ?? const []).whereType<String>(),+ );+ final String id;+ final int replies, lastSequence;+ final DateTime? lastAt;++ /// The newest distinct reply authors, newest first: the first wrote the+ /// last reply.+ final List<Map<String, dynamic>> authors;++ /// People who wrote in the thread or were tagged in it.+ final List<String> people;+}+class SuperTabMessage {SuperTabMessage.fromJson(Map<String, dynamic> row): id = _text(row, 'id'),conversationId = _text(row, 'conversationId'),text = _text(row, 'text'),replyTo = row['replyTo'] as String?,+ thread = row['thread'] as String?,+ alsoInChat = row['alsoInChat'] == true,sequence = (row['sequence'] as num).toInt(),author = Map.unmodifiable(superTabMap(row['author'])),source = Map.unmodifiable(superTabMap(row['source'] ?? const {})),@@ -786,6 +820,17 @@ class SuperTabMessage {);final String id, conversationId, text;final String? replyTo;++ /// The root of this message's thread: its own id for a top-level message,+ /// null for one written before threads (its replies stay inline quotes).+ final String? thread;++ /// A thread reply also shown in the conversation's main stream.+ final bool alsoInChat;+ bool get threadReply => thread != null && thread != id;++ /// Whether the main stream lists it: a thread reply only when also sent.+ bool get inMainStream => !threadReply || alsoInChat;final int sequence;final Map<String, dynamic> author;final Map<String, dynamic> source;diff --git a/desktop/lib/super_tabs/quick_switcher.dart b/desktop/lib/super_tabs/quick_switcher.dartindex f485a04f1..efbff497d 100644--- a/desktop/lib/super_tabs/quick_switcher.dart+++ b/desktop/lib/super_tabs/quick_switcher.dart@@ -273,13 +273,12 @@ List<_Destination> _destinations(SuperTabController c) {'Person',person: p,),- for (final a in s.agents)- if (projects.containsKey(a.projectId) &&- (!a.isBuddy || a.buddyOf == c.accountId))+ for (final a in s.teamAgents)+ if (projects.containsKey(a.projectId))_Destination('agent:${a.id}',s.agentName(a.id),- '${a.isBuddy ? 'Your Buddy' : 'Agent'} · ${projects[a.projectId]!.name}',+ 'Agent · ${projects[a.projectId]!.name}',agent: a,),];diff --git a/desktop/lib/super_tabs/roles_editor.dart b/desktop/lib/super_tabs/roles_editor.dartindex 325b9f3df..e85bfb7f9 100644--- a/desktop/lib/super_tabs/roles_editor.dart+++ b/desktop/lib/super_tabs/roles_editor.dart@@ -84,6 +84,7 @@ When the project owner asks in chat to switch this project's skills (Default or- Answer questions, blockers and completions at once.- Every post carries a result, a decision asked for with your recommendation, a question, or a fault; never an acknowledgement alone.- Write like a colleague: short, in their language, no commands or internal ids. Call the roles Product Manager, Engineer and Reviewer.+- Answer a message inside its thread: post with --reply-to that message, and your reply joins its thread. Many people talk to you at once; answers in the main chat bury each other. Post at the top level only to start a new topic.## Requests and Done- When you open a group for a person's request, asked in the project chat or proposed by their Buddy on their behalf, name them as its requester: requesterId on conversation.create, or conversation.requester for a group already open. It records only that they asked, never what they wrote.diff --git a/desktop/lib/super_tabs/thread_panel.dart b/desktop/lib/super_tabs/thread_panel.dartnew file mode 100644index 000000000..3be84e6dd--- /dev/null+++ b/desktop/lib/super_tabs/thread_panel.dart@@ -0,0 +1,335 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../shared/theme/app_icons.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_icon_button.dart';+import '../widgets/desktop_chrome.dart';+import 'controller.dart';+import 'model.dart';++/// One thread beside the chat (Dee, 2026-10-29): its root, a "N replies"+/// divider, the replies, and a composer whose reply goes to the root.+class SuperTabThreadPanel extends StatefulWidget {+ const SuperTabThreadPanel({+ super.key,+ required this.controller,+ required this.root,+ required this.row,+ required this.outgoing,+ });++ final SuperTabController controller;+ final String root;++ /// Draws one of the thread's messages as the chat draws it.+ final Widget Function(SuperTabMessage message, bool grouped) row;++ /// Draws a reply on its way.+ final Widget Function(SuperTabOutgoing sent) outgoing;++ @override+ State<SuperTabThreadPanel> createState() => _SuperTabThreadPanelState();+}++class _SuperTabThreadPanelState extends State<SuperTabThreadPanel> {+ late final _composer = TextEditingController(+ text: c.threadDraft(widget.root),+ );+ final _focus = FocusNode();+ bool _alsoSend = false;++ SuperTabController get c => widget.controller;++ @override+ void initState() {+ super.initState();+ _focus.requestFocus();+ }++ @override+ void didUpdateWidget(SuperTabThreadPanel old) {+ super.didUpdateWidget(old);+ if (old.root != widget.root) {+ // Each thread keeps its own draft.+ _composer.text = c.threadDraft(widget.root);+ _alsoSend = false;+ }+ }++ @override+ void dispose() {+ _composer.dispose();+ _focus.dispose();+ super.dispose();+ }++ /// Where "Also send" also puts the reply, as the chat is named.+ String get _alsoSendLabel {+ final group = c.selected;+ if (group != null && c.snapshot?.isProjectLead(group.id) == true) {+ return 'Also send to the project chat';+ }+ return group?.number != null+ ? 'Also send to the workgroup'+ : 'Also send to the chat';+ }++ bool get _writable =>+ c.canWrite && c.selected?.archived == false && !c.hasPendingAction;++ Future<void> _send() async {+ if (!_writable || _composer.text.trim().isEmpty) return;+ c.setThreadDraft(widget.root, _composer.text);+ final sending = c.sendThreadReply(alsoSend: _alsoSend);+ if (c.threadDraft(widget.root).isEmpty) {+ _composer.clear();+ setState(() => _alsoSend = false);+ }+ await sending;+ }++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final messages = c.threadMessages(widget.root);+ final root = messages.where((m) => m.id == widget.root).firstOrNull;+ final replies = messages.where((m) => m.id != widget.root).toList();+ final pending = c+ .outgoing(c.selectedId)+ .where((sent) => sent.thread == widget.root)+ .toList();+ final count =+ c.thread(c.selectedId, widget.root)?.replies ?? replies.length;+ return Material(+ key: const ValueKey('super-thread-panel'),+ color: DesktopChrome.surface,+ child: CallbackShortcuts(+ bindings: {+ const SingleActivator(LogicalKeyboardKey.escape): c.closeThread,+ },+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.controlGap,+ ),+ child: Row(+ children: [+ Expanded(+ child: Semantics(+ header: true,+ child: Text('Thread', style: DesktopChrome.heading()),+ ),+ ),+ AppIconButton(+ key: const ValueKey('super-thread-close'),+ icon: AppIcons.close,+ tooltip: 'Close thread',+ onPressed: c.closeThread,+ ),+ ],+ ),+ ),+ Divider(height: 1, thickness: 1, color: DesktopChrome.rim),+ Expanded(+ child: ListView(+ padding: const EdgeInsets.symmetric(+ vertical: grid.AppDesktop.controlGap,+ ),+ children: [+ if (root != null) widget.row(root, false),+ if (count > 0)+ Padding(+ key: const ValueKey('super-thread-divider'),+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.groupGap,+ vertical: grid.AppDesktop.controlGap,+ ),+ child: Row(+ children: [+ Text(+ count == 1 ? '1 reply' : '$count replies',+ style: DesktopChrome.metadata(),+ ),+ const SizedBox(width: grid.AppDesktop.controlGap),+ Expanded(+ child: Divider(+ height: 1,+ thickness: 1,+ color: DesktopChrome.rim,+ ),+ ),+ ],+ ),+ ),+ if (c.hasEarlierReplies(widget.root))+ Align(+ alignment: Alignment.centerLeft,+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: grid.AppDesktop.controlGap,+ ),+ child: TextButton(+ key: const ValueKey('super-thread-earlier'),+ onPressed: c.readingEarlierReplies+ ? null+ : () => unawaited(c.loadThread(earlier: true)),+ child: Text(+ c.readingEarlierReplies+ ? 'Loading earlier replies…'+ : 'Show earlier replies',+ ),+ ),+ ),+ ),+ for (final (index, reply) in replies.indexed)+ widget.row(+ reply,+ index > 0 &&+ replies[index - 1].authorId == reply.authorId &&+ replies[index - 1].fromAgent == reply.fromAgent,+ ),+ for (final sent in pending) widget.outgoing(sent),+ ],+ ),+ ),+ Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ 0,+ grid.AppDesktop.groupGap,+ grid.AppDesktop.groupGap,+ ),+ child: _composerBox(),+ ),+ ],+ ),+ ),+ );+ }++ Widget _composerBox() {+ final writable = _writable;+ return DecoratedBox(+ decoration: BoxDecoration(+ color: DesktopChrome.field,+ borderRadius: BorderRadius.circular(DesktopChrome.controlRadius),+ border: Border.all(color: DesktopChrome.rim),+ ),+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ grid.AppDesktop.groupGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.controlGap,+ grid.AppDesktop.controlGap,+ ),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ Focus(+ onKeyEvent: (_, event) {+ final keys = HardwareKeyboard.instance;+ final composing = _composer.value.composing;+ if (event is KeyDownEvent &&+ event.logicalKey == LogicalKeyboardKey.enter &&+ !keys.isShiftPressed &&+ !keys.isControlPressed &&+ !keys.isMetaPressed &&+ !keys.isAltPressed &&+ !(composing.isValid && !composing.isCollapsed)) {+ unawaited(_send());+ return KeyEventResult.handled;+ }+ return KeyEventResult.ignored;+ },+ child: TextField(+ key: const ValueKey('super-thread-composer'),+ controller: _composer,+ focusNode: _focus,+ enabled: c.canWrite && c.selected?.archived == false,+ minLines: 1,+ maxLines: 6,+ maxLength: 32000,+ keyboardType: TextInputType.multiline,+ style: DesktopChrome.text(),+ decoration: InputDecoration(+ isCollapsed: true,+ constraints: const BoxConstraints(),+ hintText: 'Reply',+ hintStyle: DesktopChrome.text(color: DesktopChrome.muted),+ contentPadding: EdgeInsets.zero,+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ disabledBorder: InputBorder.none,+ filled: false,+ counterText: '',+ ),+ onChanged: (text) {+ c.setThreadDraft(widget.root, text);+ setState(() {});+ },+ ),+ ),+ const SizedBox(height: grid.AppDesktop.controlGap),+ Row(+ children: [+ Expanded(+ child: MergeSemantics(+ child: Row(+ children: [+ Checkbox(+ key: const ValueKey('super-thread-also-send'),+ visualDensity: VisualDensity.compact,+ materialTapTargetSize:+ MaterialTapTargetSize.shrinkWrap,+ value: _alsoSend,+ onChanged: writable+ ? (on) => setState(() => _alsoSend = on ?? false)+ : null,+ ),+ Flexible(+ child: GestureDetector(+ onTap: writable+ ? () => setState(() => _alsoSend = !_alsoSend)+ : null,+ child: MouseRegion(+ cursor: writable+ ? SystemMouseCursors.click+ : MouseCursor.defer,+ child: Text(+ _alsoSendLabel,+ style: DesktopChrome.control(),+ ),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ AppIconButton(+ key: const ValueKey('super-thread-send'),+ icon: AppIcons.arrowUp,+ tooltip: 'Send reply',+ color: DesktopChrome.accent,+ onPressed: writable && _composer.text.trim().isNotEmpty+ ? () => unawaited(_send())+ : null,+ ),+ ],+ ),+ ],+ ),+ ),+ );+ }+}diff --git a/desktop/lib/super_tabs/view.dart b/desktop/lib/super_tabs/view.dartindex 62cb21dca..07174d97f 100644--- a/desktop/lib/super_tabs/view.dart+++ b/desktop/lib/super_tabs/view.dart@@ -40,6 +40,7 @@ import 'decisions_view.dart';import 'route_row.dart';import 'ship_row.dart';import 'terminal_row.dart';+import 'thread_panel.dart';import 'work_details.dart';import 'project_sidebar.dart';import 'project_options.dart';@@ -1244,6 +1245,12 @@ class _SuperTabViewState extends State<SuperTabView>widget.onCloseTerminal?.call();_closeSidebar();c.select(id);+ // A thread reply opens its thread; one shown only there has no row in the+ // chat to scroll to.+ if (message.threadReply) {+ c.openThread(message.thread!);+ if (!message.inMainStream) return;+ }final shownBy = _rowShowing(id, messageId) ?? messageId;setState(() {_showNotifications = false;@@ -1350,8 +1357,18 @@ class _SuperTabViewState extends State<SuperTabView>if (!_showNotifications) return;_showNotifications = false;c.select(id);+ // A tag in a thread opens the thread; one in a thread reply shown only+ // there is not in the chat to scroll to.+ if (message.thread case final root?) {+ c.openThread(root);+ if (!message.inMainStream) return;+ }setState(() {- if (c.canWrite && c.selected?.archived == false) _replies[id] = message;+ if (c.canWrite &&+ c.selected?.archived == false &&+ message.thread == null) {+ _replies[id] = message;+ }_target = message.id;// Stop following the end: the tagged message is what to see._scrollRequest++;@@ -1392,8 +1409,9 @@ class _SuperTabViewState extends State<SuperTabView>}/// The messages [id]'s list shows, in order.+ /// A thread reply shows in its thread, and here only when also sent.List<SuperTabMessage> _shownMessages(String id) =>- c.messages(id).where(_shown).toList();+ c.messages(id).where((m) => _shown(m) && m.inMainStream).toList();/// A message waiting for an agent is never announced; notices older/// backends stored stay hidden, in the list and as a reply's quote.@@ -2048,17 +2066,22 @@ class _SuperTabViewState extends State<SuperTabView>bool grouped,Map<String, SuperTabMessage> byId, {bool showReceipt = false,+ bool inThread = false,}) {_index();if (message.terminalEvent || message.source['kind'] == 'overlap') {return SuperTabTerminalRow(- key: ValueKey('super-message-${message.id}'),+ key: ValueKey(+ '${inThread ? 'super-thread-message' : 'super-message'}-${message.id}',+ ),message: message,);}if (SuperTabShipRow.shows(message)) {return SuperTabShipRow(- key: ValueKey('super-message-${message.id}'),+ key: ValueKey(+ '${inThread ? 'super-thread-message' : 'super-message'}-${message.id}',+ ),message: message,controller: c,);@@ -2066,7 +2089,9 @@ class _SuperTabViewState extends State<SuperTabView>final route = message.route;if (route != null) {return SuperTabRouteRow(- key: ValueKey('super-message-${message.id}'),+ key: ValueKey(+ '${inThread ? 'super-thread-message' : 'super-message'}-${message.id}',+ ),message: message,route: route,controller: c,@@ -2083,8 +2108,15 @@ class _SuperTabViewState extends State<SuperTabView>final reply =byId[message.replyTo] ??(fetched != null && _shown(fetched) ? fetched : null);+ final writable = c.canWrite && c.selected?.archived == false;+ final root = message.thread;+ final thread = inThread || root != message.id+ ? null+ : c.thread(message.conversationId, message.id);return SuperTabMessageRow(- key: ValueKey('super-message-${message.id}'),+ key: ValueKey(+ '${inThread ? 'super-thread-message' : 'super-message'}-${message.id}',+ ),message: message,author: _shownAuthor(c, message),proposalOwner: _proposalOwner(message),@@ -2115,11 +2147,21 @@ class _SuperTabViewState extends State<SuperTabView>),linkTarget: _linkTarget,onOpenLink: _openLink,- onReply: c.canWrite && c.selected?.archived == false- ? () {+ // A message with a thread is answered there; one from before threads+ // keeps the inline reply.+ onReply: !writable || inThread+ ? null+ : root != null+ ? () => c.openThread(root)+ : () {setState(() => _replies[c.selectedId] = message);_focus.requestFocus();- }+ },+ thread: thread,+ threadUnread: thread != null && c.threadUnread(thread),+ onOpenThread:+ !inThread && root != null && (thread != null || message.threadReply)+ ? () => c.openThread(root): null,onReturnToComposer: _focus.requestFocus,readerId: c.accountId,@@ -2161,6 +2203,21 @@ class _SuperTabViewState extends State<SuperTabView>);}+ /// The open thread of the selected conversation, beside the chat.+ Widget? _threadPanel() {+ final open = c.openedThread;+ if (open == null || open.conversationId != c.selectedId) return null;+ final rows = c.threadMessages(open.root);+ final byId = {for (final m in rows) m.id: m};+ return SuperTabThreadPanel(+ controller: c,+ root: open.root,+ row: (message, grouped) =>+ _message(message, grouped, byId, inThread: true),+ outgoing: (sent) => _outgoingRow(sent, rows, byId),+ );+ }+/// On the web a conversation is read before anything else is drawn/// ([WorkspaceChrome.superTabRecovers]); Desktop keeps "Loading" meanwhile.bool get _readsFirst => WorkspaceChrome.of(context).superTabRecovers;@@ -2467,7 +2524,10 @@ class _SuperTabViewState extends State<SuperTabView>// More came than were read: the count is a floor.final moreNew = c.hasNewer(c.selectedId);final reply = _replies[c.selectedId];- final outgoing = c.outgoing(c.selectedId);+ final outgoing = c+ .outgoing(c.selectedId)+ .where((sent) => sent.inMainStream)+ .toList();// A failed message says so in its own row, with what can be done.final errorInRow = outgoing.any((sent) => switch (sent.state) {@@ -3158,8 +3218,12 @@ class _SuperTabViewState extends State<SuperTabView>constraints.maxWidth < MediaQuery.textScalerOf(context).scale(720);final showRoster =constraints.maxWidth >= MediaQuery.textScalerOf(context).scale(1080);+ final thread = _threadPanel();+ final threadDrawer = thread != null && !showRoster;final chatCovered =- (narrow && _sidebarOpen) || (!showRoster && _rosterOpen);+ (narrow && _sidebarOpen) ||+ (!showRoster && _rosterOpen) ||+ threadDrawer;if (_chatCovered && !chatCovered) {// Both dismissing a drawer and widening the window reveal the cached// transcript without loading another message.@@ -3197,7 +3261,8 @@ class _SuperTabViewState extends State<SuperTabView>storage: widget.app?.localStore,onLeave: _leaveResize,left: narrow ? null : _sidebar(),- right: showRoster ? roster : null,+ // An open thread takes the roster's side, as in Slack.+ right: !showRoster ? null : thread ?? roster,center: Column(children: [_header(c.selected, narrow, showRoster),@@ -3241,7 +3306,31 @@ class _SuperTabViewState extends State<SuperTabView>),),),- if (!showRoster && _rosterOpen)+ if (threadDrawer)+ Positioned.fill(+ child: BlockSemantics(+ child: GestureDetector(+ onTap: c.closeThread,+ child: ColoredBox(+ color: grid.AppDesktop.veil(Theme.of(context).brightness),+ child: Align(+ alignment: Alignment.centerRight,+ child: GestureDetector(+ // A click inside the thread stays there.+ onTap: () {},+ child: SizedBox(+ width: SuperTabPaneLayout.drawerWidth(+ constraints.maxWidth,+ ),+ child: thread,+ ),+ ),+ ),+ ),+ ),+ ),+ ),+ if (!showRoster && _rosterOpen && !threadDrawer)Positioned.fill(child: BlockSemantics(child: FocusScope(diff --git a/desktop/test/super_tab_leaderboard_tabs_test.dart b/desktop/test/super_tab_leaderboard_tabs_test.dartindex ed7aee1d9..b62a4c19b 100644--- a/desktop/test/super_tab_leaderboard_tabs_test.dart+++ b/desktop/test/super_tab_leaderboard_tabs_test.dart@@ -259,7 +259,8 @@ void main() {),findsOneWidget,);- expect(find.byKey(ValueKey('leaderboard-crown-$opus')), findsOneWidget);+ // Crowns are for people and agents, not models (full review of #2097).+ expect(find.byKey(ValueKey('leaderboard-crown-$opus')), findsNothing);// Workers are never named: no agent's name in the list.for (final id in [opus, codex, reviewer]) {expect(inRow(id, find.textContaining('River')), findsNothing);diff --git a/desktop/test/super_tab_quick_switcher_test.dart b/desktop/test/super_tab_quick_switcher_test.dartindex 2a81bd5d4..5eaa22005 100644--- a/desktop/test/super_tab_quick_switcher_test.dart+++ b/desktop/test/super_tab_quick_switcher_test.dart@@ -567,6 +567,56 @@ void main() {variant: TargetPlatformVariant.only(TargetPlatform.macOS),);+ testWidgets('your Buddy is a chat destination, never an agent-list result', (+ tester,+ ) async {+ final (f, c) = await setup(tester);+ (f.connection.server.state['agents'] as List).add({+ 'id': 'own-buddy',+ 'name': 'Buddy',+ 'displayName': 'Moss',+ 'projectId': 'lead',+ 'machineId': 'm1',+ 'harnessId': 'own-buddy-harness',+ 'contributorId': c.accountId,+ 'buddyOf': {'personId': c.accountId},+ 'configuration': {'engine': 'claude', 'model': 'opus'},+ });+ final chat = (f.connection.server.state['conversations'] as List)+ .cast<Map>()+ .singleWhere((g) => g['id'] == 'buddy-mine');+ chat['agentIds'] = ['own-buddy'];+ f.connection.server.revision++;+ await c.refresh();+ await tester.pump();+ expect(c.snapshot!.agent('own-buddy')!.isBuddy, isTrue);+ await open(tester);+ final query = find.byKey(const ValueKey('swarm-quick-query'));+ await tester.enterText(query, 'Moss');+ await tester.pump();+ expect(+ find.byKey(const ValueKey('swarm-quick-agent:own-buddy')),+ findsNothing,+ );+ expect(find.text('No matches'), findsOneWidget);+ await tester.enterText(query, 'Casey');+ await tester.pump();+ expect(+ find.byKey(const ValueKey('swarm-quick-agent:casey')),+ findsOneWidget,+ );+ await tester.enterText(query, 'My Buddy');+ await tester.pump();+ expect(+ find.byKey(const ValueKey('swarm-quick-conversation:buddy-mine')),+ findsOneWidget,+ );+ await key(tester, LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(c.selectedId, 'buddy-mine');+ await close(tester, f, c);+ }, variant: TargetPlatformVariant.only(TargetPlatform.macOS));+final shots = Platform.environment['SWARM_QUICK_SWITCHER_SHOTS'];setUpAll(() => loadCaptureFonts(shots));for (final brightness in Brightness.values) {diff --git a/desktop/test/super_tab_threads_shots_test.dart b/desktop/test/super_tab_threads_shots_test.dartnew file mode 100644index 000000000..5be8b5919--- /dev/null+++ b/desktop/test/super_tab_threads_shots_test.dart@@ -0,0 +1,136 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/view.dart';++import 'box_render_preview_test.dart' show loadPreviewFonts;+import 'support/super_tab_fixture.dart';++/// Set to a folder to write the PR's screenshots there.+final shots = Platform.environment['SUPER_TAB_THREAD_SHOTS'];++/// Threads as the PR shows them: the main chat with a root's reply line, and+/// the thread open beside it, in both appearances.+void main() {+ setUpAll(() async {+ if (shots != null) await loadPreviewFonts();+ });++ for (final brightness in Brightness.values) {+ testWidgets('screenshots for review (${brightness.name})', (tester) async {+ final picture = GlobalKey();+ final server = ConversationServer()..threads = true;+ (server.state['people'] as List)+ ..add({'id': 'dee', 'email': '[email protected]', 'role': 'collaborator'})+ ..add({'id': 'ken', 'email': '[email protected]', 'role': 'owner'});+ const pm = {+ 'kind': 'agent',+ 'id': 'pm',+ 'name': 'Lead',+ 'displayName': 'River',+ };+ const dee = {'kind': 'person', 'id': 'dee', 'name': '[email protected]'};+ const ken = {'kind': 'person', 'id': 'ken', 'name': '[email protected]'};+ final now = DateTime.now().toUtc();+ void say(+ String text,+ Map<String, Object> author, {+ String? thread,+ bool alsoSend = false,+ int minutesAgo = 0,+ }) {+ server.append(text);+ server.messages.last+ ..['author'] = author+ ..['createdAt'] = now+ .subtract(Duration(minutes: minutesAgo))+ .toIso8601String();+ if (thread != null) {+ server.messages.last+ ..['thread'] = thread+ ..['replyTo'] = thread;+ }+ if (alsoSend) server.messages.last['alsoInChat'] = true;+ }++ say(+ 'Should we do thread replies like Slack? Appending makes it hard to '+ 'follow when we all talk to the PM at once.',+ dee,+ minutesAgo: 30,+ );+ say(+ 'Yes. Each top-level message stays once in the chat, with its replies '+ 'in a thread beside it.',+ pm,+ thread: 'message-1',+ minutesAgo: 20,+ );+ say(+ 'Agents still read every reply in one feed.',+ ken,+ thread: 'message-1',+ minutesAgo: 9,+ );+ say(+ 'Shipping it in wave 1 today.',+ pm,+ thread: 'message-1',+ alsoSend: true,+ minutesAgo: 2,+ );+ say('Morning digest is up for review.', ken, minutesAgo: 1);+ // A chat with a Lead, so messages read as sent.+ ((server.state['conversations'] as List)[0] as Map)['leadId'] = 'pm';+ final c = server.controller(account: 'dee');+ addTearDown(c.dispose);+ await c.refresh();+ grid.AppTheme.brightness.value = brightness;+ addTearDown(() => grid.AppTheme.brightness.value = Brightness.light);+ await tester.binding.setSurfaceSize(const Size(1280, 720));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (context, child) =>+ RepaintBoundary(key: picture, child: child),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Mac Studio',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();++ Future<void> shot(String name) => tester.runAsync(() async {+ final boundary =+ picture.currentContext!.findRenderObject()!+ as RenderRepaintBoundary;+ final image = await boundary.toImage(pixelRatio: 1.5);+ final bytes = await image.toByteData(format: ui.ImageByteFormat.png);+ await Directory(shots!).create(recursive: true);+ await File('$shots/threads-$name-${brightness.name}.png')+ .writeAsBytes(bytes!.buffer.asUint8List());+ image.dispose();+ });++ await shot('chat');+ await tester.tap(+ find.byKey(const ValueKey('super-thread-line-message-1')),+ );+ await tester.pumpAndSettle();+ await shot('panel');+ await tester.pumpWidget(const SizedBox());+ await c.flush();+ }, skip: shots == null);+ }+}diff --git a/desktop/test/super_tab_threads_test.dart b/desktop/test/super_tab_threads_test.dartnew file mode 100644index 000000000..f4dfef2bd--- /dev/null+++ b/desktop/test/super_tab_threads_test.dart@@ -0,0 +1,580 @@+import 'dart:async';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter/semantics.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/super_tabs/controller.dart';+import 'package:harness/super_tabs/message_link.dart';+import 'package:harness/super_tabs/message_row.dart';+import 'package:harness/super_tabs/model.dart';+import 'package:harness/super_tabs/view.dart';++import 'support/super_tab_fixture.dart';++/// Threads in Swarm chat: a reply files under its root and opens in a panel+/// beside the chat (Dee, 2026-10-29).+void main() {+ Future<SuperTabController> show(+ WidgetTester tester,+ ConversationServer server, {+ String account = 'owner',+ }) async {+ await tester.binding.setSurfaceSize(const Size(1400, 900));+ addTearDown(() => tester.binding.setSurfaceSize(null));+ final c = server.controller(account: account);+ await c.refresh();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: SuperTabView(+ controller: c,+ onInvite: () {},+ onAddAgent: (_) {},+ onOpenTerminal: (_) {},+ machineName: (_) => 'Team Mac',+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ addTearDown(c.dispose);+ return c;+ }++ const peer = {'kind': 'person', 'id': 'peer', 'name': '[email protected]'};++ /// A root by the owner, two replies to it (one by [replyAuthor]), and a+ /// later top-level note.+ ConversationServer threaded({+ Map<String, Object> replyAuthor = peer,+ bool alsoSend = false,+ }) {+ final server = ConversationServer()..threads = true;+ (server.state['people'] as List).add({+ 'id': 'peer',+ 'email': '[email protected]',+ 'role': 'collaborator',+ });+ server.append('Should we do thread replies?');+ server.append('Yes, like Slack.');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1'+ ..['author'] = peer;+ server.append('Agreed.');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-2'+ ..['author'] = replyAuthor;+ if (alsoSend) server.messages.last['alsoInChat'] = true;+ server.append('Next topic.');+ return server;+ }++ Finder row(String id) => find.byKey(ValueKey('super-message-$id'));+ Finder line(String root) => find.byKey(ValueKey('super-thread-line-$root'));+ Finder panel() => find.byKey(const ValueKey('super-thread-panel'));+ Finder inPanel(Finder finder) =>+ find.descendant(of: panel(), matching: finder);+ FontWeight? countWeight(WidgetTester tester, String root) => tester+ .widget<Text>(find.byKey(ValueKey('super-thread-count-$root')))+ .style+ ?.fontWeight;++ testWidgets('the main chat shows a root once with its reply line and '+ 'leaves its thread replies out', (tester) async {+ await show(tester, threaded());+ expect(row('message-1'), findsOneWidget);+ expect(row('message-2'), findsNothing);+ expect(row('message-3'), findsNothing);+ expect(row('message-4'), findsOneWidget);+ expect(+ find.descendant(of: line('message-1'), matching: find.text('2 replies')),+ findsOneWidget,+ );+ expect(line('message-4'), findsNothing);+ });++ testWidgets('a reply also sent to the chat shows in both, marked as a '+ 'thread reply', (tester) async {+ await show(tester, threaded(alsoSend: true));+ expect(row('message-3'), findsOneWidget);+ expect(+ find.byKey(const ValueKey('super-thread-also-message-3')),+ findsOneWidget,+ );+ // Counted once in the thread.+ expect(+ find.descendant(of: line('message-1'), matching: find.text('2 replies')),+ findsOneWidget,+ );+ });++ testWidgets('the reply line opens the thread beside the chat, and its '+ 'close button closes it', (tester) async {+ await show(tester, threaded());+ expect(panel(), findsNothing);+ await tester.tap(line('message-1'));+ await tester.pumpAndSettle();+ expect(panel(), findsOneWidget);+ expect(inPanel(find.text('Thread')), findsOneWidget);+ expect(inPanel(find.text('Should we do thread replies?')), findsOneWidget);+ expect(inPanel(find.text('2 replies')), findsOneWidget);+ expect(inPanel(find.text('Yes, like Slack.')), findsOneWidget);+ expect(inPanel(find.text('Agreed.')), findsOneWidget);+ // The main chat still shows the root, not its replies.+ expect(row('message-2'), findsNothing);+ await tester.tap(find.byKey(const ValueKey('super-thread-close')));+ await tester.pumpAndSettle();+ expect(panel(), findsNothing);+ });++ testWidgets('lost access closes the thread and forgets its rows and '+ 'summaries', (tester) async {+ final c = await show(tester, threaded());+ await tester.tap(line('message-1'));+ await tester.pumpAndSettle();+ expect(panel(), findsOneWidget);+ c.revokeAccess('Access removed.');+ await tester.pumpAndSettle();+ expect(panel(), findsNothing);+ expect(c.openedThread, isNull);+ expect(c.threadMessages('message-1'), isEmpty);+ expect(c.thread('lead', 'message-1'), isNull);+ expect(find.text('Agreed.'), findsNothing);+ });++ testWidgets('a thread read answered after access was lost is dropped', (+ tester,+ ) async {+ final server = threaded();+ final c = await show(tester, server);+ server.holdReads = Completer<void>();+ await tester.tap(line('message-1'));+ await tester.pump();+ c.revokeAccess('Access removed.');+ // The answer arrives as the thread is reopened, before the next frame.+ c.openedThread = (conversationId: 'lead', root: 'message-1');+ server.holdReads!.complete();+ server.holdReads = null;+ await tester.pumpAndSettle();+ c.openedThread = null;+ expect(c.threadMessages('message-1'), isEmpty);+ expect(c.thread('lead', 'message-1'), isNull);+ });++ testWidgets('a long thread reads back on opening, and "Show earlier '+ 'replies" reads the rest', (tester) async {+ final server = threaded()..messagePage = 2;+ for (var i = 1; i <= 12; i++) {+ server.append('Reply $i');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1'+ ..['author'] = peer;+ }+ final c = await show(tester, server);+ // The root is older than the chat's newest page.+ c.openThread('message-1');+ await tester.pumpAndSettle();+ List<String> texts() =>+ c.threadMessages('message-1').map((m) => m.text).toList();+ // Five pages of two, newest first, and the root read on its own.+ expect(texts().first, 'Should we do thread replies?');+ expect(texts(), containsAllInOrder(['Reply 3', 'Reply 12']));+ expect(texts(), isNot(contains('Reply 2')));+ final earlier = find.byKey(const ValueKey('super-thread-earlier'));+ for (var i = 0; i < 5 && earlier.evaluate().isNotEmpty; i++) {+ await tester.ensureVisible(earlier);+ await tester.tap(earlier);+ await tester.pumpAndSettle();+ }+ expect(earlier, findsNothing);+ expect(+ texts(),+ containsAllInOrder([+ 'Should we do thread replies?',+ 'Yes, like Slack.',+ 'Agreed.',+ 'Reply 1',+ 'Reply 12',+ ]),+ );+ expect(texts(), hasLength(15));+ });++ testWidgets('review: revoking access removes the open thread content', (+ tester,+ ) async {+ final c = await show(tester, threaded());+ await tester.tap(line('message-1'));+ await tester.pumpAndSettle();+ expect(inPanel(find.text('Agreed.')), findsOneWidget);+ c.revokeAccess('Access removed');+ await tester.pumpAndSettle();+ expect(find.text('Agreed.'), findsNothing);+ expect(panel(), findsNothing);+ expect(c.threadMessages('message-1'), isEmpty);+ });++ testWidgets('review: an older thread reply remains reachable', (+ tester,+ ) async {+ final server = threaded()..messagePage = 3;+ // Keep the root in the main feed while the thread exceeds a page.+ final c = await show(tester, server);+ await c.loadMessages('lead', older: true);+ await tester.pumpAndSettle();+ for (var i = 0; i < 8; i++) {+ server.append('Later thread reply $i');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1'+ ..['author'] = peer;+ }+ c.openThread('message-1');+ await tester.pumpAndSettle();+ // A thread needs a way to read replies between the cached page and its+ // newest page.+ expect(+ c+ .threadMessages('message-1')+ .any((m) => m.text == 'Later thread reply 0'),+ isTrue,+ );+ });++ testWidgets('review: reply line exposes an accessible activation', (+ tester,+ ) async {+ final semantics = tester.ensureSemantics();+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: Scaffold(+ body: SuperTabThreadLine(+ thread: SuperTabThread.fromJson({+ 'id': 'root',+ 'replies': 2,+ 'lastSequence': 4,+ 'authors': [],+ 'people': [],+ }),+ unread: true,+ onOpen: () {},+ ),+ ),+ ),+ );+ final node = tester.getSemantics(+ find.bySemanticsLabel('2 replies, unread'),+ );+ expect(node.getSemanticsData().hasAction(SemanticsAction.tap), isTrue);+ // Released inside the test: Flutter checks for a live handle before+ // tear-down runs.+ semantics.dispose();+ });++ testWidgets('the reply line and "Replied in thread" are reached by Tab and '+ 'open the thread with Enter or Space', (tester) async {+ final c = await show(tester, threaded(alsoSend: true));+ Future<void> focus(Finder link) async {+ final node = Focus.of(+ tester.element(+ find.descendant(of: link, matching: find.byType(Text)).first,+ ),+ );+ node.requestFocus();+ await tester.pump();+ expect(node.hasFocus, isTrue);+ }++ await focus(line('message-1'));+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(c.openedThread?.root, 'message-1');+ c.closeThread();+ await tester.pumpAndSettle();++ await focus(find.byKey(const ValueKey('super-thread-also-message-3')));+ await tester.sendKeyEvent(LogicalKeyboardKey.space);+ await tester.pumpAndSettle();+ expect(c.openedThread?.root, 'message-1');+ });++ testWidgets('the reply line is a button assistive technology can press', (+ tester,+ ) async {+ final handle = tester.ensureSemantics();+ var opened = 0;+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: Scaffold(+ body: SuperTabThreadLine(+ thread: SuperTabThread.fromJson({+ 'id': 'm1',+ 'replies': 2,+ 'lastSequence': 3,+ 'authors': [peer],+ 'people': ['peer'],+ }),+ unread: true,+ onOpen: () => opened++,+ ),+ ),+ ),+ );+ final node = find.semantics.byLabel('2 replies, unread');+ expect(node, findsOne);+ expect(+ tester.getSemantics(find.bySemanticsLabel('2 replies, unread')),+ isSemantics(+ isButton: true,+ hasTapAction: true,+ label: '2 replies, unread',+ ),+ );+ tester.semantics.tap(node);+ expect(opened, 1);+ handle.dispose();+ });++ testWidgets('a link to a reply that lives only in its thread opens that '+ 'thread', (tester) async {+ final c = await show(tester, threaded());+ c.openMessageLink(+ const SwarmMessageLink(+ tabId: 'tab',+ conversationId: 'lead',+ messageId: 'message-3',+ ),+ );+ await tester.pumpAndSettle();+ expect(c.openedThread?.root, 'message-1');+ expect(inPanel(find.text('Agreed.')), findsOneWidget);+ expect(find.text('Message unavailable'), findsNothing);+ });++ testWidgets('in a window too narrow for the side, the thread opens over '+ 'the chat and a click beside it closes it', (tester) async {+ await show(tester, threaded());+ await tester.binding.setSurfaceSize(const Size(1000, 800));+ await tester.pumpAndSettle();+ await tester.tap(line('message-1'));+ await tester.pumpAndSettle();+ expect(panel(), findsOneWidget);+ expect(inPanel(find.text('Agreed.')), findsOneWidget);+ await tester.tapAt(const Offset(40, 400));+ await tester.pumpAndSettle();+ expect(panel(), findsNothing);+ });++ testWidgets('a reply from the thread composer goes to the root, and '+ '"Also send to the project chat" sends it to both', (tester) async {+ final server = threaded();+ final c = await show(tester, server);+ await tester.tap(line('message-1'));+ await tester.pumpAndSettle();+ expect(inPanel(find.text('Also send to the project chat')), findsOneWidget);+ await tester.enterText(+ find.byKey(const ValueKey('super-thread-composer')),+ 'In the thread only.',+ );+ await tester.pump();+ await tester.tap(find.byKey(const ValueKey('super-thread-send')));+ await tester.pumpAndSettle();+ Map sentLast() => server.posts+ .map((post) => post['command'] as Map)+ .lastWhere((command) => command['type'] == 'message.send');+ final sent = sentLast();+ expect(sent['replyTo'], 'message-1');+ expect(sent.containsKey('alsoSend'), isFalse);+ expect(inPanel(find.text('In the thread only.')), findsOneWidget);+ expect(row('message-5'), findsNothing);++ await tester.tap(find.byKey(const ValueKey('super-thread-also-send')));+ await tester.enterText(+ find.byKey(const ValueKey('super-thread-composer')),+ 'Everyone should see this.',+ );+ await tester.pump();+ await tester.tap(find.byKey(const ValueKey('super-thread-send')));+ await tester.pumpAndSettle();+ expect(sentLast()['alsoSend'], isTrue);+ expect(inPanel(find.text('Everyone should see this.')), findsOneWidget);+ expect(row('message-6'), findsOneWidget);+ expect(+ find.descendant(of: line('message-1'), matching: find.text('4 replies')),+ findsOneWidget,+ );+ expect(c.messages('lead').map((m) => m.id), contains('message-6'));+ // The read mark's save.+ await tester.pump(const Duration(seconds: 1));+ });++ testWidgets('Reply on a message opens its thread; on a message from before '+ 'threads it keeps the inline reply', (tester) async {+ final server = threaded();+ server.append('Written before threads.');+ server.messages.last['thread'] = null;+ await show(tester, server);+ await tester.tap(+ find.descendant(of: row('message-4'), matching: find.byTooltip('Reply')),+ warnIfMissed: false,+ );+ await tester.pumpAndSettle();+ expect(panel(), findsOneWidget);+ expect(inPanel(find.text('Next topic.')), findsOneWidget);+ await tester.tap(find.byKey(const ValueKey('super-thread-close')));+ await tester.pumpAndSettle();++ await tester.tap(+ find.descendant(of: row('message-5'), matching: find.byTooltip('Reply')),+ warnIfMissed: false,+ );+ await tester.pumpAndSettle();+ expect(panel(), findsNothing);+ expect(find.text('Replying to owner'), findsOneWidget);+ });++ testWidgets('a reply from someone else marks the thread unread for a '+ 'person who wrote in it, until they open it', (tester) async {+ await show(tester, threaded());+ expect(countWeight(tester, 'message-1'), FontWeight.w700);+ await tester.tap(line('message-1'));+ await tester.pumpAndSettle();+ expect(countWeight(tester, 'message-1'), isNot(FontWeight.w700));+ });++ testWidgets('a thread the reader neither wrote in nor was tagged in is '+ 'never bold', (tester) async {+ final server = threaded();+ (server.state['people'] as List).add({+ 'id': 'third',+ 'email': '[email protected]',+ 'role': 'collaborator',+ });+ await show(tester, server, account: 'third');+ expect(countWeight(tester, 'message-1'), isNot(FontWeight.w700));+ });++ testWidgets('the reader\'s own last reply leaves the thread read', (+ tester,+ ) async {+ await show(+ tester,+ threaded(+ replyAuthor: {+ 'kind': 'person',+ 'id': 'owner',+ 'name': '[email protected]',+ },+ ),+ );+ expect(countWeight(tester, 'message-1'), isNot(FontWeight.w700));+ });++ testWidgets('the read mark passes thread replies after the last row shown', (+ tester,+ ) async {+ final server = threaded();+ server.append('A reply at the end.');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1'+ ..['author'] = peer;+ final c = await show(tester, server);+ expect(row('message-5'), findsNothing);+ expect(c.unread(c.snapshot!.conversation('lead')!), isFalse);+ });++ test('a reply only in its thread leaves the chat neither bold nor counted; '+ 'an also-sent reply makes it bold and counts once', () async {+ final server = ConversationServer()..threads = true;+ final offline = (server.state['conversations'] as List)+ .cast<Map<String, dynamic>>()+ .firstWhere((g) => g['id'] == 'offline');+ void reply(String text, {bool alsoSend = false}) {+ server.append(text, conversationId: 'offline');+ server.messages.last+ ..['thread'] = 'message-1'+ ..['replyTo'] = 'message-1'+ ..['author'] = peer;+ if (alsoSend) {+ server.messages.last['alsoInChat'] = true;+ offline['lastMainSequence'] = server.revision;+ }+ }++ server.append('Root', conversationId: 'offline');+ offline['lastMainSequence'] = 1;+ reply('Only in the thread.');+ final c = server.controller(+ initial: {+ 'tabId': 'tab',+ 'accountId': 'owner',+ 'readAt': {'offline': 1},+ },+ );+ addTearDown(c.dispose);+ await c.refresh();+ await c.loadMessages('offline');+ SuperTabConversation group() => c.snapshot!.conversation('offline')!;+ expect(c.unread(group()), isFalse);+ expect(c.unreadCount(group()), 0);++ reply('For everyone.', alsoSend: true);+ await c.refresh();+ await c.loadMessages('offline');+ expect(c.unread(group()), isTrue);+ expect(c.unreadCount(group()), 1);+ });++ test('a summary reads as the backend sends it', () {+ final thread = SuperTabThread.fromJson({+ 'id': 'm1',+ 'replies': 3,+ 'lastSequence': 9,+ 'lastAt': '2026-10-29T05:00:00Z',+ 'authors': [peer],+ 'people': ['owner', 'peer'],+ });+ expect(thread.replies, 3);+ expect(thread.lastAt, DateTime.utc(2026, 10, 29, 5));+ expect(thread.authors.single['id'], 'peer');+ expect(thread.people, ['owner', 'peer']);+ });++ testWidgets('the reply line names the reply count and when the last came', (+ tester,+ ) async {+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.light),+ home: Scaffold(+ body: SuperTabThreadLine(+ thread: SuperTabThread.fromJson({+ 'id': 'm1',+ 'replies': 1,+ 'lastSequence': 2,+ 'lastAt': DateTime.now()+ .toUtc()+ .subtract(const Duration(minutes: 2))+ .toIso8601String(),+ 'authors': [peer],+ 'people': ['peer'],+ }),+ unread: false,+ onOpen: () {},+ ),+ ),+ ),+ );+ expect(find.text('1 reply'), findsOneWidget);+ expect(find.text('Last reply 2 min ago'), findsOneWidget);+ });+}diff --git a/desktop/test/support/super_tab_fixture.dart b/desktop/test/support/super_tab_fixture.dartindex 20dac2041..14fa808b1 100644--- a/desktop/test/support/super_tab_fixture.dart+++ b/desktop/test/support/super_tab_fixture.dart@@ -385,6 +385,10 @@ class ConversationServer {/// Messages per page, as the backend pages them.int messagePage = 100;+ /// Whether messages are written with threads, as backends from threads on+ /// write them (backend threads.ts).+ bool threads = false;+/// Told of every messages read, by path.void Function(String path)? onRead;bool loseReply = false, reject = false, failSave = false, failReads = false;@@ -475,6 +479,9 @@ class ConversationServer {'id': 'message-$revision','conversationId': conversationId,'sequence': revision,+ // A top-level message is its own thread's root, as the backend writes+ // it; without [threads], a message from before threads.+ if (threads) 'thread': 'message-$revision','text': text,'attachments': attachments,'createdAt': '2026-10-18T00:00:00Z',@@ -486,6 +493,48 @@ class ConversationServer {)['lastMessageSequence'] = revision;}+ /// The summaries of the threads [page]'s rows are in, as the backend's+ /// pages carry them (threads.ts).+ List<Map<String, dynamic>> _threads(+ String conversationId,+ List<Map<String, dynamic>> page,+ ) => [+ for (final root in {+ for (final m in page)+ if (m['thread'] case final String root) root,+ })+ if (messages+ .where(+ (m) =>+ m['conversationId'] == conversationId &&+ m['thread'] == root,+ )+ .toList()+ case final thread when thread.length > 1)+ {+ 'id': root,+ 'replies': thread.length - 1,+ 'lastSequence': thread.last['sequence'],+ 'lastAt': thread.last['createdAt'],+ 'authors': [+ ...{+ for (final m in thread.skip(1).toList().reversed)+ '${(m['author'] as Map)['kind']}:${(m['author'] as Map)['id']}':+ m['author'],+ }.values,+ ].take(3).toList(),+ 'people': [+ ...{+ for (final m in thread) ...[+ if ((m['author'] as Map)['kind'] == 'person')+ (m['author'] as Map)['id'],+ ...(m['mentions'] as List? ?? const []),+ ],+ },+ ],+ },+ ];+// Avatar pictures uploaded, as the backend's avatar route keeps them.final avatarUploads = <Uint8List>[];@@ -645,6 +694,15 @@ class ConversationServer {],);messages.last['replyTo'] = command['replyTo'];+ // A reply joins its message's thread at the root; one to a message+ // written before threads stays inline (backend commands.ts).+ final target = messages+ .where((m) => m['id'] == command['replyTo'])+ .firstOrNull;+ if (target?['thread'] case final String root) {+ messages.last['thread'] = root;+ if (command['alsoSend'] == true) messages.last['alsoInChat'] = true;+ }output['messageId'] = 'message-$revision';} else if (command['type'] == 'member.status' ||command['type'] == 'member.avatar' ||@@ -999,7 +1057,7 @@ class ConversationServer {final after = int.tryParse(query['after'] ?? '');final before = int.tryParse(query['before'] ?? '');final afterId = query['afterId'], beforeId = query['beforeId'];- final messageId = query['messageId'];+ final messageId = query['messageId'], thread = query['thread'];if (messageId != null) {if (forbidMessageReads.contains(conversationId)) {throw const SuperTabFailure(@@ -1035,6 +1093,7 @@ class ConversationServer {(m) =>m['conversationId'] == conversationId &&(messageId == null || m['id'] == messageId) &&+ (thread == null || m['thread'] == thread) &&(after == null || past(m, after, afterId, 1)) &&(before == null || past(m, before, beforeId, -1)),)@@ -1049,6 +1108,7 @@ class ConversationServer {jsonEncode({'messages': after == null ? page.reversed.toList() : page,'next': next,+ 'threads': _threads(conversationId, page),'reactionSeq':(state['conversations'] as List).cast<Map>()diff --git a/docs/reviews/2026-10-29-swarm-switcher-team-agents/switcher-dark.png b/docs/reviews/2026-10-29-swarm-switcher-team-agents/switcher-dark.pngnew file mode 100644index 000000000..9ecf127caBinary files /dev/null and b/docs/reviews/2026-10-29-swarm-switcher-team-agents/switcher-dark.png differdiff --git a/docs/reviews/2026-10-29-swarm-switcher-team-agents/switcher-light.png b/docs/reviews/2026-10-29-swarm-switcher-team-agents/switcher-light.pngnew file mode 100644index 000000000..a9bba83beBinary files /dev/null and b/docs/reviews/2026-10-29-swarm-switcher-team-agents/switcher-light.png differdiff --git a/docs/reviews/2026-10-29-swarm-threads/threads-chat-dark.png b/docs/reviews/2026-10-29-swarm-threads/threads-chat-dark.pngnew file mode 100644index 000000000..37ec4a5c2Binary files /dev/null and b/docs/reviews/2026-10-29-swarm-threads/threads-chat-dark.png differdiff --git a/docs/reviews/2026-10-29-swarm-threads/threads-chat-light.png b/docs/reviews/2026-10-29-swarm-threads/threads-chat-light.pngnew file mode 100644index 000000000..c6351699cBinary files /dev/null and b/docs/reviews/2026-10-29-swarm-threads/threads-chat-light.png differdiff --git a/docs/reviews/2026-10-29-swarm-threads/threads-panel-dark.png b/docs/reviews/2026-10-29-swarm-threads/threads-panel-dark.pngnew file mode 100644index 000000000..3f76724c7Binary files /dev/null and b/docs/reviews/2026-10-29-swarm-threads/threads-panel-dark.png differdiff --git a/docs/reviews/2026-10-29-swarm-threads/threads-panel-light.png b/docs/reviews/2026-10-29-swarm-threads/threads-panel-light.pngnew file mode 100644index 000000000..9c874e4e9Binary files /dev/null and b/docs/reviews/2026-10-29-swarm-threads/threads-panel-light.png differ